13.2 Gated MLPs: SwiGLU and GeGLU
The 2017 transformer’s MLP is Linear(d, 4d), ReLU or GELU, Linear(4d, d). Open SmolLM2-135M’s checkpoint and the MLP looks different: three matrices per layer, gate_proj, up_proj, and down_proj, of width 1536 for a model width of 576, not . The 2017 MLP cannot load these weights, and a wrong guess at how the three combine gives logits that look plausible and are wrong.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- GELU: , the input weighted by the standard normal CDF; its tanh approximation is a different function. Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator in Mathematics
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- registration order: the order layers are created in a
Module, which fixes both the state-dict keys and the order of random initialization draws. Read more: 8.2 Bengio’s neural probabilistic language model - Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- safetensors: a checkpoint format of an 8-byte header length, a JSON header, and raw little-endian row-major tensor bytes. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
Every model in the Llama family, Mistral, Qwen, Gemma, and the experts of every mixture of experts use this gated form. This section derives it, explains where the odd width comes from, and builds a module whose outputs and gradients match Hugging Face’s for both the SwiGLU and GeGLU variants.
You will build on Linear and Module from Module system and basic layers, F.silu and F.gelu from The op library and gradcheck_all, the Tensor from Tensor, broadcasting backward, and no_grad, and the PCG32 generator from Modular arithmetic, hashing, and PCG32 in Python in Mathematics, which supplies default initialization. Activation Functions and Their Derivatives covers silu and the tanh GELU. The reference solution is python/tinyllm/modern/mlp.py, which provides GatedMLP and llama_ffn_dim, against the contract course/contracts/py/tinyllm/modern/mlp.pyi.
Learning objectives
- Write the gated MLP formula and explain why the activation belongs on the gate.
- Compute SwiGLU and GeGLU outputs by hand for a scalar example.
- Derive the hidden width and reproduce Meta’s rounding rule, including Llama 3’s multiplier.
- Build a module whose parameter names, order, and rng draws match Hugging Face.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| one token’s hidden vector | float32[..., d] | |
| , | model width, hidden width d_ff | int |
| , | gate and up weights | float32[f, d] |
| down weight | float32[d, f] | |
| logistic sigmoid | elementwise | |
| elementwise | ||
| elementwise | ||
| elementwise product |
From one projection to two
Section titled “From one projection to two”The plain MLP is : one hidden vector, one nonlinearity per unit. A gated linear unit (Dauphin et al.) computes two hidden vectors from the same input and lets one control the other elementwise: , passed through a nonlinearity on the gate side. Written out in full, the modern MLP is
Unit outputs . When is very negative, and the unit is closed regardless of ; when is large, and the unit passes , a product of two linear functions of . The network can therefore form products of input features, which a single ReLU layer cannot.
Shazeer compared the activations. SwiGLU (, used by Llama and SmolLM2) and GeGLU (, used by Gemma) both reach lower perplexity than ReLU or GELU MLPs at equal parameters. Neither has a closed-form reason; it is an empirical result that every model since has kept.
The backward again comes from autograd: F.silu and F.gelu carry the derivatives from Mathematics, and the products do the rest. The gate receives the upstream gradient times , and the up projection receives it times . Both projections learn, and a closed gate also stops the gradient to its up row.
Sizing d_ff
Section titled “Sizing d_ff”A third matrix costs parameters, so the hidden width has to shrink to compensate. Three matrices hold numbers. To compare fairly with the plain MLP’s , set . Meta’s code computes , optionally scales it by ffn_dim_multiplier, and rounds up to a multiple of multiple_of (256 or 1024) so the matrix products tile well on hardware.
Working it by hand
Section titled “Working it by hand”Take scalars throughout: , , , , .
- The gate is and the up projection is .
- For SwiGLU, , so . Times that is , and times the output is .
- For GeGLU, , its is , and . The output is .
The sizing rule works the same way on real models. Llama-2 7B has , so , which rounded up to a multiple of 256 is . SmolLM2 has : , already a multiple of 256.
The interface
Section titled “The interface”class GatedMLP(Module): def __init__(self, d, d_ff, act: Literal["silu", "gelu_tanh"] = "silu", bias=False, rng=None): ... def forward(self, x: Tensor) -> Tensor: ... # [..., d] -> [..., d]def llama_ffn_dim(d, multiple_of=256, ffn_dim_multiplier=None) -> int: ...GatedMLP maps [..., d] to [..., d] and owns three linear layers named as in the checkpoint. act selects between the two allowed activations, bias applies to all three layers, and rng is the single stream the weights are drawn from. llama_ffn_dim derives the hidden width for configs that omit intermediate_size.
Building it step by step
Section titled “Building it step by step”The checkpoint fixes the shape: three matrices named gate_proj, up_proj (both ) and down_proj (). So the module is three Linear layers under exactly those names.
The formula must be the one the weights were trained with, . The activation goes on the gate, because that is what makes “closed” mean closed: for very negative shuts unit whatever is. The activation itself is a configuration choice, silu for SwiGLU (Llama, SmolLM2) and the tanh GELU for GeGLU (Gemma’s gelu_pytorch_tanh), since the erf form differs by about per unit.
Registration order sets both the state_dict order and the order weights are drawn from one rng. Following Hugging Face (gate, up, down) makes both reproducible. A missing intermediate_size must be derived the way Meta does: , optionally times ffn_dim_multiplier (truncated), rounded up to multiple_of. For that gives . Finally, the backward follows from F.silu, F.gelu, and the product; all three projections are parameters used as Tensors, so all three train.
Here is the module:
class GatedMLP(Module): def __init__(self, d, d_ff, act="silu", bias=False, rng=None): super().__init__() # ... positive sizes; act in ("silu", "gelu_tanh") ... r = rng if rng is not None else PCG32(0).substream("init") # ONE stream for all three self.act = act # Registration order is HF's LlamaMLP order: gate, up, down. self.gate_proj = Linear(d, d_ff, bias=bias, rng=r) self.up_proj = Linear(d, d_ff, bias=bias, rng=r) self.down_proj = Linear(d_ff, d, bias=bias, rng=r)
def forward(self, x: Tensor) -> Tensor: g = self.gate_proj(x) a = F.silu(g) if self.act == "silu" else F.gelu(g, approximate="tanh") # The activation gates the OTHER projection: act(gate) * up. return self.down_proj(a * self.up_proj(x))On the worked example (, , , ): , , , and down gives . Writing act(a * up) instead would give , a different function with the same parameters. bias applies to all three layers, as Hugging Face’s mlp_bias does.
The width helper is a few lines of integer arithmetic:
def llama_ffn_dim(d, multiple_of=256, ffn_dim_multiplier=None): # ... d and multiple_of positive ... h = int(2 * (4 * d) / 3) # floor(8d/3): equal parameters to a 4d MLP if ffn_dim_multiplier is not None: # ... must be positive ... h = int(ffn_dim_multiplier * h) # Llama 3's widening, truncated like Meta's code # Round UP to a multiple: hardware-friendly matmul widths. return multiple_of * ((h + multiple_of - 1) // multiple_of)(h + m - 1) // m is the integer ceiling of . For Llama 3 8B (, multiplier 1.3, multiple_of 1024): , , rounded up to . The full solution is in mlp.py.
Why this design
Section titled “Why this design”The cost is three matmuls of per token: multiply-adds and parameters, equal to a plain MLP’s at . The elementwise activation and product are .
The solution keeps three separate Linear layers rather than one fused gate-and-up matrix so the keys load from Hugging Face checkpoints directly. Production engines such as vLLM fuse them for speed, and the C kernel in Elementwise kernels in C fuses . The activation is a string option rather than a callable because the two allowed values map to checkpoint conventions, and a typo fails at construction. The width rounds up, never down, because a width smaller than the checkpoint’s cannot hold its weights.
The tradeoff you accept is that the gated form’s advantage over ReLU and GELU MLPs is empirical (Shazeer 2020), not derived. The solution adopts it because every model it must load does.
What can go wrong
Section titled “What can go wrong”The tests pin down each of those decisions. The hand-worked example must come out right for both activations. Output and gradients must match transformers’ LlamaMLP, including checkpoints with mlp_bias, and GemmaMLP with gelu_pytorch_tanh. A float64 gradcheck covers every parameter for both activations and with biases. Parameter names, order, shapes, and act must match Hugging Face so the safetensors keys line up, and gate, up, and down must be drawn from one rng in that order so one seed fixes the weights everywhere. A property test checks that a negative gate shuts its unit, which is only true if the activation is on the gate, and another checks that the parameter count at is , matching a MLP. llama_ffn_dim must return 11008, 14336, 8192, and 1536 for the corresponding configs, and an unknown activation or a zero width must fail loudly. A model test suite whose oracle is the formula in numpy float64 with the module’s own weights from state_dict() is in test_mlp.py.
Warning: Putting the activation on the up projection loads without error, because the gate and up matrices have the same shape, and then every logit is wrong. The same is true of activating the product, . Neither shows up as a shape error.
The full list of mistakes and their symptoms:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| activation on the up projection | loads fine, every logit wrong | a is computed from gate_proj(x) and multiplies up_proj(x) |
| exact GELU for GeGLU | Gemma outputs off by about 1e-4 per unit, growing with depth | F.gelu(g, approximate="tanh") |
rounding d_ff down | 10752 instead of 11008; the checkpoint shapes do not match | integer ceiling (h + m - 1) // m |
| activating the product, | a different function with the same parameters | the activation is applied to g before the product |
| registering up before gate | state_dict order and draws differ from Hugging Face | layers assigned in the order gate, up, down |
| dropping the down bias | biased checkpoints load and are off by the bias | bias=bias on all three layers |
ignoring ffn_dim_multiplier | Llama-3 widths wrong | h = int(ffn_dim_multiplier * h) before rounding |
| the up projection as a constant | up never trains | self.up_proj(x) is a Tensor op on a parameter |
| a fresh rng for the last layer | two seeds give the same down weights | one r is passed to all three layers |
Where this leads
Section titled “Where this leads”The gated MLP is reused directly in two places in this chapter. Each expert in Mixture of Experts is a GatedMLP, and the mlp of every decoder layer in The Llama-Family Model: Config, Weight Loading, and Download is one too, where SmolLM2-135M’s logits must match Hugging Face. Later, tl_silu_mul_f32 in Elementwise kernels in C fuses in C.
Further reading
Section titled “Further reading”- Shazeer, “GLU Variants Improve Transformer” (2020).
- Dauphin et al., “Language Modeling with Gated Convolutional Networks” (2017), section 3.
- Touvron et al., “LLaMA” (2023), section 2.2.
- Hugging Face
LlamaMLPandGemmaMLPintransformers/models/llama/modeling_llama.py: the same three matrices; tensor-parallel splits shardgateandupby rows anddownby columns. - vLLM
MergedColumnParallelLinearandSiluAndMulinmodel_executor/layers/activation.py: gate and up fused into one matrix, with the activation fused into the product. - Meta’s
FeedForwardinllama/model.pyof Meta’s llama repository: the reference sizing rule.
Key terms
Section titled “Key terms”- Gated linear unit: two projections of the same input, one passed through an activation and multiplied elementwise into the other.
- SwiGLU: the gated MLP with silu on the gate (Llama, SmolLM2).
- GeGLU: the gated MLP with the tanh-approximated GELU on the gate (Gemma).
d_ff(intermediate size): the hidden width , about for a gated MLP, rounded up tomultiple_of.ffn_dim_multiplier: Llama 3’s widening factor applied to the hidden width before rounding.
Summary
Section titled “Summary”- A gated MLP computes : two projections, one gating the other.
- The activation belongs on the gate: a closed gate shuts its unit off whatever the other projection says.
- Three matrices at width cost what two at cost, which is where Llama’s odd widths come from; Meta rounds up to a hardware-friendly multiple.
- Gemma’s GeGLU uses the tanh approximation of GELU, not the erf form.
- Layer names, registration order, and a single rng stream make the module load Hugging Face weights and reproduce seeded initialization.
Review questions
Section titled “Review questions”- Why is the activation applied to the gate projection and not to the up projection?
Answer
The trained weights assume $\operatorname{act}(W_g x) \odot W_u x$. Swapping the roles loads without error (the shapes are equal) but computes a different function, so every logit is wrong. Functionally, the activation on the gate is what lets a unit be switched off independently of its value. - Why is about rather than ?
Answer
The gated MLP has three $f \times d$ matrices instead of two. Matching the plain MLP's $8d^2$ parameters requires $3df = 8d^2$, so $f = \frac83 d$. - Why must all three layers draw from the same rng in the order gate, up, down?
Answer
A seed should fix the weights in every language and implementation. One stream consumed in Hugging Face's registration order gives the same weights everywhere; a fresh stream per layer would make, for example, two different seeds produce identical down weights. - What goes wrong if
llama_ffn_dimrounds down?Answer
For $d = 4096$ it would give 10752 instead of 11008, and the module's shapes would not match the checkpoint's `gate_proj`, `up_proj` and `down_proj`. - Why does GeGLU use
approximate="tanh"?Answer
Gemma's config uses `gelu_pytorch_tanh`. The erf GELU differs by about $10^{-4}$ per unit, and those errors accumulate across layers until parity with Hugging Face fails. - On the scalar example, what does the buggy form give, and what does the correct one give?
Answer
The buggy form gives $3\operatorname{silu}(2) = 5.2848$; the correct form gives $3 \cdot \operatorname{silu}(1) \cdot 2 = 4.386352$.