quantuminfer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +96 -2
  3. package/bin/quantuminfer.js +61 -0
  4. package/c27/adapters.py +161 -0
  5. package/c27/harness27.py +349 -0
  6. package/data/input.txt +40000 -0
  7. package/data/wikitext/test.txt +7249 -0
  8. package/engine/API.txt +208 -0
  9. package/engine/PLUGINS.txt +4 -0
  10. package/engine/__init__.py +82 -0
  11. package/engine/adapter.py +505 -0
  12. package/engine/blocks.py +1180 -0
  13. package/engine/c12.py +324 -0
  14. package/engine/c12cu.py +1074 -0
  15. package/engine/ctx.py +87 -0
  16. package/engine/dev.py +11 -0
  17. package/engine/ds4.py +389 -0
  18. package/engine/kernels.py +833 -0
  19. package/engine/model.py +281 -0
  20. package/engine/record.py +140 -0
  21. package/engine/server.py +183 -0
  22. package/engine/spec.py +1030 -0
  23. package/engine/wcode.py +122 -0
  24. package/p27/SPEC.txt +66 -0
  25. package/p27/STATUS.txt +91 -0
  26. package/p27/bench_glm.py +354 -0
  27. package/p27/bench_multi.py +76 -0
  28. package/p27/mkfinal.py +98 -0
  29. package/p27/modal_comp.py +173 -0
  30. package/p27/modal_dl.py +63 -0
  31. package/p27/modal_p27.py +168 -0
  32. package/p27/modal_probe.py +49 -0
  33. package/p27/p27rules.py +29 -0
  34. package/p27/pblocks.py +1242 -0
  35. package/p27/pmodel.py +402 -0
  36. package/p27/pref.py +151 -0
  37. package/p27/prof_glm.py +34 -0
  38. package/p27/quant.py +850 -0
  39. package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
  40. package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
  41. package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
  42. package/p27/recipes/vllm_default_gb300.md +281 -0
  43. package/p27/recipes/vllm_glm53_h200.md +301 -0
  44. package/p27/run_window1.sh +21 -0
  45. package/p27/run_window2.sh +13 -0
  46. package/p27/sweep_glm.py +64 -0
  47. package/p27/t_align.py +42 -0
  48. package/p27/t_combine.py +28 -0
  49. package/p27/t_echo.py +31 -0
  50. package/p27/t_fp8dense.py +59 -0
  51. package/p27/t_fp8speed.py +48 -0
  52. package/p27/t_glm.py +340 -0
  53. package/p27/t_glu.py +30 -0
  54. package/p27/t_gsuf.py +23 -0
  55. package/p27/t_jac.py +22 -0
  56. package/p27/t_moebm.py +30 -0
  57. package/p27/t_nccl.py +36 -0
  58. package/p27/t_online_jac.py +31 -0
  59. package/p27/t_probe.py +4 -0
  60. package/p27/t_router.py +28 -0
  61. package/p27/t_symm.py +50 -0
  62. package/p27/t_tiny.py +116 -0
  63. package/package.json +10 -4
  64. package/results/ANALYSIS.md +156 -0
  65. package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
  66. package/results/glm53_b300x8_opt4.json +624 -0
  67. package/results/res_glm_c32w3_b300.json +638 -0
  68. package/results/res_glm_final_c32_b300.json +652 -0
  69. package/results/res_glm_multi_final_b300.json +1821 -0
  70. package/results/res_glm_online_b300.json +638 -0
  71. package/results/res_glm_online_fixed_b300.json +638 -0
  72. package/results/res_glm_opt4_b300.json +624 -0
  73. package/results/res_glm_text_plain_batch_b300.json +5792 -0
  74. package/results/res_glm_text_w1_b300.json +1635 -0
  75. package/results/res_glm_text_w3_b300.json +1639 -0
  76. package/results/res_sweep_echo_b300.json +129 -0
  77. package/results/res_sweep_final_b300.json +153 -0
  78. package/results/res_sweep_glm_b300.json +153 -0
  79. package/results/res_techo.json +29 -0
  80. package/results/res_tgsuf.json +21 -0
  81. package/results/res_tjac.json +17 -0
  82. package/results/res_tonline_jac.json +13 -0
@@ -0,0 +1,122 @@
1
+ """Lossless weight coding as a core feature (lanes R1 / O1 / O3): C12 = exact 12.06-bit code of bf16 weights read
2
+ directly by a tensor-core GEMM (c12cu.py, copied from exp_o3_latency). Every GEMM output is an fp32 accumulation of
3
+ exact products with the TRUE bf16 weights (outliers corrected exactly in the epilogue), so it is lossless up to
4
+ accumulation order, like any change of GEMM kernel. Model-agnostic: it walks every block's .weights() (attribute name
5
+ -> tensor) and the LM head, and swaps each eligible matrix (N % 8 == 0, K % 512 == 0) for a C12Weight. Rows > 64
6
+ (prefill) decode to bf16 on the fly and use cuBLAS."""
7
+ import torch
8
+
9
+ import blocks as Bk
10
+
11
+
12
+ class C12Weight:
13
+ def __init__(self, w):
14
+ import c12cu
15
+ self.F = c12cu.encode_frag(w)
16
+ self.shape = tuple(w.shape)
17
+ self.N, self.K = w.shape
18
+
19
+ def lin(self, x):
20
+ import c12cu
21
+ return c12cu.lin(x, self.F)
22
+
23
+ def nbytes(self):
24
+ import c12cu
25
+ return c12cu.nbytes(self.F)
26
+
27
+ def decode(self):
28
+ import c12cu
29
+ return c12cu.decode_frag(self.F)
30
+
31
+ def decode_rows(self, r0, r1, block=8192):
32
+ """exact bf16 rows [r0, r1) (row-block decode through a sliced code, bounded temporaries)."""
33
+ import c12cu
34
+ out = []
35
+ F = self.F
36
+ K = self.K
37
+ for a in range(r0, r1, block):
38
+ b = min(a + block, r1)
39
+ assert a % 8 == 0 and (b % 8 == 0 or b == self.N)
40
+ nb0, nb1 = a // 8, b // 8
41
+ per = (K // 64) * 32
42
+ sub = dict(N=b - a, K=K, frag=True,
43
+ lof=F["lof"].view(-1, per * 16)[nb0:nb1].reshape(-1),
44
+ cof=F["cof"].view(-1, per * 8)[nb0:nb1].reshape(-1),
45
+ basef=F["basef"].view(-1, (K // 128) * 8)[nb0:nb1].reshape(-1),
46
+ rcnt=F["rcnt"][a:b])
47
+ o0 = int(F["roff"][a]) if a < self.N else 0
48
+ n_o = int(sub["rcnt"].sum())
49
+ sub["ok"], sub["ob"] = F["ok"][o0:o0 + n_o], F["ob"][o0:o0 + n_o]
50
+ out.append(c12cu.decode_frag(sub))
51
+ return torch.cat(out, 0)
52
+
53
+
54
+ def eligible(w):
55
+ return isinstance(w, torch.Tensor) and w.dim() == 2 and w.shape[0] % 8 == 0 and w.shape[1] % 512 == 0
56
+
57
+
58
+ def convert(model, head=True, verify=True, tune_M=(1,)):
59
+ """In place. Returns byte accounting. verify: bit-exact decode check of every matrix."""
60
+ import c12cu
61
+ if torch.cuda.get_device_capability() != (9, 0):
62
+ raise NotImplementedError("C12 kernels are built for sm_90a (H100); this GPU: "
63
+ f"{torch.cuda.get_device_name()}")
64
+ c12cu.ext()
65
+ before = after = 0
66
+ mats = {}
67
+ objs = [L.mix for L in model.layers] + [L.mlp for L in model.layers]
68
+ if model.mtp is not None:
69
+ objs += [L.mix for L in model.mtp.layers] + [L.mlp for L in model.mtp.layers]
70
+ bad = 0
71
+ kchk = {}
72
+ import gc
73
+ log = []
74
+ for i, o in enumerate(objs):
75
+ for name, w in list(o.weights().items()):
76
+ if not eligible(w):
77
+ continue
78
+ c = C12Weight(w)
79
+ if verify and not torch.equal(c.decode_rows(0, c.N).view(torch.int16), w.view(torch.int16)):
80
+ bad += 1
81
+ continue
82
+ before += w.numel() * 2
83
+ after += c.nbytes()
84
+ key = f"{c.N}x{c.K}"
85
+ if key not in mats: # kernel check once per shape: C12 GEMM vs cuBLAS on the true bf16 weights
86
+ xx = torch.randn(4, c.K, device=w.device, dtype=torch.bfloat16)
87
+ ref = torch.nn.functional.linear(xx, w).float()
88
+ got = c.lin(xx).float()
89
+ kchk[key] = float((got - ref).abs().max() / ref.abs().max())
90
+ setattr(o, name, c)
91
+ mats.setdefault(key, []).append(c.F)
92
+ del w, c
93
+ if i % 16 == 0:
94
+ gc.collect()
95
+ torch.cuda.empty_cache()
96
+ log.append((i, round(torch.cuda.memory_allocated() / 1e9, 2)))
97
+ print("wcode", i, len(objs), log[-1], flush=True)
98
+ gc.collect()
99
+ torch.cuda.empty_cache()
100
+ if head and eligible(model.head) and model.head is not model.embed:
101
+ c = C12Weight(model.head)
102
+ # head verify in row blocks (a full decode of a 248k x 5120 matrix needs ~10 GB of int32 temporaries)
103
+ ok = True
104
+ if verify:
105
+ hb = 16384
106
+ for r0 in range(0, c.N, hb):
107
+ r1 = min(r0 + hb, c.N)
108
+ ok &= torch.equal(c.decode_rows(r0, r1).view(torch.int16), model.head[r0:r1].view(torch.int16))
109
+ if ok:
110
+ before += model.head.numel() * 2
111
+ after += c.nbytes()
112
+ model.head = c
113
+ mats.setdefault(f"{c.N}x{c.K}", []).append(c.F)
114
+ torch.cuda.empty_cache()
115
+ tune = c12cu.autotune(mats, list(tune_M)) if tune_M else {}
116
+ gc.collect()
117
+ torch.cuda.synchronize()
118
+ torch.cuda.empty_cache()
119
+ log.append(("after_tune", round(torch.cuda.memory_allocated() / 1e9, 2)))
120
+ print("wcode after autotune", log[-1], flush=True)
121
+ return {"mem_log": log, "bytes_bf16": before, "bytes_c12": after, "ratio": after / max(before, 1), "verify_fail": bad, "kernel_relerr": kchk,
122
+ "tune": {k: v for k, v in tune.items() if not k.endswith("WRONG")}}
package/p27/SPEC.txt ADDED
@@ -0,0 +1,66 @@
1
+ LANE P27 - parallelism, MoE / MLA / KDA / MXFP4 blocks, scale ladder. Written 09:15 UTC 2026-11-28, before any
2
+ measurement. Definition: gpu/BENCH27_SPEC.md (incl. "Model set replaced with current models", ~09:05) + BENCH_SPEC.md
3
+ schema. Supersedes the Qwen3.5-122B / 397B / Kimi-K2 ladder of the original P27 brief.
4
+
5
+ MODELS AND HARDWARE (same hardware for every engine, recorded per result with torch.cuda.get_device_name)
6
+ headline moonshotai/Kimi-K3.1-Pro rev 80aff651e9b2d2f5b9f70f92a0a7a77054418e16 (1.56 TB, remote config only)
7
+ 8xB300 in one Modal container if offered; else 2 clustered Modal containers of 8xB200 (16 GPUs).
8
+ 8xB200 (1.54 TB HBM) and 8xH200 (1.13 TB) cannot hold the 1.56 TB checkpoint at all -> not options.
9
+ second MiniMaxAI/MiniMax-M3.1-Flash rev ce7f4df8 (252 GB) on 4 or 8 x H100 - only if the headline is done.
10
+ Weights Modal volume qllm-big-vol (v2), HF_HOME=/vol/hf, pinned revisions (modal_dl.py). Text-only: every engine
11
+ may skip the vision tower and says whether it did.
12
+
13
+ WHAT "EXACT" MEANS FOR KIMI-K3.1-PRO
14
+ - Reference computation = the K3 reference modeling (moonshotai/Kimi-K3 rev 9f62e4e9 modeling_kimi_linear.py, the
15
+ file tiny-random/kimi-k3.1-pro pins; K3.1-Pro itself ships no modeling code), on dequantised weights, in fp32.
16
+ - MXFP4 routed experts (compressed-tensors "mxfp4-pack-quantized", group 32, E8M0 uint8 scales): every value is
17
+ e2m1 x 2^(s-127), which is EXACTLY representable in bf16 and fp32. Our engine and the reference use the same
18
+ decoded values bit for bit; no activation quantisation anywhere (the config has input_activations: null).
19
+ - DSA (top-2048 indexer on the 24 MLA layers): the HF reference has no DSA operator and runs dense MLA; vLLM's
20
+ K3.1 build runs the indexer. For contexts <= 2048 tokens top-2048 selects every key, so DSA == dense MLA
21
+ exactly. Our engine follows the reference (dense MLA) at every length; cells with context > 2048 (TTFT 8k/32k,
22
+ long-context) are labelled "dense MLA (HF reference semantics)", and the competitor's DSA there is a different
23
+ (sparse) computation. If time allows an exact indexer path is added and certified separately.
24
+ - Certificate: every certified greedy stream is teacher-forced through the fp32 reference; a token more than 0.5
25
+ below the fp32 argmax is a failure. T=1: the 23-bit measurement record (gpu/engine/record.py) + same check.
26
+ At 2.8T the reference is layer-streamed: weights stay in their published packed form; each layer is
27
+ instantiated as the HF fp32 module (experts dequantised on demand, only those routed), run on all certified
28
+ sequences at once, freed. KDA recurrence in fp32 (fla naive recurrent form, no tf32). Exactly what was
29
+ certified (#streams, #positions) is listed in FINDINGS.txt.
30
+
31
+ ENGINE (one model-agnostic engine; nothing branches on a model name)
32
+ Blocks added (registered into the core registry gpu/engine/blocks.py REGISTRY from this directory until S27
33
+ exposes a plugin hook; declared from config.json by an adapter extension):
34
+ kda Kimi Delta Attention: per-channel decay, short convs on q/k/v, l2-norm q/k, fp32 state, gated
35
+ RMSNorm out; tree verify by per-path state walks (same mechanism as gdn), commit re-walk.
36
+ mla multi-head latent attention, absorbed form; KV cache = compressed latent (kv_lora_rank) + rope part
37
+ per token; optional output gate; NoPE / RoPE / YaRN.
38
+ moe routed + shared experts, sigmoid/softmax router, correction bias, group-limited top-k, renormalise,
39
+ routed scaling, optional latent projection (down -> experts -> norm -> up); capacity-free exact
40
+ dispatch (every routed (token, expert) pair is computed, no drops).
41
+ attn_res block attention-residual wiring (Kimi AttnRes) as a generic residual scheme.
42
+ quant weight codecs: mxfp4 (e2m1 + e8m0 group 32), block fp8 (e4m3 + 128x128 fp32 scale); GEMMs
43
+ decode in registers, exact.
44
+ Parallelism (generic, torch.distributed NCCL, SPMD ranks with identical host loops):
45
+ TP heads / channels sharded per block by a per-block shard rule; one all-reduce per mixer and per MLP;
46
+ vocab-sharded lm_head + all-gather of logits (so the record sampler / speculation are unchanged).
47
+ EP routed experts partitioned across ranks; each rank computes its experts for all rows; the combine is the
48
+ same all-reduce as TP (no all-to-all at decode batch sizes).
49
+ PP contiguous layer stages, hidden passed with NCCL send/recv; used multi-node.
50
+ CUDA graphs: one graph per decode / verify step per rank, NCCL collectives captured inside.
51
+ Features that must keep working under parallelism: exact speculation + record (S27 SpecEngine), batching
52
+ (B27), shared prompt / merged worlds, lossless weights (the packed checkpoint codes are the resident format).
53
+
54
+ CELLS (BENCH27 cells that make sense at scale), held-out prompts
55
+ 1 single user greedy: code, chat, wikitext@512 (+ @8192 if time); 256 new; decode tok/s
56
+ 2 single user T=1: chat + held-out prompts, 256 new
57
+ 3 batched T=1: B in {1, 8, 32, 64, 128} as far as fits; random 32-token prompts (seeded); 128 new
58
+ 4 shared prompt: N in {32, 128} samples of one random 1000-token prompt, 64 new, T=1, total tok/s incl. prefill
59
+ 6 TTFT: fresh 8192 / 32768-token prompts, median of >= 5
60
+ Competitors: vLLM >= 0.35 nightly image from the recipe (vllm/vllm-openai:kimi-k31*), baseline TP8 and the
61
+ recipe's AgentX presets (TP8 + DCP8 + DSpark draft Inferact/Kimi-K3.1-Pro-DSpark, + EP8); SGLang cookbook config
62
+ if an image with K3.1 support exists. Memory settings recorded. Streams saved.
63
+ Replication: at 8-GPU scale 1 container x 3 runs (labelled), 2 containers if budget allows.
64
+ Containers: at most 1 multi-GPU container at a time + at most 1 single-GPU dev container (+ CPU downloaders).
65
+
66
+ DELIVERABLES final_k31.json (+ final_minimax.json if run), FINDINGS.txt, STATUS.txt; files < 5 MB.
package/p27/STATUS.txt ADDED
@@ -0,0 +1,91 @@
1
+ P27 STATUS (UTC) - parallelism / MoE / MLA / fp8-fp4 / scale ladder
2
+
3
+ 09:00 Started. Read BENCH27_SPEC.md + README rounds 3-6 + gpu/engine/*. (API.txt not present yet.)
4
+ 09:01 Downloads of the old ladder (Qwen3.5-122B / 397B-FP8 / Kimi-K2) started, then STOPPED at 09:05 when the model
5
+ set was replaced (spec section "Model set replaced with current models").
6
+ 09:06 NEW downloads running (modal_dl.py, Modal volume qllm-big-vol v2, HF_HOME=/vol/hf), 3 CPU containers:
7
+ K0+K1 moonshotai/Kimi-K3.1-Pro rev 80aff651e9b2d2f5b9f70f92a0a7a77054418e16, 1561.4 GB, split even/odd shards
8
+ path /vol/hf/hub/models--moonshotai--Kimi-K3.1-Pro/snapshots/80aff651e9b2d2f5b9f70f92a0a7a77054418e16
9
+ M tiny-random/kimi-k3.1-pro (done), Inferact/Kimi-K3.1-Pro-DSpark rev 50f5a10c (4.96 GB, done 09:06),
10
+ MiniMaxAI/MiniMax-M3.1-Flash rev ce7f4df8 (252.4 GB, downloading)
11
+ Progress lines below are appended as the downloads advance.
12
+
13
+ FACTS FOUND (09:05)
14
+ - Kimi-K3.1-Pro ships NO modeling code (auto_map has only AutoConfig). tiny-random/kimi-k3.1-pro carries the pinned
15
+ K3 reference modeling (moonshotai/Kimi-K3 rev 9f62e4e9, modeling_kimi_k3.py + modeling_kimi_linear.py) and states
16
+ that released Transformers has no gated-DSA operator: in HF the DSA layers run their dense MLA core and the
17
+ indexer tensors are unused. vLLM's K3.1 build (image vllm/vllm-openai:kimi-k31, >=0.35 nightly) does run the
18
+ top-2048 indexer. => for contexts <= 2048 tokens DSA top-2048 == dense MLA exactly; above that the "published
19
+ computation" is ambiguous (HF reference = dense, vLLM = sparse). Documented in SPEC.txt.
20
+ - 1.56 TB of weights: does NOT fit 8xB200 (1.54 TB) or 8xH200 (1.13 TB) even before KV. Single node needs 8xB300
21
+ (2.3 TB). Otherwise 2 clustered nodes (16 GPUs).
22
+ - vLLM recipes saved in recipes/ (b300 baseline TP8, b300_agentx TP8+DCP8+DSpark, b300_agentx_ep +EP8).
23
+
24
+ REQUESTS TO CORE (S27, gpu/engine/) -- P27 works around all of these in exp_p27_scale/ (pmodel.PModel wraps the
25
+ core interfaces; nothing forked), but the core should own them:
26
+ R1 WeightIndex.get(device="cuda") loads onto cuda:0 in every rank (safetensors semantics): default to
27
+ f"cuda:{torch.cuda.current_device()}". (P27 patches the instance in pmodel.build_spec_ext.)
28
+ R2 a residual-scheme hook in model.Model._stack (P27 has "standard" and "attn_res"); and a logits hook so a
29
+ vocab-sharded head can all-gather (P27: PModel.logits).
30
+ R3 blocks fuse projections with torch.cat(weights) -> breaks on coded weights; use a helper (P27: quant.cat_rows
31
+ returns a multi-segment QWeight with .lin()).
32
+ R4 a per-forward scratch dict on RowCtx for cross-layer state (P27 uses ctx._topk for DSA top-k reuse, ctx._anc).
33
+ R5 blocks.ALLREDUCE: P27 sets it to pblocks.all_reduce (fp32 NCCL all-reduce) when tp world > 1.
34
+
35
+ 09:19 GPU probes (modal_probe.py):
36
+ - 2 x 8 x B200 clustered: REFUSED at app creation: InvalidError("Cluster GPU count cannot exceed Workspace's max
37
+ concurrent GPUs (10)"). => this workspace can never run more than 10 GPUs at once, so multi-node 16-GPU is
38
+ impossible, and an 8-GPU container uses 8 of the 10 workspace GPUs shared by ALL lanes.
39
+ - 8 x B300 ("B300:8"): accepted by the API, but no container was scheduled in ~3 min (0 tasks); stopped at 09:21
40
+ when the headline moved to an 8xH200 model (no longer needed).
41
+ 09:12-09:21 HEADLINE CHANGE (spec "Headline model relaxed", coordinator): picked zai-org/GLM-5.3.
42
+ Candidates checked:
43
+ deepseek-ai/DeepSeek-V4.1-Flash-1017 (2026-10-17, 510 GB on disk, model_type deepseek_v41): NOT in
44
+ transformers 5.24.1 (latest; only deepseek_v4 exists) - the repo ships only inference/model.py, so there is
45
+ no native HF modeling for the fp32 reference (criterion 1 fails). Exotic blocks too (hyper-connections,
46
+ engram tables, compressed attention).
47
+ zai-org/GLM-5.3 (2026-08-25, 755.7 GB FP8 block-128, model_type glm_moe_dsa): native transformers modeling
48
+ (transformers/models/glm_moe_dsa, incl. the DSA indexer, so the reference defines DSA exactly); vLLM recipe
49
+ for 8xH200 (vLLM >= 0.29, TP8, fp8 KV, MTP 5 spec tokens; saved recipes/vllm_glm53_h200.md); SGLang cookbook;
50
+ fits 8xH200 (1128 GB) with ~370 GB left for KV/activations. => GLM-5.3.
51
+ Architecture: 78 layers (3 dense + 75 MoE), MLA (q_lora 2048, kv_lora 512, nope 192 + interleaved rope 64,
52
+ v 256, 64 heads) + DSA indexer (top-2048, own indexer every 4th layer, others reuse the previous top-k),
53
+ 256 routed experts top-8 + 1 shared, sigmoid router + correction bias, routed scale 2.5, 1 MTP layer,
54
+ fp8 e4m3 block 128x128 weights, vocab 154,880. For context <= 2048 DSA == dense MLA exactly.
55
+ 09:20 Kimi-K3.1-Pro downloads STOPPED (partial shards may remain on qllm-big-vol; optional now).
56
+ 09:20 GLM-5.3 download started: 3 CPU containers G0/G1/G2 (thirds of the 141 shards), rev
57
+ ba32f8c19c8738e2c57c71798c601d477a7bf844 -> /vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c1...
58
+ MiniMax-M3.1-Flash (252 GB) is DONE on the volume (09:18), tiny-random/kimi-k3.1-pro and the K3.1 DSpark draft too.
59
+ 09:24 PICK CONFIRMED FOR V27: zai-org/GLM-5.3 (rev ba32f8c1), native transformers modeling (model_type glm_moe_dsa,
60
+ transformers/models/glm_moe_dsa in transformers 5.24.1 -- NO trust_remote_code anywhere: neither our engine
61
+ nor the reference). DeepSeek-V4.1-Flash has no native transformers class (deepseek_v41 absent) -> rejected.
62
+ Kimi-K3.1 work (needs remote modeling code) is DROPPED: the remote-code test t_tiny.py was never run and won't be.
63
+ Dev model: tiny-random/glm-5.3 (rev b0430c66, native glm_moe_dsa, fp8 block 32x32, index_topk 128 so the DSA
64
+ sparse path is exercised at short contexts).
65
+ 09:43 GLM-5.3 download COMPLETE on qllm-big-vol (3 containers, 755.7 GB, 0.20-0.35 GB/s each, 12-21 min).
66
+ 09:30-09:40 dev tests on tiny-random/glm-5.3 vs native HF fp32 (t_glm.py, 1xH100):
67
+ - fp8 block GEMM vs float64 dequant matmul: rel err 1e-7 (M = 1..300); grouped fp8 MoE GEMM + capacity-free
68
+ dispatch (all-local and EP-partitioned): rel err 2e-7, every routed pair present, non-local pairs = -1.
69
+ - bugs found and fixed: second expert GEMM indexed activations by token instead of slot; reference fp8 dequant
70
+ assumed 128x128 blocks (tiny uses 32x32) - now inferred from the scale grid.
71
+ - per-module (fp32 HF hooks): attention / dense MLP / MoE (same routing) agree at bf16 level (rel 0.4-0.7%);
72
+ remaining divergence = router near-ties of the random tiny model (different experts picked from bf16 vs fp32
73
+ inputs) - expected for random weights, judged end-to-end by the certificate on the real model.
74
+ - DSA (T=200 > top-128): our indexer's top-k rows identical to HF's on 92% of rows at layer 0 (the rest differ
75
+ by <= 4 boundary keys: bf16 vs fp32 index scores near ties).
76
+ - SpecEngine (core) with the GLM MTP layer + suffix chain, CUDA graph: runs; greedy streams gap <= 0.03.
77
+ 09:39 rank-device bug (safetensors "cuda" = cuda:0) fixed for SPMD ranks.
78
+ 09:40-09:50 2xH100 TP/EP test QUEUED >10 min: workspace max 10 concurrent GPUs, ~10 single-GPU containers of other
79
+ lanes running. Asked the coordinator for an 8-GPU window (needed for 8xH200).
80
+ 10:24 H200:8 request queued 9 min with 9 workspace GPUs free (no H200 capacity) -> cancelled; switched the headline hardware to 8xB200 (spec allows 8xH200 or 8xB200); ALL engines (ours + vLLM + SGLang) on 8xB200.
81
+ 10:24-10:26 WINDOW 1 (8xB200): reduced-depth check on the REAL GLM-5.3 checkpoint (t_glm.main_real: first 4 layers =
82
+ 3 dense + 1 MoE, + final norm + head; TP8 attention/dense, experts loaded EP and re-laid-out to TP over NVLink),
83
+ vs HF fp32 with the same 4 layers: 64 positions, gap max 0.478 (< 0.5), argmax agree 75% (a 4-layer stub has
84
+ no trained logits: near-flat), max |dlogit| 0.77 std. Real 128x128 fp8 blocks, EP->TP all-to-all and 8-rank
85
+ NCCL all worked. Load of those layers 22 s.
86
+ 10:26 vLLM 0.34.0 (TP8, MTP 5 spec tokens, fp8 KV = recipe best) started on 8xB200; checkpoint loading runs at
87
+ ~7 s per 5.4 GB shard (~0.75 GB/s) => ~17 min load for vLLM. SGLang may not fit in window 1 (then window 3).
88
+ Meanwhile (no dev GPU 10:15-12:15): engine loading parallelised (16 reader threads per expert set x 4 layers
89
+ concurrently per rank, thread-local safetensors handles; EP->TP collectives afterwards in layer order), fused
90
+ RMSNorm/residual (core rms_fused), compiled glue, single-GEMM fused fp8 projections, Triton dispatch kernel
91
+ (validated at 12:15 before use). run_window2.sh = our bench at 12:15.
@@ -0,0 +1,354 @@
1
+ """Lane P27 benchmark of the one engine on an MoE/MLA checkpoint with tensor + expert parallelism (SPMD: every rank
2
+ runs this same host loop; logits are all-gathered so every rank takes identical decisions).
3
+
4
+ main(rank, world, model=..., plan={...}) cells: single (greedy, spec), single_t1 (T=1 record + spec), batched
5
+ (T=1 record, B users), shared (one prefill forked into N worlds, T=1), ttft (fresh prompts).
6
+ Timing is the same as lane C27's harness: single decode tok/s = (n-1)/(t(256 new)-t(1 new)) with a fresh state for
7
+ each call; batched decode tok/s = (sum n - B)/(t(128)-t(1)); shared total tok/s = N*64/wall incl. prefill; ttft = wall of
8
+ prefill + first token, median. Streams are returned for the fp32 certificate (V27 stream_ref input format).
9
+ """
10
+ import os
11
+ import statistics
12
+ import time
13
+
14
+ import torch
15
+ import torch.distributed as dist
16
+
17
+ SNAP = "/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844"
18
+ CHAT_Q = "Explain in three sentences why the sky is blue."
19
+ HELDOUT = [
20
+ "Write a short poem about a lighthouse keeper who has never seen the sea in daylight.",
21
+ "What are the main differences between a process and a thread in an operating system?",
22
+ "Give me a three-day itinerary for a first visit to Kyoto.",
23
+ "Summarize the causes of the French Revolution in one paragraph.",
24
+ "How does public-key cryptography let two strangers agree on a secret?",
25
+ "Write a Python function that returns the n-th prime number, with a brief explanation.",
26
+ "Describe the water cycle to a ten-year-old.",
27
+ "What should I consider when choosing between renting and buying a home?",
28
+ ]
29
+
30
+
31
+ def chat_ids(tok, q):
32
+ msgs = [{"role": "user", "content": q}]
33
+ try:
34
+ text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
35
+ except TypeError:
36
+ text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
37
+ return tok(text, add_special_tokens=False).input_ids
38
+
39
+
40
+ def text_ids(tok, which, n):
41
+ p = "/root/data/shakespeare.txt" if which == "shakespeare" else "/root/data/wikitext.txt"
42
+ return tok(open(p).read()[:2500000], add_special_tokens=False).input_ids[:n]
43
+
44
+
45
+ def rand_prompts(B, L, seed, lo=1000, hi=100000):
46
+ g = torch.Generator().manual_seed(seed)
47
+ return torch.randint(lo, hi, (B, L), generator=g).tolist()
48
+
49
+
50
+ def sync():
51
+ torch.cuda.synchronize()
52
+ if dist.is_initialized():
53
+ dist.barrier()
54
+
55
+
56
+ class BatchDecoder:
57
+ """B independent users, plain exact decoding (tree N=1), T>0 via the 23-bit record, one CUDA graph per step."""
58
+
59
+ def __init__(self, m, B, T, seq0=0):
60
+ from ctx import chain
61
+ self.m, self.B, self.T, self.seq0 = m, B, T, seq0
62
+ self.one = chain(1)
63
+ self.tok = torch.zeros(B, 1, dtype=torch.long, device="cuda")
64
+ self.lens = torch.zeros(B, dtype=torch.int32, device="cuda")
65
+ self.seq = (seq0 + torch.arange(B, device="cuda")).long()
66
+ self.graph = None
67
+
68
+ def _body(self):
69
+ from ctx import RowCtx
70
+ import spec as SP
71
+ ctx = RowCtx.tree(self.one, self.lens, self.B)
72
+ h = self.m.tree(self.tok, ctx)
73
+ z = self.m.logits(h)
74
+ nxt = SP.measure(z, self.seq * 65536 + self.lens.long() + 1, self.T)
75
+ ctx.set_accept(torch.zeros(self.B, dtype=torch.long, device="cuda"))
76
+ self.m.commit(ctx)
77
+ self.lens.add_(1)
78
+ self.tok[:, 0] = nxt
79
+
80
+ def capture(self):
81
+ s = torch.cuda.Stream()
82
+ s.wait_stream(torch.cuda.current_stream())
83
+ sv = (self.tok.clone(), self.lens.clone(), [blk.S.clone() for blk in self.m.blocks() if hasattr(blk, "S")])
84
+ with torch.cuda.stream(s):
85
+ for _ in range(2):
86
+ self._body()
87
+ torch.cuda.current_stream().wait_stream(s)
88
+ self.graph = torch.cuda.CUDAGraph()
89
+ with torch.cuda.graph(self.graph):
90
+ self._body()
91
+ self.tok.copy_(sv[0])
92
+ self.lens.copy_(sv[1])
93
+ for blk, st in zip([b for b in self.m.blocks() if hasattr(b, "S")], sv[2]):
94
+ blk.S.copy_(st)
95
+
96
+ @torch.no_grad()
97
+ def start(self, prompts):
98
+ """prefill every user (one at a time, chunked) and sample its first token."""
99
+ import spec as SP
100
+ m = self.m
101
+ firsts = []
102
+ for b, p in enumerate(prompts):
103
+ P = torch.tensor(p, dtype=torch.long, device="cuda")
104
+ m.reset(b)
105
+ h = m.prefill(P, b=b, keep_hidden=False)
106
+ z = m.logits(h[-1:])
107
+ firsts.append(SP.measure(z, torch.tensor([(self.seq0 + b) * 65536 + len(p)], device="cuda"), self.T))
108
+ self.lens[b] = len(p)
109
+ self.tok[:, 0] = torch.cat(firsts)
110
+
111
+ @torch.no_grad()
112
+ def run(self, n):
113
+ outs = [self.tok[:, 0].clone()]
114
+ for _ in range(n - 1):
115
+ self.graph.replay() if self.graph is not None else self._body()
116
+ outs.append(self.tok[:, 0].clone())
117
+ return torch.stack(outs, 1)
118
+
119
+
120
+ def _tail_periodicity(out, n=128):
121
+ """best exact period match fraction in the generated tail: a repeat-loop detector for benchmark hygiene."""
122
+ tail = list(map(int, out))[-n:]
123
+ if len(tail) < 16:
124
+ return 0.0, 0
125
+ best, bp = 0.0, 0
126
+ for p in range(2, len(tail) // 2 + 1):
127
+ v = sum(tail[i] == tail[i - p] for i in range(p, len(tail))) / (len(tail) - p)
128
+ if v > best:
129
+ best, bp = v, p
130
+ return best, bp
131
+
132
+
133
+ def _streams_add(S, key, prompt, out, T, seq=None):
134
+ per, period = _tail_periodicity(out)
135
+ S.append({"id": key, "prompt": list(map(int, prompt)), "out": list(map(int, out)), "T": T,
136
+ "tail_periodicity": per, "tail_period": period,
137
+ **({"seq": int(seq)} if seq is not None else {})})
138
+
139
+
140
+ def _save_partial(R, tag):
141
+ import json
142
+ try:
143
+ os.makedirs("/rvol/results", exist_ok=True)
144
+ json.dump(R, open(f"/rvol/results/partial_{tag}.json", "w"), default=str)
145
+ except Exception: # noqa
146
+ pass
147
+
148
+
149
+ def main(rank=0, world=1, model=SNAP, plan=None, smax=2048, B_alloc=1, expert_shard="ep_tp", reps=2, D=None, C=8,
150
+ tag="bench", load_only=False, fast=True, align_triton=False, ar32=True, fp8a8=False, E=0, EW=1, W=1, online=False, SN=4, dvocab=0, ODs=None, OCs=None, OEs=None, in_graph_suffix=False, J=0):
151
+ import pmodel
152
+ import pblocks as PB
153
+ import spec as SP
154
+ from transformers import AutoTokenizer
155
+ PB.FAST = fast
156
+ PB.AR32 = ar32
157
+ PB.MOE_FP8A8 = fp8a8
158
+ import quant as Q
159
+ Q.ALIGN_TRITON = align_triton
160
+ plan = plan or {}
161
+ t0 = time.time()
162
+ tp = {"rank": rank, "world": world, "group": None}
163
+ Bmax = 1
164
+ sm = smax # single-user phases: smax <= DSA top-k (2048) -> every key is selected: dense kernel path, exact
165
+ m = pmodel.PModel(model, B=1, smax=256, tp=tp, expert_shard=expert_shard, verbose=(rank == 0))
166
+ R = {"model": model, "gpu": torch.cuda.get_device_name(), "world": world, "load_s": time.time() - t0,
167
+ "weight_bytes_rank0": m.weight_bytes(), "state_bytes_rank0": m.state_bytes(), "expert_shard": expert_shard,
168
+ "mem_alloc_gb_rank0": torch.cuda.memory_allocated() / 1e9, "Bmax": Bmax, "smax": sm, "mtp": m.mtp is not None,
169
+ "single": [], "batched": [], "shared": [], "ttft": [], "errors": []}
170
+ R["fusion"] = {"x_fp8": sum(getattr(L.mix, "wxf", None) is not None for L in m.layers),
171
+ "x_bf16": sum(getattr(L.mix, "wxb", None) is not None for L in m.layers),
172
+ "q_fp8": sum(getattr(L.mix, "wqf", None) is not None for L in m.layers)}
173
+ if rank == 0:
174
+ print("loaded", R, flush=True)
175
+ if load_only:
176
+ return R
177
+ tok = AutoTokenizer.from_pretrained(model)
178
+ S = []
179
+ # ------------------------------------------------------------- single user (greedy, then T=1)
180
+ Dm = (D if D is not None else (3 if m.mtp is not None else 0))
181
+ cases = []
182
+ for nm in plan.get("single", []):
183
+ if nm == "code":
184
+ cases.append((nm, tok("def fibonacci(n):", add_special_tokens=False).input_ids, 0.0, 0))
185
+ elif nm == "chat":
186
+ cases.append((nm, chat_ids(tok, CHAT_Q), 0.0, 0))
187
+ else:
188
+ w, d = nm.split("@")
189
+ cases.append((nm, text_ids(tok, w, int(d)), 0.0, 0))
190
+ for nm in plan.get("single_t1", []):
191
+ if nm == "chat":
192
+ cases.append(("t1/chat", chat_ids(tok, CHAT_Q), 1.0, 5001))
193
+ elif nm == "heldout":
194
+ for i, q in enumerate(HELDOUT):
195
+ cases.append((f"t1/heldout{i}", chat_ids(tok, q), 1.0, 5100 + i))
196
+ if cases:
197
+ m.alloc(1, sm)
198
+ eng = None
199
+ for name, ids, T, seq in cases:
200
+ try:
201
+ if eng is None or eng.T != T or eng.uid != seq: # uid is baked into the captured graph
202
+ del eng
203
+ torch.cuda.empty_cache()
204
+ if online:
205
+ # bounded online rule: adaptive MTP depth/sibling width plus echo/no-echo variants, without an
206
+ # impractical full Cartesian capture of every historically supported shape
207
+ eng = SP.OnlineTree(m, Ds=tuple(ODs or (2, 3, 4, 5, 6)), Ws=tuple(dict.fromkeys((1, max(W, 1)))), C=C,
208
+ Cs=tuple(OCs or dict.fromkeys((0, 8, C))),
209
+ T=T, uid=seq, E=E, EW=EW, SN=SN, dvocab=(dvocab or None),
210
+ Es=tuple(OEs if OEs is not None else ((0, E) if E else (0,))), in_graph_suffix=in_graph_suffix, J=J,
211
+ start=(Dm, max(W, 1)))
212
+ eng.prepare(ids)
213
+ else:
214
+ eng = SP.SpecEngine(m, D=Dm, C=C, W=W, T=T, uid=seq, E=E, EW=EW, SN=SN, dvocab=(dvocab or None), in_graph_suffix=in_graph_suffix, J=J)
215
+ eng.capture(use_graph=True)
216
+ runs = []
217
+ for r in range(reps + 1):
218
+ m.reset()
219
+ sync()
220
+ tq = time.perf_counter()
221
+ o1 = eng.generate(ids, 1)
222
+ t1 = time.perf_counter() - tq
223
+ m.reset()
224
+ sync()
225
+ tq = time.perf_counter()
226
+ o = eng.generate(ids, 256)
227
+ sync()
228
+ tn = time.perf_counter() - tq
229
+ if r == 0:
230
+ _streams_add(S, f"single/{name}", ids, o["out"], T, seq if T else None)
231
+ continue
232
+ runs.append({"t1": t1, "t256": tn, "tok_s": 255 / max(tn - t1, 1e-9),
233
+ "tok_per_pass": o["tok_per_pass"], "engine_decode_tok_s": o["decode_tok_s"]})
234
+ ts = [x["tok_s"] for x in runs]
235
+ R["single"].append({"name": name, "ctx": len(ids), "sampling": "greedy" if T == 0 else "T=1 exact",
236
+ "tok_s": statistics.mean(ts), "tok_s_min": min(ts), "tok_s_max": max(ts),
237
+ "tokens_per_pass": statistics.mean(x["tok_per_pass"] for x in runs),
238
+ "mode": ("online-tree" if online else "spec") + f" D={Dm} (MTP) + suffix C={C} + echo E={E}/W{EW}", "runs": runs})
239
+ if rank == 0:
240
+ print("single", name, round(statistics.mean(ts), 1), round(runs[-1]["tok_per_pass"], 2), flush=True)
241
+ _save_partial(R, tag)
242
+ except Exception:
243
+ import traceback
244
+ R["errors"].append(f"single {name}: {traceback.format_exc()[-2000:]}")
245
+ if rank == 0:
246
+ print(R["errors"][-1], flush=True)
247
+ del eng
248
+ torch.cuda.empty_cache()
249
+ # ------------------------------------------------------------- batched T=1
250
+ for B in plan.get("batched", []):
251
+ try:
252
+ m.alloc(B, 32 + 128 + 16)
253
+ torch.cuda.empty_cache()
254
+ for seed in plan.get("batched_seeds", [1000, 1001]):
255
+ m.reset()
256
+ bd = BatchDecoder(m, B, 1.0, seq0=seed * 1000)
257
+ prompts = rand_prompts(B, 32, seed)
258
+ bd.start(prompts)
259
+ bd.capture()
260
+ sync()
261
+ tq = time.perf_counter()
262
+ bd.start(prompts)
263
+ sync()
264
+ tp1 = time.perf_counter() - tq
265
+ tq = time.perf_counter()
266
+ out = bd.run(128)
267
+ sync()
268
+ tdec = time.perf_counter() - tq
269
+ R["batched"].append({"B": B, "seed": seed, "tok_s": B * 127 / tdec, "prefill_s": tp1,
270
+ "total_tok_s": B * 128 / (tp1 + tdec), "method": "decode tok/s = B*127 / t(127 "
271
+ "graph steps); prefill (users one at a time) reported separately"})
272
+ for b in range(min(B, 4)):
273
+ _streams_add(S, f"batched/B{B}/s{seed}/u{b}", prompts[b], out[b].tolist(), 1.0, seed * 1000 + b)
274
+ if rank == 0:
275
+ print("batched", B, seed, round(B * 127 / tdec, 1), flush=True)
276
+ _save_partial(R, tag)
277
+ del bd
278
+ except Exception:
279
+ import traceback
280
+ R["errors"].append(f"batched {B}: {traceback.format_exc()[-2000:]}")
281
+ if rank == 0:
282
+ print(R["errors"][-1], flush=True)
283
+ # ------------------------------------------------------------- shared prompt, N worlds
284
+ for N in plan.get("shared", []):
285
+ try:
286
+ m.alloc(N, 1000 + 64 + 16)
287
+ torch.cuda.empty_cache()
288
+ for seed in plan.get("shared_seeds", [4243, 4244]):
289
+ P = rand_prompts(1, 1000, seed)[0]
290
+ m.reset()
291
+ bd = BatchDecoder(m, N, 1.0, seq0=seed * 1000)
292
+ bd.lens.fill_(len(P))
293
+ bd.capture()
294
+ sync()
295
+ tq = time.perf_counter()
296
+ Pt = torch.tensor(P, device="cuda")
297
+ m.reset(0)
298
+ h = m.prefill(Pt, b=0, keep_hidden=False)
299
+ m.fork(0, torch.arange(1, N, device="cuda"), len(P))
300
+ z = m.logits(h[-1:]).expand(N, -1)
301
+ bd.tok[:, 0] = SP.measure(z, bd.seq * 65536 + len(P), 1.0)
302
+ bd.lens.fill_(len(P))
303
+ out = bd.run(64)
304
+ sync()
305
+ wall = time.perf_counter() - tq
306
+ R["shared"].append({"N": N, "seed": seed, "total_tok_s": N * 64 / wall, "wall_s": wall,
307
+ "method": "one prefill of the 1000-token prompt, state forked into N worlds "
308
+ "(copy), then N-user T=1 record decode; wall includes prefill"})
309
+ for b in range(min(N, 4)):
310
+ _streams_add(S, f"shared/N{N}/s{seed}/u{b}", P, out[b].tolist(), 1.0, seed * 1000 + b)
311
+ if rank == 0:
312
+ print("shared", N, seed, round(N * 64 / wall, 1), flush=True)
313
+ _save_partial(R, tag)
314
+ del bd
315
+ except Exception:
316
+ import traceback
317
+ R["errors"].append(f"shared {N}: {traceback.format_exc()[-2000:]}")
318
+ if rank == 0:
319
+ print(R["errors"][-1], flush=True)
320
+ # ------------------------------------------------------------- TTFT
321
+ for L in plan.get("ttft", []):
322
+ try:
323
+ m.alloc(1, L + 64)
324
+ torch.cuda.empty_cache()
325
+ full = text_ids(tok, "wikitext", L * (plan.get("ttft_reps", 5) + 2))
326
+ ts = []
327
+ for r in range(plan.get("ttft_reps", 5) + 1):
328
+ ids = full[r * L:(r + 1) * L]
329
+ if len(ids) < L:
330
+ break
331
+ m.reset()
332
+ sync()
333
+ tq = time.perf_counter()
334
+ h = m.prefill(torch.tensor(ids, device="cuda"), b=0, keep_hidden=False)
335
+ t0_ = SP.measure(m.logits(h[-1:]), torch.tensor([L], device="cuda"), 0.0)
336
+ int(t0_)
337
+ sync()
338
+ if r > 0:
339
+ ts.append(time.perf_counter() - tq)
340
+ R["ttft"].append({"ctx": L, "median_s": statistics.median(ts), "runs_s": ts,
341
+ "attention": "DSA top-%s (indexer)" % m.spec["layers"][0]["mixer"]["indexer"]["topk"]
342
+ if m.spec["layers"][0]["mixer"].get("indexer") else "dense"})
343
+ if rank == 0:
344
+ print("ttft", L, ts, flush=True)
345
+ _save_partial(R, tag)
346
+ except Exception:
347
+ import traceback
348
+ R["errors"].append(f"ttft {L}: {traceback.format_exc()[-2000:]}")
349
+ R["streams"] = S
350
+ R["wall_s"] = time.time() - t0
351
+ R["mem_peak_gb_rank0"] = torch.cuda.max_memory_allocated() / 1e9
352
+ R["symm_buffers"] = len(PB._SYMM["buf"])
353
+ R["symm_ok"] = PB._SYMM["ok"]
354
+ return R