Overview
A classic feed-forward block widens the input, applies an activation, and narrows it again. A gated block widens the input twice, with two separate weight matrices. One copy, the gate branch, goes through SiLU. The other copy, the value branch, stays linear. The two are multiplied element by element, so each hidden unit's value is scaled by a factor the input itself chose. That product lets the block compute terms that depend on pairs of input features, which a single activation cannot do in one step.
A short history
Noam Shazeer introduced SwiGLU in the 2020 note 'GLU Variants Improve Transformer', which tested gated feed-forward layers with different activations on the gate. The variant gated by Swish was among the best at equal parameter count. Google's PaLM adopted it in 2022 and Meta's LLaMA in 2023, and it has since become the usual feed-forward block in large language models.
How it works
- Take an input of width (the config's
dim). - Compute the gate pre-activation and the value , each of width (
hidden_dim). Biases are added whenbiasis on. - Apply SiLU to the gate branch only.
- Multiply element by element: .
- Project back to width : .
- In
backward, send the gradient through , split it between the two branches with the product rule, and store one gradient per parameter ingrads.
Watch out for
- The block has three weight matrices, not two. Keeping
hidden_dimat makes it 50 percent larger than the classic block, so use about for a fair comparison. - The output is a product of two functions of , so it grows roughly quadratically with the input scale. Without normalisation before the block, activations can blow up.
- The template is a small NumPy version with hand-written backpropagation and plain gradient descent in
step. Real models run this block inside a framework with an adaptive optimiser. backwardmust be given the same thatforwardsaw. It recomputes both branches from it and overwritesgradson every call.
Use cases
When to use it
Transformer feed-forward layers in modern language models. LLaMA-style models use this block with no biases and a hidden width of about .
In industry
- Large language models
- PaLM and the LLaMA family use SwiGLU as the feed-forward block in every transformer layer.
- Code assistants
- Open code generation models built on LLaMA style architectures inherit the SwiGLU feed-forward block.
- Vision transformers
- Some recent self-supervised vision transformers, such as the larger DINOv2 models, use a SwiGLU feed-forward layer in place of the plain GELU block.
Choosing it: what must hold
- A transformer whose feed-forward block you control, typically a model trained from scratch.
- A hidden width set to about two thirds of the usual four times expansion, to keep the parameter count equal.
- If you load pretrained weights, a checkpoint that was trained with this block.
When to choose something else
| If | Use instead |
|---|---|
| You must match a BERT, GPT-2 or ViT style checkpoint | GELU in a plain feed-forward block |
| You want the gated block with a GELU gate, as in T5 version 1.1 | GEGLU |
| The model is a small convolutional or fully connected network | ReLU or SiLU |
Math foundations
The classic block it replaces
Widen with , apply one activation, narrow with . Each hidden unit depends on the input through one linear map only.
The gated block
Two linear maps of the same input, one activated and one not, multiplied element by element and then projected. This is what
forwardcomputes.The gate activation
Each gate value is its input scaled by its own sigmoid. It is smooth and dips slightly below zero for negative inputs.
Gradients of the two branches
The product rule. Each branch receives the upstream gradient scaled by the other branch. If one branch is near zero, the other learns slowly.
Matching the parameter count
The gated block has three matrices. The classic block with hidden width has weights. Setting them equal gives the usual hidden width.
Symbols
- the input row vector, width d
- gate and value weight matrices, each d by h;
w_gateandw_valueinparams - output weight matrix, h by d;
w_outinparams - gate pre-activation and value, each of width h
- element by element multiplication
- the gradient of the loss with respect to the hidden product
- the loss being minimised
- input width
dimand hidden widthhidden_dim - the activation of the classic block, for example ReLU or GELU
- the logistic sigmoid
Worked by hand
Take the smallest block: , no bias, with , , and input . The sigmoid gives .
The output is 0.7311. Doubling would double both branches before the activation, so the output more than doubles: the block is not linear in its input.
Visual example
Loading the example.
Try this
- Move across the curve and read the output and the slope together.
- Find where the slope is close to zero: a unit there has stopped learning.
Code sample
import numpy as np
from impl import SwiGLU
from config import SwiGLUConfig
block = SwiGLU(SwiGLUConfig(dim=8, hidden_dim=16, bias=False, seed=0))
x = np.random.default_rng(0).normal(size=(2, 5, 8)) # (batch, tokens, dim)
y = block.forward(x) # (2, 5, 8)
dx = block.backward(x, np.ones_like(y)) # gradient for x; block.grads holds the weight gradients
block.step(lr=0.01)Read the implementation (104 lines)
"""SwiGLU: gated feed-forward block, y = (SiLU(x W_gate) * (x W_value)) W_out.
NumPy only, with manual backpropagation. `forward` runs the block, `backward` returns the gradient with respect to
the input and stores the gradient of every parameter, `step` applies plain gradient descent.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import SwiGLUConfig
except ImportError: # run from the template's own folder
from config import SwiGLUConfig
def _sigmoid(x: np.ndarray) -> np.ndarray:
"""Logistic function 1 / (1 + exp(-x)), written so that large |x| cannot overflow."""
return np.exp(-np.logaddexp(0.0, -x))
def _silu(x: np.ndarray) -> np.ndarray:
"""SiLU / Swish: x * sigmoid(x)."""
return x * _sigmoid(x)
def _silu_grad(x: np.ndarray) -> np.ndarray:
"""Derivative of SiLU: s + x * s * (1 - s) with s = sigmoid(x)."""
s = _sigmoid(x)
return s + x * s * (1.0 - s)
class SwiGLU:
"""Gated feed-forward block. Parameters live in `self.params`, their gradients in `self.grads`.
params: "w_gate" (dim, hidden_dim), "w_value" (dim, hidden_dim), "w_out" (hidden_dim, dim), and with bias
"b_gate" (hidden_dim,), "b_value" (hidden_dim,), "b_out" (dim,).
"""
def __init__(self, config: SwiGLUConfig | None = None) -> None:
self.config = config or SwiGLUConfig()
c = self.config
rng = np.random.default_rng(c.seed)
lim_in, lim_hidden = 1.0 / math.sqrt(c.dim), 1.0 / math.sqrt(c.hidden_dim)
self.params = {
"w_gate": rng.uniform(-lim_in, lim_in, size=(c.dim, c.hidden_dim)),
"w_value": rng.uniform(-lim_in, lim_in, size=(c.dim, c.hidden_dim)),
"w_out": rng.uniform(-lim_hidden, lim_hidden, size=(c.hidden_dim, c.dim)),
}
if c.bias:
self.params.update(b_gate=np.zeros(c.hidden_dim), b_value=np.zeros(c.hidden_dim), b_out=np.zeros(c.dim))
self.grads = {name: np.zeros_like(value) for name, value in self.params.items()}
def _branches(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Pre-activation of the gate branch and the value branch. x: (..., dim). Both: (..., hidden_dim)."""
if x.shape[-1] != self.config.dim:
raise ValueError(f"last axis must be {self.config.dim}, got input shape {x.shape}")
gate, value = x @ self.params["w_gate"], x @ self.params["w_value"]
if self.config.bias:
gate, value = gate + self.params["b_gate"], value + self.params["b_value"]
return gate, value
def forward(self, x: np.ndarray) -> np.ndarray:
"""x: (..., dim). Returns (..., dim): (SiLU(x W_gate) * (x W_value)) W_out."""
x = np.asarray(x, dtype=float)
gate, value = self._branches(x)
y = (_silu(gate) * value) @ self.params["w_out"]
return y + self.params["b_out"] if self.config.bias else y
def backward(self, x: np.ndarray, grad_output: np.ndarray) -> np.ndarray:
"""Backpropagate through the block.
x: (..., dim), the input given to `forward`. grad_output: (..., dim), d loss / d output.
Returns d loss / d x, shape (..., dim), and fills `self.grads` with d loss / d parameter for every
entry of `self.params` (summed over all leading axes).
"""
x = np.asarray(x, dtype=float)
g_out = np.asarray(grad_output, dtype=float)
gate, value = self._branches(x)
act = _silu(gate)
hidden = act * value
g_hidden = g_out @ self.params["w_out"].T
g_gate = g_hidden * value * _silu_grad(gate)
g_value = g_hidden * act
flat = lambda a: a.reshape(-1, a.shape[-1]) # noqa: E731 merge the leading axes into one
self.grads["w_out"] = flat(hidden).T @ flat(g_out)
self.grads["w_gate"] = flat(x).T @ flat(g_gate)
self.grads["w_value"] = flat(x).T @ flat(g_value)
if self.config.bias:
self.grads["b_out"] = flat(g_out).sum(axis=0)
self.grads["b_gate"] = flat(g_gate).sum(axis=0)
self.grads["b_value"] = flat(g_value).sum(axis=0)
return g_gate @ self.params["w_gate"].T + g_value @ self.params["w_value"].T
def step(self, lr: float) -> None:
"""One plain gradient-descent update of every parameter with the gradients of the last `backward`."""
for name in self.params:
self.params[name] = self.params[name] - lr * self.grads[name]
def num_parameters(self) -> int:
"""Total count of trainable numbers in the block."""
return int(sum(p.size for p in self.params.values()))
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-swiglu
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build SwiGLU(SwiGLUConfig(dim=8, hidden_dim=16)) and confirm num_parameters() returns 384 with the default bias of false. Run forward on a random batch, call backward with a gradient of ones, then check one entry of grads["w_gate"] against a finite difference. Finish with step(0.01).
Check on learning
- The gate branch and the value branch start as two random linear maps of the same input. What makes them take on different roles during training?
A way to think about it
Look at the two gradient formulas. Each branch is scaled by the other, and only one passes through a nonlinearity. Ask what each can represent that the other cannot.
- If you swapped a classic block for this block with
hidden_dimstill at , and quality improved, what could you conclude?A way to think about it
Count parameters in both. An improvement that comes with 50 percent more weights does not show the gating helped. Design the comparison that would.
- Suppose every gate value is close to zero early in training. What happens to the gradient reaching , and how does the block get out of that state?
A way to think about it
The value gradient is . Then look at the gate gradient, which depends on and on the activation's slope near zero.
- This block uses SiLU on the gate and GEGLU uses GELU. Would you expect a large difference between them? How would you test it?
A way to think about it
Plot both activations on the same axes. They are close everywhere. A fair test holds width, seed and optimiser fixed and compares over several seeds.