KDA Hybrid Linear Attention: Breaking the Quadratic Bottleneck in Long Context

    This article explains KDA hybrid linear attention for long-context large language models. It covers why full attention incurs quadratic compute and memory costs, how KDA uses fixed-size state, gated incremental updates, diagonal gating, and block-level processing, and why it is combined with attention residual structures rather than replacing all standard attention. It also examines engineering considerations such as fused kernels, reduced KV cache pressure, and prefix state reuse, along with applications in long-horizon programming, complex reasoning, and knowledge work.

    1. Why Long Context Requires a Different Attention Mechanism

    The full attention mechanism in a standard Transformer can be described with a concise formula:

    1. Attention(Q, K, V) = softmax(QK^T / sqrt(d)) V

    When the sequence length is L, each layer must compute an L×L attention matrix, and both computation and memory usage are close to O(L²). If the context window is extended to 1 million tokens, no full-attention layer can directly bear this cost. Even with various memory optimization techniques, the complexity remains superlinear, and hardware growth can hardly keep pace with the demand for longer context.

    The problem is equally prominent during inference, not only during training. Traditional models must maintain a KV cache that grows with sequence length. Each time a new token is generated, the full cache must be read. The longer the context, the slower the decoding speed and the lower the throughput. A large amount of compute is spent on “moving historical information” rather than actually generating new content.

    As a result, the industry began to explore linear attention. By introducing feature mappings or state compression, linear attention rewrites the mechanism in which “every token must look at the entire history” into “maintain a fixed-size historical state and perform only a state update at each step.” Ideally, computational complexity can be reduced from O(L²) to O(L), and the KV cache no longer grows indefinitely with length.

    However, simple linear attention often pays a price in accuracy: it may not be able to precisely “point to” a few key tokens in the same way standard attention does. Hybrid designs therefore became a more practical route: some layers continue to use standard attention, while other layers use linear attention. KDA is a representative implementation in this direction.

    2. Core Design of KDA: Stateful, Gated, and Parallelizable

    KDA is essentially a hybrid linear attention mechanism. Its goal is not simply to compress history, but to preserve long-distance information while making state updates more controllable and hardware execution more efficient.

    2.1 Fixed-Size State and Incremental Write-Back

    In linear attention, historical information is compressed into a fixed-size state tensor. KDA follows a similar idea in this respect, but instead of simply accumulating new Key/Value pairs into the state, it uses incremental updates:

    1. The state update can be abstracted as:
    2. S_t = Gate_t ⊙ S_{t-1} + Delta_t

    Here, Gate represents the gating that retains or forgets old information, and Delta represents the new information written into the state by the current token. This “incremental write-back” approach avoids the continuous accumulation of similar Keys and enables more effective use of state capacity. The model can continuously absorb new information over long contexts without allowing old information to expand without limit.

    2.2 Diagonal Gating: More Fine-Grained Forgetting Control

    KDA makes an important improvement in gating design. Traditional gating is sometimes a global scalar, meaning all feature dimensions share the same forgetting coefficient. KDA instead adopts fine-grained diagonal gating. “Diagonal” means that the gating matrix is a diagonal matrix, so each feature dimension can independently control its own retention ratio.

    The benefit of this design is intuitive: different dimensions may carry different types of information, some dimensions need to be remembered for a long time, while others need to be forgotten quickly. Through per-channel gating, the model can achieve a more detailed balance between “retaining important context” and “suppressing irrelevant noise.” At the same time, the additional computation of the diagonal matrix is small and does not significantly increase training or inference cost.

    2.3 Block-Level Processing: Making Long Sequences GPU-Friendly

    If linear attention updates state token by token in a serial manner, it is not friendly to GPUs. KDA chooses a hardware-efficient block processing algorithm:

    1. # Illustrative pseudocode: block-level hybrid linear attention
    2. def kda_forward(q, k, v, state, gate):
    3. outputs = []
    4. for block_start in range(0, seq_len, block_size):
    5. qb = q[block_start:block_start + block_size]
    6. kb = k[block_start:block_start + block_size]
    7. vb = v[block_start:block_start + block_size]
    8. # Local attention within the block: capture relationships among tokens in the current block
    9. local_out = local_attention(qb, kb, vb)
    10. # Historical state output: read compressed memory in a linear manner
    11. history_out = query_state(qb, state)
    12. # The current block output fuses local information and historical information
    13. outputs.append(local_out + history_out)
    14. # State update: update the historical state using the current block
    15. state = update_state(state, kb, vb, gate)
    16. return outputs, state

    Block processing reduces the serial dependency from “once per token” to “once per block.” Within a block, matrix multiplication and tensor cores can be used for parallel computation, and only a fixed-size state needs to be passed between blocks. This preserves the efficiency advantages of linear attention while allowing long-sequence prefill to truly run fast on hardware.

    3. Hybrid Architecture: Not Replacing Everything with Linear Attention

    KDA is usually not the only attention mechanism in a model. A more reasonable approach is to let KDA and attention residual structures jointly form the model backbone.

    This hybrid architecture can be understood as two pathways:

    • KDA is responsible for long-distance global information compression. It uses a fixed state to carry the “summary memory” of the entire context, so the model does not need to rescan the full history at every step.
    • Attention residual structures retain the precise matching capability of standard attention. Some layers still compute exact interactions between tokens to capture information that requires point-to-point alignment, such as code variable references, document references, and local syntax.

    With this division of labor, the architecture avoids both the quadratic overhead of full attention in ultra-long contexts and the possible loss of detail caused by pure linear attention.

    In the practice of a large model with 2.8 trillion total parameters, native visual understanding, and a context window of 1 million tokens, KDA and attention residual structures together form a workable architectural backbone. For multimodal scenarios, visual tokens and text tokens are concatenated and likewise produce ultra-long sequences. Hybrid linear attention can reduce the additional computational pressure brought by visual context while retaining sensitivity to details in key regions.

    4. Engineering Deployment: From Algorithmic Gains to Real Throughput

    Lower algorithmic complexity is only the first step. What ultimately determines production benefits is kernel implementation, inference engine adaptation, and deployment strategy.

    4.1 High-Performance Kernels: Accelerating Prefill

    In linear attention, if state updates, gating computation, and output projection are executed separately, they introduce a large number of intermediate tensors and kernel launch overhead. KDA’s accompanying high-performance kernels typically fuse these operations into a more compact computation flow: when computing matrix multiplication within a block, gating and state write-back are completed at the same time, avoiding repeated reads and writes to memory.

    In publicly available engineering comparisons, such fused kernels can improve prefill speed by approximately 1.72× to 2.22× relative to an unoptimized baseline on specific accelerator cards. This number shows that algorithmic gains must be translated into real throughput through carefully designed kernels.

    4.2 Decoding: Less KV Cache Pressure

    In long-context decoding, the KV cache of a traditional full-attention model grows linearly with the number of tokens. The linear attention layers in KDA do not need to maintain a KV cache that grows with length; instead, they maintain a fixed-size state. Only some full-attention layers in the model still need to cache KV.

    As a result, the overall cache growth rate slows significantly as context length increases. The serving side can allocate more memory to concurrent requests and improve batched decoding capacity. For scenarios such as long documents, large code repositories, and multi-turn conversations, this memory benefit directly translates into lower latency and higher throughput.

    4.3 Prefix State Reuse

    KDA also enables a practical deployment approach: for the same long document, if a user asks repeated questions, the document can first be processed into a fixed state, and each subsequent question can continue decoding from that state without reprocessing the entire document. This reduces repeated computation cost and makes interactive long-context applications more economical.

    Mainstream inference frameworks have already adapted corresponding kernel implementations, indicating that this type of architecture has moved from papers to real services. When choosing a long-context solution, developers should focus not only on window length, but also on whether the underlying attention mechanism truly reduces the inference cost of ultra-long sequences.

    5. Key Application Scenarios

    5.1 Long-Horizon Programming

    Large software repositories contain thousands of files, build scripts, historical commits, and dependencies. Intelligent programming tools need to understand repository-level context to accurately perform cross-file refactoring, bug localization, and code generation. KDA can compress repository-level historical information into state while using residual attention to handle precise symbol references in the current file, allowing the model to balance global understanding and local accuracy in long-horizon programming tasks.

    5.2 Complex Reasoning

    Complex reasoning tasks often require reading a large amount of evidence and then deriving conclusions step by step. If all evidence must be rescanned for every reasoning step, the cost becomes very high. KDA’s linear state can continuously preserve information that needs long-term dependency in the reasoning chain, while a small number of full-attention layers are responsible for precisely verifying details at key steps. This division of labor allows the model to maintain near-linear computational overhead over longer contexts.

    5.3 Knowledge Work

    Fields such as law, finance, and research frequently require processing long contracts, annual reports, research papers, and meeting notes. Users want the model to “read all the material before answering,” but such inputs often far exceed the processing capacity of ordinary models. Hybrid linear attention makes ultra-long inputs affordable, which also means knowledge workers can obtain more complete and reliable answers instead of being forced to truncate materials or ask questions in repeated segments.

    6. Conclusion

    The core value of hybrid linear attention mechanisms such as KDA is that they move the cost of long-sequence attention from approximately quadratic toward approximately linear. Through fixed state, fine-grained gating, and block-level parallelism, they alleviate the compute and memory bottlenecks of full attention in ultra-long contexts. Through a hybrid architecture, they retain the precise matching capability of standard attention and avoid sacrificing quality for efficiency.

    For developers, understanding this type of mechanism helps with more reasonable technical decisions: focus on whether a model truly has linear scaling capability, whether the kernel layer has been adapted to hardware, and whether the KV cache is actually compressed during deployment. Long context is not just a number for “window size”; it is a system capability spanning algorithms and engineering.