Feed-Forward Layers as Memories
Key–value memories, gated variants and the search for where facts live.
Two-thirds of a transformer's weights sit in its feed-forward layers, and for years their role was described only as "processing". Reading each layer as a key–value memory changed that, and it launched a search for where facts live: methods that trace a fact to a layer and rewrite it with a rank-one update. The search also produced a cautionary result: finding where a fact is recalled does not tell you where editing it works.
What you’ll learn
- Rewrite a feed-forward layer as an unnormalized key–value memory, and interpret its keys by the inputs that trigger them and its values by the tokens they promote.
- Derive ROME's rank-one edit from a constrained least-squares problem, and MEMIT's update for many facts at once.
- Weigh the evidence on localization: causal tracing, knowledge neurons, the gap between localization and editing success, and ripple effects.
- Derive the hidden width that keeps gated FFNs (SwiGLU, GeGLU) at parameter parity, and describe activation sparsity.
A feed-forward layer is a key–value memory
Write the FFN's first matrix by rows and its second by columns: is row of and is column of . Then, ignoring biases,
Geva, Schuster, Berant and Levy (2021) tested the reading on a 16-layer language model trained on WikiText-103. For each key they collected the training prefixes that activated it most. Those prefixes shared human-recognizable patterns: shallow ones in the lower layers, such as ending in the same word, and semantic ones in the upper layers, such as a shared topic. Projecting a value vector onto the vocabulary gave a distribution that, in the upper layers, often agreed with the token that followed the key's top prefixes. A layer's output is a composition of many such memories, refined from layer to layer through the residual stream.
Geva, Caciularu, Wang and Goldberg (2022) followed the sub-updates through the output layer and found that they promote concepts interpretable in vocabulary space. Acting on that reading, they boosted a handful of value vectors to reduce the toxicity of GPT-2's output by almost 50%, and used the same view for an early-exit rule that saved 20% of computation on average.
import torch
import torch.nn.functional as F
# W1: (d_ff, d) keys as rows; W2: (d, d_ff) values as columns; W_U: (|V|, d) output layer
def ffn_as_memory(x, W1, b1, W2, b2):
m = F.gelu(W1 @ x + b1) # one coefficient per memory slot
return W2 @ m + b2, m # = sum_i m[i] * W2[:, i] + b2
def promoted_tokens(i, W2, W_U, k=10):
return torch.topk(W_U @ W2[:, i], k).indices # tokens value i pushes up mostProjecting a value through the output layer ignores everything that happens after this layer, so it is a first look, not a proof: the "logit lens" caveats of Reading the Residual Stream apply.
Tracing a fact to a layer
A factual association is a triple (subject, relation, object): (Eiffel Tower, is located in, Paris). Where does a model recall the object? Meng, Bau, Andonian and Belinkov (2022) used causal tracing: corrupt the subject's embeddings with noise, then restore the clean hidden state of one layer at one position and measure how much of the correct prediction comes back. In GPT-2 XL two sites stood out. MLP outputs in the middle layers at the last subject token mattered most (an "early site"), and attention at the last token of the prompt mattered later (a "late site"). The method itself, and its pitfalls, are the subject of Causal Interventions: Activation Patching.
Dai et al. (2022) pursued the same question one neuron at a time. Attributing BERT's predictions for fill-in-the-blank facts to the intermediate FFN neurons with integrated gradients, they found knowledge neurons whose suppression lowers, and whose amplification raises, the probability of the correct object.
Causal tracing in GPT-2 XL restores one hidden state at a time in a run whose subject embeddings were corrupted. Which restoration recovered the most of the correct object's probability through the MLPs?
- The MLP outputs of the final layers at the last token of the prompt
- The MLP outputs of middle layers at the last token of the subject
- The token embeddings of the object
- The MLP outputs of the first layer at every position
Show the answer
B. The MLP outputs of middle layers at the last token of the subject
The decisive MLP states sat in middle layers at the subject's last token. That observation motivated editing a middle-layer MLP, and it is also the claim that later work tested: being decisive for recall does not mean being the best place to edit.
Rank-one model editing
ROME treats the output matrix of one middle-layer MLP as a linear associative memory (Attention as Associative Memory): it maps keys , the MLP's hidden activations at a subject's last token, to values that carry facts about the subject into the residual stream. If the existing associations are the columns of and , then is (approximately) their least-squares fit, . To insert a new association while disturbing the old ones as little as possible:
Minimize the error on the old associations subject to storing the new one exactly. With a matrix of multipliers , set the gradient of the Lagrangian with respect to to zero; write :
Use and solve for : the change is an outer product with the direction , so the update has rank one ():
The constraint fixes : the new key must map to the new value.
Old keys change their outputs by : little when is nearly orthogonal to in the metric , that is, when the subject is unlike the edited one. In practice is the uncentered covariance of keys over a sample of Wikipedia text, is the average key at the subject's last token over 50 random short prefixes, and is found by optimizing the model to output the new object while a KL term keeps the subject's other properties stable.
On their CounterFact benchmark of 21,919 counterfactual edits, ROME's edits generalized to paraphrases while largely sparing unrelated subjects, with generalization peaking when it edited layer 18 of GPT-2 XL's 48. MEMIT (Meng et al., 2023) inserts many facts at once. With new keys and values added to the least-squares objective, the normal equations give
and MEMIT spreads the residual over a range of middle-layer MLPs. It scaled to thousands of edits in GPT-J (6 billion parameters) and GPT-NeoX (20 billion).
Locating is not editing
The story so far suggests a clean pipeline: trace the fact, then edit where it lives. Hase, Bansal, Kim and Ghandeharioun (2023) tested the first half's usefulness for the second. Across many facts they compared how strongly causal tracing localized each fact in each layer with how well editing that layer worked. Localization conclusions "do not provide any insight into which model MLP layer would be best to edit": the choice of layer predicted editing success far better than the tracing results did.
Ripple effects. A fact is entangled with others. If an edit says the Eiffel Tower is in Rome, a consistent model should also update which country it is in and how one would travel there. Cohen et al. (2024) built RippleEdits, a benchmark of 5,000 edits with such logically implied consequences, and found that current editing methods fail to make consistent changes to the model's knowledge; a simple baseline that puts the edited fact in the prompt scored best. Facts seem to be recalled through distributed computation, not looked up as isolated entries, which also fits the picture of features stored in superposition (Dictionary Learning at Scale).
Causal tracing says layer 15's MLP matters most for a fact. What do Hase et al. (2023) find about editing that fact?
- Editing must be done at layer 15; edits elsewhere fail
- Editing is impossible once a fact is localized
- Tracing results do not predict which layer is best to edit; the edited layer itself matters far more
- Editing works only at the first layer
Show the answer
C. Tracing results do not predict which layer is best to edit; the edited layer itself matters far more
In their experiments the tracing results gave no insight into which layer was best to edit, while the choice of layer itself was a much stronger predictor of success. Recovering a prediction and installing a new one are different interventions.
Gated FFNs and sparse activations
Most large models of the mid-2020s use a gated FFN. A gated linear unit (Dauphin, Fan, Auli & Grangier, 2017) multiplies one linear projection by a nonlinear function of another; Shazeer (2020) tried several in transformer FFNs. With , :
A standard FFN with has two matrices. A gated one has three, so at equal width it costs 50% more:
Setting them equal gives the hidden width two-thirds of ; Shazeer used instead of at :
At parameter parity with a FFN, what SwiGLU hidden width does give?
Show the answer
10923 units
. LLaMA's 7B model rounds this up to the next multiple of 256, , a width that suits hardware better.
Activation sparsity. With ReLU, most memory coefficients are exactly zero for any given input. Li et al. (2023) found that only about 3.0% of the FFN's intermediate activations are nonzero for T5-Base and 6.3% for ViT-B16, that larger models are sparser, and that the sparsity appears even with random labels, random inputs and unlimited data. Each token then reads only a few memories, which suggests skipping the rest at inference. Smooth activations such as GELU and SiLU blur this, and Mirzadeh et al. (2024) argued for returning to ReLU in large language models, reporting little effect on quality and up to three times less inference computation.
Key takeaways
- An FFN is an unnormalized key–value memory, : keys respond to input patterns (shallow in lower layers, semantic in upper ones) and values promote output tokens.
- ROME edits a fact by solving subject to , giving the rank-one update ; MEMIT generalizes it to thousands of facts over several layers.
- Locating is not editing: causal tracing finds where recall can be restored, but it does not predict which layer is best to edit, and edits rarely propagate to logically implied facts.
- Gated FFNs such as SwiGLU use three matrices, so parameter parity needs (rounded to 11,008 at in LLaMA); ReLU FFNs are naturally very sparse, which inference can exploit.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the memory reading , what plays the role that attention weights play in attention?
- The coefficients , which unlike attention weights are not normalized to sum to one
- The values
- The tokens of the context
- The softmax over the vocabulary
Show the answer
A. The coefficients , which unlike attention weights are not normalized to sum to one
Each coefficient measures how strongly input matches key and scales that slot's value. There is no competition between slots: many can fire at once, or none.
Why is ROME's update rank one?
- Because it only edits one row of
- Because the constrained least-squares solution changes by an outer product of the correction with the single direction
- Because has rank one
- Because the value is a one-hot vector
Show the answer
B. Because the constrained least-squares solution changes by an outer product of the correction with the single direction
One equality constraint adds one multiplier term, , to the normal equations, and multiplying by turns it into an outer product. Every column of can change, but only along one pattern.
A model is edited so that it answers that the Eiffel Tower is in Rome. What do ripple-effect evaluations typically find?
- Every logically related fact updates automatically
- The edit cannot be made at all
- The model forgets every fact about Paris
- The edited fact is reproduced, but implied facts, such as the tower's country, often stay unchanged or become inconsistent
Show the answer
D. The edited fact is reproduced, but implied facts, such as the tower's country, often stay unchanged or become inconsistent
Cohen et al. (2024) found that current editing methods fail to make consistent changes to related knowledge, and that putting the new fact in the prompt did better on their benchmark.
A model of width swaps its ReLU FFN for SwiGLU at the same parameter count. What hidden width should it use?
- About
Show the answer
C. About
Three matrices must match two ones: .
Further reading
- M. Geva, R. Schuster, J. Berant & O. Levy, "Transformer feed-forward layers are key-value memories," EMNLP (2021).
- M. Geva, A. Caciularu, K. R. Wang & Y. Goldberg, "Transformer feed-forward layers build predictions by promoting concepts in the vocabulary space," EMNLP (2022).
- K. Meng, D. Bau, A. Andonian & Y. Belinkov, "Locating and editing factual associations in GPT," NeurIPS (2022).
- P. Hase, M. Bansal, B. Kim & A. Ghandeharioun, "Does localization inform editing? Surprising differences in causality-based localization vs. knowledge editing in language models," NeurIPS (2023).
- N. Shazeer, "GLU variants improve transformer," arXiv:2002.05202 (2020).