Understanding LLM Attention Variants: From MHA to GQA and SWA

    This article explores the core attention mechanisms used in modern Large Language Models (LLMs), specifically focusing on variants like MHA, MQA, GQA, and SWA. It explains how these variants differ in terms of KV cache memory consumption and context window size, provides a detailed breakdown of standard multi-head attention, offers a practical formula for estimating KV cache memory, and introduces methods for reducing memory overhead.

    Introduction

    Attention mechanisms are a core component of modern Large Language Models (LLMs). Developers often encounter abbreviations like MQA, GQA, and SWA when reading about model architectures, deploying inference, or selecting models. The differences between these variants primarily lie in two aspects: the VRAM consumption of the KV cache, and the context length each token can attend to. This article first reviews standard attention, then explains methods for reducing the KV cache and limiting the computation scope, and finally provides a practical memory estimation formula.

    1. From the RNN Bottleneck to Attention

    Before the advent of attention mechanisms, sequence-to-sequence tasks primarily relied on Recurrent Neural Networks (RNNs). The encoder compressed the source sentence into a fixed-length vector, and the decoder generated the translation word by word based solely on this vector. The longer the sentence, the greater the information loss during compression. For instance, when translating a long compound sentence, the subject referred to by a pronoun might be lost during compression.

    The attention mechanism allows the decoder to re-access all hidden states of the encoder’s output at each step and assign weights based on relevance. This approach mitigates the information bottleneck of a fixed vector and lays the foundation for the Transformer architecture.

    2. Standard Multi-Head Attention

    Self-attention computation involves three steps:

    1. Projection: The input sequence is multiplied by three learnable weight matrices to obtain the Query, Key, and Value.
    2. Relevance Calculation: The Query performs a dot product with all Keys, is divided by the square root of the Key dimension, and passed through Softmax to obtain attention weights.
    3. Information Aggregation: The attention weights are used to perform a weighted sum of the Values to get the output.

    The pseudocode is as follows:

    1. def self_attention(x, W_q, W_k, W_v, W_out):
    2. q = x @ W_q # Query vectors
    3. k = x @ W_k # Key vectors
    4. v = x @ W_v # Value vectors
    5. scores = q @ k.T / sqrt(d_k) # Scaled dot-product attention scores
    6. weights = softmax(scores, dim=-1) # Normalization
    7. out = weights @ v # Weighted sum
    8. return out @ W_out # Output projection

    Multi-Head Attention (MHA) divides the hidden dimension among h heads, with each head computing attention in an independent subspace. The outputs of all heads are concatenated and undergo a linear projection. Taking Llama-2-7B as an example, it has a hidden dimension of 4096, 32 heads, and a head dimension of 128. Different heads can learn different types of relationships, with some focusing on syntactic dependencies and others on semantic associations.

    During inference, the model must save the Keys and Values of historical tokens for each layer and each KV head. This data is called the KV cache. The KV cache grows linearly with sequence length, number of layers, number of KV heads, and batch size, making it one of the primary VRAM overheads in long-context inference.

    3. KV Cache Calculation Method

    The number of bytes for a single-layer KV cache can be estimated using the following formula:

    Single-layer KV cache bytes = 2 × n_kv_heads × head_dim × seq_len × bytes_per_element

    Here, 2 represents storing both K and V; n_kv_heads is the number of KV heads; head_dim is the dimension of each head; seq_len is the sequence length; and bytes_per_element is 2 for fp16 or bf16, and 4 for fp32. The full model cache equals the single-layer cache multiplied by the number of layers and the batch size.

    The table below is calculated with 4096 tokens, fp16 precision, and a batch size of 1. Configurations are based on public models; please refer to the official configurations of each model for accurate accounting.

    Example Config Layers Query Heads KV Heads Single-layer KV Cache Full Model KV Cache
    Llama-2-7B (MHA) 32 32 32 64 MiB 2 GiB
    Llama-3-8B (GQA) 32 32 8 16 MiB 512 MiB
    Same config with MQA (Assumed) 32 32 1 2 MiB 64 MiB

    These numbers only include the KV cache and do not account for model weights, activations, or framework overhead.

    The difference becomes more pronounced with long contexts. Using the Llama-3-8B configuration as an example, the KV cache occupied per token across the full model is 2 × 8 × 128 × 2 × 32 = 131072 bytes, or 128 KiB. Processing a single sequence of 128K tokens requires approximately 16 GiB. If the same model used MHA (32 KV heads), a sequence of the same length would require approximately 64 GiB.

    4. Reducing KV Cache: MQA and GQA

    Multi-Query Attention (MQA) allows all query heads to share the same set of Keys and Values. The KV cache is reduced to 1/h of MHA, where h is the number of query heads. For the 32 query heads in the table above, the MQA KV cache is 1/32 of MHA. The reduction in KV parameters also limits the model’s expressive power, often leading to more noticeable quality degradation in tasks that require distinguishing multiple semantic roles. Grouped-Query Attention (GQA) divides the query heads into g groups