A fixed-size state matrix determines how history is represented. A serving system still has to organize the computation and manage that state: how can a long prompt avoid strictly serial token-by-token execution, how can requests safely reuse prefix state, and where should execution resume after a speculative token is rejected?

Each question requires an explicit time position for the state. The end of a compute chunk may not align with a cache-page boundary, and a sampled token may not yet have passed through a forward computation. Mixing up these positions can produce an incorrect result even when the update equation itself is correct.

Part 1 introduced outer-product accumulation, DeltaNet, GDN, and KDA. This part keeps the convention S ∈ R^(d_v×d_k) and derives chunked computation from the residuals actually written by the recurrence. The examples and checker validate algebra and state semantics; CPU reference timings do not indicate GPU performance.

Start with a Token-by-Token Reference

The core KDA steps can be written in four lines:

S_bar = S_old Diag(alpha_t)
r_t   = beta_t (v_t - S_bar k_t)
S_new = S_bar + r_t k_t^T
o_t   = S_new q_t

Here, q/k/v have already gone through the input preprocessing required by the module. Readout scaling must either be included in q or applied consistently at the output. RMSNorm, an output gate, and the output projection after the core state read are outside the recurrence derived below.

Fix three conventions in the reference implementation first: the read happens after the current write, forgetting happens before the current residual is computed, and the incoming state corresponds exactly to the position before this batch’s inputs. Every optimized version should preserve these conventions.

A naive loop is not suitable for large-scale Prefill, but it is useful for step-by-step validation. In particular, test nonzero initial states, non-orthogonal keys, and different per-channel gate values. If tests use only unit-basis vectors and a zero initial state, many implementation errors can remain hidden.

FLA provides naive_recurrent_kda and naive_chunk_kda as recurrent and chunkwise references. The code uses a K×V state orientation, and its head mapping also differs from the simplified examples here. Transpose the state and align scaling before comparing equations; matching variable names alone is not enough.

The source reference is pinned to commit 2a3e61a965f801caed462f5d963d584767bd0db6, checked on November 11, 2026, to make the implementation reproducible. Not every derivation in this article depends on that snapshot’s defaults.

Why Prefill Needs a Different Execution Plan

In a token-by-token recurrence, S_t depends on S_{t-1}, so the state for one request forms a dependency chain over time. If an entire prompt is processed as a serial sequence of small updates, each step waits for the one before it. The GPU then has fewer opportunities for the data reuse and utilization available in larger matrix multiplications.

Causality does not require all work to run serially. It says position i cannot use future-token content; it does not require the GPU to finish all computation for position 1 before starting work for position 2. Many intermediate values can be prepared early as long as the results obey the causal constraint.

A standard attention layer can produce Q/K/V for the current layer input in a batch; each attention row need not wait for the previous row’s output. A classical nonlinear RNN feeds an old hidden state through a nonlinear computation at the next step, which is usually difficult to combine into a compact long state chain. KDA projections and gates also contain nonlinearities, but the old recurrent state still enters the next step through an affine update.

Rearrange KDA as:

T_t = D_t (I-beta_t k_t k_t^T)
H_t = beta_t v_t k_t^T
S_t = S_{t-1} T_t + H_t

Here, D_t=Diag(alpha_t). Once the current layer’s batch input is available, these coefficients can be prepared without waiting for the preceding recurrent state. Computation can therefore be organized into coefficient preparation, state propagation, and output calculation.

However, constructing a dense T_t for every step and running a generic scan may require expensive matrix multiplications and extra storage. Although state updates can be composed, the composition strategy determines execution cost. Practical chunked algorithms preserve the structure of the diagonal gate and low-rank correction.

Composition Changes Parentheses, Not Order

Suppose the update for one chunk is S_a=S_in P_a+R_a, and the next chunk is S_b=S_a P_b+R_b. Expanding gives:

P_ab = P_a P_b
R_ab = R_a P_b + R_b
S_b  = S_in P_ab + R_ab

Chunk summaries compose associatively, so the grouping of combinations can change. Matrices generally do not commute, however, and swapping a and b may produce a different state. A parallel algorithm may change its schedule, but it must preserve the multiplication order implied by input order.

An affine summary and a state checkpoint also mean different things. A summary describes how an interval transforms an incoming state; a checkpoint stores the state at a particular, known prefix. A local delta cannot stand in for the complete state of an arbitrary prefix.

Practical kernels often represent P indirectly with auxiliary matrices instead of explicitly constructing the full transition matrix, and organize the work into more suitable matrix multiplications. Those auxiliary quantities can be derived from the residuals written at each position within a chunk.

Track the Residuals Before Expanding Every Large Matrix

Let a compute chunk contain C tokens, and let its initial state be S_0. Define the per-channel decay from position a through b:

d(a:b) = alpha_a ⊙ alpha_{a+1} ⊙ ... ⊙ alpha_b

The product over an empty interval is an all-ones vector. Expanding the state up to step i, before writing the current residual, gives:

S_bar_i =
  S_0 Diag(d(1:i))
  + sum_{j<i} r_j [k_j ⊙ d(j+1:i)]^T

Each historical write is already included in r_j; it then decays step by step until the current residual reads the state. The decay interval therefore starts at j+1 and includes i.

Substitute this expression into r_i=beta_i(v_i-S_bar_i k_i):

p_i  = k_i ⊙ d(1:i)
A_ij = beta_i k_i^T [k_j ⊙ d(j+1:i)]    (j<i)

r_i + sum_{j<i} A_ij r_j
    = beta_i (v_i - S_0 p_i)

The left side collects dependencies among residuals inside the chunk; the right side is the current target value adjusted for the contribution from the chunk’s initial state. Historical updates have not been dropped, and the derivation does not require mutually orthogonal keys.

The coefficient uses the current write gate beta_i. Do not multiply by the historical gate beta_j again: it is already included in the historical residual. Multiplying it a second time would rescale the old write and change the update rule.

The diagonal of A is zero because the current residual is computed before the current write, so it cannot read itself. A_ii=0 follows from operation order, not from key similarity or normalization.

Within-Chunk Dependencies Form a Unit Lower-Triangular System

Transpose each token’s column vector and stack the results by row:

E    : C × d_v, row i is r_i^T
V    : C × d_v, row i is v_i^T
K_in : C × d_k, row i is p_i^T
B    : C × C, diagonal entries are beta_i
A    : C × C, strictly lower triangular

The full set of residual equations becomes:

(I+A) E = B (V-K_in S_0^T)

This equation gathers the within-chunk dependencies in one place. To check it, first confirm that each row corresponds to the intended time position, then verify the shapes on both sides.

With three tokens, the coefficient system is:

[1     0     0] [r_1^T]   [beta_1(v_1-S_0 p_1)^T]
[A_21  1     0] [r_2^T] = [beta_2(v_2-S_0 p_2)^T]
[A_31  A_32  1] [r_3^T]   [beta_3(v_3-S_0 p_3)^T]

All diagonal entries are 1, so the system is solvable in exact arithmetic. It does not require a full-rank key matrix or an inverse of the chunk’s initial state. Conditioning and finite precision can still affect numerical error and must be compared against the reference.

To prepare work independent of S_0 before multiple chunks receive their initial states, split the right side:

(I+A) U = B V
(I+A) W = B K_in
E       = U-W S_0^T

U has shape C×d_v, and W has shape C×d_k; both can be computed before the initial chunk state arrives. Once it does, adjust them with that state to obtain the actual residuals.

Solving this system does not require explicitly computing an inverse. An inverse is convenient notation; an implementation may instead use forward substitution, subchunk solves, or reused intermediate factors. Compare approaches by their actual memory traffic and compute schedule, not just by whether the equation contains an inverse symbol.

A Matrix Equation Still Needs Optimization

With naive forward substitution, row i still waits for earlier rows. Writing (I+A)E=RHS in matrix form gathers the dependencies; it does not remove them.

Hardware-efficient implementations continue to exploit chunk structure. A unit lower-triangular matrix can be split into two diagonal blocks and one lower-left block. The diagonal blocks are handled separately, and cross-block contributions are combined with matrix multiplication. The larger problem becomes shorter dependency chains and work better suited to Tensor Cores.

Several forms of parallelism and reuse are available: requests and heads run independently, different chunks can prepare coefficients in parallel, subchunk matrix multiplications reuse inputs, and one system can process multiple right-hand sides. These opportunities come with costs for auxiliary matrices, subchunk solves, precision conversion, and kernel scheduling.

If chunks are too small, scheduling and boundary handling can dominate. If they are too large, lower-triangular matrices and intermediates grow, increasing register and shared-memory pressure. The right chunk length depends on state dimensions, input length, hardware, dtype, and implementation.

The FLA reference uses chunk_size=64, but 64 is not a universal requirement across GPUs, backends, or layers. The checker accompanying this article uses smaller chunks to make validation easier.

Chunk-End State and In-Chunk Outputs Are Different

After solving for actual residuals E, the chunk-end state can be computed by decaying each written key to the end of the chunk:

k_tail_i = k_i ⊙ d(i+1:C)
K_tail   = stack rows k_tail_i^T

S_out = S_0 Diag(d(1:C)) + E^T K_tail

The final token’s write has no subsequent decay. E^T K_tail is the sum of the actual residual outer products at the chunk boundary, with shape d_v×d_k. It can be passed to the next chunk as its initial state.

The model also needs outputs for every position inside the chunk. If every query reads S_out, earlier positions will see writes from the future, violating causality. Compute the contribution from the chunk’s initial state separately from the contribution of writes within the chunk:

q_in_i = q_i ⊙ d(1:i)
M_ij   = q_i^T [k_j ⊙ d(j+1:i)]    (j<=i)

O = Q_in S_0^T + M E

M includes the diagonal. Unlike A, residuals are read before the current write while outputs are read afterward, so an output may include its own write. The current write gate is not multiplied into M; its effect is already part of E.

These two differences give direct boundary tests: with one token, A should be zero while the diagonal of M may be nonzero. Confirm the one-token chunk matches the reference loop before debugging multiple-chunk scheduling.

A nonzero initial state also checks that both sources of information remain present. With a zero initial state, Q_in S_0^T and W S_0^T disappear, so an implementation that omits them may still pass.

Three Decay Intervals Determine Correct Boundaries

The same set of gates uses three different intervals for different purposes:

Purpose Decay interval Includes current gate?
Chunk-initial state to the read at step i 1:i Yes
Write at step j to the read at step i j+1:i Includes the read position’s gate
Write at step i to the chunk end i+1:C No

All three intervals follow from the operation order: the current step forgets first, reads the old prediction, writes the residual, and then produces the output. Changing an interval endpoint changes the corresponding update rule.

Cumulative products are often expressed with log-gate prefix sums:

g_i = log(alpha_i)
G_i = sum_{t=1..i} g_t
d(j+1:i) = exp(G_i-G_j)

This is convenient computationally, but the exponent range must be managed. Splitting a decay into exp(G_i)*exp(-G_j) can make the second factor very large. Intermediate values may overflow even when the final product is representable. Applying a causal mask afterward cannot repair every infinity or NaN that has already been produced.

Possible strategies include local reference points, segmented scaling, suitable subchunk sizes, and careful precision choices. For a read subchunk strictly after the history it reads, a reference point between them can keep both exponent sides non-positive. Diagonal subchunks require separate treatment of their causal ranges.

These strategies preserve the target formula but affect error and throughput. Validation should cover gates near 1 for long retention, strong forgetting, non-orthogonal keys, and long sequences. Random inputs with small numerical ranges may not expose extreme exponent ranges or accumulated error.

Boundaries in the Three-Stage Execution Plan

A complete prompt can be processed in three conceptual stages.

During preparation, build gate prefix sums, lower-triangular relationships, and auxiliary matrices for each compute chunk. Once the current layer input is known, this work can use parallelism across chunks and does not need the incoming state.

During the state stage, propagate state through chunks in request order. Once a chunk’s initial state arrives, compute its actual residuals and produce its ending state. Parallelism can also come from different requests, heads, and implementation strategies such as sharding the value axis.

During the output stage, use saved chunk-initial states and residuals to compute outputs for each position in each chunk. This work can again be organized across chunks. Implementations may fuse stages, recompute intermediates, or choose other storage strategies.

Saving chunk-initial states and intermediates trades space for time. Saving more may reduce recomputation and expose more parallel work; storing fewer intermediates may require more state propagation or other computation. Training’s backward pass may also use recomputation to control activation memory.

Each output sees only the history available at its own position. It cannot simply read a chunk-end state that already contains future writes.

An active recurrent state that does not grow with sequence length does not make the entire training or Prefill workspace constant-sized. When a full sequence is processed as a batch, inputs, outputs, auxiliary matrices, and backward-pass data still have their own length dimensions.

Runtime State Contains More Than One S

When a serving system restores a request, it must retain every piece of history needed by subsequent computation, not only the core matrix from a derivation.

A linear recurrent layer with short convolution usually needs both its recurrent matrix and recent convolution inputs. A hybrid model also needs KV for its full-attention layers and caches for other stateful modules. Cache page tables, position counters, and logical lengths must agree with these data.

Checkpoint completeness can be tested by continuing execution: after loading, does the same next token produce the same q/k/v, gates, state, and output as a run from the beginning? Restoring S while reusing a convolution window from a different context cannot guarantee a match.

Request cancellation and slot reuse also require valid-state checks. A physical slot may be free even if its old values have not been cleared. A new request must not consume that stale state. The scheduler, state initialization, and execution kernel must follow a consistent validity contract rather than assuming leftover values are near zero.

Multi-tenant systems also need cache identity. Model versions, adapters, input preprocessing, multimodal content, and tenant-isolation data may all affect reuse. Matching token IDs are only part of the condition; sharing across trust boundaries requires an explicit policy.

Why Fixed Active State Still Needs Prefix Checkpoints

Suppose request A has processed 1,200 tokens and holds state S_1200. Request B shares only the first 700 tokens with it.

A’s final state has already mixed in the following 500 tokens, so the system cannot hand it to B as if it were S_700.

A complete KV record preserves historical positions and can often reuse the records for a valid prefix. A recurrent state mixes positions together. Reusing an intermediate prefix therefore requires a checkpoint at that position or an execution path that reconstructs one.

This does not mean every recurrent update is mathematically irreversible. Some transitions have inverses under specific parameter conditions, but inversion may require extra inputs, add cost, or amplify numerical error; singular transitions cannot be inverted. A general online service should not use unvalidated reverse recovery as a safe truncation strategy.

Saving a complete matrix at every token makes checkpoint storage grow with sequence length and may generate substantial HBM writes. Keeping only the final state loses opportunities to share intermediate prefixes. The system must choose checkpoint boundaries by weighing reuse benefits against state cost.

Marconi discusses this trade-off in hybrid models. Admission and eviction for recurrent-state caches cannot simply copy ordinary KV-page policies; they must account for reuse probability, saved computation, state footprint, and fork patterns. A system policy proposed in a paper should also be distinguished from the exact behavior of a particular framework release.

Compute Chunks, Physical Pages, and Match Blocks Are Different

Cache discussions often use the word “block” for three different units:

Name Main purpose What it affects
Operator compute chunk C Organize recurrence into GPU work Intermediates, dependencies, and kernel efficiency
Physical cache page B Allocate and address memory Page size, alignment, fragmentation, and transfers
Hash match block H Identify a reusable prefix boundary Lookup granularity and reuse boundaries

These units may be related, but their shared name does not make their sizes interchangeable. Changing compute chunk size does not necessarily require a new cache-page size, and making the hash block smaller does not automatically create recurrent states at every position.

Consider a separate capacity example. Suppose one layer’s recurrent state and auxiliary cache use 600 KiB, the corresponding attention layer cache uses 2 KiB per token, and physical pages must be aligned to a multiple of 128 tokens. To fit one recurrent state, choose:

B = 128 × ceil(600 / (128×2)) = 384 token
page_bytes = 384 × 2 KiB = 768 KiB
padding = 168 KiB

Padding adds 28% relative to the useful state. These values illustrate overhead in a uniform-page-size scheme; they are not defaults for a real model. Layer counts within each group, heterogeneous layouts, and other alignment requirements also affect total allocation.

If the hash match block is 64 tokens, the system can identify more candidate prefix boundaries. But resuming from one of them still requires the complete state at that position: a hash identifies matching content, while a checkpoint provides data for continuing computation. Both are needed.

The vLLM Hybrid KV Cache Manager documentation describes uniform page sizes, cache groups, and coordination across hybrid hits, while noting a reference commit and subsequent evolution. Its grouping heuristics should not be treated as a fixed interface contract across all releases.

Protect Checkpoints When Forking a Shared Prefix

Suppose requests A and B can reuse a public prefix state S_p. They both hit it, then continue with different inputs. If they update the same physical matrix in place, whichever request runs first changes the starting point for the other.

Keep the shared checkpoint immutable and let each request continue with its own active state. This can be implemented with copy-on-write, private slots, or another strategy with the same isolation semantics. Shared references and write permissions must remain distinct.

Every private state must be restored to the same position p; recurrent matrix S_p and short-convolution window conv_p must be restored together.

A content hash can confirm prefix identity, but it cannot replace S_p and conv_p in the checkpoint. After a match, the system still needs to retrieve the full state for that position.

If no recurrent state exists at the shared fork point, a reusable KV hit for a full-attention layer does not make the overall prefix reusable. A request can save the missing state while recomputing the shared region for future requests, though it may not benefit immediately.

Consider a conceptual example: A and B share through position 700, and the system has checkpoints only at 512 and 1,024. The checkpoint at 1,024 already contains forked content; 512 is the safe candidate. B still has to compute the shared region from 512 through 700. Whether saving a checkpoint at 700 is worthwhile depends on boundary support, future reuse probability, and write cost.

Hybrid models must coordinate restoration positions across layer types. Full-attention, sliding-window, and recurrent layers have different reuse conditions. Skipping a prefix is valid only when every group has the required state. Restoring to the longest hit in just one group can leave other layers at a mismatched time position.

Releasing a state reference does not necessarily erase the cache contents immediately. A physical block with no active references may retain its cache identity until eviction or reuse. Account separately for state held by active requests and historical snapshots retained by the cache pool.

Speculative Decoding: A Sampled Token Is One Step Ahead of Processed Input

Speculative decoding proposes candidates and verifies them with the target model. A recurrent layer updates state while processing candidates, so after a rejection it cannot keep using the final candidate matrix. The system must restore a snapshot, replay from a checkpoint, or use another validated equivalent recovery strategy.

Use two draft tokens to illustrate the positions. Suppose the target-model state has processed prefix p. The previous round has sampled a definite token x0, but the target model has not yet executed it as an input.

The target input in this round is:

[x0, d1, d2]

After processing the three inputs in order, candidate states correspond to S_(p+1), S_(p+2), and S_(p+3). Physical slots need not be contiguous; keep logical indices distinct from physical IDs.

The output after processing x0 verifies d1; the output after processing d1 verifies d2. If d1 is accepted and d2 rejected, resampling produces correction token r, and the newly confirmed outputs for this round are [d1,r].

At this point, the target model has processed only [x0,d1] on the correct branch. The next round should start from S_(p+2) and feed r as a definite input. Although r has already been sampled, the recurrent state has not processed it.

If snapshots were saved after all three input positions, the second one is the correct choice. Whether fields such as accepted_count include the definite token or an additional sampled token is framework-version-specific; do not infer it from the field name alone.

The short-convolution window must also be restored to the same input position. Even with the right matrix S, a window that retains a rejected token will produce different next-step q/k/v. Full-attention KV, recurrent state, and convolution history must all observe the same commit boundary.

After committing S_(p+2) for this round, r is confirmed but still will not be processed as input until the next round. Count processed inputs first when locating the rollback point.

Longer verification usually requires more snapshots, replayed inputs, or other recovery material. To measure speculative-decoding gains, include the cost of those materials alongside the target-model steps saved. Even with the same acceptance rate, speedup can differ between hybrid and full-attention models.

Validate the Math Before the State Lifecycle

The numerical checker accompanying this series uses only the Python standard library. With a fixed random seed and explicit tolerances, it compares every position’s output and the final state from token-by-token and chunked computation on small matrices.

Coverage includes single-token cases, incomplete final chunks, nonzero initial states, non-orthogonal keys, zero write gates, and channel-wise forgetting. It also compares independent continuations after prefix-state forks and continuations restored to an accepted speculative position. These tests validate the teaching equations, not a complete CUDA backend.

For a GPU implementation, add tests for batch and head mappings, variable-length input, different dtypes, extreme gate values, and long-sequence error. A reference program may use double precision while a GPU kernel uses mixed precision and a different reduction order; compare with suitable absolute and relative tolerances.

Numerical agreement alone does not prove state-pool correctness. System tests should also cover request cancellation, slot reuse, releasing shared references, checkpoint eviction, and prefixes that land exactly on or just beyond a boundary. Reuse bugs may depend on a particular concurrency order and escape single-request sequential tests.

Cache identity should also cover model versions, adapters, and multimodal inputs. vLLM’s prefix-caching documentation explicitly includes extra hash information in identity and describes cache isolation mechanisms. A salt controls the sharing scope; it does not replace account authentication, resource isolation, or log-privacy controls.

Performance Evaluation Must Cover the Full Serving Cost

After converting a recurrent loop into a chunked algorithm, measure preparation, state propagation, and output stages separately. Even when one stage becomes faster, projections, memory copies, routing, or communication may still limit overall serving. A best-case kernel result alone cannot explain real TTFT or tail latency.

Test cold and warm caches separately. When shared system prompts are common, checkpoint reuse may reduce Prefill; for unrelated requests, performance depends more on the operator. To compare caching strategies, record tokens hit, computation actually avoided, and cache footprint together.

Output length matters too. Short prompts with long outputs repeatedly update active state, making speculative snapshots and state-write bandwidth more prominent. Long prompts with short outputs expose the cost of chunk preparation and triangular computation. One fixed prompt length cannot represent both workloads.

At minimum, memory reports should distinguish model weights, active recurrent state, convolution caches, full-attention KV, shared checkpoints, speculative recovery material, and temporary workspace. Also report logical data size, allocated GPU memory, and retained cache-pool capacity separately to avoid mistaking evictable cache for a permanent leak.

Record the implementation version, GPU model, parallel sharding, dtype, chunk parameters, request-length distribution, and acceptance rate. TTFT, per-token latency, throughput, and quality metrics are comparable only when these conditions are aligned. This article contains no real-GPU benchmark and reports no speedup that was not measured.

Put the Mechanisms Back into One Progression

Use the same initial state [[4,2],[1,6]], k=e1, and target value [2,3]. With beta=0.5 for the three gated updates, the single-step results are:

Mechanism Additional forgetting Updated first column Updated second column
Outer-product accumulation None [6,4] [2,6]
DeltaNet None [3,2] [2,6]
GDN Scalar 0.5 [2,1.75] [1,3]
KDA Vector [0.9,0.25] [2.8,1.95] [0.5,1.5]

Outer-product accumulation retains the sum of old and new values. DeltaNet corrects the prediction along the current key. GDN also decays the other column, which the current residual does not access. KDA lets the columns use different retention rates. These examples compare update rules, not model quality.

Chunked computation changes how the solution is organized but must reproduce every output and final state of the same mechanism. Cache policy determines which time positions have recoverable states; speculative commit determines which computed branch to keep. The final matrix alone cannot replace those contracts.

Moving from equations to online serving requires separate validation of update rules, computation results, and state lifecycle. Small matrices check the mechanism, chunked algorithms organize GPU computation, and checkpoints and commit boundaries ensure requests resume from the right position. Performance evaluation should build on these correctness checks.

References and Implementation Scope