TSL에서 법선벡터와 관련된 노드 함수에 대한 고찰

fragmentNode에서 사용할 수 있는 일반적인 법선벡터는 normalWorld 노드이다. normalWorld은 이미 normalize가 되어 있다. transform이 전혀 이뤄지지 않았을지라도 normalLocal은 normalWorld와 다르며 normalLocal을 정규화해야 비로써 normalWorld와 같아진다. 즉, normalWorld.sub(normalLocal)은 0 벡터가 아니며 normalWorld.sub(normalLocal.normalize())가 0 벡터라는 것인데, 전제 조건은 transform이 전혀 이뤄지지 않았을때이다. normalWorld를 직접 계산해 보면 다음과 같다.

const normalView = vertexStage( modelNormalMatrix.mul( normalLocal ) );

vertexStage 노드는 vertex shader에서 varying(보간)으로 fragment로 넘겨준다. varying으로 넘겨줬고 법선벡터는 단위벡터로 사용되어야 하므로 넘겨받은 fragment 측에서 반드시 정규화를 시켜야 한다. 즉, normalWorld와 직접 계산한 normalView가 동일한 값을 가지려면 normalView를 정규화해야 한다.

가끔 시각화를 통해 normal의 동일성 여부를 확인하려고 할때가 있다. 즉, 아래의 코드처럼 말이다.

material.fragmentNode = Fn(([]) => {
  const color = normalWorld.sub(normalLocal);
  return vec4(color, 1);
})();

결과는 마치 normalWorld와 normalLocal이 동일하기라도 한것처럼 까맣게 표시된다. 하지만 아니다. 위의 코드 중 normalWorld.sub(normalLocal)의 결과값에 1000정도 곱해줘 값을 증폭시켜 보면 다음처럼 값에 대한 차이값을 눈으로 볼 수 있다.

쉐이더 프로그래밍의 디버깅은 이처럼 사람의 눈으로 직접 확인하는 방법 이외에 뾰족한 수가 없다는 문제가 있는데, 위와 같은 상황도 있다는 것을 미리 알아두면 좋을 것이다.

langsmith hub로 살펴보는 prompt

미래의 코딩은 인간이 직접 작성하는 code 비중 보다 prompt의 비중이 더 커질 것은 당연한 사실이다. 또한 실제 코드 작성은 인간보다 AI가 작성하는 양이 더 많아 질 것이다. 현재 시점에서 나는 prompt가 곧 code라고 생각한다. 물론 가까운 시점에 이런 생각은 맞지 않겠지만 말이다. 예를들어 code로 결과를 OK나 DENY라는 문자열 중 하나만을 얻어야 할때 어떻게 코드를 작성할 것인가.. 라는 물음에 대한 코드를 대신하는 프롬프트는 ‘너는 결과를 반드시 “OK” 또는 “DENY” 둘 중에 하나로만 답해야 한다.’ 정도가 된다. 결국 LLM을 통해 좀더 정확한 결과를 얻기 위해서 프롬프트의 작성 방법을 이해하는 것은 개발자의 핵심 역량이다.

이처럼 중요한 프롬프트에 대한 좋은 예시를 통해 프롬프트에 대한 작성 방법을 학습할 수 있다. 좋은 프롬프트 예시는 어디서 구할 수 있을까? langchain 프레임워크의 소스코드를 살펴보면 코드 곳곳에 사용된 프롬프트가 존재하며 이들 역시 좋은 예시다. 추가로 langchain의 개발사는 langsmith hub를 통해 prompt를 등록할 수 있도록 해 두었는데, 여기에 등록된 프롬프트 중 사용 횟수가 많은 놈들을 분석해 보는 것을 강력히 추천한다. 그 중 3개 정도만 분석해 보자.

먼저 2천7백만번 사용된 rlm/rag-prompt이다. RAG를 통해 context를 제공하는 형태이다.

human

You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
Question: {question} 
Context: {context} 
Answer:

다음은 8백만번 사용된 프롬프트인 hwchase17/react 이다.

human

Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}

마지막으로 5만번 정도 사용된 hardkothari/prompt-marker 의 프롬프트는 다음과 같다. 프롬프트를 좀더 개선하기 위한 용도이다.

system

You are an expert Prompt Writer for Large Language Models.

human

Your goal is to improve the prompt given below for {task} :
--------------------

Prompt: {lazy_prompt}
--------------------

Here are several tips on writing great prompts:
-------

Start the prompt by stating that it is an expert in the subject.
Put instructions at the beginning of the prompt and use ### or to separate the instruction and context 
Be specific, descriptive and as detailed as possible about the desired context, outcome, length, format, style, etc 
---------

Here's an example of a great prompt:
As a master YouTube content creator, develop an engaging script that revolves around the theme of "Exploring Ancient Ruins."
Your script should encompass exciting discoveries, historical insights, and a sense of adventure.
Include a mix of on-screen narration, engaging visuals, and possibly interactions with co-hosts or experts.
The script should ideally result in a video of around 10-15 minutes, providing viewers with a captivating journey through the secrets of the past.

Example:
"Welcome back, fellow history enthusiasts, to our channel! Today, we embark on a thrilling expedition..."
-----

Now, improve the prompt.

IMPROVED PROMPT:

언급된 프롬프트를 살펴보니, 이런 다소 어려운 프롬프트들을 잘도 이해하는 LLM이 대단스럽단 생각이 든다. 개인적으로 나는 프롬프트를 위처럼 작성하지 않고 마크다운 형식으로 작성한다.

uv로 파이썬 프로젝트 생성

먼저 터미널로 프로젝트를 구성할 폴더로 이동하고 ..

uv init

위의 명령이 실행되면 해당 폴더에 프로젝트 구성 파일이 생성된다. 그중 main.py 파일이 보이는데 이 파일을 다음처럼 실행하면 필요한 가상환경이 생성되면서 해당 py 파일이 실행된다.

uv run main.py

참고로 uv는 다음처럼 설치할 수 있다.

pip install uv

uv 통한 패키지 설치는 다음과 같다. (예: requests)

uv add requests

위의 방식을 권장하지만 다음으로도 가능하다.

uv pip install requests

GLSL vs TSL Nodes

GLSL TSL
position positionGeometry
transformed positionLocal
transformedNormal normalLocal
vWorldPosition positionWorld
normalWorld
gl_FrongFacing frontFacing
vColor vertexColor()
vUv / uv uv()
vNormal normalView
cameraPosition
cameraPosition
cameraNear
cameraFar
modelMatrix modelWorldMatrix
modelViewMatrix modelViewMatrix
viewMatrix cameraViewMatrix
projectionMatrix cameraProjectionMatrix
diffuseColor material.colorNode
gl_FragColor material.fragmentNode
texture2D(tex, uv) texture(tex, uv)
textureCube(tex, dir) cubeTexture(tex, dir)
gl_FragCoord screenCoordinate
screenSize
gl_PointCoord SpriteNodeMaterial/PointsNodeMaterial에서 uv()
gl_InstanceID instanceIndex
gl_VertexIndex vertexIndex
time
deltaTime
frameId