Inferensys

Glossary

QK Circuit

The computational pathway formed by the query and key projection matrices that determines which previous tokens an attention head attends to by computing attention scores.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
ATTENTION MECHANISM

What is QK Circuit?

The QK circuit is the computational pathway formed by the query and key projection matrices that determines which previous tokens an attention head attends to by computing attention scores.

A QK circuit is the computational subgraph within a transformer attention head formed by the query (W_Q) and key (W_K) weight matrices. Its sole function is to compute the raw attention score between a destination token and a source token by taking the dot product of the query vector and the key vector, determining where the head should attend in the preceding context.

Mechanistic interpretability decomposes an attention head into two independent half-circuits: the QK circuit for attention pattern formation and the OV circuit for information copying. The QK circuit's behavior is often analyzed using singular value decomposition (SVD) to identify the principal token-matching patterns, such as copying or induction, encoded in the product of the two weight matrices.

MECHANISTIC INTERPRETABILITY

Core Characteristics of QK Circuits

The QK circuit is the computational pathway formed by the query (W_Q) and key (W_K) projection matrices. It determines the attention pattern by computing the dot-product similarity between the query vector of the current token and the key vectors of all previous tokens, dictating which positions the head attends to.

01

The Attention Score Computation

The QK circuit's primary function is to compute the raw attention logits. For a destination token d and source token s, the score is calculated as:

  • Formula: (x_d * W_Q) · (x_s * W_K)^T
  • This dot product measures the semantic relevance of the source token to the destination token's query.
  • The resulting scores are scaled by 1/√d_k and passed through a softmax function to produce the final attention weights.
  • This mechanism allows the head to implement behaviors like copying, attending to syntax, or focusing on specific entities.
O(n²)
Computational Complexity
02

Bilinear Form and Low-Rank Structure

The QK interaction is a bilinear form governed by the matrix W_QK = W_Q^T * W_K. Key properties include:

  • Rank Analysis: The rank of W_QK is bounded by min(d_head, d_model). A low effective rank indicates the head is only sensitive to a few feature directions.
  • Singular Value Decomposition (SVD): Decomposing W_QK reveals the principal query-key directions that dominate the attention pattern.
  • Split-Head View: The circuit can be analyzed by examining the W_Q and W_K matrices directly, or by studying the composite W_QK matrix for the head's overall matching function.
03

Interaction with Positional Encoding

The QK circuit integrates positional information to control which relative distances the head attends to:

  • Rotary Position Embedding (RoPE): Applies a rotation to the query and key vectors based on their absolute positions. The dot product then depends only on the relative position d - s.
  • Absolute Positional Encodings: Added to the input embeddings before the QK projection, allowing the head to learn to attend to specific absolute locations.
  • Attention Sinks: The QK circuit often assigns very high scores to the initial tokens (e.g., the BOS token), creating an 'attention sink' that absorbs excess probability mass.
04

Causal Masking and Autoregressive Constraint

In decoder-only transformers, the QK circuit operates under a strict causal constraint:

  • Causal Mask: A mask sets all attention scores for s > d to negative infinity before the softmax, ensuring the model cannot attend to future tokens.
  • Information Bottleneck: The QK circuit is the gatekeeper of information flow. It can only route information from the past, making its learned patterns critical for in-context learning and sequence modeling.
  • Efficient Implementation: The causal mask is often fused with the softmax kernel in optimized implementations like FlashAttention to reduce memory I/O.
05

Circuit Analysis and Intervention

Mechanistic interpretability uses causal interventions to understand QK circuits:

  • Activation Patching: Replacing the QK attention scores of a specific head with scores from a corrupted or different forward pass to isolate its functional role.
  • Path Patching: A refined technique that isolates the direct effect of the QK circuit from one layer to another, bypassing intermediate computations.
  • Causal Scrubbing: Formally tests hypotheses about a QK circuit by resampling activations and verifying if the circuit's proposed function is faithful to the model's behavior under all resampled conditions.
06

Grouped Query Attention (GQA) and KV Cache

The QK circuit's design directly impacts inference efficiency through the KV cache:

  • KV Cache: During autoregressive generation, the key vectors for all previous tokens are cached to avoid recomputation. The QK circuit only computes the query for the new token and scores it against the cached keys.
  • Grouped Query Attention (GQA): Uses fewer key-value heads than query heads. Multiple query heads share a single key head, reducing the KV cache size while preserving most of the quality.
  • Multi-Query Attention (MQA): An extreme case of GQA where all query heads share a single key-value head, maximizing cache reduction at a small cost to model capability.
QK CIRCUIT DEEP DIVE

Frequently Asked Questions

Explore the fundamental mechanics of how transformer attention heads decide which tokens to attend to through the query-key interaction pathway.

A QK circuit is the computational pathway formed by the query (Q) and key (K) projection matrices within a transformer attention head that computes attention scores to determine which previous tokens the head attends to. The circuit operates by projecting the current token's residual stream state through the W_Q matrix to form a query vector, and projecting all previous tokens through the W_K matrix to form key vectors. The dot product Q · K^T produces raw attention logits, which are then softmax-normalized into attention weights. This mechanism effectively implements a content-based lookup table, where the query encodes "what information am I looking for?" and the keys encode "what information do I contain?" The QK circuit is the sole determinant of attention patterns—it decides where to attend, while the separate OV circuit determines what information is copied from the attended positions.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.