Transformer FFN: every token runs its own tiny MLP
Grow through practice
No need to finish reading — test nowAttention is where tokens meet; the FFN is where each token goes back to its desk and runs a small MLP. Attention mixes information; the FFN transforms it.
The one-line formula
The FFN (feed-forward network) in a Transformer is not a convolution or a recurrent network. It is a two-layer MLP applied independently at every position:
FFN(x) = W2 · activation(W1 · x + b1) + b2
x: one token vector with dimensiond_model.W1:d_model → d_ff.W2:d_ff → d_model.activation: ReLU, GELU, SwiGLU, etc.
The original paper used d_model = 512 and d_ff = 2048: expand by 4x, then project back.
512 ──W1──> 2048 ──activation──> 2048 ──W2──> 512
Why “position-wise”
The same FFN weights are applied independently at every position:
token 1 → FFN → output 1
token 2 → FFN → output 2
token 3 → FFN → output 3
It does not mix information across tokens. How token 1 interacts with token 5 is attention's job; the FFN only reprocesses the representation of the current token.
A minimal PyTorch shape check:
import torch
import torch.nn as nn
d_model, d_ff = 8, 32
ffn = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.GELU(),
nn.Linear(d_ff, d_model),
)
x = torch.randn(2, 5, d_model) # batch=2, seq=5
y = ffn(x)
print(y.shape) # torch.Size([2, 5, 8])
Put the same vector at any position and the FFN output is identical. That is what position-wise means: same weights, applied per position, not a different network per position.
Where the FFN sits in the architecture
The FFN is not an outer stage and it is not between the encoder and decoder. It sits inside every Transformer block, immediately after attention:
Encoder block:
x
└─ Self-Attention → Add & Norm
└─ FFN → Add & Norm
└─ next layer
Decoder block:
x
└─ Masked Self-Attention → Add & Norm
└─ Cross-Attention (Q from decoder, K/V from encoder) → Add & Norm
└─ FFN → Add & Norm
└─ next layer
In the original Post-LN form:
x1 = LayerNorm(x + Attention(x))
x2 = LayerNorm(x1 + FFN(x1))
The more common Pre-LN form:
x1 = x + Attention(LayerNorm(x))
x2 = x1 + FFN(LayerNorm(x1))
In both, the FFN comes after attention; only the LayerNorm placement changes.
Three easy confusions
- There is not one FFN for the whole model.
Every block has its own FFN weights; they are not shared across layers.
- The FFN does not handle encoder-decoder interaction.
Decoder cross-attention reads the encoder; the FFN only transforms the current token representation.
- The final output head is not the FFN.
After all blocks, a final linear/vocabulary projection produces logits. That is the output head, not the FFN inside a block.
The standard Transformer is serial: attention → FFN. A few models compute them in parallel, but that is a variant, not the original architecture.
Why nonlinearity is required
Attention plus purely linear layers still collapses to a linear transformation. The activation inside the FFN is a key source of nonlinear expressiveness.
Early Transformers used ReLU:
ReLU(z) = max(0, z)
Later language models commonly use GELU, which is smoother:
GELU(z) ≈ 0.5z(1 + tanh(√(2/π)(z + 0.044715z³)))
Modern LLMs often use SwiGLU, a gated FFN with two branches multiplied element-wise:
FFN_SwiGLU(x) = W2 · (Swish(W1x) ⊙ W3x)
W1andW3expandd_modeltod_ff;⊙is element-wise multiplication;W2projects back tod_model.
LLaMA-style models use this gated form. Because W3 adds parameters, d_ff is often smaller than the plain 4x choice while keeping the total parameter count in a similar range.
Why 4x
4x is an engineering heuristic, not a law:
- Too narrow: the layer lacks capacity.
- Too wide: parameters and compute grow too fast.
- 4x was the original starting point; later models tune
d_fffor parameter budget, stability and hardware efficiency.
The FFN parameter count is roughly:
2 × d_model × d_ff
With d_model = 512 and d_ff = 2048, that is about 2.1M parameters per layer. Attention's Q/K/V/output projections are about 4 × d_model² ≈ 1M, so the FFN often dominates a layer's parameter count.
Division of labor with attention
| Module | What it does | Cross-token? |
|---|---|---|
| Self-attention | Find relationships; mix information | Yes |
| FFN | Nonlinear transformation per token | No |
A useful shorthand:
Attention decides “who to look at”; the FFN decides “what to think after looking”.
Without attention, tokens cannot communicate. Without the FFN, each token only gets a linear transformation, and depth buys much less expressiveness.
FFN and MoE
MoE (Mixture of Experts) is not a different attention mechanism; it mainly replaces the FFN:
Dense Transformer: every token → the same FFN
MoE Transformer: every token → router selects top-k expert FFNs
- Total parameters can be very large.
- Each token activates only a few experts, so compute does not grow proportionally.
- The cost is routing, load balancing, communication and training complexity.
So when you see “a huge MoE model”, separate total parameters from parameters activated per token.
Common misconceptions
- “The FFN is a fully connected layer across tokens.”
No. It is position-wise. Attention is what crosses token boundaries.
- “The FFN is just two linear layers; it cannot matter much.”
It is the main per-token nonlinear transformation and often holds most of a layer's parameters.
- “4x is mandatory.”
No. d_ff is a hyperparameter; modern models tune it with activation choice, parallelism and hardware.
- “FFN output goes straight into the next layer.”
Usually it passes through a residual connection and LayerNorm; Pre-LN and Post-LN differ by model.
Verification
- ✅ Formulas and shapes follow the standard Transformer from Vaswani et al. 2017.
- ✅ Parameter estimate:
2 × d_model × d_ff, ignoring biases. - ⚠️ The PyTorch example was not executed locally (no PyTorch in this environment); it illustrates position-wise behavior and shapes.
- ❓ Not covered: training stability, measured differences between activations, MoE routing details.
One sentence
Attention lets tokens see each other; the FFN lets each token become smarter on its own. Alternating them is the Transformer.
Series: Understanding Attention and Transformers from Scratch · Previous: Multi-head and positional encoding · Next: where Q/K/V come from Test yourself: Transformer ranked quiz
Comments 0
No comments yet — be the first!