Behind Long Context: How Attention, Residuals, and Optimizers Work Together

    Long context is costly first because the key-value cache grows with sequence length and must be read at every new token. This article explains that memory and bandwidth bottleneck, compares multi-head, multi-query, and grouped-query attention, and outlines how residual normalization and AdamW optimizer state affect training stability and GPU memory.

    Where the Long-Context Bottleneck Is

    When a large language model generates text, each new token requires reading the keys and values of all previous tokens—the key-value cache (KV cache). Longer sequences use more GPU memory for that cache and move more data at every step. Long-context cost therefore shows up first as pressure on memory capacity and memory bandwidth.

    KV-cache size can be estimated as:

    1. KV cache bytes = 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element

    The formula counts only the cache and assumes each element uses a fixed number of bytes. The factor of 2 accounts for storing both keys and values. Real memory use also includes model weights, activations, fragmentation, and framework overhead, so the result is only a lower-bound reference.

    The following estimate is hypothetical. The parameters are chosen for easy calculation and do not match any specific model: 32 layers, head dimension 128, sequence length 1 million tokens, and 2 bytes per element (BF16).

    • With 8 KV heads, the cache is about 1.31×10^11 bytes, or 131 GB in decimal units (1 GB = 10^9 bytes), about 122 GiB in binary units (1 GiB = 2^30 bytes).
    • With 64 KV heads, the cache is about 1.05×10^12 bytes, or 1.05 TB, about 977 GiB.

    Both figures are theoretical values for a single sequence. Under the same other parameters, raising the KV-head count from 8 to 64 multiplies the cache by 8. KV-head count therefore directly sets cache size, but only if layers, head dimension, sequence length, and bytes per element stay fixed. Changing any of those changes the result. Attention structure is the first lever for reducing long-context cost.

    Attention Structure: MHA, MQA, and GQA

    How Multi-Head Attention Uses Cache

    Standard multi-head attention (MHA) keeps separate queries (Q), keys (K), and values (V) for each head. Heads can learn different attention patterns, which usually improves expressiveness. Cache size scales with the number of heads, so memory pressure is highest on long sequences.

    What Multi-Query Attention Saves, and What It Costs

    Multi-query attention (MQA) shares one set of K and V across all query heads. Cache size falls to 1/H of MHA, where H is the number of query heads, and each decoding step reads less data. The cost is fewer distinct attention patterns, so quality can drop on some tasks. How much it drops depends on model scale and task type and has to be measured.

    How Grouped-Query Attention Balances Quality and Cache

    Grouped-query attention (GQA) splits query heads into groups, and each group shares one set of K and V. The group count G is a tunable parameter. When G equals the query-head count H, the structure reduces to MHA. When G equals 1, it reduces to MQA. Cache size scales with G, so an intermediate G lands between the two extremes.

    With 32 query heads and 8 groups, each group has 4 query heads and the KV cache is one quarter of MHA. Intermediate settings like this are common in practice because they balance quality and cache size. The group count should be chosen by comparing results on the target tasks, not from the cache-savings ratio alone.

    Design KV heads Relative cache size (MHA = 1) Quality risk Typical use Implementation complexity
    MHA Equal to query heads H 1 Lowest Short context, quality first Low
    GQA G groups, 1 < G < H G/H Moderate, rising as G falls Medium to long context, general deployment Medium
    MQA 1 1/H Higher and task-dependent Decode throughput first, when some quality loss is acceptable Low

    Residual Paths: A Stable Base for Deep Training

    A residual connection adds a layer’s input to its output. Gradients can skip some nonlinear transforms on the way back, which is why deep networks can be trained. Long-context models have many layers and a wide attention span, so residual design directly affects training stability.

    Two common normalization placements are:

    • Pre-Norm: normalization is applied before the sublayer. Training is usually more stable and the gradient path is smoother, but the numeric range of deep outputs can keep growing, so activation scale needs attention.
    • Post-Norm: normalization is applied after the residual add. It can work better in some settings, but deep training depends more on learning-rate warmup and initialization.

    In practice, track activation norms by layer, record peak gradient norms, and scale residual-branch outputs when needed. Whether to change the residual structure should follow the training curves and long-context evaluation results, not a default recipe.

    Optimizer Changes: Balancing Stability and Memory

    AdamW is a common baseline for large-model training. It keeps a first-moment and a second-moment state for every parameter, both usually stored in FP32. In mixed-precision training, each parameter also needs an FP32 master weight. Under that common setup, each parameter uses about 12 bytes: 4 bytes for the master weight and 4 bytes for each of the two moments. Larger models therefore spend more memory on optimizer state.

    A common engineering direction is to reduce the memory used by optimizer state.