Simple Algorithm
Deep Learning · Emergence · 26 min

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 dff=8d/3d_{\text{ff}}=8d/3 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: ki⊤\mathbf k_i^\top is row ii of W1W_1 and vi\mathbf v_i is column ii of W2W_2. Then, ignoring biases,

FFN⁡(x)=W2 ϕ(W1x)=∑i=1dffϕ(ki⋅x)⏟mi(x) vivs.Attn⁡(q)=∑j=1tsoftmax⁡j(q⋅kj) vj\operatorname{FFN}(\mathbf x)=W_2\,\phi(W_1\mathbf x)=\sum_{i=1}^{d_{\text{ff}}}\underbrace{\phi(\mathbf k_i\cdot\mathbf x)}_{m_i(\mathbf x)}\,\mathbf v_i\qquad\text{vs.}\qquad\operatorname{Attn}(\mathbf q)=\sum_{j=1}^{t}\softmax_j(\mathbf q\cdot\mathbf k_j)\,\mathbf v_j
The same shape as attention, with three differences: the dffd_{\text{ff}} keys and values are parameters rather than tokens of the context, the coefficients mim_i are not normalized, and ϕ\phi is a ReLU or GELU instead of a softmax. Sukhbaatar et al. (2019) made the analogy literal, replacing feed-forward layers by learned persistent key–value vectors inside attention.

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 mivim_i\mathbf v_i 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.

python
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 most

Projecting 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.

Check your understanding

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?

  1. The MLP outputs of the final layers at the last token of the prompt
  2. The MLP outputs of middle layers at the last token of the subject
  3. The token embeddings of the object
  4. 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 WW of one middle-layer MLP as a linear associative memory (Attention as Associative Memory): it maps keys k\mathbf k, the MLP's hidden activations at a subject's last token, to values v\mathbf v that carry facts about the subject into the residual stream. If the existing associations are the columns of KK and VV, then WW is (approximately) their least-squares fit, WKK⊤=VK⊤WKK^\top=VK^\top. To insert a new association (k∗,v∗)(\mathbf k_*,\mathbf v_*) while disturbing the old ones as little as possible:

DerivationThe closed-form edit
  1. min⁡W^ ∥W^K−V∥F2  s.t.  W^k∗=v∗⟹2(W^K−V)K⊤+λ k∗⊤=0\min_{\hat W}\ \norm{\hat WK-V}_F^2\ \ \text{s.t.}\ \ \hat W\mathbf k_*=\mathbf v_*\quad\Longrightarrow\quad2(\hat WK-V)K^\top+\boldsymbol\lambda\,\mathbf k_*^\top=0

    Minimize the error on the old associations subject to storing the new one exactly. With a matrix of multipliers λ\boldsymbol\lambda, set the gradient of the Lagrangian with respect to W^\hat W to zero; write C=KK⊤C=KK^\top:

  2. W^C=WC−12λ k∗⊤⟹W^=W+Λ (C−1k∗)⊤\hat WC=WC-\tfrac12\boldsymbol\lambda\,\mathbf k_*^\top\quad\Longrightarrow\quad\hat W=W+\boldsymbol\Lambda\,(C^{-1}\mathbf k_*)^\top

    Use VK⊤=WCVK^\top=WC and solve for W^\hat W: the change is an outer product with the direction C−1k∗C^{-1}\mathbf k_*, so the update has rank one (Λ=−λ/2\boldsymbol\Lambda=-\boldsymbol\lambda/2):

  3. W^k∗=Wk∗+Λ (C−1k∗)⊤k∗=v∗⟹Λ=v∗−Wk∗(C−1k∗)⊤k∗\hat W\mathbf k_*=W\mathbf k_*+\boldsymbol\Lambda\,(C^{-1}\mathbf k_*)^\top\mathbf k_*=\mathbf v_*\quad\Longrightarrow\quad\boldsymbol\Lambda=\frac{\mathbf v_*-W\mathbf k_*}{(C^{-1}\mathbf k_*)^\top\mathbf k_*}

    The constraint fixes Λ\boldsymbol\Lambda: the new key must map to the new value.

  4. Δ(Wk)=Λ (k∗⊤C−1k)\Delta(W\mathbf k)=\boldsymbol\Lambda\,\big(\mathbf k_*^\top C^{-1}\mathbf k\big)

    Old keys k\mathbf k change their outputs by Λ (C−1k∗)⊤k\boldsymbol\Lambda\,(C^{-1}\mathbf k_*)^\top\mathbf k: little when k\mathbf k is nearly orthogonal to k∗\mathbf k_* in the metric C−1C^{-1}, that is, when the subject is unlike the edited one. In practice CC is the uncentered covariance of keys over a sample of Wikipedia text, k∗\mathbf k_* is the average key at the subject's last token over 50 random short prefixes, and v∗\mathbf v_* 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 K1,V1K_1,V_1 added to the least-squares objective, the normal equations give

W^=W+RK1⊤(C0+K1K1⊤)−1,R=V1−WK1,\hat W=W+RK_1^\top\big(C_0+K_1K_1^\top\big)^{-1},\qquad R=V_1-WK_1,

and MEMIT spreads the residual RR 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).

Check your understanding

Causal tracing says layer 15's MLP matters most for a fact. What do Hase et al. (2023) find about editing that fact?

  1. Editing must be done at layer 15; edits elsewhere fail
  2. Editing is impossible once a fact is localized
  3. Tracing results do not predict which layer is best to edit; the edited layer itself matters far more
  4. 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 Swish⁡1=SiLU⁡\operatorname{Swish}_1=\operatorname{SiLU}, SiLU⁡(z)=z σ(z)\operatorname{SiLU}(z)=z\,\sigma(z):

FFN⁡SwiGLU(x)=W2(SiLU⁡(W1x)⊙W3x),W1,W3∈Rdff×d,W2∈Rd×dff\operatorname{FFN}_{\text{SwiGLU}}(\mathbf x)=W_2\big(\operatorname{SiLU}(W_1\mathbf x)\odot W_3\mathbf x\big),\qquad W_1,W_3\in\R^{d_{\text{ff}}\times d},\quad W_2\in\R^{d\times d_{\text{ff}}}
SwiGLU uses SiLU and GEGLU uses GELU as the gate; in the memory reading, each key's coefficient becomes a product of a gate and a second, linear key. Shazeer found the GEGLU and SwiGLU variants gave the best perplexities of those compared, and offered no explanation: "we attribute their success, as all else, to divine benevolence."
DerivationMatching the parameter count
  1. Pstd=2⋅d⋅4d=8d2,Pgated=3 d dffP_{\text{std}}=2\cdot d\cdot4d=8d^2,\qquad P_{\text{gated}}=3\,d\,d_{\text{ff}}

    A standard FFN with dff=4dd_{\text{ff}}=4d has two matrices. A gated one has three, so at equal width it costs 50% more:

  2. 3 d dff=8d2⟹dff=8d3=23⋅4d3\,d\,d_{\text{ff}}=8d^2\quad\Longrightarrow\quad d_{\text{ff}}=\frac{8d}{3}=\frac23\cdot4d

    Setting them equal gives the hidden width two-thirds of 4d4d; Shazeer used 20482048 instead of 30723072 at d=768d=768:

Predict before you look

At parameter parity with a 4d4d FFN, what SwiGLU hidden width does d=4096d=4096 give?

Show the answer

10923 units

8×4096/3≈10,922.78\times4096/3\approx10{,}922.7. LLaMA's 7B model rounds this up to the next multiple of 256, 43×256=11,00843\times256=11{,}008, 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, ∑iϕ(ki⋅x)vi\sum_i\phi(\mathbf k_i\cdot\mathbf x)\mathbf v_i: keys respond to input patterns (shallow in lower layers, semantic in upper ones) and values promote output tokens.
  • ROME edits a fact by solving min⁡∥W^K−V∥F\min\norm{\hat WK-V}_F subject to W^k∗=v∗\hat W\mathbf k_*=\mathbf v_*, giving the rank-one update W^=W+Λ(C−1k∗)⊤\hat W=W+\boldsymbol\Lambda(C^{-1}\mathbf k_*)^\top; 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 dff=8d/3d_{\text{ff}}=8d/3 (rounded to 11,008 at d=4096d=4096 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.

Question 1

In the memory reading FFN⁡(x)=∑iϕ(ki⋅x) vi\operatorname{FFN}(\mathbf x)=\sum_i\phi(\mathbf k_i\cdot\mathbf x)\,\mathbf v_i, what plays the role that attention weights play in attention?

  1. The coefficients ϕ(ki⋅x)\phi(\mathbf k_i\cdot\mathbf x), which unlike attention weights are not normalized to sum to one
  2. The values vi\mathbf v_i
  3. The tokens of the context
  4. The softmax over the vocabulary
Show the answer

A. The coefficients ϕ(ki⋅x)\phi(\mathbf k_i\cdot\mathbf x), which unlike attention weights are not normalized to sum to one

Each coefficient measures how strongly input x\mathbf x matches key ki\mathbf k_i and scales that slot's value. There is no competition between slots: many can fire at once, or none.

Question 2

Why is ROME's update W^=W+Λ(C−1k∗)⊤\hat W=W+\boldsymbol\Lambda(C^{-1}\mathbf k_*)^\top rank one?

  1. Because it only edits one row of WW
  2. Because the constrained least-squares solution changes WW by an outer product of the correction Λ\boldsymbol\Lambda with the single direction C−1k∗C^{-1}\mathbf k_*
  3. Because CC has rank one
  4. Because the value v∗\mathbf v_* is a one-hot vector
Show the answer

B. Because the constrained least-squares solution changes WW by an outer product of the correction Λ\boldsymbol\Lambda with the single direction C−1k∗C^{-1}\mathbf k_*

One equality constraint adds one multiplier term, λk∗⊤\boldsymbol\lambda\mathbf k_*^\top, to the normal equations, and multiplying by C−1C^{-1} turns it into an outer product. Every column of WW can change, but only along one pattern.

Question 3

A model is edited so that it answers that the Eiffel Tower is in Rome. What do ripple-effect evaluations typically find?

  1. Every logically related fact updates automatically
  2. The edit cannot be made at all
  3. The model forgets every fact about Paris
  4. 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.

Question 4

A model of width d=1024d=1024 swaps its 4d4d ReLU FFN for SwiGLU at the same parameter count. What hidden width should it use?

  1. 40964096
  2. 13651365
  3. About 27312731
  4. 61446144
Show the answer

C. About 27312731

Three d×dffd\times d_{\text{ff}} matrices must match two d×4dd\times4d ones: dff=8d/3≈2730.7d_{\text{ff}}=8d/3\approx2730.7.

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).