Sign in

GLU

Gated Linear Unit

A gate that splits its input into two halves and multiplies the first half by the sigmoid of the second.

Overview

A gated linear unit lets a network decide, feature by feature, how much of a signal to pass on. The input arrives with twice the width that will leave. The first half carries values. The second half carries gate scores, which a sigmoid turns into numbers between 0 and 1. Each value is multiplied by its gate. A gate near 1 passes the value through, a gate near 0 blocks it. The values themselves are never squashed, so a fully open gate gives the gradient a straight linear path.

A short history

Yann Dauphin, Angela Fan, Michael Auli and David Grangier introduced the gated linear unit in the 2016 paper 'Language Modeling with Gated Convolutional Networks'. They wanted the gating that makes LSTMs work, but inside a convolutional model that processes all positions in parallel. Because one half of the product stays linear, gradients pass without being squashed. The idea later became the basis of the gated feed-forward blocks used in large language models.

How it works

  1. Take an input whose length along the split axis is even, 2n2n.
  2. Split it into a value half aa and a gate half bb, each of length nn.
  3. Turn the gate half into gates between 0 and 1 with the sigmoid: σ(b)\sigma(b).
  4. Multiply element by element: the output is a⊙σ(b)a \odot \sigma(b), of length nn.
  5. In backward, the value half receives the gradient times the gate, and the gate half receives the gradient times a σ(b) (1−σ(b))a\,\sigma(b)\,(1 - \sigma(b)).

Watch out for

  • The output has half the width of the input. The layer before it must produce 2n2n features to get nn out, which doubles that layer's parameters.
  • The split axis must have an even length. The template raises a ValueError otherwise, and the wrong axis on a batched input silently pairs unrelated features if the length happens to be even.
  • When a gate saturates near 0, both the value and the gate itself receive almost no gradient, so a closed gate can stay closed.
  • The template is the gate only. In the original design the two halves come from a convolution or linear layer that you provide.

Use cases

When to use it

Gated convolutional language models, tabular networks and feature-selection layers, where the previous layer can produce twice the width and the network should learn what to let through.

In industry

Machine translation
Convolutional sequence to sequence translation models used gated linear units in every layer of the encoder and decoder.
Tabular prediction
TabNet uses gated linear unit blocks in its feature transformers when learning from rows of mixed numeric and categorical data.
Demand forecasting
The Temporal Fusion Transformer uses gated linear units inside its gated residual networks so the model can skip components a given series does not need.

Choosing it: what must hold

  • A layer whose output width you can double, because the unit splits its input into a value half and a gate half.
  • A reason to let the network switch features on and off per position or per example, such as inputs of mixed relevance.
  • A budget that can absorb the extra parameters of the doubled projection.

When to choose something else

IfUse instead
You are designing the feed-forward block of a transformerSwiGLU or GEGLU
You only need a simple nonlinearity and no gatingReLU or GELU
The sequence model needs memory across many steps, not just a per-position gateAn LSTM or a transformer

Math foundations

  1. The gate

    σ(b)=11+e−b\sigma(b) = \frac{1}{1 + e^{-b}}

    The logistic sigmoid maps any score to a number between 0 and 1. It is 0.5 at b=0b = 0, so an untrained gate passes half of each value.

  2. The unit

    GLU⁡([a,b])=a⊙σ(b)\operatorname{GLU}([a, b]) = a \odot \sigma(b)

    Each value is scaled by its own gate. Compare an LSTM gate, which does the same thing but squashes the value with tanh first.

  3. Gradient for the value half

    ∂L∂a=δ⊙σ(b)\frac{\partial \mathcal{L}}{\partial a} = \delta \odot \sigma(b)

    The upstream gradient δ\delta scaled by the gate. With an open gate it passes almost unchanged, which is the linear path that helps deep stacks train.

  4. Gradient for the gate half

    ∂L∂b=δ⊙a⊙σ(b) (1−σ(b))\frac{\partial \mathcal{L}}{\partial b} = \delta \odot a \odot \sigma(b)\,\big(1 - \sigma(b)\big)

    The sigmoid's slope is σ(1−σ)\sigma(1 - \sigma), largest at 0.25 when the gate is half open. The gate learns fastest when it is undecided and the value is large.

Symbols

aa
the value half of the input, length n
bb
the gate half of the input, length n
σ\sigma
the logistic sigmoid
⊙\odot
element by element multiplication
δ\delta
the gradient of the loss with respect to the output, grad_output
L\mathcal{L}
the loss being minimised

Worked by hand

Feed the two-element input [2,1][2, 1], so a=2a = 2 and b=1b = 1, with an upstream gradient of 1. Use σ(1)=0.7311\sigma(1) = 0.7311.

GLU⁡([2,1])=2×0.7311=1.4622\operatorname{GLU}([2, 1]) = 2 \times 0.7311 = 1.4622
∂y∂a=0.7311\frac{\partial y}{\partial a} = 0.7311
∂y∂b=2×0.7311×(1−0.7311)=0.3932\frac{\partial y}{\partial b} = 2 \times 0.7311 \times (1 - 0.7311) = 0.3932

The output is 1.4622. backward returns [0.7311,0.3932][0.7311, 0.3932]: the value half first, then the gate half, in the same layout as the 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 GLU
from config import GLUConfig

act = GLU(GLUConfig(axis=-1))
x = np.array([[2.0, -4.0, 0.0, 1.0986]])   # values [2, -4], gates [0, log 3]
y = act.forward(x)                          # [[1.0, -3.0]]: half the width
dx = act.backward(x, np.ones((1, 2)))       # gradient with respect to all four inputs
Read the implementation (49 lines)
"""GLU: gated linear unit, f([a, b]) = a * sigmoid(b), where a and b are the two halves of the input.

NumPy only. `forward` computes the gated output, `backward` the gradient with respect to the whole input.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import GLUConfig
except ImportError:  # run from the template's own folder
    from config import GLUConfig

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))


class GLU:
    """Splits the input in halves a, b along `axis` and returns a * sigmoid(b)."""

    def __init__(self, config: GLUConfig | None = None) -> None:
        self.config = config or GLUConfig()

    def _split(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Return the value half and the gate half of x. Raises ValueError when the axis length is odd."""
        if x.ndim == 0 or x.shape[self.config.axis] % 2 != 0:
            raise ValueError(f"the split axis must have an even length, got input shape {x.shape}")
        a, b = np.split(x, 2, axis=self.config.axis)
        return a, b

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (..., 2 * n, ...) with 2 * n on the split axis. Returns (..., n, ...)."""
        a, b = self._split(np.asarray(x, dtype=float))
        return a * _sigmoid(b)

    def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
        """Gradient with respect to the whole input.

        x: the input given to `forward`. grad_output: d loss / d output, the shape `forward` returns (ones when
        omitted). Returns d loss / d x, same shape as x: the value half gets g * sigmoid(b), the gate half gets
        g * a * sigmoid(b) * (1 - sigmoid(b)).
        """
        a, b = self._split(np.asarray(x, dtype=float))
        gate = _sigmoid(b)
        g = np.ones_like(a) if grad_output is None else np.asarray(grad_output, dtype=float)
        return np.concatenate([g * gate, g * a * gate * (1.0 - gate)], axis=self.config.axis)

    __call__ = forward
Repository
gitlab.com/designsbyduhart/solomon-templates/activation-glu
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Build GLU(GLUConfig(axis=-1)) and call forward on an array of shape (4, 6). Confirm the output shape is (4, 3). Then call backward and check it against a finite difference of forward for one value entry and one gate entry.

Check on learning

  1. The value half is not passed through any activation. Why might leaving it linear help gradients in a deep stack?
    A way to think about it

    Write the gradient for aa. With the gate open it is close to δ\delta itself. Compare with tanh, whose slope shrinks whenever the value is large.

  2. A gate sits at σ(b)=0.001\sigma(b) = 0.001. How much gradient reaches aa and bb, and what does that mean for a feature that was closed off by mistake?
    A way to think about it

    Plug 0.001 into both gradient formulas. Both carry the factor σ(b)\sigma(b). Think about what initial bias on the gate scores would make this less likely.

  3. Two designs produce nn gated features: a layer of width 2n2n followed by this unit, or two separate layers of width nn. Are they the same model?
    A way to think about it

    Count the weights and write out both. A single matrix of width 2n2n split in halves is exactly two matrices of width nn on the same input.

  4. What would change if the sigmoid were replaced by a hard 0 or 1 threshold?
    A way to think about it

    Think about the slope of a step function. Ask how the gate scores would ever receive a learning signal.