KDA Hybrid Linear Attention: Linearizing Long-Context Inference

    This article examines KDA (Kimi Delta Attention) as a representative hybrid linear attention design for long-context LLM inference. It explains why full attention becomes expensive, how KDA’s recursive state update and per-channel gating work, how chunked parallel execution preserves mathematical equivalence, why a small number of full-attention layers are retained for exact retrieval, and how to estimate KV cache and state memory. It also covers production metrics and a comparison table for choosing among full, sliding-window, pure linear, and hybrid linear attention.

    The cost of long-context inference mainly comes from two places: the quadratic computation of standard attention and the KV cache that grows with sequence length. Hybrid linear attention takes a different approach: most layers use a fixed-size state instead of an attention matrix, while a small number of full-attention layers are kept for exact retrieval. KDA (Kimi Delta Attention) is a representative of this approach. The following sections explain its method across four parts—principles, algorithm, memory, and selection—along with the numbers that need to be checked before deployment.

    Why Standard Attention Struggles with Long Contexts

    Transformer self-attention computes an N×N attention matrix for a sequence of length N, with O(N²) computational complexity. When context expands from tens of thousands of tokens to millions of tokens, the overhead shows up in three main areas.

    First, computation during prefill grows quadratically with sequence length, so first-token latency for long documents becomes noticeably longer. Second, during decoding, the key-value vectors for all historical tokens must be cached, and memory usage is proportional to sequence length. Under long contexts, the KV cache often exhausts memory before compute does. Third, each generated token requires reading all historical KV, so decoding throughput drops as context grows.

    Methods such as sliding windows, sparse attention, KV quantization, and compression can reduce the burden in some dimensions, but they do not change the scale of the attention matrix or the rule that the KV cache grows with N. Linear attention starts from another direction: it maintains a fixed-size state through recursive updates, making the per-token processing cost independent of history length and reducing total complexity to O(N).

    How to Read KDA’s Recursive Update Formula

    At the core of KDA is an incremental state update. Let the key vector k_t belong to R^{d_k}, the value vector v_t belong to R^{d_v}, the state matrix S_t belong to R^{d_k×d_v}, and β_t be a scalar in (0, 1) representing the strength of the current write. The update rule is:

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

    Here α_t belongs to R^{d_k} and is a per-channel forget gate, described in detail in the next section. Readers can understand this expression as three steps: first use (I − β_t k_t k_t^T) to erase old content in the state that is aligned with the current key direction, then write the new key-value association β_t k_t v_t^T. If k_t is L2-normalized, the strength of the erase operation is controlled by β_t, which is more numerically stable.

    For readout, use the query vector q_t belonging to R^{d_k} to compute the output o_t = S_t^T q_t, where o_t belongs to R^{d_v}. Throughout the process, the size of the state matrix remains d_k×d_v, independent of sequence length.

    How Per-Channel Gating Differs from Gated DeltaNet

    Gated DeltaNet uses a scalar forget gate α_t for each attention head, so all state channels within the same head share the same retention rate. This is simple to implement, but it is difficult to balance long-term memory and local detail at the same time.

    KDA extends the forget gate to a per-channel vector αt. Diag(α_t) acts on the left side of S{t−1}, so the i-th element of α_t controls only the retention ratio of the i-th row of the state matrix, corresponding to the i-th key channel. The practical effect is that some channels have α close to 1 and are responsible for long-term information storage, while some channels have smaller α and are responsible for quickly updating local content. The model can learn this division of labor during training.

    The cost of this improvement is increased parameters and computation: gating needs to be stored and computed per channel. Whether it is worth it depends on the target task’s requirements for long-range memory and local precision.

    How a Chunked Parallel Algorithm Speeds Up Linear Attention

    Token-by-token recursive updates cannot fully utilize GPU parallelism. A common approach is to split the sequence into fixed-length chunks, usually 64 or 128, with the exact value depending on the implementation.

    Within a chunk, matrix algebra identities are used to expand the recurrence into a set of matrix operations, allowing the entire chunk to be processed at once with tensor-core matrix multiplication. Between chunks, execution remains serial: the state at the end of the previous chunk is passed as the initial state for the next chunk. This “parallel within chunks, recurrent across chunks” structure is mathematically equivalent to token-by-token recurrence and does not change the model’s output definition.

    Numerical stability needs separate handling. Forget gates are multiplied repeatedly across the sequence, and direct cumulative multiplication can easily underflow. Implementations usually accumulate gates in the log domain, use fp32 for state accumulation and reduction, and may use bf16 for matrix multiplication. These details affect precision, and before deployment the output should be compared layer by layer with the reference implementation.

    Why Keep a Few Full-Attention Layers?

    Pure linear attention compresses the entire history into a fixed-size state and cannot losslessly retrieve content at a specific position. This gives it a natural weakness on needle-in-a-haystack exact retrieval tasks, such as precisely copying a code snippet or a number from a million tokens.

    A hybrid architecture lets most layers use linear attention to handle long-range information compression, then inserts a small number of full-attention layers for exact retrieval. The ratio of linear layers to full-attention layers is a hyperparameter that needs tuning. The specific ratio should follow the model’s official technical report; configurations from other models should not be applied directly.

    How to Estimate the KV Cache

    Estimating the KV cache before deployment can help avoid running out of memory after launch. The KV cache size for full-attention layers can be estimated with the following formula:

    M_kv = 2 × L_full × H_kv × d_head × N × b × B

    Here L_full is the number of full-attention layers, H_kv is the number of KV heads, d_head is the dimension per head, N is sequence length, b is the number of bytes per element (2 for bf16), and B is batch size. The coefficient 2 means that both K and V are stored.

    The state size of linear layers is independent of N:

    M_state = L_lin × H × d_k × d_v × b_state × B

    Consider a hypothetical configuration: 48 layers in total, 8 KV heads, head dimension 128, bf16 storage, sequence length 1 million, and batch size 1. If all 48 layers are full attention, the KV cache is about 196.6 GB. If 1 in every 4 layers is full attention—that is, 12 full-attention layers and 36 linear layers—the KV cache for the full-attention portion drops to about 49.2 GB. For linear-layer state, assuming 128×128 per head, fp32 storage, and 8 heads, the total is about 18.9 MB, far smaller than the former.

    This example only illustrates the order of magnitude. Real models have different layer counts, head counts, and storage precision, so actual configurations should be used in the calculation.

    Which Metrics Matter in Production Deployment

    Linear attention operators need to be designed for the GPU memory hierarchy. Kernel fusion can reduce the number of times intermediate results are written back to memory, which is often the main source of prefill speedup. On heterogeneous hardware platforms, state-update and chunked-scan operators often need to be reimplemented and tuned, and they must work together with the inference framework’s cache management.

    Inference framework integration is equally important. New operators need to enter mainstream inference engines and support prefill and decode scheduling, batching, and paged KV cache management. When a model is open-sourced, operator implementations are usually provided as well, making it easier for the community to reproduce deployment.

    When evaluating performance, it is recommended to record the following metrics together: prefill throughput, decode throughput, peak memory, KV cache footprint, and comparison with a standard attention baseline at the same sequence length. Each number should specify model scale, sequence length, hardware model, precision, and measurement method. A speedup without these conditions can only be used as a reference and cannot be directly used for cost estimation.

    When to Choose a Hybrid Linear Architecture

    The table below summarizes the rough trade-offs among four types of approaches. The judgment is based on common business workloads, and specific results need to be validated with your own data.

    Approach Compute complexity KV cache growth Exact retrieval capability Suitable scenarios
    Standard full attention O(N²) Grows linearly with N Strong Short context, high retrieval accuracy requirements
    Sliding-window attention O(N·w) within the window Discarded outside the window Cannot retrieve outside the window Mainly local dependencies
    Pure linear attention O(N) Fixed size Weak Long-range compression, low exact retrieval requirements
    Hybrid linear attention Near O(N) Only full-attention layers grow Relatively strong Very long documents, repository-level context

    In practice, when context length reaches tens of thousands of tokens and the workload frequently processes long documents or code repositories, hybrid linear architectures show clear advantages in cost and latency. If the main task is exact question answering within a few thousand tokens, standard attention is usually simpler.

    Mixed linear architectures also have clear failure scenarios.