Skip to main content

engine.solvers.kv_cache

engine.solvers.kv_cache

KV cache management solvers: what retained attention state costs a serving node.

Domain implementations behind mlsysim.solvers (added 2026-10-20). Each model is arithmetic on a model’s KV geometry and a node’s registry specs: the per-token payload and the pool left after the weights, the bytes per token each attention design keeps, full-cap reservation against paged blocks, the prefill a prefix hit avoids, chunked prefill against a monolithic one, keeping, moving, or dropping a paused request’s state, and block-rounded resident fit turned into a turn rate by Little’s law. None models attention traffic during a pass, link contention, or an engine’s scheduler; every rate is a memory-only or weight-only bound.

Classes

Name Description
ChunkedPrefillModel The decode gap a new prompt causes, run whole or in chunks.
KvAttentionDesignModel Bytes each token keeps under multi-head, grouped-query, and latent attention.
KvBlockSharingModel Block-rounded resident fit with and without a shared prefix, as a turn rate.
KvResidencyArchetypeModel Sharing gain, residency tax, and resume cost for one agent workload.
PagedAllocationModel Full-cap reservation against fixed-size blocks allocated on demand.
PausedKvStateModel Keep, move, or drop a paused request’s KV state during a tool wait.
PrefixRebuildModel The prefill a prefix-cache hit avoids, against one short suffix pass.

ChunkedPrefillModel

engine.solvers.kv_cache.ChunkedPrefillModel()

The decode gap a new prompt causes, run whole or in chunks.

T(N) = max(T_weights, 2 P N / R)

Run whole, the prompt sits between two decode steps, so every ongoing stream waits T(decodes) + T(prompt). Chunked, each iteration runs one chunk beside the decodes, so the gap is T(chunk + decodes) and the prompt finishes after prompt / chunk iterations. Weight work only.

Methods

Name Description
solve Compare monolithic and chunked weight-only prefill intervals.
solve
engine.solvers.kv_cache.ChunkedPrefillModel.solve(
    n_params,
    sustained_rate,
    weight_read_time,
    decodes,
    prompt_tokens,
    chunk_tokens,
)

Compare monolithic and chunked weight-only prefill intervals.

Parameters
Name Type Description Default
n_params Quantity Positive model parameter count in param. required
sustained_rate Quantity Positive declared sustained compute rate in FLOP/s. required
weight_read_time Quantity Nonnegative time to read model weights once. required
decodes int Nonnegative active decode tokens per iteration. required
prompt_tokens int Positive prompt length, evenly divisible by chunk_tokens. required
chunk_tokens int Positive prefill chunk length in tokens. required
Returns
Name Type Description
ChunkedPrefillResult Decode and prefill time quantities, complete chunk count, total chunked duration, and monolithic-to-chunked gap ratio. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: T(n) = max(weight_read_time, 2P*n / rate); chunks = prompt_tokens // chunk_tokens; done = chunks * T(chunk_tokens+decodes).

Assumptions: Prompt tokens divide evenly into positive chunks; each iteration shares weight reads.

Excludes: Attention work, residual partial chunks, dispatch overhead, and scheduling variation.

References

Derivation: T(n) = max(weight_read_time, 2P*n / rate); chunks = prompt_tokens // chunk_tokens; done = chunks * T(chunk_tokens+decodes). This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import ChunkedPrefillModel
>>> ChunkedPrefillModel().solve(Q_('1000 param'), Q_('1 GFLOP/s'), Q_('1 ms'), 1, 16, 4).chunks == 4
True

KvAttentionDesignModel

engine.solvers.kv_cache.KvAttentionDesignModel()

Bytes each token keeps under multi-head, grouped-query, and latent attention.

The design is fixed in pretraining: MHA stores a key and value per query head, GQA shares each stored head among a group, and MLA stores one compressed latent per layer. Parameter count does not enter.

Methods

Name Description
solve Compare retained KV bytes across attention designs.
solve
engine.solvers.kv_cache.KvAttentionDesignModel.solve(
    models,
    mha,
    gqa,
    mla,
    precision,
    session_tokens,
)

Compare retained KV bytes across attention designs.

Parameters
Name Type Description Default
models Sequence Sequence of workloads whose names identify the comparison. required
mha object MHA comparison workload included in models. required
gqa object GQA comparison workload included in models. required
mla object MLA comparison workload included in models. required
precision str KV-cache element precision name (for example, ‘fp16’, ‘bf16’, or ‘fp8’). required
session_tokens int Nonnegative session length in tokens. required
Returns
Name Type Description
KvAttentionDesignResult Bytes per token and attention-design labels keyed by workload name, dimensionless comparison ratios, and session-state byte quantities. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: session_bytes = per_token_bytes * session_tokens; ratios divide MHA or GQA per-token bytes by MLA bytes.

Assumptions: Named comparison models are present in models and their KV geometry is defined.

Excludes: Weights, activations, allocator reserve, and attention execution time.

References

Derivation: session_bytes = per_token_bytes * session_tokens; ratios divide MHA or GQA per-token bytes by MLA bytes. This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import KvAttentionDesignModel
>>> m = Models.Language.Llama3_8B
>>> KvAttentionDesignModel().solve([m], m, m, m, 'fp16', 8).mha_over_mla == 1
True

KvBlockSharingModel

engine.solvers.kv_cache.KvBlockSharingModel()

Block-rounded resident fit with and without a shared prefix, as a turn rate.

B = floor(N_blocks / N_req),   B_shared = floor((N_blocks - N_common) / N_private)
lambda = B / W,   W = T_gen (+ T_wait if the state is kept)

Each request reserves its input and output allowance in whole blocks; a fraction of the pool is withheld as headroom. The gain from sharing approaches 1 / (1 - f) in a large pool.

Methods

Name Description
solve Turn block-rounded KV residency into a memory-limited turn rate.
solve
engine.solvers.kv_cache.KvBlockSharingModel.solve(
    bytes_per_token,
    pool,
    headroom,
    context,
    output,
    common,
    block_tokens,
    generation,
    wait,
)

Turn block-rounded KV residency into a memory-limited turn rate.

Parameters
Name Type Description Default
bytes_per_token Quantity Positive bytes retained per token across all layers. required
pool Quantity Positive bytes available for KV state. required
headroom float Pool fraction withheld, between zero and one (exclusive of one). required
context int Positive input-context token count. required
output int Nonnegative reserved output-token allowance. required
common int Nonnegative shared prefix shorter than total request length. required
block_tokens int Positive allocation block length in tokens. required
generation Quantity Positive generation duration. required
wait Quantity Nonnegative paused residence time. required
Returns
Name Type Description
KvBlockSharingResult Block-rounded byte counts and resident counts, retained duration, turn rates, and dimensionless residency and sharing factors. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: fit = usable_blocks // request_blocks; shared_fit = (usable_blocks-common_blocks) // private_blocks; rate = fit / residence_time.

Assumptions: Common prefix stored once, positive private state and generation time, and sufficient pool for one request.

Excludes: Actual serving throughput, scheduler contention, and fragmentation beyond block rounding.

References

Derivation: fit = usable_blocks // request_blocks; shared_fit = (usable_blocks-common_blocks) // private_blocks; rate = fit / residence_time. This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import KvBlockSharingModel
>>> KvBlockSharingModel().solve(Q_('1 KB'), Q_('1 GB'), 0.1, 16, 8, 4, 4, Q_('1 s'), Q_('1 s')).fit_shared >= 1
True

KvResidencyArchetypeModel

engine.solvers.kv_cache.KvResidencyArchetypeModel()

Sharing gain, residency tax, and resume cost for one agent workload.

Unrounded resident fit with a shared prefix stored once; the residency tax 1 + T_wait / T_gen; and the two resume paths for a dropped or moved state, recompute 2 P S / R against reload S m_token / B_link.

Methods

Name Description
solve Compare shared-prefix residency and paused-state resume paths.
solve
engine.solvers.kv_cache.KvResidencyArchetypeModel.solve(
    bytes_per_token,
    pool,
    n_params,
    sustained_rate,
    link,
    context_tokens,
    shared_prefix,
    generation,
    wait,
)

Compare shared-prefix residency and paused-state resume paths.

Parameters
Name Type Description Default
bytes_per_token Quantity Positive bytes retained per token across all layers. required
pool Quantity Positive bytes available for KV state. required
n_params Quantity Positive model parameter count in param. required
sustained_rate Quantity Positive declared sustained compute rate in FLOP/s. required
link Quantity Positive aggregate copy bandwidth in byte/s. required
context_tokens int Positive retained context length in tokens. required
shared_prefix int Nonnegative shared prefix shorter than context_tokens. required
generation Quantity Positive generation duration. required
wait Quantity Nonnegative paused residence time. required
Returns
Name Type Description
KvResidencyArchetypeResult Resident counts, sharing and residency factors, cycle/recompute seconds, reload milliseconds, and retained/released turn rates. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: fit_shared = floor((pool-shared_prefix*bytes_per_token)/((context-shared_prefix)*bytes_per_token)); cycle = generation+wait; recompute = 2P*context/rate.

Assumptions: Shared prefix shorter than context, positive rates, and enough pool for one request.

Excludes: Block rounding, attention recomputation, contention, and execution-capacity limits.

References

Derivation: fit_shared = floor((pool-shared_prefix*bytes_per_token)/((context-shared_prefix)*bytes_per_token)); cycle = generation+wait; recompute = 2P*context/rate. This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import KvResidencyArchetypeModel
>>> KvResidencyArchetypeModel().solve(Q_('1 KB'), Q_('1 GB'), Q_('1000 param'), Q_('1 GFLOP/s'), Q_('1 GB/s'), 16, 4, Q_('1 s'), Q_('1 s')).fit_shared > 0
True

PagedAllocationModel

engine.solvers.kv_cache.PagedAllocationModel()

Full-cap reservation against fixed-size blocks allocated on demand.

A reservation holds S_max slots from admission; a request ending at a mean of S_mean tokens fills S_mean / S_max of it. Paged blocks waste at most the unused tail of the last block; under capped exponential final lengths (a modeling assumption, calc_expected_paged_kv_tokens) the expected allocation sets a final-length snapshot count, not a live admission capacity.

Methods

Name Description
solve Compare full-context reservation with expected block allocation.
solve
engine.solvers.kv_cache.PagedAllocationModel.solve(
    bytes_per_token,
    pool,
    cap,
    mean_final,
    small_block,
    large_block,
)

Compare full-context reservation with expected block allocation.

Parameters
Name Type Description Default
bytes_per_token Quantity Positive bytes retained per token across all layers. required
pool Quantity Positive bytes available for KV state. required
cap int Positive maximum request length in tokens. required
mean_final int Positive mean final token count below the cap. required
small_block int Positive smaller allocation block size in tokens. required
large_block int Positive larger allocation block size in tokens. required
Returns
Name Type Description
PagedAllocationResult Reserved bytes and request counts, expected allocated token counts, wasted fractions, block-tail bytes, and dimensionless residency gain. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: reservation = cap * bytes_per_token; fit = floor(pool / allocation_bytes); efficiency = mean_final / cap.

Assumptions: Capped exponential final lengths and positive blocks; pool holds at least one full reservation.

Excludes: Live scheduler admission, fragmentation between requests, and transient growth.

References

Derivation: reservation = cap * bytes_per_token; fit = floor(pool / allocation_bytes); efficiency = mean_final / cap. This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import PagedAllocationModel
>>> PagedAllocationModel().solve(Q_('1 KB'), Q_('1 GB'), 128, 32, 8, 16).reservations > 0
True

PausedKvStateModel

engine.solvers.kv_cache.PausedKvStateModel()

Keep, move, or drop a paused request’s KV state during a tool wait.

T_reload = M / (n B_link),   T_recompute = 2 P S / R

Both grow linearly with the context, so their ratio does not depend on length. Keeping holds M x T_wait of memory time; moving frees the memory for the wait less the copy-out (on demand) or less the round trip (prefetch). Correlated returns serialize on the shared links.

Methods

Name Description
solve Compare keeping, copying, and rebuilding paused KV state.
solve
engine.solvers.kv_cache.PausedKvStateModel.solve(
    bytes_per_token,
    n_params,
    sustained_rate,
    link,
    context_tokens,
    block_tokens,
    wait,
    link_fraction,
    returns,
)

Compare keeping, copying, and rebuilding paused KV state.

Parameters
Name Type Description Default
bytes_per_token Quantity Positive bytes retained per token across all layers. required
n_params Quantity Positive model parameter count in param. required
sustained_rate Quantity Positive declared sustained compute rate in FLOP/s. required
link Quantity Positive aggregate copy bandwidth in byte/s. required
context_tokens int Positive retained context length in tokens. required
block_tokens int Positive allocation block length in tokens. required
wait Quantity Nonnegative paused residence time. required
link_fraction float Positive fraction of peak link rate, at most one. required
returns int Positive number of simultaneous returning requests. required
Returns
Name Type Description
PausedKvStateResult Block count, state bytes, copy milliseconds, recompute seconds, byte-time occupancy, released durations, and serialized burst costs. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: state = ceil(context/block_tokens) * block_tokens * bytes_per_token; copy = state/link; recompute = 2P*context/rate.

Assumptions: Whole-block state, equal inbound/outbound bandwidth, and serialized simultaneous returns.

Excludes: Attention recomputation, copy overlap, contention, and feasibility clipping of negative released time.

References

Derivation: state = ceil(context/block_tokens) * block_tokens * bytes_per_token; copy = state/link; recompute = 2P*context/rate. This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import PausedKvStateModel
>>> PausedKvStateModel().solve(Q_('1 KB'), Q_('1000 param'), Q_('1 GFLOP/s'), Q_('1 GB/s'), 16, 4, Q_('1 s'), 1, 2).blocks == 4
True

PrefixRebuildModel

engine.solvers.kv_cache.PrefixRebuildModel()

The prefill a prefix-cache hit avoids, against one short suffix pass.

T_rebuild = (2 P S + 2 L d S^2) / R,   R = n R_peak u
T_hit = max(W / (n B_mem), 2 P S_suffix / R)

A miss rebuilds the prefix’s linear and causal-attention work at the sustained rate; a hit runs one pass over the suffix, bounded by reading the weights once when the suffix is short.

Methods

Name Description
solve Compare rebuilding a cached prefix with a suffix-only pass.
solve
engine.solvers.kv_cache.PrefixRebuildModel.solve(
    workload,
    node,
    precision,
    prefix_tokens,
    suffix_tokens,
    utilization,
)

Compare rebuilding a cached prefix with a suffix-only pass.

Parameters
Name Type Description Default
workload object Transformer workload with parameter and KV geometry. required
node object System node containing accelerator count and specifications. required
precision str KV-cache element precision name (for example, ‘fp16’, ‘bf16’, or ‘fp8’). required
prefix_tokens int Positive cached-prefix token count. required
suffix_tokens int Positive suffix token count. required
utilization float Compute utilization fraction above zero and at most one. required
Returns
Name Type Description
PrefixRebuildResult Prefix-state bytes, linear and attention FLOPs, sustained FLOP/s, rebuild/read/suffix milliseconds, and the rebuild-to-hit time ratio. Bounds are conditional on the stated assumptions, not deployment guarantees.
Notes

Equation: rebuild = (2PS + 2LdS^2) / rate; hit = max(weights / aggregate_bandwidth, 2P*suffix / rate).

Assumptions: Aggregate device bandwidth and compute add ideally; utilization is a declared fraction.

Excludes: Inter-device collectives, suffix attention, scheduler overhead, and capacity validation.

References

Derivation: rebuild = (2PS + 2LdS^2) / rate; hit = max(weights / aggregate_bandwidth, 2P*suffix / rate). This combines the supplied quantities by conservation of traffic or residence time; it is an analytical accounting model.

Examples
>>> from mlsysim import Models
>>> from mlsysim.core.units import Q_
>>> from mlsysim.solvers import PrefixRebuildModel
>>> from mlsysim import Systems
>>> PrefixRebuildModel().solve(Models.Language.Llama3_8B, Systems.Nodes.DGX_H100, 'fp16', 128, 1, 0.5).rebuild_time.magnitude > 0
True
Back to top