Compute the SwiGLU feed-forward hidden size used by Llama
Why it matters These exact rules decide the MLP width of Llama-family checkpoints, and loading weights fails if you compute the size differently.
SwiGLU has three weight matrices instead of two, so Llama-style models shrink the hidden size to about 2/3 of 4d to keep the parameter count similar, then round up for hardware efficiency.
Write swiglu_hidden(d, multiple_of, ffn_mult=None). Start with h = int(2 * (4 * d) / 3). If ffn_mult is given, h = int(ffn_mult * h). Round h UP to the nearest multiple of multiple_of. Return a dict with "hidden": h, "swiglu_params": 3 * d * h and "gelu_params": 8 * d * d (the two-matrix MLP with hidden 4d, no biases).
def swiglu_hidden(d, multiple_of, ffn_mult=None)Example
swiglu_hidden(4096, 256) is {"hidden": 11008, "swiglu_params": 135266304, "gelu_params": 134217728}.
Understand the idea
A GELU MLP has two matrices, d to 4d and 4d to d, so 8d^2 weights. SwiGLU has three matrices (gate, up, down). To keep roughly the same budget, the hidden width is cut to 2/3 of 4d, because 3 * d * (8d/3) = 8d^2.
Example: d = 4096. 4d = 16384, times 2/3 is 10922.67, truncated to 10922. Rounding up to a multiple of 256 gives 11008. SwiGLU parameters: 3 * 4096 * 11008 = 135.3 million, close to the GELU MLP's 8 * 4096^2 = 134.2 million.
Rule: h = int(8d / 3); optionally h = int(m * h); h = ceil(h / multiple_of) * multiple_of.
Rounding to a multiple of 256 or more makes matrix shapes friendly for GPU tiles. Llama 7B uses hidden size 11008 this way, and larger Llama 2 models add a multiplier, for example d = 8192 with 1.3 and multiple 4096 gives 28672.