The GGUF header already knows whether the model fits: a reader that answers in 300 ms

Marcus

Professional Premium
Professional Premium
Download
Two files with the same architecture name, qwen35, disagree about the number a memory plan depends on. In the 9B file, attention.head_count_kv is an array of 32 entries, most of them zero and eight of them four. In the 27B file it is the single number 4, written next to a block count of 65. Read that scalar as per-block and the usual formula gives 260 KiB of cache per token, which at 32k is 8.1 GiB. The tensor table in the same file says 68 KiB, and 2.1 GiB. The second number is the one the card agreed with.

The formula is not wrong. It gets applied to the wrong set of blocks. K and V are appended per layer, so the cost is (KV heads) x (key width + value width) x (bytes per element) for every block that ships an attn_k and an attn_v tensor. Hybrid models keep attention in a minority of layers and give the rest a fixed-size recurrent state that does not grow with the window. Qwen3.5 9B keeps 8 of 32. The 27B keeps 17 of 65 and still writes 4 as its KV head count. The metadata is a summary written by whoever converted the file. The tensor names are the inventory, and they answer before a byte of weights is loaded.

That is the same habit as scanning a GGUF before you load it: read the manifest, do not trust the label. The GGUF specification defines the header as a list of key and value pairs followed by one entry per tensor, with a type code and a byte offset. A script that walks it needs sixty lines and no dependencies, and it answers in a third of a second on a 15.7 GB file because it stops at the first tensor data offset.

So I wrote the one I wanted when planning the 32k measurement. It prints four things: weight bytes summed from the tensor table, the count of blocks that actually write a cache, the KV bytes per token for the cache type you choose, and resident VRAM per window against a budget.

Code:
$ python gguf_vram.py qwen3.5-9b.gguf --ctx 4096,32768,65536 --reserve 280
arch      qwen35  32 blocks  16 heads  head_dim 256  kv heads [0, 4]
weights   6.13 GiB in 883 tensors
cache     8 of 32 blocks write KV (24 state-space)
kv/token  32.0 KiB (f16)
quants    Q4_K 231t 3.82G, Q6_K 27t 1.46G, F16 166t 0.85G, F32 459t 0.01G
ctx    4096 | kv    128.0 | total   6685.5 MiB | fits
ctx   32768 | kv   1024.0 | total   7581.5 MiB | fits
ctx   65536 | kv   2048.0 | total   8605.5 MiB | fits

The quant census is worth its own line. A file sold as Q4_K_M is 231 Q4_K tensors, 27 Q6_K tensors and 166 F16 tensors. That 0.85 GiB of F16 in a 6.13 GiB file is the embedding and the norms, and it does not shrink when you pick a smaller quant of the same model. If your budget is failing by 800 MiB, this is where it went.

Then the measurements. Resident means the median of five nvidia-smi samples taken after the model settled, minus the reading before it loaded, on a 4090 with 24,564 MiB and Ollama 0.40.19. The script's --check mode reads those runs back and prints the residual:

Code:
$ python ctx_steady_today.py qwen3:14b 8192,16384,32768
qwen3:14b ctx   8192 | resident 10396 MiB
qwen3:14b ctx  16384 | resident 11692 MiB
qwen3:14b ctx  32768 | resident 14284 MiB

$ python gguf_vram.py qwen3-14b.gguf --ctx 8192,16384,32768 --reserve 280 \
      --check state/bench_ctx_steady_2026-12-05.json --tag qwen3:14b
check qwen3:14b ctx   8192: measured 10396, predicted 10401, error -5 MiB
check qwen3:14b ctx  16384: measured 11692, predicted 11681, error +11 MiB
check qwen3:14b ctx  32768: measured 14284, predicted 14241, error +43 MiB

Three windows, 48 MiB of error at the widest, on a model I had never measured before. The dense case is the easy one: 40 blocks, all of them attention, 160 KiB per token, and the card reproduced 162.

Code:
model                file      blocks  kv blocks  KiB/tok    ctx    measured  predicted
qwen3:14b Q4_K_M     8.63 GiB      40         40      160  32,768    14,284     14,241
qwen3.5:9b Q4_K_M    6.13 GiB      32          8       32  32,768     7,588      7,582
qwen3.5:9b Q4_K_M    6.13 GiB      32          8       32  65,536     8,676      8,606
qwen38liber IQ4_XS  14.62 GiB      65         17       68  32,768    17,968     17,424

growth between the two widest windows, which is what the cache term predicts
model                window      measured   predicted   error
qwen3:14b            8k -> 32k   3,888 MiB   3,840 MiB   +1.2%
qwen3.5:9b           4k -> 64k   2,137 MiB   1,920 MiB  -10.1%
qwen38liber          8k -> 32k   1,410 MiB   1,632 MiB  +15.7%

The two hybrid files miss in opposite directions, so I quote them as a band of plus or minus 15 percent rather than a number. I did not chase which blocks account for the gap on the 27B, and until I do, the honest reading is that the planner bounds the cache and does not nail it on state-space architectures. On dense models it nails it.

The other thing the same header answers: what a quantised cache buys. With --kv q8_0 the 14B at 32k drops from 160 to 85 KiB per token. I restarted Ollama with OLLAMA_KV_CACHE_TYPE=q8_0 and measured the same window again, which is the only reason I am willing to quote it:

Code:
qwen3:14b, 32,768 tokens, f16 weights
kv f16    14,284 MiB resident
kv q8_0   11,890 MiB resident    (-2,394 MiB measured, -2,400 MiB predicted)

Two point three gigabytes recovered by changing one setting. On llama.cpp's server that setting is --cache-type-k and --cache-type-v, and it needs flash attention enabled; the server documentation lists the accepted types. I did not measure the quality difference between an f16 and a q8_0 cache, and I would not ship it on a model doing long-context retrieval without that test. The KV cache arithmetic in Raschka's gallery is the reference I used to check the per-layer form.

What the script does not do, in the order those gaps will bite you. It counts every expert tensor in the weight total, so a MoE file with CPU expert offload will read high. --ngl takes a fraction of the layers, not a layer list, so a two-card split is outside it. It predicts allocation, not speed: prompt processing depends on the compute buffer and on how much of the model runs on the CPU, so a file that fits can still prefill slowly. And the reserve term is per machine. 280 MiB matched this 4090 under Ollama; on Windows with a browser open it will not. Fit it once with --check against a run you measured yourself.

The script is too long for one post body, so it follows whole in the next post. The attached file, gguf-vram-planner-2026-12-05.md, carries the same source plus the raw output of every run quoted here. One file, standard library, no model download required. The link below asks for an account first.

View attachment gguf-vram-planner-2026-12-05.md

The one number I would want from you: if your window were 16k instead of 32k, what would you spend the recovered 2 GiB on, a wider context, a bigger quant, or a second model kept resident?
 
Last edited:
The whole script, as promised. Save it as gguf_vram.py and run it against any .gguf file, including the blobs under .ollama/models/blobs.

Code:
#!/usr/bin/env python3
"""gguf_vram.py - what a GGUF will cost on your card, read from the file header alone.

Reads metadata and the tensor table, so it answers in under a second on a model you have
not fully downloaded. Reports weight bytes per quant type, which blocks actually own a
growing KV cache, KV bytes per token, and resident VRAM per context window.

  python gguf_vram.py MODEL.gguf --ctx 8192,32768,131072 --vram 24564 --reserve 280
  python gguf_vram.py MODEL.gguf --kv q8_0 --md
  python gguf_vram.py MODEL.gguf --check state/bench_ctx_steady.json --tag qwen3:14b
"""
from __future__ import annotations
import argparse, json, math, struct, sys
from pathlib import Path

# ggml type -> (name, elements per block, bytes per block)
GGML = {0: ("F32", 1, 4), 1: ("F16", 1, 2), 2: ("Q4_0", 32, 18), 3: ("Q4_1", 32, 20),
        6: ("Q5_0", 32, 22), 7: ("Q5_1", 32, 24), 8: ("Q8_0", 32, 34), 9: ("Q8_1", 32, 36),
        10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110), 12: ("Q4_K", 256, 144),
        13: ("Q5_K", 256, 176), 14: ("Q6_K", 256, 210), 15: ("Q8_K", 256, 292),
        16: ("IQ2_XXS", 256, 66), 17: ("IQ2_XS", 256, 74), 18: ("IQ3_XXS", 256, 98),
        19: ("IQ1_S", 256, 50), 20: ("IQ4_NL", 32, 18), 21: ("IQ3_S", 256, 110),
        22: ("IQ2_S", 256, 82), 23: ("IQ4_XS", 256, 136), 24: ("I8", 1, 1),
        25: ("I16", 1, 2), 26: ("I32", 1, 4), 27: ("I64", 1, 8), 28: ("F64", 1, 8),
        29: ("IQ1_M", 256, 56), 30: ("BF16", 1, 2), 34: ("TQ1_0", 256, 54),
        35: ("TQ2_0", 256, 66), 36: ("MXFP4", 32, 17)}
# bytes per KV element, per cache type llama.cpp accepts
KV_TYPE = {"f16": 2.0, "bf16": 2.0, "q8_0": 34 / 32, "q5_1": 24 / 32, "q4_0": 18 / 32}

class Rd:
    def __init__(self, p: Path):
        self.f = open(p, "rb")

    def take(self, n: int) -> bytes:
        b = self.f.read(n)
        if len(b) != n:
            raise EOFError("truncated header")
        return b

    def u32(self) -> int: return struct.unpack("<I", self.take(4))[0]
    def u64(self) -> int: return struct.unpack("<Q", self.take(8))[0]
    def s(self) -> str: return self.take(self.u64()).decode("utf-8", "replace")

    def val(self, t: int):
        if t == 4: return self.u32()
        if t == 10: return self.u64()
        if t == 8: return self.s()
        if t == 9:
            et, n = self.u32(), self.u64()
            return [self.val(et) for _ in range(n)]
        fmt = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 5: "<i", 6: "<f", 11: "<q", 12: "<d"}.get(t)
        if t == 7: return self.take(1) != b"\x00"
        if not fmt: raise ValueError(f"metadata type {t}")
        return struct.unpack(fmt, self.take(struct.calcsize(fmt)))[0]

def parse(path: Path) -> dict:
    r = Rd(path)
    if r.take(4) != b"GGUF":
        raise SystemExit(f"{path}: not a GGUF file")
    version, n_tensors, n_kv = r.u32(), r.u64(), r.u64()
    meta = {r.s(): r.val(r.u32()) for _ in range(n_kv)}
    tensors = []
    for _ in range(n_tensors):
        name, nd = r.s(), r.u32()
        dims = [r.u64() for _ in range(nd)]
        ttype, off = r.u32(), r.u64()
        name_t, block, size = GGML.get(ttype, ("?", 1, 4))
        elems = math.prod(dims) if dims else 0
        tensors.append({"name": name, "type": name_t, "offset": off,
                        "elements": elems, "bytes": elems * size / block})
    return {"version": version, "meta": meta, "tensors": tensors}

def analyse(g: dict) -> dict:
    meta = g["meta"]
    arch = str(meta.get("general.architecture", "unknown"))

    def get(key, default=None):
        return meta.get(f"{arch}.{key}", meta.get(key, default))

    blocks = int(get("block_count", 0) or 0)
    n_head = int(get("attention.head_count", 0) or 0)
    embed = int(get("embedding_length", 0) or 0)
    k_len = int(get("attention.key_length") or (embed // n_head if n_head else 0))
    v_len = int(get("attention.value_length") or k_len)
    kv_meta = get("attention.head_count_kv")
    if isinstance(kv_meta, list):
        kv_heads = [int(x) for x in kv_meta]
    else:
        kv_heads = [int(kv_meta or n_head)] * max(blocks, 1)

    # the tensor table is the authority on which blocks append to a cache
    attn, ssm = set(), set()
    for t in g["tensors"]:
        p = t["name"].split(".")
        if len(p) < 3 or p[0] != "blk":
            continue
        i, kind = int(p[1]), p[2]
        if kind in ("attn_k", "attn_v", "attn_k_norm", "attn_v_norm"):
            attn.add(i)
        elif kind.startswith(("ssm", "linear")):
            ssm.add(i)
    cache = sorted(attn) if attn else list(range(blocks))

    by_type: dict = {}
    for t in g["tensors"]:
        d = by_type.setdefault(t["type"], {"tensors": 0, "bytes": 0.0})
        d["tensors"] += 1
        d["bytes"] += t["bytes"]

    return {"arch": arch, "blocks": blocks, "n_head": n_head, "embed": embed,
            "head_dim": k_len, "v_dim": v_len, "kv_meta": kv_meta, "kv_heads": kv_heads,
            "cache_blocks": cache, "ssm_blocks": sorted(ssm), "by_type": by_type,
            "weights": sum(t["bytes"] for t in g["tensors"]),
            "experts": get("expert_count"), "train_ctx": get("context_length")}

def kv_per_token(a: dict, kv_type: str = "f16") -> float:
    el = KV_TYPE[kv_type]
    return sum((a["kv_heads"][i] if i < len(a["kv_heads"]) else a["kv_heads"][-1])
               * (a["head_dim"] + a["v_dim"]) * el for i in a["cache_blocks"])

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("model")
    ap.add_argument("--ctx", default="4096,8192,32768,131072")
    ap.add_argument("--vram", type=int, default=24564, help="card size, MiB")
    ap.add_argument("--offload", type=int, default=0, help="budget to use, MiB (default: card size)")
    ap.add_argument("--kv", default="f16", choices=sorted(KV_TYPE))
    ap.add_argument("--ngl", type=float, default=1.0, help="fraction of layers on the GPU")
    ap.add_argument("--reserve", type=float, default=700.0, help="compute buffer + driver, MiB")
    ap.add_argument("--md", action="store_true")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--check", default="", help="bench json with measured resident MiB")
    ap.add_argument("--tag", default="", help="model tag inside the bench file")
    a = ap.parse_args()

    g = parse(Path(a.model))
    info = analyse(g)
    per_tok = kv_per_token(info, a.kv)
    budget = a.offload or a.vram
    gpu_w = info["weights"] * a.ngl / 1024 / 1024

    rows = []
    for ctx in [int(x) for x in a.ctx.split(",") if x.strip()]:
        kv = per_tok * ctx / 1024 / 1024
        rows.append({"ctx": ctx, "kv": round(kv, 1), "total": round(gpu_w + kv + a.reserve, 1),
                     "fits": gpu_w + kv + a.reserve <= budget})
    room = max(0.0, (budget - a.reserve - gpu_w) * 1024 * 1024 / per_tok)

    if a.json:
        print(json.dumps({"model": a.model, "info": info, "kv_bytes_per_token": per_tok,
                          "weights_mib": round(gpu_w, 1), "rows": rows,
                          "max_ctx": int(room)}, indent=1, default=str))
        return 0

    print(f"file      {a.model}")
    print(f"arch      {info['arch']}  {info['blocks']} blocks  {info['n_head']} heads  "
          f"head_dim {info['head_dim']}  kv heads {sorted(set(info['kv_heads']))}")
    print(f"weights   {info['weights']/1024**3:.2f} GiB in {len(g['tensors'])} tensors")
    print(f"cache     {len(info['cache_blocks'])} of {info['blocks']} blocks write KV "
          f"({len(info['ssm_blocks'])} state-space)")
    print(f"kv/token  {per_tok/1024:.1f} KiB ({a.kv})")
    top = sorted(info["by_type"].items(), key=lambda x: -x[1]["bytes"])[:4]
    print("quants    " + ", ".join(f"{k} {v['tensors']}t {v['bytes']/1024**3:.2f}G" for k, v in top))
    if a.md:
        print("\n| ctx | KV cache | resident | fits |\n|---:|---:|---:|:--|")
        for r in rows:
            print(f"| {r['ctx']:,} | {r['kv']:,.0f} MiB | {r['total']:,.0f} MiB | "
                  f"{'yes' if r['fits'] else 'no'} |")
        print(f"\nLargest window that fits: {int(room):,} tokens.")
    else:
        for r in rows:
            print(f"ctx {r['ctx']:>7} | kv {r['kv']:>8.1f} | total {r['total']:>8.1f} MiB | "
                  f"{'fits' if r['fits'] else 'over'}")

    if a.check:
        bench = json.loads(Path(a.check).read_text(encoding="utf-8"))
        for tag, runs in bench.get("models", {}).items():
            if a.tag and tag != a.tag:
                continue
            base, errs = None, []
            for run in runs:
                measured, ctx = run.get("resident_mib"), run.get("num_ctx")
                if not measured or not ctx:
                    continue
                kv = per_tok * ctx / 1024 / 1024
                base = base if base is not None else measured - kv
                errs.append(measured - (base + kv))
                print(f"check {tag} ctx {ctx:>6}: measured {measured} MiB, predicted "
                      f"{base + kv:>7.1f} MiB, error {errs[-1]:+.1f} MiB")
            if errs:
                print(f"check {tag}: max residual {max(abs(e) for e in errs):.1f} MiB "
                      f"over {len(errs)} windows")
    return 0

if __name__ == "__main__":
    sys.exit(main())
 
Back
Top