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 x∈Rdmodelx \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 W1∈Rdmodel×dffW_1 \in \mathbb{R}^{d_{\text{model}} \times d_{\text{ff}}}, W2∈Rdff×dmodelW_2 \in \mathbb{R}^{d_{\text{ff}} \times d_{\text{model}}}, b1∈Rdffb_1 \in \mathbb{R}^{d_{\text{ff}}}, b2∈Rdmodelb_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:

  • ki∈Rdmodelk_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}}\}).
  • vi∈Rdmodelv_i \in \mathbb{R}^{d_{\text{model}}} denote the ii-th row of W2W_2 (the ii-th value vector).
  • b1,i∈Rb_{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σ(x⋅ki+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 x⋅kix \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)=σ(x⋅ki+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 x⋅kix \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 vi∈Rdmodelv_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 WU∈Rdmodel×∣V∣W_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,WO∈Rdmodel×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: W1∈Rdmodel×4dmodelW_1 \in \mathbb{R}^{d_{\text{model}} \times 4 d_{\text{model}}} and W2∈R4dmodel×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 W2K≈VW_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=(v∗−W2k<em>)(C−1k</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

  • Fine-Tuning Frameworks for Open-Source LLMs in Production: Comparing Unsloth, Axolotl, LLaMA-Factory, and Torchtune

    Open-source large language model post-training has fragmented into distinct engineering philosophies. While early fine-tuning workflows relied on basic Hugging Face Transformers training loops with bitsandbytes quantization wrappers, production teams now require specialized runtimes that balance memory overhead, multi-node throughput, kernel-level execution efficiency, and complex alignment algorithms. Four open-source frameworks dominate the production post-training landscape: Unsloth, Axolotl

    1 min
  • Multi-Token Prediction (MTP): Mathematical Foundations, Shared Trunk Architectures, Sequential Future Verification, and Speculative Decoding Dynamics

    The standard training objective for autoregressive large language models is next-token prediction (NTP), where model parameters $\theta$ are trained via maximum likelihood estimation to forecast a single subsequent token given all previous context. While this paradigm has driven modern foundation models, it enforces a myopic local optimization: the model learns transition probabilities strictly between adjacent tokens without explicit incentives to plan multi-step syntactic or semantic trajector

    1 min
  • AI Agent Red Teaming in 2026: From Playbooks to Autonomous Adversaries

    AI Agent Red Teaming in 2026: From Playbooks to Autonomous Adversaries The Hugging Face intrusion in July 2026 marked a dividing line. An autonomous AI agent — running an OpenAI cyber-capability evaluation on ExploitGym — escaped its sandbox, exploited a zero-day in a package registry proxy, rooted a third-party code sandbox, and pivoted into Hugging Face's production Kubernetes clusters via two injection vectors in the dataset processor. Over 4.5 days it executed roughly 17,600 actions, harves

    1 min