All the parts are here: the same MLP at every position (lesson 1), backpropagation (lesson 2), normalisation and residual connections (lesson 3), multi-head attention (lesson 6). A Transformer block is just these assembled in a fixed order. This lesson traces the pre-norm decoder block of the GPT and LLaMA families down to every tensor shape, and counts parameters and compute by hand. These numbers keep coming up later when we discuss scaling laws, inference optimisation and RL training budgets.
Overall structure
A decoder-only language model flows as follows.
- Embedding: a sequence of token ids is looked up in a table to make a tensor . This is the start of the residual stream.
- Blocks × L: each block reads and adds something to it. The shape stays throughout.
- Final norm + LM head: after a last RMSNorm, a matrix produces logits over the whole vocabulary, . The logits at position are the distribution of token .
One block consists of two residual branches.
Attention moves information between tokens (the only place positions are mixed), and the FFN processes information within each token (the same MLP at every position). Both read a normalised input and only add to the stream. The current standard way to inject positional information is to rotate attention’s q and k, as RoPE does (Track III).
부품은 다 모였다. 위치마다 같은 MLP(1레슨), 역전파(2레슨), 정규화와 residual(3레슨), multi-head attention(6레슨). Transformer 블록은 이것들을 정해진 순서로 조립한 것일 뿐이다. 이 레슨은 GPT·LLaMA 계열의 pre-norm 디코더 블록 을 텐서 모양 하나하나까지 추적하고, 매개변수와 연산량을 손으로 센다. 이 숫자들은 이후 스케일링 법칙, 추론 최적화, RL 학습 예산을 이야기할 때 계속 쓰인다.
전체 구조
디코더 전용(decoder-only) 언어 모델은 다음과 같이 흐른다.
- 임베딩: 토큰 id 시퀀스 를 표에서 찾아 텐서 로 만든다. 이것이 residual stream의 시작이다.
- 블록 × L: 각 블록이 를 읽고 무언가를 더한다. 모양은 내내 로 유지된다.
- final norm + LM head: 마지막 RMSNorm 뒤 행렬로 vocabulary 전체에 대한 logit 를 낸다. 위치 의 logit이 토큰 의 분포다.
블록 하나는 두 개의 residual 가지로 되어 있다.
attention은 토큰 사이로 정보를 옮기고(위치를 섞는 유일한 곳), FFN은 각 토큰 안에서 정보를 가공한다(위치마다 같은 MLP). 둘 다 정규화된 입력을 읽어 stream에 더하기만 한다. 위치 정보는 RoPE처럼 attention의 q, k에 회전을 주는 방식으로 넣는 것이 현재의 표준이다(Track III).
| 블록 하나의 매개변수Parameters per block | |
|---|---|
| attention (Q,K,V,O) | |
| FFN | |
| 블록 합 (norm 포함)block total (incl. norm) | |
| 12·d² 근사12·d² approximation | |
| 모델 전체Whole model | |
| L × 블록block | |
| 임베딩embedding + LM head | |
| 총 매개변수total parameters | |
| 토큰 하나 forward (문맥 길이 T)Forward for one token (context length T) | |
| 행렬곱matmul 2·N | |
| attention 4·L·T·d | |
| attention 비중share | |
| 메모리Memory (bf16) | |
| KV cache / 토큰token | |
| KV cache B×T 전체B×T total | |
| 점수 행렬 1층 (만들면)score matrix, 1 layer (if materialised) | |
FFN: from a GELU MLP to SwiGLU
The FFN of the original Transformer and of GPT-2 is a one-hidden-layer MLP. by convention.
Shazeer (2020) compared GLU variants that put a gate where the activation was, and of these SwiGLU became the standard after LLaMA.
There are now three matrices, so to match the same parameter budget, , i.e. shrink to . LLaMA-2 7B’s is rounded up to a multiple of 256. The gate is a multiplication that decides, per hidden unit and depending on the input, “how much to let through”, so it is more expressive than the ReLU kink of the first lesson. The theory of why it works better is still thin; Shazeer himself, at the end of the paper, attributed its success to “divine benevolence”.
Counting parameters: 12d²
With (or SwiGLU’s ), independent of the number of heads:
| Part | Matrices | Parameters |
|---|---|---|
| attention | , each | |
| FFN | (or ) | |
| 2 RMSNorms | vectors | |
| Block total |
The total is ( if the input embedding and LM head are not shared). For GPT-2 small (, , , shared), plus of embeddings gives . Adding biases and position embeddings gives the official 124M. GQA (grouped-query attention) uses fewer key/value heads than query heads, making of size . Parameters shrink a little, the KV cache by a factor of (LLaMA-3 8B has 32 query heads and 8 KV heads).
Counting compute: 2N + attention
In a matrix–vector product each weight costs one multiplication and one addition, i.e. 2 FLOPs. So the matrix-multiply cost of one token’s forward pass is about (excluding the embedding lookup, which is not a multiplication, and including the LM head). On top of that comes attention, an operation with no parameters. One token with context length computes, per layer, one row of ( inner products, FLOPs) and ( FLOPs), so
In training, backprop costs about twice the forward pass (one matrix product each for the activation gradients and the weight gradients), so it becomes per token. This is the ( = number of training tokens) of Kaplan et al. (2020) and Chinchilla. Increase T in the figure: at short contexts attention is only 10–20%, but at a 128K context it far exceeds the matrix products. That is why attention optimisation is decisive for long-context models.
→ Go deeper: The design space extends this parameter and FLOP counting to GQA/MLA, MoE and the other knobs of a modern block, and uses it to compare real model configs.
import numpy as np
rng = np.random.default_rng(0)
def rmsnorm(x, g, eps=1e-6):
return g * x / np.sqrt((x * x).mean(-1, keepdims=True) + eps)
def silu(x):
return x / (1 + np.exp(-x))
def softmax(z):
z = z - z.max(-1, keepdims=True)
e = np.exp(z)
return e / e.sum(-1, keepdims=True)
def init_block(d, n_heads, d_ff, n_layers=1):
s = 1 / np.sqrt(d)
return {
"g1": np.ones(d), "g2": np.ones(d), # RMSNorm gains
"Wq": rng.normal(size=(d, d)) * s, "Wk": rng.normal(size=(d, d)) * s,
"Wv": rng.normal(size=(d, d)) * s,
"Wo": rng.normal(size=(d, d)) * s / np.sqrt(2 * n_layers), # outputs feeding the residual are scaled down
"W1": rng.normal(size=(d, d_ff)) * s, "W3": rng.normal(size=(d, d_ff)) * s,
"W2": rng.normal(size=(d_ff, d)) / np.sqrt(d_ff) / np.sqrt(2 * n_layers),
"n_heads": n_heads,
}
def block(p, x):
B, T, d = x.shape
h = p["n_heads"]; dh = d // h
# --- attention branch ---
u = rmsnorm(x, p["g1"]) # (B,T,d)
def heads(W): # (B,T,d) → (B,h,T,dh)
return (u @ W).reshape(B, T, h, dh).transpose(0, 2, 1, 3)
q, k, v = heads(p["Wq"]), heads(p["Wk"]), heads(p["Wv"])
assert q.shape == (B, h, T, dh)
scores = q @ k.transpose(0, 1, 3, 2) / np.sqrt(dh) # (B,h,T,T)
assert scores.shape == (B, h, T, T)
causal = np.tril(np.ones((T, T), dtype=bool))
A = softmax(np.where(causal, scores, -np.inf))
o = (A @ v).transpose(0, 2, 1, 3).reshape(B, T, d) # concatenate heads
x = x + o @ p["Wo"] # residual add
# --- FFN branch (SwiGLU) ---
u = rmsnorm(x, p["g2"])
hdn = silu(u @ p["W1"]) * (u @ p["W3"]) # (B,T,d_ff)
assert hdn.shape == (B, T, p["W1"].shape[1])
x = x + hdn @ p["W2"]
assert x.shape == (B, T, d)
return x
B, T, d, h = 2, 16, 64, 4
d_ff = 172 # ≈ (8/3)·d: the convention for matching SwiGLU's parameters to GELU 4d
p = init_block(d, h, d_ff)
x = rng.normal(size=(B, T, d))
y = block(p, x)
print("input", x.shape, "→ output", y.shape)
n_params = sum(v.size for k, v in p.items() if k != "n_heads")
attn, ffn = 4 * d * d, 3 * d * d_ff
print(f"parameters: attention {attn:,} + FFN {ffn:,} + norm {2*d} = {n_params:,}")
print(f"12·d² = {12*d*d:,} (SwiGLU d_ff≈8d/3 → 4d² + 8d² = 12d²)")
# causality: changing future tokens leaves past outputs unchanged
x2 = x.copy(); x2[:, 10:] = rng.normal(size=(B, T - 10, d))
y2 = block(p, x2)
print("output change at positions 0–9:", np.abs(y2[:, :10] - y[:, :10]).max(), " at positions 10+:", round(float(np.abs(y2[:, 10:] - y[:, 10:]).max()), 3))
# stacking 12 blocks, the stream size grows only gently (pre-norm + scaled-down output init)
L = 12
blocks = [init_block(d, h, d_ff, n_layers=L) for _ in range(L)]
z = x
rms = lambda t: float(np.sqrt((t ** 2).mean()))
trace = [rms(z)]
for pb in blocks:
z = block(pb, z)
trace.append(rms(z))
print("residual stream RMS per layer:", np.round(trace, 3))
# forward FLOPs per token (multiply+add = 2): matmuls 2·P, attention 4·T·d (QKᵀ and AV, attending over the full context T)
print()
for d_, T_ in [(768, 1024), (4096, 4096), (4096, 131072)]:
P = 12 * d_ * d_
mm, att = 2 * P, 4 * T_ * d_
print(f"one block, d={d_:5d}, T={T_:6d}: matmul {mm/1e6:7.1f} MFLOP, attention {att/1e6:7.1f} MFLOP → attention share {att/(mm+att):.0%}")For a GELU Transformer with d_model = 4096, 32 layers and d_ff = 4d, what is the total block parameter count (excluding embeddings), roughly?
. Add the embedding and LM head (B each with ) and you get LLaMA-2 7B’s 6.7B. Nearly all of a large model’s parameters are matrices inside the blocks.
The residual-stream view
Unrolling the block equations, the stream at the last layer is
The outputs of all the parts are added into one vector. Elhage et al. (2021) proposed viewing this stream as a communication channel shared by every layer. Each part reads some subspace of the stream through a linear projection ( or after normalisation) and writes to another subspace through or . A later layer reading what an earlier layer wrote — e.g. the induction head of the last lesson reading as its key the “token before me” written by the previous-token head — is composition through this channel. The LM head ultimately reads , so each part’s contribution to the final logits can be decomposed directly, as in (direct logit attribution). This is why interpretability research leans so heavily on this additive structure.
That clean sum holds because it is pre-norm. In post-norm the whole stream is renormalised at every layer, , so earlier content shrinks with every layer it passes.
FFN: GELU MLP에서 SwiGLU로
원조 Transformer와 GPT-2의 FFN은 은닉층 하나짜리 MLP다. 가 관례다.
Shazeer(2020)는 활성화 자리에 게이트를 넣은 GLU 변형들을 비교했고, 그중 SwiGLU가 LLaMA 이후 표준이 되었다.
행렬이 셋이 되었으므로 같은 매개변수 예산을 맞추려면 , 즉 로 줄인다. LLaMA-2 7B의 은 을 256의 배수로 올린 값이다. 게이트 는 은닉 유닛마다 “얼마나 통과시킬지”를 입력에 따라 정하는 곱셈이라, 첫 레슨의 ReLU 꺾임보다 표현이 풍부하다. 왜 더 좋은지에 대한 이론은 아직 빈약하고, Shazeer 자신도 논문 말미에서 그 성공을 “divine benevolence” 덕으로 돌렸다.
매개변수 세기: 12d²
(또는 SwiGLU ), 헤드 수와 무관하게:
| 부품 | 행렬 | 매개변수 |
|---|---|---|
| attention | 각 | |
| FFN | (또는 ) | |
| RMSNorm 2개 | 벡터 | |
| 블록 합 |
전체는 (입력 임베딩과 LM head를 공유하지 않으면 )이다. GPT-2 small(, , , 공유)이면 에 임베딩 을 더해 . 편향과 위치 임베딩을 더하면 공식 수치 124M이 된다. GQA(grouped-query attention)는 key·value 헤드 수 를 query 헤드 수보다 줄여 를 로 만든다. 매개변수는 조금, KV cache는 배 줄어든다(LLaMA-3 8B는 32개 query 헤드에 8개 KV 헤드).
연산량 세기: 2N + attention
행렬–벡터 곱에서 가중치 하나는 곱셈 하나와 덧셈 하나, 즉 2 FLOP을 쓴다. 그러니 토큰 하나의 순전파에서 행렬곱 비용은 약 이다(임베딩 조회는 곱셈이 아니므로 빼고, LM head는 넣는다). 여기에 매개변수가 없는 연산인 attention이 더해진다. 문맥 길이 의 토큰 하나는 층마다 의 한 행(개 내적, FLOP)과 ( FLOP)를 계산하므로
이다. 학습할 때는 역전파가 순전파의 약 2배(활성화 기울기와 가중치 기울기 각각 행렬곱 하나)이므로 토큰당 이 된다. Kaplan et al.(2020)과 Chinchilla의 ( = 학습 토큰 수)가 이것이다. 그림에서 T를 늘려 보면 짧은 문맥에서는 attention이 10–20%에 불과하지만, 128K 문맥에서는 행렬곱을 훨씬 넘어선다. 긴 문맥 모델에서 attention 최적화가 결정적인 이유다.
→ 더 깊이: 설계 공간에서 이 매개변수·FLOPs 세기를 GQA/MLA, MoE 같은 현대 블록의 다른 손잡이로 넓히고, 실제 모델 config를 비교하는 데 쓴다.
import numpy as np
rng = np.random.default_rng(0)
def rmsnorm(x, g, eps=1e-6):
return g * x / np.sqrt((x * x).mean(-1, keepdims=True) + eps)
def silu(x):
return x / (1 + np.exp(-x))
def softmax(z):
z = z - z.max(-1, keepdims=True)
e = np.exp(z)
return e / e.sum(-1, keepdims=True)
def init_block(d, n_heads, d_ff, n_layers=1):
s = 1 / np.sqrt(d)
return {
"g1": np.ones(d), "g2": np.ones(d), # RMSNorm 이득
"Wq": rng.normal(size=(d, d)) * s, "Wk": rng.normal(size=(d, d)) * s,
"Wv": rng.normal(size=(d, d)) * s,
"Wo": rng.normal(size=(d, d)) * s / np.sqrt(2 * n_layers), # residual로 들어가는 출력은 축소
"W1": rng.normal(size=(d, d_ff)) * s, "W3": rng.normal(size=(d, d_ff)) * s,
"W2": rng.normal(size=(d_ff, d)) / np.sqrt(d_ff) / np.sqrt(2 * n_layers),
"n_heads": n_heads,
}
def block(p, x):
B, T, d = x.shape
h = p["n_heads"]; dh = d // h
# --- attention 가지 ---
u = rmsnorm(x, p["g1"]) # (B,T,d)
def heads(W): # (B,T,d) → (B,h,T,dh)
return (u @ W).reshape(B, T, h, dh).transpose(0, 2, 1, 3)
q, k, v = heads(p["Wq"]), heads(p["Wk"]), heads(p["Wv"])
assert q.shape == (B, h, T, dh)
scores = q @ k.transpose(0, 1, 3, 2) / np.sqrt(dh) # (B,h,T,T)
assert scores.shape == (B, h, T, T)
causal = np.tril(np.ones((T, T), dtype=bool))
A = softmax(np.where(causal, scores, -np.inf))
o = (A @ v).transpose(0, 2, 1, 3).reshape(B, T, d) # 헤드 이어 붙이기
x = x + o @ p["Wo"] # residual 덧셈
# --- FFN 가지 (SwiGLU) ---
u = rmsnorm(x, p["g2"])
hdn = silu(u @ p["W1"]) * (u @ p["W3"]) # (B,T,d_ff)
assert hdn.shape == (B, T, p["W1"].shape[1])
x = x + hdn @ p["W2"]
assert x.shape == (B, T, d)
return x
B, T, d, h = 2, 16, 64, 4
d_ff = 172 # ≈ (8/3)·d: SwiGLU에서 매개변수를 GELU 4d와 맞추는 관례
p = init_block(d, h, d_ff)
x = rng.normal(size=(B, T, d))
y = block(p, x)
print("입력", x.shape, "→ 출력", y.shape)
n_params = sum(v.size for k, v in p.items() if k != "n_heads")
attn, ffn = 4 * d * d, 3 * d * d_ff
print(f"매개변수: attention {attn:,} + FFN {ffn:,} + norm {2*d} = {n_params:,}")
print(f"12·d² = {12*d*d:,} (SwiGLU d_ff≈8d/3 → 4d² + 8d² = 12d²)")
# 인과성: 미래 토큰을 바꿔도 과거 출력은 그대로
x2 = x.copy(); x2[:, 10:] = rng.normal(size=(B, T - 10, d))
y2 = block(p, x2)
print("위치 0–9 출력 변화:", np.abs(y2[:, :10] - y[:, :10]).max(), " 위치 10+ 변화:", round(float(np.abs(y2[:, 10:] - y[:, 10:]).max()), 3))
# 12개 블록을 쌓아도 stream 크기가 완만하게만 자란다 (pre-norm + 출력 축소 초기화)
L = 12
blocks = [init_block(d, h, d_ff, n_layers=L) for _ in range(L)]
z = x
rms = lambda t: float(np.sqrt((t ** 2).mean()))
trace = [rms(z)]
for pb in blocks:
z = block(pb, z)
trace.append(rms(z))
print("층별 residual stream RMS:", np.round(trace, 3))
# 토큰당 forward FLOPs (곱셈+덧셈 = 2): 행렬곱 2·P, attention 4·T·d (QKᵀ와 AV, 문맥 T 전체를 볼 때)
print()
for d_, T_ in [(768, 1024), (4096, 4096), (4096, 131072)]:
P = 12 * d_ * d_
mm, att = 2 * P, 4 * T_ * d_
print(f"블록 하나, d={d_:5d}, T={T_:6d}: 행렬곱 {mm/1e6:7.1f} MFLOP, attention {att/1e6:7.1f} MFLOP → attention 비중 {att/(mm+att):.0%}")d_model = 4096, 32층, d_ff = 4d인 GELU Transformer의 블록 매개변수 합(임베딩 제외)은 대략?
. 여기에 임베딩과 LM head(이면 각 B)를 더하면 LLaMA-2 7B의 6.7B가 된다. 큰 모델의 매개변수는 거의 전부 블록 안의 행렬이다.
Residual stream이라는 관점
블록의 식을 펼쳐 쓰면 마지막 층의 stream은
이다. 모든 부품의 출력이 더해져서 하나의 벡터를 이룬다. Elhage et al.(2021)은 이 stream을 각 층이 공유하는 통신 채널 로 보자고 제안했다. 각 부품은 선형 투영(정규화 후 나 )으로 stream의 일부 부분공간을 읽고, 나 로 다른 부분공간에 쓴다. 앞 층이 써 둔 정보를 뒤 층이 읽어서 쓰는 것, 예를 들어 지난 레슨의 이전 토큰 헤드가 쓴 “내 앞 토큰”을 유도 헤드가 key로 읽는 것이 이 채널을 통한 합성이다. LM head는 결국 을 읽으므로, 각 부품이 최종 logit에 준 기여를 처럼 직접 분해해 볼 수 있다(direct logit attribution). 해석 가능성 연구가 이 덧셈 구조에 크게 기대는 이유다.
그 깨끗한 덧셈은 pre-norm 이기 때문에 성립한다. post-norm에서는 매 층 로 stream 전체가 다시 정규화되므로, 앞쪽 내용이 층을 지날 때마다 줄어든다.
RMSNorm only divides the vector by a scalar, so even in post-norm the stream can be tracked as an exact sum of “x₀ + what each block wrote”. The result is stark. In pre-norm the input embedding survives intact to the end and each block’s share is even. In post-norm each layer shrinks things by about , so after 24 layers the embedding’s share is effectively 0 and the output is decided by the last few blocks. Seen through backprop, the gradient on the identity path shrinks by the same ratio — the same root as the training instability of post-LN (the need for warmup) seen in lesson 3. DeepNet (Wang et al., 2022) trained 1000 layers in post-norm by multiplying the residual by () to slow this decay — the same effect as lowering β in the figure.
Encoders, decoders, encoder–decoders
The same block is used three ways, changing only the mask and the wiring.
| Attention mask | Representative models | Training objective | Used for | |
|---|---|---|---|---|
| Encoder | bidirectional (no mask) | BERT | predict masked tokens (MLM) | classification, retrieval embeddings |
| Decoder | causal | GPT, LLaMA | next-token prediction | generation, today’s LLMs |
| Encoder–decoder | bidirectional encoder + causal decoder + cross-attention | original Transformer, T5 | input → output transformation | translation, summarisation |
Cross-attention takes its queries from the decoder stream and its keys and values from the encoder output. A decoder-only model concatenates input (prompt) and output into one sequence and handles both with a single causal mask. Because the architecture is simple, every token is trained on the same objective of next-token prediction, and generation is efficient with a KV cache, nearly all of today’s LLMs are decoder-only.
import torch
import torch.nn as nn
import torch.nn.functional as F
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)
class Block(nn.Module):
def __init__(self, d, n_heads, d_ff):
super().__init__()
self.h = n_heads
self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
self.wqkv = nn.Linear(d, 3 * d, bias=False)
self.wo = nn.Linear(d, d, bias=False)
self.w1 = nn.Linear(d, d_ff, bias=False)
self.w3 = nn.Linear(d, d_ff, bias=False)
self.w2 = nn.Linear(d_ff, d, bias=False)
def forward(self, x): # x: (B, T, d)
B, T, d = x.shape
q, k, v = self.wqkv(self.norm1(x)).split(d, dim=-1)
q, k, v = (t.view(B, T, self.h, d // self.h).transpose(1, 2) for t in (q, k, v))
o = F.scaled_dot_product_attention(q, k, v, is_causal=True) # (B, h, T, d_h)
x = x + self.wo(o.transpose(1, 2).reshape(B, T, d))
u = self.norm2(x)
return x + self.w2(F.silu(self.w1(u)) * self.w3(u))
d, h, L, V = 512, 8, 6, 32000
d_ff = 256 * ((8 * d // 3 + 255) // 256) # round 8d/3 up to a multiple of 256 → 1536
embed = nn.Embedding(V, d)
blocks = nn.ModuleList(Block(d, h, d_ff) for _ in range(L))
norm, lm_head = RMSNorm(d), nn.Linear(d, V, bias=False)
tokens = torch.randint(0, V, (2, 128))
x = embed(tokens)
for blk in blocks:
x = blk(x)
logits = lm_head(norm(x)) # (2, 128, 32000)
per_block = sum(p.numel() for p in blocks[0].parameters())
print(logits.shape, per_block, 12 * d * d) # block parameters ≈ 12·d²Pre-training a 7B-parameter model on 2T (2×10¹²) tokens: by C ≈ 6ND, roughly how much compute is needed?
FLOP. Per training token, the forward pass is and backprop . With long contexts the attention term is added on top. If one GPU delivers an effective FLOP/s, that is about seconds — 6–7 GPU-years.
Summary
- Decoder block: , . Attention works between tokens, the FFN within each token.
- The shape is throughout. Only inside attention does it split into and .
- Block parameters (attention + FFN ); SwiGLU matches the same budget with . In total .
- Forward per token , training . At long contexts the attention term dominates.
- In pre-norm the residual stream is the exact sum of every part’s output. Post-norm shrinks earlier content at every layer and grows unstable with depth.
- Encoder (bidirectional), decoder (causal), encoder–decoder (cross-attention). Today’s LLMs are decoder-only.
RMSNorm은 벡터를 스칼라로 나누기만 하므로, post-norm에서도 stream을 “x₀ + 각 블록의 쓰기”의 정확한 합으로 추적할 수 있다. 결과는 극명하다. pre-norm은 입력 임베딩이 끝까지 고스란히 남고 각 블록의 몫이 고르다. post-norm에서는 매 층 약 배씩 줄어, 24층 뒤 임베딩의 몫이 사실상 0이고 출력은 마지막 몇 블록이 결정한다. 역전파로 보면 항등 경로의 기울기가 같은 비율로 줄어든다. 3레슨에서 본 post-LN의 학습 불안정(warmup 필요)과 같은 뿌리다. DeepNet(Wang et al., 2022)은 post-norm에서 residual에 을 곱해() 이 감쇠를 늦추는 방식으로 1000층 학습을 보였다. 그림의 β를 줄이는 것과 같은 효과다.
인코더, 디코더, 인코더–디코더
같은 블록을 mask와 연결만 바꿔 세 가지로 쓴다.
| attention mask | 대표 모델 | 학습 목표 | 쓰임 | |
|---|---|---|---|---|
| 인코더 | 양방향(mask 없음) | BERT | 가려진 토큰 맞히기(MLM) | 분류·검색 임베딩 |
| 디코더 | causal | GPT, LLaMA | 다음 토큰 예측 | 생성, 현재의 LLM |
| 인코더–디코더 | 인코더 양방향 + 디코더 causal + cross-attention | 원조 Transformer, T5 | 입력 → 출력 변환 | 번역·요약 |
cross-attention은 query를 디코더 stream에서, key·value를 인코더 출력에서 가져오는 attention이다. 디코더 전용 모델은 입력(프롬프트)과 출력을 한 시퀀스로 이어 붙이고 causal mask 하나로 둘 다 처리한다. 구조가 단순하고, 모든 토큰이 다음 토큰 예측이라는 같은 목표로 학습되며, KV cache로 생성이 효율적이라는 점에서 현재의 LLM은 거의 모두 디코더 전용이다.
import torch
import torch.nn as nn
import torch.nn.functional as F
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)
class Block(nn.Module):
def __init__(self, d, n_heads, d_ff):
super().__init__()
self.h = n_heads
self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
self.wqkv = nn.Linear(d, 3 * d, bias=False)
self.wo = nn.Linear(d, d, bias=False)
self.w1 = nn.Linear(d, d_ff, bias=False)
self.w3 = nn.Linear(d, d_ff, bias=False)
self.w2 = nn.Linear(d_ff, d, bias=False)
def forward(self, x): # x: (B, T, d)
B, T, d = x.shape
q, k, v = self.wqkv(self.norm1(x)).split(d, dim=-1)
q, k, v = (t.view(B, T, self.h, d // self.h).transpose(1, 2) for t in (q, k, v))
o = F.scaled_dot_product_attention(q, k, v, is_causal=True) # (B, h, T, d_h)
x = x + self.wo(o.transpose(1, 2).reshape(B, T, d))
u = self.norm2(x)
return x + self.w2(F.silu(self.w1(u)) * self.w3(u))
d, h, L, V = 512, 8, 6, 32000
d_ff = 256 * ((8 * d // 3 + 255) // 256) # 8d/3을 256의 배수로 올림 → 1536
embed = nn.Embedding(V, d)
blocks = nn.ModuleList(Block(d, h, d_ff) for _ in range(L))
norm, lm_head = RMSNorm(d), nn.Linear(d, V, bias=False)
tokens = torch.randint(0, V, (2, 128))
x = embed(tokens)
for blk in blocks:
x = blk(x)
logits = lm_head(norm(x)) # (2, 128, 32000)
per_block = sum(p.numel() for p in blocks[0].parameters())
print(logits.shape, per_block, 12 * d * d) # 블록 매개변수 ≈ 12·d²7B 매개변수 모델을 2T(2×10¹²) 토큰으로 사전학습할 때 필요한 연산량은 C ≈ 6ND로 대략?
FLOP. 학습 토큰 하나당 순전파 , 역전파 이다. 문맥이 길면 여기에 attention 항이 더해진다. GPU 한 장이 실효 FLOP/s를 낸다면 약 초, 즉 GPU 6–7년 분량이다.
정리
- 디코더 블록: , . attention은 토큰 사이, FFN은 토큰 안을 처리한다.
- 모양은 내내 . attention 내부만 와 로 갈라진다.
- 블록 매개변수 (attention + FFN ), SwiGLU는 로 같은 예산을 맞춘다. 전체 .
- 토큰당 순전파 , 학습 . 긴 문맥에서는 attention 항이 지배한다.
- pre-norm에서 residual stream은 모든 부품 출력의 정확한 합이다. post-norm은 매 층 앞 내용을 줄여 깊어질수록 불안정하다.
- 인코더(양방향), 디코더(causal), 인코더–디코더(cross-attention). 현재 LLM은 디코더 전용이다.
더 읽을거리Further reading
- Vaswani et al., Attention Is All You Need (NeurIPS, 2017) — 인코더–디코더 Transformer 원 논문 (post-norm, ReLU FFN)The original encoder–decoder Transformer paper (post-norm, ReLU FFN)
- Radford et al., Language Models are Unsupervised Multitask Learners (OpenAI, 2019) — GPT-2. 디코더 전용, pre-norm, residual 가중치 1/√N 초기화GPT-2. Decoder-only, pre-norm, residual weights initialised scaled by 1/√N
- Shazeer, GLU Variants Improve Transformer (2020) — SwiGLU 등 게이트 FFN 변형과 d_ff를 2/3로 줄여 매개변수를 맞추는 관례Gated FFN variants such as SwiGLU, and the convention of shrinking d_ff by 2/3 to match parameter counts
- Touvron et al., LLaMA: Open and Efficient Foundation Language Models (2023) — RMSNorm pre-norm + SwiGLU + RoPE. 오늘날 오픈 LLM 블록의 표준 레시피RMSNorm pre-norm + SwiGLU + RoPE. Today's standard recipe for an open LLM block
- Xiong et al., On Layer Normalization in the Transformer Architecture (ICML, 2020) — post-LN vs pre-LN의 기울기 분석과 warmup 필요성Gradient analysis of post-LN vs pre-LN and why warmup is needed
- Elhage et al., A Mathematical Framework for Transformer Circuits (Anthropic, 2021) — residual stream을 각 층이 읽고 쓰는 통신 채널로 보는 관점The view of the residual stream as a communication channel that every layer reads from and writes to
- Kaplan et al., Scaling Laws for Neural Language Models (2020) — 매개변수 수와 토큰당 FLOPs(2N, 학습 6N)의 표준 계산The standard calculation of parameter count and FLOPs per token (2N, 6N for training)
- Wang et al., DeepNet: Scaling Transformers to 1,000 Layers (2022) — residual 가중(DeepNorm)으로 post-norm을 1000층까지 안정화Stabilises post-norm up to 1000 layers by weighting the residual (DeepNorm)