"""Size Kimi K3.1 Pro's cache, delta-rule state and per-GPU pool from its config.json and safetensors headers. Used for content/standalone/06-serving-in-production/05-kimi-k31-pro-serving (2026-11-05). Runs on a laptop, standard library only, no GPU, no weight download: it reads config.json and the safetensors *headers* (HTTP range requests, a few MB in all) from the Hugging Face repo at a pinned revision. python3 kimi_k31_kv.py # bytes per token, state, weights per GPU, pools, sessions python3 kimi_k31_kv.py --config config.json # bytes per token and state from a local config.json only python3 kimi_k31_kv.py --context 404000 # sessions for another context length Cache rows (per DSA layer, per token): - vLLM PR #65685 @ 4414f472fb: per-tensor FP8 latent on SM100-class GPUs (FlashInfer sparse MLA), 512 + 64 = 576 B (model_executor/models/config.py, KimiK3ForConditionalGenerationConfig); fp8_ds_mla (656 B) elsewhere; NVFP4 latent 352 B (--kv-cache-dtype nvfp4_ds_mla). Index key: 128 FP8 + one FP32 scale = 132 B, or MXFP4 64 + 4 = 68 B (models/kimi_k3/common/dsa_cache.py, indexer_cache_entry_bytes). - SGLang (main @ 61a3c7f, PR #48415): FP8 forced; the default FlashMLA DSA path keeps fp8_ds_mla rows, 512 FP8 + 4 FP32 scales + 64 BF16 = 656 B (dsa_quant_k_cache.py, fp8_ds_mla_row_width); TRT-LLM and Prims-TS backends store plain FP8, 576 B. KDA state per layer and request: 96 heads x 128 x 128 recurrent values (FP32 by default in both engines) plus the short-conv windows of q, k and v (kernel 4 keeps 3 positions) over 96 x 128 channels each, in BF16. Both split by head across TP ranks; DCP doesn't divide them. Weights per GPU at TP (plain tensor parallelism, no expert parallelism): tensors split by TP are divided by TP; the ones PR #65685 builds replicated stay whole on every GPU: the q/kv down-projections (fused_qkv_a_proj, disable_tp), the indexer (wq_index ReplicatedLinear, wk + weights_proj disable_tp, k_norm), the KDA f_a_proj (replicated shard of in_proj_qkvgfab), the router, the latent-MoE down/up projections (ReplicatedLinear), the Attention Residuals projections, every norm, the vision tower and the multimodal projector. Pool per GPU: what vLLM's published capacities imply (tokens x bytes per token). Pass --budget-gb to build it as budget - weights per GPU for your own GPUs. """ import argparse import json import re import struct import urllib.request REPO, REV, SHARDS = "moonshotai/Kimi-K3.1-Pro", "6d0a0202956796543364d666ab19c6ad1a494ee1", 96 K3 = ("moonshotai/Kimi-K3", "f831ab66814297da540d832a5235f8e904f29d06") REPLICATED = [r"q_a_proj", r"kv_a_proj_with_mqa", r"layernorm", r"\.indexer\.", r"f_a_proj", r"\.gate\.", r"routed_expert_(down|up)_proj", r"routed_expert_norm", r"_res_proj", r"_res_norm", r"\.norm\.", r"o_norm", r"^vision_tower", r"^mm_projector"] # vLLM blog (2026-11-04), 8x GB300, TP8: tokens of KV, and bytes per token of the layout they were measured with. PUBLISHED = {"FP8 latent + FP8 keys, TP8": (3.04e6, 16992, 1), "NVFP4 latent + FP8 keys, TP8": (4.49e6, 11616, 1), "FP8 latent + FP8 keys, TP8 DCP8": (21.8e6, 16992, 8), "NVFP4 latent + FP8 keys, TP8 DCP8": (32.1e6, 11616, 8)} MIB, GIB = 2**20, 2**30 def fetch(url, rng=None): req = urllib.request.Request(url, headers={"Range": f"bytes={rng}"} if rng else {}) with urllib.request.urlopen(req) as r: return r.read() def hf(repo, rev, name): return f"https://huggingface.co/{repo}/resolve/{rev}/{name}" def text_config(c): return c.get("text_config", c) def layouts(t): """Bytes per token: {name: (latent row, index row, per token)} over the DSA (full-attention) layers.""" n = len(t["linear_attn_config"]["full_attn_layers"]) lat = t["kv_lora_rank"] + t["qk_rope_head_dim"] d = t["dsa_config"]["index_head_dim"] rows = { "vLLM FP8 (per-tensor, SM100)": (lat, d + 4), "SGLang FP8 (fp8_ds_mla, FlashMLA)": (t["kv_lora_rank"] + 4 * t["kv_lora_rank"] // 128 + 2 * t["qk_rope_head_dim"], d + 4), "BF16 latent + FP8 keys": (2 * lat, d + 4), "vLLM NVFP4 latent + FP8 keys": (352, d + 4), "vLLM NVFP4 latent + MXFP4 keys": (352, d // 2 + d // 32), } return n, {k: (a, b, n * (a + b)) for k, (a, b) in rows.items()} def state(t, recurrent_bytes=4, conv_bytes=2): kda = t["linear_attn_config"] n, h, d, k = len(kda["kda_layers"]), kda["num_heads"], kda["head_dim"], kda["short_conv_kernel_size"] rec = n * h * d * d * recurrent_bytes conv = n * (k - 1) * 3 * h * d * conv_bytes return n, h, rec, conv def weights_per_gpu(tps): sharded = replicated = 0 for i in range(1, SHARDS + 1): url = hf(REPO, REV, f"model-{i:05d}-of-{SHARDS:06d}.safetensors") n = struct.unpack(" 1 else ''}") topk, lat, key = dsa["index_topk"], rows["vLLM FP8 (per-tensor, SM100)"][0], rows["vLLM FP8 (per-tensor, SM100)"][1] be = lat * topk / (lat - key) print(f"\ndecode bytes read per DSA layer: dense {lat} x L, DSA {key} x L + {lat} x {topk}; break-even {be:,.0f} tokens") for L in (8192, 32768, 131072, 1048576): print(f" L={L:>9,}: DSA / dense = {(key * L + lat * topk) / (lat * L):.1%}") qh = t["num_attention_heads"] mla_flops = qh * 2 * (lat + t["kv_lora_rank"]) * topk idx_flops = dsa["index_num_heads"] * dsa["index_head_dim"] * 2 print(f"per query token per layer: sparse MLA {mla_flops / 1e6:.1f} MFLOP over {topk} keys ({qh} heads x 2 x " f"({lat}+{t['kv_lora_rank']})); indexer {idx_flops:,} FLOP x L. Equal at L = {mla_flops / idx_flops:,.0f}; " f"under TP8 (MLA heads split, indexer not) at L = {mla_flops / 8 / idx_flops:,.0f}") if args.config: return wpg, total, rep = weights_per_gpu((8, 16)) print(f"\ncheckpoint {total / 1e9:.1f} GB, replicated under TP {rep / 1e9:.2f} GB") for tp, w in wpg.items(): print(f" TP{tp}: weights per GPU {w / 1e9:.1f} GB ({w / GIB:.1f} GiB)") print("\npools implied by vLLM's published capacities (8x GB300):") for name, (tok, bpt, dcp) in PUBLISHED.items(): pool = tok * bpt / dcp print(f" {name:34s} {tok / 1e6:5.2f}M x {bpt:,} / {dcp} = {pool / 1e9:.1f} GB per GPU; " f"+ weights = {(pool + wpg[8]) / 1e9:.1f} GB") tp_pool = PUBLISHED["FP8 latent + FP8 keys, TP8"][0] * v dcp_pool = PUBLISHED["FP8 latent + FP8 keys, TP8 DCP8"][0] * v / 8 print(f" DCP8 / TP8 tokens: {21.8 / 3.04:.2f}x; the DCP8 pool is {(tp_pool - dcp_pool) / 1e9:.1f} GB per GPU smaller") if args.budget_gb: tp_pool = dcp_pool = args.budget_gb * 1e9 - wpg[8] print(f" --budget-gb {args.budget_gb}: pool {tp_pool / 1e9:.1f} GB per GPU at TP8 and DCP8") s8 = tot_state / 8 print(f"\nsessions on 8 GPUs (pool - sessions x (context x bytes / DCP + state per GPU) >= 0), vLLM FP8 rows:") for ctx in (8192, 100_000, args.context, 1_048_576): tp = tp_pool / (ctx * v + s8) dc = dcp_pool / (ctx * v / 8 + s8) print(f" {ctx:>9,} tokens: TP8 {tp:6.1f} (KV only {tp_pool / (ctx * v):6.1f}), " f"DCP8 {dc:6.1f} (KV only {dcp_pool / (ctx * v / 8):6.1f}); state share at DCP8 {s8 / (ctx * v / 8 + s8):.0%}") if __name__ == "__main__": main()