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 GELU. 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 tested a family of gated feed-forward layers for transformers in the 2020 note 'GLU Variants Improve Transformer'. Each variant replaces the usual single activation with a product of two linear branches, one passed through an activation. GEGLU uses GELU on the gating branch. It gave lower perplexity than the plain ReLU or GELU block at the same parameter count, and was adopted in T5 version 1.1 and in the attention blocks of latent diffusion image 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 GELU 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 where a gated block gives better quality than a plain GELU block at the same parameter count. GEGLU is the variant used in some diffusion and encoder models.
In industry
- Language models
- T5 version 1.1 and the models built on it use the GELU-gated feed-forward block in every encoder and decoder layer.
- Image generation
- The transformer blocks inside latent diffusion image generators, as implemented in common open source libraries, use a GEGLU feed-forward layer.
- Tabular and sequence modelling
- Teams building transformer encoders for structured records swap the plain feed-forward block for a gated one to gain accuracy at a fixed parameter budget.
Choosing it: what must hold
- A transformer style block with a feed-forward sublayer that you are free to redesign.
- A hidden width cut to about two thirds of the usual size, so that three weight matrices cost the same as the original two.
- If you load pretrained weights, a checkpoint that was trained with this exact block.
When to choose something else
| If | Use instead |
|---|---|
| You are following the design of recent large language models | SwiGLU |
| You want the simplest block or must match a BERT or GPT-2 style checkpoint | GELU in a plain feed-forward block |
| You need a gate over features outside a transformer feed-forward block | GLU |
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 the standard normal CDF. The template uses the exact form with the error function.
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
- standard normal cumulative distribution function
Worked by hand
Take the smallest block: , no bias, with , , and input . The normal table gives .
The output is 0.8413. 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 GEGLU
from config import GEGLUConfig
block = GEGLU(GEGLUConfig(dim=8, hidden_dim=16, bias=True, 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 (102 lines)
"""GEGLU: gated feed-forward block, y = (GELU(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 GEGLUConfig
except ImportError: # run from the template's own folder
from config import GEGLUConfig
_erf = np.vectorize(math.erf, otypes=[float])
def _gelu(x: np.ndarray) -> np.ndarray:
"""Exact GELU: x * Phi(x), with Phi the standard normal CDF."""
return 0.5 * x * (1.0 + _erf(x / math.sqrt(2.0)))
def _gelu_grad(x: np.ndarray) -> np.ndarray:
"""Derivative of GELU: Phi(x) + x * phi(x), with phi the standard normal density."""
cdf = 0.5 * (1.0 + _erf(x / math.sqrt(2.0)))
return cdf + x * np.exp(-0.5 * x**2) / math.sqrt(2.0 * math.pi)
class GEGLU:
"""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: GEGLUConfig | None = None) -> None:
self.config = config or GEGLUConfig()
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): (GELU(x W_gate) * (x W_value)) W_out."""
x = np.asarray(x, dtype=float)
gate, value = self._branches(x)
y = (_gelu(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 = _gelu(gate)
hidden = act * value
g_hidden = g_out @ self.params["w_out"].T
g_gate = g_hidden * value * _gelu_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-geglu
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build GEGLU(GEGLUConfig(dim=8, hidden_dim=16)) and confirm num_parameters() returns 424 with the default bias of true. 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 GELU on the gate and SwiGLU uses SiLU. 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.