Gated Attention: Replacing Residuals and ReLU with Learned Gates
Building gated transformer blocks from the ground up — why standard residual connections and ReLU activations leave performance on the table, identity map reordering (pre-norm), five gating variants from input gating to GRU-type gates, gated identity initialization, GLU and its variants (SwiGLU, GEGLU, ReGLU, Bilinear), the 2/3 parameter budget trick, and the unified view of gating as multiplicative control — all derived step by step with a 4-dimensional running example.
The previous three blogs derived methods for reducing the attention pattern — which tokens attend to which. The Sparse Factorization blog covered fixed factorized patterns at . The Sliding Window blog covered sliding windows plus global tokens at . The DeepSeek Sparse Attention blog covered learning the pattern itself at .
All three blogs lived on Axis 3 of our taxonomy: the attention pattern. They modified the mask in the attention formula. The attention mechanism itself — the projections, the softmax, the weighted sum — remained unchanged. And the wrapper around the attention block — the residual connection, the normalization, the feed-forward network — was untouched entirely.
This blog moves to Axis 5: the layer-level architecture. We keep the attention computation exactly as it is and instead modify two things that surround it:
- The residual connection — replacing the fixed skip connection with a learned gate that controls how much of the submodule output to let through
- The FFN activation — replacing the ReLU activation with a gated linear unit that multiplies two parallel linear transformations, one of which acts as a learned gate
The first modification comes from the Gated Transformer-XL (GTrXL) paper (Parisotto, Song, Rae et al., 2019), which showed that gating the residual connections stabilizes transformer training in reinforcement learning — an environment where standard transformers completely fail to learn. The second comes from Shazeer (2020), who showed that replacing ReLU with Gated Linear Unit variants (SwiGLU, GEGLU) in the FFN sublayer improves language model quality at matched parameter and compute budgets.
The common thread is multiplicative gating: instead of additive combination (residuals) or pointwise activation (ReLU), these methods use element-wise products where one factor is a sigmoid or similar function that learns to selectively pass or suppress information. This is the same principle that made LSTMs trainable and Highway Networks deep. We are applying it to the transformer block.
We will derive every gating variant from scratch, trace the forward pass with concrete numbers, and verify parameter counts numerically.
The Running Example
We use a single token’s hidden state as it flows through one transformer layer. Fix the model parameters from the series:
- , heads, , layers, fp16
For numerical derivations, we work with a tiny hidden state to make every computation tractable by hand:
This vector represents the hidden state of a single token entering a transformer sub-block (either the attention sub-block or the FFN sub-block). We will trace how different gating mechanisms transform it.
We also fix a submodule output — the result of the attention or FFN computation on :
So is the residual stream and is the submodule output. The question this entire blog asks is: how should we combine and to produce the updated hidden state?
1. The Standard Residual Connection
1.1 The formula
In a standard transformer, the residual connection combines and by simple addition:
This is the identity shortcut introduced by He et al. (2016a) for ResNets. The gradient flows through the addition unchanged — — which prevents vanishing gradients in deep networks.
1.2 Numerical example
Every dimension of is added with equal weight of 1. There is no mechanism for the network to say “dimension 2 of the submodule output is useful but dimension 3 is noise — keep the first, suppress the second.” The addition is unconditional.
1.3 Why this becomes a problem
For supervised learning on large, well-curated datasets, the standard residual connection works well. But in reinforcement learning, two problems emerge:
Training instability. RL gradients are inherently noisy — the reward signal is sparse, delayed, and highly variable across episodes. The submodule output can be large and poorly directed early in training. Adding it unconditionally to the residual stream can destabilize the hidden state, causing policy collapse or divergent losses.
No selective filtering. When a transformer is used as a memory for an RL agent, different layers contribute information of varying quality. Lower layers may have learned useful local features while upper layers are still producing random outputs. The standard residual forces the agent to accept all contributions equally.
Parisotto et al. (2019) found that the canonical Transformer-XL (TrXL), trained with V-MPO on the DMLab-30 multitask RL benchmark, achieved a mean human-normalized score of only — essentially random. The LSTM baseline achieved . The transformer completely failed to learn.
2. Identity Map Reordering (Pre-Norm)
2.1 The canonical transformer block
The original Transformer (Vaswani et al., 2017) applies layer normalization after the residual connection. For the attention sub-block, the computation is:
This is post-norm: normalize after the residual addition. The residual path from input to output passes through layer normalization operations, one at each layer. Each LayerNorm is a nonlinear function (it divides by the standard deviation), so the path from the first layer’s input to the last layer’s output is a composition of nonlinear transformations. There is no clean identity map.
2.2 The reordering
Identity map reordering, described by He et al. (2016b) for ResNets and adopted by Radford et al. (2019) and Baevski and Auli (2019) for transformers, moves the layer normalization to the input of each sub-block:
This is pre-norm: normalize before the submodule, not after. Now the residual connection is truly an identity map — no nonlinear transformations lie on the skip path. The gradient flows from layer back to layer 0 through pure additions.
2.3 Why this matters for stability
Consider the gradient of the loss with respect to the input at layer . In the pre-norm formulation, unrolling the residual connections gives:
Taking the derivative by the chain rule of calculus:
The here is the identity matrix — the matrix with ones on the diagonal and zeros everywhere else:
Its defining property: for any vector , . It is the matrix that does nothing — the identity function in matrix form. It appears here because the derivative of the addition with respect to is exactly — each dimension of the input passes through to the output with a derivative of 1, and no dimension affects any other dimension.
This term is the reason the gradient cannot vanish. Even if all the terms are small (which they are at initialization, when the submodules produce near-zero outputs), the gradient is at least — it passes through unchanged. In post-norm, the LayerNorm operations on the skip path multiply additional Jacobian factors (the matrix of all partial derivatives of a vector-valued function) that can shrink or rotate the gradient, breaking this clean pass-through.
2.4 The effect on initialization
The pre-norm layout has a second, more subtle benefit for RL. At initialization, the submodule outputs are close to zero (random weights produce near-zero outputs in expectation). So — the output of the transformer is approximately the input embedding. This means the agent starts with a near-Markovian policy: it acts based on the current observation, ignoring history. This is a good starting point for RL, because reactive behaviors (responding to what is on screen right now) need to be learned before memory-dependent behaviors (remembering what happened 100 steps ago).
2.5 Numerical verification: TrXL-I results
The paper calls the pre-norm Transformer-XL “TrXL-I” (for Identity map reordering). On DMLab-30:
| Model | Mean Human Norm. Score |
|---|---|
| TrXL (post-norm) | |
| TrXL-I (pre-norm) | |
| LSTM |
Pre-norm alone transforms the transformer from a complete failure (, essentially random) to superhuman performance (, above the human baseline of ). This is a improvement from a single architectural change that does not add a single parameter.
2.6 Interpretation
Identity map reordering is not a new idea — it was known in the ResNet literature (He et al., 2016b) and adopted by GPT-2 (Radford et al., 2019). But its effect in RL is dramatic. The reason is that RL’s noisy gradients amplify the problems of post-norm: the gradient signal is already weak and variable, and passing it through nonlinear LayerNorm operations on the skip path can destroy it entirely. Pre-norm removes this amplification.
But pre-norm is not enough. While TrXL-I vastly outperforms TrXL, it is still less stable than the LSTM across hyperparameter settings. The next step is to replace the residual connection itself with a learned gate.
3. Gating Layers
3.1 The general idea
A gating layer replaces the residual connection with a function that uses a learned, element-wise multiplicative mechanism to control the flow of information. The gate is typically a sigmoid function applied to a linear transformation of the inputs, producing values in for each dimension independently.
The key insight, borrowed from LSTMs (Hochreiter and Schmidhuber, 1997), is that multiplicative interactions give the network fine-grained, per-dimension control over information flow. A gate value of 0.9 in dimension means “let 90% of this signal through.” A gate value of 0.1 means “suppress this dimension.” The network learns these gate values from data.
3.2 The GTrXL block
The final Gated Transformer-XL (GTrXL) block combines identity map reordering with gating layers. For the attention sub-block:
For the FFN sub-block:
Two things changed compared to the standard block. First, the layer normalization is applied to the input (pre-norm). Second, the residual addition is replaced by the gating function .
Note the ReLU activation applied to the submodule output before gating. This is because the identity map reordering creates a path where two consecutive linear layers (the submodule output projection and the gating layer’s linear transformation) could collapse into a single linear layer. The ReLU breaks this degeneracy.
3.3 Five gating variants
The paper ablates five different gating functions, each with increasing expressivity. We derive each one from scratch, trace the computation with our running example ( is the residual stream, is the submodule output), and count parameters.
For the numerical examples, we need a weight matrix. Fix a small gating weight matrix for :
and a bias vector (this large positive bias is the “gated identity initialization” — we will explain why in Section 4).
3.4 Variant 1: Input Gating
Definition
The input gate applies a sigmoid modulation to the residual stream , then adds the submodule output :
where is the logistic sigmoid function (derived in the math prerequisites for RL) and is the Hadamard product (element-wise multiplication). Given two vectors , the Hadamard product is:
Each dimension is multiplied independently — there is no interaction between dimensions. This is fundamentally different from the dot product , which collapses dimensions into a single scalar. The Hadamard product preserves dimensionality: the input is two -vectors, the output is one -vector. It is the operation that makes per-dimension gating possible — each gate value in scales its own dimension independently.
This variant is similar to the short-cut-only gating of He et al. (2016b).
The gate decides, for each dimension, how much of the residual stream to keep. When the gate is 1 (fully open), passes through unchanged and is added — recovering the standard residual. When the gate is 0 (fully closed), is zeroed out and only remains.
Numerical example
First, compute :
Note: the input gate variant in the paper has no bias term. But we include the computation for the sigmoid. Apply element-wise (using ):
Now apply the Hadamard product with and add :
Compare to the standard residual output of . The gate has scaled down the residual stream contribution — dimension 3, for example, kept only 44.3% of instead of the full value, while dimension 1 kept 56.5%.
Parameters
Input gating adds one weight matrix per gate. Each transformer layer has two gates (one for MHA, one for MLP):
Across layers:
3.5 Variant 2: Output Gating
Definition
The output gate applies a sigmoid modulation to the submodule output instead of the residual stream:
The gate controls how much of the submodule’s contribution to let through. When the gate is 0, — the submodule is completely ignored and the residual stream passes through unchanged. When the gate is 1, — the standard residual connection is recovered.
The minus sign on the bias is a convention: with , the sigmoid input is shifted negative, biasing the gate toward 0 (closed). This implements a conservative initialization where new layers start by doing nothing.
Numerical example
Compute :
Apply :
The gate values are all well below 0.5 — the positive bias pushes the gate toward closed. Now compute the output:
The output is much closer to than the standard residual . The gate is letting through only 22–35% of each dimension of . This is the conservative initialization at work: early in training, the layer barely modifies the residual stream.
Parameters
Same as input gating: one weight matrix plus one bias vector per gate. The bias is negligible:
3.6 Variant 3: Highway
Definition
The Highway connection (Srivastava et al., 2015) modulates both streams with a single gate. When the gate opens for , it closes for , and vice versa:
Let . Then:
This is a convex combination. In general, a convex combination of two values and with weight is:
The defining property: the weights are non-negative and sum to 1 (). This guarantees that the result always lies “between” and — for scalars, literally on the line segment from to ; for vectors, in the convex hull of the two endpoints. No matter what is, the output cannot exceed both and in any dimension, nor fall below both. It is a constrained interpolation.
Here, the weight is determined per-dimension by the gate. When , dimension of the output is (skip the submodule entirely). When , it is (use only the submodule). When , it is the midpoint .
This is exactly the gating mechanism of Highway Networks, which were the first architectures to successfully train networks with hundreds of layers — predating ResNets.
Numerical example
Compute :
The positive bias pushes toward 1, so the gate favors keeping the residual stream .
Numerical check: convex combination
For dimension 1: , so the output should satisfy .
This verifies the convex combination property: the output for each dimension lies between and (or at one of them).
The constraint
The Highway gate imposes a hard constraint: the total weight on and must sum to 1 in each dimension. If the gate lets more of through, it must proportionally reduce . This is more structured than the input or output gates, which can independently scale each stream. Whether this constraint helps or hurts depends on the task.
Parameters
Same as output gating: per gate.
3.7 Variant 4: Sigmoid-Tanh (SigTanh)
Definition
The sigmoid-tanh gate (Van den Oord et al., 2016) is similar to the output gate but adds a tanh activation on a separate linear projection of :
Note that both the sigmoid and the tanh operate on , not . The sigmoid controls how much to add, while is a re-projected and bounded version of . This is the gating mechanism used in WaveNet and PixelCNN.
Why tanh?
The function squashes its input to , which serves two purposes. First, it bounds the magnitude of the update — unlike the output gate where can be arbitrarily large. Second, the separate projection allows the gated update to be in a different subspace than the raw submodule output .
Parameters
This variant has two weight matrices per gate ( and ), plus bias vectors:
Double the parameters of the simpler variants.
3.8 Variant 5: GRU-Type Gating
Definition
The most expressive variant adapts the Gated Recurrent Unit (GRU) (Chung et al., 2014) as a gating function. The GRU is a recurrent architecture that simplifies the LSTM by using two gates instead of three. Here it is applied as a depth-wise (layer-to-layer) gate rather than a time-wise (step-to-step) gate:
Let us trace what each component does:
- is the reset gate: it controls how much of the residual stream is visible when computing the candidate update . When , the candidate is computed from alone, ignoring . When , the full is available.
- is the update gate: it controls the interpolation between and the candidate . This is the same convex combination as the Highway gate, but the “new value” is a more complex function of both and .
- is the candidate update: a tanh-bounded combination of and the reset-gated .
The final output is a convex combination of the old state and the candidate , weighted by .
Why this is the most expressive variant
The GRU gate has three matrix-vector products involving (, , ) and three involving (, , ), for a total of six matrices per gate. It can represent all of the simpler variants as special cases:
- Setting and making recovers the Highway gate (with as the Highway’s gate)
- Setting to a fixed small value recovers something close to the output gate
- The tanh on bounds the update, like the SigTanh variant
Parameters per gate
Per layer (two gates):
Across 12 layers:
Parameter count comparison
| Gating variant | Matrices per gate | Params per layer | Total (12 layers) |
|---|---|---|---|
| Input | 1 | 524K | 6.3M |
| Output | 1 | 525K | 6.3M |
| Highway | 1 | 525K | 6.3M |
| SigTanh | 2 | 1.05M | 12.6M |
| GRU | 6 | 3.15M | 37.7M |
For a baseline TrXL with approximately 28.6M parameters (12 layers, , 8 heads, ), the GRU gating adds 37.7M parameters — more than the base model. The paper addresses this by testing a “Thin GTrXL” variant with halved embedding dimension, which we discuss in Section 5.
4. Gated Identity Initialization
4.1 The motivation
We have argued that pre-norm (identity map reordering) helps because the initial transformer acts like an identity function — the randomly initialized submodules contribute near-zero outputs, so . But the gating variants introduce new parameters (, ) that, if randomly initialized, will produce gate values near . This means the gate is “half open” from the start, which partially disrupts the identity property.
Gated identity initialization explicitly sets the bias to a positive value so that the gate starts near the identity function. The specific value depends on the gating variant.
4.2 How it works for each variant
Output gate: . Setting makes at initialization (since for random ). So . The gate starts closed: the submodule output is suppressed.
Highway gate: where . Setting makes . So . Same effect: identity.
GRU gate: . Setting in makes . So . Identity again.
4.3 Numerical verification
For the output gate with (the value used in the paper for GRU gating), at initialization where :
So each dimension of is scaled by approximately 0.119 — the submodule’s contribution is reduced to about 12% of its value. For :
About 27% passes through. The paper uses for GRU gating and for other variants.
4.4 The effect on learning speed
The paper ablates the gated identity initialization on the Memory Maze task using the GRU-gated GTrXL. With , the model reaches human-level performance ( reward) with 10 out of 10 hyperparameter settings by 4B environment steps. Without the bias (), only 2 out of 10 settings reach human level, and the rest plateau below 4 reward.
The mechanism is clear: without the identity bias, the randomly initialized gates produce gate values near 0.5 from the start. This means the untrained submodule outputs immediately corrupt the residual stream with noise. With the bias, the gates start nearly closed, so the network begins as an approximately Markovian policy and gradually opens the gates as the submodules learn useful transformations.
5. The Full GTrXL Results
5.1 DMLab-30 performance
The paper evaluates all gating variants on the DMLab-30 multitask RL suite. All transformer variants use 12 layers, , 8 heads, , and memory size 512:
| Model | Mean Human Norm. | 100-capped |
|---|---|---|
| LSTM (3-layer) | ||
| TrXL (post-norm) | ||
| TrXL-I (pre-norm) | ||
| GTrXL (Input) | ||
| GTrXL (Output) | ||
| GTrXL (Highway) | ||
| GTrXL (SigTanh) | ||
| GTrXL (GRU) | ||
| MERLIN@100B | 115.2 | 89.4 |
Several observations:
GRU gating is the clear winner. It achieves mean human-normalized score, beating the LSTM () by 18 points and exceeding even MERLIN (), an external memory architecture that was trained for more environment steps (100B vs 10B).
Input gating fails. At , it performs worse than TrXL-I without any gating (). This is because input gating modulates the residual stream before adding the submodule output, which disrupts the identity path. The gate suppresses parts of that may be important, and the raw is added without any filtering.
Output gating and Highway have opposite stability profiles. Output gating is strong () with low variance (). Highway gating has a comparable best case but much higher variance (), indicating sensitivity to hyperparameters.
Standard error matters. The GRU variant’s standard error of is the smallest of all models. This means it is not just the highest-performing but also the most robust across different hyperparameter settings and random seeds.
5.2 Parameter-controlled comparison
The GRU gating adds substantial parameters (M total vs M for TrXL). To verify that the improvement is not simply from added capacity, the paper tests a “Thin GTrXL (GRU)” with halved embedding dimension (, 4 heads), giving M total parameters — fewer than the baseline TrXL.
| Model | Params | Mean Human Norm. |
|---|---|---|
| TrXL | 28.6M | |
| TrXL-I | 28.6M | |
| Thin GTrXL (GRU) | 22.4M | |
| GTrXL (Output) | 34.9M | |
| GTrXL (GRU) | 66.4M |
The Thin GTrXL achieves with 22.4M parameters — fewer parameters than any other transformer variant, yet it matches the best-performing GTrXL (Output) at and beats every non-GRU gating variant. This confirms that the GRU’s advantage comes from the gating mechanism itself, not from parameter count.
5.3 Divergence rates
The paper tracks how often each model’s training loss diverges to infinity across 25 random hyperparameter settings on the Memory Maze task:
| Model | % Diverged |
|---|---|
| LSTM | 0% |
| TrXL | 0% |
| TrXL-I | 16% |
| GTrXL (GRU) | 0% |
| GTrXL (Output) | 12% |
The GRU-gated GTrXL never diverges — matching the LSTM’s stability — while TrXL-I diverges 16% of the time. The GRU gate provides both higher performance and greater stability.
5.4 Scaling with memory horizon
On the Numpad task, which requires memorizing sequences of increasing length, the LSTM’s performance degrades sharply as the pad size increases from 2 to 4. The GTrXL (GRU) maintains strong performance at all sizes and “almost instantly solves the environment” at pad sizes 2 and 3, demonstrating superior memory capacity.
6. GLU: Gating the Feed-Forward Network
We now turn to the second paper: “GLU Variants Improve Transformer” (Shazeer, 2020). Where GTrXL applied gating to the residual connections (the wrapper around submodules), GLU applies gating inside the FFN submodule itself — replacing the activation function.
6.1 The standard FFN
The standard Transformer FFN (Vaswani et al., 2017) for a single token’s hidden state is:
where , , and is the FFN hidden dimension. Typically .
The activation is ReLU: . It passes positive values unchanged and zeros out negative values. There is no learned control over which dimensions are active — the decision is made purely by the sign of the pre-activation.
Following T5 (Raffel et al., 2019), we use a bias-free version:
6.2 Parameters in the standard FFN
Two weight matrices:
With and :
6.3 Other activations: GELU and Swish
Before introducing gating, two other activation functions were proposed as ReLU replacements:
GELU (Gaussian Error Linear Unit, Hendrycks and Gimpel, 2016):
where is the standard Gaussian CDF. This can be seen as a smooth approximation to ReLU that weights each value by its probability of being positive under a Gaussian distribution.
Swish (Ramachandran et al., 2017):
where is the logistic sigmoid and is a parameter (typically ). Swish is similar to GELU and was found by neural architecture search.
Both replace the hard zero of ReLU with a smooth, non-monotonic function that allows small negative values through. Importantly, both have the form — they multiply the input by a function of the input. This is already a form of self-gating, but with a single linear transformation.
7. The Gated Linear Unit (GLU)
7.1 Definition
The Gated Linear Unit (Dauphin et al., 2016) is a neural network layer defined as:
where are two separate weight matrices, is the sigmoid function, and is the Hadamard product.
The two linear projections and compute two different views of the input. The first, , produces gate values in — it decides, for each dimension of the hidden representation, how much information to let through. The second, , produces the actual values to be gated.
7.2 Why this is fundamentally different from ReLU
In the ReLU FFN, a single linear projection is computed, and ReLU decides which dimensions to keep based solely on sign. Positive values pass, negative values are zeroed. The gating decision is:
This is a hard, binary decision — the gate value is always 0 or 1, with no intermediate scaling. While the gate does depend on the input through , it cannot modulate magnitude: the network has no way to say “this dimension is positive but I want to scale it down to 30%.”
In the GLU, the gating decision is a separate learned function , which can produce any value in :
This is a soft, continuous, learned decision. The gate is computed from a different projection than the value — so the network can learn that certain input patterns should produce high gate values even when the value projection is small, or vice versa.
7.3 Numerical example
Use and for tractability. Fix:
Compute (the gate projection):
Apply sigmoid: .
Compute (the value projection):
Apply the Hadamard product:
The gate has scaled each value dimension independently. Dimension 1 had a high gate value (0.650) so the negative value mostly passes through. Dimension 2 had a lower gate (0.387), reducing the positive value to . Dimension 3 was nearly zeroed: even though the gate was fairly open (0.641), the value itself was tiny ().
7.4 The Bilinear variant
Dauphin et al. (2016) also suggest dropping the sigmoid entirely, creating the Bilinear layer:
No activation at all — just the element-wise product of two linear projections. Despite the absence of a nonlinearity, the Hadamard product itself is a nonlinear operation (it is bilinear in the two projections, but nonlinear in ). This is an important observation: the gating structure provides nonlinearity even without sigmoid or tanh.
8. GLU Variants in the Transformer FFN
8.1 The FFN with GLU
Replacing ReLU with GLU in the FFN gives:
There are now three weight matrices instead of two: (gate projection), (value projection), and (output projection).
8.2 The full family of variants
Shazeer (2020) systematically replaces the sigmoid in GLU with other activation functions:
Each variant uses a different activation on the gate branch while keeping the value branch linear. The general pattern is:
8.3 The parameter budget trick
This is the part that makes GLU variants practical. The standard FFN has two matrices totaling parameters. The GLU variants have three matrices totaling parameters — a 50% increase.
To match the parameter count and computation of the original FFN, Shazeer reduces the hidden dimension from to :
Setting these equal:
8.4 Numerical check
With (T5-base) and :
Standard FFN: parameters per layer.
GLU variant with : parameters per layer.
The parameter counts match exactly. The GLU variant has three smaller matrices instead of two larger ones, but the total parameter budget and FLOP count are the same.
8.5 Numerical check with our running model
For the running model (, ):
Standard FFN: per layer.
GLU variant with : per layer.
The small difference () comes from rounding to . In practice, is rounded to a multiple of 64 or 128 for hardware efficiency.
9. Experimental Results: GLU Variants
9.1 Pre-training perplexity
Shazeer evaluates all FFN variants using the T5 setup: encoder-decoder transformer, , 12 layers, 12 heads, trained on C4 with the span-filling denoising objective. All GLU variants use to match the baseline’s .
| FFN Variant | Log-perplexity (65K steps) | Log-perplexity (524K steps) |
|---|---|---|
| FFN (baseline) | 1.997 | 1.677 |
| FFN | 1.983 | 1.679 |
| FFN | 1.994 | 1.683 |
| FFN | 1.982 | 1.663 |
| FFN | 1.960 | 1.648 |
| FFN | 1.942 | 1.633 |
| FFN | 1.944 | 1.636 |
| FFN | 1.953 | 1.645 |
The two best variants — GEGLU and SwiGLU — achieve log-perplexities of 1.633 and 1.636 respectively, compared to the ReLU baseline’s 1.677. This is a significant improvement: a reduction of 0.044 in log-perplexity at matched parameters and compute.
9.2 The ranking
At convergence (524K steps), the ranking from best to worst is:
Two patterns emerge:
Gating helps. Every GLU variant (bottom five) outperforms every non-gated variant (top three). The worst GLU variant (GLU at 1.663) beats the best non-gated variant (ReLU at 1.677).
GELU and Swish gates beat sigmoid and ReLU gates. Among the GLU variants, GEGLU and SwiGLU are the best. The sigmoid-gated GLU (1.663) is worse than the GELU-gated GEGLU (1.633). This is somewhat surprising — the sigmoid produces values in , which is the “correct” range for a gate, while GELU and Swish can produce values outside this range. Apparently, the smooth, non-monotonic shape of GELU and Swish is more important than having outputs bounded to .
9.3 Fine-tuning results
On GLUE:
| FFN Variant | Score Average |
|---|---|
| FFN | 83.80 |
| FFN | 84.20 |
| FFN | 84.36 |
| FFN | 84.67 |
| FFN | 83.79 |
On SuperGLUE:
| FFN Variant | Score Average |
|---|---|
| FFN | 72.76 |
| FFN | 73.96 |
| FFN | 73.66 |
| FFN | 73.81 |
| FFN | 73.66 |
On SQuAD v1.1:
| FFN Variant | EM | F1 |
|---|---|---|
| FFN | 83.18 | 90.87 |
| FFN | 83.82 | 91.06 |
| FFN | 83.55 | 91.12 |
| FFN | 83.53 | 91.18 |
The results are noisy across tasks, but the overall pattern is consistent: GLU variants match or slightly exceed the ReLU baseline on every downstream benchmark, while also achieving better pre-training perplexity. As Shazeer concludes: “These architectures are simple to implement, and have no apparent computational drawbacks.”
9.4 Why SwiGLU became standard
Since this paper, SwiGLU has been adopted by LLaMA (Touvron et al., 2023), PaLM (Chowdhery et al., 2022), and most subsequent large language models. The parameter trick makes it a drop-in replacement for the standard FFN, and the consistent improvements in perplexity translate to downstream quality gains at scale. It is now the default FFN activation in modern transformers.
10. The Unified View: Gating as Multiplicative Control
10.1 The common structure
Every gating mechanism we have derived in this blog shares a single structural motif: an element-wise product where one factor acts as a learned controller.
The controller produces values that modulate the content, dimension by dimension. The differences lie in what the controller sees, what activation it uses, and what the content is:
| Mechanism | Controller | Activation | Content |
|---|---|---|---|
| GTrXL Output gate | (submodule output) | ||
| GTrXL Highway gate | and (convex) | ||
| GTrXL GRU gate | and (convex) | ||
| GLU | |||
| GEGLU | GELU | ||
| SwiGLU | Swish | ||
| ReGLU | ReLU | ||
| LSTM forget gate | (cell state) |
10.2 Where each mechanism acts
The GTrXL gates act on the residual connections — the wiring between submodules. They control how submodule outputs enter the residual stream.
The GLU gates act inside the FFN — the activation function within the submodule. They control which dimensions of the intermediate representation pass through.
These are orthogonal modifications. A modern transformer can use both: SwiGLU in the FFN (Axis 5, inside the submodule) and potentially gated residuals (Axis 5, around the submodule). They modify different parts of the same axis.
10.3 The LSTM connection
This is not coincidence. The LSTM (Hochreiter and Schmidhuber, 1997) was the first architecture to use learned multiplicative gates for controlling information flow. It used three gates (input, forget, output) to regulate a persistent cell state. The GRU (Chung et al., 2014) simplified this to two gates (reset, update).
Highway Networks (Srivastava et al., 2015) took the LSTM’s gating mechanism and applied it to feedforward depth — the same idea as GTrXL’s Highway variant. GLU (Dauphin et al., 2016) applied gating to convolutional language models. GTrXL and SwiGLU bring these ideas into the transformer, applied to different components.
The progression is: gates for temporal memory (LSTM, 1997) gates for network depth (Highway, 2015) gates for convolutional channels (GLU, 2016) gates for transformer residuals (GTrXL, 2019) gates for transformer FFN (SwiGLU, 2020).
10.4 Placing gating in the taxonomy
In the taxonomy from the earlier blog, Axis 5 covers “layer-level architecture” — everything about how the attention block is wrapped: normalization, residual connections, FFN design, and block ordering.
Both GTrXL and GLU variants are Axis 5 modifications. They do not change the attention pattern (Axis 3), the KV representation (Axis 2), or the number of heads (Axis 1). The attention computation itself — queries, keys, values, softmax, weighted sum — is completely unchanged. What changes is the infrastructure surrounding it.
Summary
Gating replaces the fixed, unconditional operations in a transformer block — the additive residual connection and the ReLU activation — with learned, multiplicative control mechanisms. The GTrXL paper (Parisotto et al., 2019) showed that two changes to the Transformer-XL, identity map reordering (pre-norm) and GRU-type gating on residual connections, transform the architecture from a complete failure in RL ( human-normalized score) to state-of-the-art (), exceeding both LSTMs and external memory architectures while matching the LSTM’s stability. The GLU Variants paper (Shazeer, 2020) showed that replacing ReLU with gated linear units in the FFN — specifically SwiGLU or GEGLU — improves pre-training perplexity and downstream task quality at matched parameter and compute budgets, using the trick to equalize costs. Both papers apply the same principle: let the network learn, dimension by dimension, how much information to pass through — the same principle that made LSTMs trainable two decades earlier.
Previous: Mathematical Prerequisites for the Delta Rule
Next: Why Replace Attention? The Softmax Bottleneck and the Path to Linear Time
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.