Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

AI Infra Advanced: 30,000 Words to Deeply Understand Linear Attention Mechanisms

This comprehensive guide explores the evolution of linear attention from basic linear attention to KDA. It provides an in-depth analysis of RNN state updates, forget gates, residual writes, and how AI infrastructure converts nonlinear gating into affine transformations to enable chunk-wise parallelism while balancing model expressiveness and hardware efficiency.

linear attentionlinear attention mechanismKDARNN state updateforget gate

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original Link: https://mp.weixin.qq.com/s/O0_v8wz4iHxbk...

Tencent Programmer · WeChat Public Account · Tencent Technology Engineering · 2026-10-29 17:27

📌 This article is a reprint. Copyright belongs to the original author. The full text is subject to the original link.

Author: binnnliu

Introduction: This is not a popular science article. If you truly want to understand how large language models perform reasoning, this piece is absolutely worth reading.

Lately I’ve become somewhat obsessed with studying AI Infra — to the point where I’ve almost forgotten to eat or sleep. Driven by intense curiosity, I want to truly understand “why” at every step.

However, as you know, why large language models are able to exhibit emergent reasoning and thinking capabilities remains largely unexplainable. This is still very much an experimental science — the “It just works” at the fundamental principle level of large models.

Not long ago, mathematician Terence Tao posed a question in his Math 2.0 talk at Caltech: If an AI-developed new cancer drug passes Phase III clinical trials, should we require that at least one human expert fully understands its pharmacological mechanism before administering it to patients? His intention was to warn about the risks of uninterpretable black boxes, yet it drew widespread mockery. After all, medicine has long had many treatments whose efficacy was discovered first, with the underlying mechanisms understood only later. This is the “It just works” at the AI application level.

Fortunately, the foundational infrastructure supporting large language models — the AI Infra domain — including operator implementation and optimization, memory allocation, and GPU architecture scheduling, is all built upon rigorous mathematical and physical logic.

The core topic of this article, the evolution of linear attention mechanisms, spans both layers. At the model level, how to design forget gates and residual writes (from DeltaNet and GDN to KDA) belongs to hypothesis-driven experimental science. At the AI Infra level, in order to balance model expressiveness with the computational throughput of chunk-wise parallelism, complex nonlinear RNN gating must be rigorously derived into affine transformations and lower-triangular matrix solving. In the end, architecture design is a continuous trade-off among algebraic structure, algorithmic expressiveness, and hardware memory access costs.

Background

The inference process of large language models (LLMs) is divided into two stages: Prefill and Decode. Have you ever wondered which stage has higher hardware utilization?

The answer is clearly Prefill. Prefill is compute-intensive, while Decode is memory-intensive. Prefill can fully leverage the GPU’s computational power and is therefore more efficient. But why exactly?

The essence of Prefill is batching: by packing multiple tokens into matrix multiplications (GEMM), it increases arithmetic intensity and amortizes the cost of loading model weights from GPU memory. Is this statement correct? Yes, but it is incomplete — it fails to mention KV Cache, which is precisely what makes LLM inference fundamentally different from other inference workloads.

We know that during LLM inference, the data stored in GPU memory mainly falls into three categories: model weights (fixed size), KV Cache (linearly growing, O(N)), and activations.

The high utilization of Prefill comes not only from multiple tokens reusing the same model weights, but also from multiple Query (Q) heads within the same request reusing the same batch of Key/Value (K/V) tiles. What about Decode? For every single token generated, the GPU must load the entire set of model weights from HBM once; even worse, it must also load all historical KV Cache accumulated in memory once. This causes the compute units to sit idle, waiting on memory accesses.

Is it possible to amortize costs during the Decode phase? vLLM introduced Continuous Batching, which shifts batching from the request dimension to the token dimension. This allows a single weight load to serve tokens from different requests. The introduction of PagedAttention was to ensure that when processing at the token level, memory allocation for KV Cache can also be done at the token level. Otherwise, allocating KV Cache for each request according to its max_length at the very beginning would cause severe memory fragmentation and waste.

Apart from shared prefixes, the contexts of different requests are isolated from each other, each maintaining its own independent KV Cache. This means Continuous Batching can only help amortize model weight loading for Linear and FFN layers, but provides no benefit for the Attention layer in terms of reading historical KV Cache.

Speculative Decoding partially solves the KV Cache memory access overhead during single-request decoding. Its essence is to convert Decode into a tiny Prefill.

The above discussion holds when context lengths are short. However, in the current era of AI agents with contexts often reaching millions of tokens, three major problems emerge:

  1. KV Cache memory usage grows linearly with context length → Memory capacity bottleneck;
  2. Every Decode step requires loading all historical KV Cache from memory to compute units → Memory bandwidth bottleneck;
  3. Computational cost grows linearly with context length → Compute bottleneck.

Today, most model architecture innovations are aimed at solving the above three problems. The industry currently has three main approaches:

  1. Sparse Attention (DSA/SWA);
  2. Compressed Attention mechanisms (Multi-head Latent Attention / Latent Compression Attention);
  3. Linear Attention mechanisms.

Most of China’s top open-source models — except for DeepSeek and Tencent’s Hy — adopt a Hybrid architecture combining Linear Attention with Full/Sparse Attention. Therefore, I believe it is necessary to take a deep dive into Linear Attention.

Of course, there are other techniques as well, such as KV Cache quantization, cross-layer KV Cache sharing (DeepSeek V4.1 Flash CED), IndexCache for cross-layer reuse (Hy4 Preview), and Hierarchical Sparse Indexer.

From Linear Attention to KDA: The Evolutionary Path

Since the core bottleneck of autoregressive decoding lies in the linear growth of the KV Cache, a natural idea emerges: Can we merge all historical K and V into a single fixed-size state, so that an incoming Query no longer has to laboriously iterate over every past token, but can interact directly with this O(1) state? This is essentially the RNN paradigm.

All forms of linear attention share the same core idea: compress the entire historical context into a fixed-size state matrix ( S \in \mathbb{R}^{d_v \times d_k} ). During decoding, the output is simply read out with ( o = Sq ), achieving memory usage, read cost, and computation that are constant (O(1)) with respect to sequence length — the constant being ( O(d_v \cdot d_k) ). However, a fixed capacity also means new knowledge constantly overwrites old knowledge. The evolution of linear attention essentially revolves around how to update this fixed-capacity state. To better understand KDA (Kimi Delta Attention), we need to zoom out and examine how the state update mechanism has progressed step by step.

Standard Linear Attention

(Based on Transformers are RNNs, ICML 2020)

In standard Softmax attention, the output for the i-th token is computed as follows (scaling factor omitted):

During autoregressive decoding, the core pain point is that Softmax — i.e., ( \exp(q_t^\top k_j) ) — is a nonlinear operation. You must first compute the full attention score matrix between Q and all K before multiplying by all V. (Note: This is from a logical perspective; in practice, FlashAttention can compute this via online softmax + kernel fusion without fully materializing the score matrix.) This means all historical K and V must be retained, causing the KV Cache to grow linearly with context length.

The idea behind linear attention is to replace Softmax with a feature mapping function ( \phi(\cdot) ) (e.g., ( \text{elu}(x) + 1 )) that can be applied independently to Q and K. The formula then becomes a continuous matrix multiplication:

Since ( \phi(q_i)^\top \phi(k_j) ) is a scalar and equals ( \phi(k_j)^\top \phi(q_i) ), we can leverage the associativity of matrix multiplication. We first accumulate the outer product of historical values and mapped keys, then right-multiply by the mapped query:

At this point, the part inside the summation is a fixed state independent of Q. We define:

  • Memory matrix: ( S_i = \sum_{j=1}^i v_j \phi(k_j)^\top )
  • Normalization term: ( Z_i = \sum_{j=1}^i \phi(k_j) )

No matter how long the sequence i grows, the dimensions of states ( S_i ) and ( Z_i ) remain fixed. Each step only requires an additive update based on the previous state. The final readout formula at step t becomes:

Removing the Denominator and Introducing Convolution

The paper The Devil in Linear Transformer observed that the denominator ( \phi(q_t)^\top Z_t ) can become very small, leading to unstable gradients during training. The authors proposed simply removing the denominator and applying normalization at the output of the attention layer.

To avoid the unbounded gradients, we introduce NORMATTENTION, which gets rid of scaling over attention matrices while appending an additional normalization only after the attention layer. The choice of the normalization operator is unrestricted, for example, LayerNorm (Ba et al., 2016) or RMSNorm (Zhang and Sennrich, 2019) both serve the purpose.

Once the denominator is removed, the requirement that ( \phi ) must always be positive (to ensure the output with a denominator remains a valid weighted average) is eliminated. Without the denominator, the output becomes a simple linear combination ( \sum_j w_j v_j ). Negative weights simply mean subtracting the corresponding value, removing the previous restriction.

Linear attention compresses historical context into a fixed-size state. While this avoids accessing each historical token individually, it can also lose fine-grained details during compression—especially when stronger modeling of local neighboring tokens is required. To address this, architectures such as DeltaNet, GDN, and KDA add a one-dimensional causal short convolution (Causal Conv1d) on the projected q/k/v. They first fuse information from a few nearby tokens before performing the global state update and read. This design pattern—“convolution supplements local information, linear attention aggregates global history”—has become a common architectural choice in this family of models.

Don’t be intimidated by the word “convolution” 😓. In simple terms, it is just a per-channel, fixed-weight sliding window weighted sum applied separately to q, k, and v. Both sliding-window attention and short convolution aggregate local information, but attention computes weights dynamically based on content, whereas short convolution uses fixed weights learned during training.

Convolution output = SiLU(
    qkv of token t-3 * conv_weight[:, 0]
  + qkv of token t-2 * conv_weight[:, 1]
  + qkv of token t-1 * conv_weight[:, 2]
  + qkv of current token * conv_weight[:, 3]
)

Therefore, during normal decoding, each request only needs to keep the most recent conv_kernel−1 qkv vectors before the convolution. The convolution output itself is not written into conv_state. The cache pool has shape [num_cache_slots, 3 × num_heads × head_dim, conv_kernel−1], and each request locates its own slot through a cache index.

The papers H3 and Mamba introduced the convolution: H3 mixes the most recent few tokens using a shift SSM, while Mamba formalizes it as a causal conv1d (kernel=4) followed by SiLU. In 2024, Yang et al. applied this technique to delta-rule linear attention in DeltaNet and added L2 normalization on q and k (replacing the sum normalization used by Schlag et al. in 2021). This combination effectively replaces the original φ mapping. Subsequent architectures such as GDN and KDA all adopted the same approach. The role of L2 norm is explained in the DeltaNet section.

Once the denominator is removed and the nonlinear mapping φ is replaced by the preceding convolution plus L2 Norm, the update and read operations on the global memory state naturally simplify to a pure accumulation form:

That is, S ← S + v k^T. This means that once the outer product accumulation for the current v_t and k_t is completed, they can be discarded immediately. There is no need to retain them as per-token historical records. Subsequent reads depend only on the state matrix, eliminating the need for a full KV Cache that grows with context length. The preceding short convolution still maintains its own fixed-length buffer of pre-convolution qkv inputs.

New values are added directly on top of previous predictions. Writing the same key twice yields the sum of the two values. With no forgetting mechanism, incorrectly written or outdated information is indiscriminately stuffed into this fixed-capacity memory, causing the memory to saturate quickly and potentially leading to numerical explosion.

DeltaNet: Write Gate and Residual Write

(Based on Linear Transformers Are Secretly Fast Weight Programmers, ICML 2021 and Parallelizing Linear Transformers with the Delta Rule over Sequence Length, NeurIPS 2024)

The delta-rule form of linear attention was first proposed by Schlag et al. (2021), but it could only be trained token-by-token in a serial manner. Yang et al. (2024) used the WY representation to compress the chained product I−β_i k_i k_i^T into a low-rank form, designing a chunk-parallel algorithm. This enables DeltaNet to be trained efficiently and scaled to large model sizes. At the same time, they established the modern architectural template of short convolution + SiLU + L2 norm.

Linear attention can only accumulate. The core idea of DeltaNet is: before writing, first use the current key to query what is already stored in the state, and only write the difference between what you want to store and what is already there.

DeltaNet: Residual Write with Write Gate

St-1kt is the value read from the old state using kt, representing the information already present in the previous state regarding the current token. Therefore, vt - St-1kt is the residual to be written. DeltaNet introduces a write gate βt = σ(·) ∈ (0,1) (a scalar per head, computed from the hidden state) that scales this residual before writing it:

Rewriting it in right-multiplication form makes it easier to see what it does to the state:

The core of this formulation lies in the transition matrix I - βt kt ktT. Because kt is L2-normalized, this matrix ensures that the old state can only shrink or stay the same during propagation (i.e., the old state is smoothly contracted by a factor of (1-βt) along the direction of the current kt, while remaining unchanged in all orthogonal directions). This prevents the state explosion that often occurs in traditional linear attention when Key norms become excessively large.

The limitation of DeltaNet is that the current update only preserves directions orthogonal to kt, but these directions do not necessarily correspond to individual feature channels. If certain relevant directions go unupdated for a long time, outdated associations may persist, increasing memory interference. Additionally, it lacks an active forgetting mechanism that is independent of the current key overwrite.

GDN: Introducing a Forget Gate

(Based on Gated Delta Networks, 2024)

The forget gate concept did not originate with GDN. RetNet, 2023 used a fixed per-head decay factor, Mamba2, 2024 used a scalar per head that varies with the input, and GLA, 2023 used a per-key-channel decay that also varies with the input. GDN’s contribution is to combine the Mamba2-style scalar gate with the Delta rule while preserving the validity of chunk-parallel algorithms. The later KDA extends this idea by combining the GLA-style per-channel gate with the Delta rule.

Before applying the Delta rule write, GDN first multiplies the entire state matrix by a scalar forget gate αt ∈ (0,1) (one scalar per head, broadcast across all rows and columns):

This causes all memories across the entire state matrix (in every direction) to decay uniformly by αt, after which the Delta rule write from the previous section is applied.

The issue here is that all feature channels within the same head must share the same forgetting rate αt. This means that regardless of how important the corresponding content is, every step shrinks it by the same proportion. In other words, the expressive power of the forget gate is somewhat limited. So, can we replace the scalar αt with a dk-dimensional vector?

KDA: Per-Channel Forget Gate

(Proposed by Moonshot AI in Kimi Linear, 2025; GLM-5.3-Flash also adopts KDA)

KDA retains the residual overwrite mechanism but elevates the forget gate from a scalar to a dk-dimensional vector. Right-multiplying the state matrix by the diagonal matrix Diag(αt) gives each j-th channel its own dedicated forgetting rate αt,j:

Thus, the forget gate expands from GDN’s num_heads parameters to KDA’s num_heads × head_dim.

You might be wondering: since we can evolve the forgetting dimension from per-head scalars to per-head-channel vectors, could we take it even further to a per-element level in the S matrix? That is, let the forget gate become a full matrix αt ∈ ℝ^{dv × dk} and perform element-wise decay S̄t = St-1 ⊙ αt. Wouldn’t that maximize expressiveness?

The answer is that it’s not that we don’t want to — it’s a trade-off between expressiveness and parallel efficiency. The algebraic structure determines the upper bound of parallelism, while hardware cost defines the boundary of expressiveness. Although element-wise independent forgetting is mathematically definable, the number of gate values per head per token would increase from head_dim to head_dim_v × head_dim_k, incurring significantly higher costs in gate generation and memory I/O. More importantly, when forgetting is applied per key channel, all value rows share the same right-multiplication transition. The overall update still maintains a diagonal-plus-rank-one correction structure, which allows for efficient block-parallel algorithms. Arbitrary element-wise forgetting usually breaks this shared structure and can no longer directly benefit from the same algorithmic advantages. We will discuss this in detail later.

Mechanism ① Decay ② Write Forgetting Granularity Per-Token Gate Shape
Linear Attention $\bar{S}t = S{t-1}$ $S_t = \bar{S}_t + v_t k_t^\top$ None No gates
DeltaNet $\bar{S}t = S{t-1}$ $S_t = \bar{S}_t + \beta_t (v_t - \bar{S}_t k_t) k_t^\top$ None $\beta$ [num_heads]
GLA $\bar{S}t = S{t-1} \operatorname{Diag}(\alpha_t)$ Same as Linear Attention Per-head, per-key-channel $\alpha$ [num_heads, head_dim]
GDN $\bar{S}t = \alpha_t S{t-1}$ Same as DeltaNet One scalar per head $\beta$ and $\alpha$ each [num_heads]
KDA $\bar{S}t = S{t-1} \operatorname{Diag}(\alpha_t)$ Same as DeltaNet Per-head, per-key-channel (i.e., each column of $S$) $\beta$ [num_heads]; $\alpha$ [num_heads, head_dim]

Side Note: The RWKV Path
RWKV does not fall into any of the four categories above. RWKV-6 already performs per-channel decay, but its write operation remains $S \leftarrow S \operatorname{Diag}(w) + v k^\top$, so new and old values on the same key continue to accumulate. In contrast, GDN uses a single scalar decay per head but performs residual overwrite along the $k$ dimension. KDA combines both ideas: the overwrite comes from DeltaNet, while the per-channel forgetting comes from splitting the scalar $\alpha$ in GDN into a per-channel vector. RWKV-7 also adopts a diagonal-plus-rank-one transition, but the key used for erasure can differ from the key used for writing — that is a separate evolutionary branch.

Understanding KDA: A Scientific Hypothesis

The previous section summarized the update formula into KDA. Taking the KDA used in GLM-5.3-Flash as an example, we now examine how the state is maintained, how forgetting and overwriting occur, and how training and Prefill can be parallelized.

In KDA, every layer and every head of each request maintains a fixed-size matrix — the global memory state $S_t$ — dedicated to storing contextual information for all tokens in the current request.

During the forward pass of each KDA layer, the model uses the current token’s hidden state and the corresponding weights to linearly project and compute the query vector $q_t$ for information retrieval, the addressing key $k_t$, the content-bearing value $v_t$, as well as the forget gate $\alpha_t$, write gate $\beta_t$, and output gate $\gamma_t$ that control memory updates. The following operations are then performed:

Where:

  • Forget Gate — $S_{t-1} \operatorname{Diag}(\alpha_t)$
    Determines which information from the previous hidden state $S_{t-1}$ should be retained and which should be forgotten.

  • Write Gate — $\beta_t v_t k_t^\top$
    New knowledge provided by the current token, ready to be written into the state matrix.

  • Delta Rule Correction — $-\beta_t S_{t-1} (\alpha_t \odot k_t) k_t^\top$
    Subtracts the portion of the decayed historical state that matches the current $k_t$ pattern. This prevents duplicate writes of the same feature, avoids numerical explosion caused by repeated accumulation of identical features in long contexts, and gives the state matrix the ability to perform precise overwriting.

Limitations of the RNN Paradigm

If the KDA path proves viable, the three core problems mentioned earlier — memory capacity, memory bandwidth, and compute scaling linearly with context length — would all be solved.

However, as we all know, RNNs have a troubled history; otherwise Transformers would never have emerged. The classic problems of RNNs are:

Fixed-size state — how can it remember an ever-growing history?

All history is compressed into a fixed-size matrix, which inevitably leads to lossy compression and information loss. As the context grows longer, new tokens continuously overwrite and wash away the old state. This causes the model to easily forget information when handling long-context “needle-in-a-haystack” tasks or when it needs to recall specific details precisely, resulting in degraded exact-recall capability.

Gating mechanisms and Delta Rule updates can improve how information is selected and written, but they cannot give a fixed-size state infinite capacity. A natural compromise is a Hybrid architecture: let linear layers handle low-cost historical aggregation, while Full/Sparse Attention layers retain more direct access to historical information.

PS: As long as full attention layers that require complete historical KV are retained, the KV Cache of those layers will still grow linearly with context length. Sparse attention only reduces memory access volume; all KV pairs are still stored. There are also techniques such as Sliding Window Attention, Compressed Sparse Attention, and cross-layer KV Cache sharing, but these are outside the scope of this article.

Recursive dependencies along the time dimension prevent parallel computation, making it impossible to fully utilize compute resources. How can training and Prefill be performed efficiently?

Temporal / Causal Parallelism

Classic RNN

The update rule for a classic RNN is:

Even when x₁, x₂, x₃ are all known, computation still proceeds sequentially as h₀ → h₁ → h₂ → h₃. While all Wₓxₜ terms can be precomputed in batch, computing Wh₂ requires h₂ first — it cannot be obtained directly from the known x₃ alone.

Unrolling two steps makes this even clearer:

Classic RNNs embed nonlinearity into the recurrent state feedback loop. This makes state transitions difficult to merge efficiently, preventing effective parallelization along the time dimension.

Transformer Attention Parallelism

Consider a given layer where all input representations X have already been computed by the previous layer:

Softmax is computed row-wise, where M is the causal mask: allowed positions are 0, future positions are -∞.

The output at position t for causal attention is:

Notice on the right-hand side: we have qₜ, kⱼ, vⱼ, but no oₜ₋₁. Therefore, computing o₃ does not require knowing o₁ or o₂ — each row can start computation simultaneously.

Although softmax is nonlinear, it does not prevent row-wise parallelism because it does not create a feedback chain from “previous position’s output in this layer” to “next position’s output in this layer.” The FFN, normalization, and residual connections in a standard Transformer also do not introduce such position-wise recurrence.

This is the key difference from classic RNNs:

  • RNN: The next position reads the recurrent state that was just computed at the previous position in the same layer.
  • Attention: Every position reads projections that are generated from the current layer’s inputs and are already fully prepared.

As a result, attention computation for all Queries can be scheduled in parallel. While softmax is nonlinear, it does not establish a recurrent chain from “output at previous position in this layer” to “output at next position in this layer.”

The causal mask only restricts which information is allowed to be read; it does not dictate the order in which positions must be executed. In practice, kernels can be computed in blocks without explicitly materializing the full T×T matrix, while still preserving the opportunity for parallelism across positions.

Linear Attention Chunk-Wise

Returning to KDA, let the state matrix Sₜ ∈ ℝ^{dᵥ×dₖ}, with kₜ ∈ ℝ^{dₖ}, vₜ ∈ ℝ^{dᵥ} as column vectors, and βₜ as a scalar. We start from the original KDA state update formula:

In matrix form, αₜ ⊙ kₜ is equivalent to Diag(αₜ)kₜ. We merge the terms involving the old state Sₜ₋₁ and factor out the common parts:

After merging, we obtain this crucial expression:

where Tₜ is the decay-and-correction transformation matrix for the memory state, and Hₜ is the raw incremental matrix contributed by the current token (pure increment before residual).

This transformation is critical: although KDA involves complex nonlinear gating, forgetting, and error correction, once the coefficients formed by kₜ, vₜ, αₜ, and βₜ are fixed at the current step, the update from the old state Sₜ₋₁ to the new state Sₜ becomes an affine transformation. More importantly, both Tₜ and Hₜ can be prepared from the current layer’s already-known inputs without waiting for the preceding recurrent state Sₜ₋₁ to finish. In other words: preparation can be fully parallelized, while state is passed sequentially between chunks.

Strictly speaking, in mathematics y = Ax is a linear transformation, while y = Ax + b is an affine transformation. Since our formula is Sₜ = Sₜ₋₁Tₜ + Hₜ (with an extra Hₜ term), we refer to it as an affine transformation.

Given that a chunk contains C tokens, the state at the end of the chunk can be written as:

Here Transition₍chunk₎ represents the state transition across the entire chunk, and Δ₍chunk₎ represents the intra-chunk increment independent of the incoming state. The raw write of a single token is still denoted as Hₜ. With this formulation, we can compute Transition₍chunk₎ and Δ₍chunk₎ for every chunk in parallel, then merge the results for each block in sequential order.

Chunkwise Implementation (Unified with C=64)

The following discussion assumes a unified chunk size of C=64, executed in three distinct stages:

Stage Main Work Dependencies Between Chunks
1. Intra-chunk Precomputation Prepare decay coefficients, reorganize intra-chunk residual dependencies into a lower-triangular system, and compute auxiliary matrices independent of the incoming state (intra-chunk parallelism will be explained later) Different chunks can be fully parallelized
2. Inter-chunk State Passing Correct residuals using the chunk’s incoming state, update the state at the end of the chunk, and save data required for the output stage Within the same request, chunks must be processed sequentially
3. Intra-chunk Output Using the prepared initial state of the chunk and the actual residuals, compute the output for each token Different chunks can be fully parallelized

Stage 2 derives its parallelism from the number of requests, the number of heads, and blocking along the V dimension; it still preserves the sequential recurrence between chunks. Stages 1 and 3 can exploit parallelism along the sequence dimension. The parallelism here operates at two levels — inter-chunk and intra-chunk:

  • Macro-level parallelism: State updates are composable affine transformations. We can compute the Transition chunk and Δ chunk for every chunk in parallel.
  • Micro-level parallelism: The intra-chunk residual recurrence is rewritten as a lower-triangular system that can be solved via matrix operations.

The following sections will explain the logic of intra-chunk parallelism, derive the auxiliary matrices involved, and show how a large portion of the intra-chunk computation can be transformed into matrix multiplications.

Projection and gating may contain nonlinearities. The key point is not whether the entire model is linear, but how the recurrent state enters the next update and whether the update coefficients can be prepared independently of that recurrent state.

Rope vs. Nope

In practice, this parallelism comes at a cost. The state recurrence of an RNN is inherently order-sensitive: swapping the positions of two tokens changes the state they pass through and all subsequent computations. In contrast, a single attention aggregation does not directly encode positional relationships — fixing a Query and arbitrarily reordering the Keys and Values within its visible range does not change the result of that aggregation.

Interestingly, the reason KDA can simultaneously achieve O(1) memory/compute complexity and parallelism is by moving from nonlinearity to linearity. In my understanding, this reflects a trade-off between expressiveness and computational efficiency:

  • To obtain Chunkwise parallelism: Classic RNNs use nonlinear state feedback → replaced by linear/affine updates to the old state.
  • To obtain O(1) state storage and computation relative to context length during single-step decoding: Softmax Attention’s nonlinear matching → replaced by fixed-state aggregation and linear readout.

It is worth noting that traditional RNNs, due to the non-commutative nesting of nonlinear functions (such as tanh), naturally preserve positional information. However, purely linear attention (without a forget gate) that simply accumulates states (St = St-1 + vt kt^T) obeys the commutative law of matrix addition. As a result, inputs [A, B] and [B, A] produce identical final states, leading to complete loss of positional information.

How do we recover the lost positional information? Through the forget gate. The KDA paper also points out that forgetting itself is a form of relative positional encoding: the farther a token is from the current position, the more decay steps it experiences, and the weaker its signal becomes. This implicitly injects distance information.

The Causal Mask in Softmax Attention only solves the problem of which tokens are allowed to be seen. Both position 99 and position 1 are within the visible history for position 100; the mask allows access to both, but does not further differentiate a distance of 1 versus a distance of 99 through the mask values themselves. Of course, across multiple layers, Causal Masks with different visible prefixes indirectly allow V (as well as K and Q) to acquire implicit positional information. However, this implicit positional encoding has several issues:

  1. The first layer is permutation-invariant: the 3rd position in Layer 1 cannot distinguish between [A, B, C] and [B, A, C].
  2. Positional and semantic information become entangled.
  3. It cannot explicitly represent relative distances.

RoPE (Rotary Position Embedding) is a widely used explicit positional modeling mechanism. It essentially uses rotation angles to represent a token’s position. Let qt and kj denote the content projections before rotation. After applying position-specific rotations, we have:

When using standard RoPE, the QKT term in the attention formula is replaced by the rotated Q̃K̃T. The relative position j−t is thus directly incorporated into the Query–Key dot product. This allows the model to learn positional relationships, but does not guarantee that closer tokens will receive higher scores.

Compared with RNNs that do not use explicit positional encodings, Attention with RoPE incurs additional computational and engineering costs for positional modeling:

  • Extra rotation operations.
  • Management of positions and rotation coefficients.
  • Long-context adaptation. When the inference context exceeds the training position range, adjustments to rotary frequency, position scaling, etc., may be required. These need dedicated training and validation; simply increasing the position indices does not guarantee that the model’s capabilities will automatically extend.

Multi-layer causal Attention can indirectly form sequential cues through visible prefixes at different positions. RoPE, on the other hand, explicitly incorporates relative position information directly into the attention computation by injecting relative positions into the Query–Key scoring. KDA, meanwhile, embeds the effect of ordering into the state evolution process; even when executed in a Chunkwise parallel manner, this sequential relationship is preserved. Therefore, whether to use RoPE depends on the existing sequential modeling mechanisms already present in the overall architecture, as well as the actual benefits and costs of adding extra positional representations.

The table below compares the choices made by several models:

Model Model Architecture Positional Encoding
Kimi K3 93 layers = 69 KDA + 24 MLA. Basically arranged as 3 KDA + 1 MLA every 4 layers, with the final two layers (92 and 93) both being MLA. NoPE
GLM-5.3 78 layers of full DSA (MLA + indexer). The indexer consists of 21 layers of full + 57 layers of shared. RoPE
GLM-5.3-Flash 45 layers = 34 KDA + 11 DSA. 3 KDA + 1 DSA every 4 layers, for a total of 11 groups, plus one additional KDA layer at the end. NoPE
Qwen3.8-Flash-Next 48 layers = 36 GDN + 12 QSA. 3 GDN + 1 QSA every 4 layers. RoPE
Qwen3.8-Max 92 layers = 69 GDN + 23 Gated Attention. 3 GDN + 1 Gated Attention every 4 layers, for a total of 23 groups. RoPE

From a Training Perspective: Understanding the Evolution

Linear Transformers Are Secretly Fast Weight Programmers explains linear attention from the perspective of fast-weight associative memory: the state matrix ( S_t ) is not only a hidden state that recurses with the sequence, but can also be viewed as a set of fast weights that are continuously updated during context processing, used to store temporary associations from keys to values. Kimi Linear builds on this perspective and further unifies DeltaNet, Gated DeltaNet, and KDA through online learning, reconstruction loss, and fast-weight decay.
From the fast-weight perspective, ( S_t ) serves as an associative memory storing transient mappings from keys to values.
— From the KDA chapter: Linear Attention as Online Learning

Memory As a Model

The most basic form of linear attention writes the current key-value association into the state via an outer product and reads from the state using a query:

Unlike the projection parameters, which usually remain fixed during inference, ( S_t ) changes continuously as new tokens arrive. Yet it behaves exactly like the weight matrix of an ordinary linear layer, acting on the input through matrix multiplication. Therefore, from the fast-weight perspective, ( S_t ) is a set of weights that are rapidly updated with context, as well as a piece of dynamic associative memory.

Starting from the initial state ( S_0 = 0 ), we can unroll the state recurrence as:

If ( S_0 \neq 0 ), the right-hand side must also add ( S_0 ), and the readout equation below will correspondingly include an extra ( S_0 q ).

When reading with an arbitrary query ( q ):

Here, ( k_i^\top q ) measures how well the query matches each historical key and determines how much of the corresponding value is retrieved. Thus, the outer product ( v_i k_i^\top ) can be seen as writing a key-value association into the state, while ( S_t q ) aggregates historical values weighted by their key-matching scores.

Since ( S ) can accept a query, it can naturally also accept a key:

This represents the value recalled by the current associative memory when given key ( k ). Therefore, before writing the current association ( (k_t, v_t) ), the expression

can be interpreted as the old memory’s reconstruction or prediction of the current value.

Loss Function

Standard linear attention always adds the outer product ( v_t k_t^\top ) to the state, regardless of whether the current association already exists:

First, denote the change in state at step ( t ) as

The outer-product update of standard linear attention implies

According to the gradient descent update rule:

where:

Δθ: the change in parameters (sometimes denoted Δw for weight change).
θ (Theta) or w (Weight): the parameters of the model.
η (Eta) or α (Alpha): the learning rate, which controls the step size.
∇L(θ) or ∂L/∂θ: the gradient of the loss function with respect to the parameters.

To align this with the update rule of standard linear attention, we first set the learning rate ( \eta = 1 ). The gradient we then need is:

The corresponding loss function should therefore be:

Before we mentioned that Skt is the value recalled from memory using the current key, while vt is the target value we want to remember. Therefore, vtᵀ Skt is the inner product between the target value and the recalled value. Minimizing its negative value encourages this inner product to become larger. However, what we actually want is for the recalled value to be close to the target value — that is, to drive the reconstruction error toward zero — rather than letting the loss above continuously decrease all the way to −∞. So, is it possible to design a loss function that achieves this?

Reconstruction Loss Function

DeltaNet reformulates this as a reconstruction problem: treat S as a linear model that predicts value from key, and require Skt to be as close as possible to vt. The regression loss for the current sample is:

According to the chain rule:

Taking a single gradient descent step on the current sample with learning rate βt yields the Delta Rule:

This shows that the Delta Rule no longer simply adds vt directly into memory. Instead, it first checks what the old memory can already predict, then writes only the part that has not yet been predicted correctly. If St−1 kt = vt, the prediction residual is zero and no redundant write is needed.

Multiplying the update equation on the right by the current key makes this error-correction effect even clearer:

When the key is normalized, i.e., ‖kt‖₂ = 1:

In other words, the updated prediction moves from the old prediction toward the target vt. Here, 0 < βt < 1 indicates partial correction, while βt = 1 represents exact overwrite on the current key.

It is important to note that this is not a set of independent, non-interfering slots in a dictionary. For another key k', the change caused by this update is:

Therefore, keys similar to kt will also be affected; only directions orthogonal to kt are not directly influenced by this update.

From Reconstruction Error to Regularization

Earlier, we viewed the associative memory S as an online-trained linear model: for every incoming sample (kt, vt), we perform one update based on the reconstruction loss:

However, reconstruction loss only cares about one thing: whether the current sample is predicted accurately.

From a training perspective, a natural extension is to impose a regularization constraint on the model weights in addition to fitting the current sample, penalizing large weights. Adding an L2 regularization term to the loss function gives Lreg = L + λ/2 ‖θ‖². The gradient of this loss with respect to the parameter θ is ∇L + λθ. Substituting into the SGD update formula:

Here gt = ∇L(θt) denotes the gradient of the current data loss. Only when 0 < ηλ < 1 is 1 − ηλ a decay factor between 0 and 1. When ηλ = 0, there is no decay; when ηλ = 1, the direct term of the old weight is cleared to zero. One cannot simply claim that any step size will produce such decay just because L2 regularization has been added.

Accordingly, we directly add an L2 regularization term to the reconstruction loss:

Performing one step of ordinary SGD on the old state St−1 with learning rate βt yields:

Let αt = 1 − βtλt (to correspond to a forget gate where 0 < αt < 1, we need 0 < βtλt < 1). Then:

As you can see, 1 − ηλ and the forget gate in GDN have the same mathematical form when it comes to “shrinking old weights.” If we treat the associative memory S as fast weights, forgetting can be understood as applying decay to these fast weights.

However, GDN has one additional design detail worth noting: it first decays the old memory, then computes the reconstruction error using the decayed memory, and finally corrects based on that error:

Therefore, GDN can be understood as “first apply fast-weight decay, then perform one step of reconstruction learning.” αt controls how much of the old memory is retained, while βt controls how much the current association is corrected. The two play different roles and are typically generated by the model based on the input, rather than being forced to satisfy a fixed relationship such as αt = 1 − βtλ.

KDA Implementation Details

For KDA, Decode can use a different execution plan from training and Prefill:

  • Decode: Only one new token arrives at a time. It directly updates the state once and reads the output, using a fixed state to control the per-step cost.

  • Training and Prefill: The entire input sequence is known in advance, allowing pre-computation of update coefficients. Through scan or Chunkwise reordering, computational throughput is significantly improved.

In vLLM v0.32.0, the KDA layer of GLM-5.3-Flash selects the prefill backend based on the platform and the additional_config.kda_prefill_backend setting (auto / triton / flashkda, default auto):

Platform / Config Prefill Decode & Speculative Verification Internal Prefill Checkpoint
CUDA SM90/SM10x/SM12x, bf16, head_dim=128, bounded gate, auto or flashkda FlashKDA (torch.ops._flashkda_C.fwd, with L2 Norm, gating, and β sigmoid all fused inside the kernel) Triton fused_recurrent_kda Supported: num_prefill_checkpoint_blocks=1, prefill_checkpoint_alignment=16
kda_prefill_backend=triton Triton chunk_kda_with_fused_gate Triton fused_recurrent_kda Not supported
ROCm AMD version of chunk_kda_with_fused_gate AMD version of fused_recurrent_kda Not supported

For each KDA layer of every request, an independent state is maintained for each head. Taking the head count and dimension configuration of GLM-5.3-Flash in this article as an example, the following shows the logical shape when all heads are combined. Speculative decoding uses the per-token state snapshot path described later:

State Single Shape Logical Usage When Speculative Decoding Is Enabled
conv_state [3 × num_heads × head_dim, conv_kernel − 1 + num_spec] Uses an extended window and selects the appropriate historical segment based on the accepted length
S(recurrent_state) [num_heads, head_dim, head_dim] Stores state snapshots corresponding to 1 + num_spec verification positions

Prefix Cache

However, the ideal is beautiful, but reality is harsh. If each request only saves one copy of S(recurrent_state), Prefix Cache cannot be implemented, and the cost of discarding the KV Cache is enormous. (This is why vLLM enables Prefix Cache by default.)

If we still save one copy per block_size, the cache-saving benefit of Linear Attention would be greatly diminished (VRAM capacity is no longer O(1), while memory bandwidth and computation remain O(1)). So what’s the solution? Let’s see how vLLM handles it.

First, Prefix Cache in vLLM is managed at the Block level (default block size is 16). It computes a unique Hash Key using the token sequence within the current block and the hash values of preceding blocks. This relatively coarse matching granularity is often compared with SGLang’s token-level Radix Tree, although in practice it has almost no impact. (For basic knowledge about prefix cache, refer to the vLLM official documentation: Automatic Prefix Caching)

Additionally, almost all open-source models that currently use Linear Attention are Hybrid architectures. So how should this be designed?

How KV Cache Is Managed

vLLM first needs to know what the cache for each layer looks like. This is described by KVCacheSpec. Layers of the same type typically produce the same spec.

However, if each layer independently manages its own block table based on KVCacheSpec, even if the KV cache VRAM is pre-allocated at startup, the system would still need to maintain and allocate Block IDs separately for each layer during request execution. This increases scheduling metadata and management overhead. So what’s the solution?

English Translation:

One approach is to manage KVCacheSpec layers that are identical together, which leads to the concept of a KVCache Group. Each KVCache Group corresponds to one block table. However, since all groups share the same BlockPool, allocation must consider making the page sizes of different blocks as consistent as possible. This effectively reduces VRAM fragmentation. Therefore, even if the KVCacheSpec is identical, layers may still be split into different KVCache Groups.

There is another scenario: for example, when the MLA and Indexer have the same lifecycle and both use the MLAAttentionSpec class, but their head_size differs, resulting in different per-layer page sizes. Taking bf16 and block_size=64 as an example:

  • MLA: 1152B per token, 72KB per page
  • Indexer: 132B per token, 8.25KB per page

What should we do? If we follow the previous approach and split them into two separate Groups, it would require their per-layer page sizes to be equal. There are two possible solutions:

  1. Pad the Indexer to match the page size of MLA. This would cause extremely large waste;
  2. Adjust the block size of the Indexer so that its page size is as close as possible to that of MLA. However, this would make their lifecycles inconsistent.

So how do we solve this? vLLM introduces a special KVCache Spec called UniformTypeKVCacheSpecs. The merging condition is: the block_size must be the same, and they must belong to the same uniform base class in the registry.

python
KVCacheGroupSpec(
    layer_names=[
        "model.layers.0.self_attn.attn",              # MLA
        "model.layers.0.self_attn.indexer.k_cache",   # Indexer
        "model.layers.1.self_attn.attn",
        "model.layers.1.self_attn.indexer.k_cache",
        ...                                           # Total 61 × 2 = 122 layers
    ],
    kv_cache_spec=UniformTypeKVCacheSpecs(
        block_size=64,
        kv_cache_specs={
            "model.layers.0.self_attn.attn":            mla_spec,  # 72 KiB
            "model.layers.0.self_attn.indexer.k_cache": idx_spec,  # 8.25 KiB
            ...
        },
    ),
)

mla_spec = MLAAttentionSpec(block_size=64, num_kv_heads=1,
                            head_size=576,          # kv_lora_rank 512 + rope 64
                            dtype=torch.bfloat16)

# Single-layer page = 64 × 576 × 2B = 73,728 B = 72 KiB

idx_spec = MLAAttentionSpec(block_size=64, num_kv_heads=1,
                            head_size=132,          # 128 fp8 + 128/128 × 4B scale
                            dtype=torch.uint8)

Single Layer page = 64 × 132 × 1B = 8,448 B = 8.25 KiB


After merging, all layers in the group share one block table. The `page_size_bytes` of a Group is the sum of the page sizes of all layers within the group:

```python
@property
def page_size_bytes(self) -> int:
    return sum(spec.page_size_bytes for spec in self.kv_cache_specs.values())

This means that when vLLM’s CacheEngine requests memory from the GPU VRAM pool, it allocates one block ID that directly contains storage locations for 61 MLA pages and 61 Indexer pages, totaling 61 × (72 + 8.25) KiB = 4,895.25 KiB ≈ 4.78 MiB.

Prefix Cache for Linear Attention

Now that we’ve covered Groups, let’s return to linear attention. Layers such as KDA and Mamba maintain only one fixed-size state per layer per request, which does not grow with the number of tokens. To fit into this Block mechanism while satisfying the requirement that all groups have the same page size, the byte size of one state must equal the per-layer page size of one attention block.

Here’s why the byte size of one state must equal the per-layer page size of one attention block. Taking Qwen3-8-27B as an example, it has one 16-layer Full Attention KVCache Group and three 16-layer GDN KVCache Groups:

  • Attention KVCache Group per Block: 16 × Attention per-layer page size
  • GDN KVCache Group per Block: 16 × GDN per-layer storage page size
    Therefore, it is sufficient to ensure that Attention per-layer page size = GDN per-layer storage page size.

Things become more complex with GLM-5.3-Flash because it involves the UniformTypeKVCacheSpecs mentioned earlier. Its KV Cache Group division is as follows (Groups are generated by the generic _get_packed_kv_cache_groups):

python
[
    # Group 0: MLA + Indexer, combined into one UniformTypeKVCacheSpecs
    # 11-layer MLA+Indexer
    KVCacheGroupSpec(
        layer_names=[mla.*, indexer.k_cache.*],
        kv_cache_spec=UniformTypeKVCacheSpecs(block_size=640, kv_cache_specs={
            mla.i:     MLAAttentionSpec(head_size=512, dtype=bf16),        # 640 KiB
            indexer.i: MLAAttentionSpec(head_size=132, dtype=uint8,
                                        tokens_per_state=4),               # 20.6 KiB
        }),
    ),

    # Group 1: Indexer’s kpool tail ring buffer; each request uses a fixed 1 block
    # and does not participate in prefix caching
    KVCacheGroupSpec(layer_names=[tail.*], kv_cache_spec=UniformTypeKVCacheSpecs(
        kv_cache_specs={tail.i: CircularBufferSpec(block_size=ring)})),    # ring=4 when MTP is disabled, 2 KiB

# Group 2..:KDA layers, split into 4 groups according to the number of states that can fit in one block, [9, 9, 8, 8]
    KVCacheGroupSpec(layer_names=[kda.0, kda.3, ...],
                     kv_cache_spec=UniformTypeKVCacheSpecs(kv_cache_specs={
                         kda.i: MambaSpec(page_size_padded=MLA single-layer page)})),
    ...
]

The number of KDA groups comes from the packing rule: one block must hold 11 MLA layers + 11 Indexer layers, totaling 11 × 640 + 11 × 20.625 = 7,266.875 KiB. This can accommodate ⌊7266.875 / 640⌋ = 11 KDA states. Therefore, the 34 KDA layers are divided into cdiv(34, 11) = 4 groups, with layers taken in a round-robin fashion, resulting in [9, 9, 8, 8].

In the end, the byte size occupied by one state must equal the byte size occupied by one MLA KV Block. The approach is to enlarge the block_size of the attention while padding the state to the same byte count.

  1. GLM-5.3 Flash MLA attention layer, bytes per token (single layer):
attn_page_size_1_token
  = num_heads × (head_size + head_size_v) × dtype bytes
  = 1 × 512 × 2
  = 1024 B
  • num_heads = 1: During decoding, MLA is equivalent to MQA; there is only one KV head, which is not partitioned by TP.

  • head_size = kv_lora_rank + qk_rope_head_dim = 512 + 0 = 512: GLM-5.3-Flash’s MLA uses a NoPE design (mla_use_nope = true), so there is no RoPE component.

  • head_size_v = 0: MLA only caches one latent vector and does not maintain a separate V cache.

  • dtype is bf16 (2 bytes).

For GQA the formula is: num_heads × (head_dim + head_dim_v) × dtype bytes.
DeepSeek-V3 or Hy4Preview with 64-dim RoPE has head_size = kv_lora_rank + qk_rope_head_dim = 576, resulting in 1152 B per token.

  1. KDA layer — bytes per state (single layer, single request, single GPU, TP=1, num_spec=0)
State Shape dtype Bytes
conv_state [3 × num_heads × head_dim, conv_kernel − 1 + num_spec] = [3072, 3] bf16 18,432
recurrent_state [num_heads, head_dim, head_dim] = [8, 128, 128] fp32 524,288
Total mamba_page_size 542,720
  1. Compute block_size (_align_hybrid_block_size)
python
attn_block_size = kernel_block_alignment_size * cdiv(
    mamba_page_size,
    kernel_block_alignment_size * attn_page_size_1_token,
)

if cache_config.block_size < attn_block_size:
    cache_config.block_size = attn_block_size
    logger.info(
        "Setting attention block size to %d tokens "
        "to ensure that attention page size is >= mamba page size.",
        attn_block_size,
    )
markdown
block_size = kernel_block_alignment_size × cdiv(mamba_page_size, kernel_block_alignment_size × attn_page_size_1_token)
           = 128 × cdiv(542720, 128 × 1024)
           = 128 × 5
           = 640
  • kernel_block_alignment_size takes the larger value between the minimum kernel block supported by the backend and the user-configured block_size. For MLA hybrid models, it is further compared with 128 and the maximum is taken. In this example, the value is 128. The reason is that TRTLLM/FlashInfer’s MLA decode kernel requires the number of physical kernel blocks to be aligned to a multiple of 128 / kernel_block_size. Therefore, the manager’s block size is set to a multiple of 128 so that after being split into kernel blocks, the constraint is still satisfied.

  • Afterwards, the value is rounded up again according to the least common multiple of the minimum kernel block sizes across all non-SSM backends (backend_block_alignment). In this example, the Indexer requires index_kpool × 32 = 128. Since 640 is already a multiple of 128, the result remains unchanged.

  • Align page size

  • Bytes per MLA block: 640 × 1024 = 655,360 B.

  • KDA’s state is padded to the same size: mamba_page_size_padded = 655,360 B, resulting in approximately 20.7% extra padding.

Calculation Result
MLA per token 1 × (512 + 0) × 2B (NoPE, no RoPE portion) 1024 B
One KDA state conv_state [3072, 3] bf16 + recurrent_state [8, 128, 128] fp32 542,720 B
block_size 128 × cdiv(542720, 128 × 1024) 640
MLA single-layer page 640 × 1024 655,360 B
After KDA padding mamba_page_size_padded = 655,360 B ~20.7% extra

This is also why block_size is often adjusted to several hundred or even over a thousand when starting a hybrid model. The smaller the TP degree, the larger the state per card, and the larger the block_size.

Group Corresponding Spec Class block_table shape
Group 0 (MLA + Indexer) UniformTypeKVCacheSpecs<br>(MLAAttentionSpec) [max_num_reqs, cdiv(max_model_len, block_size)]
Group 1 (Tail Group) UniformTypeKVCacheSpecs<br>(CircularBufferSpec) [max_num_reqs, 1]
Group 2~5 (KDA Group 0~3)<br>(when mamba_cache_mode="align") UniformTypeKVCacheSpecs<br>(MambaSpec) [max_num_reqs, cdiv(max_model_len, block_size) + num_speculative_blocks]
Group 2~5 (KDA Group 0~3)<br>(mamba_cache_mode="none") UniformTypeKVCacheSpecs<br>(MambaSpec) [max_num_reqs, 1 + num_speculative_blocks]

**After grouping into Groups, the next step is to decide how these Groups are physically laid out in VRAM.**

Prior to v0.31.0, GLM-5.3-Flash did not reuse the common **Block-outermost** layout. Instead, it used a custom **Layer-outermost** layout. In v0.32.0 ([#57169](https://github.com/vllm-project/vllm/pull/57169)), this custom logic was removed, and the model now adopts the generic **BLHNC** (Block-outermost) packing layout. (The `KpoolTailBackend` for the kpool tail only declares support for `BLHNC`.)

Let’s first look at the old layout:

![](/api/kb-media/QBFobajtqogW37x6PCicMRgSnwg)

The original reason for introducing a custom layout was that the sparse attention layer’s **Indexer** and **MLA Kernel** each imposed strict, fixed-stride addressing constraints:

### 1. First Kernel (DeepGEMM `paged_mqa_logits` — responsible for reading the **Indexer Cache** to compute scores)

vLLM’s KVCacheManager allocates 1 block containing 640 tokens. After 4-to-1 compression, this corresponds to 160 Pool States in the `Indexer Cache` (160 × 132 B = 20.625 KiB). However, DeepGEMM’s `paged_mqa_logits` kernel only accepts 32 or 64 states per page (only 64 is supported on SM120). Therefore, it actually loads data in pages of 32 states (corresponding to 128 tokens, occupying `32 × 132 B = 4.125 KiB`).

As a result, the Indexer cannot directly use vLLM’s global 640-token-granularity `block_table`. It must split each 20.625 KiB large block into **5** **4.125 KiB** small pages (called **`kernel_block`**), and derive a dedicated fine-grained page table — **`kernel_block_table`** — that is 5× wider and uses 128-token (32-state) granularity. This table is then passed to `paged_mqa_logits`. Inside the kernel, it reads an integer small-page index `k` from `kernel_block_table` and addresses memory using **`indexer_ptr + k * 4.125 KiB`**.

### 2. Second Kernel (Sparse MLA — responsible for reading the **MLA Cache** according to the Top-K results to compute Attention)

After the first kernel selects 2048 discrete token indices, the Sparse MLA kernel treats the entire MLA Cache as a flattened 2D table of token rows (each row represents the complete KV for one token, occupying **`512 × 2 B = 1 KiB`**). It uses the `block_table` to remap logical token positions to global integer row numbers `r`, then addresses memory inside the kernel using **`mla_ptr + r * 1 KiB`**.

Under the **Layer-outermost** layout, all large blocks belonging to the same layer are stored contiguously in VRAM. The distance between adjacent large blocks equals the layer’s own block size (20.625 KiB = 5 × 4.125 KiB for Indexer; 640 KiB = 640 × 1 KiB for MLA). This distance is **naturally an integer multiple of both kernels’ addressing strides**. Therefore, a large block `[0, 1]` in the `block_table` can be simply multiplied by 5 to expand into `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]` in the `kernel_block_table`, elegantly avoiding cross-block stride alignment issues.

The downside is that **Layer-outermost** requires all layers within the same Group to have *exactly the same* `page_size` stride. This forced the team to maintain a custom Layer-outermost layout specifically for GLM-5.3-Flash.

From the perspective of long-term maintainability and architectural unification, the goal is to eliminate this custom logic and converge GLM-5.3-Flash onto the generic **Block-outermost** (tightly packed within each block) path.

However, under **Block-outermost**, adjacent large blocks of the same layer are interleaved with data from all the other 21 layers. The cross-block stride becomes the total block size `bytes_per_block` (the sum of all effective data equals 7,266.875 KiB). The original natural divisibility is broken.

Therefore, switching to `Block-outermost` requires simultaneously satisfying the stride divisibility constraints of the two independent kernels mentioned above. Each spec declares its required inter-block stride through `block_stride_alignment`: the Indexer uses 4.125 KiB per kernel block, while Sparse MLA uses 1 KiB per row. `_get_kv_cache_bytes_per_block` then rounds up the total block size (`bytes_per_block`) to an integer multiple of `LCM(4.125KiB, 1KiB) = 33KiB` (i.e., 7293 KiB). This ensures that the spacing between adjacent large blocks is simultaneously 1768 times the DeepGEMM small page size (4.125 KiB) and 7293 times the MLA token row size (1 KiB).

On this foundation, the Worker-side `AttentionGroup` only needs to, when building metadata, expand each large block number `b` in the `block_table` according to the stride formula `1768 * b + [0, 1, 2, 3, 4]` and write it into a private 5×-wider `kernel_block_table` (for example, large blocks [0, 1] expand to [0, 1, 2, 3, 4, 1768, 1769, 1770, 1771, 1772]). Meanwhile, Sparse MLA remaps row indices using `7293 * b + off`. This achieves perfect cross-layer strided addressing without modifying a single line of the underlying CUDA kernel code.

The layout of `Block-outermost` is as follows:

![](/api/kb-media/ZfiGbNHBMoKTh7x7RfsctnDjn9c)

For homogeneous models, all layers have the same single-page size, so using Layer-outermost naturally makes blocks within the same layer physically contiguous with naturally aligned per-layer strides. In contrast, Hybrid models contain heterogeneous cache layers with different per-page byte sizes (such as 640 KiB MLA, 20.625 KiB Indexer, and 2 KiB Tail). By adopting Block-outermost, layers of different sizes under the same `block_id` are tightly packed within the block according to their actual byte sizes, and the overall block-level stride (`bytes_per_block`) is uniformly aligned. This not only allows the same block planning logic to support arbitrary combinations of heterogeneous layers, but also ensures that a single `block_id` corresponds to a physically contiguous memory segment, thereby satisfying the requirements for block-based allocation and block-based RDMA transfer. (Although KDA and MLA still maintain 640 KiB per-layer alignment due to `_align_hybrid_block_size`, there is no longer a need for equal per-layer sizes between MLA (640 KiB), Indexer (20.625 KiB), and Tail (2 KiB).)

#### How Many Copies of S Should Be Stored?

So the question is: how many copies of S should actually be stored? Should we save one copy of S for every `block_size` tokens?

In its early days, vLLM did offer an `mamba_cache_mode="all"` mode. This was completely removed in v0.32.0, leaving only `"align"` and `"none"` in `MambaCacheMode`.

It is important to understand that cache blocks themselves are managed by LRU and can be evicted at any time. Therefore, the truly fatal flaw of the "all" mode is not long-term VRAM occupation, but rather useless VRAM writes and wasted compute. It forces the operators to export and write every intermediate state at each `block_size` boundary to HBM during a single forward pass. This both slows down kernel execution and wastes a large amount of bandwidth on intermediate states that will never be reused.

![](/api/kb-media/JnPrbQ1wLobmdqxGT3IclI9Yn4d)

Currently, when Prefix Cache is enabled, hybrid models default to `mamba_cache_mode="align"`. The rule is: only the S of the last token in each scheduler step is saved, and the block is registered into the prefix cache **only** when that token is located at position `i * block_size`.

**On the scheduling side**: `Scheduler._mamba_block_aligned_split` is responsible for aligning the end position of each step with `block_size` (640):

1. When the per-step token budget is sufficient, truncate at the `last_cache_position`: For a 2000-token prompt, if the per-step budget is large enough, the system will neither run the entire range [0, 2000) in one go (which would leave the only written state at position 2000, with no preserved full-block state at position 1920), nor split it into four steps as 640 → 1280 → 1920 → 2000. Instead, it performs a single cut only at the last cacheable full-block boundary, `last_cache_position = 1920` (3 × 640). Step 1 directly runs [0, 1920), and Step 2 runs the remainder [1920, 2000). The positions 640 and 1280 crossed in Step 1 do not allocate physical blocks; `null_block` is directly filled in the block table. (If the operator supports `num_prefill_checkpoint_blocks > 0` for internal exporting, there is no need to truncate at 1920 — the entire [0, 2000) range can be executed in one step, with the operator internally writing the S state at 1920 into a reserved block.)

2. **When the per-step token budget is limited, intermediate chunks are floored to `i * 640` (`aligned_end`)**: If the current step’s budget is insufficient to process the entire prompt, the chunk length is truncated to an integer multiple of 640. If the remaining budget is less than one full 640-token block, the step returns 0 and the request is not scheduled. This avoids writing intermediate states that are not aligned to block boundaries.

**Memory-side behavior**: Calculated per KDA layer in `align mode`, during state block transitions, each in-flight request temporarily references `2 + num_speculative_blocks` state blocks simultaneously — used for the old state, new state, and speculative decoding. The numbers reported here represent the count of non-`null_block` entries in the Scheduler’s `req_to_blocks` list for that request, i.e., the number of state blocks still actively referenced by this request. This does **not** include historical S snapshots that have already been released by this request but remain in the cache pool:

- When advancing within the same 640-token block, S is typically updated in-place on the current physical block; no new block needs to be allocated for each step.
- When switching to the next state block, `MambaManager` allocates a new physical block. Before the forward pass, the Worker uses `preprocess_mamba` to copy the old S into the new block, then continues computation on the new block. This prevents overwriting reusable snapshots in the old block. Until the handover is complete and the old block can be safely released, the current request holds references to both the old and new blocks.
- Earlier blocks that are no longer needed by the current request are removed from the Scheduler-maintained request block list by `MambaManager.remove_skipped_blocks`, replaced with `null_block` placeholders, and their corresponding physical block’s `ref_cnt` is decremented by 1. **Only when there are no other references will `ref_cnt` reach zero.** After a registered-hash block’s `ref_cnt` drops to zero, it can still remain in the BlockPool’s free queue carrying its S and hash, available for cache hits by other requests, or it may be reassigned and overwritten according to the cache eviction policy.

Prefill for a 2000-token request (block_size = 640, illustrative):

Case A: Sufficient per-step budget (truncated at last_cache_position = 1920, completed in 2 steps) step 1 [0, 1920) KDA block table: [null, null, B2] Positions 640/1280 are skipped and not stored; B2 stores S@1920 step 2 [1920, 2000) KDA block table: [null, null, B2, B3] B2 remains in the pool for potential hits; B3 stores S@2000

Case A': Sufficient per-step budget with backend supporting internal checkpoint (default FlashKDA in GLM-5.3-Flash v0.32.0) step 1 [0, 2000) KDA block table: [null, null, B2, B3] The kernel internally exports S@1920 to B2; B3 stores S@2000


**Scenario B: Single-step budget constrained** (e.g. at most 1 block per step, completed in 4 steps)

```markdown
step 1 [0, 640)       KDA block table: [B0]                    B0 stores S@640
step 2 [640, 1280)    KDA block table: [B0, B1]                B1 stores S@1280
step 3 [1280, 1920)   KDA block table: [null, B1, B2]         B0 is evicted back to pool (with hash), B2 stores S@1920
step 4 [1920, 2000)   KDA block table: [null, null, B2, B3]   B1 is evicted back to pool (with hash), B3 stores S@2000

On the hit side: MambaManager.find_longest_cache_hit searches from right to left and only takes the last matched block; all preceding positions are filled with null_block. This is because linear attention only needs the S state at the breakpoint — historical S values from the prefix are not required. The Full Attention layers, on the other hand, perform normal left-to-right matching. When the hit lengths differ across layers, HybridKVCacheCoordinator iteratively takes the minimum until all groups converge to the same hit length.

From this we can see that, when Prefix Cache align mode is enabled, it is indeed sufficient to retain only 2 + num_speculative_blocks (plus 1 for the step that exports the internal checkpoint). All other blocks can be released back to the BlockPool; they may still be hit later, but can also be evicted if VRAM is insufficient. This differs from Full Attention, where all KV blocks must remain unreleased (ref_count > 0) until the request completes.

PS: To reduce the number of extra segments created solely to preserve cacheable S states. Taking the example above:

  • Without internal checkpoint support: [0, 1920) and [1920, 2000) require 2 forward passes.
  • With internal checkpoint support and conditions met: [0, 2000) requires only 1 forward pass, while saving both S@1920 and S@2000.

However, upon closer inspection, the solution of using a large block_size (640) + storing only one copy of S at last_cache_position (1920) is not perfect. In real-world online serving, it encounters two typical pain points:

  1. Long System Prompt + different user queries (shared prefix forks in the middle): Under normal conditions with sufficient per-step budget, the scheduler only truncates and saves S near the very end of the entire prompt (last_cache_position = 1920). The skipped middle blocks at 640 and 1280 are all null_block. If multiple requests share the first 1300 tokens of the System Prompt and then append their own distinct user queries, the S saved by the first request at position 1920 already contains its own user query. Since position 1280 is a null_block, subsequent requests cannot hit even a single full block.

  2. Agent multi-turn conversations / retry of the same request (block_size = 640 makes the matching granularity too coarse). Even in tail-continuation or retry scenarios, because block_size has ballooned from 16 to 640, the matching granularity is more than 10× coarser. Any short prefix shorter than 640 tokens, or the remainder after a full block (e.g. the 1920 ~ 2000 tail in a 2000-token sequence), cannot be cached and reused, forcing a full Prefill computation.

Let’s see how vLLM addresses these two problems one by one.

Shared Prefix Fork Point (Marconi-style APC)

First, let’s look at the first issue: in the scenario where “a very long System Prompt is followed by different user queries”, the shared prefix ends in the middle of the prompt. The tail cache point (1920) registered by the first request falls inside the non-shared user query, so later requests cannot hit it. This is awkward — does that mean we have to fall back to saving an S state every block_size tokens again?

Following the earlier example: when the first request arrives, the system genuinely does not know which portion of the prompt is the common System Prompt. However, remember that although Mamba only saved the block at position 1920 and skipped the middle blocks at 640 and 1280 (filling them with null_block), the Full Attention layers have registered the three full blocks at 640, 1280, and 1920 — including their KV and hashes — into the cache pool.

A natural solution is to use the hit length from Full Attention as the cache boundary for the next request. vLLM draws inspiration from Marconi’s approach: the first request makes no guesses; when the second request arrives, it directly infers the fork point of the common prefix from the Full Attention hit results. This allows the second request to save the S at the fork point “on the way” during computation, so that the third and subsequent requests can reuse it directly. The implementation consists of three steps:

  1. Detection when the second request arrives: In KVCacheManager.get_computed_blocks, if the Full Attention hit length is longer than the Mamba hit (the extra portion is recorded as num_uncached), the longest single-group hit is taken as the fork point and recorded in Request.shared_prefix_boundary:
python
shared_prefix_boundary = num_new_computed_tokens + num_uncached

Here, num_new_computed_tokens is the common hit length after all groups are aligned (at this point it is constrained by Mamba, e.g. 0). Since Full Attention only registers hashes at full-block boundaries in the middle, the intermediate fork point naturally falls on an integer multiple of block_size (640). (If the fork exactly matches the end of a previous request, it is aligned to hash_block_size.)

  1. Truncation during scheduling of the second request: When it is the second request’s turn to execute, Scheduler._mamba_block_aligned_split adds shared_prefix_boundary to the forced stop list stops (by default aligned to block_size; when --enable-mamba-shared-prefix-checkpoint is enabled, it supports stopping at fine-grained intra-block fork points). This makes the current step’s chunk end exactly at the junction. Once the kernel finishes, the S at that position is naturally produced.

  2. Retention: When registering the cache, cache_blocks adds this fork point to reachable_boundaries (and relaxes the acceptance condition for _cache_partial_tail_block). This ensures that even if the sparse retention policy (retention_interval) is enabled, the S deliberately saved at the fork point will not be treated as an ordinary intermediate state and skipped or discarded.

Using the previous numbers for illustration (block_size = 640, --prefix-match-unit not set):

Request A: 2000 tokens. One chunk 0 → 1920, then 1920 → 2000 (FlashKDA runs the final checkpoint in one step internally). Only position 1920 has an S.
Request B: Shares the first 1300 tokens with A.
        Full Attention hits 1280, Mamba hits 0 (no S at 640 or 1280)
        → Overall hit = 0, B computes from scratch
        → shared_prefix_boundary = 0 + 1280 = 1280
        → B’s prefill is split into 0 → 1280, 1280 → ..., and the S at 1280 is cached.
Request C: Shares the first 1300 tokens with both A and B. Mamba hits 1280, overall hit = 1280.

This mechanism is enabled by default. Request B itself receives no benefit; its job is to save the S at the fork point for subsequent requests.

Solving the problem of increased block_size

After solving the retention of S at both the intermediate full-block boundary (1280) and the tail full-block boundary (1920), the second pain point emerges: when block_size increases from 64 to 640, the matching granularity of Prefix Cache also becomes 10× coarser. This means that only when two requests share a common prefix of at least 640 tokens (or an integer multiple of 640) and the content is completely identical can they hit a complete cache block. Any matching segment shorter than 640 tokens (or the remainder at the tail) cannot be cached and reused, and must be recomputed during Prefill. This issue can no longer be ignored as before.

What’s the solution? It’s actually not that complicated. Since the hash dimension and block_size were previously tightly coupled, why not decouple them? Keep the physical memory allocation block_size unchanged, but introduce a smaller hash_block_size that evenly divides block_size to serve as the step size for hash computation (i.e., one physical block contains multiple hash units).

This way, even if the last physical block is not fully filled, as long as it contains at least one complete hash_block_size, we can cache this partial physical block using the hash value at the last hash boundary within the block — this is the so-called cache_partial_block (partial block caching). Of course, limited by the overhead of CPU hash computation and intra-block lookups, as well as the alignment requirements of the underlying operators, hash_block_size cannot be made arbitrarily small.

Configuration assumptions for the two fine-grained examples below: The physical block_size remains 640, but --prefix-match-unit=64 is explicitly set, making hash_block_size = 64.

Applying this fine-grained hashing mechanism together with the cache_partial_block strategy to the two scenarios mentioned earlier (while also accounting for EAGLE/MTP speculative decoding’s requirement to forcibly roll back one hash_block_size and recompute), results in two fine-grained stopping points inside the scheduler:

1. Agent Multi-turn Conversations / Retry of the Same Request (Prompt Tail Boundary tail_boundary)

In these scenarios, the reuse boundary lies at the end of the previous round’s Prompt. With the --prefix-match-unit=64 setting above, when internal checkpoints are not used, Scheduler._mamba_block_aligned_split calculates the position of the last Prompt tail aligned to hash_block_size (64) as tail_boundary.

  • When EAGLE/MTP is disabled: 2000 tokens correspond to 1984 = 31 × 64.
  • When EAGLE/MTP is enabled: because matching rolls back one hash_block_size, the system proactively retreats one step to 1920 = 1984 - 64.
python
tail_boundary = (
    get_mamba_prefill_checkpoint_position(
        request.num_prompt_tokens,
        self.hash_block_size,
        self.use_eagle_block_drop,
    )
    if self.mamba_partial_cache_hit and not use_internal_checkpoint
    else 0
)

In the 64-granularity example above with EAGLE/MTP disabled, the scheduler makes an extra cut at tail_boundary (1984). Both Full Attention and Mamba register the unfilled block B3 (along with S@1984) under h31 through _cache_partial_tail_block → cache_partial_block. When the next round of dialogue or a retry request arrives, it can directly hit at 1984 (and Copy-on-Write the block to a new private block to continue writing), thereby saving the original 1920–1984 tail remainder.

If the default FlashKDA of GLM-5.3-Flash is used, internal checkpoints are supported (1984 - 0 is a multiple of 16), so the scheduler no longer makes this extra cut. A single forward pass runs [0, 2000). The kernel internally exports S@1984 to a reserved block, after which MambaManager._cache_partial_tail_block re-registers that block under hash 1984.

2. Long System Prompt + Different User Questions (Fine-grained Fork-point Stopping Point --enable-mamba-shared-prefix-checkpoint):

Returning to the earlier Marconi shared-prefix fork scenario: if EAGLE/MTP is enabled (or a previous request left a fine-grained tail), after the second request hits 1280 in Full Attention, EAGLE will roll it back by one hash_block_size (64). As a result, the detected fork point junction = shared_prefix_boundary falls inside a physical block at 1216!

  1. By default, Mamba only recognizes 640-token block boundaries in the middle. It floors 1216 down to 640, causing the third request to only hit at the 640 position (because EAGLE rolled back 64 tokens, resulting in a wasteful loss of 576 tokens).

  2. After enabling --enable-mamba-shared-prefix-checkpoint, the scheduler’s junction_stop no longer floors to 640. Instead, it stops directly at the fine-grained fork point of 1216 within the block. At the same time, MambaManager._cache_partial_tail_block allows this fork point and calls cache_partial_block to cache the S state at position 1216. This enables the third and subsequent requests to achieve fine-grained prefix matching at the 1216 position.

Special attention is required here: In the “long System Prompt + different user queries” scenario with intermediate forking, --prefix-match-unit cannot make the fork point match at a 64-token fine-grained granularity. Under full attention, only the tail block is allowed to use partial caching; the intermediate portions are still fully occupied. Therefore, the resulting junction_stop is always a multiple of the block size. The cache.enable-mamba-shared-prefix-checkpoint option merely mitigates the problem of EAGLE/MTP discarding entire blocks, reducing the loss to a small hash_block_size.

In align mode, Prefill can process a large chunk that spans multiple block_size units, filling all intermediate positions with null_block. However, Decode generates tokens one by one, so it inevitably hits every i * block_size (640) boundary. Each time Decode crosses a 640-token boundary:

  1. The newly filled old block is registered into the Prefix Cache (so that in multi-turn conversations, the model’s own generated replies can also serve as a prefix hit for the next round);

  2. To avoid overwriting the snapshot in the old block, a new physical block must be allocated. Before the next forward pass, preprocess_mamba (precopy_mamba_align_fused_kernel) is used to fully copy the S state of all layers from the old block to the new block. Generation then continues with in-place updates on the new block.

Reading and writing S becomes a bottleneck here. Moreover, frequently writing S can evict truly high-frequency Prompt caches from the cache pool. To address this, vLLM has further evolved two optimization paths:

  • Sparse cache retention (prefix_cache_retention_interval): Filters out unnecessary intermediate block registrations, retaining only S snapshots at the end of the Prompt, at Marconi fork points, or at specified large intervals. This prevents long Decode sequences from flushing the cache pool.

  • ReplaySSM: Introduces a small circular buffer during the Decode phase to cache recent recurrent inputs. It usually avoids incrementally writing the full S state back to HBM. Instead, it flushes and writes back only when the buffer window is full or a checkpoint needs to be saved, thereby alleviating the bandwidth bottleneck caused by high-frequency S writes during Decode. vLLM’s Mamba2 implementation enables this via --use-replayssm, with a default buffer window of 16 steps.

Method applicability ≠ Current implementation coverage: Both ReplaySSM’s “cache input and replay” approach and RecoverSSM’s “save correction values in a validation window, then restore and commit the state upon acceptance” can, in principle, be applied to both GDN and KDA. One cannot simply claim that “ReplaySSM is not applicable to GLM-5.3-Flash’s KDA.” Whether it can be enabled directly depends on whether vLLM has implemented the corresponding support for that specific model, kernel, backend, and configuration.

Speculative Decoding: How to Restore State After Verification

Speculative decoding for linear attention differs significantly from Full Attention:

In Full Attention, the KV Cache and the short-convolution state (conv_state) in linear attention both store per-token independent vectors. For conv_state, you only need to widen the sliding window to conv_kernel - 1 + num_spec, append the candidate tokens sequentially to the end of the window, and then read with an offset of num_accepted_tokens - 1 in the next step. Rejected draft tokens do not pollute the preceding historical state.

Only the recurrent state S (recurrent_state) of linear attention is affected: all tokens are mixed in-place and accumulated into the same matrix of shape [num_heads, head_dim, head_dim]. Once a rejected draft token is written into it, the historical state is irreversibly polluted. Therefore, the default implementation must allocate an extra num_speculative_blocks physical blocks for each request, saving the updated S for every candidate token into separate slots. This allows clean rollback to the state corresponding to num_accepted_tokens - 1 after rejection sampling. For models that have already integrated the corresponding implementation, ReplaySSM / RecoverSSM can also be used: after verification, only the state updates for the accepted portion are committed. Both GDN and KDA can adopt this approach. However, the GLM-5.3-Flash model used in the benchmark of this article has not yet integrated these mechanisms, so they cannot be treated as the model’s existing default path (see the implementation scope noted above).

Assume the target model’s state has already been processed up to prefix p. In the previous round, a confirmed token x0 was sampled, but the target model has not yet performed a forward pass with it as input. The draft model then produces d1, d2, d3 (num_spec = 3). The actual input to the target model in this round is:

[x0, d1, d2, d3]

The output of processing x0 is used to verify d1, the output of processing d1 is used to verify d2, and so on. The output at the last position can be used for the bonus token if all drafts are accepted. The verification kernel saves states for these four input positions as follows:

State Column Index Input Processed in This Round Saved Recurrent State
0 x0 S_{p+1}
1 x0, d1 S_{p+2}
2 x0, d1, d2 S_{p+3}
3 x0, d1, d2, d3 S_{p+4}

Assume the verification result accepts d1 and d2, rejects d3, and a corrected token r is resampled. The tokens confirmed generated in this round are [d1, d2, r]. The portion of this round’s input that was actually processed by the target model and whose states were fully computed is exactly [x0, d1, d2] (a total of 3 tokens). Therefore, the next round should start from S_{p+3}, treating the yet-to-be-fed r as the first confirmed input x0' of the next round. In other words: sampling r does not mean the target model has already computed and cached the state for r.

In general, if a draft tokens are accepted, one additional recovered token (or a bonus token in the case of full acceptance) will also be sampled. Thus:

In the implementation, spec_state_indices_tensor provides one row of physical slots per request, with shape [num_spec_requests, 1 + num_spec]. These physical slot IDs do not need to be contiguous. For example:

spec_state_indices_tensor[request] = [41, 9, 72, 18]

Accepting two drafts (a = 2):
num_accepted_tokens = 3
selected_column = 2
Next round’s initial recurrent state = state_pool[72] (i.e. S_{p+3})

In the common path without cross-block state movement (e.g. mamba_cache_mode="none", or when still advancing within the same 640-block in align mode), the next round’s fused_recurrent_kda directly uses the following when reading the initial state:

column = num_accepted_tokens[request] - 1
slot = spec_state_indices_tensor[request, column]
S = state_pool[slot]

This step completes the logical rollback directly via index offset, without first copying the selected state from slot 72 back to the fixed main slot slot 41. Subsequently, the kernel starts from state_pool[72] on-chip and sequentially overwrites each state slot from column 0 (slot 41) according to the new round’s input order. The snapshot left by the rejected branch from the previous round (slot 18) is naturally overwritten. (Only when crossing a block_size boundary in align mode and old blocks need to be sealed does preprocess_mamba explicitly copy the state from the selected slot — determined by num_accepted_tokens - 1 — to the newly allocated block slot, and reset num_accepted_tokens to 1.)

Overview of KDA Implementation Logic

markdown
α[c]  = exp(forget_log[c])                        # Forget gate, one per key channel, ∈ (e^{-5}, 1)
β     = sigmoid(write_logit)                      # Write gate, a scalar per head
γ[c]  = sigmoid(output_b[c])                      # Output gate, per head per channel, ∈ (0, 1)

Where:

Variable Computation Formula Weight Shape Output Shape
qkv hidden @ W_q<br>hidden @ W_k<br>hidden @ W_v<br>SiLU(causal_conv1d(qkv)) All qkv weights: [hidden_size, num_heads × head_dim]<br>conv weight: [3 × num_heads × head_dim, conv_kernel] q, k, v are all [num_sched_tokens, num_heads, head_dim]
β (write gate) sigmoid(hidden @ W_β) [hidden_size, num_heads] [num_sched_tokens, num_heads]
γ (output gate) sigmoid(hidden @ W_γa @ W_γb) [hidden_size, head_dim], [head_dim, num_heads × head_dim] [num_sched_tokens, num_heads, head_dim]
α (forget gate) exp(forget_log(hidden @ W_αa @ W_αb)) Same two-stage weights as γ; plus A_log, dt_bias [num_sched_tokens, num_heads, head_dim]
python
q, k = l2norm(q), l2norm(k)                       # Normalize per head independently along head_dim
S  ← S ⊙ α                                        # Forget: scale per key column
Δv ← v − S k                                      # Residual
S  ← S + (β · Δv) ⊗ k                             # Outer-product write
o  ← S (q · head_dim^{-1/2})                      # Readout, note the scaling
o  ← RMSNorm(o) ⊙ γ                               # Output, W_o[num_heads × head_dim, hidden_size]

⊙ is broadcast along the V axis and differs only across K channels. Both GDN and KDA generate the forget gate dynamically from the current token’s hidden state. The key difference is that GDN produces one decay scalar per head, while KDA produces an independent decay coefficient for each key channel of each head.

The forget gate computation logic is explained in detail below:

python
x          = forget_b + dt_bias           # forget_b = hidden @ W_αa @ W_αb
z          = exp(A_log) · x
forget_log = lower_bound · sigmoid(z)     # clamped to (lower_bound, 0)
α          = exp(forget_log)              # clamped to (e^{lower_bound}, 1)
S          = S * α                        # At each step it can shrink to at most ~0.67% and will never amplify

Note: The forget gate in both GDN and KDA is dynamically generated from the current token’s hidden representation. The core distinction lies in granularity: GDN uses a single scalar decay per head, whereas KDA employs a per-channel decay coefficient for each head’s key dimension.


| Step | Formula | Input Shape | Weight Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Add bias | `x = forget_b + dt_bias` | `[num_sched_tokens, num_heads, head_dim]` | `[num_heads, head_dim]`, broadcast along the token dimension | `[num_sched_tokens, num_heads, head_dim]` |
| Scale per head | `z = exp(A_log) · x` | `[num_sched_tokens, num_heads, head_dim]` | `[1, num_heads, 1]`, broadcast along token and channel dimensions | `[num_sched_tokens, num_heads, head_dim]` |
| Bounded log | `forget_log = -5 · sigmoid(z)` | `[num_sched_tokens, num_heads, head_dim]` | `lower_bound = -5` | Same as input, ∈ `(-5, 0)` |
| Forget gate | `α = exp(forget_log)` | `[num_sched_tokens, num_heads, head_dim]` | — | Same as input, ∈ `(e^{-5}, 1)` |
| Multiply to state | `S = S × α` | `S[h,req]`: `[head_dim, head_dim]`; `α[num_sched_tokens, num_heads]`: `[head_dim]` | — | `S[h]` same as input; each column is scaled down to at most ~`e^{-5}≈0.67%`, never amplified |

`A_log` is a per-head scalar; `dt_bias` is per-head per-channel. The table above omits the batch dimension. When the input uses shape `[1, num_sched_tokens, num_heads, head_dim]`, the broadcast shape of `A_log` becomes `[1, 1, num_heads, 1]`. `S` is a recurrent state of shape `[head_dim, head_dim]` for each request and each head.

![](/api/kb-media/CyFiboYikoZeUKxhZf0cb9UynIc)

---

### vLLM Decode Implementation

#### Fused GEMM Projection

The implementation fuses the 6 projections into a single `in_proj_qkvbfg_a`.

| Step | Formula | Input Shape | Weight Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Fused projection | `hidden @ W_qkvbfg_a` | `[num_sched_tokens, hidden_size]` | `[hidden_size, 3 × num_heads × head_dim + num_heads + 2 × head_dim]` | `[num_sched_tokens, 3 × num_heads × head_dim + num_heads + 2 × head_dim]` |
| Split | Split along the column dimension | Previous row | — | See table below |

| Tensor | Shape | Description |
| --- | --- | --- |
| `qkv` | `[num_sched_tokens, 3 × num_heads × head_dim]` | q/k/v not yet split |
| `write_logit` | `[num_sched_tokens, num_heads]` | Write gate logit, **one value per head** |
| `forget_a` | `[num_sched_tokens, head_dim]` | First part of the forget gate, **not split by head** |
| `output_a` | `[num_sched_tokens, head_dim]` | First part of the output gate, also not split by head |

#### GEMM: Lift forget gate and output gate to per-channel

| Step | Formula | Input Shape | Weight Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Forget Gate Projection | `forget_a @ W_fb` | `[num_sched_tokens, head_dim]` | `[head_dim, num_heads × head_dim]` | `forget_b [num_sched_tokens, num_heads × head_dim]` |
| Output Gate Projection | `output_a @ W_gb` | `[num_sched_tokens, head_dim]` | `[head_dim, num_heads × head_dim]` | `output_b [num_sched_tokens, num_heads × head_dim]` |
| Reshape forget_b | view | `forget_b` | — | `[1, num_sched_tokens, num_heads, head_dim]` |
| Reshape output_b | view | `output_b` | — | `[num_sched_tokens, num_heads, head_dim]` |

#### Short Convolution

Since operations are independent across the channel dimension, the q/k/v projections are concatenated along the channel dimension and passed through a single causal convolution. This is mathematically equivalent to performing three separate convolutions.

| Step | Formula | Input Shape | Weight Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Merged Conv | causal conv1d, SiLU, kernel=`conv_kernel` | `qkv [num_sched_tokens, 3 × num_heads × head_dim]` | Original q/k/v weights are each `[num_heads × head_dim, 1, conv_kernel]`; after merging, the weight passed to the operator is `[3 × num_heads × head_dim, conv_kernel]` | Same as input shape |
| Split | view | Previous row | — | `q`, `k`, `v` each `[num_sched_tokens, num_heads × head_dim]` |
| Split Heads | view | Each projection | — | `[1, num_sched_tokens, num_heads, head_dim]` |

The convolution reads/writes `conv_state`. During decoding, `causal_conv1d_update` is used; during prefill, `causal_conv1d_fn` is used.

#### Gating Converted to α, β (Decode Performed Inside Kernel)

| Step | Formula | Input Shape | Parameter Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Write Gate | `β = sigmoid(write_logit)` | `[1, num_sched_tokens, num_heads]` | — | Same as input, fp32 |
| Forget Gate | `forget_log = lower_bound · sigmoid( exp(A_log) · (forget_b + dt_bias) )` | `forget_b [1, num_sched_tokens, num_heads, head_dim]` | `A_log [1,1,num_heads,1]`;`dt_bias [num_heads, head_dim]` | Same shape as `forget_b`, values lie in `(lower_bound, 0)` |
| Decay Coefficient | `α = exp(forget_log)` | `[1, num_sched_tokens, num_heads, head_dim]` | — | One value per head and per key channel, range `(e^{lower_bound}, 1)` |

#### Recurrent Kernel (Per-Head Independent)

Inside the kernel, L2 normalization is also applied to q and k (`use_qk_l2norm_in_kernel=True`).

| Step | Formula | Input Shape | State Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Normalization | `q, k ← l2norm(q), l2norm(k)`; `q ← q · head_dim^{-1/2}` | `q, k [head_dim]` | — | Same as input |
| Forget | `S ← S ⊙ α` | `α [head_dim]` broadcast to V | `S [head_dim_v, head_dim_k]` | In-place |
| Residual | `Δv ← v − S k` | `v, k [head_dim]` | Same as above | `Δv [head_dim]` |
| Write | `S ← S + (β Δv) ⊗ k` | `β` scalar | Same as above | In-place |
| Read | `o ← S q` | `q [head_dim]` | Same as above | `o [head_dim]` |

After scanning all tokens:

core [1, num_sched_tokens, num_heads, head_dim]


Both decode (including speculative verification) and prefill use `fused_recurrent_kda` on all platforms. Under the configuration in this article, prefill defaults to FlashKDA; when FlashKDA is forcibly disabled or its conditions are not met, it falls back to `chunk_kda_with_fused_gate` (chunked + gated cumsum). See the backend table at the beginning of this chapter. The formulas are identical; only the execution plan differs. The next section expands on the Triton path.

#### Output Gate + Projection back to hidden

| Step | Formula | Input Shape | Weight Shape | Output Shape |
| --- | --- | --- | --- | --- |
| Gated RMSNorm | Per-head RMSNorm, then `× sigmoid(output_b)` | `core` and `output_b [num_sched_tokens, num_heads, head_dim]` | RMSNorm’s `head_dim` vector | Same as `core` |
| Flatten | view | Previous row | — | `[num_sched_tokens, local_projection_size]` |
| Output Projection | `flat @ W_o`; AllReduce if using TP | `[num_sched_tokens, local_projection_size]` | `[num_heads × head_dim, hidden_size]` (mathematically; RowParallel is row-sharded) | `[num_sched_tokens, hidden_size]` |

### Chunk-level Micro-parallelism in Prefill

This section explains the implementation using the Triton FLA path (`chunk_kda_with_fused_gate`), with **chunk length C=64 (`FLA_CHUNK_SIZE`)** and **sub-block size 16×16**. The general formulas hold for any C. FlashKDA computes the same algebra but is an independent fused CUDA kernel; its tile partitioning and intermediate storage follow its own implementation and cannot directly reuse the chunking parameters shown here.

> First, we define the notation within a single chunk and a single head. S₀ is the state at the beginning of the chunk, S_C is the state at the end of the chunk. Both qᵢ and kᵢ refer to the vectors after short convolution and activation, already L2-normalized. During readout, q̂ᵢ = qᵢ √(dₖ) is used. The oᵢ and O in this section represent only the core state readout and have not yet gone through the output RMSNorm, output gate, or projection. We define per-channel log-gate and intra-chunk prefix sums: both logarithm and exponentiation are element-wise, and the prefix sum is reset at the start of each chunk. α multiplication and e^G represent the same set of decay factors. As mentioned earlier, there are three execution stages: precomputation and output across different chunks can be parallelized, while state passing between blocks of the same request remains sequential. Chunking itself does not eliminate recursive dependencies; the intra-chunk computation must still be reorganized into operations suitable for GPU execution.

In the Decode phase, only one new token arrives at a time, so the S_{t-1} → S_t update is naturally performed in a single step. In the Prefill phase, an entire batch of input is already available. If state updates were still performed token-by-token, the temporal dependency would limit parallelism. The main computations would remain matrix-vector multiplications, outer products, and reductions, making it difficult to achieve the high efficiency of large matrix multiplications on Tensor Cores.

**Chunkwise Reordering** converts a large number of per-token sequential operations into matrix multiplications. This allows both state and input to be reused across multiple tokens and increases opportunities for parallelism along the time dimension. At the same time, it introduces overhead from auxiliary matrices and snapshots. It does not require every token in every step to execute simultaneously; the final benefit depends on the balance of these costs and must be measured against real kernel performance.

What we need to compute is not only “what the state becomes after this chunk ends,” but also “what each token inside the chunk reads out individually.” Therefore, the following derivation has two goals:

- **Block-end state SC** is passed to the next chunk to continue maintaining historical memory.
- **Intra-chunk output O** contains, for every token in the current chunk, the value *oi* it reads after completing its own update. These values are used for subsequent normalization, output gating, and projection.

![](/api/kb-media/W88PbGwJQo7NmZxVYYZcDuurnZg)

Obtaining only **SC** is not equivalent to having obtained all *oi*. The *i*-th token must read its own *Si*; it cannot simply use the block-end **SC**. What follows is to rewrite both the state update and the per-position readout as lower-triangular systems and matrix operations—while preserving the original recurrent results—without having to materialize the full intermediate states *S₁, …, S_{C-1}* just to compute the outputs.

From the earlier discussion, we already have the formula:

![](/api/kb-media/BrlhbdoUmo2rC7xQGVVcZe98nsg)

Given that a chunk contains *C* tokens, its block-end state can be written as

![](/api/kb-media/LxKwbg22qoSsXLx80TycItcAn2e)

The matrix chain multiplications are arranged from left to right in increasing index order. When *i = C*, the empty product is **I**_dₖ, so the last term is simply *H_C*.

![](/api/kb-media/WDspb9WYKoq9EIx3Trhc2by5nDh)

Abbreviated as:

![](/api/kb-media/Vl0Ibbyu5odVGfxDtnIcm0hOn23)

![](/api/kb-media/Fy27bFZU4oZjYSxLzyocRymnn1e)

This formula splits the origin of the state into two independent paths:

- **New information added inside the chunk**: After the chunk’s values are written, how much of them remains after being transformed by all subsequent tokens? This is exactly **Δchunk**.

![](/api/kb-media/HD93b1xiPokxL1xAJD4ce86bnif)

- **Information passed in from outside the chunk**: What does the incoming state *S₀* become after passing through the current chunk? This is described by **Transitionchunk**.

![](/api/kb-media/J0febCKugoURoMxrWiHcmLpYn81)

Therefore, the derivation proceeds in the following order:

1. Compute **Δchunk**: By definition it does not contain *S₀*, so it only tracks the value writes within this chunk and their subsequent transformations.
2. Compute **Transitionchunk**, then split it into two parts:
3. a. Direct decay of *S₀* by the chunk-end forget gate **α**.
4. b. Residual updates from each token in the chunk, which further modify *S₀*.
5. Recombine the two paths to obtain the block-end state **SC** for inter-chunk passing.
6. Compute the intra-chunk output **O**: reuse the actual residual writes obtained earlier, and organize each position’s *oᵢ = Sᵢ q̂ᵢ* into matrix multiplications, without needing to materialize the full intermediate states.

The output part ultimately yields:

![](/api/kb-media/FUJ3buNeyodvzCxPwBQc8hHAnoc)

Keep in mind the role of each term: **Q̂**_in is the query attenuated from the beginning of the chunk up to the current position; **E** stores the actual residual write of each token in rows (already multiplied by the write gate **β**); **M** is a lower-triangular read matrix that includes the diagonal, ensuring each token only reads its own writes and those before it. The concrete forms will be expanded in the later “Intra-chunk Output” section.

The following two diagonal-matrix identities are used repeatedly:

![](/api/kb-media/Nrx1bZ3CQova5uxeHdHcVtv2nMb)

Only diagonal decay terms can be merged this way; general *Tᵢ* cannot be freely reordered.

#### Computing Δchunk

**1. Considering only intra-chunk writes, re-express each write**

**Because Δchunk does not contain S₀, this section only computes the accumulation of writes inside the chunk and ignores the effect of the incoming state.** This is equivalent to executing the same update starting from a zero state, rather than requiring the actual incoming state to be zero.

We first expand with a reduced four-token example:

![](/api/kb-media/ZB34bmvSDowIgCxK69DcZyItnAG)

Let *Sᵢˡᵒᶜ* denote the state that starts from zero and contains only the writes of the current chunk, with *S₀ˡᵒᶜ = 0* and *S_Cˡᵒᶜ = Δchunk* at the end of the chunk. The corresponding residual value is denoted *uᵢ*: it is obtained by subtracting the prediction produced by previous writes inside the chunk from the current *vᵢ*, then multiplying by the update strength *βᵢ*. It does not include the influence of the actual incoming state *S₀*. The actual residual that does contain the old-state influence is still denoted *rᵢ*.

![](/api/kb-media/WG3gbPWqeoCnLpxozeJczAlbnKg)

From the recursive expansion written with pure decay + residual:

![](/api/kb-media/GmXzbxi8sowewLxVcBxcT6vbnxe)

Generalize to arbitrary **i**. That is, at the moment when token **i** has already undergone decay but has not yet been written:

![](/api/kb-media/KXPqbhFErowSvfxtmuDcyTDAnBd)

**2. Deriving Aij from the current read**

The contribution of a historical token **j** to the current local read **S̄iloc_ki** is

![](/api/kb-media/EoMZblFvPo4R6ix60q5cRjtInmM)

The term in brackets is a scalar representing the degree of alignment between the historical key (after decaying to the current read position) and the current key. Sum all historical contributions and substitute into the residual definition:

![](/api/kb-media/UgsGbc7RhoEr1px14A1cajagngd)

Only now do we name the coefficient inside the brackets **Aij**:

![](/api/kb-media/JVRKbOX1wohkKRxkgtKcuyXsn3f)

**A** is a coefficient matrix that **records “how much predictive contribution previous tokens make to the current token.”** Thus we have

![](/api/kb-media/T5LNb69S8omh0txBekicbd3bnlg)

Three details here are easy to confuse:

- Decay starts at **j+1**, because **u_j k_j^T** is written only after token **j**’s own decay has been applied.
- The decay includes **i**, because token **i** first decays and then reads the historical state.
- The coefficient is multiplied by the current **β_i**, rather than multiplying **β_j** again; the historical update strength is already absorbed inside **u_j**.

Setting the coefficient to zero when **j ≥ i** comes from the causal order, not from any orthogonality requirement on the keys.

**3. Organizing the recurrence into a unit lower-triangular system**

For ease of illustration, the following uses a reduced 4-token example (**C=4**):

![](/api/kb-media/PcMdbManroGnX4xKAxKcmF8Ancf)

Move all **u** terms to the left-hand side, arrange the transposes of the column vectors into rows ordered by token, and define

![](/api/kb-media/WJvJbP6qSoE83NxUPZwcrgZenSe)

The four equations above then become

![](/api/kb-media/S9BJbfbp6oGWPoxk2VxcLVdenPb)

Therefore, for any **C** we have

![](/api/kb-media/TehAba23soFHdqxfVwtcmHo5nl1)

The 1’s on the diagonal come from each row’s own **u_i**; the strictly lower-triangular **A** records the dependence on historical residuals. Since **I+A** has all 1’s on the diagonal, it is always invertible and does not require the keys to be linearly independent.

Writing it as an inverse matrix is a mathematical expression; in practice one can directly solve the unit lower-triangular system, or first compute the inverse and then multiply it by the right-hand side. Both approaches solve the same underlying relationship.

**Why does rewriting as a lower-triangular system make it faster, even though dependencies still exist?**

Simply writing **(I+A)^(-1)** does not eliminate the dependencies. If one still performs forward substitution row-by-row, the per-row dependence remains. The engineering solution is to further block the matrix: short recurrences are kept inside small blocks, while merging across sub-blocks is turned into matrix multiplications as much as possible.

Let **L = I + A** and partition it into blocks corresponding to two groups of tokens:

![](/api/kb-media/E4i0bfGqRo4uPXxfw19c1GqRnse)

**L11^(-1)** and **L22^(-1)** can be prepared independently. Once both are ready, the bottom-left block is merged via matrix multiplication. This formula can be applied recursively, breaking a long row-wise dependence into short sub-block recurrences plus several matrix-multiplication stages.

The vLLM Triton `solve_tril` implementation examined in this article uses 16×16 sub-blocks and provides paths for merging up to 32×32, 64×64, etc. Loops remain inside the sub-blocks, while the cross-sub-block part uses matrix multiplication.

After obtaining **R = (I+A)^(-1)**, one can compute **U = R(BV)** via matrix multiplication. The same **R** can be reused later when computing the correction direction **W** for the old state. The performance gains come from parallelism between sub-blocks and chunks, data reuse in matrix multiplications, and reuse of the solved results. Computing the inverse and storing auxiliary matrices also incurs cost, so the chunk size must be chosen according to hardware and precision requirements.

**4. Sending each residual write to the end of the block**

The obtained **u_i** corresponds to the write instant. Its corresponding term in the block-end expansion must also include the decay that occurs after writing. Define

![](/api/kb-media/FQLGbXdzMoUjYsxHfpOcYDJwn9g)

The empty element-wise product here is the all-1 vector, so **k_{g,C} = k_C**. In the 4-token reduced example:

![](/api/kb-media/N2w9bTYDeoX4qPxUbubcfbqsn7S)

This section only accumulates writes within the chunk, so what we obtain at the end of the chunk is exactly **Δchunk**. Still using four tokens (C=4) as an example, let’s fully expand the matrix multiplication:

![](/api/kb-media/AvqIbB5cxoxdAAxZhsZcmhgtnEf)

The final step is not an extra assumption but the very definition of matrix multiplication: the *i*-th column of **UT** is **ui**, the *i*-th row of **Kg** is **kg,i**<sup>T</sup>, and their product is precisely the sum of these outer products.

This relationship holds for any chunk length *C*, so the result of the first line is

![](/api/kb-media/BhU1b0HmJoWcBGxC6Tbci7zbn6f)

#### Computing Transition<sub>chunk</sub>

What we calculated above is the intra-chunk increment excluding **S0**. Now we compute the influence of the incoming state **S0**. Here **Si** denotes the full actual state, distinguished from the earlier local state **Si**<sub>loc</sub>. This line answers only one question: **what remains of the old state after passing through the entire chunk?**

Starting from the single-token formula

![](/api/kb-media/Hx0sbcgyQoboesx5bKrcSDQhnrg)

we can see that the old state undergoes two distinct operations:

- The forget gate directly scales the key columns of the state.
- The current token first reads the existing prediction from the state, then subtracts that prediction along the outer-product direction of the current key before writing the target value.

**Direct effect of the DC forget gate on S0**

First, extract the direct terms in the expansion where **S0** is only scaled by successive gate-controlled decays:

![](/api/kb-media/Rm0EbXOxAoFvMkxBgu8cvsalnLe)

Since **Diag(αi)** is a diagonal matrix, these decays can be multiplied element-wise:

![](/api/kb-media/YYxwbQWe3oXuFTxSHWPc6pdFn8g)

which yields

![](/api/kb-media/WBfpbVhYloPZowxwe0Sck1hFn3g)

For the *b*-th column of the state, the scaling factor is simply ∏<sub>t=1</sub><sup>C</sup> α<sub>t,b</sub>. This part depends only on the forget gate and is independent of the keys, values, and β.

However, this is still not the complete **S0Transitionchunk**: even if all αi = 1, subsequent residual updates can still modify the old state.

**Further influence of subsequent tokens’ residual updates on S0**

**1. First, compute the direct read from the old state up to the current position**

What token *i* reads from the purely decayed old state is

![](/api/kb-media/MXUybMNfEoNYnNxbF4Xcxh8nnFu)

Defining

![](/api/kb-media/APFwb6dmrohXyjx0SwRcGibXnMh)

the above becomes **S0pi**. The decay here runs from the beginning of the chunk all the way to the current token and includes αi, because the read occurs *after* the current decay.

For example:

![](/api/kb-media/HlaubKCk4o6lmMxH7DhcNCYxngZ)

Note: **S0pi** is only the direct read from the old state *before* any previous residual corrections. It is **not** the complete influence of the old state on the current position. Previous tokens have already rewritten their residuals based on the old state, and the current token will also read those modifications.

**2. Isolate the effect of S0 within the full actual residual**

Expand the general recurrence **Si = Si−1 Diag(αi) + ri ki**<sup>T</sup>. Before token *i* performs its read, we have

![](/api/kb-media/ZKZabbac7owvC6xtwQ9c64ginHc)

Multiplying on the right by **ki** and substituting **ri = βi (vi − S̄i ki)** gives

![](/api/kb-media/PnkubS4lyoSK0oxUWY6cHKhXnvb)

The matrix **A** appearing here is exactly the same as the one used when computing Δ. This is because, regardless of where the historical residuals came from, the decay and readout process for any historical write **rj kj**<sup>T</sup> up to the current position remains identical.

Compare this with the local residual formula obtained earlier when tracking only intra-chunk increments:

![](/api/kb-media/JyWibjQpAotK7IxjZj5crcBEnMc)

Subtracting the two equations cancels the original value terms:

![](/api/kb-media/GetWbJizpoiawUxS9I3cGw8KnXb)

This is the complete recurrence describing “how the incoming old state changes each residual.” It includes both the direct read of the current token from the old state and the indirect effects propagated through previous corrections.

**3. Extract the correction direction wi independent of S0**

The first token has no historical residual, so

![](/api/kb-media/VTqcbdwRqok1eExqxsBcdF8yn0b)

We therefore define **w1 = β1 p1**. If we already have **uj − rj = S0 wj** for previous steps, then

![](/api/kb-media/QaDIbzfn7otj14x3IMocCI7antd)

From this we define and generalize:

![](/api/kb-media/Y2wnbctQRowCylxKhR1clwf5nme)

Here we do not invert S0, nor do we require S0 to be full rank. The vector **wi** is a direction vector of length **dk**, determined solely by the key, the forget gate, and **β**. When converting the local residual **ui** into the actual residual **ri**, the portion of the old state’s value that must be subtracted is exactly **S0wi**.

Taking four tokens as an example:

![](/api/kb-media/UYN3bZ0cDotG8Yxf9xNcG4RWnCc)

**Why can’t we simply set wi = βi pi?** Consider the second token as an example. The actual residual **r1** of token 1 has already been corrected relative to its local residual **u1** by the term **−S0w1**. Token 2 will read this difference, so its own net correction must further subtract **A21w1**. The same logic applies to all subsequent steps.

Therefore, each correction is not an independent erasure of the original **S0**. Previous tokens have already altered the influence of the old state that later tokens will read. These interactions are fully captured by the recurrence of **A**.

**4. Why computing W can reuse the lower-triangular system computed for U**

The previous section derived a per-token recurrence:

![](/api/kb-media/NENQbamvQoXfe8xgNE5c2h8nnVd)

where both **wi** and **pi** are vectors of length **dk**, and **Aij** is a scalar used to scale the historical vector **wj**. We now reorganize these recurrences into a single matrix equation. The key insight is that each row of the matrix multiplication exactly corresponds to the recurrence equation of one token.

**Step 1: Move all terms involving w to the left-hand side.**

![](/api/kb-media/U7O9bS1NWoWU7px5KBbc89ywnWc)

Continuing with the four-token example, after rearrangement we obtain:

![](/api/kb-media/QNCLbfx9XosDDLxGWI8cl2LdnWg)

In each row, the coefficient of the current **wi** is 1, the coefficients of historical **wj** are **Aij**, and the coefficients of future **wj** are 0. This is precisely a lower-triangular coefficient matrix with ones on the diagonal.

**Step 2: Arrange the equations by token into matrix form.**

First, let’s clarify what **Kin** stores. Earlier we expressed token **i**’s pure decay reading of the old state as **S0pi**, where

![](/api/kb-media/WyuNbraqho3YpexHr3gcks3Unrg)

That is, we can fold the gated decay from the beginning of the chunk up to the current position into the current key, and then use this **pi** to read the original incoming state **S0**. **Stacking these reading directions for all tokens row-wise yields Kin.** The subscript “in” indicates that it is used for reading the incoming state.

![](/api/kb-media/Fk1Eb4C7uoNYKoxCWB9cemqNnDb)

For the four-token case:

![](/api/kb-media/SH0ebC4YAoabRrxYApAcYSnUnSN)

**Kin** depends only on the keys and forget gates; it does not contain **S0**, values, or **β**. It provides the direct reading directions. Only after combining **β** with the corrections from historical residuals do we obtain the **wi** appearing in the earlier recurrence. We also stack these correction directions row-wise and define

![](/api/kb-media/SsANb6ohEoEzVMxb41Ocw20znzO)

Both matrices have shape **C × dk**. The transpose is used simply to turn the original column vectors into rows of a matrix; therefore, each vector equation above must also be transposed. The four-token equations can then be written compactly as:

![](/api/kb-media/Z0mqbbABPoGUe1xuHIgcOcO7nab)

For example, expanding the third row of the left-hand matrix multiplication gives

![](/api/kb-media/UQkPb9rDjozF9rxFJHWcGKcTndb)

which exactly equals **β3p3T** on the right-hand side of the third row. Thus, this matrix equation merely assembles the per-token equations without altering the underlying recurrence.

The matrix **A** defined earlier is strictly lower-triangular with zeros on the diagonal. Adding the identity matrix **I** supplies the coefficient 1 for the current **wi**. Each row on the right-hand side is **piT** scaled by the corresponding **βi**. Using the notation **B = Diag(β1, …, βC)**, the right-hand side becomes **B Kin**.

Therefore, for any chunk length **C**, we have

![](/api/kb-media/ET9ybeOLfovaaXxCQJkcy4WFnWd)

**Step 3: Reuse the already-computed lower-triangular inverse.**

Placing this alongside the equation for **U** obtained earlier:

![](/api/kb-media/XpGVbRocloNg57xfln4cdC3dnwf)

Both equations share the same coefficient matrix **I + A**. We can therefore reuse the matrix **R = (I + A)−1** that was computed while solving for **U**:

![](/api/kb-media/J6OZbJp4qo6d6RxAkZccXjUcnnb)

Computing **W** requires no additional inversion; we only need to multiply the same **R** by the new right-hand side **B Kin**.

**5. Propagating the correction to the old state to the end of the chunk**

We have already derived the relationship between the actual residual and the local residual:

![](/api/kb-media/Qu7IbtCbHoA6TExhiwHcKxuRnVd)

But the residual **value** itself is not yet a matrix in the written state. According to the update rule \( S_i = S_{i-1} \operatorname{Diag}(\alpha_i) + r_i k_i^T \), each write operation requires taking the outer product of the residual value with the current key. Therefore, the \( i \)-th write in the two cases is as follows:

![](/api/kb-media/It0mbqN9Yo8WT4x38WMcB9uFnmc)

Subtracting the local incremental write from the actual write yields the write difference caused by \( S_0 \):

![](/api/kb-media/VmMwbrFLqoAB9kxE4iRcQAeunug)

Next, we carry this difference to the end of the chunk. Following the definition used when computing \( \Delta_{\text{chunk}} \), we define the end-of-chunk decayed key:

![](/api/kb-media/QD9QbKFRxoaEA4xwfjicxbtWnKh)

This expression does not include \( \alpha_i \), because the current write occurs after the decay; for the last token, \( k_{g,C} = k_C \). Under the residual write expansion, the corresponding term from the \( i \)-th write difference to the end of the chunk is

![](/api/kb-media/OcgObcF6coGyklxJv2pcIvsDn7g)

Subsequent residual responses to it have already been recorded in later \( w_j \). Therefore, similar to the calculation of \( \Delta \), we only retain the subsequent pure decay here and cannot multiply by a full \( T \) again.

Arranging \( k_{g,i}^T \) into rows by token produces the earlier \( K_g \); the \( i \)-th row of \( W \) is \( w_i^T \). Thus, the matrix multiplication \( W^T K_g \) exactly equals the sum of all outer products \( \sum_i w_i k_{g,i}^T \). Adding up all tokens’ correction terms to the old state, we obtain:

![](/api/kb-media/Zm4ubovGNodAp6x0XEbcBIDGnNc)

The two parts of the Transition are now finally combined:

![](/api/kb-media/FAnbbQ3hxoD4pJxYhxxcI5kunjg)

This equation holds for any \( S_0 \), so

![](/api/kb-media/E84wbM7SZonoUVxS1Ncc1tMsnsg)

The statement that “forgetting in part b is a form of directional correction” is intuitive. It does not imply that every element of \( W^T K_g \) is non-negative, nor does it guarantee that every element of the state decreases. For example, when \( \|k_i\|_2 = 1 \) and \( \beta_i = 1 \), \( I - k_i k_i^T \) removes the component of the decayed state in the direction of \( k_i \). In general, the matrix formula should be taken as the authoritative reference.

#### Merging to Obtain the End-of-Chunk State

For any \( S_0 \), expanding \( S_i = S_{i-1} \operatorname{Diag}(\alpha_i) + r_i k_i^T \) gives

![](/api/kb-media/D0NhbkgQ1oHiuExW0XHchfLBnRg)

Substituting the derived \( r_i = u_i - S_0 w_i \):

![](/api/kb-media/XSMRbQbMeoFHWAx8sVccVon3nzf)

Thus we finally obtain

![](/api/kb-media/CNyZbGIc9oinOkx0UIKcq8BsnKf)

The first two terms belong to \( S_0 \text{Transition}_{\text{chunk}} \), and the third term belongs to \( \Delta_{\text{chunk}} \). This is an exact rewrite of the opening formula, with no approximations and no omission of cross terms between tokens.

![](/api/kb-media/OscqbZ188orOAkxX5u3c2u4Kndd)

#### Intra-Chunk Output: Parallel Readout Without Materializing Per-Token States

The previous merging yields the end-of-chunk state \( S_C \). However, the model output requires each token to read its own state \( S_i \), and \( S_1, \dots, S_{C-1} \) are precisely the intermediate states that the chunk algorithm aims to avoid generating one by one.

The complete sequential order for a single token is: decay first, then read the residual, then write, and finally read out.

![](/api/kb-media/L2TybKlfqoFYPxxtABPcjY6Zntg)

Unrolling the state recurrence to step \( i \):

![](/api/kb-media/CEZAbg2MQoYWMJxea8HcMkE6ntc)

Therefore, the output of the \( i \)-th token is:

![](/api/kb-media/XYWPbKf1oojrBixuW4fcaf1gnEg)

The first term is read from the decayed chunk-initial state; the second term is read from the actual writes at the current and historical positions.

Define the query with decay from the chunk start to the current position:

![](/api/kb-media/Hi7ebJmjuoLGqoxeTCKcx5Kunyf)

For ease of illustration, the following uses a reduced 4-token example (\( C = 4 \)):

![](/api/kb-media/VMBPbZynRoZgJUxJ5H9cAAlOn1e)

Define the lower-triangular readout matrix \( M \) that includes the diagonal:

![](/api/kb-media/KbrObtqNroe0hRxRRYfct5qinxe)

\( M_{ij} \) represents the proportion of token \( j \)'s write, after decaying to position \( i \), that is read out by \( \hat{q}_i \).

![](/api/kb-media/IlJQbCnyxoRNUuxq8C0cWUc0nJh)

Then stack the actual residuals by row:

![](/api/kb-media/RVFubsAINopmvyxUpPMcnRZwnPh)

Thus, the output of the entire chunk can be written as:

![](/api/kb-media/QvuZbk44IogXWmxhD6Uc8LIynCd)

The *i*-th row of **E** is the actual residual *rᵢᵀ*, i.e., the value that token *i* actually writes into the state. It differs from the earlier local residual **U** by the correction *WS₀ᵀ* introduced by the old state. Here **U** comes from solving the local write residual, and **W** comes from the old state’s correction to the residual.

Verification for *i*=1:  
*S₁ = S₀Diag(α₁) + r₁k₁ᵀ*, so  
*o₁ = S₀(ˆq₁ ⊙ α₁) + (ˆq₁ᵀ k₁)r₁*, which matches the formula.

Expanding **E** yields a term-by-term correspondence with the previous block-end state formula:

![](/api/kb-media/A1QlbFuTJoc4S1xZUeJceeokndb)

#### Complete Computation Order

We have now derived the intra-chunk local write, the correction from the old state to the write, and the intra-chunk output. Combining them gives the full computation formula for one chunk.

A chunk must produce two types of results:

- **Block-end state S_C** to be passed to the next chunk;
- **Intra-chunk output O** containing the output for every token in the current chunk.

**Decay Intervals**

| Purpose | Decay Factor | Corresponding Interval | Interval | Object |
| --- | --- | --- | --- | --- |
| Old state participates in the residual computation and read at step *i* | *e^{G_i}* | Step 1 to step *i* | From old state at block start until before current read | *p_i*, i.e. the *i*-th row of **K**_in transposed |
| Write at step *j* affects step *i* | *e^{G_i - G_j}* | Step *j*+1 to step *i* | After historical write until before current read | Historical key used when constructing *A_{ij}*, *j < i* |
| Write at step *i* is aggregated to the block tail | *e^{G_C - G_i}* | Step *i*+1 to step *C* | After current write until block end | *k_{g,i}*, i.e. the *i*-th row of **K**_g transposed |

All boundaries follow the same convention: **decay first, then read/write.**

Because element-wise multiplication equals the exponential of the sum of logs, we have

![](/api/kb-media/UeQBbm5lFor0ZKxtoS2cIBjWndO)

Here *G_i - G_j* exactly cancels the first *j* terms, leaving only terms *j*+1 through *i*. Similarly, *G_C - G_i* leaves only terms *i*+1 through *C*.

**Computation Order and Shape Checking**

We can now start from the inputs and chain the entire process according to computation dependencies. The following considers only one chunk and one head. The inputs are: incoming state *S₀*, key matrix **K** with tokens arranged in rows, value matrix **V**, update strength *βᵢ* for each token, and per-dimension log-gate *gᵢ = ln αᵢ*.

**Step 1: Compute prefix sums along the token dimension to obtain G.**

![](/api/kb-media/GeJ2blCSZoPidUxrtnGcqEGRnCh)

Arrange each *gᵢᵀ* as a row. For four tokens this becomes:

![](/api/kb-media/TO4wbbArfotq2hx1e8VcoAQJn0d)

This step only produces the cumulative log-gates; it does not yet produce the decay factors or the decayed keys. Only after taking the element-wise exponential of *Gᵢ* do we recover *α₁ ⊙ ⋯ ⊙ αᵢ*.

**Step 2: From the same G, construct two kinds of keys and extract the full-block decay.**

For **K**_in, each row of keys is multiplied by the decay from the block start up to the current position:

![](/api/kb-media/FYYsbwsezoT9TLxbnNYcSQ73nrg)

![](/api/kb-media/LGD0bqDM5oCKKbxshBqcpMeQnFe)

For **K**_g, subtract each row’s cumulative value from the block-end cumulative value, then take the exponential and multiply by the key:

![](/api/kb-media/Cz9vbys5bo1QGXxd2wbcVywYnIf)

![](/api/kb-media/IhHbb0c3xo1OUlxRCqPccLpSnLe)

For example, with four tokens, *G₄ - G₂ = g₃ + g₄*, so the second row of **K**_g is *(k₂ ⊙ α₃ ⊙ α₄)ᵀ*. The same prefix sum is reused; there is no need to compute a separate suffix sum.

The pure decay of the old state is also given by the same result: the scaling factor for each column is *e^{G_C}*. Up to this point, only keys and gates have been used; the residual has not yet been computed.

**Step 3: Construct A from the keys, G, and β, then compute (I + A)⁻¹.**

![](/api/kb-media/WoJjbVEL5ocPMnxo01kcl0DWnsb)

Specifically, first compute *exp(Gᵢ - Gⱼ)* to obtain the cumulative decay factor between the historical write at *j* and the current read at *i*; element-wise multiply it with the historical key *kⱼ*, take the inner product with the current key *kᵢ*, and finally multiply by the current update strength *βᵢ*.

Then compute

![](/api/kb-media/XnMtbIcmLoQaNaxKcy2cNeIGnph)

Here, **I + A** is the coefficient matrix of the residual recurrence, not the all-ones lower triangular matrix used in the first step for accumulating log-gates. The prefix sums together with the two types of keys only solve the decay problem; the residual dependencies between historical writes still need to be handled by this lower triangular system.

**Step 4: Compute U and W separately using the same R.**

![](/api/kb-media/B24lbMzF5oJr3Nxa2kFc25s0nNf)

First multiply each row of **V** and **K**<sub>in</sub> by its corresponding β<sub>i</sub>, then left-multiply by **R**. This step respectively produces the local residual **U** of the current chunk and the residual correction direction **W** induced by the old state.

**Step 5: Substitute S₀, merge the residuals, and update the state.**

![](/api/kb-media/GhA9bmoRTom6wbxUAkzcVwbRnoc)

First compute the actual residual using the undecayed **S₀**, then multiply **S₀** column-wise by the full-block decay, and finally add the write aggregated by **K**<sub>g</sub> from the actual residual. There is no need to generate three complete state matrices (pure decay, residual correction, and local increment) separately and then add them together.

**Step 6: Introduce the query and compute the intra-chunk output using the same actual residual E.**

The output also requires a query matrix **Q̂** ∈ ℝ<sup>C×d<sub>k</sub></sup> arranged by token (already L2-normalized and scaled). First reuse the cumulative log-gate **G** from Step 1, so that each row of the query is multiplied by the decay from the beginning of the chunk to the current position:

![](/api/kb-media/K63rbbpzNoox1bxYhUYcMsVIn3f)

Then construct the lower triangular read matrix **M** that includes the diagonal:

![](/api/kb-media/LcaWbvJ6bo5KgnxWGrbcQJHgnGd)

It is constructed similarly to matrix **A** in Step 3, but with three differences: the current read vector uses **q̂**<sub>i</sub> instead of **k**<sub>i</sub>, it no longer multiplies by the update strength β<sub>i</sub>, and the diagonal is retained. Because the output is read after the current write, the *i*-th token can read its own write:

![](/api/kb-media/W3C9b9p83oCG6RxHIK6crinDnRh)

Then directly use the actual residual **E** obtained in Step 5 to compute the output for the entire chunk:

![](/api/kb-media/YCGyb4BPcovixHxYveAc95j3npc)

Among them, **Q̂**<sub>in</sub>**S₀**<sup>T</sup> is read from the decayed chunk-initial state, and **ME** is read from the current and historical actual writes. The update strength β<sub>i</sub> is already incorporated in **E**, so there is no need to multiply it again inside **M**.

The starting point of the entire derivation is the transformation of the old state plus the accumulation of intra-chunk writes. To actually compute these two parts, the per-token update is first rewritten as pure decay + residual write.

For the new value, historical reads produce the coefficient matrix **A**. From this we solve for the residual **U** that contains no influence from the old state, then aggregate it with the chunk-end key **K**<sub>g</sub> to obtain **Δ**<sub>chunk</sub>.

For the old state, we first retain **S₀**Diag(α₁⊙⋯⊙α<sub>C</sub>) brought by the forget gates, then track how the old state modifies each residual. This difference goes through the same historical read relationship, so we reuse the same **A** to solve for **W**, which forms **−S₀W**<sup>T</sup>**K**<sub>g</sub> at the end of the chunk.

Ultimately, the two sources of information propagate through the same update rule:

![](/api/kb-media/KLZCbWWx1oJl1QxUi7Jca0aenzh)


## Summary

As the saying goes, large language models themselves are more like an experimental science built on assumptions, while the underlying AI Infra is genuine mathematics and engineering.

From standard linear attention, DeltaNet, and GDN all the way to KDA, the core idea has always been the same: making trade-offs between model expressiveness, algorithmic parallelism (algebraic structure), and hardware cost (memory access and compute). Whether it is the Linear Attention discussed in this article, or MLA, DSA, CSA, SWA, and IndexCache, they are all essentially moderate compromises on the full attention mechanism—sacrificing some expressive power in exchange for improvements in computation and memory efficiency. This is precisely the essence of **Hardware-Software Co-design** between algorithms and system architecture.

This article is part of the series *Large Model Architecture Evolution: From Memory Wall to Million-Token Context*. Other parts are still being prepared...

## References

[Attention Is All You Need](https://arxiv.org/abs/1706.03762)

[DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://arxiv.org/abs/2501.12948)

[DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model](https://arxiv.org/abs/2405.04434)

[DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437)

[DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence](https://arxiv.org/abs/2606.19348)

[DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/main/DeepSeek_V41_Tech_Report.pdf)

[DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models](https://arxiv.org/abs/2401.06066)

[Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention](https://arxiv.org/abs/2502.11089)

[IndexCache: Accelerating Sparse Attention via Cross-Layer Index Reuse](https://arxiv.org/abs/2603.12201)

[Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)

[Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)

[Identity Mappings in Deep Residual Networks](https://arxiv.org/abs/1603.05027)

[Hyper-Connections](https://arxiv.org/abs/2409.19606)

[mHC: Manifold-Constrained Hyper-Connections](https://arxiv.org/abs/2512.24880)

[Your DeepSeek mHC Probably Doesn’t Need the “m”](https://zhuanlan.zhihu.com/p/2010852389670908320)

[Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models](https://arxiv.org/abs/2601.07372)

[Universal Transformers](https://arxiv.org/abs/1807.03819)

[Adaptive Computation Time for Recurrent Neural Networks](https://arxiv.org/abs/1603.08983)

[Relaxed Recursive Transformers: Effective Parameter Sharing with Layer-wise LoRA](https://arxiv.org/abs/2410.20672)

**Mixture-of-Recursions: Learning Dynamic Recursive Depths for Adaptive Token-Level Computation**  
**Scaling up Test-Time Compute with Latent Reasoning: A Recurrent Depth Approach**  
**Blockwise Parallel Decoding for Deep Autoregressive Models**  
**Speculative Decoding: Exploiting Speculative Execution for Accelerating Seq2seq Generation**  
**Fast Inference from Transformers via Speculative Decoding**  
**Accelerating Large Language Model Decoding with Speculative Sampling**  
**EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty**  
**EAGLE-2: Faster Inference of Language Models with Dynamic Draft Trees**  
**EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test**  
**Better & Faster Large Language Models via Multi-token Prediction**  
**SuffixDecoding: Extreme Speculative Decoding for Emerging AI Applications**  
**Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads**  
**DFlash: Block Diffusion for Flash Speculative Decoding**  
**DSpark: Confidence-Scheduled Speculative Decoding with Semi-Autoregressive Generation**  
**Speculative Decoding**  
**Adaptive Verification in vLLM: DSpark confidence-scheduled verification**  
**Efficient Streaming Language Models with Attention Sinks**  
**Attention Is Off By One**

[When Attention Sink Emerges in Language Models: An Empirical View](https://arxiv.org/abs/2410.10781)

[Why do LLMs attend to the first token?](https://arxiv.org/abs/2504.02732)

[gpt-oss-120b & gpt-oss-20b Model Card](https://arxiv.org/abs/2508.10925)

[RadiK: Scalable and Optimized GPU-Parallel Radix Top-K Selection](https://arxiv.org/abs/2501.14336)

[Gated Delta Networks: Improving Mamba2 with Delta Rule](https://arxiv.org/abs/2412.06464)

[Kimi Linear: An Expressive, Efficient Attention Architecture](https://arxiv.org/abs/2510.26692)

[Linear Transformers Are Secretly Fast Weight Programmers](https://arxiv.org/abs/2102.11174)

[Parallelizing Linear Transformers with the Delta Rule over Sequence Length](https://arxiv.org/abs/2406.06484)

[Eagle and Finch: RWKV with Matrix-Valued States and Dynamic Recurrence](https://arxiv.org/abs/2404.05892)

[Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention](https://arxiv.org/abs/2006.16236)

[The Devil in Linear Transformer](https://arxiv.org/abs/2210.10340)

[Hungry Hungry Hippos: Towards Language Modeling with State Space Models](https://arxiv.org/abs/2212.14052)

[Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://arxiv.org/abs/2312.00752)

[Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality](https://arxiv.org/abs/2405.21060)

[Retentive Network: A Successor to Transformer for Large Language Models](https://arxiv.org/abs/2307.08621)

[Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635)

[RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864)

[LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685)

[A Storage Efficient WY Representation for Products of Householder Transformations](https://ecommons.cornell.edu/entities/publication/592a21c4-ab2b-4bee-b804-8dc8b154a1eb)

[Marconi: Prefix Caching for the Era of Hybrid LLMs](https://arxiv.org/abs/2411.19379)

[ReplaySSM: Cache SSM Inputs, Not State](https://arxiv.org/abs/2610.13778)

[ReplaySSM: Rethinking State Storage for Faster Hybrid-Model Decoding](https://developer.nvidia.com/blog/replayssm-rethinking-state-storage-for-faster-hybrid-model-decoding/)

[Automatic Prefix Caching](https://docs.vllm.ai/en/latest/design/prefix_caching/)

[Hybrid KV Cache Manager](https://docs.vllm.ai/en/stable/design/hybrid_kv_cache_manager/)

[The Transformer Positional Encoding That Has Researchers Rack Their Brains](https://kexue.fm/archives/8130)

[A Brief History of Linear Attention: From Imitation and Innovation to Mutual Reinforcement](https://www.spaces.ac.cn/archives/11033)

[Linearizing Softmax Attention into Gated DeltaNet](https://spaces.ac.cn/archives/11823)

[Linear Attention, Visualized](https://snowchord.com/blog/linear-attention-visualized/)

[The Road to Transformer Upgrades: 2. Rotary Positional Encoding That Combines the Strengths of Many Approaches](https://kexue.fm/archives/8265)

[YaRN: Efficient Context Window Extension of Large Language Models](https://arxiv.org/abs/2309.00071)

[The Extreme Tug-of-War Between Cache and Performance: From MHA, MQA, GQA to MLA](https://kexue.fm/archives/10091)

[From 305 GB to 7.4 GB: A Full Panorama of Large Language Model KVCache Architecture Evolution](https://km.woa.com/articles/show/659617?from=iSearch)

[Calculating the KVCache Size of DeepSeek Flash V4.1](https://mp.weixin.qq.com/s?__biz=MzI2NDQyNjY3NA==&mid=2247484178&idx=1&sn=9e0474f49b532f05549e978292a354ad&scene=21#wechat_redirect)

[Scaling Kimi K3 on AMD Instinct MI355X: Matching NVIDIA HGX B300 Throughput per GPU on AgentX](https://vllm.ai/blog/2026-10-16-kimi-k3-mi355x)

[Kimi K3 Is Here: Efficient Day-0 Support on vLLM](https://vllm.ai/blog/2026-07-27-k3)

## Appendix 1. Computation of A and M within a Chunk

### 1. Why a Single Matrix Multiplication Is Not Enough

Writing it out element-wise:

![](/api/kb-media/S0QNbEdCToOuDRxlkGiciVAPnHb)

The decay factor depends on both *i* and *j*. If we split it channel-wise into *e^{G_i} ⊙ e^{-G_j}*, it can theoretically be expressed as a single matrix multiplication followed by taking the lower triangle under exact arithmetic:

![](/api/kb-media/UZqFbdrLooEUqCxzohec93bUnUf)

Here `tril` keeps the diagonal. However, since *G* is a cumulative sum of negative values, within a single chunk it can reach values as low as 64 × (-5) = -320. Then *e^{320}* far exceeds the upper limit of fp32 (approximately *e^{88.7}*), causing overflow. Adding a causal mask afterward cannot recover the already-overflowed valid lower-triangular entries.

### 2. Splitting into 16×16 Sub-blocks

We divide a `chunk_size = 64` into 4 sub-blocks:

![](/api/kb-media/FCOTbQLMKom4oDxnuG6c8opYnlb)

All upper-triangular sub-blocks are zero and can be skipped entirely.

**Non-diagonal sub-blocks *M_{ab}* (a > b): Factorized via a reference point.**  
Take the first token of row sub-block *a* as the reference point *n*:

![](/api/kb-media/A0GUb1IF8oB5J7xbP1yclcMineb)

- The factorization is exact: the two exponential segments in the same channel add up to exactly recover *G_i - G_j*.
- No overflow occurs: row *i* lies after the reference point while column *j* lies before it (*i ≥ n > j*). Since *G* is monotonically non-increasing, both exponential segments are ≤ 0.

**Diagonal sub-blocks *D_a*: Computed directly column by column.**  
Within a diagonal sub-block, rows and columns belong to the same token segment, so no reference point exists where “all rows are after and all columns are before.” Let the global index of the first token in the sub-block be *n_a*, and the local row/column indices be *r, s ∈ {1, …, 16}*, corresponding to *i = n_a + r - 1* and *j = n_a + s - 1*. Then:

![](/api/kb-media/ZtNXbOoUpojmgCxY6wbcANDinQx)

If the implementation first computes the entire column and then zeros out the rows where *i < j*, the positions being zeroed have positive exponents. However, the maximum span is only 15 tokens. When `lower_bound = -5`, the largest value is approximately *e^{75}*, which still fits within the fp32 range. The final result keeps only the part where *i ≥ j*, including the diagonal.

### 3. Sharing the Same Kernel with A

Within the same sub-block, *K_b ⊙ e^{G_n - G_b}* is computed only once and then split into two branches:

|          | Matrix multiplied on the left       | Post-processing          | Retained range |
|----------|-------------------------------------|--------------------------|----------------|
| A        | *K_a ⊙ e^{G_a - G_n}*               | Multiply each row by *β_i* | i > j          |
| M        | *Q̂_a ⊙ e^{G_a - G_n}* (Q̂ already contains scale) | —                        | i ≥ j          |

Therefore, M and A are two outputs of the same kernel. There is no need to read the key and gate values a second time.

### 4. Comparison between M and A

Both use the same decay interval from *j+1* to *i*. The differences are only in three aspects:

|                      | A_{ij}                                 | M_{ij}                                      |
|----------------------|----------------------------------------|---------------------------------------------|
| Vector for inner product with historical writes | *k_i*                                  | *q̂_i*                                       |
| Coefficient          | Multiplied by *β_i* to form the current residual | Not multiplied; write strength is already included in *r_j* |
| Diagonal             | Not included, because the residual is read before writing | Included, because the output is read after writing |

**Appendix 2: Why L2 Norm**

### What is L2 Norm

Assume the original Key vector \(\tilde{k}_t\) is a \(d_k\)-dimensional column vector: \(\tilde{k}_t = [x_1, x_2, \dots, x_{d_k}]^T\).

According to the strict mathematical definition of the L2 norm, the length of vector \(\tilde{k}_t\) is:

![](/api/kb-media/Ts5Sb2apyoZGmWxqC7vcUhh6nHe)

Now let’s look at the inner product inside the square root, \(\tilde{k}_t^T \tilde{k}_t\). When a row vector is multiplied by a column vector, it expands to the sum of the squares of all elements:

![](/api/kb-media/JmPwbELwaonWbyxWhgkc8ubbnAg)

Taking the square root of this inner product gives:

![](/api/kb-media/WYDKbFBLYoXok8xEWerc2zdSnrc)

For a non-zero vector \(\tilde{k}_t\), the ideal L2 normalization operation is:

![](/api/kb-media/Djd3bc78woGLqDx0dNycjvI2nWb)

Therefore, under non-zero input and exact arithmetic, the normalized vector satisfies \(k_t^T k_t = 1\). In engineering implementations, a small \(\varepsilon\) is usually added for numerical stability to avoid division by zero; in such cases the norm may not be strictly equal to 1. The following derivation first assumes the ideal unit-norm case. When the norm is not exactly 1, the term \(\|k_t\|_2^2\) from earlier formulas should be retained.

### Ensuring the Delta Rule Transfer Does Not Amplify Old States

First, consider the DeltaNet update without an additional forget gate:

![](/api/kb-media/AhiobKsctoVBDHxG9obc49zMngg)

L2 normalization constrains the old-state transition matrix \(I - \beta_t k_t k_t^T\). It does not by itself guarantee that the full state with persistent writes remains bounded forever, nor does it guarantee that no historical associations will be forgotten.

To verify this, we need to build an intuition: **the matrix \(S_t\) is a memory bank**. The best way to test the quality of this memory bank is to read it with different query vectors and see what can be retrieved (i.e., compute \(S_t q\)).

We need to prove that when \(0 \leq \beta_t \leq 1\), the old-state transition of the Delta Rule only shrinks or preserves values in every direction and never amplifies them. This is distinct from the standalone forget gate \(\alpha_t\) used in GDN/KDA.

We examine two directions:  
1. Querying with \(k_t\) itself (pattern matching the newly written key).  
2. Querying with vectors orthogonal to \(k_t\).

#### Querying the Knowledge Just Written

That is, querying with \(k_t\) itself:

![](/api/kb-media/Ddprbe5HBo3sK8xIPGxcIPvKnBf)

Using the associative property, we group the inner product \(k_t^T k_t\):

![](/api/kb-media/EDlnb79Kxo3Zbpx0EsscEsYdnXf)

Substituting \(k_t^T k_t = 1\):

![](/api/kb-media/V8fob8N5hojVaTxU654cwcTMnNe)

Here:

- \(S_{t-1} k_t\) is the old state’s readout on the current key.  
- \((1 - \beta_t) S_{t-1} k_t\) means the old readout is retained with a factor of \(1 - \beta_t\).  
- \(\beta_t v_t\) is the newly written value.

Thus, when \(0 \leq \beta_t \leq 1\), the readout for the current key is a weighted average between the old readout and the new value.

#### Querying Completely Unrelated Knowledge

What if, after writing \(k_t\), we query the memory with a vector \(q\) that is strictly orthogonal to it? The condition here is the mathematical requirement \(k_t^T q = 0\); semantic “irrelevance” cannot be directly treated as orthogonality.

We again right-multiply the updated memory \(S_t\) by \(q\):

![](/api/kb-media/GtQVbZumIoW0msxFu3kcvav2nLc)

Substituting the orthogonality condition \(k_t^T q = 0\):

![](/api/kb-media/JpQwbGBjKoV9itxnURJcFbcAnic)

Conclusion: In this DeltaNet update without an extra forget gate, the readout for any query strictly orthogonal to the current key remains unchanged. Non-orthogonal directions may still experience interference. When the key is unit-norm, the matrix \(I - \beta_t k_t k_t^T\) has eigenvalue \(1 - \beta_t\) along the \(k_t\) direction and eigenvalue 1 on its orthogonal complement. Therefore, the spectral norm of the old-state transition is at most 1.

For GDN/KDA, replace \(S_{t-1}\) in the above derivation with the already-decayed \(\bar{S}_t\). For example, when \(k_t^T q = 0\), KDA satisfies:

![](/api/kb-media/Qkqsb2cbVoxbZFxoUAPcCSa5njg)

which is generally not equal to \(S_{t-1} q\). In other words, orthogonal directions are unaffected by the current residual write but are still subject to the forget gate. The full old-state transition in KDA also does not amplify:

![](/api/kb-media/Ot2Tb1vS0oeYDBxefe6cBEfInAe)

This assumes \(0 \leq \alpha_{t,d} \leq 1\) and \(0 \leq \beta_t \leq 1\). When numerical protection makes \(\|k_t\|_2 \leq 1\), the “no amplification” conclusion still holds, but the claim of “exact overwrite when \(\beta_t = 1\)” requires \(\|k_t\|_2 = 1\).

## Appendix 3: Chain Rule

Assume *s*, *k*, and *v* are ordinary numbers. The loss is then:

![](/api/kb-media/VDIybueAropX8bxZsTpcgyNUnTb)

To compute the derivative with respect to *s*, we need to consider two layers:

- The outer layer is the square: the derivative of 12x² with respect to x is x.
- The inner layer is *v - sk*: its derivative with respect to *s* is *-k*.

According to the chain rule, multiply these two parts together:

![](/api/kb-media/CbadbSPM6obtrLxH5EYcDi1JnMe)


## Appendix 4: Hash Granularity

In the configuration used in this article, the `block_size` for both the MLA group and the 4 KDA groups is 640. The tail group does not participate in prefix caching hash granularity calculations. When **`--prefix-match-unit`** is **not set**:

- `hash_block_size = gcd(640, 640, …) = 640`
- `scheduler_block_size = lcm(…) = 640`

The examples in the main text — the tail stop point at 1984 and the fork point at 1216 — additionally assume that `--prefix-match-unit=64` has been explicitly set. In this case, `hash_block_size = 64`, while the physical `block_size` and `scheduler_block_size` remain 640. What changes is the hash matching granularity, not the physical block size.

```python
group_block_sizes = [
    resolve_dcp_kv_block_size(g.kv_cache_spec, dcp) for g in groups
]
scheduler_block_size = math.lcm(*group_block_sizes)
...
hashing_sizes = [
    block_size
    for group, block_size in zip(groups, group_block_sizes)
    if group.kv_cache_spec.prefix_cacheable
] or group_block_sizes
requested = cache_config.prefix_match_unit
hash_block_size = requested if requested is not None else math.gcd(*hashing_sizes)
scheduler_block_size hash_block_size
Value Least common multiple (LCM) of all groups’ block_size Greatest common divisor (GCD) of the block_size of groups participating in prefix caching; if prefix_match_unit is set, that value is used instead
Purpose Alignment unit for the scheduler: prefix hit length and advancement of computed tokens are both aligned to this unit Unit for computing Request.block_hashes: a chained hash is calculated every time this many tokens are reached
Why this choice Using the LCM ensures that at these boundaries, every group consists of an integer number of Blocks, so all groups become available simultaneously after a hit Using the GCD ensures that each group’s Block is composed of an integer number of hash units. For groups with a larger block_size, one hash is taken every block_size / hash_block_size hash units (BlockHashListWithBlockSize). The hash only needs to be computed once.

Appendix 5: Why Must Prefix Cache Hits Unconditionally Roll Back One Block When EAGLE/MTP Is Enabled (use_eagle_block_drop)?

Draft KV[i] = f(h[i], t[i+1]). The draft KV at each position depends on the next token. The last position k-1 of the final matched block uses t[k] from outside the block, but the block hash only covers t[0..k-1]. If the cached request A and the subsequent request B differ at t[k], that slot becomes invalid for B. Multi-module MTP has even longer dependencies, so up to n-1 slots at the end of a block may be affected.

  • True pollution only occurs when the fork point lands exactly on a block boundary. Let the fork point be d; a hit will stop at k = ⌊d/B⌋·B. Only when d % B == 0 is t[k] the token after the fork. When not aligned, t[k] still belongs to the common prefix, so A and B are consistent and the block is actually clean.

  • The scheduler does not store t[k] nor the hidden states, so it cannot distinguish between these two cases. It must handle the worst case: unconditionally roll back one block (or one hash unit when fine-grained hashing is enabled).

  • Shared cache blocks are read-only, so it is not possible to rewrite only that single slot; the entire block must be recomputed.

PS: Even if the entire prompt is already in the cache, the scheduler must still run a forward pass on the last token to obtain its logits for sampling the first output token. Therefore, the theoretical maximum hit rate is num_tokens - 1. Because hits are aligned to block boundaries, this “-1” leads to two different outcomes:

  • When the prompt length is not block-aligned, the last block is not full and would not be hit anyway, so the -1 introduces no extra penalty.

  • When the prompt length is an exact multiple of block_size, the -1 causes the final full block to miss entirely, forcing the entire block containing that last token to be recomputed. This is exactly what happens when an identical prompt is sent again.