LLM Attention Mechanisms: From Principles to Engineering Selection

    This article explains how attention works in large language models and how major variants differ in access scope, key-value sharing, and state representation. It covers self-attention computation, causal masking, multi-head attention, KV cache sizing, MQA and GQA, sliding window attention, latent compression, linear attention, selection criteria, and a reproducible validation workflow for engineering teams.

    1. Understanding Attention: Start With the Information Access Bottleneck

    Early sequence generation models typically updated hidden states step by step in input order, and a decoder generated outputs from those states. If input information mainly depends on fixed-capacity state passing, then as text grows longer, distant entities, conditions, and semantic relationships become harder to preserve completely.

    Consider technical documentation question answering. A user question may depend on a term definition at the beginning of the document, configuration constraints in the middle, and exception notes at the end. Compressing this information into a single summary can easily omit key details. Attention offers another path: when generating the representation for the current position, the model can perform a weighted read over accessible input positions according to the current need.

    It is important to note that attention is not an exact keyword search, nor does it guarantee that all facts will be found automatically. It is a learnable information aggregation mechanism whose effectiveness depends on training data, parameter learning, context organization, and positional modeling.

    Modern attention variants can be understood through three questions:

    1. Which positions can each query access?
    2. Do different attention heads share keys and values?
    3. In what form is historical information stored and read?

    These questions correspond to three optimization directions: access scope, cross-head sharing, and state compression.

    2. How Self-Attention Is Computed

    2.1 What Roles Do Queries, Keys, and Values Play?

    Let the input representation be a matrix X, where each row corresponds to the vector representation of a token. Three learnable projections produce queries, keys, and values:

    Q = XW_Q
    K = XW_K
    V = XW_V

    The query Q represents what information the current position needs. The key K provides features used to match each position. The value V is the content that actually participates in aggregation after matching.

    Standard scaled dot-product attention can be written as:

    Attention(Q, K, V) = softmax(QK^T / sqrt(d_k) + M)V

    Here, d_k is the dimension of the key vector, and M is the attention mask. For inaccessible positions, a sufficiently large negative value is usually added before normalization so that their attention weights are close to zero.

    Dividing by sqrt(d_k) controls the numerical scale of the dot product. This avoids overly large score magnitudes as the vector dimension increases, which could otherwise make the normalized result too concentrated and destabilize gradients.

    2.2 Self-Attention and Causal Attention Are Not the Same Classification Dimension

    Self-attention describes a setting where queries, keys, and values come from the same sequence. Causal attention describes a visibility constraint between positions.

    In autoregressive generation, position t can access only the current position and earlier information, not future positions. Otherwise, the model would use information during training that does not exist at inference time, causing information leakage.

    Therefore, autoregressive models commonly use “self-attention with a causal mask.” In tasks that allow bidirectional understanding, self-attention can also let each position access the entire input sequence.

    This distinction matters for implementation and testing: correct projection logic does not imply correct mask logic.

    3. Multi-Head Attention: A Basic Way to Increase Expressiveness

    Multi-head attention, or MHA, splits attention computation across multiple representation subspaces and runs them in parallel. Each head uses different projection parameters to produce independent queries, keys, and values. The outputs of all heads are then concatenated and fused through an output projection.

    One way to understand this is that the same text is reorganized into a richer contextual representation through multiple sets of information-matching rules.

    Different heads may exhibit different attention patterns, but it is not accurate to assume that one head is always responsible for syntax and another for facts. The actual division of work usually depends on the model, layer, training process, and input content, and there is often overlap and redundancy.

    Standard MHA is characterized by independent keys and values for each head. It is flexible in expression, but inference requires caching more historical state. As context length and concurrent requests increase, cache capacity and read bandwidth become important costs.

    For a sequence of length n, full attention must consider pairwise relationships between positions. With a fixed head dimension, attention computation grows with n². If the full attention matrix is stored explicitly, the associated intermediate storage also grows with n². Optimized implementations can reduce the actual storage and memory traffic of intermediate matrices, but this does not mean the theoretical computation of full attention has become linear.

    Autoregressive generation is usually divided into two phases.

    The first phase is prefill: the model processes the existing prompt text at once and establishes historical key-value state for each layer. The second phase is decode: the model generates one new token at a time, computes the query, key, and value for the new position, and reads the already stored historical keys and values.

    The KV cache avoids recomputing projections for all historical positions at every step, but the cache size grows with sequence length.

    Under simplified conditions where all layers have the same configuration and keys and values have the same dimension, the cache size can be estimated as:

    Cache bytes ≈ 2 × L × B × T × H_kv × D × S

    Where:

    • L is the number of layers;
    • B is the batch size;
    • T is the cached sequence length;
    • H_kv is the number of key-value heads;
    • D is the dimension of each key-value head;
    • S is the number of bytes per element;
    • The coefficient 2 corresponds to the two cache types: keys and values.

    For example, purely as a calculation example, assume a model has 32 layers, batch size 1, cache length 8192, 8 key-value heads, head dimension 128, and 2 bytes per element. The KV cache is then approximately 1 GiB.

    This estimate does not include model weights, temporary activations, cache allocation overhead, or runtime workspace. Actual GPU memory usage is also affected by parallel partitioning, cache data type, request scheduling, and memory layout.

    5. Multi-Query and Grouped-Query Attention: Reducing Duplicate Storage Across Heads

    5.1 Multi-Query Attention

    Multi-query attention, or MQA, keeps multiple query heads but lets them share one set of keys and values.

    Compared with standard MHA, this structure significantly reduces the number of key-value heads, thereby lowering cache capacity and the amount of historical state that must be read. Its main benefit usually appears in long-sequence decoding, where historical cache must be accessed repeatedly.

    The tradeoff is reduced freedom in key and value representations. Whether this affects task quality cannot be inferred from architecture alone; it must be validated with training results and the target task.

    5.2 Grouped-Query Attention

    Grouped-query attention, or GQA, provides a compromise between MHA and MQA: query heads are divided into groups, heads in the same group share keys and values, and different groups use different keys and values.

    If the number of query heads is H_q and the number of key-value heads is H_kv, then in common uniform grouping implementations, H_q must be divisible by H_kv.

    When H_kv = H_q, GQA reduces to standard MHA. When H_kv = 1, it corresponds to MQA.

    With other configurations held constant, cache size is roughly proportional to H_kv. Therefore, reducing the number of key-value heads can directly reduce cache capacity. However, overall throughput is also affected by operator efficiency, memory bandwidth, batch size, and scheduling strategy. The cache reduction ratio should not be treated directly as an end-to-end speedup ratio.

    6. Sliding Window Attention: Limiting the Context Range Read at Each Step

    Sliding window attention lets each position access only a nearby span of context. In causal generation, it usually allows access only to a limited number of positions before the current position.

    If the window size is w and the implementation can skip computation outside the window, the attention computation can drop from O(n²) for full attention to O(nw).

    This approach is suitable for scenarios that rely heavily on local context, such as understanding adjacent sentences, local code completion, and processing continuous paragraphs. However, a local window limits the ability of a single layer to directly access distant information.

    Stacking multiple layers can expand the range of indirect information propagation, but this layer-by-layer passing is not equivalent to allowing any position to directly read the full text. For condition matching across long distances, exact citations, and long-document evidence integration, it is important to check whether the window limit causes information loss.

    A common approach is to combine local attention with global attention: some layers handle low-cost local aggregation, while other layers handle long-distance interaction.

    Whether the cache can be truncated with the window also needs separate judgment. Only when later computation truly no longer uses earlier state, and the implementation supports safe eviction, can the relevant cache be released. If global attention layers or other historical access paths still exist, all early states cannot be uniformly deleted.

    7. Latent Representation Compression: Changing How Historical State Is Stored

    Another type of optimization does not reduce visible positions but compresses the historical information that must be stored. The core idea is to map key-value-related information into a lower-dimensional latent representation, which then participates in attention computation through corresponding projections during generation.

    Compared with the cross-head sharing in GQA, this type of method changes the cache representation more directly. It can potentially reduce the storage required per historical token, but it also makes the computation graph, positional handling, and operator implementation more complex.

    Engineering evaluation should consider:

    • Whether the latent representation dimension brings sufficient cache savings;
    • Whether extra projection computation offsets bandwidth gains;
    • Whether positional encoding requires separately retained state;
    • Whether the decoding implementation can avoid repeatedly expanding large intermediate representations;
    • Whether low-precision storage amplifies errors after compression.

    Therefore, this is not a generic capability obtained by simply compressing the cache of an existing model. It usually requires co-design of model architecture, training method, and inference implementation.

    8. Linear Attention: Reducing Long-Sequence Cost Through Different Aggregation

    Linear attention is an umbrella term for a class of methods. Some approaches use feature mappings, associativity reordering, or recurrent state updates to avoid explicitly constructing the full pairwise position interaction matrix.

    Under specific assumptions, these methods can reduce computation or storage costs related to sequence length, making them especially suitable for streaming processing and very long sequences.

    However, “linear attention” does not mean “fully equivalent to standard normalized attention with no cost.” Different methods may change the similarity function, normalization method, or form of historical information storage.

    If historical content is aggregated into a fixed-capacity state, the model must retain useful information within a limited state. This may affect the ability to precisely retrieve specific distant details. Whether it suits a business use case should be judged through tests involving long-range dependencies, repeated interference, and exact citations, not merely by comparing complexity formulas.

    9. Distinguish Optimization Goals Before Selection

    These attention approaches are not alternatives on the same dimension:

    • MHA, MQA, and GQA mainly change the sharing relationship between query heads and key-value heads;
    • Sliding window attention mainly changes the range of visible positions;
    • Latent representation compression mainly changes the representation form of cache content;
    • Linear attention mainly changes information aggregation and computation.

    Some of these approaches can be combined. For example, grouped-query attention can coexist with sliding window attention. To judge whether a combination is reasonable, it is necessary to check quality, cache capacity, operator support, and long-distance access requirements together.

    If the workload is mainly short text with low concurrency, complex cache optimization may not be the first priority. If the workload is mainly long input, high concurrency, and continuous generation, priority should be given to KV cache, decoding bandwidth, and scheduling efficiency. If the workload depends on cross-document evidence integration, the importance of global access should not be ignored simply because local attention is cheaper.

    10. Build a Reproducible Engineering Validation Process

    10.1 Validate Correctness First

    Before an attention optimization goes live, compare full-sequence computation with step-by-step cached decoding to confirm that results agree within a reasonable numerical error.

    Focus on checking:

    • Whether the causal mask leaks future information;
    • Whether padding positions are correctly masked;
    • Whether grouped-query head mapping is correct;
    • Whether cache position indices are continuous;
    • Whether state crosstalk occurs between different requests;
    • Whether there are offset errors at window boundaries;
    • Whether fully masked positions are handled stably.

    These issues often cause real failures more easily than the formulas themselves.

    10.2 Evaluate Prefill and Decode Separately

    The prefill phase is more affected by long-sequence computation, while the decode phase is often affected by cache reads and batching behavior.

    Evaluation should cover at least time to first token, subsequent generation latency, throughput, peak memory usage, and task quality. Input length, output length, concurrency, data type, and hardware conditions should be kept consistent; otherwise, attribution becomes difficult.

    10.3 Validate Real Task Quality at the Same Time

    Test sets should include distant fact retrieval, cross-paragraph condition composition, repeated-information interference, long code dependencies, and multi-turn history references.

    It should also be noted that long-context degradation may not all come from attention structure. It may also be related to positional encoding, training length distribution, and data quality. Engineering analysis needs to separate variables and avoid attributing every problem to a particular attention approach.

    11. Conclusion

    The evolution of modern attention mechanisms is essentially about finding a balance among expressiveness, historical information access, computation cost, and storage cost.

    Multi-head attention provides flexible parallel representations; multi-query and grouped-query attention reduce KV cache; sliding window attention controls access range; latent representation compression changes how historical state is stored; and linear attention explores lower-cost information aggregation paths.

    For developers, the most important thing is not to memorize all variant names, but to answer three engineering questions: Does the business need direct access to distant information? Is the system bottleneck mainly computation or cache? And does the optimized system still meet quality requirements? Using these three questions as the main line is how attention mechanisms can move from an architectural concept to a verifiable, deployable technical choice.