KV cache and state recovery

How DeepSeek V4.1 Flash Budgets State for Long-Running Agents

Long-running agent context meets compact global KV and a distinct local window
Long-running agent context meets compact global KV and a distinct local window
Date

Author

Han (Andrew) Zheng

Category


DeepSeek V4.1 Flash figure 1

Figure 1. Across a pause, global KV is retained and reused. Local SWA can expire and is approximately rebuilt by replaying recent tokens.

Introduction: long-context models are being designed around the state lifecycle

Long-context agent efficiency depends on how state is stored, restored, and computed.

DeepSeek V4.1 Flash addresses these costs through a joint redesign of state storage, recovery, and computation.

The paper's techniques form a coherent state lifecycle:


DeepSeek V4.1 Flash figure 2

Figure 2. The state-management problem addressed by each architectural component.

That design leads to two readily quoted, readily misunderstood numbers: 890 bytes/token of global KV and a persistent cache roughly 1/8 the size of its predecessor's.

1. Agent workloads require three separate cost accounts

Consider a coding agent that reads a repository, searches files, edits code, runs tests, and revises its changes in response to errors. Its final deliverable may be a single patch, but along the way it continually absorbs code, logs, and tool outputs.

This workflow incurs three distinct kinds of cost.

The first is computation for new input. Even when the historical prefix hits the cache, newly produced tool results still require prefill, the processing of input tokens before generation. An invalidated or rearranged prefix can expand the amount of recomputation.

The second is state capacity for active sessions. Long trajectories require context representations that later generation can use. As concurrency increases, cache capacity can limit how many requests the system can serve at once.

The third is saving and restoring paused sessions. An agent waiting for a tool or a user does not need continuous GPU computation, but resuming it later still incurs storage, transfer, and recomputation costs.

An efficient agent model therefore needs to answer:

  • Which historical information must be retained for the long term?

  • Which states can be shared across layers?

  • Which states can be recovered cheaply after they are lost?

  • Which prompt computations serve only to prepare caches for future use?

This is why tokens/s or cache-hit rate alone is insufficient. A cache hit may still require data movement, local-state recovery, and processing of new input. A model with less computation per token can still be constrained by weight capacity and communication.

Separate model size from execution size

The V4.1-Flash release materials describe the following structure. [2]


DeepSeek V4.1 Flash figure 3

Figure 3. Released model configuration, separating stored capacity from per-token execution.

"16B activated" describes the computation path for one token. The serving system must still keep the other expert weights accessible, and Engram has its own storage requirements.

The official vLLM recipe puts the released checkpoint at approximately 511 GB, or 476 GiB. This is the on-disk weight footprint. Runtime GPU memory also depends on Engram placement, parallel partitioning, caches, and temporary space. [3]

A deployment analysis should therefore track three quantities together: weight storage, computation per token, and session-state capacity.

2. CED: why most prompt tokens can finish computation early

Start with who produces the KV needed later

In a conventional decoder-only Transformer, the KV at layer l usually depends on that layer's input hidden states. To prepare all the layer-level caches needed for later generation, the prompt must pass through the entire network.

YOCO has explored a different division of labor: the first half constructs shared global KV, and the second half reads that memory using its own queries. Once the global memory is constructed, some subsequent computation on historical prompt positions can be omitted. [4]

The Causal Encoder-Decoder (CED) architecture develops this direction. Conceptually:

Decoder global KV = KV projection(encoder final hidden states)

In V4.1-Flash, a single source layer produces the decoder's global KV, which the other decoder layers reuse. Each layer retains its own query and local sliding-window attention (SWA). [5]


DeepSeek V4.1 Flash figure 4

Figure 4. Conceptual CED prompt-execution path: build shared global KV, then replay the tail to prepare local SWA before generation.

This is a conceptual execution path. An actual inference engine may schedule the projection at the last global KV source separately from that layer's remaining computation.

Why the decoder still needs tail computation

Sharing global KV does not mean that all decoder layers perform the same computation.

Different layers can read the same history with different queries, while local SWA retains each layer's own state. This preserves the depth of local processing, but it also means that the decoder's local state at the tail must be prepared before generation starts.

The deployment path therefore replays the tail. Most historical positions can skip deeper computation; a short segment at the end prepares the state needed to continue generating.

A simplified work model

For a cold start without prefix-cache reuse, let:

  • N be the full prompt length;

  • W be the tail-window limit, set to 128.

Ignoring differences in per-layer cost, additional projections, and scheduling overhead:

C_full ≈ 40N

C_CED ≈ 20N + 20 min(W, N)

Therefore:

C_CED / C_full ≈ 1/2 + min(W, N)/(2N)

  • For N = 8192 and W = 128, the ratio is approximately 0.508.

  • For N = 256, the ratio is approximately 0.75.

As input length grows, the fixed tail overhead is amortized more effectively.

This expression cannot directly predict time to first token (TTFT), nor can the length of a new suffix after a cache hit simply be substituted for N. If the encoder's local state has been lost, the tail of the cached prefix also needs replay. Cache conditions must be held constant when comparing baselines.

Generating a new token still uses the full backbone. The approximately 8B activated parameters during prefill and 16B during decode reflect the division of execution between these stages.

3. CSA2: control what is stored separately from where to read

To understand Compressed Sparse Attention 2 (CSA2), distinguish three objects:

  • Main KV: the content available for attention to read.

  • Indexer K: the representation scored by a lightweight retrieval mechanism.

  • Top-K indices: the positions selected by the current query.

Sharing Top-K selections reduces repeated retrieval work but does not automatically reduce KV storage. Sharing KV reduces what must be stored while still allowing subsequent layers to choose new positions to read.

CSA2 organizes these behaviors into three modes. [6]


DeepSeek V4.1 Flash figure 5

Figure 5. CSA2 separates global-cache construction from Top-K selection.

In all three modes, each layer still computes its own main query, local SWA, and attention output.

The released configuration specifies only four global KV sources, with zero-based layer indices:

Global KV source layers (zero-based): 2, 8, 14, 20

The layers that produce indices are:

Indexer-producing layers (zero-based): 2, 8, 14, 20, 24, 28, 32, 36

The first three KV sources have a sequence-compression ratio of 2; the decoder's source has a ratio of 1. [5]

The decoder's global memory therefore retains the resolution of one record per token, while multiple layers share that memory.

A substantial portion of the compression benefit comes from removing duplication across layers.

From an information-processing perspective, multiple queries can interpret the same history repeatedly. Reuse further reduces retrieval work, but makes multiple layers share the benefits and risks of one selection. Reindex provides an opportunity to select again.

4. Deriving 890 bytes/token from the public configuration

The following calculation describes the logical payload in a compact format, not measured GPU memory usage in a particular inference engine. The dimensions, compression ratios, and quantization groups can be checked against the released configuration and reference code. [5]

4.1 One main KV record: 288 bytes

The main KV latent has 512 dimensions. Each value occupies 4 bits, with a 1-byte E4M3 scale for every 16 dimensions:

B_main = 512 × 4/8 + (512/16) × 1 = 288 bytes

What is stored here is a shared KV latent. It should not be multiplied by 2 on the assumption that K and V are stored as separate conventional tensors.

4.2 One indexer K record: 68 bytes

Indexer K has 128 dimensions, with a 1-byte scale for every 32 dimensions:

B_indexer = 128 × 4/8 + (128/32) × 1 = 68 bytes

The number of query heads does not translate directly into the same number of K-cache copies. Capacity must be calculated from the shape of the tensors actually stored.

4.3 Each original token contributes 2.5 global records

Each of the three encoder sources stores approximately N/2 records, and the decoder source stores N records:

N_entries ≈ 3 × N/2 + N = 2.5N

Therefore:

B_per_token = 2.5 × (288 + 68) = 890 bytes

The 890 figure results from record precision, sequence compression, and cross-layer sharing together. Changing a conventional model's KV dtype to FP4 alone will not produce the same result.

Converting this linear term into capacity:


DeepSeek V4.1 Flash figure 6

Figure 6. Compact global-KV logical payload at 890 bytes per original token; local SWA and runtime overhead are excluded.

For the decimal count of 1,000,000 tokens, the result is 890 MB.

4.4 FP4 requires the model to adapt to quantization error

The paper introduces quantization-aware training (QAT) for main KV during post-training. Main KV uses E2M1 data with grouped E4M3 scales and omits NVFP4's second-level global scale. [7]

In the implementation, main KV is quantized after rotary position embedding (RoPE), while local SWA remains FP8. [6]

This assigns precision according to the state's role: the global cache determines the linear capacity cost of a long sequence, whereas the smaller local window can retain higher precision.

A reproduction must check group size, scale type, and quantization order together. "Both are 4-bit" is not enough to establish identical numerical behavior.

4.5 What must be added beyond 890 bytes/token?

Counting only the FP8 main vectors, local SWA across 40 layers, with 128 positions per layer and 512 bytes per position, requires approximately 2.5 MiB. Scales and other states are additional.

The complete runtime-memory budget should have the following structure:

M_runtime = M_weights + M_global_KV + M_local_state + M_workspace + M_communication + M_alignment_and_replicas

For shared prefixes, count uniquely stored cache blocks. With tensor parallelism (TP) and other parallel arrangements, check whether shared tensors are physically replicated.

Reducing logical data volume and freeing high-bandwidth memory (HBM) across a cluster are related, but they are different calculations.

5. Hierarchical indexing: sparse reads still need affordable search

Sparse attention reads only a small set of positions, but finding those positions can itself be expensive.

V4.1-Flash's decoder first indexes the full range and constructs a candidate pool of at most 2048 blocks, each containing 8 positions: 16,384 candidates in total. Subsequent Reindex layers select their own Top-512 within that pool; Reuse layers retain the selection. [5]

Let the candidate limit be P = 16384. The number of positions scored by the decoder's indexers can be estimated as:

C_independent ≈ 5N

C_hierarchical ≈ N + 4 min(N, P)

For N = 1,048,576:

5N / (N + 4P) ≈ 4.706

The number of positions scored in this part of the computation falls to approximately 1/4.706 of the baseline. That does not mean the whole model is 4.706 times faster. Block selection, data movement, other indexing layers, and actual kernel efficiency are not included.

The first pass still scans the full range, so the complete algorithm retains a component that grows with N.

The candidate pool introduces a specific quality risk

Subsequent Reindex layers can reselect global KV only within the candidate pool. Those global retrieval steps cannot directly recover positions outside it. The model still retains per-layer SWA and information already incorporated into hidden states.

This suggests a more discriminating evaluation: place multiple semantically similar distractors in a long context, require the task to combine distant evidence, and sweep evidence positions and window boundaries.

"The model can accommodate 1M tokens" and "the model reliably uses different kinds of evidence within them" require separate measurements.

6. Bounded Replay: limited recomputation changes how sessions are saved

A 128-token window does not imply exact local reconstruction

A deep hidden state has already incorporated information from earlier layers. Even if an individual layer attends only to a local window, tracing dependencies back through the layers makes exact recovery depend on more than the last 128 original tokens.

Bounded Replay accepts a limited approximation: replay the tail, truncate local attention at the replay boundary, and retain the existing global KV. The reconstructed local state then supports subsequent generation. The framework has separate paths for encoder recovery and decoder-tail computation. [8]

The two kinds of state can consequently follow different lifecycles:

  • Global memory is suitable for longer retention and historical reuse.

  • Local state primarily serves active sessions and can be reconstructed by replay after it expires.

This gives the cache system another choice: trade the storage of local state against future recomputation.

Why the 1/8 persistent-cache ratio depends on the old system

The paper's approximately 1/8 figure combines two factors: global cache shrinks to roughly 1/4 of its predecessor's, and persistent SWA, which occupied about half of the old deployment's cache, is removed. [7]

Let f be the SWA share of the old cache and g the ratio of compressed global cache to its previous size. Then:

M_new / M_old ≈ g(1 − f)

For g = 1/4 and f = 1/2:

M_new / M_old ≈ 1/8

If SWA accounted for only 10% of another system's old cache, however, the result would be:

0.25 × 0.9 = 0.225

That corresponds to an approximately 4.44-fold capacity improvement.

Assessing migration benefits should therefore begin by measuring the composition of the old cache. Local state must still exist for active requests or in a short-lived pool; not persisting it for the long term does not remove it from the runtime system.

Focus validation on recovery boundaries

Approximate recovery does not guarantee mathematical equivalence to a full forward pass. [9]

The same text can be processed through different execution paths:

  • A single full prefill;

  • A cache hit at an earlier position;

  • A cache hit at a later position;

  • Repeated pauses and resumptions.

Compare task success, format correctness, use of critical evidence, and behavioral changes after repeated recovery.

Exact token-by-token agreement is a stronger property and cannot be established by matching outputs on a small sample. Acceptance criteria should specify which quality differences are tolerable and which protocol behaviors must remain strictly unchanged.

7. How Engram, mHC, and DSpark fit together

Engram: add knowledge capacity through on-demand lookup tables

Engram determines addresses from token n-grams, then combines the retrieved conditional memory with the current hidden state. This adds knowledge capacity through sparse access. [10]

Deterministic addressing creates a systems opportunity: lookups can begin earlier, and host-side transfers may overlap with computation.

The cost of freeing HBM may, however, shift to host memory, address translation, PCIe/RDMA, and lookup communication. SGLang offers different placement options; actual benefits must be evaluated against the CPU–GPU path. [9]

Single-Pass mHC: change dependencies to enable fusion

This change lets the current sublayer use input-mixing coefficients produced by the preceding sublayer, reducing dependencies that would otherwise wait for the current reduction to finish. [8]

It illustrates the value of co-designing models and kernels. If a computation's dependencies force hardware to reread a large tensor, wrapping the existing formula in kernel fusion can hit a limit. Changing the computation order can further reduce data movement.

DSpark: speculative length should follow system load

DSpark combines semi-autoregressive drafts with confidence scheduling to select a more favorable verification length. [11]

The longest draft is not necessarily the most economical. Accepted length, verification overhead, concurrency, and batch saturation all affect net benefit. Evaluating speculative decoding requires recording acceptance rate, verification time, and total throughput together.

Final capabilities reflect architecture, data, and training together

The model card reports pre-training on 45T tokens, followed by supervised fine-tuning (SFT), reinforcement learning (RL), and on-policy distillation (OPD). Post-training changes concentrate on scaling the construction of tasks and environments. [2]

Final capability gains therefore cannot all be attributed to a single cache component. Architecture changes resource constraints; training changes how the model completes tasks. Controlled experiments for individual components are needed to separate their contributions further.

8. Engineering implications for inference platforms such as Infron

Routing must account for both cache location and waiting time

Moving a long session to another instance may require reloading or recomputing its history. Keeping it on the original instance may mean a longer queue.

A request can be estimated using the following structure:

T_request = T_queue + T_restore + T_prefill-new + T_decode

Routing needs visibility into prefix location, reusable state, instance load, and latency targets.

More effective caching makes session affinity more valuable. As queues become congested, the opportunity cost of migration deserves to be reassessed.

Record global cache hits separately from local recovery

A single cache-hit rate hides important differences. Consider adding these observations:


DeepSeek V4.1 Flash figure 7

Figure 7. Suggested observability metrics for separating global-cache reuse, local-state restoration and end-to-end performance.

Connect quality and efficiency through cost per successful task

One actionable business metric is:

Cost per successful task = total resource cost of task batch / tasks passing acceptance

Costs should include inference, tools, retries, and the storage and host overhead allocated to serving.

If a lower token price leads to more retries, this metric can expose the actual cost. It also places effort, cache policy, model selection, and the agent harness within a common decision framework.

Start by validating four traffic classes


DeepSeek V4.1 Flash figure 8

Figure 8. Four workload groups for controlled validation of prefill, restoration, prefix branching and multimodal or code tasks.

For each group, fix the checkpoint, engine version, sampling parameters, effort, and tool environment. Then increase context length and concurrency gradually.

  • For replay, sweep recovery boundaries.

  • For sparse indexing, emphasize distant evidence and similar distractors.

  • For Engram offload, check whether freed HBM actually becomes sustainable serving capacity.

Conclusion: design inference systems around the role and lifecycle of state

This paper offers a systems design principle worth carrying forward:

Long-lived global memory, local state for active sessions, and the deep computation used to generate new tokens can follow different storage and execution paths.

  • Global memory must retain retrievable information.

  • Local state must support continuous processing and be recoverable after it expires.

  • New output needs sufficient computational depth.

Assigning different paths to these needs reduces duplicated work while preserving the representational capacity required to complete tasks.

For inference infrastructure, the central job is to turn these paths into observable, schedulable, verifiable services: know what each request reused, what it reconstructed, what resources it actually consumed, and whether it ultimately completed the task.

Only when cache state, execution policy, and task quality are measured together can 890 bytes/token move from an architectural metric to sustainable product value.

Reference links

DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression

FAQ

Can 890 bytes/token be used as the GPU-memory budget for a deployment?

Use it as the linear compact-global-KV payload term, not the whole budget. Add weights, local SWA state including its scales, other state, workspace, communication buffers, alignment, and physical replicas. The global record scales are already included in 890 bytes/token. For shared prefixes, count unique stored blocks rather than summing every session's logical context.

Why might a prefix-cache hit still have substantial latency?

A hit can avoid some historical computation while still requiring queueing, state transfer or local recovery, and prefill of new tool output. Measure these stages separately before attributing TTFT changes to cache reuse.

What should an acceptance test check after repeated state recovery?

Compare task success, output-format and protocol correctness, and use of critical evidence across uninterrupted prefill, early and late cache hits, and repeated pauses. Define tolerable quality differences explicitly; a few matching token sequences do not prove exact equivalence.

Does the 1M-token context limit establish reliable long-range retrieval?

No. Capacity and evidence use are separate properties. The hierarchical indexer's later selections are restricted to its candidate pool, so test distant evidence, similar distractors, and boundary positions rather than relying on context capacity alone.

What can be inferred about an Infron API route from these architecture figures?

They describe model and deployment mechanisms, not measured Infron route behavior. The verified model listing establishes the model destination. Latency, cache reuse, billed cost, and recovery behavior for a particular route need their own documented observations.

Explore DeepSeek V4.1 Flash on Infron

Sources and references

  • [1]Andrew: original DeepSeek-V4.1-Flash article:: Source

  • [2]DeepSeek-V4.1-Flash model card:: Source

  • [3]vLLM: DeepSeek-V4.1-Flash deployment recipe:: Source

  • [4]YOCO: You Only Cache Once:: Source

  • [5]DeepSeek-V4.1-Flash released configuration:: Source

  • [6]DeepSeek-V4.1-Flash reference inference implementation:: Source

  • [7]DeepSeek-V4.1-Flash technical report, version 1:: Source

  • [8]SGLang and Miles: Day-0 support for DeepSeek-V4.1:: Source

  • [9]SGLang: DeepSeek-V4.1 deployment cookbook:: Source

  • [10]Engram: conditional memory via scalable lookup:: Source

  • [11]DSpark speculative decoding paper:: Source

  • [12]DeepSeek-V4.1-Flash technical report abstract:: Source

  • [13]DeepSeek V4.1 Flash on Infron:: Source