"""Size Mistral Large 4's KV cache and per-GPU pool from its params.json and safetensors headers. Used for content/standalone/06-serving-in-production/11-mistral-large-4-serving (2026-11-03). Runs on a laptop, standard library only, no GPU, no weight download: it reads params.json and the safetensors *headers* (HTTP range requests, a few MB in all) from the Hugging Face repos at pinned revisions. python3 mistral_large4_kv.py # bytes per token, weights per GPU, pools, sessions python3 mistral_large4_kv.py --params params.json # bytes per token from a local params.json only python3 mistral_large4_kv.py --budget-gb 250 --context 100000 --sessions 32 Layer rules (vLLM PR #64534 @ bd4fa2633e, vllm/models/mistral/common/layer_spec.py and vllm/transformers_utils/configs/mistral.py): a layer owns a latent KV row unless kv_sharing points it at an earlier layer; it owns an indexer row when dsa.sharing says "full". NoPE layers keep the same 576-wide row. Row sizes: fp8_ds_mla = 512 FP8 + 4 FP32 scales + 64 BF16 RoPE = 656 B; plain FP8 (ROCm, SGLang trtllm) = 576 B; BF16 = 1,152 B; FP8 indexer key = 128 FP8 + 1 FP32 scale = 132 B (FP8 in every layout). Weights per GPU: tensors split by tensor parallelism are divided by TP; the ones the PR builds as replicated (the latent down-projection, the indexer's query and key projections, the router, the Pixtral encoder, the drafter's target projection and Markov head) stay whole on every GPU. Pool per GPU: budget - weights per GPU, where budget is what the engine leaves for weights + KV at its memory setting. 250 GB fits the three capacities vLLM published for 8x/4x GB300 at gpu-memory-utilization 0.85 (2.38M FP8 TP8, 3.60M NVFP4 TP8, 1.97M NVFP4 TP4) within 0.7%. Pass --budget-gb for your own GPUs, or --hbm-gb/--util/--overhead-gb to build one. DCP divides every row by the DCP size (all of them are sharded); the result is an upper bound (vLLM reports 7.93x, not 8x, for FP8 TP8 -> TP8 DCP8). """ import argparse import json import re import struct import urllib.request REPOS = { "FP8": ("mistralai/Mistral-Large-4-1T-A52B", "af26e7869af601441d5cdf75a1272469ddc3d059", 54), "NVFP4": ("mistralai/Mistral-Large-4-1T-A52B-NVFP4", "bb6d00fe249b0e876f0cffc6b85014be02de3e68", 32), } ROW = {"fp8_ds_mla": 656, "fp8 (plain E4M3)": 576, "bf16": 1152} INDEXER_ROW = 132 REPLICATED = [r"attention\.wkv_a_with_mqa", r"attention\.kv_a_norm", r"indexer\.", r"\.gate\.weight$", r"^vision_encoder", r"^vision_language_adapter", r"^patch_merger", r"^pre_mm_projector_norm", r"target_projection", r"joint_proj", r"autoregressive_head\.(embedding|output)", r"_norm\.", r"^norm\.", r"ssmax", r"lerope", r"mask_embedding"] PUBLISHED = {("FP8", 8): 2.38e6, ("NVFP4", 8): 3.60e6, ("NVFP4", 4): 1.97e6} # vLLM blog, 8x/4x GB300, 0.85 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 layer_map(p): n = p["n_layers"] pat = p["nope"].split(",") nope = [pat[i % len(pat)] == "nope" for i in range(n)] src = [int(x) for x in p["kv_sharing"]["source_layers_str"].split(",")] idx = p["dsa"]["sharing"].split(",") return [{"layer": i, "nope": nope[i], "kv_owner": src[i] == i, "kv_source": src[i], "indexer_owner": idx[i] == "full", "dense": i < p["moe"]["first_k_dense_replace"]} for i in range(n)] def bytes_per_token(layers, row): kv = sum(row for l in layers if l["kv_owner"]) ix = sum(INDEXER_ROW for l in layers if l["indexer_owner"]) return kv, ix, kv + ix def weights_per_gpu(repo, rev, nshards, tp): sharded = replicated = 0 for i in range(1, nshards + 1): url = hf(repo, rev, f"consolidated-{i:05d}-of-{nshards:05d}.safetensors") n = struct.unpack(" layer {sorted({l['kv_source'] for l in layers if not l['kv_owner']})}") print(f"indexer owners {ix_owners}, reusing top-k {[l['layer'] for l in layers if not l['indexer_owner']]}") gqa = 2 * p["n_layers"] * p["n_kv_heads"] * p["head_dim"] * 2 print(f"\nGQA formula (2 x {p['n_layers']} x {p['n_kv_heads']} x {p['head_dim']} x 2 B): {gqa:,} B per token") for name, row in ROW.items(): kv, ix, tot = bytes_per_token(layers, row) print(f"{name:17s}: {owners} x {row} + {ix_owners} x {INDEXER_ROW} = {kv:,} + {ix:,} = {tot:,} B per token" f" ({tot / 1024:.2f} KiB; {tot * 2**20 / 2**30:.2f} GiB per 1,048,576 tokens)") n = len(layers) base = bytes_per_token(layers, 656)[2] no_kv_share = n * 656 + ix_owners * INDEXER_ROW no_ix_share = owners * 656 + n * INDEXER_ROW neither = n * 656 + n * INDEXER_ROW print(f"without KV sharing {no_kv_share:,} B, without top-k sharing {no_ix_share:,} B, " f"without either {neither:,} B; sharing saves {1 - base / neither:.1%}") print(f"GQA formula / fp8_ds_mla = {gqa / base:.1f}x") w = p["mtp"].get("ragged_attention", "2048").split(",")[0] draft = p["mtp"]["n_layers"] * int(w) * ROW["bf16"] print(f"DSpark draft window cache: {p['mtp']['n_layers']} x {w} x {ROW['bf16']} B = {draft / 1e6:.1f} MB per request") if args.params: return budget = args.hbm_gb * args.util - args.overhead_gb if args.hbm_gb else args.budget_gb print(f"\nweights per GPU (safetensors headers; sharded / TP + replicated); budget {budget:.1f} GB per GPU") print("| checkpoint | TP | weights/GPU | pool/GPU | tokens TP | vLLM, GB300 at 0.85 | tokens DCP=TP | " f"{args.context // 1000}k sessions TP | DCP |") print("|---|---|---|---|---|---|---|---|---|") pools = {} for ck, (repo, rev, nsh) in REPOS.items(): wpg, total, rep = weights_per_gpu(repo, rev, nsh, (4, 8, 16)) print(f"") for tp, wg in wpg.items(): pool = budget - wg / 1e9 if pool <= 0: print(f"| {ck} | {tp} | {wg / 1e9:.1f} GB ({wg / 2**30:.1f} GiB) | does not fit | - | - | - | - | - |") continue tok = pool * 1e9 / base pools[(ck, tp)] = tok pub = PUBLISHED.get((ck, tp)) pubs = f"{pub / 1e6:.2f}M ({tok / pub - 1:+.1%})" if pub else "-" print(f"| {ck} | {tp} | {wg / 1e9:.1f} GB ({wg / 2**30:.1f} GiB) | {pool:.1f} GB | {tok / 1e6:.2f}M | {pubs} | " f"{tok * tp / 1e6:.2f}M | {int(tok // args.context)} | {int(tok * tp // args.context)} |") need = args.sessions * args.context * base print(f"\n{args.sessions} sessions x {args.context:,} tokens x {base:,} B = {need / 1e9:.1f} GB of cache, " f"on every GPU under TP, 1/DCP of it under DCP") if pools.get(("FP8", 8)) and pools.get(("NVFP4", 8)): print(f"NVFP4 / FP8 tokens at TP8: {pools[('NVFP4', 8)] / pools[('FP8', 8)]:.2f}x (same {base:,} B rows)") if __name__ == "__main__": main()