Track II · DL Fundamentals · 07/07

Transformer 블록 해부Anatomy of a Transformer block

지금까지의 부품(MLP, 정규화, residual, attention)을 조립해 현대 LLM의 pre-norm 디코더 블록을 완성한다. 텐서 모양을 끝까지 추적하고, 블록당 매개변수 ≈ 12d², 토큰당 FLOPs ≈ 2N + attention을 직접 세며, residual stream 관점과 인코더/디코더의 차이를 설명할 수 있게 된다.Assemble the parts so far (MLP, normalisation, residual connections, attention) into the pre-norm decoder block of modern LLMs. You will trace tensor shapes all the way through, count parameters per block ≈ 12d² and FLOPs per token ≈ 2N + attention yourself, and explain the residual-stream view and the difference between encoders and decoders.

40 분min transformer · multi-head attention · SwiGLU · residual stream · pre-norm · parameter count · FLOPs 먼저 볼 것:Before this: Attention: query·key·valueAttention: query, key, value, 깊은 망 학습하기Training deep networks

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.

  1. Embedding: a sequence of token ids (B,T)(B, T) is looked up in a V×dV \times d table to make a (B,T,d)(B, T, d) tensor xx. This is the start of the residual stream.
  2. Blocks × L: each block reads xx and adds something to it. The shape stays (B,T,d)(B, T, d) throughout.
  3. Final norm + LM head: after a last RMSNorm, a d×Vd \times V matrix produces logits over the whole vocabulary, (B,T,V)(B, T, V). The logits at position tt are the distribution of token t+1t+1.

One block consists of two residual branches.

x←x+MHA⁡(RMSNorm⁡(x))x←x+FFN⁡(RMSNorm⁡(x))\begin{aligned} x &\leftarrow x + \operatorname{MHA}\big(\operatorname{RMSNorm}(x)\big) \\ x &\leftarrow x + \operatorname{FFN}\big(\operatorname{RMSNorm}(x)\big) \end{aligned}

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) 언어 모델은 다음과 같이 흐른다.

  1. 임베딩: 토큰 id 시퀀스 (B,T)(B, T)를 V×dV \times d 표에서 찾아 (B,T,d)(B, T, d) 텐서 xx로 만든다. 이것이 residual stream의 시작이다.
  2. 블록 × L: 각 블록이 xx를 읽고 무언가를 더한다. 모양은 내내 (B,T,d)(B, T, d)로 유지된다.
  3. final norm + LM head: 마지막 RMSNorm 뒤 d×Vd \times V 행렬로 vocabulary 전체에 대한 logit (B,T,V)(B, T, V)를 낸다. 위치 tt의 logit이 토큰 t+1t+1의 분포다.

블록 하나는 두 개의 residual 가지로 되어 있다.

x←x+MHA⁡(RMSNorm⁡(x))x←x+FFN⁡(RMSNorm⁡(x))\begin{aligned} x &\leftarrow x + \operatorname{MHA}\big(\operatorname{RMSNorm}(x)\big) \\ x &\leftarrow x + \operatorname{FFN}\big(\operatorname{RMSNorm}(x)\big) \end{aligned}

attention은 토큰 사이로 정보를 옮기고(위치를 섞는 유일한 곳), FFN은 각 토큰 안에서 정보를 가공한다(위치마다 같은 MLP). 둘 다 정규화된 입력을 읽어 stream에 더하기만 한다. 위치 정보는 RoPE처럼 attention의 q, k에 회전을 주는 방식으로 넣는 것이 현재의 표준이다(Track III).

프리셋Presets
입력input x (residual stream)
Attention 가지Attention branch
RMSNorm
Q = xWQ
K, V = xWK, xWV
QKᵀ/√dh + mask → softmax
× V
concat · WO
⊕ x ← x + Attn(Norm(x))
FFN 가지FFN branch
RMSNorm
W₁x, W₃x
SiLU(W₁x) ⊙ W₃x
· W₂
⊕ x ← x + FFN(Norm(x))
× L 블록blocks → final norm → LM head
블록 하나의 매개변수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)
Press a preset and move the sliders to see how each tensor shape and the numbers on the right change. Parameters grow with the square of dmodel; attention compute grows in proportion to the context length T. Raise T to 128K and attention overtakes the matmuls in FLOPs per token. Reducing KV heads (GQA) shrinks the KV cache by the same factor. Small terms such as biases and position embeddings are omitted (about 1% off GPT-2 small's actual 124M). 프리셋을 누르고 슬라이더를 움직여 각 텐서 모양과 오른쪽 숫자가 어떻게 변하는지 보세요. 매개변수는 dmodel의 제곱으로, attention 연산은 문맥 길이 T에 비례해 자란다. T를 128K로 올리면 토큰당 FLOPs에서 attention이 행렬곱을 넘어선다. KV heads를 줄이면(GQA) KV cache가 그만큼 준다. 편향·위치 임베딩 같은 작은 항은 생략했다(GPT-2 small의 실제 124M과 약 1% 차이).

FFN: from a GELU MLP to SwiGLU

The FFN of the original Transformer and of GPT-2 is a one-hidden-layer MLP. dff=4dd_{ff} = 4d by convention.

FFN⁡GELU(u)=W2 GELU⁡(W1u),W1∈Rdff×d,  W2∈Rd×dff\operatorname{FFN}_{\text{GELU}}(u) = W_2\,\operatorname{GELU}(W_1 u), \qquad W_1 \in \mathbb{R}^{d_{ff}\times d},\; W_2 \in \mathbb{R}^{d\times d_{ff}}

Shazeer (2020) compared GLU variants that put a gate where the activation was, and of these SwiGLU became the standard after LLaMA.

FFN⁡SwiGLU(u)=W2(SiLU⁡(W1u)⊙W3u),SiLU⁡(z)=z σ(z)\operatorname{FFN}_{\text{SwiGLU}}(u) = W_2\big(\operatorname{SiLU}(W_1 u) \odot W_3 u\big), \qquad \operatorname{SiLU}(z) = z\,\sigma(z)

There are now three matrices, so to match the same parameter budget, 3d dff=2d⋅4d3 d\, d_{ff} = 2d \cdot 4d, i.e. shrink to dff=83dd_{ff} = \tfrac{8}{3}d. LLaMA-2 7B’s dff=11008d_{ff} = 11008 is 83×4096≈10923\tfrac83 \times 4096 \approx 10923 rounded up to a multiple of 256. The gate W3uW_3 u 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 dff=4dd_{ff} = 4d (or SwiGLU’s 83d\tfrac83 d), independent of the number of heads:

PartMatricesParameters
attentionWQ,WK,WV,WOW_Q, W_K, W_V, W_O, each d×dd\times d4d24d^2
FFN2×d⋅4d2 \times d \cdot 4d (or 3×d⋅83d3\times d\cdot\tfrac83 d)8d28d^2
2 RMSNormsγ\gamma vectors2d2d
Block total≈12d2\approx 12d^2

The total is N≈12 L d2+VdN \approx 12\,L\,d^2 + V d (2Vd2Vd if the input embedding and LM head are not shared). For GPT-2 small (d=768d = 768, L=12L = 12, V=50257V = 50257, shared), 12⋅12⋅7682≈84.9M12 \cdot 12 \cdot 768^2 \approx 84.9\text{M} plus 38.6M38.6\text{M} of embeddings gives 123.5M123.5\text{M}. Adding biases and position embeddings gives the official 124M. GQA (grouped-query attention) uses fewer key/value heads nkvn_{kv} than query heads, making WK,WVW_K, W_V of size d×nkvdhd \times n_{kv}d_h. Parameters shrink a little, the KV cache by a factor of h/nkvh/n_{kv} (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 2N2N (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 TT computes, per layer, one row of QK⊤QK^\top (TT inner products, 2Td2Td FLOPs) and AVAV (2Td2Td FLOPs), so

Cforward≈2N+4 L T d(per token)C_{\text{forward}} \approx 2N + 4\,L\,T\,d \quad \text{(per token)}

In training, backprop costs about twice the forward pass (one matrix product each for the activation gradients and the weight gradients), so it becomes ≈6N\approx 6N per token. This is the C≈6NDC \approx 6ND (DD = 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.

NumPy NumPy: a pre-norm decoder block (MHA + SwiGLU + RMSNorm)
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%}")
 
확인 문제Check yourself

For a GELU Transformer with d_model = 4096, 32 layers and d_ff = 4d, what is the total block parameter count (excluding embeddings), roughly?

12Ld2=12×32×40962≈6.44×10912 L d^2 = 12 \times 32 \times 4096^2 \approx 6.44 \times 10^9. Add the embedding and LM head (0.130.13B each with V=32000V = 32000) 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

xL=x0+∑l=1L(attn⁡l+ffn⁡l)x_L = x_0 + \sum_{l=1}^{L}\Big(\operatorname{attn}_l + \operatorname{ffn}_l\Big)

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 (WQ,WK,WVW_Q, W_K, W_V or W1W_1 after normalisation) and writes to another subspace through WOW_O or W2W_2. 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 xLx_L, so each part’s contribution to the final logits can be decomposed directly, as in WU attn⁡lW_U\,\operatorname{attn}_l (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, x←Norm⁡(x+f(x))x \leftarrow \operatorname{Norm}(x + f(x)), so earlier content shrinks with every layer it passes.

FFN: GELU MLP에서 SwiGLU로

원조 Transformer와 GPT-2의 FFN은 은닉층 하나짜리 MLP다. dff=4dd_{ff} = 4d가 관례다.

FFN⁡GELU(u)=W2 GELU⁡(W1u),W1∈Rdff×d,  W2∈Rd×dff\operatorname{FFN}_{\text{GELU}}(u) = W_2\,\operatorname{GELU}(W_1 u), \qquad W_1 \in \mathbb{R}^{d_{ff}\times d},\; W_2 \in \mathbb{R}^{d\times d_{ff}}

Shazeer(2020)는 활성화 자리에 게이트를 넣은 GLU 변형들을 비교했고, 그중 SwiGLU가 LLaMA 이후 표준이 되었다.

FFN⁡SwiGLU(u)=W2(SiLU⁡(W1u)⊙W3u),SiLU⁡(z)=z σ(z)\operatorname{FFN}_{\text{SwiGLU}}(u) = W_2\big(\operatorname{SiLU}(W_1 u) \odot W_3 u\big), \qquad \operatorname{SiLU}(z) = z\,\sigma(z)

행렬이 셋이 되었으므로 같은 매개변수 예산을 맞추려면 3d dff=2d⋅4d3 d\, d_{ff} = 2d \cdot 4d, 즉 dff=83dd_{ff} = \tfrac{8}{3}d로 줄인다. LLaMA-2 7B의 dff=11008d_{ff} = 11008은 83×4096≈10923\tfrac83 \times 4096 \approx 10923을 256의 배수로 올린 값이다. 게이트 W3uW_3 u는 은닉 유닛마다 “얼마나 통과시킬지”를 입력에 따라 정하는 곱셈이라, 첫 레슨의 ReLU 꺾임보다 표현이 풍부하다. 왜 더 좋은지에 대한 이론은 아직 빈약하고, Shazeer 자신도 논문 말미에서 그 성공을 “divine benevolence” 덕으로 돌렸다.

매개변수 세기: 12d²

dff=4dd_{ff} = 4d(또는 SwiGLU 83d\tfrac83 d), 헤드 수와 무관하게:

부품행렬매개변수
attentionWQ,WK,WV,WOW_Q, W_K, W_V, W_O 각 d×dd\times d4d24d^2
FFN2×d⋅4d2 \times d \cdot 4d (또는 3×d⋅83d3\times d\cdot\tfrac83 d)8d28d^2
RMSNorm 2개γ\gamma 벡터2d2d
블록 합≈12d2\approx 12d^2

전체는 N≈12 L d2+VdN \approx 12\,L\,d^2 + V d (입력 임베딩과 LM head를 공유하지 않으면 2Vd2Vd)이다. GPT-2 small(d=768d = 768, L=12L = 12, V=50257V = 50257, 공유)이면 12⋅12⋅7682≈84.9M12 \cdot 12 \cdot 768^2 \approx 84.9\text{M}에 임베딩 38.6M38.6\text{M}을 더해 123.5M123.5\text{M}. 편향과 위치 임베딩을 더하면 공식 수치 124M이 된다. GQA(grouped-query attention)는 key·value 헤드 수 nkvn_{kv}를 query 헤드 수보다 줄여 WK,WVW_K, W_V를 d×nkvdhd \times n_{kv}d_h로 만든다. 매개변수는 조금, KV cache는 h/nkvh/n_{kv}배 줄어든다(LLaMA-3 8B는 32개 query 헤드에 8개 KV 헤드).

연산량 세기: 2N + attention

행렬–벡터 곱에서 가중치 하나는 곱셈 하나와 덧셈 하나, 즉 2 FLOP을 쓴다. 그러니 토큰 하나의 순전파에서 행렬곱 비용은 약 2N2N이다(임베딩 조회는 곱셈이 아니므로 빼고, LM head는 넣는다). 여기에 매개변수가 없는 연산인 attention이 더해진다. 문맥 길이 TT의 토큰 하나는 층마다 QK⊤QK^\top의 한 행(TT개 내적, 2Td2Td FLOP)과 AVAV(2Td2Td FLOP)를 계산하므로

Cforward≈2N+4 L T d(토큰당)C_{\text{forward}} \approx 2N + 4\,L\,T\,d \quad \text{(토큰당)}

이다. 학습할 때는 역전파가 순전파의 약 2배(활성화 기울기와 가중치 기울기 각각 행렬곱 하나)이므로 토큰당 ≈6N\approx 6N이 된다. Kaplan et al.(2020)과 Chinchilla의 C≈6NDC \approx 6ND(DD = 학습 토큰 수)가 이것이다. 그림에서 T를 늘려 보면 짧은 문맥에서는 attention이 10–20%에 불과하지만, 128K 문맥에서는 행렬곱을 훨씬 넘어선다. 긴 문맥 모델에서 attention 최적화가 결정적인 이유다.

→ 더 깊이: 설계 공간에서 이 매개변수·FLOPs 세기를 GQA/MLA, MoE 같은 현대 블록의 다른 손잡이로 넓히고, 실제 모델 config를 비교하는 데 쓴다.

NumPy NumPy: pre-norm 디코더 블록 (MHA + SwiGLU + RMSNorm)
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%}")
 
확인 문제Check yourself

d_model = 4096, 32층, d_ff = 4d인 GELU Transformer의 블록 매개변수 합(임베딩 제외)은 대략?

12Ld2=12×32×40962≈6.44×10912 L d^2 = 12 \times 32 \times 4096^2 \approx 6.44 \times 10^9. 여기에 임베딩과 LM head(V=32000V = 32000이면 각 0.130.13B)를 더하면 LLaMA-2 7B의 6.7B가 된다. 큰 모델의 매개변수는 거의 전부 블록 안의 행렬이다.

Residual stream이라는 관점

블록의 식을 펼쳐 쓰면 마지막 층의 stream은

xL=x0+∑l=1L(attn⁡l+ffn⁡l)x_L = x_0 + \sum_{l=1}^{L}\Big(\operatorname{attn}_l + \operatorname{ffn}_l\Big)

이다. 모든 부품의 출력이 더해져서 하나의 벡터를 이룬다. Elhage et al.(2021)은 이 stream을 각 층이 공유하는 통신 채널 로 보자고 제안했다. 각 부품은 선형 투영(정규화 후 WQ,WK,WVW_Q, W_K, W_V나 W1W_1)으로 stream의 일부 부분공간을 읽고, WOW_O나 W2W_2로 다른 부분공간에 쓴다. 앞 층이 써 둔 정보를 뒤 층이 읽어서 쓰는 것, 예를 들어 지난 레슨의 이전 토큰 헤드가 쓴 “내 앞 토큰”을 유도 헤드가 key로 읽는 것이 이 채널을 통한 합성이다. LM head는 결국 xLx_L을 읽으므로, 각 부품이 최종 logit에 준 기여를 WU attn⁡lW_U\,\operatorname{attn}_l처럼 직접 분해해 볼 수 있다(direct logit attribution). 해석 가능성 연구가 이 덧셈 구조에 크게 기대는 이유다.

그 깨끗한 덧셈은 pre-norm 이기 때문에 성립한다. post-norm에서는 매 층 x←Norm⁡(x+f(x))x \leftarrow \operatorname{Norm}(x + f(x))로 stream 전체가 다시 정규화되므로, 앞쪽 내용이 층을 지날 때마다 줄어든다.

Pre-norm: x ← x + f(Norm(x))
Post-norm: x ← Norm(x + f(x))
최종 stream 중 x₀(임베딩) 몫:share of x₀ (embedding) in the final stream: pre – · post – 최종 RMS:final RMS: pre – · post –
Where the energy ‖xl‖² of the residual stream xl comes from at each layer l (horizontal axis): black = input embedding x₀, blue→red = the values fk added by earlier→later blocks. Under pre-norm the stream is a plain sum of every write, so the contributions of x₀ and the early blocks survive to the end (the identity path). Under post-norm the normalisation at every layer shrinks the earlier content by about 1/√2, so the output is dominated by the last few blocks. Lower β (initialise the branches small) and post-norm also preserves x₀ for longer. Post-norm stabilisation methods such as DeepNet tune exactly this ratio. 각 층 l(가로축)에서 residual stream xl의 에너지 ‖xl‖²가 어디서 왔는지: 검정 = 입력 임베딩 x₀, 파랑→빨강 = 앞쪽→뒤쪽 블록이 더한 값 fk. pre-norm에서는 stream이 모든 쓰기의 단순한 합이라 x₀와 초기 블록의 기여가 끝까지 그대로 남는다(항등 경로). post-norm에서는 매 층 정규화가 지난 내용을 약 1/√2배씩 줄여서, 출력이 마지막 몇 블록에 지배된다. β를 줄이면(가지를 작게 초기화) post-norm도 x₀를 오래 보존한다. DeepNet 같은 post-norm 안정화 기법이 바로 이 비율을 조절한다.

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 1/21/\sqrt2, 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 α>1\alpha > 1 (Norm⁡(αx+f(x))\operatorname{Norm}(\alpha x + f(x))) 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 maskRepresentative modelsTraining objectiveUsed for
Encoderbidirectional (no mask)BERTpredict masked tokens (MLM)classification, retrieval embeddings
DecodercausalGPT, LLaMAnext-token predictiongeneration, today’s LLMs
Encoder–decoderbidirectional encoder + causal decoder + cross-attentionoriginal Transformer, T5input → output transformationtranslation, 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.

PyTorch PyTorch: the same block as an nn.Module 로컬에서 실행run locally (pip install torch)
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²
 
확인 문제Check yourself

Pre-training a 7B-parameter model on 2T (2×10¹²) tokens: by C ≈ 6ND, roughly how much compute is needed?

6×7×109×2×1012=8.4×10226 \times 7\times10^9 \times 2\times10^{12} = 8.4\times10^{22} FLOP. Per training token, the forward pass is 2N2N and backprop 4N4N. With long contexts the attention term is added on top. If one GPU delivers an effective 4×10144\times10^{14} FLOP/s, that is about 2×1082\times10^8 seconds — 6–7 GPU-years.

Summary

  • Decoder block: x←x+MHA⁡(Norm⁡(x))x \leftarrow x + \operatorname{MHA}(\operatorname{Norm}(x)), x←x+FFN⁡(Norm⁡(x))x \leftarrow x + \operatorname{FFN}(\operatorname{Norm}(x)). Attention works between tokens, the FFN within each token.
  • The shape is (B,T,d)(B, T, d) throughout. Only inside attention does it split into (B,h,T,dh)(B, h, T, d_h) and (B,h,T,T)(B, h, T, T).
  • Block parameters ≈12d2\approx 12d^2 (attention 4d24d^2 + FFN 8d28d^2); SwiGLU matches the same budget with dff=83dd_{ff} = \tfrac83 d. In total N≈12Ld2+VdN \approx 12Ld^2 + Vd.
  • Forward per token ≈2N+4LTd\approx 2N + 4LTd, training ≈6N\approx 6N. 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에서는 매 층 약 1/21/\sqrt2배씩 줄어, 24층 뒤 임베딩의 몫이 사실상 0이고 출력은 마지막 몇 블록이 결정한다. 역전파로 보면 항등 경로의 기울기가 같은 비율로 줄어든다. 3레슨에서 본 post-LN의 학습 불안정(warmup 필요)과 같은 뿌리다. DeepNet(Wang et al., 2022)은 post-norm에서 residual에 α>1\alpha > 1을 곱해(Norm⁡(αx+f(x))\operatorname{Norm}(\alpha x + f(x))) 이 감쇠를 늦추는 방식으로 1000층 학습을 보였다. 그림의 β를 줄이는 것과 같은 효과다.

인코더, 디코더, 인코더–디코더

같은 블록을 mask와 연결만 바꿔 세 가지로 쓴다.

attention mask대표 모델학습 목표쓰임
인코더양방향(mask 없음)BERT가려진 토큰 맞히기(MLM)분류·검색 임베딩
디코더causalGPT, LLaMA다음 토큰 예측생성, 현재의 LLM
인코더–디코더인코더 양방향 + 디코더 causal + cross-attention원조 Transformer, T5입력 → 출력 변환번역·요약

cross-attention은 query를 디코더 stream에서, key·value를 인코더 출력에서 가져오는 attention이다. 디코더 전용 모델은 입력(프롬프트)과 출력을 한 시퀀스로 이어 붙이고 causal mask 하나로 둘 다 처리한다. 구조가 단순하고, 모든 토큰이 다음 토큰 예측이라는 같은 목표로 학습되며, KV cache로 생성이 효율적이라는 점에서 현재의 LLM은 거의 모두 디코더 전용이다.

PyTorch PyTorch: 같은 블록을 nn.Module로 로컬에서 실행run locally (pip install torch)
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²
 
확인 문제Check yourself

7B 매개변수 모델을 2T(2×10¹²) 토큰으로 사전학습할 때 필요한 연산량은 C ≈ 6ND로 대략?

6×7×109×2×1012=8.4×10226 \times 7\times10^9 \times 2\times10^{12} = 8.4\times10^{22} FLOP. 학습 토큰 하나당 순전파 2N2N, 역전파 4N4N이다. 문맥이 길면 여기에 attention 항이 더해진다. GPU 한 장이 실효 4×10144\times10^{14} FLOP/s를 낸다면 약 2×1082\times10^8초, 즉 GPU 6–7년 분량이다.

정리

  • 디코더 블록: x←x+MHA⁡(Norm⁡(x))x \leftarrow x + \operatorname{MHA}(\operatorname{Norm}(x)), x←x+FFN⁡(Norm⁡(x))x \leftarrow x + \operatorname{FFN}(\operatorname{Norm}(x)). attention은 토큰 사이, FFN은 토큰 안을 처리한다.
  • 모양은 내내 (B,T,d)(B, T, d). attention 내부만 (B,h,T,dh)(B, h, T, d_h)와 (B,h,T,T)(B, h, T, T)로 갈라진다.
  • 블록 매개변수 ≈12d2\approx 12d^2 (attention 4d24d^2 + FFN 8d28d^2), SwiGLU는 dff=83dd_{ff} = \tfrac83 d로 같은 예산을 맞춘다. 전체 N≈12Ld2+VdN \approx 12Ld^2 + Vd.
  • 토큰당 순전파 ≈2N+4LTd\approx 2N + 4LTd, 학습 ≈6N\approx 6N. 긴 문맥에서는 attention 항이 지배한다.
  • pre-norm에서 residual stream은 모든 부품 출력의 정확한 합이다. post-norm은 매 층 앞 내용을 줄여 깊어질수록 불안정하다.
  • 인코더(양방향), 디코더(causal), 인코더–디코더(cross-attention). 현재 LLM은 디코더 전용이다.

더 읽을거리Further reading