6.8 — The feed-forward block (position-wise MLP)
Goal: Define the FFN sub-layer, FFN(x) = W₂ σ(W₁ x + b₁) + b₂, applied independently per position; understand the standard d_ff = 4d expansion; count its parameters (8 d²) and FLOPs; place it as the per-position counterpart of attention's cross-position mixing.
1. Why this session exists
The attention sub-layer of 6.4–6.7 does one thing: it lets each token gather a content-addressed mixture of values from across the sequence. That is cross-position mixing — a linear operation in the value space, weighted by attention.
That is not enough. A purely-linear cross-position operation cannot, by itself, build complex per-position representations: an attention output is a convex combination of values, which lives in the convex hull of the value rows. To make the model represent compositional structure — "this is a noun phrase head with these modifiers" — we need a per-position non-linear feature transformer sitting next to attention.
That role is played by the feed-forward network (FFN) sub-layer: a two-layer MLP applied independently at each position. It is the second of the two sub-layers in every Transformer block. The pair "attention + FFN" is the fundamental computational unit of the architecture, and FFN holds more parameters than attention in every standard Transformer — typically 2/3 of the parameters of a block.
This session defines the FFN, motivates the standard "expand-to-, contract back" shape, counts the parameters and FLOPs, and connects to the per-position role that makes it complementary to attention.[1, 4]
2. The FFN formula
Let be the hidden representation of a single token at one position. The standard Transformer FFN, as in AIAYN, is a two-layer MLP with a non-linearity in the middle:
with weight matrices
and biases . The non-linearity in AIAYN was ReLU; modern LLMs use GELU (GPT-3, BERT) or SwiGLU/GeGLU (LLaMA, Mistral) — these gated variants are deferred to [8.4] and slightly change the formula, but the shape of the block remains: expand to , apply non-linearity, contract back to .
2.1 "Per-position": what it means
Although we wrote for a single position, in practice we apply it to all positions of a sequence by batching. For an input tensor representing tokens, the FFN sub-layer computes
Crucially, the same are used at every position, and there is no mixing between positions. The FFN is a position-wise operation: it transforms each row of independently.
This is what makes the FFN structurally orthogonal to attention. Attention mixes across positions but cannot do per-token non-linear transformations; FFN does per-token non-linear transformations but cannot mix across positions. Together, in alternating sub-layers, they cover both axes of the computation.
3. Why ?
The standard choice in AIAYN, and in every Transformer since, is
The number 4 is empirical, not derived from a theorem. Three observations make it stable:
(a) Wider hidden layer = more capacity. The MLP's expressive power scales with (more units in the hidden layer = more learnable features). Increasing improves model quality monotonically, but at quadratic cost in parameters: .
(b) Compute parity with attention. With , the FFN block has parameters per layer. The attention sub-layer has . So the FFN holds about twice the parameter count of attention per block — a 2:1 ratio that the field has settled on. (For models with SwiGLU and three FFN matrices, the ratio is closer to 3:1; see 8.4.)
(c) Hardware-friendly shape. is a "nice" number for GEMM on GPU. Anything substantially larger costs proportionally more memory; anything smaller hurts quality. Some recent models (PaLM, GPT-NeoX) experimented with but always returned to roughly as the sweet spot.
When LLMs were scaled up, the field generally kept and increased both and the number of layers together. The Chinchilla scaling laws (7.12) ratify this as the compute-optimal choice.
4. Parameter count
For the standard FFN with :
The bias terms are an additive correction; in modern LLMs (e.g. LLaMA) they are often omitted, leaving . Compare with the attention sub-layer's (6.4 §3). One Transformer block therefore has
parameters (no biases, no norms). For LLaMA-7B (): params per block, times 32 layers . Add the embedding matrix and the output projection (tied with embedding), and you reach — the canonical "7B" headline number.
5. FLOPs and the per-position cost
For a sequence of length :
(Each matrix multiply contributes FLOPs counting multiply+add; the non-linearity is comparatively free.) Compare with attention's FLOPs per layer (6.4 §3.1).
The cross-over is at . For the FFN dominates; for , attention does. For LLaMA-7B (), this is — a longer context than the original training window of 2048. So at standard pretraining context lengths, FFN compute dominates. Long-context inference shifts the balance to attention; this is the structural reason "attention is expensive at long context" is the headline cost figure but "FFN is expensive at short context" is the unsung counterpart. We will revisit this when we count compute in 6.12 (Part 2).
6. The FFN as a "feature memory"
A useful way to read the FFN: each row of is a pattern detector on the input (the row is a vector in ; its inner product with scores a particular feature). The non-linearity then gates the response. Each column of is a feature contribution — when the corresponding hidden unit fires, the column is added (scaled) to the output.
Schematically:
The hidden units each define a "(detector, contribution)" pair: detect a feature in , contribute a vector to the output. This view has been formalised by Geva, Schuster, Berant & Levy (2021)[2], who showed that FFN weights in trained Transformers behave like an associative memory: rows act as keys, columns as values, and the FFN as a key-value lookup mediated by the non-linearity.
This is the same structural pattern as attention — a key-value lookup — except the keys and values are fixed weights (learned at training time) rather than computed from the input. Attention is a runtime lookup against the sequence; FFN is a parametric lookup against memorised features.
The two together — runtime cross-position retrieval (attention) and per-position parametric memory (FFN) — are why a Transformer can both "look at what's in the input" and "look at what it knows." Modern interpretability papers (Cap 11) often map model behaviour to these two complementary mechanisms.
7. Why per-position, not cross-position?
A natural question: why doesn't the FFN mix across positions too? It could, in principle — a "global" FFN would take as a flattened vector of dimension and apply a dense MLP to it.
It doesn't, for three reasons:
(a) Parameter explosion. A dense MLP from to has parameters — quadratic in sequence length. For : , infeasible.
(b) Position-coupling is attention's job. Cross-position mixing is what attention is for. Re-doing it in the FFN would be redundant and would re-introduce the parameter-count and translation-symmetry pathologies that attention was designed to avoid.
(c) Per-position structure is the right inductive bias. Once attention has mixed the relevant cross-position information into each position's representation, the FFN's job is to transform that representation, position-by-position. The two operations sit naturally on orthogonal axes of the computation.
The discipline is general: in a Transformer block, every operation is either per-position (FFN, layer norm, activation) or cross-position (attention). Mixing the two would over-couple the design.
8. What we keep going forward
The FFN sub-layer is one line of math:
Applied position-wise. parameters. Dominates compute at short context; underweighted at long context. Functions as a parametric key-value memory complementary to attention's runtime retrieval.
We now have every piece of one Transformer block. Part 2 stacks them: residual connections (6.9), pre-norm vs post-norm (6.10), the complete block + the Attention Is All You Need read (6.11), compute counting (6.12), long-context variants (6.13), KV cache (6.14), hand-written numpy attention (6.15), and the nanoGPT walkthrough (6.16).
(a) Confirm the parameter count by counting the entries of for .
(b) Compute the FFN FLOPs for one forward pass of LLaMA-7B (): . Compare with the attention FLOPs . Which dominates at this ? At what would attention dominate?
(c) Write the FFN forward pass for a small example: , biases zero, ReLU. Compute and .
(d) Argue why a "global" FFN that mixes across positions would be redundant with attention. What would happen to the Transformer's translation-equivariance/position-handling story?
(e) A SwiGLU FFN replaces the single matrix with two parallel matrices used as . Argue that this triples the "expand" parameter count relative to standard FFN. To keep the total parameter count constant in modern LLMs, what is typically done to ?
References
- [1]
Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762 — The Transformer paper. Scaled dot-product attention (6.2), multi-head attention (6.4), encoder–decoder cross-attention (6.3), sinusoidal positional encoding (Appendix 6.A), the FFN sub-layer (6.8), post-LN block diagram (6.10), full architecture read (6.11).
↩ - [2]
Geva, M., Schuster, R., Berant, J., & Levy, O. (2021). "Transformer feed-forward layers are key-value memories". EMNLP. arXiv:2012.14913 — FFN as parametric associative memory (6.8 §6).
↩ - [3]
Shazeer, N. (2020). "GLU variants improve Transformer". arXiv:2002.05202 — SwiGLU / GeGLU; modern FFN variant (6.8 Aside; full treatment in Cap 8.4).
↩ - [4]
Alammar, J. (2018). "The illustrated Transformer". jalammar.github.io — Canonical visual walkthrough (6.4, 6.8).
↩