Multi-Head Attention in Large Language Models: How Query, Key, and Value Projections Route Information Across Subspaces

Multi-Head Attention in Large Language Models: How Query, Key, and Value Projections Route Information Across Subspaces The attention mechanism serves as the computational core of modern Transformer architectures, providing a mechanism for tokens to dynamically exchange information across arbitrary sequence positions without recurrent state transitions or fixed convolutional receptive fields. While single-head attention computes a single set of attention weights per token pair, modern large lan

10 min
Multi-Head Attention in Large Language Models: How Query, Key, and Value Projections Route Information Across Subspaces

Multi-Head Attention in Large Language Models: How Query, Key, and Value Projections Route Information Across Subspaces

The attention mechanism serves as the computational core of modern Transformer architectures, providing a mechanism for tokens to dynamically exchange information across arbitrary sequence positions without recurrent state transitions or fixed convolutional receptive fields. While single-head attention computes a single set of attention weights per token pair, modern large language models rely on Multi-Head Attention (MHA) to route information across multiple representation subspaces concurrently.

By projecting input hidden states into multiple distinct Query, Key, and Value subspaces, Multi-Head Attention prevents the model from averaging out distinct linguistic, syntactic, and semantic relationships into a single homogenized distribution.

Multi-Head Attention Subspace Projections and Scaled Dot-Product Computation

1. Mathematical Formulation of Scaled Dot-Product Attention

The foundational building block of the Transformer attention layer is Scaled Dot-Product Attention, introduced by Vaswani et al. (2017). Given an input sequence matrix XRN×dmodelX \in \mathbb{R}^{N \times d_{\text{model}}} representing NN tokens of hidden dimension dmodeld_{\text{model}}, the input is projected into three distinct representations via learnable linear weight matrices:

Q=XWQ,K=XWK,V=XWVQ = X W_Q, \quad K = X W_K, \quad V = X W_V

Where:

  • WQRdmodel×dkW_Q \in \mathbb{R}^{d_{\text{model}} \times d_k} is the Query projection matrix.
  • WKRdmodel×dkW_K \in \mathbb{R}^{d_{\text{model}} \times d_k} is the Key projection matrix.
  • WVRdmodel×dvW_V \in \mathbb{R}^{d_{\text{model}} \times d_v} is the Value projection matrix.
  • dkd_k is the dimensionality of queries and keys, and dvd_v is the dimensionality of values (typically dk=dvd_k = d_v).

The Scaled Dot-Product Equation

Scaled Dot-Product Attention computes the inner product between queries and keys, scales the resulting logit scores, applies a row-wise softmax normalization, and weights the value vectors:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V

Input Tokens (X)
  ├──> [ * W_Q ] ──> Query (Q) ──┐
  ├──> [ * W_K ] ──> Key (K)   ──┴──> MatMul(Q, K^T) ──> Scale (1/√d_k) ──> [Mask] ──> Softmax ──┐
  └──> [ * W_V ] ───────────────────> Value (V) ───────────────────────────────────────────┴──> MatMul(A, V) ──> Head Output

Why the dk\sqrt{d_k} Scaling Factor Is Necessary

The division by dk\sqrt{d_k} is critical for training stability in high-dimensional vector spaces. To understand why, consider the components of a single query vector qRdkq \in \mathbb{R}^{d_k} and a key vector kRdkk \in \mathbb{R}^{d_k}.

Assuming the individual vector elements qiq_i and kik_i are independent random variables with zero mean (E[qi]=E[ki]=0\mathbb{E}[q_i] = \mathbb{E}[k_i] = 0) and unit variance (Var(qi)=Var(ki)=1\text{Var}(q_i) = \text{Var}(k_i) = 1):

  1. The expected value of the inner product is zero:

E[qk]=E[i=1dkqiki]=i=1dkE[qi]E[ki]=0\mathbb{E}[q \cdot k] = \mathbb{E}\left[\sum_{i=1}^{d_k} q_i k_i\right] = \sum_{i=1}^{d_k} \mathbb{E}[q_i]\mathbb{E}[k_i] = 0

  1. Because the individual products qikiq_i k_i are independent, the variance of their sum equals the sum of their variances:

Var(qiki)=E[(qiki)2](E[qiki])2=E[qi2]E[ki2]0=1×1=1\text{Var}(q_i k_i) = \mathbb{E}[(q_i k_i)^2] - (\mathbb{E}[q_i k_i])^2 = \mathbb{E}[q_i^2]\mathbb{E}[k_i^2] - 0 = 1 \times 1 = 1 Var(qk)=Var(i=1dkqiki)=i=1dkVar(qiki)=dk\text{Var}(q \cdot k) = \text{Var}\left(\sum_{i=1}^{d_k} q_i k_i\right) = \sum_{i=1}^{d_k} \text{Var}(q_i k_i) = d_k

  1. The standard deviation of the raw dot product is therefore σ=dk\sigma = \sqrt{d_k}.

As the head dimension dkd_k grows (for instance, dk=64d_k = 64 or dk=128d_k = 128), the magnitude of the dot products scales proportionally with dk\sqrt{d_k}. When unscaled dot products enter the softmax function, large inputs push the exponential terms to extremes, driving the softmax outputs toward one-hot distributions.

In this saturated regime, the gradients of the softmax function with respect to its inputs approach zero (softmax(z)izj0\frac{\partial \text{softmax}(z)_i}{\partial z_j} \approx 0). Dividing QKTQ K^T by dk\sqrt{d_k} rescales the variance of the attention logits back to 1.0, preserving healthy gradient flow throughout backpropagation.

Causal Masking in Autoregressive Models

In decoder-only language models (such as GPT-4, LLaMA, and Claude), tokens must not attend to future sequence positions. This constraint is enforced by applying an additive upper-triangular causal mask MRN×NM \in \mathbb{R}^{N \times N} to the scaled logits prior to the softmax operation:

Mij={0if ijif i<jM_{ij} = \begin{cases} 0 & \text{if } i \ge j \\ -\infty & \text{if } i < j \end{cases}

Attentioncausal(Q,K,V)=softmax(QKTdk+M)V\text{Attention}_{\text{causal}}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}} + M\right) V

When Mij=M_{ij} = -\infty, the corresponding exponential term in the softmax denominator evaluates to e=0e^{-\infty} = 0, ensuring zero attention weight is assigned to subsequent tokens.


2. Multi-Head Attention Architecture

Single-head attention computes a single weighted combination of value vectors for each token. In natural language, however, a single token simultaneously participates in multiple relationships:

  • Syntactic dependencies (for example, linking a verb to its subject and direct object).
  • Coreference resolution (linking pronouns to preceding proper nouns).
  • Positional proximity (attending to immediately preceding or subsequent tokens).
  • Semantic association (linking related domain concepts across long paragraph spans).

A single attention distribution forces the model to average these disparate attention patterns into a single weighted vector, diluting specific relational signals. Multi-Head Attention overcomes this limitation by partitioning the feature space into hh parallel attention heads.

                  Input Hidden States X (N x d_model)
                                   │
      ┌──────────────┬─────────────┼─────────────┬──────────────┐
      ▼              ▼             ▼             ▼              ▼
   Head 1         Head 2        Head 3        Head 4         Head h
  Q1, K1, V1    Q2, K2, V2    Q3, K3, V3    Q4, K4, V4     Qh, Kh, Vh
      │              │             │             │              │
  Attention      Attention     Attention     Attention      Attention
      │              │             │             │              │
   Output 1       Output 2      Output 3      Output 4       Output h
      └──────────────┴─────────────┼─────────────┴──────────────┘
                                   │
                           Concat(head_1, ..., head_h)
                                   │
                           Linear Projection (W_O)
                                   │
                      Output States (N x d_model)

Multi-Head Equations

Instead of performing a single attention function with dmodeld_{\text{model}}-dimensional queries, keys, and values, Multi-Head Attention linearly projects queries, keys, and values hh times with distinct learnable parameter matrices:

MultiHead(Q,K,V)=Concat(head1,head2,,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \text{head}_2, \dots, \text{head}_h) W_O

where headi=Attention(QWiQ,KWiK,VWiV)\text{where } \text{head}_i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)

The parameter dimensions are structured as:

  • WiQRdmodel×dkW_i^Q \in \mathbb{R}^{d_{\text{model}} \times d_k}
  • WiKRdmodel×dkW_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}
  • WiVRdmodel×dvW_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v}
  • WORhdv×dmodelW_O \in \mathbb{R}^{h d_v \times d_{\text{model}}}

In standard implementations, the head dimension is set to dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h. For example, in a model with dmodel=4096d_{\text{model}} = 4096 and h=32h = 32 heads, each individual head operates in a dk=128d_k = 128 dimensional subspace.

Because each head operates at reduced dimensionality (dmodel/hd_{\text{model}} / h), the total computational cost of computing hh parallel heads is identical to that of a single full-dimensional attention head with dk=dmodeld_k = d_{\text{model}}.

Fused Matrix Implementation

In production inference and training engines (such as PyTorch, vLLM, and TensorRT-LLM), the hh individual head projections are not executed as separate sequential kernel launches. Instead, they are fused into three large matrix multiplications:

# Batch dimension B, sequence length N, model dimension D, heads H, head_dim d_k
# Fused linear projections:
q = self.w_q(x)  # Shape: [B, N, H * d_k]
k = self.w_k(x)  # Shape: [B, N, H * d_k]
v = self.w_v(x)  # Shape: [B, N, H * d_v]

# Reshape into parallel heads:
q = q.view(B, N, H, d_k).transpose(1, 2)  # Shape: [B, H, N, d_k]
k = k.view(B, N, H, d_k).transpose(1, 2)  # Shape: [B, H, N, d_k]
v = v.view(B, N, H, d_v).transpose(1, 2)  # Shape: [B, H, N, d_v]

# Batched scaled dot-product attention across all heads simultaneously:
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)
if causal_mask is not None:
    scores = scores + causal_mask
attn_weights = torch.softmax(scores, dim=-1)
context = torch.matmul(attn_weights, v)  # Shape: [B, H, N, d_v]

# Recombine heads and apply output projection:
context = context.transpose(1, 2).contiguous().view(B, N, H * d_v)
output = self.w_o(context)  # Shape: [B, N, D]

3. Mechanistic Head Specialization

Research in mechanistic interpretability and natural language processing has uncovered how individual attention heads specialize during pre-training.

Positional, Syntactic, and Lexical Heads

In an empirical analysis of multi-head attention mechanisms, Voita et al. (2019) and Clark et al. (2019) demonstrated that attention heads naturally partition into specific functional categories:

  1. Positional Heads: Heads that consistently attend to fixed relative offsets (such as token i1i-1, token i+1i+1, or the initial sequence delimiter token <s> / [CLS]).
  2. Syntactic Heads: Heads that track grammatical relationships, such as pointing from direct objects to their governing verbs, or connecting noun modifiers to their head nouns.
  3. Coreference and Anaphora Heads: Heads that link pronouns (e.g., "it", "they", "she") to candidate antecedent noun phrases across multi-sentence contexts.
Syntactic Head (Verb -> Object):
  "The engineer [built] [the distributed cluster] yesterday"
                  ▲              │
                  └──────────────┘ (High attention weight)

Positional Head (Previous Token):
  "Large" <── "Language" <── "Models" <── "Scale"

Induction Heads and In-Context Learning

In A Mathematical Framework for Transformer Circuits (Anthropic, 2021), Elhage et al. showed that two-layer attention circuits form "induction heads."

An induction head detects sequence repetitions of the form [A][B] ... [A] and attends back to [B], copying it to complete the pattern. This two-step circuit consists of:

  • Layer 1 (Previous-Token Head): Writes information about token i1i-1 into the residual stream at position ii.
  • Layer 2 (Induction Head): Query vector at position jj (matching [A]) matches Key vector at position ii (which carries information that [A] was followed by [B]), routing Value [B] into the next-token prediction.

Induction heads represent the primary mechanistic driver behind in-context few-shot learning in large language models.

Head Redundancy and Pruning

Despite the necessity of multiple heads during training, research indicates substantial redundancy in trained models. Voita et al. (2019) demonstrated that applying L0L_0 regularization allowed pruning up to 80% of attention heads in machine translation models without significant BLEU score degradation.

However, multi-head diversity remains essential during optimization: having numerous parallel heads allows gradient descent to explore multiple functional sub-circuits simultaneously before settling into specialized configurations.


4. Computational and Memory Bottlenecks

While Multi-Head Attention enables expressive representational capacity, it introduces substantial computational and memory demands.

Computational Complexity

For a sequence of length NN and model dimension dmodeld_{\text{model}}:

| Operation | Flops Count per Layer | Computational Regime | | :--- | :--- | :--- | | Q, K, V Projections (3×XW3 \times X W) | 6Ndmodel26 N d_{\text{model}}^2 | Compute-bound (BLAS Level 3 GEMM) | | Attention Scores (QKTQ K^T) | 2N2dmodel2 N^2 d_{\text{model}} | Quadratic in sequence length NN | | Softmax Normalization | O(hN2)O(h N^2) | Memory bandwidth-bound | | Context Aggregation (AVA V) | 2N2dmodel2 N^2 d_{\text{model}} | Quadratic in sequence length NN | | Output Projection (WOW_O) | 2Ndmodel22 N d_{\text{model}}^2 | Compute-bound (BLAS Level 3 GEMM) |

In the prefill phase (processing long prompt sequences), the O(N2dmodel)O(N^2 d_{\text{model}}) quadratic scaling of QKTQ K^T and AVA V dominates execution time.

The KV Cache Memory Bottleneck

During autoregressive token-by-token generation (decoding phase), past Key and Value activations are cached in GPU High Bandwidth Memory (HBM) to avoid recomputing past representations at each generation step.

For a standard Multi-Head Attention model with LL layers, hh heads, head dimension dkd_k, and batch size BB, the KV cache memory footprint for a context of NN tokens is:

KV Cache Size=2×B×N×L×h×dk×BytesPerElement\text{KV Cache Size} = 2 \times B \times N \times L \times h \times d_k \times \text{BytesPerElement}

For a 70-billion parameter model (such as LLaMA-2 70B with L=80L=80, h=64h=64, dk=128d_k=128, FP16 precision):

  • Key cache per token: 80×64×128×2 bytes=1.31 MB80 \times 64 \times 128 \times 2 \text{ bytes} = 1.31 \text{ MB}
  • Value cache per token: 80×64×128×2 bytes=1.31 MB80 \times 64 \times 128 \times 2 \text{ bytes} = 1.31 \text{ MB}
  • Total KV cache per token: 2.62 MB2.62 \text{ MB} per sequence

At a sequence length of N=4096N = 4096 tokens and a batch size of B=32B = 32, the KV cache alone requires:

Memory=32×4096×2.62 MB343.4 GB of GPU VRAM\text{Memory} = 32 \times 4096 \times 2.62 \text{ MB} \approx 343.4 \text{ GB of GPU VRAM}

In autoregressive decoding, loading these large Key and Value matrices from HBM into GPU SRAM at every single token step causes the memory bandwidth of the GPU to saturate long before its compute ALUs reach capacity.


5. Architectural Evolutions: MHA, MQA, GQA, and MLA

To mitigate the memory bandwidth bottleneck of standard Multi-Head Attention in production serving, modern LLMs employ modified attention projection variants.

Multi-Head Attention (MHA)      Grouped-Query Attention (GQA)      Multi-Query Attention (MQA)
  Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8          Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8            Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8
  │  │  │  │  │  │  │  │           └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘            └───┬───┴───┬───┘
  K1 K2 K3 K4 K5 K6 K7 K8             K1      K2      K3      K4                    K1
  V1 V2 V3 V4 V5 V6 V7 V8             V1      V2      V3      V4                    V1
  (8 Query, 8 Key/Value)           (8 Query, 4 Key/Value Groups)       (8 Query, 1 Key/Value)

1. Multi-Query Attention (MQA)

Proposed by Shazeer (2019), Multi-Query Attention retains hh distinct Query heads but uses a single shared Key head and a single shared Value head (hkv=1h_{kv} = 1).

  • KV Cache Reduction: Reduces KV cache size and memory traffic by a factor of hh.
  • Trade-off: Can lead to minor quality degradation on complex reasoning and long-context retrieval tasks due to reduced Key/Value capacity.

2. Grouped-Query Attention (GQA)

Introduced by Ainslie et al. (2023), Grouped-Query Attention groups Query heads into gg partitions, with each partition sharing a single Key and Value head (1<g<h1 < g < h).

  • For example, in LLaMA-3 70B (h=64h=64 query heads, g=8g=8 KV groups), each group of 8 Query heads shares one Key head and one Value head.
  • KV Cache Reduction: Slashes KV cache memory footprint by an 8×8\times factor while matching the downstream task performance of full Multi-Head Attention. GQA has become the de facto standard for open-weight foundation models.

3. Multi-Head Latent Attention (MLA)

Pioneered in DeepSeek-V2 (2024) and DeepSeek-V3, Multi-Head Latent Attention compresses Key and Value projections into a shared low-rank latent vector cKVRdcc^{KV} \in \mathbb{R}^{d_c} (where dchdkd_c \ll h \cdot d_k) before caching:

  • Only the compressed latent vector is stored in the KV cache during generation.
  • During attention computation, the latent representation is uncompressed on-the-fly or mathematically folded into the Query projection matrix via matrix associativity, achieving extreme KV cache compression without sacrificing multi-head expressivity.

6. Summary Comparison

| Attention Variant | Query Heads (hqh_q) | Key/Value Heads (hkvh_{kv}) | KV Cache Memory per Token | Typical Adoption | | :--- | :--- | :--- | :--- | :--- | | Multi-Head Attention (MHA) | hh | hh | 2×L×h×dk2 \times L \times h \times d_k | Transformer (2017), GPT-3, LLaMA-1 | | Multi-Query Attention (MQA) | hh | 11 | 2×L×1×dk2 \times L \times 1 \times d_k | PaLM, StarCoder, Falcon | | Grouped-Query Attention (GQA) | hh | gg (1<g<h1 < g < h) | 2×L×g×dk2 \times L \times g \times d_k | LLaMA-2/3, Mistral, Gemma-2 | | Multi-Head Latent Attention (MLA) | hh | Low-rank compressed (dcd_c) | L×(dc+dR)L \times (d_c + d_{R}) | DeepSeek-V2, DeepSeek-V3 |

Multi-Head Attention remains the foundational mechanism that enabled Transformers to replace recurrent neural networks. By decoupling sequence routing across multiple parallel geometric subspaces, MHA provides the mathematical foundation upon which modern scaling laws, in-context learning circuits, and efficient serving architectures are built.


Sources

Written by

More to read

  • Fast Model Weight Loading in Production: Safetensors, Tensorizer, and Direct GPU Deserialization

    Fast Model Weight Loading in Production: Safetensors, Tensorizer, and Direct GPU Deserialization In modern large language model inference clusters, cold start latency is rarely bounded by GPU compute allocation. Instead, the operational bottleneck centers on storage I/O and weight deserialization. As foundation models scale from 70 billion to 405 billion parameters, raw weight footprints range from 140 GB to over 800 GB in standard 16-bit precision. On naive serving stacks, deserializing these

    1 min
  • Maximal Update Parametrization (muP): How Tensor Programs Enable Zero-Shot Hyperparameter Transfer in LLM Pre-Training

    Pre-training a frontier large language model requires hundreds of thousands of GPU hours and millions of dollars in compute. At that scale, traditional hyperparameter tuning is financially and operationally impossible: teams cannot sweep learning rates, weight initializations, or optimizer betas across multiple 70B parameter runs to find the loss minimum. Historically, practitioners relied on ad-hoc heuristic extrapolation or manual guesses from small runs, often leading to sub-optimal loss curv

    1 min
  • Apple Music Mandates AI Transparency Tags Across Tracks, Compositions, and Artwork

    Apple Music has notified record labels and distribution partners that it is introducing mandatory AI transparency tags across its ingestion pipeline, establishing visible indicators for synthetic audio and visual assets later this year. Under the updated ingestion specifications, content providers must declare when artificial intelligence tools have been used to generate a material portion of a release. Four-Tier Metadata Taxonomy The framework establishes distinct metadata flags across four

    1 min