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
- Take an input whose length along the split axis is even, .
- Split it into a value half and a gate half , each of length .
- Turn the gate half into gates between 0 and 1 with the sigmoid: .
- Multiply element by element: the output is , of length .
- In
backward, the value half receives the gradient times the gate, and the gate half receives the gradient times .
Watch out for
- The output has half the width of the input. The layer before it must produce features to get out, which doubles that layer's parameters.
- The split axis must have an even length. The template raises a
ValueErrorotherwise, and the wrongaxison 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
| If | Use instead |
|---|---|
| You are designing the feed-forward block of a transformer | SwiGLU or GEGLU |
| You only need a simple nonlinearity and no gating | ReLU or GELU |
| The sequence model needs memory across many steps, not just a per-position gate | An LSTM or a transformer |
Math foundations
The gate
The logistic sigmoid maps any score to a number between 0 and 1. It is 0.5 at , so an untrained gate passes half of each value.
The unit
Each value is scaled by its own gate. Compare an LSTM gate, which does the same thing but squashes the value with tanh first.
Gradient for the value half
The upstream gradient scaled by the gate. With an open gate it passes almost unchanged, which is the linear path that helps deep stacks train.
Gradient for the gate half
The sigmoid's slope is , largest at 0.25 when the gate is half open. The gate learns fastest when it is undecided and the value is large.
Symbols
- the value half of the input, length n
- the gate half of the input, length n
- the logistic sigmoid
- element by element multiplication
- the gradient of the loss with respect to the output,
grad_output - the loss being minimised
Worked by hand
Feed the two-element input , so and , with an upstream gradient of 1. Use .
The output is 1.4622. backward returns : 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 inputsRead 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
- 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 . With the gate open it is close to itself. Compare with tanh, whose slope shrinks whenever the value is large.
- A gate sits at . How much gradient reaches and , 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 . Think about what initial bias on the gate scores would make this less likely.
- Two designs produce gated features: a layer of width followed by this unit, or two separate layers of width . Are they the same model?
A way to think about it
Count the weights and write out both. A single matrix of width split in halves is exactly two matrices of width on the same input.
- 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.