Looking for the lab runner…

Hands-on lab 02 of 10 · Transformer block

A pre-norm transformer block, and counting its parameters

Assemble one decoder block the way GPT-2 (LayerNorm + GELU MLP) and Llama (RMSNorm + SwiGLU) build it, then write a closed-form parameter count and check it against PyTorch's own count. Lab 01 built attention; here it becomes one sub-layer of a block.

Time: 60 minCheck: python labs/check.py 2

The maths, step by step (x is [B, N, d])

LayerNorm, per token, over the last dim (d values)

mu      = mean(x)                                   [B, N, 1]
var     = mean((x - mu)^2)       (divide by d, NOT d - 1)
LN(x)   = gamma * (x - mu) / sqrt(var + eps) + beta     gamma, beta: [d]

RMSNorm (Llama, Mistral, Qwen...): no mean subtraction, no beta

RMS(x)  = gamma * x / sqrt(mean(x^2) + eps)              gamma: [d]

Feed-forward network (FFN), applied to every token independently

GELU MLP:  W2 GELU(W1 x + b1) + b2            d → d_ff → d   (d_ff = 4d in GPT-2)
SwiGLU:    W_down( SiLU(W_gate x) * (W_up x) )  d → d_ff (twice) → d
           SiLU(z) = z * sigmoid(z); the "gate" decides, per hidden unit,
           how much of W_up x passes through.

Self-attention: lab 01's multi-head attention (q/k/v/o projections).

Pre-norm block (every modern LLM and ViT)

h = x + Attn(Norm1(x))          the residual stream x is never normalised
y = h + FFN(Norm2(h))           itself; each sub-layer reads a normalised
                                copy and ADDS its result back.

(The 2017 paper used post-norm, x = Norm(x + Attn(x)), which trains worse when deep.)

Parameter count (d model width, f = d_ff)

attention   4 d^2           + 4 d   biases (q, k, v, o), if bias
GELU MLP    2 d f           + f + d biases, if bias
SwiGLU      3 d f           (no biases in Llama-style models)
LayerNorm   2 d  (gamma, beta)       RMSNorm  d  (gamma)

The number of heads does not change the count: heads only split d.

Read alongside

Preview (covered in the next tutorial, Build an LLM)

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 2: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab02_transformer_block.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.

Cells on this page:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 LayerNorm and RMSNorm

class LayerNorm(nn.Module)

to write

LayerNorm over the last dimension, written out (do not call F.layer_norm).

Write forward(x)

x: [..., d] → [..., d]

Hint 1
mean and variance over dim=-1 with keepdim=True, so they broadcast.
Hint 2
LayerNorm uses the biased variance: x.var(dim=-1, unbiased=False), or ((x - mu) ** 2).mean(-1, keepdim=True). Avoid E[x^2] - E[x]^2: it loses precision in float32 when the mean is large.
Hint 3
return self.weight * (x - mu) / torch.sqrt(var + self.eps) + self.bias

class RMSNorm(nn.Module)

to write

RMSNorm over the last dimension: gamma * x / sqrt(mean(x^2) + eps).

Write forward(x)

x: [..., d] → [..., d]

Hint 1
one line once you have mean(x^2) over the last dim (keepdim=True).
Hint 2
torch.rsqrt(t) = 1 / sqrt(t).
Hint 3
return self.weight * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

2 the two feed-forward networks

class GeluMLP(nn.Module)

to write

GPT-2 / ViT FFN: fc2(GELU(fc1(x))), d → d_ff → d.

Write forward(x)

Hint 1
use F.gelu with its default (exact, erf-based) form; approximate="tanh" differs by about 1e-3.
Hint 2
return self.fc2(F.gelu(self.fc1(x)))

class SwiGLU(nn.Module)

to write

Llama FFN: w_down( SiLU(w_gate(x)) * w_up(x) ), d → d_ff → d.

Write forward(x)

Hint 1
SiLU is applied to the gate branch only; the up branch stays linear.
Hint 2
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))

3 self-attention (lab 01 again, as a sub-layer)

attend(q, k, v, causal)

given

Given: lab 01's scaled_dot_product_attention, as torch's fused kernel. q, k, v [B, h, N, d_k] → [B, h, N, d_k].

Show the given code (it is already written: just run it)

class SelfAttention(nn.Module)

to write

Multi-head self-attention. Same maths as lab 01's MultiHeadAttention.

Write forward(x, causal=True)

x: [B, N, d] → [B, N, d] (returns only the output, no weights)

Hint 1
project, split into heads, attend, merge, project: lab 01's MultiHeadAttention, with the given attend() for the middle step.
Hint 2
split: t.view(B, N, h, d // h).transpose(1, 2) merge: o.transpose(1, 2).reshape(B, N, d)
Hint 3
def split(t): return t.view(B, N, h, d // h).transpose(1, 2) q, k, v = split(self.q_proj(x)), split(self.k_proj(x)), split(self.v_proj(x)) o = attend(q, k, v, causal) return self.o_proj(o.transpose(1, 2).reshape(B, N, d))

4 the pre-norm block

class Block(nn.Module)

to write

Pre-norm transformer block.

norm: "layernorm" (GPT-2, ViT) or "rmsnorm" (Llama) ffn: "gelu" (GPT-2, ViT) or "swiglu" (Llama) bias: whether the Linear layers have biases (GPT-2: yes, Llama: no)

Write forward(x, causal=True)

x: [B, N, d] → [B, N, d]

Hint 1
two lines, one per sub-layer, each of the form x = x + sublayer(norm(x)).
Hint 2
the norm goes INSIDE the residual branch (pre-norm), not after the add.
Hint 3
x = x + self.attn(self.norm1(x), causal=causal); x = x + self.ffn(self.norm2(x))

5 count the parameters in closed form

count_block_params(d, n_heads, d_ff, norm='layernorm', ffn='gelu', bias=True)

to write

Number of parameters of Block(d, n_heads, d_ff, norm, ffn, bias), from a formula.

Do not build the module and call .numel(); work it out from the shapes. Sanity anchors:

GPT-2 small block: d=768, d_ff=3072, layernorm, gelu, bias  → 7,087,872
Llama-2-7B block:  d=4096, d_ff=11008, rmsnorm, swiglu, no bias → 202,383,360
Hint 1
add up the pieces listed in the module docstring: attention, FFN, 2 norms.
Hint 2
a Linear(a, b) holds a*b weights plus b biases (if bias).
Hint 3
attn = 4*d*d + (4*d if bias else 0) ffn = 2*d*d_ff + (d_ff + d if bias else 0) for gelu 3*d*d_ff + (2*d_ff + d if bias else 0) for swiglu norms = 2 * (2*d if layernorm else d)

✎ Scratch cell

Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).