Build the SwiGLU feed-forward block used in Llama
Llama, Mistral and most new LLMs replaced the plain GELU MLP with a gated one called SwiGLU. Two projections run in parallel; one goes through SiLU and gates the other.
silu(z) = z * sigmoid(z)
swiglu_ffn(x, W_gate, W_up, W_down) = (silu(x @ W_gate) * (x @ W_up)) @ W_down
x is (n, d), W_gate and W_up are (d, h), W_down is (h, d). Return (n, d). Make sigmoid stable for large negative inputs.
def swiglu_ffn(x, W_gate, W_up, W_down)Understand the idea
SwiGLU is a gated feed-forward block. Two linear projections of the input run side by side. One goes through SiLU and acts like a dimmer switch; the other stays linear and gets multiplied by that dimmer. The product is projected back to the model size. SiLU is z x sigmoid(z): close to z for big positive z and close to 0 for big negative z. Worked example with scalars: x = 1, W_gate = 2, W_up = 3, W_down = 0.5. Gate input = 2, sigmoid(2) = 0.881, silu = 1.762. Up branch = 3. Product = 5.285. Output = 5.285 x 0.5 = 2.642. Rule: out = (silu(x W_gate) * (x W_up)) W_down, where * is element-wise; shapes go (n, d) to (n, h) to (n, d). For very negative z, compute sigmoid using exp(-|z|) so nothing overflows. Llama, Mistral and most recent LLMs use SwiGLU in every transformer block.