Sign in

GeGLU

GELU-Gated Linear Unit (Gaussian Error Linear Unit gate)

A gated feed-forward block: one linear branch passes through GELU and multiplies a second linear branch, then a third map projects back.

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

  1. Take an input xx of width dd (the config's dim).
  2. Compute the gate pre-activation g=xWgg = x W_g and the value v=xWvv = x W_v, each of width hh (hidden_dim). Biases are added when bias is on.
  3. Apply GELU to the gate branch only.
  4. Multiply element by element: m=GELU⁡(g)⊙vm = \operatorname{GELU}(g) \odot v.
  5. Project back to width dd: y=m Woy = m\,W_o.
  6. In backward, send the gradient through WoW_o, split it between the two branches with the product rule, and store one gradient per parameter in grads.

Watch out for

  • The block has three weight matrices, not two. Keeping hidden_dim at 4d4d makes it 50 percent larger than the classic block, so use about 83d\tfrac{8}{3} d for a fair comparison.
  • The output is a product of two functions of xx, 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.
  • backward must be given the same xx that forward saw. It recomputes both branches from it and overwrites grads on 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

IfUse instead
You are following the design of recent large language modelsSwiGLU
You want the simplest block or must match a BERT or GPT-2 style checkpointGELU in a plain feed-forward block
You need a gate over features outside a transformer feed-forward blockGLU

Math foundations

  1. The classic block it replaces

    y=σact(xW1) W2y = \sigma_{\text{act}}(x W_1)\, W_2

    Widen with W1W_1, apply one activation, narrow with W2W_2. Each hidden unit depends on the input through one linear map only.

  2. The gated block

    y=(GELU⁡(xWg)⊙(xWv)) Woy = \big(\operatorname{GELU}(x W_g) \odot (x W_v)\big)\, W_o

    Two linear maps of the same input, one activated and one not, multiplied element by element and then projected. This is what forward computes.

  3. The gate activation

    GELU⁡(z)=z Φ(z)\operatorname{GELU}(z) = z\,\Phi(z)

    Each gate value is its input scaled by the standard normal CDF. The template uses the exact form with the error function.

  4. Gradients of the two branches

    ∂L∂g=δ⊙v⊙GELU⁡′(g),∂L∂v=δ⊙GELU⁡(g),δ=∂L∂y Wo⊤\frac{\partial \mathcal{L}}{\partial g} = \delta \odot v \odot \operatorname{GELU}'(g), \qquad \frac{\partial \mathcal{L}}{\partial v} = \delta \odot \operatorname{GELU}(g), \qquad \delta = \frac{\partial \mathcal{L}}{\partial y}\, W_o^{\top}

    The product rule. Each branch receives the upstream gradient δ\delta scaled by the other branch. If one branch is near zero, the other learns slowly.

  5. Matching the parameter count

    3 d h=2⋅d⋅4d  ⟹  h=83 d3\,d\,h = 2 \cdot d \cdot 4d \;\Longrightarrow\; h = \tfrac{8}{3}\,d

    The gated block has three d×hd \times h matrices. The classic block with hidden width 4d4d has 8d28d^{2} weights. Setting them equal gives the usual hidden width.

Symbols

xx
the input row vector, width d
Wg,WvW_g, W_v
gate and value weight matrices, each d by h; w_gate and w_value in params
WoW_o
output weight matrix, h by d; w_out in params
g,vg, v
gate pre-activation and value, each of width h
⊙\odot
element by element multiplication
δ\delta
the gradient of the loss with respect to the hidden product
L\mathcal{L}
the loss being minimised
d,hd, h
input width dim and hidden width hidden_dim
σact\sigma_{\text{act}}
the activation of the classic block, for example ReLU or GELU
Φ\Phi
standard normal cumulative distribution function

Worked by hand

Take the smallest block: d=h=1d = h = 1, no bias, with Wg=1W_g = 1, Wv=2W_v = 2, Wo=0.5W_o = 0.5 and input x=1x = 1. The normal table gives Φ(1)=0.8413\Phi(1) = 0.8413.

g=1×1=1,v=1×2=2g = 1 \times 1 = 1, \qquad v = 1 \times 2 = 2
GELU⁡(1)=1×0.8413=0.8413\operatorname{GELU}(1) = 1 \times 0.8413 = 0.8413
m=0.8413×2=1.6826m = 0.8413 \times 2 = 1.6826
y=1.6826×0.5=0.8413y = 1.6826 \times 0.5 = 0.8413

The output is 0.8413. Doubling xx 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

  1. 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.

  2. If you swapped a classic 4d4d block for this block with hidden_dim still at 4d4d, 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.

  3. Suppose every gate value is close to zero early in training. What happens to the gradient reaching WvW_v, and how does the block get out of that state?
    A way to think about it

    The value gradient is δ⊙GELU⁡(g)\delta \odot \operatorname{GELU}(g). Then look at the gate gradient, which depends on vv and on the activation's slope near zero.

  4. 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.