Transformer Feed-Forward Networks (FFN): Principles, Variants, and Practical Choices
This article explains the role of the feed-forward network (FFN) inside the Transformer, why it matters, and how its common variants differ. It walks through the standard FFN computation flow, surveys widely used activation functions (ReLU, GELU, GLU, GEGLU, Swish, and SwiGLU), explains why gated FFNs shrink the intermediate dimension, and outlines how to compare variants fairly. It closes with practical guidance for choosing an FFN design under different resource and inference constraints.
1. Where the FFN Sits in the Transformer and What It Does
A Transformer is usually built by stacking multiple similar modules, and each module typically contains an attention sub-layer and a feed-forward network sub-layer. Attention builds connections between different tokens, answering “which positions should the current token attend to.” The FFN, in contrast, applies a nonlinear transformation to the representation of each token itself, answering “how do we further process and reorganize this token’s features.”
A typical FFN can be written as:
[
\mathrm{FFN}(x)=W_2 \sigma(W_1x+b_1)+b_2
]
Here, (x) is the input vector, (W1) expands the hidden dimension from (d) to an intermediate dimension (d{ff}), the activation function (\sigma) provides nonlinearity, and (W_2) maps the features back to the model hidden dimension (d).
For each token in the sequence, the FFN usually processes it independently with the same parameters:
[
\mathrm{FFN}(x_i)
]
Here (x_i) denotes the hidden state of the (i)-th token. Note that “independent processing” does not mean tokens have no interaction at all, because the attention layer has already fused the context. The input the FFN receives already contains context, so it performs a position-wise deep transformation on the fused semantic representation.
2. Why the FFN Layer Matters
2.1 It Provides Essential Nonlinear Expressiveness
If a network consisted only of linear transformations, multiple linear layers could ultimately be collapsed into a single linear mapping, limiting the model’s ability to represent complex functions. The activation function makes inputs in different regions transform in different ways, allowing the network to learn more complex decision boundaries and feature combinations.
In a language model, the FFN can learn internal representations related to lexical, syntactic, semantic, and knowledge patterns. For example, some neurons may respond to specific semantic attributes, while others may activate when particular context patterns appear. Although you cannot simply equate a single neuron with a well-defined knowledge entry, the FFN does have the ability to select, reorganize, and map high-dimensional features.
2.2 It Carries a Large Share of the Parameters
A standard FFN contains an input projection matrix and an output projection matrix:
[
W1\in \mathbb{R}^{d{ff}\times d},\qquad
W2\in \mathbb{R}^{d\times d{ff}}
]
If the intermediate dimension is a few times the hidden dimension, the FFN parameter count is roughly:
[
2d d_{ff}
]
while the projection matrices in the attention module are usually on the order of (d^2). As a result, in many Transformer architectures the FFN carries a substantial proportion of the parameters within a single layer, commonly estimated at about two-thirds of the module’s parameters, though the exact ratio depends on the number of attention heads, whether biases are used, how the vocabulary mapping is done, and the FFN structure.
Functionally, the FFN is often understood as a “key-value memory invoked independently per token.” The first projection can be seen as mapping the input to a set of feature directions, the activation function filters and modulates those directions, and the second projection combines the activated features back into the output space. This view helps explain why the FFN is not just a simple compute layer but may also store and retrieve a large amount of pattern-based information.
3. The Standard FFN Computation Flow
Let the input hidden state be:
[
x\in \mathbb{R}^{d}
]
A standard FFN can be broken into three steps:
Up-projection
[
h=W1x+b_1
]
Expands the input from (d) dimensions to (d{ff}) dimensions, giving the model a wider feature space.Nonlinear activation
[
\tilde h=\sigma(h)
]
Applies the activation function independently to each dimension, giving the network nonlinear expressiveness.Down-projection
[
y=W_2\tilde h+b_2
]
Projects the intermediate representation back to the model hidden dimension so it can be added to the residual connection.
In an actual Transformer module, the FFN is usually combined with a normalization layer and a residual connection:
[
y=x+\mathrm{FFN}(\mathrm{Norm}(x))
]
This structure helps stabilize training in deep networks and eases gradient propagation difficulties.
4. Common Activation Functions and Their Characteristics
4.1 ReLU
ReLU is defined as:
[
\mathrm{ReLU}(x)=\max(0,x)
]
It is simple to compute and converges relatively fast. When the input is negative, the output is zero; when the input is positive, it stays linear.
ReLU’s drawback is also clear: if a neuron keeps receiving negative values, its output and gradient may stay at zero, causing the “dying neuron” problem. In addition, ReLU is not differentiable at zero, and while engineering implementations usually do not suffer serious issues from this, its shape is relatively abrupt.
ReLU was very common in early neural networks, but in large language models, using ReLU alone is often not the best choice.
4.2 GELU
GELU, the Gaussian Error Linear Unit, can be written as:
[
\mathrm{GELU}(x)=x\Phi(x)
]
where (\Phi(x)) is the cumulative distribution function of the standard normal distribution. Unlike ReLU, which truncates negative values directly to zero, GELU decides the proportion of information to retain in a smooth way based on the magnitude of the input.
Engineering practice often uses the following approximation:
[
\mathrm{GELU}(x)\approx
\frac{1}{2}x\left(1+\tanh\left[
\sqrt{\frac{2}{\pi}}
\left(x+0.044715x^3\right)
\right]\right)
]
GELU’s advantages are its smooth shape, continuous gradient changes, and the fact that it does not abruptly truncate inputs close to zero. It is therefore usually better suited than ReLU for language modeling tasks that require fine-grained feature modulation.
4.3 GLU: Introducing a Gating Mechanism
The core idea of GLU is to use one branch to generate candidate features and another branch to generate a gating signal, then multiply them element-wise:
[
\mathrm{GLU}(x)=A(x)\odot \sigma(B(x))
]
where (A(x)) is the candidate feature, (B(x)) is the gating branch, (\sigma) is usually the Sigmoid function, and (\odot) denotes element-wise multiplication.
The gating mechanism can be understood as a soft selector. When the gate value is close to 1, the corresponding feature is allowed through; when it is close to 0, the feature is suppressed. Compared with a single activation function, GLU lets the model dynamically decide, based on the input content, which features should be enhanced and which should be weakened.
4.4 GEGLU
GEGLU replaces the gating activation in GLU with GELU, in the typical form:
[
\mathrm{GEGLU}(x)=\mathrm{GELU}(A(x))\odot B(x)
]
The two branches can also be swapped depending on the specific implementation. The key point is not the arrangement of symbols but the combination of:
- GELU’s smooth nonlinearity;
- GLU’s dynamic gating;
- feature interaction between the two projection branches.
GEGLU usually has strong expressiveness, but because it requires an extra projection branch, its parameter count and computation are higher than those of an ordinary single-branch FFN.
4.5 Swish
Swish is a family of smooth, self-gated activation functions, commonly written as:
[
\mathrm{Swish}(x)=x\cdot \mathrm{Sigmoid}(\beta x)
]
where (\beta) can be a fixed value or a learnable parameter. When (\beta=1), Swish is also often called SiLU.
Compared with ReLU, Swish allows some negative values to pass smoothly and still maintains good gradient behavior for large inputs. It balances nonlinearity and continuity, and in deep networks it usually shows more stable optimization behavior.
4.6 SwiGLU
SwiGLU uses Swish as the gating branch, in the typical form:
[
\mathrm{SwiGLU}(x)=
\mathrm{Swish}(W_gx)\odot (W_vx)
]
Expanded further, it can be written as:
[
\mathrm{SwiGLU}(x)=
\left(W_gx\cdot \mathrm{Sigmoid}(W_gx)\right)
\odot (W_vx)
]
Then an output projection maps it back to the hidden dimension:
[
y=W_o\mathrm{SwiGLU}(x)
]
SwiGLU uses both a smooth activation function and a gating structure, enabling finer-grained dynamic adjustment across different features. In many experiments, gated FFNs tend to outperform simple ReLU or single-branch activations, making them a very important class of structure in current large language models.
5. Why Gated FFNs Need a Smaller Intermediate Dimension
An ordinary FFN usually has two main matrices, while gated structures like SwiGLU typically require three projection matrices:
- candidate feature projection;
- gating feature projection;
- output projection.
If the same intermediate dimension as an ordinary FFN were kept, the parameter count of the gated structure would increase noticeably. To allow a fair comparison across structures, engineering practice usually shrinks the intermediate dimension of the gated FFN appropriately.
The main parameter count of an ordinary FFN is approximately:
[
2dd_{ff}
]
The main parameter count of a gated FFN is approximately:
[
3dd’_{ff}
]
To make the two parameter counts close, you can set:
[
3dd’{ff}\approx 2dd{ff}
]
Therefore:
[
d’{ff}\approx \frac{2}{3}d{ff}
]
For example, when an ordinary FFN’s intermediate dimension is about 4 times the hidden dimension, the gated structure’s intermediate dimension can be adjusted to about (8/3) times the hidden dimension, then aligned to a suitable integer multiple based on hardware and matrix-compute efficiency. This alignment does not change the model’s principle; it improves parallel computation efficiency, memory access, and matrix-multiplication utilization.
6. How to Compare the Effects of Different Activation Functions
When comparing FFN variants, you should not look only at the activation function itself but also consider the following factors:
Whether the parameter count is the same
If a model uses more parameters, better results alone do not prove the activation function itself is superior.Whether the number of training tokens is the same
Different training data scales significantly affect loss and generalization.Whether the optimizer and learning-rate strategy are the same
Different activation functions may differ in sensitivity to initialization and optimization hyperparameters.Whether the intermediate dimension is reasonable
A gated structure that does not adjust its intermediate dimension may gain an unfair advantage from extra parameters.Whether the evaluation metrics are comprehensive
Language models often use validation perplexity, and can also be evaluated with downstream tasks, long-text modeling, inference stability, and training efficiency.
In experiments with good control of variables, the following trends are usually observed: ReLU is simple in structure but relatively limited in expressiveness; GELU and Swish perform well in smoothness and training stability; GEGLU and SwiGLU improve feature-selection ability through gating and often achieve better validation loss and generalization. However, this does not mean SwiGLU is absolutely superior on every task, at every scale, and on every hardware.
7. Practical Selection Guidance
7.1 Limited Resources and a Preference for Simplicity
If the model is small and the inference device has limited compute, ReLU or GELU remain safe choices. They are simple in structure, mature in implementation, and easy to debug and deploy.
7.2 Pursuing Better Overall Results
If the focus is language modeling quality and you can accept the extra matrix computation, a gated FFN is usually worth prioritizing. Both SwiGLU and GEGLU are common options; the choice should be validated against training stability, inference throughput, and memory usage.
7.3 Focus on Inference Efficiency
Gated structures increase the number of projection computations, so you cannot look only at single-token theoretical expressiveness; you also need to watch:
- the number of matrix multiplications;
- activation memory;
- throughput under varying batch sizes;
- low-precision compute compatibility;
- inference latency and energy consumption.
In real systems, a suitable intermediate dimension, weight layout, and operator fusion are often just as important as the activation function itself.
8. Summary
The FFN is an indispensable part of the Transformer. On one hand, it improves the model’s expressiveness through nonlinear activation; on the other hand, with its large parameter count it carries a great deal of feature transformation and pattern storage.
From ReLU to GELU, and then to the gated GEGLU and SwiGLU, the direction of FFN development reflects a clear trend: models no longer apply only a fixed nonlinear transformation to features but try to dynamically control information flow based on the input content. Gated structures therefore have stronger feature-selection ability, but they also bring extra parameters and computation cost.
In practice, SwiGLU is usually a competitive choice between quality and engineering usability, but the final decision should still be based on comparative experiments according to model scale, training budget, inference hardware, and the target task. Understanding the FFN’s computation structure, parameter composition, and the differences among its variants is an important foundation for analyzing and designing large-model architectures.
