Repository navigation
feat(kv_cache): estimate what context costs next to the quantized weights - #4158
Conversation
…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
|
@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.
|
You are right - the first version assumed one K/V pair per KV head on every layer, and returned Reworked in
The size of the mistake is easy to see on a V3-shaped config (61 layers, latent 512, rope 64): About 60x apart, which is why I would rather not ship the naive formula behind an For mixed stacks the estimator walks 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 Verified against real config classes, not hand-built namespaces:
One thing I could not check: |
|
@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.
|
Tested all of them. The sweep is in Coverage
What the sweep forcedThree designs did not survive contact with the registry: Gemma4 is heterogeneous. Its text config raises DeepSeek V4 is not MLA and not gqa. Its layers are 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 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 Measurement, not arithmeticFor a model that can be built, the prediction is compared against the bytes transformers actually allocates for 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 What I cannot claimThe 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 |
|
@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().
|
Merged Conflict: Verified after the merge: |
|
Thanks - I re-ran everything on your merge head ( 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=0And an end-to-end quantization of a 2-layer model on that head, which exercises both statements in the merged tail ( 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 MiBThe 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 |
…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
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:
and a real config, for reference:
API
gptqmodel.utils.kv_cache:tokens_foris the question users actually have after loading a model, and having it in one place beats every caller reimplementinglayers * 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:
kv_lora_rank/q_lora_rank) returnNone. 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.Nonerather than a plausible default.None(int8 KV storage is a different layout, not 1 byte per element here).text_config, andsliding_windowis carried and printed, since it caps growth.Noneis deliberate: this is a config calculation, not a runtime measurement, and a wrong number is worse than no number for capacity planning.Tests
Coverage: GQA and MQA arithmetic against hand-computed values,
head_dimdefault and override, fp32 doubling, both MLA fields refused,text_configunwrapping, missing shapes, unsupported dtype, config dtype inheritance and fallback, sliding window, zero/negative inputs,tokens_forinvertingbytes_for, and the unit scaling offormat().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 useGPTQ_BYPASS_SAFETY_CHECKS=1. The flag is only for verification on this machine; nothing in the patch depends on it.