kv-cache-size
Exact KV-cache arithmetic for transformer inference. No dependencies, no allocation, no model downloads, no network.
kv_bytes = 2 x bytes_per_element x num_hidden_layers x num_key_value_heads
x head_dim x context_length x batch_size
The leading 2 is one K tensor plus one V tensor.
The two terms people get wrong
num_key_value_heads, notnum_attention_heads. Grouped-query attention keeps fewer key/value heads than query heads (Ainslie et al., GQA, arXiv:2305.13245), so using the query-head count overstates the cache by the GQA group size — 4x on Llama 3.1 8B, 8x on Qwen2.5-7B.head_dimas published, not derived.hidden_size / num_attention_headsis a habit that breaks on configs where the publishedhead_dimdisagrees with it.head_dim_from_hiddenexists for configs that genuinely omit the field, and is deliberately separate from the main path so the fallback is visible at the call site.
Example
use ;
// Llama 3.1 8B: 32 layers, 8 key-value heads, head_dim 128.
let cfg = new.unwrap;
assert_eq!; // 128 KiB per token
assert_eq!;
// How much context fits in 16 GiB of spare VRAM at fp8, batch 4?
let budget = 16.0 * 1024.0 * 1024.0 * 1024.0;
assert_eq!;
What this crate does not do
It sizes the KV cache only. Weights, activations, CUDA context and allocator fragmentation are not included, so the number is a floor for planning, not a capacity guarantee. Interactive version and per-model configs: https://ml0x.com/calculators/kv-cache-size-calculator.html.
Licensed under MIT OR Apache-2.0.