Transformer Feed-Forward Networks as Key-Value Memories: How First-Layer Keys and Second-Layer Values Store Knowledge

Transformer Feed-Forward Networks as Key-Value Memories: How First-Layer Keys and Second-Layer Values Store Knowledge In modern autoregressive Transformers, the division of labor between attention heads and multi-layer perceptron (MLP) blocks is often summarized through a clean functional split: attention routes information across sequence positions, while feed-forward networks (FFNs) process information per position. Yet for years, the exact mechanism by which FFNs process that information rem

6 min
Transformer Feed-Forward Networks as Key-Value Memories: How First-Layer Keys and Second-Layer Values Store Knowledge

Transformer Feed-Forward Networks as Key-Value Memories: How First-Layer Keys and Second-Layer Values Store Knowledge

In modern autoregressive Transformers, the division of labor between attention heads and multi-layer perceptron (MLP) blocks is often summarized through a clean functional split: attention routes information across sequence positions, while feed-forward networks (FFNs) process information per position. Yet for years, the exact mechanism by which FFNs process that information remained a black box.

Foundational interpretability research by Geva et al. (2021) demonstrated that Transformer feed-forward networks operate mathematically as unnormalized associative key-value memories. Under this formulation:

  1. The first linear layer acts as a bank of pattern-matching keys (W1W_1) that detect textual, syntactic, or semantic triggers in the input representation.
  2. The non-linear activation function serves as a thresholding and routing filter.
  3. The second linear layer acts as a bank of values (W2W_2) whose corresponding vectors are retrieved, weighted, and written directly into the model's residual stream.

Understanding this key-value memory formulation explains why FFNs account for roughly two-thirds of a Transformer's total non-embedding parameter budget, how factual knowledge is localized across layers, and how techniques like model editing and Mixture of Experts scale LLM capacity.


The Mathematical Isomorphism: FFN as Associative Lookup

In a standard Transformer block, the feed-forward sublayer processes an incoming hidden vector xRdmodelx \in \mathbb{R}^{d_{\text{model}}} from the residual stream. The standard two-layer MLP computation is defined as:

FFN(x)=σ(xW1+b1)W2+b2\text{FFN}(x) = \sigma(x W_1 + b_1) W_2 + b_2

where W1Rdmodel×dffW_1 \in \mathbb{R}^{d_{\text{model}} \times d_{\text{ff}}}, W2Rdff×dmodelW_2 \in \mathbb{R}^{d_{\text{ff}} \times d_{\text{model}}}, b1Rdffb_1 \in \mathbb{R}^{d_{\text{ff}}}, b2Rdmodelb_2 \in \mathbb{R}^{d_{\text{model}}}, and σ()\sigma(\cdot) is a non-linear activation function (such as GELU or ReLU). The intermediate dimension dffd_{\text{ff}} is typically set to 4dmodel4 d_{\text{model}} in standard architectures (or 83dmodel\frac{8}{3} d_{\text{model}} in gated variants such as SwiGLU).

Transformer Feed-Forward Key-Value Architecture

To see the key-value memory structure, let:

  • kiRdmodelk_i \in \mathbb{R}^{d_{\text{model}}} denote the ii-th column of W1W_1 (the ii-th key vector, for i{1,,dff}i \in \{1, \dots, d_{\text{ff}}\}).
  • viRdmodelv_i \in \mathbb{R}^{d_{\text{model}}} denote the ii-th row of W2W_2 (the ii-th value vector).
  • b1,iRb_{1,i} \in \mathbb{R} denote the ii-th scalar bias in b1b_1.

Expanding the matrix multiplication into vector operations yields:

FFN(x)=i=1dffσ(xki+b1,i)vi+b2\text{FFN}(x) = \sum_{i=1}^{d_{\text{ff}}} \sigma(x \cdot k_i + b_{1,i}) v_i + b_2

This formulation matches the mathematical definition of an associative key-value memory:

  1. Key Matching (Addressing): The inner product xkix \cdot k_i measures the similarity between the current hidden state xx and the ii-th key vector kik_i.
  2. Activation Filtering: The scalar activation mi(x)=σ(xki+b1,i)m_i(x) = \sigma(x \cdot k_i + b_{1,i}) determines how strongly memory slot ii fires.
  3. Value Retrieval and Superposition: The output is a linear combination of value vectors imi(x)vi\sum_i m_i(x) v_i, where each value vector viv_i is injected in proportion to its activation intensity.

Unlike attention-based key-value retrieval, which normalizes coefficients via softmax across tokens in a context window, the FFN memory operates independently per token across dffd_{\text{ff}} discrete memory slots using elementwise activations.


Keys as Pattern Detectors, Values as Vocabulary Concepts

What do individual keys and values actually represent? Subsequent mechanistic work by Geva et al. (2022) and Dai et al. (2022) systematically analyzed the inputs that activate specific neurons and the output distributions induced by their corresponding value vectors.

Keys as Trigger Patterns

By tracking which text prefixes produce the largest inner product xkix \cdot k_i, researchers found that individual keys act as specialized pattern detectors:

  • Shallow Patterns: Keys in early layers trigger on specific n-grams, capitalization, punctuation formats, or morphological suffixes (such as words ending in "-ing" or capitalized acronyms).
  • Semantic Classes: Keys in middle layers trigger on conceptual categories, such as mentions of programming languages, geographical locations, or corporate entities.
  • Relational Contexts: Keys in upper-middle layers trigger on specific relational prompts (such as "The capital of [Country] is" or "authored by").

Values as Vocabulary Directions

Because each value vector viRdmodelv_i \in \mathbb{R}^{d_{\text{model}}} lives in the same hidden space as the residual stream, it can be directly analyzed by projecting it through the language model's unembedding matrix WURdmodel×VW_U \in \mathbb{R}^{d_{\text{model}} \times |V|} (often termed the Logit Lens):

logits(vi)=viWU\text{logits}(v_i) = v_i W_U

When projected into vocabulary space, individual value vectors viv_i place high probability mass on a small, semantically coherent cluster of tokens. For instance:

  • A key kik_i that activates on phrases describing the Eiffel Tower or the Louvre pairs with a value vector viv_i that directly boosts the logits for "Paris", "France", and "French".
  • A key kik_i that detects code definitions pairs with a value vector viv_i that promotes programming syntax tokens such as return, def, or import.

Feed-forward layers function by querying these memory slots and adding their output directly to the residual stream:

xl+1=xl+Attn(xl)+i=1dffmi(xl)vix_{l+1} = x_l + \text{Attn}(x_l) + \sum_{i=1}^{d_{\text{ff}}} m_i(x_l) v_i

Each layer sequentially modifies the token distribution by promoting or suppressing specific vocabulary candidates.


Layerwise Specialization: The Three-Tier Memory Hierarchy

Across a multi-layer Transformer, the functional role of key-value memories evolves systematically from lower to upper layers:

| Layer Tier | Representation Level | Key Triggers (kik_i) | Value Vector Output (viWUv_i W_U) | | :--- | :--- | :--- | :--- | | Lower Layers (0 to 30%) | Surface & Syntax | Token prefixes, casing, syntax markers, subword concatenations | Syntactic continuations, morphological completions | | Middle Layers (30 to 70%) | Semantics & Knowledge | Entity types, subject-relation tuples, relational contexts | Factual attributes, related entity names, topical terms | | Upper Layers (70 to 100%) | Prediction & Distribution | Task-specific goals, next-token formatting context | Exact next-token candidates, probability mass sharpening |

In research exploring knowledge localization, Meng et al. (2022) demonstrated via causal tracing that factual recall (such as determining the country associated with a landmark) originates in the early-to-middle MLP layers at the subject token position, which is then routed to the final sequence position by late attention layers.


The Parameter Budget and SwiGLU Gating

Feed-forward layers represent the largest parameter footprint in standard language models. In a vanilla Transformer with hidden dimension dmodeld_{\text{model}} and dff=4dmodeld_{\text{ff}} = 4 d_{\text{model}}:

  • Self-Attention Sublayer: WQ,WK,WV,WORdmodel×dmodelW_Q, W_K, W_V, W_O \in \mathbb{R}^{d_{\text{model}} \times d_{\text{model}}} account for 4dmodel24 d_{\text{model}}^2 parameters.
  • FFN Sublayer: W1Rdmodel×4dmodelW_1 \in \mathbb{R}^{d_{\text{model}} \times 4 d_{\text{model}}} and W2R4dmodel×dmodelW_2 \in \mathbb{R}^{4 d_{\text{model}} \times d_{\text{model}}} account for 8dmodel28 d_{\text{model}}^2 parameters.

Thus, FFN blocks consume 812=66.7%\frac{8}{12} = 66.7\% of total transformer layer weights (excluding embeddings).

Standard FFN (2-Layer MLP):
Input x ────────────────────────┬───────────────────────────┐
                                │                           │
                                ▼                           │
                        [ Key Matrix W₁ ]                   │
                                │ (x · k_i)                 │
                                ▼                           │
                        [ Activation σ ]                    │
                                │ (m_i)                     │
                                ▼                           │
                       [ Value Matrix W₂ ]                  │
                                │ (Σ m_i · v_i)             │
                                ▼                           │
                               ( + ) ◄──────────────────────┘ (Residual Stream)
                                │
                              Output

SwiGLU Gating Architecture

Modern architectures (such as LLaMA, Mistral, and Qwen) replace the two-matrix MLP with SwiGLU (Shazeer, 2020), which introduces an explicit multiplicative gating branch:

SwiGLU(x)=(Swish(xWgate)xWup)Wdown\text{SwiGLU}(x) = \left( \text{Swish}(x W_{\text{gate}}) \odot x W_{\text{up}} \right) W_{\text{down}}

To maintain a comparable parameter budget of 8dmodel28 d_{\text{model}}^2, dffd_{\text{ff}} is scaled down to approximately 83dmodel\frac{8}{3} d_{\text{model}}:

Parameters=3×dmodel×(83dmodel)=8dmodel2\text{Parameters} = 3 \times d_{\text{model}} \times \left(\frac{8}{3} d_{\text{model}}\right) = 8 d_{\text{model}}^2

Under the key-value interpretation, the gating branch Swish(xWgate)\text{Swish}(x W_{\text{gate}}) provides a dynamic continuous gate that scales the projection xWupx W_{\text{up}} before the linear value recombination in WdownW_{\text{down}}, increasing memory capacity per parameter without increasing inference FLOPs.


Practical Applications: Model Editing and Mixture of Experts

Viewing FFN layers as associative memories is not merely an interpretability framework; it has enabled practical architectural and operational capabilities:

1. Rank-One Model Editing (ROME) and MEMIT

Because the second linear layer W2W_2 serves as a linear value lookup matrix satisfying W2KVW_2 K \approx V, researchers can treat factual editing as a constrained linear algebra problem. Meng et al. (2022) and Meng et al. (2023) demonstrated that injecting a new fact (or updating an existing one) can be executed in closed form using a rank-one weight update:

ΔW2=(vW2k<em>)(C1k</em>)T\Delta W_2 = (v^* - W_2 k^<em>) (C^{-1} k^</em>)^T

where $k^$ is the key vector for the target subject entity, $v^$ is the desired value vector corresponding to the target property, and CC is a covariance matrix of unperturbed key activations that prevents catastrophic forgetting.

2. Mixture of Experts (MoE)

The key-value memory perspective explains why Mixture of Experts architectures (such as Mixtral, DeepSeek-V3, and Grok) scale model capacity by replicating FFN layers while keeping attention layers shared:

  • FFN parameters store static knowledge and associative facts.
  • Attention parameters govern dynamic contextual routing.

By partitioning the FFN key-value memory banks into discrete routed experts (E1,,ENE_1, \dots, E_N), models can expand total factual memory capacity to hundreds of billions of parameters while only activating top-kk memory banks per token, keeping active inference latency and FLOPs constant.


Sources

Written by

More to read

  • LLM Text Watermarking in Production: Statistical Logit Biasing, Cryptographic Signatures, and Evasion Vectors

    As regulatory frameworks such as Article 50 of the EU AI Act enforce machine-generated content provenance, text watermarking has transitioned from academic theory to a core component of production LLM serving stacks. Unlike post-hoc classifiers that evaluate perplexity or burstiness and suffer from high false-positive rates on formal or non-native writing, generation-time watermarks embed imperceptible statistical or cryptographic signals directly into the token sampling process. When engineere

    1 min
  • Grokking in Large Language Models: How Weight Decay and Circuit Efficiency Drive Delayed Generalization

    Grokking in Large Language Models: How Weight Decay and Circuit Efficiency Drive Delayed Generalization In standard machine learning paradigms, model generalization closely tracks training loss: as an optimizer minimizes loss on training data, performance on held-out validation data improves in tandem until the model begins to overfit. In 2022, researchers at OpenAI observed a phenomenon that inverted this assumption: small neural networks trained on algorithmic tasks achieved near-zero trainin

    1 min
  • Serverless GPU Inference in Production: Cold Starts, GPU Memory Snapshotting, and Weight Paging Architectures

    Serverless GPU Inference in Production: Cold Starts, GPU Memory Snapshotting, and Weight Paging Architectures Deploying large language models on dedicated cloud GPUs creates an uncomfortable financial trade-off: keeping enterprise accelerators such as NVIDIA H100s or A100s warm 24/7 costs thousands of dollars per instance each month, yet scaling instances to zero introduces severe latency penalties. When traffic arrives at a dormant node, a standard inference server cold start can take anywhere

    1 min