The problem
Time to assemble the pieces into the block that models in the style of LLaMA (Large Language Model Meta AI) stack dozens of times. A block has two sub-layers, each wrapped the same way:
- MHA (multi-head attention), where the tokens exchange information;
- an MLP (multilayer perceptron) of the SwiGLU (Swish-gated linear unit) kind, where each token is processed on its own;
- before each sub-layer, an RMSNorm (root mean square layer normalization).
The block
For x of shape :
where and have their own gains. Read each line as: take a normalized copy of the stream, run the sub-layer on it, and add the result to the stream itself (the residual connection). The stream is never replaced, only corrected.
Example. A useful check. If the output matrices of both sub-layers are zero ( in attention, in the MLP), both sub-layers output zero, so and : the block returns
xunchanged. A block that normalizes the stream itself, instead of a copy, fails this check.
The SwiGLU MLP
where:
- is the normalized input, and have shape and widen each vector to numbers, and , of shape , narrows it back;
- is the SiLU (sigmoid linear unit): times its sigmoid ;
- is the elementwise product: the branch acts as a gate that scales each entry of the other branch.
Example. SiLU of a few numbers: , , , , . Large positive inputs pass almost unchanged, large negative ones are switched off, like ReLU (rectified linear unit) but smooth.
What to implement
silu(z), elementwise.swiglu_mlp(u, W1, W3, W2).transformer_block(x, p, n_heads), wherepis a dict with"norm1","norm2"(RMSNorm gains, shape ),"Wq","Wk","Wv","Wo"(shape ) and"W1","W3","W2".
rmsnorm(x, gamma) and mha_forward(x, Wq, Wk, Wv, Wo, n_heads) (causal, from the earlier exercises) are given. To keep the block focused, it has no RoPE (rotary position embedding).
Requirements
- Pre-norm: normalize the input of each sub-layer, and add the sub-layer's output to the un-normalized stream.
- The second sub-layer reads , the output of the first, not .
- No loops.
Hint
For a sigmoid that never overflows, (section 2).