Skip to content

feat(kv_cache): estimate what context costs next to the quantized weights - #4158

Merged
Qubitium merged 4 commits into
ModelCloud:mainfrom
Lumea-art:feat/kv-cache-estimate
Nov 16, 2026
Merged

Qubitium merged 4 commits into
ModelCloud:mainfrom
Lumea-art:feat/kv-cache-estimate

Conversation

@Lumea-art

Copy link
Copy Markdown
Contributor

Summary

Weight quantization decides the checkpoint size; the KV cache decides how much context fits beside it, and the two are independent. A 4-bit 8B model can still need more VRAM for a 32k cache than for its weights, and nothing in the run output said so.

A finished quantization now ends with one more line:

INFO  Quantize summary: 1 layer(s), 14 module(s), 2s
INFO  KV cache: 256 B/token (2L x 2KV x 16d, bfloat16) | 8k ctx 2 MiB | 32k ctx 8 MiB

and a real config, for reference:

INFO  KV cache: 144 KiB/token (36L x 8KV x 128d, float16) | 8k ctx 1.1 GiB | 32k ctx 4.5 GiB   # Qwen3-8B
INFO  KV cache: 12 KiB/token (24L x 2KV x 64d, float16) | 8k ctx 96 MiB | 32k ctx 384 MiB      # Qwen2.5-0.5B

API

gptqmodel.utils.kv_cache:

estimate = estimate_kv_cache(config)         # None when the config does not say
estimate.bytes_per_token                     # K and V, every layer, one batch element
estimate.bytes_for(8192, batch_size=4)
estimate.tokens_for(free_vram_bytes)         # "how much context fits in what is left"
estimate.format()

tokens_for is the question users actually have after loading a model, and having it in one place beats every caller reimplementing layers * 2 * kv_heads * head_dim * itemsize.

What it refuses to guess

The arithmetic is only meaningful for the standard per-head K/V layout, so:

  • MLA configs (kv_lora_rank / q_lora_rank) return None. A DeepSeek-style cache is a compressed latent, not one K/V pair per head per layer; a number there would look authoritative and be wrong.
  • Configs without layer/head/hidden sizes return None rather than a plausible default.
  • Unsupported dtypes return None (int8 KV storage is a different layout, not 1 byte per element here).
  • Multimodal configs are unwrapped through text_config, and sliding_window is carried and printed, since it caps growth.

None is deliberate: this is a config calculation, not a runtime measurement, and a wrong number is worse than no number for capacity planning.

Tests

tests/test_kv_cache_estimate.py     17 passed
tests/test_quantize_run_summary.py  23 passed
tests/test_quant_telemetry.py        11 passed
tests/test_calibration_data_device.py 17 passed, 5 skipped

Coverage: GQA and MQA arithmetic against hand-computed values, head_dim default and override, fp32 doubling, both MLA fields refused, text_config unwrapping, missing shapes, unsupported dtype, config dtype inheritance and fallback, sliding window, zero/negative inputs, tokens_for inverting bytes_for, and the unit scaling of format().

One environment note

This checkout runs torch 2.14.1, which the new ensure_safe_torch() gate rejects (GHSA-v32g-mr63-3j83, patched in 2.15.0), so local runs here use GPTQ_BYPASS_SAFETY_CHECKS=1. The flag is only for verification on this machine; nothing in the patch depends on it.

…ghts

Weight quantization decides the checkpoint size; the KV cache decides how much
context fits beside it, and the two are independent. A 4-bit 8B model can still
need more VRAM for a 32k cache than for its weights, and nothing in the run
output said so. A finished quantization now ends with:

    INFO  Quantize summary: 1 layer(s), 14 module(s), 2s
    INFO  KV cache: 256 B/token (2L x 2KV x 16d, bfloat16) | 8k ctx 2 MiB | 32k ctx 8 MiB

`gptqmodel/utils/kv_cache.py` does the arithmetic on the config and refuses to
guess where the shapes are not what the formula assumes:

- MLA configs (`kv_lora_rank` / `q_lora_rank`) return None: a compressed latent
  is not one K/V pair per head per layer, so a number there would be wrong;
- a config without layer/head/hidden sizes returns None instead of a plausible
  value;
- multimodal configs are unwrapped through `text_config`;
- `sliding_window` is carried and reported, because it caps growth.

`KVCacheEstimate` exposes `bytes_per_token`, `bytes_for(tokens, batch_size)`,
`tokens_for(budget)` and `format()`, so callers can ask "how much context fits in
the VRAM I have left" rather than reimplementing the formula.

    tests/test_kv_cache_estimate.py    17 passed
    tests/test_quantize_run_summary.py 23 passed
    real 4-bit CPU run                 summary + KV line both emitted
@Qubitium

Qubitium commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

@Lumea-art The current code is not accurate right now. Check DeepSeek v4.1 flash like models new class of models to make sure it is more accurate.

… gqa

The first version assumed every layer keeps one K and one V per KV head, and
returned None for anything else. That is wrong for the model families the
maintainer pointed at: DeepSeek-style attention keeps one compressed latent
(`kv_lora_rank`) plus a decoupled RoPE key (`qk_rope_head_dim`) shared across
heads, GLM5 and DeepSeek V4.1 declare mixed stacks through `layer_types`, and
linear-attention layers keep a constant-size state that never grows with context.

The estimator now classifies every layer and reports what it could not classify:

  gqa / mqa      2 * kv_heads * head_dim elements per token per layer
  mla            kv_lora_rank + qk_rope_head_dim, shared across heads, no
                 factor of two. For a V3-shaped config (61 layers, latent 512,
                 rope 64) that is 68.6 KiB/token; reading the per-head shapes
                 instead gives 4 MB/token, about 60x too large.
  linear         counted separately as constant state, never in the per-token
                 slope
  sliding        growth capped at min(context, window), reported as such
  mtp            `num_nextn_predict_layers` reuse the last declared layout and
                 are labelled in the output
  unknown        named in the line and `exact` goes False, instead of being
                 folded into a total that looks authoritative

`bytes_for` respects the window per layer, and `tokens_for` inverts it across
the window boundary, so "what fits in the VRAM I have left" stays right for
hybrid stacks.

Tests grew from 17 to 23, and three of them run against real config classes
rather than hand-built namespaces: DeepseekV2Config for MLA and
Glm5NextTextConfig for the mixed `linear_attention` + `indexed_attention` stack.
@Lumea-art

Copy link
Copy Markdown
Contributor Author

You are right - the first version assumed one K/V pair per KV head on every layer, and returned None for anything else. That is wrong exactly where you pointed: the compressed-latent families.

Reworked in 40fae8859. The layout is now resolved per layer:

layout elements per token per layer example
gqa / mqa 2 * kv_heads * head_dim Llama-style
mla kv_lora_rank + qk_rope_head_dim, shared across heads, no factor of two DeepSeek V2/V3/V4
linear attention constant state, reported separately, never in the per-token slope GLM5 linear_attention
sliding growth capped at min(ctx, window)
mtp num_nextn_predict_layers reuse the last declared layout, labelled

The size of the mistake is easy to see on a V3-shaped config (61 layers, latent 512, rope 64):

mla:  61 * (512 + 64) * 2 B = 68.6 KiB/token   ->  32k ctx = 2.1 GiB
per-head reading of the same config: 61 * 2 * 128 * 128 * 2 = 4 MB/token

About 60x apart, which is why I would rather not ship the naive formula behind an if.

For mixed stacks the estimator walks layer_types (also attention_layer_types / attn_layer_types), counts the growing layers, and reports the rest:

INFO  KV cache: 512 B/token (2L x 128 elem/token, mla, float16) | 8k ctx 4 MiB | 32k ctx 16 MiB | 1 linear-attention layer(s) hold constant state | incl. 1 MTP layer(s)

Anything it cannot classify is named in the line and sets exact=False instead of being folded into a total that looks authoritative. tokens_for() inverts across the window boundary, so "how much context fits in what is left" stays correct for hybrids.

Verified against real config classes, not hand-built namespaces:

  • DeepseekV2Config(kv_lora_rank=512, qk_rope_head_dim=64, ...) -> 576 elem/token, mla
  • Glm5NextTextConfig(layer_types=["linear_attention", "deepseek_sparse_attention"], ...) -> 2 growing layers, 1 linear, 1 MTP, exact=True
tests/test_kv_cache_estimate.py     23 passed
tests/test_quantize_run_summary.py  23 passed
format/check.sh                     clean for the touched files

One thing I could not check: transformers.models.deepseek_v41 is not in the installed transformers (5.22), so I cannot instantiate V4.1 Flash's own config here. The repo's definitions/deepseek_v41.py imports it, so it exists in the tree you build against. If V4.1 declares cache structure beyond layer_types - the inventory doc mentions window_kv_cache / compress_kv_cache as runtime caches - point me at the config fields and I will resolve those too; right now such a config either maps onto mla + sliding/linear layer types or lands in unclassified with exact=False.

@Qubitium

Copy link
Copy Markdown
Collaborator

@Lumea-art You need to show me ALL supported models have correct kv calculation and not ust the few models tested here. Test ALL models

…d model

The previous revision assumed one K/V pair per KV head on every layer and
returned None for anything else. Walking the whole registry showed how little
that covers, and turned up the two families the maintainer pointed at.

Layouts are now resolved layer by layer:

  gqa / mqa       2 * kv_heads * head_dim
  mla             kv_lora_rank + qk_rope_head_dim, shared across heads, no x2
  compressed      bounded sliding K/V plus one pooled entry every
                  ``compress_rate`` source tokens (DeepSeek V4 HCA/CSA). Shared-KV
                  MQA stores keys and values in one tensor, so no x2 either.
  linear          constant state, reported, never in the per-token slope
  sliding         growth capped at min(context, window)
  hybrid          a layer that mixes a recurrent branch with attention keeps
                  standard K/V for the attention half

Heterogeneous stacks are read through ``per_layer_config``, where per-layer
attributes refuse global reads (Gemma4 raises AmbiguousGlobalPerLayerAttributeError
on ``head_dim``); multimodal wrappers are unwrapped and their stacks summed
(omni thinker + talker). An unrecognized layer type is named and sets
``exact=False`` - it is never counted as a full attention layer, which is what
the earlier revision did and would have produced confident wrong numbers.

Measurements, not just arithmetic:

- ``estimate.bytes_for(tokens)`` equals the bytes transformers actually allocates
  for ``past_key_values`` on llama and qwen2 tiny models, once the weight dtype
  is supplied (the earlier revision defaulted to fp16 and was 2x off for fp32).
- The all-models sweep covers every supported type:
  ``tests/test_kv_cache_all_models.py`` 137 passed, 71 skipped (config class not
  installed in this transformers), 0 errors. ``scripts/check_kv_cache_models.py``
  prints the same table: 206 models -> 132 estimated (119 gqa, 12 mla, 1
  compressed), 3 without a per-token cache (2 all-recurrent, 1 OCR wrapper),
  71 unmapped, 0 exceptions. deepseek_v4 resolves to ``compressed`` with 44
  growing layers and 5.3 KiB/token, instead of None.
@Lumea-art

Copy link
Copy Markdown
Contributor Author

Tested all of them. The sweep is in 81b31c56d and it changed the design, not just the test list.

Coverage

scripts/check_kv_cache_models.py walks SUPPORTED_MODELS:

models=206 no_cache=3 ok=132 unmapped=71
layouts: {'gqa': 119, 'mla': 12, 'compressed': 1}
exact=True: 129 / 132      (llama4, llama4_text, nemotron_h carry unrecognized layer types)
no_cache: falcon_mamba, granitemoehybrid (every layer recurrent), unlimited_ocr (no decoder stack exposed)
unmapped: 71 - config class not installed in this transformers 5.22 (remote-code families: chatglm, baichuan, dbrx, ...)
errors: 0

tests/test_kv_cache_all_models.py asserts the same sweep in CI: 137 passed, 71 skipped, 0 failed. A skipped model prints the reason it was skipped, so the coverage number is honest rather than implied.

What the sweep forced

Three designs did not survive contact with the registry:

Gemma4 is heterogeneous. Its text config raises AmbiguousGlobalPerLayerAttributeError on head_dim because the field varies per layer. Reading the global value would be wrong for every layer but one, so the estimator now walks per_layer_config and sums per-layer dims. Omni wrappers are unwrapped and their stacks summed (thinker + talker).

DeepSeek V4 is not MLA and not gqa. Its layers are heavily_compressed_attention / compressed_sparse_attention, whose cache is a bounded sliding branch plus one pooled entry every compress_rate source tokens, with keys and values sharing one tensor:

config: sliding_window=128, compress_rates={HCA: 128, CSA: 4}, head_dim=512, num_key_value_heads=1
result: 44 growing layers, 5.3 KiB/token -> 8k ctx 47 MiB, 32k ctx 171.5 MiB

Reading it as per-head K/V would give 43 * 2 * 64 * 512 * 2 = 2.8 MB/token, about 540x too large. Before this commit deepseek_v4 returned None.

Unknown layer types were being silently counted. The first per-layer version treated any unrecognized type as a full attention layer - confident and wrong. They are now named and set exact=False; that is what flagged llama4 and nemotron_h instead of hiding them.

Measurement, not arithmetic

For a model that can be built, the prediction is compared against the bytes transformers actually allocates for past_key_values:

llama   dtype=float32  measured=4096  predicted=4096  MATCH
qwen2   dtype=float32  measured=2048  predicted=2048  MATCH

That check also caught a real bug: the estimate defaulted to fp16, so it was exactly 2x low on fp32 weights. The dtype now comes from the weights that were quantized, not from config.torch_dtype (which is usually unset).

tests/test_kv_cache_estimate.py      24 passed
tests/test_kv_cache_all_models.py    137 passed, 71 skipped
tests/test_quantize_run_summary.py   23 passed

What I cannot claim

The 71 unmapped types have no config class in the installed transformers, so nothing here exercises them - the sweep skips them by name, it does not vouch for them. For those, the estimator falls back to whatever fields the remote config exposes and marks the result inexact if a layer type is unrecognized.

The CSA entry width (one head_dim per pooled entry) is read from the modeling docstring in transformers/models/deepseek_v4. If the paper's 2 * compress_rate_csa means the emitted entry is wider than head_dim, that term needs adjusting - it is one number in _estimate_for_stack, and --json from the sweep script shows exactly which models would move.

@Qubitium

Copy link
Copy Markdown
Collaborator

@Lumea-art Looks good. Please fix tge merge conflict

Resolve gptqmodel/models/base.py: keep the pinned-host-cache release from
main and the new kv-cache estimate log at the end of quantize().
@Qubitium

Copy link
Copy Markdown
Collaborator

Merged origin/main into feat/kv-cache-estimate to clear the new conflict (maintainer edit).

Conflict: gptqmodel/models/base.py, both sides added a statement at the end of quantize(). Resolution keeps both — release_pinned_host_cache() (from #4395) followed by _log_kv_cache_estimate(self).

Verified after the merge: PYTHONPATH=... pytest tests/test_kv_cache_estimate.py tests/test_kv_cache_all_models.py -q -> 161 passed, 71 skipped. The PR is mergeable again; no other files were touched.

@Lumea-art

Copy link
Copy Markdown
Contributor Author

Thanks - I re-ran everything on your merge head (954d61052) rather than on my last commit, since the resolution is the thing that ships.

tests/test_kv_cache_estimate.py      24 passed
tests/test_kv_cache_all_models.py   137 passed, 71 skipped
tests/test_quantize_run_summary.py   24 passed
format/check.sh (ruff 0.14.2)        All checks passed
scripts/check_kv_cache_models.py     models=206 ok=132 no_cache=3 unmapped=71 errors=0

And an end-to-end quantization of a 2-layer model on that head, which exercises both statements in the merged tail (release_pinned_host_cache() then _log_kv_cache_estimate):

INFO  Quantize summary: 2 layer(s), 14 module(s), 2s
INFO  KV cache: 256 B/token (2 growing layer(s), gqa, bfloat16) | 8k ctx 2 MiB | 32k ctx 8 MiB

The ordering in your resolution is the right one: the pinned-host release is about memory the run staged, and the KV line only reads config plus dtype, so nothing depends on the freed blocks.

One thing on my side: the PR shows mergeable=MERGEABLE but mergeStateStatus=BLOCKED, and there are no check runs on 954d61052 (commits/<sha>/check-runs is empty). That is the fork-workflow approval gate rather than a failure - if you approve the run, the checks should populate; otherwise it is ready from my side and I will not touch the branch again.

@Qubitium
Qubitium merged commit 3ff1cde into ModelCloud:main Nov 16, 2026
Qubitium pushed a commit that referenced this pull request Nov 17, 2026
…low fp8 (#4516)

The estimator #4158 resolves the cache layout per layer, and the sweep that came
with it flagged three models as inexact. Looking at why turned up a real
under-report rather than a cosmetic gap.

Llama4 declares 48 layers as 36 `chunked_attention` + 12 `full_attention`.
`chunked_attention` is not an unknown layout: it is global attention with a
chunked causal mask, so its cache covers the whole context (transformers'
`create_chunked_causal_mask` documents it as the global half of Llama4's hybrid
cache). It was being excluded, so only 12 of 48 layers were counted:

    before: 48 KiB/token (12 growing layers), 32k ctx 1.5 GiB
    after:  192 KiB/token (48 growing layers), 32k ctx 6 GiB
            -> 4.00x under-report

Nemotron-H lists `moe` / `mlp` in `layer_types`, but those are blocks, not
attention: the modeling code dispatches them to `NemotronHMoE` / `NemotronHMLP`
mixers and its own comment says "Nemotron-H layer_types include non-attention
block types (moe / mlp)". They are now counted as `block` layers that hold no
cache state, reported separately from linear-attention layers so the line does
not claim a recurrent state that is not there.

`torch.float8_e4m3fn` and friends are now one byte per element, which is what a
serving engine stores when it runs an fp8 KV cache, so the halved footprint can
be estimated instead of returning None.

Sweep after this change:

    models=206 ok=132 no_cache=3 unmapped=71 errors=0
    exact: 132 / 132        (was 129 / 132)
    llama4      48 growing layers, exact=True
    llama4_text 48 growing layers, exact=True
    nemotron_h   1 growing + 1 linear + 2 non-attention block(s), exact=True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants