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 of length ,
and the logit row at position defines .
Token embedding
With vocabulary size and model width , the embedding is a matrix , and the vector for token is row of . This equals multiplying the one-hot vector by , 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.
| Method | How | Used in | Properties |
|---|---|---|---|
| Learned absolute position | add a learned vector per position to | GPT-2 (max 1024) | Simple. Positions beyond the training length have no vector at all |
| Sinusoidal | add a fixed vector | the original Transformer | No learning. Encodes position with several frequencies |
| RoPE | rotate each layer’s by the position | the Llama family and most recent LLMs | attention score depends only on the relative position |
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 applied to the query at position and the key at position such that their dot product depends only on .
Start in two dimensions. Write the vector as the complex number ; then the 2-D real dot product is . Now let be a rotation by an angle proportional to position, :
The absolute positions vanish and only the difference 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, , and since we get .
In dimensions the coordinates are grouped into pairs and each pair is rotated at a different frequency.
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) and . It is not applied to : 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줄로 쓰고, 정말로 미래를 못 보는지 테스트한다.
전체 흐름은 이렇다. 길이 의 토큰 id 가 들어오면
이고, 위치 의 logit 행이 를 정한다.
토큰 임베딩(Token embedding)
어휘 크기 , 모델 폭 일 때 embedding은 행렬 이고, 토큰 의 벡터는 의 번째 행이다. one-hot 벡터 에 를 곱한 것과 같지만 실제로는 인덱싱(lookup)으로 구현한다. 역전파에서는 그 배치에 나온 토큰의 행에만 기울기가 간다. 토크나이저 레슨에서 본 “드문 토큰은 학습이 덜 된다”는 현상이 여기서 나온다.
위치 정보: 왜 필요하고, 어떻게 넣나
Self-attention은 순서를 모른다. 입력 토큰의 순서를 바꾸면 출력도 똑같이 순서만 바뀐다(permutation equivariance). 각 위치는 다른 위치들을 “가중 집합”으로 볼 뿐이다. causal mask가 어느 정도 순서 정보를 흘려 주긴 하지만 그것만으로는 약하므로, 위치를 명시적으로 넣는다. 세 가지 방식이 있다.
| 방식 | 어떻게 | 쓰는 곳 | 특징 |
|---|---|---|---|
| 학습된 절대 위치 | 위치마다 학습되는 벡터 를 에 더함 | GPT-2 (최대 1024) | 단순. 학습 길이 밖의 위치는 벡터 자체가 없다 |
| Sinusoidal | 고정된 벡터를 더함 | 원래 Transformer | 학습 없음. 여러 주파수 로 위치를 부호화 |
| RoPE | 각 층의 를 위치만큼 회전 | Llama 계열 등 대부분의 최신 LLM | attention 점수가 상대 위치 에만 의존 |
절대 위치 방식에서 “고양이”와 “앉았다” 사이의 관계는 두 단어가 문장 어디에 있느냐에 따라 다른 벡터 조합으로 나타난다. 언어에서 중요한 것은 대개 상대 거리(“두 칸 앞의 명사”)다. RoPE는 이것을 구조적으로 보장한다.
RoPE 유도
목표는 위치 의 query와 위치 의 key에 어떤 변환 를 적용했을 때, 내적이 에만 의존하게 하는 것이다.
2차원부터 보자. 벡터 을 복소수 로 쓰면, 2차원 실수 내적은 이다. 이제 를 위치에 비례하는 각도만큼의 회전 로 두면
절대 위치 은 사라지고 차이 만 남는다. 두 벡터를 같은 각속도로 돌리면 둘 사이의 각은 출발 시각의 차이만 기억한다는 뜻이다. 실수 행렬로 쓰면 이고 라서 다.
차원에서는 좌표를 개의 쌍으로 묶고 쌍마다 다른 주파수로 돌린다.
rad/위치로 가장 빠르고, 마지막 쌍은 거의 돌지 않는다. 시곗바늘이 여러 개인 시계와 같다. 빠른 쌍은 가까운 위치를 세밀하게 구분하고, 느린 쌍은 먼 거리를 구분한다. 주파수 자체는 sinusoidal 인코딩과 같지만, 벡터에 더하는 대신 를 곱해서(회전해서) 넣는다는 점이 다르다. 에는 적용하지 않는다. 위치는 “누구를 볼지”에만 영향을 주고 “무엇을 가져올지”에는 넣지 않는 셈이다.
Things to check in the figure:
- 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.
- 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.
- 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 and split it into inputs and targets . The output at position must predict , and to do so it may look only at . This is enforced by adding a mask to the attention scores.
becomes exactly 0 after softmax, so the output at position is a weighted sum of . Stacking many layers, each uses the same mask, so information flows only from left to right. As a result, a single forward pass gives predictions and loss terms at once. This is the key reason Transformers train faster than RNNs.
그림에서 확인할 것:
- “둘 다 +10” 을 누르면 네 시계의 화살표가 전부 돌지만 두 화살표 사이의 보라색 각은 그대로이고, q·k 값이 소수점 넷째 자리까지 같다.
- m − n을 고정하고 base를 바꾸면 pair 0(θ = 1)은 그대로 빠르게 돌고, pair 31처럼 느린 쌍만 주파수가 바뀐다. base가 크면 느린 쌍이 거의 회전하지 않아 먼 거리까지 구분할 수 있는 대신 가까운 거리에 대한 해상도는 빠른 쌍에 의존한다.
- q = k로 두면 곡선은 m = n에서 최대가 되고, 거리가 멀어지면 각 쌍의 위상이 흩어져 평균적으로 작아진다. RoFormer 논문이 말하는 “멀리 떨어진 토큰일수록 상호작용이 약해지는” 경향이다(엄밀한 단조 감소는 아니다).
Causal mask와 한 칸 밀린 target
학습 때 길이 의 토큰열을 가져와 입력 와 target 로 나눈다. 위치 의 출력은 을 맞혀야 하고, 그러려면 만 봐야 한다. attention 점수에 mask를 더해 이것을 강제한다.
는 softmax 후 정확히 0이 되므로 위치 의 출력은 의 가중합이다. 층을 여러 개 쌓아도 각 층이 같은 mask를 쓰니 정보는 왼쪽에서 오른쪽으로만 흐른다. 그 결과 forward 한 번으로 개의 예측과 개의 loss 항을 동시에 얻는다. 이것이 Transformer가 RNN보다 학습이 빠른 핵심 이유다.
Turn the mask off and every position conditions on the whole input instead of : each position can read its own answer straight from key (the last position has no key , 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.
Most recent LLMs use RMSNorm, , as the Norm. It is LayerNorm with the mean subtraction and the bias removed. The MLP has width with GELU, or a gated variant such as SwiGLU.
The output of the last layer is normalised once more and multiplied by a matrix to produce the logits. Sharing this output matrix with the input embedding is weight tying (Press & Wolf, 2017).
“The score that the next token is ” becomes “the similarity between the last hidden vector and ‘s embedding”. It saves 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 is a large fraction, often tie them).
From logits to loss
Let be the logit vector at position and the answer. Then
logsumexp is computed after subtracting 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 . If it is much larger, the initialisation is wrong.
Implementing it
First, check numerically that RoPE really keeps only relative position.
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.
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 . 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.
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()))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 terms, so if in both cases the scores are equal. (In a real model themselves vary with context at every layer, but for the same vectors absolute position has no effect on the score.) “Distance” means , not absolute position.
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 only has to predict “its own token”. The causal mask allows , 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 → pre-norm blocks (causal self-attention + MLP) → final RMSNorm → LM head. About parameters.
- Self-attention does not know order, so position is injected. RoPE rotates each 2-D pair of by so the score depends only on .
- The causal mask ( for ) and shifted-by-one targets give 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 ≈ is the cheapest sanity check.
마스크를 끄면 모든 위치가 대신 입력 전체 를 조건으로 삼는다. 인 위치는 key 에서 자기 정답을 그대로 읽을 수 있다(마지막 위치에는 key 이 없으므로 누출이 없는 유일한 행이다). 모델은 “다음 토큰을 복사”하는 쉬운 해법을 찾아 학습 loss를 0 근처로 떨어뜨리지만, 생성 시에는 그 미래 토큰이 존재하지 않으니 쓸모가 없다. 학습 loss가 비정상적으로 빨리 내려가면 가장 먼저 의심할 버그다.
블록, 그리고 LM head
블록 내부는 dl/transformer에서 본 pre-norm residual 구조다.
최신 LLM은 대부분 Norm으로 RMSNorm 을 쓴다. LayerNorm에서 평균 빼기와 bias를 없앤 것이다. MLP는 폭 의 GELU 또는 SwiGLU 같은 gated 변형이다.
마지막 층의 출력을 한 번 더 정규화한 뒤 행렬을 곱해 logit을 만든다. 이 출력 행렬을 입력 embedding 와 공유하는 것이 weight tying이다(Press & Wolf, 2017).
“다음 토큰이 일 점수”가 “마지막 은닉 벡터와 의 embedding의 유사도”가 된다. 개의 매개변수를 아끼고 드문 토큰의 출력 행이 입력 쪽 학습의 덕을 본다. GPT-2는 묶었고, 매개변수가 많은 최신 대형 모델은 따로 두는 경우가 많다(작은 모델에서는 의 비중이 커서 묶는 경우가 많다).
logit에서 loss까지
위치 의 logit 벡터를 , 정답을 이라 하면
logsumexp는 를 빼고 계산해서 overflow를 막는다(log-softmax). 기울기가 “예측 분포 − 정답 one-hot”이라는 깔끔한 꼴이 cross-entropy와 softmax를 같이 쓰는 이유다. 초기화 직후에는 logit이 거의 0이라 예측이 균등에 가깝고, 초기 loss는 근처여야 한다. 이보다 훨씬 크면 초기화가 잘못된 것이다.
직접 구현하기
먼저 RoPE가 정말로 상대 위치만 남기는지 숫자로 확인한다.
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이 정확히 그대로인지 확인한다.
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가 근처라는 것도 확인하자. 같은 구조를 PyTorch로 쓰고 문자 단위 장난감 텍스트에 학습시키면 다음과 같다. CPU에서 처음 수백 step 안에 loss가 눈에 띄게 내려가고, 1,500 step 전체는 몇 분 걸린다.
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()))RoPE를 쓰는 모델에서 query 위치 5, key 위치 3의 attention 점수와, 같은 q·k 벡터를 query 위치 1005, key 위치 1003에 두었을 때의 점수는?
회전 후 내적은 의 합이라 로 같으면 같다. (실제 모델에서는 층마다 자체가 문맥에 따라 달라지지만, 같은 벡터라면 절대 위치는 점수에 아무 영향이 없다.) “거리”는 이지 절대 위치가 아니다.
nanoGPT식 학습 코드에서 inputs = tokens[:, :-1], targets = tokens[:, 1:] 대신 실수로 targets = tokens[:, :-1]로 썼다. causal mask는 정상이다. 무슨 일이 생기나?
target이 입력과 같아지면 위치 는 “자기 자신의 토큰”을 맞히면 된다. causal mask는 를 허용하므로 자기 위치는 보인다. 복사만 배우면 되니 loss는 0으로 가지만, 다음 토큰 예측은 전혀 배우지 않는다. shape도 같아서 오류도 나지 않는다. off-by-one은 LM 코드에서 가장 흔하고 조용한 버그다.
정리
- GPT = token embedding → 개의 pre-norm 블록(causal self-attention + MLP) → 최종 RMSNorm → LM head. 매개변수는 약 .
- Self-attention은 순서를 모르므로 위치를 넣는다. RoPE는 의 각 2차원 쌍을 만큼 회전해 점수가 에만 의존하게 만든다.
- Causal mask(에 )와 한 칸 밀린 target 덕분에 forward 한 번으로 개의 다음 토큰 예측과 loss를 얻는다.
- Weight tying은 logit을 “은닉 벡터와 토큰 embedding의 내적”으로 만든다.
- loss는 logsumexp − 정답 logit, 기울기는 softmax − one-hot. 초기 loss ≈ 는 가장 싼 sanity check다.
더 읽을거리Further reading
- Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, 2019) — decoder-only Transformer + pre-norm + weight tying. 이 레슨 모델의 직접 원형.Decoder-only Transformer + pre-norm + weight tying; the direct prototype of this lesson's model.
- Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021) — RoPE의 원 논문. 복소수 회전으로 상대 위치를 내적에 넣는 유도.The original RoPE paper; derives how complex rotation puts relative position into the dot product.
- Vaswani et al., Attention Is All You Need (NeurIPS, 2017) — sinusoidal 위치 인코딩과 masked self-attention의 출처.Source of sinusoidal position encoding and masked self-attention.
- Press & Wolf, Using the Output Embedding to Improve Language Models (EACL, 2017) — 입력 embedding과 출력 행렬을 공유하는 weight tying.Weight tying — sharing the input embedding with the output matrix.
- Karpathy, nanoGPT (GitHub) & Let's build GPT: from scratch, in code, spelled out (video, 2023) — 아래 PyTorch 코드와 같은 구조의 최소 GPT 구현과 학습 루프.A minimal GPT implementation and training loop with the same structure as the PyTorch code below.
- Zhang & Sennrich, Root Mean Square Layer Normalization (NeurIPS, 2019) — 평균을 빼지 않는 RMSNorm. 대부분의 최신 LLM이 LayerNorm 대신 쓴다.RMSNorm, which does not subtract the mean; most recent LLMs use it instead of LayerNorm.