As context grows, the GPU has to retain more of the interaction history. Model weights do not change during inference, but an attention layer still needs to compare the next query with past keys and aggregate their values. That history accounts for a substantial share of the memory pressure in long-context inference.
Linear attention writes the effect of history into a state matrix. When a new token arrives, the matrix is updated and then read. Storage therefore stops growing directly with the number of tokens already seen. The trade-off is that individual records no longer occupy independent positions: many associations share a finite state space. How to revise outdated information and limit interference between associations becomes a central design question.
This first part covers what the state stores, how update rules modify it, and which guarantees those rules actually provide. Part 2 organizes the same updates into GPU-friendly chunks, then examines prefix reuse, shared state, and speculative-decoding rollback. Small matrices and memory estimates throughout are teaching examples; they do not represent the hidden semantics of a production model or constitute performance measurements.
Fix the State-Matrix Convention First
Papers and implementations do not always use the same state orientation; some differ only by a transpose. We will use one convention throughout before comparing formulas:
q_t, k_t : column vectors of length d_k
v_t, o_t : column vectors of length d_v
S_t : d_v × d_k state matrix
o_t = S_t q_t
Under this convention, columns of S_t correspond to key directions and rows to value components. Writing one association uses the outer product v_t k_t^T. The Kimi Linear paper uses a d_k × d_v state; transposing it aligns the notation here and turns its left-multiplying transition into a right-multiplying one. This matters especially for channel gates: in our convention, forgetting along key channels acts on the columns of the state.
Projection matrices, input-dependent vectors, and request state should also be kept distinct. Projection matrices are learned during training and usually remain fixed during inference. The current input produces q/k/v and gate values. S_t is runtime state belonging to the active request. When this article says the model “learns a memory,” it means the state is adjusted within a request, not that the base model is updated through backpropagation.
What Long-Context Inference Pays For
Start with an attention layer that retains a conventional KV cache. Let the context length be T, the number of cached layers L, the number of KV heads per layer H_kv, and the element size b bytes. Ignoring alignment and metadata, cache storage is:
KV_bytes = T × L × H_kv × (d_k + d_v) × b
Use the number of KV heads actually stored; substituting the query-head count can overestimate the cache. GQA, MQA, MLA, sliding windows, and quantization all affect storage. The equation describes layouts that retain the complete history of keys and values.
For a shape-only estimate, take L=24, H_kv=8, d_k=d_v=128, two-byte cache elements, and a context of 32,768 tokens. The KV cache alone is exactly 3 GiB. Doubling the context doubles this cache. The estimate excludes weights, activations, workspaces, allocator slack, and other model state.
Retaining history also has a read cost. During a single Decode step, conventional exact attention computes the relationship between the current query and visible history. Attention scores do not have to be materialized in full for the computation to depend on historical KV. FlashAttention reduces intermediate materialization and data movement; it does not turn an attention layer that depends on the full history into a fixed-state layer.
Prefill processes multiple positions together, creating opportunities for matrix multiplication and data reuse. Decode often adds one position per request, with different compute shapes and reuse opportunities. But “Prefill is always compute-bound and Decode is always bandwidth-bound” is too broad. Batch size, model size, context length, quantization, parallel communication, and kernel implementation all move the bottleneck.
Continuous batching lets multiple requests reuse a weight load, but requests with different contexts generally still read their own KV histories. Identical prefixes can also be shared through prefix caching, which is a separate form of reuse. As a result, higher throughput from batching does not necessarily remove KV bandwidth pressure for long requests.
Linear attention changes how history is represented. It reduces state costs for a class of token-mixing layers, while the model’s FFNs, expert routing, projections, and communication remain. Runtime costs should be evaluated across the complete request path.
From Repeated Queries to an Updatable Matrix
Conventional causal attention can be written as a weighted sum of historical values:
o_t = sum_{i<=t} exp(q_t^T k_i) v_i
/ sum_{i<=t} exp(q_t^T k_i)
The scale factor is omitted here. The key obstacle is that each matching weight depends on the combination of q_t and a historical k_i. When the query changes, those weights change too, so the history remains useful.
Early linear attention represents the matching relation with a factorized kernel feature map. If phi(q) and phi(k) have fixed dimensions, one formulation is:
S_t = S_{t-1} + v_t phi(k_t)^T
z_t = z_{t-1} + phi(k_t)
o_t = S_t phi(q_t) / [phi(q_t)^T z_t]
Associativity lets the system aggregate history before processing a query. Each write updates only fixed-shape S_t and z_t, and future queries read the aggregated state. A finite-dimensional feature map gives a recurrent expression for the corresponding kernel attention; it generally does not equal exact Softmax Attention for arbitrary inputs.
Reordering matrix multiplications alone therefore cannot remove all KV without loss. The reordering requires a factorized matching relation; the exponential query-key matching in Softmax cannot be split up in the same way.
Modern linear recurrent modules also change normalization, projections, and gating. Their core update is often simplified to:
S_t = S_{t-1} + v_t k_t^T
o_t = S_t q_t
This simplified form is useful for understanding associative memory, but it is not a reason to remove the denominator from a trained standard-attention layer. Whether to keep a denominator, how to normalize, and which activation to use are choices that must be designed together with training.
A fixed-dimensional state does not grow with sequence length, but it still contains d_v × d_k elements. An update and a read typically require work on that same order. Here, O(1) refers only to sequence length; the state dimensions still carry cost.
Two Associations Make “Memory” Concrete
Shrink the abstract vectors to two dimensions. Let the two addressing directions be:
e_1 = [1, 0]^T
e_2 = [0, 1]^T
S_0 = [[0, 0],
[0, 0]]
Write [2,1]^T under e_1; the first column becomes [2,1]^T.
Then write [3,4]^T under e_2. The state after accumulating both outer products is:
S = [[2, 3],
[1, 4]]
S e_1 = [2, 1]^T
S e_2 = [3, 4]^T
In this basis, the two columns happen to correspond to the two associations, and q=e_1 reads [2,1]^T. Keys in real models are not necessarily this orthogonal. Expanding the state gives the general read:
S_t q = sum_i v_i (k_i^T q)
Each historical value contributes according to the inner product between its key and the query. The result is a superposition of associations. The matrix does not retain directly extractable text passages or stable fact IDs.
Now write [4,-1]^T under e_1 again. Pure accumulation changes the first column to [6,0]^T, so querying with e_1 returns [6,0]^T. The old value was not replaced; old and new content both contribute.
If the intended meaning is “replace the old balance with a new balance,” accumulation is not the right update. If the goal is a running total, it may be useful. Training teaches the model how to organize keys, values, and state; the model does not directly read these business labels. This example illustrates only what the update rule does.
Non-orthogonal keys make the picture more complex. A write v k^T changes the read for another query q by v(k^T q). Related directions can interfere. Training must arrange many associations in a finite-dimensional space, so it cannot assume every token has an independent slot.
A column of the state matrix also cannot be assigned a fixed meaning such as “person” or “time.” The model determines the coordinate system, and one direction may mix several semantic factors. Throughout this article, “channel” means a tensor coordinate and the granularity of its corresponding gate.
How a Finite State Limits Exact Recall
The constraint imposed by a fixed shape can be seen through a linear-algebra problem. Put historical keys into a matrix K and ask whether one state S can satisfy every association:
S K = V
As the number of keys grows within a fixed d_k-dimensional space, constraints eventually become dependent. A state that satisfies every constraint does not always exist for arbitrary values. Two identical keys that are expected to return different values are already contradictory.
This does not mean a model can remember only d_k natural-language facts. Natural language has compressible structure, representations are learned rather than arbitrary lookup tables, and multiple heads, layers, nonlinear projections, and hybrid attention can add expressive power. But useful compression does not guarantee lossless retrieval of arbitrary history.
Choose tests according to the task. Summarizing a long document, tracking an attribute that changes over time, and exactly copying a random identifier from far back in context place different demands on memory. An improvement in average language-model metrics does not replace exact-recall tests.
State capacity also depends on numerical precision. A matrix with a fixed number of elements cannot hold an unlimited number of independent details at finite precision. Increasing state dimensions or precision raises memory and compute costs. Architecture design operates within these constraints.
An update rule therefore has to answer several questions: how much of a new input to add when old associations remain useful, how to revise an association that no longer fits, and whether a direction untouched by the current key should be forgotten over time.
DeltaNet: Read the Old Prediction, Then Write the Difference
DeltaNet adds a query before writing. The current key reads a prediction from the old state; the difference between the target value and that prediction is then written back:
prediction_t = S_{t-1} k_t
error_t = v_t - prediction_t
S_t = S_{t-1} + beta_t error_t k_t^T
beta_t is the write strength. It can be produced from the current input and is commonly bounded by an activation. If the state already predicts the new value correctly, the residual is near zero, so repeating the same input does not keep adding it unconditionally.
Restore the state from before the repeated write and compare one update. The old prediction in the first column is [2,1]^T; the new target is [4,-1]^T.
Subtract the old prediction from the target to get the residual:
error = [2, -2]^T
Set beta=0.5 and write back half the residual:
new_prediction = [2, 1]^T + 0.5 × [2, -2]^T
= [3, 0]^T
Repeating the same association moves the prediction closer to the target rather than accumulating without bound in the original direction. Under the idealized condition of a unit key:
S_t k_t = (1-beta_t) S_{t-1} k_t + beta_t v_t
With beta=1, the read along the current key can be set exactly to the target value; with beta=0, this residual is not written. A sigmoid output is usually inside the open interval, so the endpoints describe limiting behavior.
This property has a clear prerequisite: k_t^T k_t=1. Without normalization, the updated prediction includes an extra squared key norm, and the convex-combination result does not apply directly. Epsilon terms and zero-vector safeguards in implementations can also make normalization deviate from the ideal unit norm.
For another query direction q, the effect of this write is:
delta_output = beta_t error_t (k_t^T q)
Only directions strictly orthogonal to the current key are unaffected by this residual write.
Semantic unrelatedness does not guarantee an inner product of exactly zero. “Precise update” means correction along the addressing direction; it does not provide the isolation of independent database keys.
Why Key Normalization Changes State Propagation
Rearranging the DeltaNet state update gives:
S_t = S_{t-1} (I-beta_t k_t k_t^T) + beta_t v_t k_t^T
The old state continues through the matrix I-beta k k^T. For a unit key, this matrix has eigenvalue 1-beta along k and 1 over the orthogonal complement. When 0<=beta<=1, this old-state transition does not increase vector length.
L2 normalization therefore controls the geometry of old-state propagation and is directly related to the stability of the update.
However, a non-expansive old-state transition does not guarantee that the complete state remains bounded. New writes keep arriving; input magnitude, gate values, numerical precision, and long-term accumulation all affect the state. Output normalization cannot guarantee that the internal state always remains well-behaved.
Likewise, preserving an orthogonal direction is only a property of this part of DeltaNet. Once a forgetting gate is added, the orthogonal direction may still be scaled by that gate even though the current residual outer product does not affect it. Stability analysis should separate old-state propagation, ongoing writes, and output processing.
For debugging, log key norms, write-gate distributions, state norms, residual norms, and output norms separately. When comparing GPU kernels, use the same preprocessed inputs so projection or normalization differences are not mistaken for recurrence errors.
Associative Memory as Online Regression
The Delta Rule can be derived from a small regression problem. Treat state S as a linear model that accepts a key and predicts a value. For the current sample:
loss_t(S) = 0.5 ||S k_t - v_t||^2
gradient = (S k_t - v_t) k_t^T
Taking one gradient step of size beta_t from the old state gives the DeltaNet recurrence. This offers another interpretation of the write gate: it controls how strongly the current sample corrects the temporary association model.
These “fast weights” differ from the neural network’s base weights. Base projection parameters are updated during large-scale training; the state matrix changes quickly while processing one context. Inference executes this algebraic update without retaining optimizer state for the base model, and it is not ordinary fine-tuning on user input.
The online-regression view makes the difference between two rules clearer: pure outer-product accumulation directly adds the current association, while a residual update first checks how far the current prediction is from the target. Repeated writes, attribute replacement, and interference between similar keys can all be examined through prediction error.
Online regression explains only a local state update. It does not mean the whole language model optimizes a simple convex objective or has understood an input fact. Multiple representations, gates, and the final prediction are still determined jointly by the network.
Forgetting should not be casually equated with L2-regularized SGD applied at the same point. Decaying first and then computing the residual is not always equivalent to computing the residual from the old state and adding a decay term afterward. Gated DeltaNet must preserve this order.
Gated DeltaNet: Let Unused Directions Fade
DeltaNet modifies state along the current key but has no separate active-forgetting mechanism. An association in a direction that is not overwritten for a long time may remain. Gated DeltaNet combines decay with the residual update:
S_bar = alpha_t S_{t-1}
error = v_t - S_bar k_t
S_t = S_bar + beta_t error k_t^T
Use the same initial state as the KDA example below: S_old=[[4,2],[1,6]], with columns [4,1]^T and [2,6]^T.
Set alpha=0.5. The entire matrix is first halved, giving S_bar=[[2,1],[0.5,3]].
For this input, use k=e_1 and v=[2,3]^T. Compute the residual from the decayed S_bar; do not reuse the prediction from the old state.
The current prediction is [2,0.5]^T. Subtracting it from the target gives [0,2.5]^T; set the write gate to beta=0.5.
After writing half the residual, the first column is [2,1.75]^T; the second retains its decayed value [1,3]^T. The final state is [[2,1],[1.75,3]].
Each head uses a scalar alpha_t to scale the entire state uniformly before reading a prediction and correcting it. The write gate controls the strength of the current correction; the forgetting gate controls how much history is retained overall.
The order can be checked with a scalar example. Let the old prediction be 3 and the target be 4, with alpha=0.5 and beta=0.5. Decay first to 1.5; the current error is 2.5; after the write, the prediction is 2.75. Computing the error from the pre-decay value of 3 instead would produce 2, which is a different update rule.
A half-life makes repeated decay intuitive. With a fixed gate a, a purely historical contribution retains a^n after n steps. For example, with a=0.99, it takes about 69 steps to fall by half. Real gates vary with the input, so retention depends on the product of gates along the path; this does not give the model a fixed memory length.
A scalar gate can clear state with few parameters and operations, but all key directions within one head share the same decay at each update. The model can specialize different heads or learn input-dependent gates, yet the forgetting granularity of one update remains uniform.
Uniform scaling affects useful and unhelpful history alike. When some associations should be discarded, others may not be ready to fade at the same rate. This motivates finer-grained gating.
KDA: Forget Each Key Channel Separately
Kimi Delta Attention extends the scalar forgetting gate to a vector over the key dimension. Under the state orientation used here, its core update is:
D_t = Diag(alpha_t)
S_bar = S_{t-1} D_t
error = v_t - S_bar k_t
S_t = S_bar + beta_t error k_t^T
All value components in a column share one decay coefficient, while different columns can retain different proportions. beta_t can still be a scalar per head; the output gate handles post-read processing and is distinct from forgetting.
Consider one update with:
S_old = [[4, 2],
[1, 6]]
k = [1,0]^T, v = [2,3]^T, beta = 0.5
GDN uses a scalar alpha=0.5, giving S_bar=[[2,1],[0.5,3]]. Updating along the current key produces [[2,1],[1.75,3]]. The second column is also halved even though this residual write does not affect it.
KDA uses the vector alpha=[0.9,0.25]^T. The first column retains 90%, the second 25%, and the matrix shape stays the same.
Right-multiplying by the diagonal gate gives the decayed state [[3.6,0.5],[0.9,1.5]].
Reading along e_1 gives prediction [3.6,0.9]^T. Subtract it from target [2,3]^T to obtain residual [-1.6,2.1]^T.
Writing half the residual changes the first column to [2.8,1.95]^T, yielding final state [[2.8,0.5],[1.95,1.5]].
The second column remains at its decayed value [0.5,1.5]^T; a residual outer product along e_1 writes zero to that column. The first column retains more old information and receives a correction, while the second decays faster.
These numbers illustrate the difference in gate granularity; they do not say which gate values are better. Gate generation depends on training and task. More degrees of freedom allow more update patterns, while increasing gate-generation and data-processing costs.
One could define a separate gate for every element of S, but the gate count would grow from d_k to d_v*d_k. This could also break the structure in which every value row shares the same right-multiplying transition, limiting data reuse in efficient chunked algorithms.
KDA retains a transition that combines diagonal decay with a rank-one correction. Every value row shares the same right-multiplying transition, which makes later reordering easier. More complex gates should be compared across expressive benefit, numerical behavior, and GPU cost.
Short Convolution, Output Gates, and Normalization Have Different Roles
A complete module may include input projections, causal short convolutions, activations, q/k normalization, state updates, reads, output normalization, output gates, and output projections. Exact parameterization varies by model.
Short convolution mixes nearby information. A depthwise causal convolution combines recent inputs on each channel using learned coefficients before passing them to the state mechanism. During inference, convolution-kernel weights remain fixed while input-dependent gates vary by token; they serve different purposes.
Convolution has its own cache. With kernel width w, token-by-token execution usually retains enough recent convolution inputs to reconstruct the same window for the next step; the exact buffer layout depends on the implementation. Restoring the recurrent matrix but omitting the convolution cache changes subsequent q/k/v.
An output gate is applied after reading from state. Shrinking an output does not automatically remove the corresponding history from state. A forgetting gate acts during the state update and changes what can be read later. Both can depend on current input, but they act at different points and on different objects.
Normalization also depends on where it occurs. L2-normalizing q/k constrains addressing and the state transition; output-side RMSNorm and similar operations control the read distribution. They are not interchangeable. When comparing implementations, record whether q scaling happens inside or outside the kernel; otherwise, matching formulas can still produce different numbers because preprocessing differs.
In multi-head configurations, query, key, and value head counts or dimensions can differ. The small example here does not cover grouped mappings, tensor-parallel sharding, or state layout. These implementation choices can change how tensors are stored, but must preserve the mathematical order: decay, compute residual, write, then read.
Sequence Order and the Case for Hybrid Architectures
Pure outer-product accumulation is commutative. Given the same already-projected key-value pairs, swapping write order does not change their sum. Delta Rule updates with forgetting are generally non-commutative: changing the order of the same records can change later results.
This order dependence can support sequence modeling, but it does not establish that recurrent models need no positional encoding. Positional schemes still need evaluation alongside other attention layers, short convolutions, training-length distributions, and target tasks.
Causality is also not the same as distance representation. A causal mask prevents a position from reading the future; it does not necessarily distinguish the relative distance between two visible history positions. RoPE puts positional relations into query-key scores, while gated recurrence changes historical contributions through a sequence of state transitions. They organize information differently.
Fixed state can aggregate history at low cost, which is attractive for summarization and ongoing state tracking. Direct access to arbitrary details remains capacity-limited. Hybrid models often combine recurrent layers with full attention, sliding windows, or other sparse-access mechanisms to complement retrieval.
Hybrid complexity must be calculated by layer type. If any layer retains a complete KV history, that part of the cache still grows with context length. Reducing the number of full-attention layers lowers the coefficient; it does not make the complete model cache constant. Training activations, prefix snapshots, and speculative-verification state must also be counted separately from active matrices.
Changing the representation of history does not mean quality, exact recall, and long-range reasoning improve together on every task. Whether an architecture is worthwhile must be evaluated on the target workload across quality, cost, and system compatibility.
Turn Mechanism Claims into Pre-Launch Checks
Before estimating serving state, inspect the loaded model structure: attention-layer types, recurrent head count, key/value dimensions, state dtype, short-convolution window, and hybrid-layer ratio. A model name or summary configuration is rarely enough.
Then calculate capacity by component. Suppose there are 24 recurrent layers, 8 state heads per layer, 128×128 per head, and FP32 state. Active recurrent matrices total 12 MiB. If each layer also has three three-step BF16 convolution histories with matching head counts and dimensions, they add 432 KiB. These are logical data sizes; physical page padding, parallel sharding, and snapshots must be counted separately.
Comparing 12 MiB with the earlier 3 GiB only compares storage for the two specified shapes. Model capacity, head configuration, training method, and attention structure may differ. The ratio is neither a compression factor at equal quality nor a throughput ratio.
Effectiveness tests should include repeatedly rewriting the same attribute, interference from similar keys, long-gap recall, copying random strings, multi-turn updates, and context branching. Passing these tests provides evidence about whether a memory mechanism suits the target workload. Test data should also cover combinations of input and output lengths, not only the longest prompt.
Performance tests should record cold start versus steady state, cold versus warm cache, and TTFT, per-token latency, and tail latency at different concurrency levels. Long-input/short-output requests, short-input/long-output requests, shared system prompts, and unrelated requests stress state and compute differently.
Memory reports should separate model weights, active recurrent state, convolution caches, full-attention KV, shared checkpoints, speculative recovery material, and temporary workspaces. Logical payload size, physically allocated memory, and cache-pool retention should also be reported separately so evictable cache is not mistaken for a permanent leak.
Record implementation version, GPU model, parallel sharding, dtype, chunk parameters, request-length distribution, and acceptance rate. TTFT, per-token latency, throughput, and quality metrics can be compared only when these conditions are aligned. This article contains no benchmarks on real GPUs and reports no unmeasured speedup.
Fixed state changes the storage and compute costs of long-context inference while requiring the model to compress history and manage interference between associations. DeltaNet corrects the current prediction with a residual, GDN adds forgetting across the whole state, and KDA refines forgetting to key channels. This progression is a useful path for checking each mechanism during selection and debugging.
Further Reading
Part 2: Chunkwise Parallelism, State Caching, and Speculative Rollback, covering the symbol conventions, gates, and assumptions used in the examples.
- Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention, recurrent formulations of fixed-state kernel attention.
- Linear Transformers Are Secretly Fast Weight Programmers, associative memory, fast weights, and the Delta Rule.
- Parallelizing Linear Transformers with the Delta Rule over Sequence Length, state and chunked formulations for modern DeltaNet.
- Gated Delta Networks: Improving Mamba2 with Delta Rule, combining scalar forgetting with residual updates.
- Kimi Linear: An Expressive, Efficient Attention Architecture, fine-grained KDA gates and hybrid architecture.
- FLA KDA implementation snapshot, checked on November 11, 2026; operator parameters and supported cases refer to this pinned commit.