Four Architectures for Long-Context Models: Principles, Costs, and Verification

    Long-context transformers face two compounding costs: quadratic prefill compute in standard softmax attention and linearly growing KV cache memory per layer. This article breaks down four major approaches to managing these costs—linear attention with the Delta rule, sparse indexing, index pooling, and latent KV compression—along with training-stability techniques that compose with all of them. It includes the core recurrences, complexity analysis, runnable NumPy reference implementations with English comments, and practical guidance on hybrid layer ratios, auxiliary indexer losses, and pooling block-size selection. A comparison table summarizes per-step decode cost, cache footprint, and primary risks for each design.

    Four Architectures for Long-Context Models: Principles, Costs, and Verification

    1. The Problem and Its Costs

    Standard softmax attention computes n² scores for a sequence of length n, so prefill compute grows quadratically with length. During inference, every layer must store a KV cache, and memory grows linearly with length. Together, these drive up time-to-first-token (TTFT) and reduce decoding throughput in long-context scenarios.

    The industry primarily reduces costs along three directions:

    1. Linearization: rewrite attention as a recurrence with a fixed-size state, making per-step cost independent of history length.
    2. Sparsification: let each query interact with only a small subset of historical positions, reducing the number of tokens actually involved in computation.
    3. Cache compression: compress KV representations into a smaller latent space, reducing per-token memory.

    Training-stability techniques (hyper-connections) are orthogonal to these three and can be combined with them. Before choosing an approach, first identify your bottleneck: is it prefill compute, decoding memory, or accurate long-range retrieval?

    Approach Per-step decode compute Cache per token per layer Primary risk
    Full attention O(n·d) 2·h·d_h values Memory and latency degrade with length
    Delta linear attention O(d_k·d_v), independent of n Fixed state, independent of n Weak exact retrieval; typically requires mixed full-attention layers
    Sparse indexing O(n·d_idx + k·d) Same as full attention Indexer misses critical positions
    Pooled indexing O(n/b·d_idx + m·b·d_idx + k·d) Same as full attention Block boundaries misaligned with semantic boundaries
    Latent KV compression Includes extra up-projection compute d_c plus small positional dimensions Up-projection overhead; complex positional handling

    Here h is the number of heads, d_h the per-head dimension, d the main attention dimension, d_idx the indexer dimension, k the number of sparsely selected positions, b the pooling block size, m the number of coarsely selected blocks, and d_c the latent dimension.

    2. Linear Attention and the Delta Rule

    2.1 Preliminaries

    Linear attention without softmax can be written as a recurrence:

    • State update: St = S{t-1} + v_t k_t^T
    • Output computation: o_t = S_t q_t

    This is the simplest form, and it assumes no softmax, no denominator normalization, a single head, and—initially—no positional encoding. Practical models usually replace the raw q and k with feature maps φ(·) and add a normalization term z_t (a running sum of φ(k)): o_t = S_t φ(q_t) / (z_t^T φ(q_t)). Linear attention is therefore not a drop-in replacement for standard attention; any substitution requires retraining and validation.

    In this formulation, the state S has a fixed size independent of sequence length. Its weakness is that it only accumulates and never removes old information. Old and new values associated with the same key add together, causing memory interference and degraded retrieval precision.

    2.2 The Delta Rule: Read Before Write

    The Delta rule reads out the old value associated with the current key before writing—pred = S·k—and then writes only “the new value minus the old value.” Old memory for the same key is thus corrected rather than accumulated.

    With a gating decay α_t and write strength β_t, the full recurrence is:

    St = α_t · S{t-1}(I − β_t k_t k_t^T) + α_t · β_t · v_t k_t^T

    Parameter constraints:

    • k_t: L2-normalized so that ‖k_t‖₂ = 1. Otherwise (I − β k k^T) may amplify the state.
    • β_t ∈ (0, 1): typically a sigmoid output. When β is too large, the contraction factor approaches or exceeds the stability boundary and the state oscillates.
    • α_t ∈ (0, 1): typically a sigmoid or exp(−softplus(·)). α near 1 means long memory; near 0 means fast forgetting.
    • I is the d_k×d_k identity matrix, and S has shape d_v×d_k.

    Below is a single-head, step-by-step recurrence implemented for illustration only—not a production implementation. It omits chunked parallelism, denominator normalization, and numerical-stability handling.

    1. import numpy as np
    2. def delta_linear_attention(q, k, v, alpha, beta):
    3. """
    4. Single-head, step-by-step illustrative implementation.
    5. Shapes: q, k: [T, d_k]; v: [T, d_v]; alpha, beta: [T]
    6. Conventions: k is L2-normalized; alpha, beta are in (0, 1)
    7. """
    8. T, d_k = k.shape
    9. assert np.allclose(np.linalg.norm(k, axis=-1), 1.0, atol=1e-5)
    10. assert np.all((alpha > 0) & (alpha < 1)) and np.all((beta > 0) & (beta < 1))
    11. S = np.zeros((v.shape[1], d_k))
    12. outputs = np.empty((T, v.shape[1]))
    13. for t in range(T):
    14. kt = k[t]
    15. pred = S @ kt # Read out the old value for the current key first
    16. S = alpha[t] * (S + beta[t] * np.outer(v[t] - pred, kt)) # Then write the correction
    17. outputs[t] = S @ q[t]
    18. return outputs

    2.3 Training and Hybrid Architectures

    Training cannot proceed step by step, or you lose the GPU’s ability to parallelize. The common approach is to split the sequence into chunks: compute in parallel within each chunk, passing only the state S across chunks. The chunk size C trades off throughput against numerical stability. When C is too large, the product of α within a chunk can easily underflow. During decoding at inference time, the recurrence runs directly with fixed per-step cost.

    How to choose the hybrid ratio: pure linear layers are generally weaker than full attention at exact retrieval, so in practice a full-attention layer is often retained every few layers. For example, one full-attention layer every four layers is a common starting point, not a universal optimum. When determining the ratio, fix total parameters and training tokens, vary only the ratio, then compare on long-context retrieval (such as needle-in-a-haystack), multi-hop reasoning, and long-document perplexity.

    3. Sparse Indexing: Select First, Compute Later

    3.1 Basic Flow

    The core of sparse attention is “select first, compute later.” For each query, a lightweight indexer first scores all historical positions and picks the top-k positions; the main attention then computes only against those k positions. The indexer uses a lower dimension d_idx and fewer heads, so each scoring pass costs far less than full attention.

    1. import numpy as np
    2. def softmax(x):
    3. x = x - x.max(axis=-1, keepdims=True)
    4. e = np.exp(x)
    5. return e / e.sum(axis=-1, keepdims=True)
    6. def top_k_indices(scores, k):
    7. """Return the k highest-scoring positions. argpartition does not guarantee order; sort if needed."""
    8. n = scores.shape[0]
    9. k = min(k, n)
    10. if k == 0:
    11. return np.empty(0, dtype=np.int64)
    12. return np.argpartition(-scores, k - 1)[:k]
    13. def sparse_attention_step(q, K, V, q_idx, K_idx, top_k):
    14. """
    15. Single decode step. q: [d]; K, V: [T, d]; q_idx: [d_idx]; K_idx: [T, d_idx]
    16. T is the currently visible history length, excluding future positions.
    17. """
    18. T = K.shape[0]
    19. if T == 0:
    20. raise ValueError("History is empty; attention cannot be computed")
    21. scores = K_idx @ q_idx # Lightweight scoring over the full history
    22. top = np.sort(top_k_indices(scores, top_k)) # Sorting aids debugging and reproducibility
    23. attn = softmax(K[top] @ q / np.sqrt(q.shape[-1]))
    24. return attn @ V[top]

    3.2 Complexity and Boundaries

    A single query must scan the entire history, so per-step decoding index cost is O(n·d_idx). During prefill over a full sequence, if every query performs indexing, total indexing cost is O(n²·d_idx). The main attention processes only k positions per query, at a cost of O(k·d).

    Sparse selection therefore does not change the quadratic order of growth. Its benefit is twofold: the indexer’s constant factor is far smaller than full attention (d_idx is much smaller than d), and during decoding the main attention cost is decoupled from n.

    Key implementation boundaries:

    • When k exceeds the history length T, clamp to min(k, T); otherwise argpartition raises an error.
    • During prefill, query t may only select keys at positions ≤ t. In practice, pass only K_idx[:t+1] to prevent future-information leakage.
    • Top-k is a discrete operation and cannot be differentiated directly.

    How to set the indexer’s auxiliary loss: during training, the indexer’s score distribution is often trained to approximate the main attention’s true weights. The target distribution comes from the main attention weights and requires a stop-gradient to avoid backpropagation from the indexer distorting the main attention. A common approach is to softmax over each query’s historical positions, compute KL divergence against the main attention weights, and add it to the total loss with a small coefficient. A coefficient that is too large degrades the main attention as it caters to the indexer; too small, and the indexer fails to learn the important positions.

    4. Index Pooling: Compressing the Index

    4.1 Why Pooling Is Needed

    In ultra-long contexts, even a lightweight indexer becomes a bottleneck when scanning token by token. Adjacent tokens are usually semantically related, so merging their index keys into block-level representations typically incurs limited information loss.

    After pooling, the coarse-selection stage scans n/b entries instead of n. With n = 131072 and b = 64, coarse selection scans only 2048 block-level keys. This is an arithmetic result, not a measured latency.

    4.2 Complete Two-Stage Selection Implementation

    The code below implements block-level coarse selection followed by within-block fine selection, and handles the final partially filled block. Pooling averages only over valid tokens—no zero padding—to avoid depressing the mean.

    1. import numpy as np
    2. def pool_index_keys(K_idx, block):
    3. """Mean-pool index keys within each block. The final partial block averages only valid tokens."""
    4. T, d = K_idx.shape
    5. n_blocks = -(-T // block) # Ceiling division
    6. block_id = np.arange(T) // block
    7. sums = np.zeros((n_blocks, d), dtype=K_idx.dtype)
    8. counts = np.zeros(n_blocks, dtype=K_idx.dtype)
    9. np.add.at(sums, block_id, K_idx)
    10. np.add.at(counts, block_id, 1)
    11. return sums / counts[:, None]
    12. def pooled_two_stage_select(q_idx, K_idx, block, top_blocks, top_k):
    13. """
    14. Returns the selected token positions (ascending).
    15. q_idx: [d_idx]; K_idx: [T, d_idx]
    16. block: block size b; top_blocks: number of coarsely selected blocks m; top_k: number of fine-selected tokens k
    17. During prefill, pass K_idx[:t+1] for query t to preserve causality.
    18. """
    19. T = K_idx.shape[0]
    20. if T == 0 or block < 1 or top_blocks < 1 or top_k < 1:
    21. raise ValueError("Invalid arguments")
    22. # Stage 1: coarse selection, scanning n/b blocks
    23. block_keys = pool_index_keys(K_idx, block) # [NB, d_idx]
    24. block_scores = block_keys @ q_idx
    25. m = min(top_blocks, block_scores.shape[0])
    26. chosen = np.argpartition(-block_scores, m - 1)[:m]
    27. # Expand to token positions; at most m * b candidates
    28. cand = np.concatenate([
    29. np.arange(b * block, min((b + 1) * block, T)) for b in chosen
    30. ])
    31. # Stage 2: fine selection within blocks
    32. tok_scores = K_idx[cand] @ q_idx
    33. k = min(top_k, cand.shape[0])
    34. pick = np.argpartition(-tok_scores, k - 1)[:k]
    35. return np.sort(cand[pick])
    36. def pooled_sparse_attend(q, K, V, sel):
    37. """Attend over the selected positions; softmax as in Section 3.1."""
    38. attn = softmax(K[sel] @ q / np.sqrt(q.shape[-1]))
    39. return attn @ V[sel]

    4.3 Risks and Checkpoints

    Pooling carries three main risks:

    • When the block size b is misaligned with semantic boundaries, a single block may span two unrelated segments; its mean vector gets diluted and coarse selection misses genuinely relevant blocks. Sweep b over values such as 16, 32, 64, and 128 in evaluation and monitor changes on long-range dependency tasks.
    • Padding or truncation changes block statistics. The implementation above mitigates this by averaging only over valid tokens, but any pipeline that pads or truncates sequences should re-check block statistics.