Track III · LLM Fundamentals · 03/07

GPT를 바닥부터GPT from scratch

토큰 id에서 loss까지 GPT의 forward를 한 줄씩 조립한다. 위치 정보를 넣는 세 방법을 비교하고 RoPE가 왜 상대 위치만 남기는지 유도하며, causal mask와 한 칸 밀린 target이 어떻게 T개의 예측을 한 번에 만드는지 확인한다.Assemble GPT's forward pass line by line, from token ids to the loss. Compare three ways of injecting position, derive why RoPE keeps only relative position, and see how the causal mask and the shifted-by-one targets yield T predictions at once.

40 분min GPT · transformer · embedding · RoPE · causal mask · weight tying · cross-entropy 먼저 볼 것:Before this: 토크나이저Tokenizers, Transformer 블록 해부Anatomy of a Transformer block

In Track II we dissected the Transformer block (dl/transformer). This lesson attaches the remaining parts that turn that block into a language model: the embedding that turns token ids into vectors, the position information that conveys order, the causal mask that keeps the model from seeing the future, the LM head that turns vectors back into a distribution over the vocabulary, and the loss computed against targets shifted by one. At the end we write all of it in 70 lines of NumPy and test that it really cannot see the future.

The overall flow is this. Given token ids x1:Tx_{1:T} of length TT,

h(0)=E[x1:T]  →  L blocks (causal self-attention + MLP, pre-norm residual)    h(L)  →RMSNorm  logits=h^ Wout⊤∈RT×Vh^{(0)} = E[x_{1:T}] \;\xrightarrow{\;L \text{ blocks (causal self-attention + MLP, pre-norm residual)}\;}\; h^{(L)} \;\xrightarrow{\text{RMSNorm}}\; \text{logits} = \hat h\, W_{\text{out}}^{\top} \in \mathbb{R}^{T \times V}

and the logit row at position tt defines pθ(xt+1∣x≤t)p_\theta(x_{t+1} \mid x_{\le t}).

Token embedding

With vocabulary size VV and model width dd, the embedding is a V×dV \times d matrix EE, and the vector for token xtx_t is row xtx_t of EE. This equals multiplying the one-hot vector exte_{x_t} by EE, but in practice it is implemented as indexing (a lookup). In backprop, only the rows of tokens that appear in the batch receive gradient. The phenomenon from the tokenizer lesson — “rare tokens are under-trained” — comes from here.

Position information: why it is needed and how to add it

Self-attention does not know order. Permute the input tokens and the output is permuted in exactly the same way (permutation equivariance). Each position sees the others only as a “weighted set”. The causal mask leaks some order information, but that alone is weak, so position is injected explicitly. There are three approaches.

MethodHowUsed inProperties
Learned absolute positionadd a learned vector PtP_t per position to E[xt]E[x_t]GPT-2 (max 1024)Simple. Positions beyond the training length have no vector at all
Sinusoidaladd a fixed sin⁡/cos⁡(t θi)\sin/\cos(t\,\theta_i) vectorthe original TransformerNo learning. Encodes position with several frequencies θi\theta_i
RoPErotate each layer’s q,kq, k by the positionthe Llama family and most recent LLMsattention score depends only on the relative position m−nm - n

With absolute positions, the relation between “cat” and “sat” shows up as a different combination of vectors depending on where in the sentence the two words are. What usually matters in language is relative distance (“the noun two positions back”). RoPE guarantees this structurally.

Deriving RoPE

The goal is a transformation ff applied to the query at position mm and the key at position nn such that their dot product depends only on m−nm - n.

⟨f(q,m), f(k,n)⟩=g(q,k,m−n)\langle f(q, m),\, f(k, n) \rangle = g(q, k, m - n)

Start in two dimensions. Write the vector (q0,q1)(q_0, q_1) as the complex number q~=q0+iq1\tilde q = q_0 + i q_1; then the 2-D real dot product is ⟨a,b⟩=Re⁡[a~ b~‾]\langle a, b \rangle = \operatorname{Re}[\tilde a\, \overline{\tilde b}]. Now let ff be a rotation by an angle proportional to position, f(q,m)=q~ eimθf(q, m) = \tilde q\, e^{i m\theta}:

⟨f(q,m),f(k,n)⟩=Re⁡ ⁣[q~ eimθ  k~ einθ‾]=Re⁡ ⁣[q~ k~‾  ei(m−n)θ]\langle f(q,m), f(k,n) \rangle = \operatorname{Re}\!\big[\tilde q\, e^{im\theta}\; \overline{\tilde k\, e^{in\theta}}\big] = \operatorname{Re}\!\big[\tilde q\, \overline{\tilde k}\; e^{i(m-n)\theta}\big]

The absolute positions m,nm, n vanish and only the difference m−nm - n remains. If you spin two vectors at the same angular speed, the angle between them remembers only the difference in their start times. As a real matrix, f(q,m)=R(mθ) qf(q, m) = R(m\theta)\, q, and since R(mθ)⊤R(nθ)=R((n−m)θ)R(m\theta)^\top R(n\theta) = R((n-m)\theta) we get q⊤R(mθ)⊤R(nθ)k=q⊤R((n−m)θ) kq^\top R(m\theta)^\top R(n\theta) k = q^\top R((n - m)\theta)\, k.

In dd dimensions the coordinates are grouped into d/2d/2 pairs and each pair is rotated at a different frequency.

θi=base−2i/d,i=0,…,d2−1,base=10000 (default)\theta_i = \text{base}^{-2i/d}, \quad i = 0, \dots, \tfrac{d}{2} - 1, \qquad \text{base} = 10000 \text{ (default)}

θ0=1\theta_0 = 1 rad/position is the fastest, and the last pair barely turns. It is like a clock with many hands: fast pairs finely distinguish nearby positions, slow pairs distinguish long distances. The frequencies are the same as in sinusoidal encoding, but instead of being added to the vector, position enters by multiplying (rotating) qq and kk. It is not applied to vv: position affects only “whom to look at”, not “what to fetch”.

Track II에서 Transformer 블록을 해부했다(dl/transformer). 이 레슨은 그 블록을 언어 모델로 만드는 나머지 부품을 붙인다. 토큰 id를 벡터로 바꾸는 embedding, 순서를 알려 주는 위치 정보, 미래를 못 보게 하는 causal mask, 벡터를 다시 어휘 위의 분포로 바꾸는 LM head, 그리고 한 칸 밀린 target으로 계산하는 loss다. 끝에는 이 전부를 NumPy 70줄로 쓰고, 정말로 미래를 못 보는지 테스트한다.

전체 흐름은 이렇다. 길이 TT의 토큰 id x1:Tx_{1:T}가 들어오면

h(0)=E[x1:T]  →  L개 블록 (causal self-attention + MLP, pre-norm residual)    h(L)  →RMSNorm  logits=h^ Wout⊤∈RT×Vh^{(0)} = E[x_{1:T}] \;\xrightarrow{\;L \text{개 블록 (causal self-attention + MLP, pre-norm residual)}\;}\; h^{(L)} \;\xrightarrow{\text{RMSNorm}}\; \text{logits} = \hat h\, W_{\text{out}}^{\top} \in \mathbb{R}^{T \times V}

이고, 위치 tt의 logit 행이 pθ(xt+1∣x≤t)p_\theta(x_{t+1} \mid x_{\le t})를 정한다.

토큰 임베딩(Token embedding)

어휘 크기 VV, 모델 폭 dd일 때 embedding은 V×dV \times d 행렬 EE이고, 토큰 xtx_t의 벡터는 EE의 xtx_t번째 행이다. one-hot 벡터 exte_{x_t}에 EE를 곱한 것과 같지만 실제로는 인덱싱(lookup)으로 구현한다. 역전파에서는 그 배치에 나온 토큰의 행에만 기울기가 간다. 토크나이저 레슨에서 본 “드문 토큰은 학습이 덜 된다”는 현상이 여기서 나온다.

위치 정보: 왜 필요하고, 어떻게 넣나

Self-attention은 순서를 모른다. 입력 토큰의 순서를 바꾸면 출력도 똑같이 순서만 바뀐다(permutation equivariance). 각 위치는 다른 위치들을 “가중 집합”으로 볼 뿐이다. causal mask가 어느 정도 순서 정보를 흘려 주긴 하지만 그것만으로는 약하므로, 위치를 명시적으로 넣는다. 세 가지 방식이 있다.

방식어떻게쓰는 곳특징
학습된 절대 위치위치마다 학습되는 벡터 PtP_t를 E[xt]E[x_t]에 더함GPT-2 (최대 1024)단순. 학습 길이 밖의 위치는 벡터 자체가 없다
Sinusoidal고정된 sin⁡/cos⁡(t θi)\sin/\cos(t\,\theta_i) 벡터를 더함원래 Transformer학습 없음. 여러 주파수 θi\theta_i로 위치를 부호화
RoPE각 층의 q,kq, k를 위치만큼 회전Llama 계열 등 대부분의 최신 LLMattention 점수가 상대 위치 m−nm - n에만 의존

절대 위치 방식에서 “고양이”와 “앉았다” 사이의 관계는 두 단어가 문장 어디에 있느냐에 따라 다른 벡터 조합으로 나타난다. 언어에서 중요한 것은 대개 상대 거리(“두 칸 앞의 명사”)다. RoPE는 이것을 구조적으로 보장한다.

RoPE 유도

목표는 위치 mm의 query와 위치 nn의 key에 어떤 변환 ff를 적용했을 때, 내적이 m−nm - n에만 의존하게 하는 것이다.

⟨f(q,m), f(k,n)⟩=g(q,k,m−n)\langle f(q, m),\, f(k, n) \rangle = g(q, k, m - n)

2차원부터 보자. 벡터 (q0,q1)(q_0, q_1)을 복소수 q~=q0+iq1\tilde q = q_0 + i q_1로 쓰면, 2차원 실수 내적은 ⟨a,b⟩=Re⁡[a~ b~‾]\langle a, b \rangle = \operatorname{Re}[\tilde a\, \overline{\tilde b}]이다. 이제 ff를 위치에 비례하는 각도만큼의 회전 f(q,m)=q~ eimθf(q, m) = \tilde q\, e^{i m\theta}로 두면

⟨f(q,m),f(k,n)⟩=Re⁡ ⁣[q~ eimθ  k~ einθ‾]=Re⁡ ⁣[q~ k~‾  ei(m−n)θ]\langle f(q,m), f(k,n) \rangle = \operatorname{Re}\!\big[\tilde q\, e^{im\theta}\; \overline{\tilde k\, e^{in\theta}}\big] = \operatorname{Re}\!\big[\tilde q\, \overline{\tilde k}\; e^{i(m-n)\theta}\big]

절대 위치 m,nm, n은 사라지고 차이 m−nm - n만 남는다. 두 벡터를 같은 각속도로 돌리면 둘 사이의 각은 출발 시각의 차이만 기억한다는 뜻이다. 실수 행렬로 쓰면 f(q,m)=R(mθ) qf(q, m) = R(m\theta)\, q이고 R(mθ)⊤R(nθ)=R((n−m)θ)R(m\theta)^\top R(n\theta) = R((n-m)\theta)라서 q⊤R(mθ)⊤R(nθ)k=q⊤R((n−m)θ) kq^\top R(m\theta)^\top R(n\theta) k = q^\top R((n - m)\theta)\, k다.

dd차원에서는 좌표를 d/2d/2개의 쌍으로 묶고 쌍마다 다른 주파수로 돌린다.

θi=base−2i/d,i=0,…,d2−1,base=10000 (기본값)\theta_i = \text{base}^{-2i/d}, \quad i = 0, \dots, \tfrac{d}{2} - 1, \qquad \text{base} = 10000 \text{ (기본값)}

θ0=1\theta_0 = 1 rad/위치로 가장 빠르고, 마지막 쌍은 거의 돌지 않는다. 시곗바늘이 여러 개인 시계와 같다. 빠른 쌍은 가까운 위치를 세밀하게 구분하고, 느린 쌍은 먼 거리를 구분한다. 주파수 자체는 sinusoidal 인코딩과 같지만, 벡터에 더하는 대신 q,kq, k를 곱해서(회전해서) 넣는다는 점이 다르다. vv에는 적용하지 않는다. 위치는 “누구를 볼지”에만 영향을 주고 “무엇을 가져올지”에는 넣지 않는 셈이다.

m − n – q·k (회전 후, 직접 계산)(after rotation, computed directly) – 회전 전 q·kq·k before rotation –
The four clocks on top are four of the pairs of the 64-dimensional q and k. Pair i is rotated by position × θi (blue q by m, red k by n). Press "both +10": every arrow turns, but the angle between the two arrows stays the same, so q·k does not change. The score depends only on m − n. Raise base and the slow pairs almost stop, and the oscillation of the curve below slows down. Turn on q = k to see a maximum at m = n that, broadly, shrinks with distance. 위쪽 시계 네 개는 64차원 q, k 중 네 쌍(pair)이다. 쌍 i는 위치 × θi 만큼 회전한다(파랑 q는 m, 빨강 k는 n). "둘 다 +10"을 눌러 보면 모든 화살표가 돌아가지만 두 화살표 사이의 각이 그대로라 q·k가 변하지 않는다. 점수는 m − n에만 의존한다. base를 키우면 느린 쌍이 거의 멈추고, 아래 곡선의 진동이 느려진다. q = k를 켜면 m = n에서 최대이고 멀어질수록 대체로 작아지는 모양이 보인다.

Things to check in the figure:

  1. Press “both +10”: the arrows on all four clocks turn, but the purple angle between the two arrows stays the same and the q·k value is identical to the fourth decimal place.
  2. Fix m − n and change base: pair 0 (θ = 1) keeps spinning fast, and only slow pairs such as pair 31 change frequency. With a large base the slow pairs barely rotate, so they can distinguish long distances, while resolution at short distances relies on the fast pairs.
  3. Set q = k: the curve peaks at m = n, and as the distance grows the phases of the pairs scatter so it gets smaller on average. This is the tendency the RoFormer paper describes as “interaction weakens between distant tokens” (it is not strictly monotone).

Causal mask and shifted-by-one targets

During training we take a token sequence of length T+1T+1 and split it into inputs x1:Tx_{1:T} and targets x2:T+1x_{2:T+1}. The output at position tt must predict xt+1x_{t+1}, and to do so it may look only at x≤tx_{\le t}. This is enforced by adding a mask to the attention scores.

A=softmax⁡ ⁣(QK⊤dh+M),Mtj={0j≤t−∞j>tA = \operatorname{softmax}\!\Big(\frac{QK^\top}{\sqrt{d_h}} + M\Big), \qquad M_{tj} = \begin{cases} 0 & j \le t \\ -\infty & j > t \end{cases}

−∞-\infty becomes exactly 0 after softmax, so the output at position tt is a weighted sum of v1,…,vtv_1, \dots, v_t. Stacking many layers, each uses the same mask, so information flows only from left to right. As a result, a single forward pass gives TT predictions and TT loss terms at once. This is the key reason Transformers train faster than RNNs.

그림에서 확인할 것:

  1. “둘 다 +10” 을 누르면 네 시계의 화살표가 전부 돌지만 두 화살표 사이의 보라색 각은 그대로이고, q·k 값이 소수점 넷째 자리까지 같다.
  2. m − n을 고정하고 base를 바꾸면 pair 0(θ = 1)은 그대로 빠르게 돌고, pair 31처럼 느린 쌍만 주파수가 바뀐다. base가 크면 느린 쌍이 거의 회전하지 않아 먼 거리까지 구분할 수 있는 대신 가까운 거리에 대한 해상도는 빠른 쌍에 의존한다.
  3. q = k로 두면 곡선은 m = n에서 최대가 되고, 거리가 멀어지면 각 쌍의 위상이 흩어져 평균적으로 작아진다. RoFormer 논문이 말하는 “멀리 떨어진 토큰일수록 상호작용이 약해지는” 경향이다(엄밀한 단조 감소는 아니다).

Causal mask와 한 칸 밀린 target

학습 때 길이 T+1T+1의 토큰열을 가져와 입력 x1:Tx_{1:T}와 target x2:T+1x_{2:T+1}로 나눈다. 위치 tt의 출력은 xt+1x_{t+1}을 맞혀야 하고, 그러려면 x≤tx_{\le t}만 봐야 한다. attention 점수에 mask를 더해 이것을 강제한다.

A=softmax⁡ ⁣(QK⊤dh+M),Mtj={0j≤t−∞j>tA = \operatorname{softmax}\!\Big(\frac{QK^\top}{\sqrt{d_h}} + M\Big), \qquad M_{tj} = \begin{cases} 0 & j \le t \\ -\infty & j > t \end{cases}

−∞-\infty는 softmax 후 정확히 0이 되므로 위치 tt의 출력은 v1,…,vtv_1, \dots, v_t의 가중합이다. 층을 여러 개 쌓아도 각 층이 같은 mask를 쓰니 정보는 왼쪽에서 오른쪽으로만 흐른다. 그 결과 forward 한 번으로 TT개의 예측과 TT개의 loss 항을 동시에 얻는다. 이것이 Transformer가 RNN보다 학습이 빠른 핵심 이유다.

Rows = query positions (input tokens), columns = key positions. The number in a cell is that row's attention weight (softmax, each row sums to 1). Click a row to highlight the tokens that position can see and, in the right column, its target: the next token, shifted by one. Turn the causal mask off and every row conditions on the whole input x1:T: position i sees key i+1, its own answer, directly (red cell). The training loss drops to 0 easily, but at generation time that cell does not exist. The last row has no red cell: its answer xT+1 is not in the input, and it sees all of x1:T with or without the mask. 행 = query 위치(입력 토큰), 열 = key 위치. 칸의 숫자는 그 행의 attention 가중치(softmax, 행 합 1)다. 행을 클릭하면 그 위치가 볼 수 있는 토큰과, 오른쪽 열에서 그 위치의 정답(target), 즉 한 칸 밀린 다음 토큰이 강조된다. causal mask를 끄면 모든 행이 입력 전체 x1:T를 조건으로 삼는다. 위치 i가 key i+1, 곧 자기 정답을 직접 보게 된다(빨간 칸). 학습 손실은 쉽게 0으로 가지만 생성할 때는 그 칸이 존재하지 않는다. 마지막 행에는 빨간 칸이 없다. 정답 xT+1이 입력에 없고, mask가 있든 없든 x1:T 전체를 보기 때문이다.

Turn the mask off and every position conditions on the whole input x1:Tx_{1:T} instead of x≤tx_{\le t}: each position t<Tt < T can read its own answer straight from key t+1t+1 (the last position has no key T+1T+1, so it is the one row that does not leak). The model finds the easy solution of “copy the next token” and drives the training loss toward 0, but at generation time that future token does not exist, so this is useless. If the training loss drops suspiciously fast, this is the first bug to suspect.

Blocks, and the LM head

Inside a block is the pre-norm residual structure from dl/transformer.

h←h+Attn⁡(Norm⁡(h)),h←h+MLP⁡(Norm⁡(h))h \leftarrow h + \operatorname{Attn}(\operatorname{Norm}(h)), \qquad h \leftarrow h + \operatorname{MLP}(\operatorname{Norm}(h))

Most recent LLMs use RMSNorm,   RMSNorm⁡(h)=g⊙h/mean⁡(h2)+ϵ  \;\operatorname{RMSNorm}(h) = g \odot h \big/ \sqrt{\operatorname{mean}(h^2) + \epsilon}\;, as the Norm. It is LayerNorm with the mean subtraction and the bias removed. The MLP has width 4d4d with GELU, or a gated variant such as SwiGLU.

The output of the last layer is normalised once more and multiplied by a d×Vd \times V matrix to produce the logits. Sharing this output matrix with the input embedding EE is weight tying (Press & Wolf, 2017).

logitst=h^t E⊤,logitt,v=⟨h^t, Ev⟩\text{logits}_t = \hat h_t\, E^\top, \qquad \text{logit}_{t, v} = \langle \hat h_t,\, E_v \rangle

“The score that the next token is vv” becomes “the similarity between the last hidden vector and vv‘s embedding”. It saves V×dV \times d parameters, and the output rows of rare tokens benefit from training on the input side. GPT-2 tied them; recent large models with many parameters often keep them separate (small models, where VdVd is a large fraction, often tie them).

From logits to loss

Let zz be the logit vector at position tt and y=xt+1y = x_{t+1} the answer. Then

ℓt=−log⁡softmax⁡(z)y=log⁡∑vezv⏟logsumexp−zy,∂ℓt∂z=softmax⁡(z)−ey\ell_t = -\log \operatorname{softmax}(z)_y = \underbrace{\log \textstyle\sum_{v} e^{z_v}}_{\text{logsumexp}} - z_y, \qquad \frac{\partial \ell_t}{\partial z} = \operatorname{softmax}(z) - e_y

logsumexp is computed after subtracting max⁡vzv\max_v z_v to avoid overflow (log-softmax). The clean form of the gradient, “predicted distribution − one-hot answer”, is why cross-entropy and softmax are used together. Right after initialisation the logits are nearly 0, so the prediction is close to uniform and the initial loss should be near ln⁡V\ln V. If it is much larger, the initialisation is wrong.

Implementing it

First, check numerically that RoPE really keeps only relative position.

NumPy RoPE: after rotation, q·k depends only on m − n
import numpy as np

def rope_angles(T, hd, base=10000.0):
    theta = base ** (-np.arange(0, hd, 2) / hd)      # θ_i, (hd/2,)
    return np.arange(T)[:, None] * theta[None, :]    # (T, hd/2): position m × θ_i

def apply_rope(x, ang):
    """x: (..., hd), ang: same leading shape + (hd/2,). Rotates adjacent coords (0,1),(2,3),..."""
    x1, x2 = x[..., 0::2], x[..., 1::2]
    c, s = np.cos(ang), np.sin(ang)
    out = np.empty_like(x)
    out[..., 0::2] = x1 * c - x2 * s
    out[..., 1::2] = x1 * s + x2 * c
    return out

rng = np.random.default_rng(0)
hd = 16
q, k = rng.normal(size=hd), rng.normal(size=hd)
ang = rope_angles(512, hd)
for m, n in [(5, 3), (105, 103), (405, 403), (5, 4), (300, 0)]:
    s = apply_rope(q, ang[m]) @ apply_rope(k, ang[n])
    print(f"m={m:>3}, n={n:>3}, m-n={m - n:>3}:  q·k = {s:+.6f}")
print("q·k before rotation =", round(float(q @ k), 6), "(same as when m = n)")
print("norm preserved:", np.allclose(np.linalg.norm(apply_rope(q, ang[77])), np.linalg.norm(q)))
 

Now the whole model: embedding → (RMSNorm → RoPE causal multi-head attention → residual → RMSNorm → MLP → residual) × L → RMSNorm → tied head → log-softmax → NLL against the shifted-by-one targets. There is no training, only the forward pass. At the end we change one future token and check that the logits at earlier positions stay exactly the same.

NumPy NumPy tiny GPT: forward, loss, causality test
V, d, H, L = 50, 32, 4, 2          # vocab, model width, heads, layers
hd = d // H

def init(scale=0.02, seed=0):
    r = np.random.default_rng(seed)
    p = {"emb": r.normal(0, scale, (V, d)), "gf": np.ones(d)}
    for l in range(L):
        p[f"{l}.wqkv"] = r.normal(0, scale, (d, 3 * d))
        p[f"{l}.wo"]   = r.normal(0, scale, (d, d))
        p[f"{l}.w1"]   = r.normal(0, scale, (d, 4 * d))
        p[f"{l}.w2"]   = r.normal(0, scale, (4 * d, d))
        p[f"{l}.g1"], p[f"{l}.g2"] = np.ones(d), np.ones(d)
    return p

def rmsnorm(x, g, eps=1e-6):
    return g * x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps)

def gelu(x):
    return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))

def attention(x, wqkv, wo, ang, causal=True):
    T = x.shape[0]
    q, k, v = np.split(x @ wqkv, 3, axis=-1)                              # (T, d) each
    q, k, v = (t.reshape(T, H, hd).transpose(1, 0, 2) for t in (q, k, v))  # (H, T, hd)
    q, k = apply_rope(q, ang), apply_rope(k, ang)                          # rotate by position
    s = q @ k.transpose(0, 2, 1) / np.sqrt(hd)                             # (H, T, T)
    if causal:
        s = np.where(np.tril(np.ones((T, T), dtype=bool)), s, -np.inf)     # block j > t
    a = np.exp(s - s.max(-1, keepdims=True))
    a /= a.sum(-1, keepdims=True)                                          # row-wise softmax
    return (a @ v).transpose(1, 0, 2).reshape(T, d) @ wo

def forward(p, idx, causal=True):
    ang = rope_angles(len(idx), hd)
    x = p["emb"][idx]                                                      # (T, d) lookup
    for l in range(L):
        x = x + attention(rmsnorm(x, p[f"{l}.g1"]), p[f"{l}.wqkv"], p[f"{l}.wo"], ang, causal)
        x = x + gelu(rmsnorm(x, p[f"{l}.g2"]) @ p[f"{l}.w1"]) @ p[f"{l}.w2"]
    return rmsnorm(x, p["gf"]) @ p["emb"].T                                # tied head: (T, V)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

def lm_loss(p, tokens):
    inputs, targets = tokens[:-1], tokens[1:]                              # shift by one
    logp = log_softmax(forward(p, inputs))
    return -logp[np.arange(len(targets)), targets].mean()

p = init()
n_params = sum(v.size for v in p.values())
print(f"{n_params:,} parameters  (12·L·d² + V·d = {12 * L * d * d + V * d:,} + RMSNorm weights {(2 * L + 1) * d})")
tokens = np.random.default_rng(1).integers(0, V, size=13)
print(f"initial loss = {lm_loss(p, tokens):.4f}   vs  ln V = {np.log(V):.4f}")

# causality test: changing the token at position 8 must leave the logits at positions 0..7 unchanged
t2 = tokens.copy(); t2[8] = (t2[8] + 1) % V
for causal in [True, False]:
    a, b = forward(p, tokens[:-1], causal), forward(p, t2[:-1], causal)
    diff = np.abs(a - b).max(-1)
    print(f"causal={causal!s:<5}: max change at positions 0..7 = {diff[:8].max():.2e},  positions 8..11 = {diff[8:].max():.2e}")
 

With causal=True the change at positions 0..7 is exactly 0; with the mask off, earlier positions are also affected by the future token. Also check that the initial loss is near ln⁡50≈3.91\ln 50 \approx 3.91. Writing the same structure in PyTorch and training it on a toy character-level text looks like this. On a CPU the loss drops visibly within the first few hundred steps; all 1,500 steps take several minutes.

PyTorch PyTorch: nanoGPT-style model + training loop 로컬에서 실행run locally (pip install torch)
import math
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)

class RMSNorm(nn.Module):
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps, self.weight = eps, nn.Parameter(torch.ones(d))
    def forward(self, x):
        return self.weight * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

def rope_cache(T, hd, base=10000.0):
    theta = base ** (-torch.arange(0, hd, 2).float() / hd)       # (hd/2,)
    ang = torch.arange(T).float()[:, None] * theta[None, :]      # (T, hd/2)
    return ang.cos(), ang.sin()

def apply_rope(x, cos, sin):                                     # x: (B, H, T, hd)
    T = x.size(-2)
    c, s = cos[:T], sin[:T]
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1).flatten(-2)

class Block(nn.Module):
    def __init__(self, d, n_head):
        super().__init__()
        self.n_head = n_head
        self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
        self.qkv = nn.Linear(d, 3 * d, bias=False)
        self.proj = nn.Linear(d, d, bias=False)
        self.mlp = nn.Sequential(nn.Linear(d, 4 * d, bias=False), nn.GELU(), nn.Linear(4 * d, d, bias=False))
    def forward(self, x, cos, sin):
        B, T, D = x.shape
        q, k, v = self.qkv(self.norm1(x)).split(D, dim=-1)
        q, k, v = (t.view(B, T, self.n_head, D // self.n_head).transpose(1, 2) for t in (q, k, v))
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # causal mask built in
        x = x + self.proj(y.transpose(1, 2).reshape(B, T, D))
        return x + self.mlp(self.norm2(x))

class GPT(nn.Module):
    def __init__(self, vocab, d=128, n_head=4, n_layer=4, max_len=128):
        super().__init__()
        self.emb = nn.Embedding(vocab, d)
        self.blocks = nn.ModuleList([Block(d, n_head) for _ in range(n_layer)])
        self.norm = RMSNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.apply(self._init)
        self.head.weight = self.emb.weight                           # weight tying
        cos, sin = rope_cache(max_len, d // n_head)
        self.register_buffer("cos", cos, persistent=False)
        self.register_buffer("sin", sin, persistent=False)

    def _init(self, m):
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)

    def forward(self, idx, targets=None):
        x = self.emb(idx)
        for blk in self.blocks:
            x = blk(x, self.cos, self.sin)
        logits = self.head(self.norm(x))                             # (B, T, V)
        if targets is None:
            return logits, None
        return logits, F.cross_entropy(logits.flatten(0, 1), targets.flatten())

    @torch.no_grad()
    def generate(self, idx, n_new, temperature=1.0):
        for _ in range(n_new):
            logits, _ = self(idx[:, -self.cos.size(0):])
            probs = F.softmax(logits[:, -1] / temperature, dim=-1)
            idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
        return idx

text = open(__file__).read() * 20        # any text file will do: here, this script itself
chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text])

def get_batch(B=32, T=128):
    ix = torch.randint(len(data) - T - 1, (B,))
    x = torch.stack([data[i:i + T] for i in ix])
    y = torch.stack([data[i + 1:i + T + 1] for i in ix])         # targets shifted by one
    return x, y

model = GPT(len(chars))
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.1)
for step in range(1501):
    x, y = get_batch()
    _, loss = model(x, y)
    opt.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    if step % 300 == 0:
        print(f"step {step:4d}  loss {loss.item():.3f}  (ln V = {math.log(len(chars)):.3f})")

out = model.generate(torch.tensor([[stoi["d"]]]), 300, temperature=0.8)
print("".join(chars[i] for i in out[0].tolist()))
 
확인 문제Check yourself

In a model using RoPE, compare the attention score for query position 5 and key position 3 with the score when the same q and k vectors are placed at query position 1005 and key position 1003.

The dot product after rotation is a sum of Re⁡[q~ k~‾ ei(m−n)θi]\operatorname{Re}[\tilde q\,\overline{\tilde k}\,e^{i(m-n)\theta_i}] terms, so if m−n=2m - n = 2 in both cases the scores are equal. (In a real model q,kq, k themselves vary with context at every layer, but for the same vectors absolute position has no effect on the score.) “Distance” means m−nm-n, not absolute position.

확인 문제Check yourself

In nanoGPT-style training code, instead of inputs = tokens[:, :-1], targets = tokens[:, 1:], you accidentally wrote targets = tokens[:, :-1]. The causal mask is correct. What happens?

When the targets equal the inputs, position tt only has to predict “its own token”. The causal mask allows j≤tj \le t, so its own position is visible. All it has to learn is copying, so the loss goes to 0, but it learns nothing about next-token prediction. The shapes match too, so there is no error. Off-by-one is the most common and quietest bug in LM code.

Summary

  • GPT = token embedding → LL pre-norm blocks (causal self-attention + MLP) → final RMSNorm → LM head. About 12Ld2+Vd12Ld^2 + Vd parameters.
  • Self-attention does not know order, so position is injected. RoPE rotates each 2-D pair of q,kq, k by mθim\theta_i so the score depends only on m−nm - n.
  • The causal mask (−∞-\infty for j>tj > t) and shifted-by-one targets give TT next-token predictions and losses in one forward pass.
  • Weight tying makes a logit “the dot product of the hidden vector with a token embedding”.
  • The loss is logsumexp − the correct logit, its gradient is softmax − one-hot. Initial loss ≈ ln⁡V\ln V is the cheapest sanity check.

마스크를 끄면 모든 위치가 x≤tx_{\le t} 대신 입력 전체 x1:Tx_{1:T}를 조건으로 삼는다. t<Tt < T인 위치는 key t+1t+1에서 자기 정답을 그대로 읽을 수 있다(마지막 위치에는 key T+1T+1이 없으므로 누출이 없는 유일한 행이다). 모델은 “다음 토큰을 복사”하는 쉬운 해법을 찾아 학습 loss를 0 근처로 떨어뜨리지만, 생성 시에는 그 미래 토큰이 존재하지 않으니 쓸모가 없다. 학습 loss가 비정상적으로 빨리 내려가면 가장 먼저 의심할 버그다.

블록, 그리고 LM head

블록 내부는 dl/transformer에서 본 pre-norm residual 구조다.

h←h+Attn⁡(Norm⁡(h)),h←h+MLP⁡(Norm⁡(h))h \leftarrow h + \operatorname{Attn}(\operatorname{Norm}(h)), \qquad h \leftarrow h + \operatorname{MLP}(\operatorname{Norm}(h))

최신 LLM은 대부분 Norm으로 RMSNorm   RMSNorm⁡(h)=g⊙h/mean⁡(h2)+ϵ  \;\operatorname{RMSNorm}(h) = g \odot h \big/ \sqrt{\operatorname{mean}(h^2) + \epsilon}\;을 쓴다. LayerNorm에서 평균 빼기와 bias를 없앤 것이다. MLP는 폭 4d4d의 GELU 또는 SwiGLU 같은 gated 변형이다.

마지막 층의 출력을 한 번 더 정규화한 뒤 d×Vd \times V 행렬을 곱해 logit을 만든다. 이 출력 행렬을 입력 embedding EE와 공유하는 것이 weight tying이다(Press & Wolf, 2017).

logitst=h^t E⊤,logitt,v=⟨h^t, Ev⟩\text{logits}_t = \hat h_t\, E^\top, \qquad \text{logit}_{t, v} = \langle \hat h_t,\, E_v \rangle

“다음 토큰이 vv일 점수”가 “마지막 은닉 벡터와 vv의 embedding의 유사도”가 된다. V×dV \times d개의 매개변수를 아끼고 드문 토큰의 출력 행이 입력 쪽 학습의 덕을 본다. GPT-2는 묶었고, 매개변수가 많은 최신 대형 모델은 따로 두는 경우가 많다(작은 모델에서는 VdVd의 비중이 커서 묶는 경우가 많다).

logit에서 loss까지

위치 tt의 logit 벡터를 zz, 정답을 y=xt+1y = x_{t+1}이라 하면

ℓt=−log⁡softmax⁡(z)y=log⁡∑vezv⏟logsumexp−zy,∂ℓt∂z=softmax⁡(z)−ey\ell_t = -\log \operatorname{softmax}(z)_y = \underbrace{\log \textstyle\sum_{v} e^{z_v}}_{\text{logsumexp}} - z_y, \qquad \frac{\partial \ell_t}{\partial z} = \operatorname{softmax}(z) - e_y

logsumexp는 max⁡vzv\max_v z_v를 빼고 계산해서 overflow를 막는다(log-softmax). 기울기가 “예측 분포 − 정답 one-hot”이라는 깔끔한 꼴이 cross-entropy와 softmax를 같이 쓰는 이유다. 초기화 직후에는 logit이 거의 0이라 예측이 균등에 가깝고, 초기 loss는 ln⁡V\ln V 근처여야 한다. 이보다 훨씬 크면 초기화가 잘못된 것이다.

직접 구현하기

먼저 RoPE가 정말로 상대 위치만 남기는지 숫자로 확인한다.

NumPy RoPE: 회전 후 q·k는 m − n에만 의존한다
import numpy as np

def rope_angles(T, hd, base=10000.0):
    theta = base ** (-np.arange(0, hd, 2) / hd)      # θ_i, (hd/2,)
    return np.arange(T)[:, None] * theta[None, :]    # (T, hd/2): 위치 m × θ_i

def apply_rope(x, ang):
    """x: (..., hd), ang: 같은 앞쪽 shape + (hd/2,). 인접 좌표 (0,1),(2,3),...을 회전."""
    x1, x2 = x[..., 0::2], x[..., 1::2]
    c, s = np.cos(ang), np.sin(ang)
    out = np.empty_like(x)
    out[..., 0::2] = x1 * c - x2 * s
    out[..., 1::2] = x1 * s + x2 * c
    return out

rng = np.random.default_rng(0)
hd = 16
q, k = rng.normal(size=hd), rng.normal(size=hd)
ang = rope_angles(512, hd)
for m, n in [(5, 3), (105, 103), (405, 403), (5, 4), (300, 0)]:
    s = apply_rope(q, ang[m]) @ apply_rope(k, ang[n])
    print(f"m={m:>3}, n={n:>3}, m-n={m - n:>3}:  q·k = {s:+.6f}")
print("회전 전 q·k =", round(float(q @ k), 6), "(m = n일 때와 같다)")
print("norm 보존:", np.allclose(np.linalg.norm(apply_rope(q, ang[77])), np.linalg.norm(q)))
 

이제 전체 모델이다. embedding → (RMSNorm → RoPE causal multi-head attention → residual → RMSNorm → MLP → residual) × L → RMSNorm → tied head → log-softmax → 한 칸 밀린 target의 NLL. 학습은 하지 않고 forward만 한다. 마지막에 미래 토큰 하나를 바꿔서 과거 위치의 logit이 정확히 그대로인지 확인한다.

NumPy NumPy tiny GPT: forward, loss, causality test
V, d, H, L = 50, 32, 4, 2          # 어휘, 모델 폭, head 수, 층 수
hd = d // H

def init(scale=0.02, seed=0):
    r = np.random.default_rng(seed)
    p = {"emb": r.normal(0, scale, (V, d)), "gf": np.ones(d)}
    for l in range(L):
        p[f"{l}.wqkv"] = r.normal(0, scale, (d, 3 * d))
        p[f"{l}.wo"]   = r.normal(0, scale, (d, d))
        p[f"{l}.w1"]   = r.normal(0, scale, (d, 4 * d))
        p[f"{l}.w2"]   = r.normal(0, scale, (4 * d, d))
        p[f"{l}.g1"], p[f"{l}.g2"] = np.ones(d), np.ones(d)
    return p

def rmsnorm(x, g, eps=1e-6):
    return g * x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps)

def gelu(x):
    return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))

def attention(x, wqkv, wo, ang, causal=True):
    T = x.shape[0]
    q, k, v = np.split(x @ wqkv, 3, axis=-1)                              # (T, d) 각각
    q, k, v = (t.reshape(T, H, hd).transpose(1, 0, 2) for t in (q, k, v))  # (H, T, hd)
    q, k = apply_rope(q, ang), apply_rope(k, ang)                          # 위치만큼 회전
    s = q @ k.transpose(0, 2, 1) / np.sqrt(hd)                             # (H, T, T)
    if causal:
        s = np.where(np.tril(np.ones((T, T), dtype=bool)), s, -np.inf)     # j > t 차단
    a = np.exp(s - s.max(-1, keepdims=True))
    a /= a.sum(-1, keepdims=True)                                          # 행별 softmax
    return (a @ v).transpose(1, 0, 2).reshape(T, d) @ wo

def forward(p, idx, causal=True):
    ang = rope_angles(len(idx), hd)
    x = p["emb"][idx]                                                      # (T, d) lookup
    for l in range(L):
        x = x + attention(rmsnorm(x, p[f"{l}.g1"]), p[f"{l}.wqkv"], p[f"{l}.wo"], ang, causal)
        x = x + gelu(rmsnorm(x, p[f"{l}.g2"]) @ p[f"{l}.w1"]) @ p[f"{l}.w2"]
    return rmsnorm(x, p["gf"]) @ p["emb"].T                                # tied head: (T, V)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

def lm_loss(p, tokens):
    inputs, targets = tokens[:-1], tokens[1:]                              # 한 칸 밀기
    logp = log_softmax(forward(p, inputs))
    return -logp[np.arange(len(targets)), targets].mean()

p = init()
n_params = sum(v.size for v in p.values())
print(f"매개변수 {n_params:,}개  (12·L·d² + V·d = {12 * L * d * d + V * d:,} + RMSNorm 가중치 {(2 * L + 1) * d})")
tokens = np.random.default_rng(1).integers(0, V, size=13)
print(f"초기 loss = {lm_loss(p, tokens):.4f}   vs  ln V = {np.log(V):.4f}")

# causality test: 위치 8의 토큰을 바꾸면 위치 0..7의 logit은 그대로여야 한다
t2 = tokens.copy(); t2[8] = (t2[8] + 1) % V
for causal in [True, False]:
    a, b = forward(p, tokens[:-1], causal), forward(p, t2[:-1], causal)
    diff = np.abs(a - b).max(-1)
    print(f"causal={causal!s:<5}: 위치 0..7 최대 변화 = {diff[:8].max():.2e},  위치 8..11 = {diff[8:].max():.2e}")
 

causal=True일 때 위치 0..7의 변화가 정확히 0이고, 마스크를 끄면 과거 위치도 미래 토큰의 영향을 받는다. 초기 loss가 ln⁡50≈3.91\ln 50 \approx 3.91 근처라는 것도 확인하자. 같은 구조를 PyTorch로 쓰고 문자 단위 장난감 텍스트에 학습시키면 다음과 같다. CPU에서 처음 수백 step 안에 loss가 눈에 띄게 내려가고, 1,500 step 전체는 몇 분 걸린다.

PyTorch PyTorch: nanoGPT 스타일 모델 + 학습 루프 로컬에서 실행run locally (pip install torch)
import math
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)

class RMSNorm(nn.Module):
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps, self.weight = eps, nn.Parameter(torch.ones(d))
    def forward(self, x):
        return self.weight * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

def rope_cache(T, hd, base=10000.0):
    theta = base ** (-torch.arange(0, hd, 2).float() / hd)       # (hd/2,)
    ang = torch.arange(T).float()[:, None] * theta[None, :]      # (T, hd/2)
    return ang.cos(), ang.sin()

def apply_rope(x, cos, sin):                                     # x: (B, H, T, hd)
    T = x.size(-2)
    c, s = cos[:T], sin[:T]
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1).flatten(-2)

class Block(nn.Module):
    def __init__(self, d, n_head):
        super().__init__()
        self.n_head = n_head
        self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
        self.qkv = nn.Linear(d, 3 * d, bias=False)
        self.proj = nn.Linear(d, d, bias=False)
        self.mlp = nn.Sequential(nn.Linear(d, 4 * d, bias=False), nn.GELU(), nn.Linear(4 * d, d, bias=False))
    def forward(self, x, cos, sin):
        B, T, D = x.shape
        q, k, v = self.qkv(self.norm1(x)).split(D, dim=-1)
        q, k, v = (t.view(B, T, self.n_head, D // self.n_head).transpose(1, 2) for t in (q, k, v))
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # causal mask 내장
        x = x + self.proj(y.transpose(1, 2).reshape(B, T, D))
        return x + self.mlp(self.norm2(x))

class GPT(nn.Module):
    def __init__(self, vocab, d=128, n_head=4, n_layer=4, max_len=128):
        super().__init__()
        self.emb = nn.Embedding(vocab, d)
        self.blocks = nn.ModuleList([Block(d, n_head) for _ in range(n_layer)])
        self.norm = RMSNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.apply(self._init)
        self.head.weight = self.emb.weight                           # weight tying
        cos, sin = rope_cache(max_len, d // n_head)
        self.register_buffer("cos", cos, persistent=False)
        self.register_buffer("sin", sin, persistent=False)

    def _init(self, m):
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)

    def forward(self, idx, targets=None):
        x = self.emb(idx)
        for blk in self.blocks:
            x = blk(x, self.cos, self.sin)
        logits = self.head(self.norm(x))                             # (B, T, V)
        if targets is None:
            return logits, None
        return logits, F.cross_entropy(logits.flatten(0, 1), targets.flatten())

    @torch.no_grad()
    def generate(self, idx, n_new, temperature=1.0):
        for _ in range(n_new):
            logits, _ = self(idx[:, -self.cos.size(0):])
            probs = F.softmax(logits[:, -1] / temperature, dim=-1)
            idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
        return idx

text = open(__file__).read() * 20        # 아무 텍스트 파일이나: 여기서는 이 스크립트 자신
chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}
data = torch.tensor([stoi[c] for c in text])

def get_batch(B=32, T=128):
    ix = torch.randint(len(data) - T - 1, (B,))
    x = torch.stack([data[i:i + T] for i in ix])
    y = torch.stack([data[i + 1:i + T + 1] for i in ix])         # 한 칸 밀린 target
    return x, y

model = GPT(len(chars))
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.1)
for step in range(1501):
    x, y = get_batch()
    _, loss = model(x, y)
    opt.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    if step % 300 == 0:
        print(f"step {step:4d}  loss {loss.item():.3f}  (ln V = {math.log(len(chars)):.3f})")

out = model.generate(torch.tensor([[stoi["d"]]]), 300, temperature=0.8)
print("".join(chars[i] for i in out[0].tolist()))
 
확인 문제Check yourself

RoPE를 쓰는 모델에서 query 위치 5, key 위치 3의 attention 점수와, 같은 q·k 벡터를 query 위치 1005, key 위치 1003에 두었을 때의 점수는?

회전 후 내적은 Re⁡[q~ k~‾ ei(m−n)θi]\operatorname{Re}[\tilde q\,\overline{\tilde k}\,e^{i(m-n)\theta_i}]의 합이라 m−n=2m - n = 2로 같으면 같다. (실제 모델에서는 층마다 q,kq, k 자체가 문맥에 따라 달라지지만, 같은 벡터라면 절대 위치는 점수에 아무 영향이 없다.) “거리”는 m−nm-n이지 절대 위치가 아니다.

확인 문제Check yourself

nanoGPT식 학습 코드에서 inputs = tokens[:, :-1], targets = tokens[:, 1:] 대신 실수로 targets = tokens[:, :-1]로 썼다. causal mask는 정상이다. 무슨 일이 생기나?

target이 입력과 같아지면 위치 tt는 “자기 자신의 토큰”을 맞히면 된다. causal mask는 j≤tj \le t를 허용하므로 자기 위치는 보인다. 복사만 배우면 되니 loss는 0으로 가지만, 다음 토큰 예측은 전혀 배우지 않는다. shape도 같아서 오류도 나지 않는다. off-by-one은 LM 코드에서 가장 흔하고 조용한 버그다.

정리

  • GPT = token embedding → LL개의 pre-norm 블록(causal self-attention + MLP) → 최종 RMSNorm → LM head. 매개변수는 약 12Ld2+Vd12Ld^2 + Vd.
  • Self-attention은 순서를 모르므로 위치를 넣는다. RoPE는 q,kq, k의 각 2차원 쌍을 mθim\theta_i만큼 회전해 점수가 m−nm - n에만 의존하게 만든다.
  • Causal mask(j>tj > t에 −∞-\infty)와 한 칸 밀린 target 덕분에 forward 한 번으로 TT개의 다음 토큰 예측과 loss를 얻는다.
  • Weight tying은 logit을 “은닉 벡터와 토큰 embedding의 내적”으로 만든다.
  • loss는 logsumexp − 정답 logit, 기울기는 softmax − one-hot. 초기 loss ≈ ln⁡V\ln V는 가장 싼 sanity check다.

더 읽을거리Further reading