Convert a GPT block to a Llama-style block (RMSNorm, RoPE, SwiGLU)
Why it matters Porting GPT-2 code to a Llama-family architecture is a common exercise, and these three swaps are exactly what changes.
Llama-style blocks change three pieces of a GPT block: LayerNorm becomes RMSNorm, learned positions become rotary embeddings on q and k, and the GELU MLP becomes SwiGLU. There are no biases.
Write llama_block(x, p, n_heads, base=10000.0). x is (T, d), positions are 0..T-1, hd = d // n_heads (even). p holds w1, w2 (d,), Wq, Wk, Wv, Wo (d, d), Wg, Wu (d, f) and Wd (f, d).
1. rms(z, w) = z / sqrt(mean(z^2, last axis) + 1e-6) * w.
2. h = rms(x, w1); q, k, v = h @ Wq, h @ Wk, h @ Wv, split into heads of width hd (head i uses columns i*hd to (i+1)*hd).
3. RoPE on q and k per head, half-split form: for j < hd/2, theta_j = base^(-2j/hd), angle = pos * theta_j, a = z[:, :hd/2], b = z[:, hd/2:], new z = [a*cos - b*sin, a*sin + b*cos].
4. Causal softmax attention per head with scale 1/sqrt(hd); merge heads; x = x + merged @ Wo.
5. g = rms(x, w2); x = x + (silu(g @ Wg) * (g @ Wu)) @ Wd, with silu(t) = t / (1 + exp(-t)). Return x.
def llama_block(x, p, n_heads, base=10000.0)Example
with all matrices zero and w1 = w2 = ones, x = [[1, 2, 3, 4], [5, 6, 7, 8]] comes back unchanged.
Understand the idea
A Llama-style block keeps the GPT skeleton (pre-norm, attention, residual, MLP, residual) and swaps three parts.
RMSNorm: divide by the root mean square instead of subtracting the mean and dividing by the standard deviation. For [3, 4] the RMS is sqrt((9 + 16) / 2) = 3.54, giving [0.85, 1.13].
RoPE: instead of adding a position vector, rotate each pair of query and key numbers by an angle that grows with position. A pair (1, 0) at position 1 with theta 1 rotates to (cos 1, sin 1) = (0.54, 0.84). Because q and k rotate together, their dot product depends only on the distance between positions.
SwiGLU: out = (silu(g Wg) * (g Wu)) Wd. One branch decides how much of the other passes through, like a dimmer switch.
Rule: x = x + Attn(RoPE(rms(x))) Wo; x = x + SwiGLU(rms(x)). No biases anywhere. Llama, Mistral, Qwen and many other open models follow this layout.
Shapes and data flow
x (T, d) -> q, k, v (H, T, hd) -> RoPE(q), RoPE(k) -> scores (H, T, T) -> att (T, d) -> MLP gate, up (T, f) -> down (T, d)