"""Bytes per decode token for the three ways of running an MoE that does not fit in VRAM. Used for content/standalone/01-inference-engines/07-moe-expert-paging (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 repos at pinned revisions. python3 expert_paging.py # all four checkpoints, then the arithmetic on SGLang PR #42557's rows python3 expert_paging.py --model qwen3-30b-int4 --k 64 --link-gbps 25 python3 expert_paging.py --trace responses.jsonl --k 26 --k 40 --k 92 # your miss rate per K (LRU replay) Per checkpoint it prints: bytes per routed expert (summed from the headers, every MoE layer), the cost of one resident slot (per-expert bytes x MoE layers: what K multiplies), all routed experts, everything else (attention, embeddings, shared experts: stays on the GPU), the worst case per decode token (top_k x MoE layers x expert, every route a miss), the page-in a long prefill triggers (E - K experts per layer), the decode graph cap (K // top_k) and, for the models with plain GQA layers, how many KV tokens one slot costs. Paged bytes follow SGLang v0.5.23 (297e54f, srt/layers/moe/paged_experts/formats.py): GPTQ's zero points are not paged (the Marlin MoE kernel never reads them) and g_idx is empty without act order, so a GPTQ slot holds qweight and scales. gpt-oss's MXFP4 experts are stored stacked (one tensor per layer for all 32 experts) and Marlin pads them at load, so its GPU slot is somewhat larger than the checkpoint bytes printed here. Link-bound ceilings only: time = bytes / link bandwidth, compute and overlap ignored, so every tok/s printed is an upper bound and every "at most N loads" is an upper bound on page-ins. PCIe rates are the theoretical per-direction rates (GT/s x lanes x 128/130 / 8); the script also derives the effective rate the PR's own --cpu-offload-gb rows imply. SGLang's --cpu-offload-gb is in GiB (offloader.py: cpu_offload_gb * 1024**3). """ import argparse import array import base64 import json import re import struct import urllib.request MODELS = { # key: (repo, revision, label) "qwen3-30b-int4": ("Qwen/Qwen3-30B-A3B-GPTQ-Int4", "9b534e4318b7ebc3c961a839f13eb18b1833f441", "GPTQ int4 g128"), "qwen3-30b-fp8": ("Qwen/Qwen3-30B-A3B-FP8", "d206ba732169f29bb77fbf80fc2c4b81d4d30782", "block FP8"), "gpt-oss-20b": ("openai/gpt-oss-20b", "6cee5e81ee83917806bbde320786a8fb61efebee", "MXFP4"), "qwen36-35b-fp8": ("Qwen/Qwen3.6-35B-A3B-FP8", "95a723d08a9490559dae23d0cff1d9466213d989", "block FP8"), } LINKS = {"PCIe 4.0 x8": 16 * 8 * 128 / 130 / 8, "PCIe 4.0 x16": 16 * 16 * 128 / 130 / 8, "PCIe 5.0 x16": 32 * 16 * 128 / 130 / 8} # GB/s, one direction GIB = 2**30 UNPAGED = re.compile(r"\.(qzeros|g_idx)$") # GPTQ on Marlin: zero points unpaged, g_idx empty (no act order) 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 headers(repo, rev): sib = json.loads(fetch(f"https://huggingface.co/api/models/{repo}/revision/{rev}"))["siblings"] for name in sorted(s["rfilename"] for s in sib): if name.endswith(".safetensors") and "/" not in name: # skips gpt-oss's original/ and metal/ url = hf(repo, rev, name) n = struct.unpack(" {worst / B * 1e3:.1f} ms on {link} ({B / worst:.1f} tok/s ceiling)") if m["kv"]: note = " (full-attention layers; sliding layers hold 128 tokens)" if m["key"] == "gpt-oss-20b" else "" print(f"KV cache {m['kv']:,} B per token, BF16{note}: one slot = {m['slot'] / m['kv']:,.0f} KV tokens") print(f"| K | resident | graph cap K//top_k | random-routing misses/token | GB/token | ceiling on {link} | " f"long-prefill page-in | at {link} |") print("|---|---|---|---|---|---|---|---|") for k in ks: if not m["top_k"] <= k <= m["E"]: continue miss = routes * (1 - k / m["E"]) # what uniform, memoryless routing would cost: the no-locality baseline gb = miss * m["expert"] pre = (m["E"] - k) * m["moe_layers"] * m["expert"] ceil = f"{B / gb:.0f} tok/s" if gb else "no paging" print(f"| {k} | {m['slot'] * k / 1e9:.1f} GB | {k // m['top_k']} | {miss:.0f} of {routes} | {gb / 1e9:.2f} | " f"{ceil} | {pre / 1e9:.1f} GB | {pre / B * 1e3:.0f} ms |") def pr_rows(ms): q4, q8 = ms.get("qwen3-30b-int4"), ms.get("qwen3-30b-fp8") if not (q4 and q8): return print("\n## SGLang PR #42557's rows, as link arithmetic (author's numbers: RTX 5070 Ti 16 GB on PCIe 5.0 x16, " "RTX 4070 Laptop 8 GB on PCIe 4.0 x8; ShareGPT, 256 output tokens, bs 1, ITL p50)") print("--cpu-offload-gb streams every offloaded byte every step: effective rate = offloaded bytes / ITL") eff = {} for gib, itl, link in ((3, 60.1, "PCIe 5.0 x16"), (18, 341, "PCIe 5.0 x16"), (10, 833, "PCIe 4.0 x8")): r = gib * GIB / (itl / 1e3) / 1e9 eff.setdefault(link, []).append(r) print(f" {gib:>2} GiB / {itl} ms = {r:.1f} GB/s, {r / LINKS[link]:.0%} of {link}'s {LINKS[link]:.1f} GB/s") rate = {link: max(v) for link, v in eff.items()} print("Paging: at most ITL x rate / expert bytes page-ins per token (all of the ITL spent copying), " "against what routing with no locality would need") for m, k, itl, link in ((q4, 92, 4.8, "PCIe 5.0 x16"), (q8, 40, 10.5, "PCIe 5.0 x16"), (q4, 26, 28.2, "PCIe 4.0 x8")): routes = m["top_k"] * m["moe_layers"] cap = itl / 1e3 * rate[link] * 1e9 / m["expert"] rnd = routes * (1 - k / m["E"]) print(f" {m['key']} K={k}: {itl} ms x {rate[link]:.1f} GB/s / {m['expert'] / 1e6:.2f} MB = at most {cap:.0f} " f"page-ins of {routes} routes ({min(cap / routes, 1):.0%}); no locality: {rnd:.0f} ({rnd / routes:.0%}), " f"{rnd * m['expert'] / (rate[link] * 1e9) * 1e3:.1f} ms of copies") g = ms.get("gpt-oss-20b") if g: itl = 1000 / 107.7 # PR #45787: 107.7 output tok/s at bs 1, K=16 (includes prefill time: ITL is shorter) routes = g["top_k"] * g["moe_layers"] cap = itl / 1e3 * rate["PCIe 5.0 x16"] * 1e9 / g["expert"] print(f" gpt-oss-20b K=16 (PR #45787, 107.7 tok/s -> {itl:.1f} ms per token): at most {cap:.0f} page-ins of " f"{routes} ({cap / routes:.0%}); no locality: {routes * (1 - 16 / g['E']):.0f} (50%)") print("vLLM v0.33.0 UVA (--offload-backend uva --cpu-offload-gb 16 --cpu-offload-params experts): the GPU reads " "each routed offloaded expert over the link every step, nothing cached") off = 16 * GIB / q8["experts"] reads = q8["top_k"] * q8["moe_layers"] * off gb = reads * q8["expert"] link = "PCIe 4.0 x16" print(f" qwen3-30b-fp8, 16 GiB of {q8['experts'] / GIB:.1f} GiB offloaded ({off:.0%}, the first " f"{16 * GIB / (q8['experts'] / q8['moe_layers']):.1f} layers): {reads:.0f} expert reads x " f"{q8['expert'] / 1e6:.2f} MB = {gb / 1e9:.2f} GB per token -> ceiling {LINKS[link] * 1e9 / gb:.1f} tok/s " f"on {link}; vLLM PR #62054 measured 20.7 tok/s at bs 1 (RTX 4090)") print("SGLang --cpu-offload-gb ceiling (offloaded GiB / link), same links") for gib, link in ((3, "PCIe 5.0 x16"), (18, "PCIe 5.0 x16"), (10, "PCIe 4.0 x8")): print(f" {gib} GiB on {link}: {LINKS[link] * 1e9 / (gib * GIB):.1f} tok/s") print("Bytes over the link per decode token, qwen3-30b-fp8 on the 16 GB card (figure 1)") routes = q8["top_k"] * q8["moe_layers"] print(f" SGLang --cpu-offload-gb 18: {18 * GIB / 1e9:.2f} GB (every offloaded byte)") off = 18 * GIB / q8["experts"] print(f" UVA reads with the same 18 GiB of experts on the host: {routes * off:.0f} reads, " f"{routes * off * q8['expert'] / 1e9:.2f} GB") print(f" Paging K=40, no locality: {routes * (1 - 40 / 128):.0f} page-ins, " f"{routes * (1 - 40 / 128) * q8['expert'] / 1e9:.2f} GB") print(f" Paging K=40, bound from the measured 10.5 ms ITL: <= {10.5e-3 * rate['PCIe 5.0 x16']:.2f} GB") q8_0 = q8["weights"] * 8.5 / 8 # GGUF Q8_0: 32 int8 weights + one FP16 scale = 8.5 bits per weight print(f" llama.cpp --n-cpu-moe 27 (Q8_0): activations only over the link (kilobytes per layer); the CPU reads " f"27 x {q8['top_k']} x {q8_0 / 1e6:.2f} MB = {27 * q8['top_k'] * q8_0 / 1e9:.2f} GB from host DRAM per token") def replay(path, layers, top_k, E, ks): """LRU replay of routed-expert traces, as SGLang's LRUPolicy (residency.py): slots start with experts 0..K-1, a step's resident experts are touched first, each miss takes the least recently used slot. Input: JSON lines, each a /generate response (or its meta_info) from a server started with --enable-return-routed-experts, requests sent with "return_routed_experts": true. meta_info.routed_experts is base64 int32, shape (tokens, layers, top_k). Requests are replayed one after the other (bs 1), slots carried over; prompt rows warm the slots and are not counted.""" reqs = [] for line in open(path): if line.strip(): obj = json.loads(line) meta = obj.get("meta_info", obj) ids = array.array("i", base64.b64decode(meta["routed_experts"])) reqs.append((ids, len(ids) // (layers * top_k), meta.get("prompt_tokens", 0))) print(f"# LRU replay of {path}: {len(reqs)} requests, {layers} layers x {E} experts, top-{top_k}") print("| K | decode tokens | misses per token | miss rate | no reuse (1 - K/E) |\n|---|---|---|---|---|") for k in ks: if not top_k <= k <= E: # SGLang refuses K < top_k at startup; K > E pages nothing raise SystemExit(f"--k {k}: K must be between top-k ({top_k}) and the expert count ({E})") slots = [dict.fromkeys(range(k)) for _ in range(layers)] # insertion order = LRU order misses = tokens = 0 for ids, n, prompt in reqs: for t in range(n): for li, lru in enumerate(slots): row = set(ids[(t * layers + li) * top_k:(t * layers + li + 1) * top_k]) for e in sorted(row, key=lambda e: e not in lru): # hits first, then misses if e not in lru: misses += t >= prompt del lru[next(iter(lru))] lru.pop(e, None) lru[e] = None tokens += t >= prompt print(f"| {k} | {tokens} | {misses / max(tokens, 1):.1f} of {layers * top_k} | " f"{misses / max(tokens * layers * top_k, 1):.0%} | {1 - k / E:.0%} |") def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", choices=MODELS, action="append", help="default: all") ap.add_argument("--k", type=int, action="append", help="resident experts per layer (default: a sweep)") ap.add_argument("--link", choices=LINKS, default="PCIe 5.0 x16") ap.add_argument("--link-gbps", type=float, help="your measured host-to-device GB/s instead of --link") ap.add_argument("--trace", help="JSON lines of /generate responses with routed experts: LRU replay, no download") ap.add_argument("--layers", type=int, default=48, help="--trace: MoE layers (default: Qwen3-30B-A3B's 48)") ap.add_argument("--top-k", type=int, default=8, help="--trace: experts per token (default 8)") ap.add_argument("--experts", type=int, default=128, help="--trace: routed experts per layer (default 128)") args = ap.parse_args() if args.trace: return replay(args.trace, args.layers, args.top_k, args.experts, args.k or [26, 40, 64, 92]) if args.link_gbps: LINKS["measured"] = args.link_gbps args.link = "measured" print("Links, theoretical GB/s per direction: " + ", ".join(f"{k} {v:.2f}" for k, v in LINKS.items())) ms = {} for key in args.model or MODELS: m = ms[key] = measure(key) sweep = args.k or sorted({m["top_k"], m["E"] // 8, m["E"] // 4, m["E"] * 5 // 16, m["E"] // 2, m["E"] * 23 // 32, m["E"]} | ({26, 40, 92} if m["E"] == 128 else set())) report(m, sweep, args.link) pr_rows(ms) if __name__ == "__main__": main()