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,76 @@
1
+ """One-load multi-configuration GLM benchmark: compare speculative shapes without paying checkpoint load each time."""
2
+ import statistics
3
+ import time
4
+
5
+ import torch
6
+
7
+ import bench_glm as BG
8
+
9
+
10
+ def main(rank=0, world=1, model=BG.SNAP, configs=None, reps=1, tag="multi", fast=True, align_triton=True,
11
+ ar32=True, fp8a8=False, t1=False):
12
+ import pmodel
13
+ import pblocks as PB
14
+ import spec as SP
15
+ import quant as Q
16
+ from transformers import AutoTokenizer
17
+ PB.FAST, PB.AR32, PB.MOE_FP8A8 = fast, ar32, fp8a8
18
+ Q.ALIGN_TRITON = align_triton
19
+ configs = configs or []
20
+ t0 = time.time()
21
+ tp = {"rank": rank, "world": world, "group": None}
22
+ m = pmodel.PModel(model, B=1, smax=256, tp=tp, expert_shard="ep_tp", verbose=(rank == 0))
23
+ tok = AutoTokenizer.from_pretrained(model)
24
+ R = {"model": model, "gpu": torch.cuda.get_device_name(), "world": world, "load_s": time.time() - t0,
25
+ "configs": [], "errors": []}
26
+ if t1:
27
+ cases = [("t1/chat", BG.chat_ids(tok, BG.CHAT_Q), 1.0, 5001)]
28
+ else:
29
+ cases = [("code", tok("def fibonacci(n):", add_special_tokens=False).input_ids, 0.0, 0),
30
+ ("chat", BG.chat_ids(tok, BG.CHAT_Q), 0.0, 0)]
31
+ m.alloc(1, 2048)
32
+ S = []
33
+ for ci, cfg in enumerate(configs):
34
+ CR = {"config": cfg, "single": []}
35
+ for name, ids, T, seq in cases:
36
+ eng = None
37
+ try:
38
+ eng = SP.SpecEngine(m, D=cfg.get("D", 3), C=cfg.get("C", 8), W=cfg.get("W", 1), T=T,
39
+ uid=seq, E=cfg.get("E", 0), EW=cfg.get("EW", 1), SN=cfg.get("SN", 4),
40
+ dvocab=cfg.get("dvocab") or None, in_graph_suffix=cfg.get("in_graph_suffix", False), J=cfg.get("J", 0))
41
+ eng.capture(use_graph=True)
42
+ runs = []
43
+ for r in range(reps + 1):
44
+ m.reset()
45
+ BG.sync()
46
+ tq = time.perf_counter()
47
+ o1 = eng.generate(ids, 1)
48
+ t1 = time.perf_counter() - tq
49
+ m.reset()
50
+ BG.sync()
51
+ tq = time.perf_counter()
52
+ o = eng.generate(ids, 256)
53
+ BG.sync()
54
+ tn = time.perf_counter() - tq
55
+ if r == 0:
56
+ BG._streams_add(S, f"c{ci}/{name}", ids, o["out"], T, seq if T else None)
57
+ continue
58
+ runs.append({"t1": t1, "t256": tn, "tok_s": 255 / max(tn - t1, 1e-9),
59
+ "tok_per_pass": o["tok_per_pass"], "engine_decode_tok_s": o["decode_tok_s"]})
60
+ ts = [x["tok_s"] for x in runs]
61
+ CR["single"].append({"name": name, "tok_s": statistics.mean(ts), "tok_s_min": min(ts),
62
+ "tok_s_max": max(ts), "tokens_per_pass": statistics.mean(x["tok_per_pass"] for x in runs),
63
+ "runs": runs})
64
+ if rank == 0:
65
+ print("multi", ci, name, round(statistics.mean(ts), 1), round(runs[-1]["tok_per_pass"], 2), flush=True)
66
+ BG._save_partial(R, tag)
67
+ except Exception:
68
+ import traceback
69
+ R["errors"].append(f"c{ci}/{name}: {traceback.format_exc()[-2000:]}")
70
+ if rank == 0:
71
+ print(R["errors"][-1], flush=True)
72
+ del eng
73
+ torch.cuda.empty_cache()
74
+ R["configs"].append(CR)
75
+ R["streams"] = S if rank == 0 else []
76
+ return R
package/p27/mkfinal.py ADDED
@@ -0,0 +1,98 @@
1
+ """Assemble final_glm53.json (BENCH_SPEC schema + ttft list + competitors) from lane P27 raw results.
2
+ python mkfinal.py [--cert out/cert_glm53.json]
3
+ Also writes out/streams_ours_glm53.json in the V27 certificate input format (prompt/out/T/seq per stream)."""
4
+ import glob
5
+ import json
6
+ import os
7
+ import statistics
8
+ import sys
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+
12
+
13
+ def load(p):
14
+ try:
15
+ return json.load(open(p))
16
+ except Exception: # noqa
17
+ return None
18
+
19
+
20
+ def ours_rows(runs):
21
+ """merge single/batched/shared/ttft rows over our bench runs (replicates)."""
22
+ out = {"single": {}, "batched": {}, "shared": {}, "ttft": {}}
23
+ for tag, R in runs:
24
+ for r in R.get("single", []):
25
+ out["single"].setdefault(r["name"], []).append((tag, r))
26
+ for r in R.get("batched", []):
27
+ out["batched"].setdefault(r["B"], []).append((tag, r))
28
+ for r in R.get("shared", []):
29
+ out["shared"].setdefault(r["N"], []).append((tag, r))
30
+ for r in R.get("ttft", []):
31
+ out["ttft"].setdefault(r["ctx"], []).append((tag, r))
32
+ single = []
33
+ for name, rows in out["single"].items():
34
+ ts = [r["tok_s"] for _, r in rows]
35
+ single.append({"case": name.split("@")[0], "name": name, "ctx": rows[0][1]["ctx"],
36
+ "sampling": rows[0][1]["sampling"], "tok_s": statistics.mean(ts), "tok_s_min": min(ts),
37
+ "tok_s_max": max(ts), "tokens_per_pass": statistics.mean(r["tokens_per_pass"] for _, r in rows),
38
+ "mode": rows[0][1]["mode"], "runs": [dict(tag=t, **{k: v for k, v in r.items() if k != "runs"},
39
+ reps=r.get("runs")) for t, r in rows]})
40
+ batched = []
41
+ for B, rows in sorted(out["batched"].items()):
42
+ ts = [r["tok_s"] for _, r in rows]
43
+ batched.append({"B": B, "tok_s": statistics.mean(ts), "tok_s_min": min(ts), "tok_s_max": max(ts),
44
+ "sampling": "T=1 exact (23-bit record)", "n_prompts": B, "method": rows[0][1]["method"],
45
+ "runs": [dict(tag=t, **r) for t, r in rows]})
46
+ shared = []
47
+ for N, rows in sorted(out["shared"].items()):
48
+ ts = [r["total_tok_s"] for _, r in rows]
49
+ shared.append({"N": N, "total_tok_s": statistics.mean(ts), "min": min(ts), "max": max(ts),
50
+ "method": rows[0][1]["method"], "runs": [dict(tag=t, **r) for t, r in rows]})
51
+ ttft = []
52
+ for L, rows in sorted(out["ttft"].items()):
53
+ allr = [x for _, r in rows for x in r["runs_s"]]
54
+ ttft.append({"ctx": L, "median_s": statistics.median(allr), "runs_s": allr, "attention": rows[0][1]["attention"],
55
+ "method": "fresh wikitext window, state reset, wall of prefill + first token (sync)"})
56
+ return single, batched, shared, ttft
57
+
58
+
59
+ def comp_rows(R):
60
+ keep = ("single", "batched", "shared", "ttft", "longctx")
61
+ return {k: R.get(k, []) for k in keep}
62
+
63
+
64
+ def main(cert=None):
65
+ runs = []
66
+ for p in sorted(glob.glob(os.path.join(HERE, "out", "res_bench_*.json"))):
67
+ R = load(p)
68
+ if R and not R.get("error"):
69
+ runs.append((os.path.basename(p)[10:-5], R))
70
+ single, batched, shared, ttft = ours_rows(runs)
71
+ streams = [s for _, R in runs for s in R.get("streams", [])]
72
+ json.dump({"streams": streams}, open(os.path.join(HERE, "out", "streams_ours_glm53.json"), "w"))
73
+ comps = {}
74
+ for p in sorted(glob.glob(os.path.join(HERE, "out", "comp_*.json"))):
75
+ R = load(p)
76
+ if R:
77
+ comps[os.path.basename(p)[5:-5]] = dict(engine=R.get("engine"), version=R.get("engine_version"),
78
+ mode=R.get("mode"), gpu=R.get("gpu"), load_s=R.get("load_s"),
79
+ config=R.get("config"), errors=R.get("errors") or R.get("fatal"),
80
+ **comp_rows(R))
81
+ C = load(cert) if cert else None
82
+ first = runs[0][1] if runs else {}
83
+ F = {"gpu": first.get("gpu"), "n_gpus": first.get("world"), "engine": "P27 one engine (gpu/engine core + "
84
+ "exp_p27_scale blocks: MLA+DSA, fp8 MoE, TP/EP)", "engine_version": "round7-p27",
85
+ "model": "zai-org/GLM-5.3 (rev ba32f8c1, FP8 block-128)", "single": single, "batched": batched,
86
+ "shared": shared, "ttft": ttft, "competitors": comps,
87
+ "correctness": (C.get("summary") if C else "pending: V27 stream_ref fp32 certificate"),
88
+ "load": [{"tag": t, "load_s": R.get("load_s"), "weight_bytes_rank0": R.get("weight_bytes_rank0"),
89
+ "mem_peak_gb_rank0": R.get("mem_peak_gb_rank0")} for t, R in runs],
90
+ "notes": "see FINDINGS.txt"}
91
+ json.dump(F, open(os.path.join(HERE, "final_glm53.json"), "w"), indent=1, default=str)
92
+ print("wrote final_glm53.json:", len(single), "single,", len(batched), "batched,", len(shared), "shared,",
93
+ len(ttft), "ttft; competitors:", list(comps), "; streams:", len(streams))
94
+
95
+
96
+ if __name__ == "__main__":
97
+ a = sys.argv[1:]
98
+ main(a[a.index("--cert") + 1] if "--cert" in a else None)
@@ -0,0 +1,173 @@
1
+ """Lane P27: vLLM / SGLang on zai-org/GLM-5.3 (FP8) on one 8xH200 node, BENCH27 cells that make sense at scale.
2
+ Reuses lane C27's benchmark loop and adapters (gpu/exp_c27_engines/harness27.py, adapters.py; read-only copies in the
3
+ image) so competitor timing is identical across lanes.
4
+ modal run modal_comp.py --engine vllm --mode plain --plan '{...}' --tag A
5
+ Writes out/comp_<engine>_<mode>_<tag>.json + out/streams_<...>.npz.
6
+ Modes: vllm plain TP8, bf16 KV (exact-comparable) mtp recipe best: TP8 + fp8 KV + MTP 5 spec tokens
7
+ sglang plain TP8 mtp NEXTN (EAGLE-style) with the model's MTP layer
8
+ """
9
+ import json
10
+ import os
11
+ import time
12
+
13
+ import modal
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ GPUDIR = os.path.dirname(HERE)
17
+ ROOT = os.path.dirname(GPUDIR)
18
+
19
+
20
+ def repo_path(*parts):
21
+ """original research-tree location, with the flat standalone-repo layout as fallback."""
22
+ a = os.path.join(ROOT, *parts)
23
+ return a if os.path.exists(a) else os.path.join(GPUDIR, *parts)
24
+ C27 = repo_path("c27") if os.path.exists(repo_path("c27")) else os.path.join(GPUDIR, "exp_c27_engines")
25
+ VOL = modal.Volume.from_name("qllm-big-vol")
26
+ RVOL = modal.Volume.from_name("qllm-p27-vol", create_if_missing=True)
27
+ ENV = {"HF_HOME": "/vol/hf", "HF_HUB_OFFLINE": "1", "TOKENIZERS_PARALLELISM": "false",
28
+ "VLLM_CACHE_ROOT": "/rvol/cache/vllm", "FLASHINFER_WORKSPACE_BASE": "/rvol/cache/flashinfer"}
29
+ TAGS = {"vllm": "vllm/vllm-openai:v0.34.0", "sglang": "lmsysorg/sglang:v0.5.23"}
30
+ MODEL = "/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844"
31
+ GPU = os.environ.get("P27_GPU", "H200:8")
32
+
33
+
34
+ def _img(engine):
35
+ im = (modal.Image.from_registry(TAGS[engine]).entrypoint([])
36
+ .run_commands("command -v python >/dev/null || ln -sf $(command -v python3) /usr/local/bin/python")
37
+ .env(ENV))
38
+ for src, dst in [(os.path.join(C27, "harness27.py"), "/root/c27/harness27.py"),
39
+ (os.path.join(C27, "adapters.py"), "/root/c27/adapters.py"),
40
+ (repo_path("data", "input.txt"), "/root/c27/shakespeare.txt"),
41
+ (repo_path("data", "wikitext", "test.txt"), "/root/c27/wikitext.txt")]:
42
+ im = im.add_local_file(src, dst)
43
+ return im
44
+
45
+
46
+ IMAGES = {e: _img(e) for e in TAGS}
47
+ app = modal.App("qllm-p27-comp")
48
+
49
+
50
+ def spec_for(engine, mode, k):
51
+ if mode == "plain":
52
+ return None
53
+ if engine == "vllm" and mode == "mtp":
54
+ return {"method": "mtp", "num_speculative_tokens": k or 5}
55
+ if engine == "sglang" and mode == "mtp":
56
+ s = k or 3
57
+ return {"speculative_algorithm": "EAGLE", "speculative_num_steps": s, "speculative_eagle_topk": 1,
58
+ "speculative_num_draft_tokens": s + 1}
59
+ raise ValueError(mode)
60
+
61
+
62
+ def _common(engine, mode, plan, k, opts, version):
63
+ import sys
64
+ sys.path.insert(0, "/root/c27")
65
+ import torch
66
+ import harness27
67
+ from transformers import AutoTokenizer
68
+ mem = harness27.MemPoll()
69
+ tag = f"{engine}_{mode}" + (f"_k{k}" if k else "") + (f"_{opts['tag']}" if opts.get("tag") else "")
70
+ os.makedirs("/rvol/results", exist_ok=True)
71
+ out_path = f"/rvol/results/comp_{tag}.json"
72
+ tok = AutoTokenizer.from_pretrained(MODEL)
73
+ R = dict(engine=engine, engine_version=version, image=TAGS[engine], model="zai-org/GLM-5.3", model_path=MODEL,
74
+ mode=mode, k=k, gpu=torch.cuda.get_device_name(), n_gpus=torch.cuda.device_count(),
75
+ started=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), opts=opts, plan=plan,
76
+ container=os.environ.get("MODAL_TASK_ID"))
77
+ spec = spec_for(engine, mode, k)
78
+ extra = dict(opts.get("extra") or {})
79
+ t0 = time.time()
80
+ if engine == "vllm":
81
+ from adapters import VLLM
82
+ extra.setdefault("tensor_parallel_size", 8)
83
+ if mode == "mtp" and opts.get("recipe_kv", True):
84
+ extra.setdefault("kv_cache_dtype", "fp8") # recipe's best config (fp8 KV is lossy; recorded)
85
+ A = VLLM(MODEL, mode, spec, extra=extra, max_num_seqs=opts.get("max_seqs", 256),
86
+ max_model_len=opts.get("max_len", 40960))
87
+ else:
88
+ from adapters import SGLang
89
+ extra.setdefault("tp_size", 8)
90
+ A = SGLang(MODEL, mode, spec, extra=extra, max_running=opts.get("max_seqs", 256), ctx=opts.get("max_len", 40960))
91
+ R["load_s"] = time.time() - t0
92
+ R["config"] = {k2: (v if isinstance(v, (int, float, str, bool, dict, list, type(None))) else repr(v))
93
+ for k2, v in A.config.items()}
94
+ print("engine up in", R["load_s"], flush=True)
95
+ harness27.run_all(A, tok, R, plan, out_path=out_path, deadline=opts.get("deadline"), mem=mem)
96
+ R["mem_peak_mib_gpu0"] = mem.peak
97
+ R["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
98
+ json.dump(R, open(out_path, "w"), indent=1)
99
+ RVOL.commit()
100
+ R["_streams"] = harness27.STREAMS
101
+ return R
102
+
103
+
104
+ KW = dict(gpu=GPU, volumes={"/vol": VOL, "/rvol": RVOL}, timeout=4 * 3600, memory=1024 * 1024, cpu=64, retries=0)
105
+
106
+
107
+ @app.function(image=IMAGES["vllm"], **KW)
108
+ def run_vllm(mode, plan, k=None, opts=None):
109
+ import vllm
110
+ return _common("vllm", mode, plan, k, opts or {}, vllm.__version__)
111
+
112
+
113
+ @app.function(image=IMAGES["sglang"], **KW)
114
+ def run_sglang(mode, plan, k=None, opts=None):
115
+ import sglang
116
+ return _common("sglang", mode, plan, k, opts or {}, sglang.__version__)
117
+
118
+
119
+ def save_streams(S, p):
120
+ import numpy as np
121
+ keys, lens, flat = [], [], []
122
+ for key, v in S.items():
123
+ seqs = v if (v and isinstance(v[0], list)) else [v]
124
+ for i, s in enumerate(seqs):
125
+ keys.append(f"{key}/{i}" if (v and isinstance(v[0], list)) else key)
126
+ lens.append(len(s))
127
+ flat.extend(s)
128
+ np.savez_compressed(p, keys=np.array(keys), lens=np.array(lens, dtype=np.int32), ids=np.array(flat, dtype=np.int32))
129
+
130
+
131
+ @app.local_entrypoint()
132
+ def main(engine: str = "vllm", mode: str = "plain", plan: str = "{}", k: int = 0, opts: str = "{}", tag: str = ""):
133
+ o = json.loads(opts)
134
+ if tag:
135
+ o["tag"] = tag
136
+ name = f"{engine}_{mode}" + (f"_k{k}" if k else "") + (f"_{o['tag']}" if o.get("tag") else "")
137
+ t = time.time()
138
+ try:
139
+ R = {"vllm": run_vllm, "sglang": run_sglang}[engine].remote(mode, json.loads(plan), k or None, o)
140
+ except Exception as e:
141
+ R = {"engine": engine, "mode": mode, "fatal": repr(e)[-5000:]}
142
+ R["wall_s"] = time.time() - t
143
+ S = R.pop("_streams", None)
144
+ os.makedirs(os.path.join(HERE, "out"), exist_ok=True)
145
+ if S:
146
+ save_streams(S, os.path.join(HERE, "out", f"streams_comp_{name}.npz"))
147
+ p = os.path.join(HERE, "out", f"comp_{name}.json")
148
+ json.dump(R, open(p, "w"), indent=1)
149
+ print("wrote", p, "errors:", R.get("errors") or R.get("fatal"))
150
+
151
+
152
+ @app.function(image=IMAGES["vllm"], volumes={"/vol": VOL}, timeout=1800, cpu=4, memory=16384)
153
+ def prep_vllm():
154
+ import vllm
155
+ from vllm import ModelRegistry
156
+ return {"vllm": vllm.__version__, "glm_moe_dsa": "GlmMoeDsaForCausalLM" in ModelRegistry.get_supported_archs(),
157
+ "model_present": os.path.exists(MODEL + "/config.json")}
158
+
159
+
160
+ @app.function(image=IMAGES["sglang"], volumes={"/vol": VOL}, timeout=1800, cpu=4, memory=16384)
161
+ def prep_sglang():
162
+ import sglang
163
+ import glob
164
+ import subprocess
165
+ r = subprocess.run("grep -rl 'GlmMoeDsaForCausalLM' $(python -c 'import sglang,os;print(os.path.dirname(sglang.__file__))')/srt/models | head",
166
+ shell=True, capture_output=True, text=True).stdout
167
+ return {"sglang": sglang.__version__, "glm_files": r}
168
+
169
+
170
+ @app.local_entrypoint()
171
+ def prep():
172
+ print(prep_vllm.remote())
173
+ print(prep_sglang.remote())
@@ -0,0 +1,63 @@
1
+ """Lane P27: download the scale-ladder checkpoints (+ two single-GPU dev models) to Modal volume qllm-big-vol
2
+ (v2), HF_HOME=/vol/hf, revisions pinned. modal run --detach modal_dl.py::main --group A|B
3
+ (09:10 model set replaced: Kimi-K3.1-Pro headline, MiniMax-M3.1-Flash; old Qwen3.5/K2 downloads stopped)
4
+ K0 / K1: moonshotai/Kimi-K3.1-Pro, even / odd safetensors shards (two CPU containers, 1.56 TB)
5
+ (09:25 headline relaxed -> zai-org/GLM-5.3, 755.7 GB, split in thirds G0/G1/G2; Kimi downloads stopped)
6
+ M: tiny-random/kimi-k3.1-pro, Inferact/Kimi-K3.1-Pro-DSpark, MiniMaxAI/MiniMax-M3.1-Flash
7
+ """
8
+ import time
9
+
10
+ import modal
11
+
12
+ VOL = modal.Volume.from_name("qllm-big-vol", create_if_missing=True, version=2)
13
+ REPOS = {"moonshotai/Kimi-K3.1-Pro": "80aff651e9b2d2f5b9f70f92a0a7a77054418e16",
14
+ "MiniMaxAI/MiniMax-M3.1-Flash": "ce7f4df87d2e05262f5775f373dac4772f134041",
15
+ "Inferact/Kimi-K3.1-Pro-DSpark": "50f5a10c9385fb9a225c534dda8f7a1f5ae87110",
16
+ "tiny-random/kimi-k3.1-pro": "507bf23a377e31775c3a79b63b2c42bd6e4b9cc0",
17
+ "zai-org/GLM-5.3": "ba32f8c19c8738e2c57c71798c601d477a7bf844"}
18
+ GROUPS = {"G0": [("zai-org/GLM-5.3", (0, 3))], "G1": [("zai-org/GLM-5.3", (1, 3))],
19
+ "G2": [("zai-org/GLM-5.3", (2, 3))], "K0": [("moonshotai/Kimi-K3.1-Pro", (0, 2))], "K1": [("moonshotai/Kimi-K3.1-Pro", (1, 2))],
20
+ "M": [("tiny-random/kimi-k3.1-pro", None), ("Inferact/Kimi-K3.1-Pro-DSpark", None),
21
+ ("MiniMaxAI/MiniMax-M3.1-Flash", None)]}
22
+ IGNORE = ["figures/*", "*.png", ".eval_results/*", "assets/*"]
23
+ img = (modal.Image.debian_slim(python_version="3.11").pip_install("huggingface_hub[hf_xet]==0.36.0")
24
+ .env({"HF_HOME": "/vol/hf", "HF_XET_HIGH_PERFORMANCE": "1"}))
25
+ app = modal.App("qllm-p27-dl")
26
+
27
+
28
+ @app.function(image=img, volumes={"/vol": VOL}, timeout=10 * 3600, cpu=16, memory=32768)
29
+ def dl(repos: list):
30
+ import os
31
+ from huggingface_hub import HfApi, snapshot_download
32
+ out = {}
33
+ for r, half in repos:
34
+ t = time.time()
35
+ allow = None
36
+ if half is not None:
37
+ files = HfApi().list_repo_files(r, revision=REPOS[r])
38
+ sh = sorted(f for f in files if f.endswith(".safetensors"))
39
+ allow = [f for i, f in enumerate(sh) if i % half[1] == half[0]] + [f for f in files if not f.endswith(".safetensors")]
40
+ p = snapshot_download(r, revision=REPOS[r], max_workers=48, ignore_patterns=IGNORE, allow_patterns=allow)
41
+ sz = sum(os.path.getsize(os.path.join(dp, f)) for dp, _, fs in os.walk(p) for f in fs)
42
+ out[r] = dict(path=p, s=round(time.time() - t, 1), bytes=sz, GBps=round(sz / 1e9 / (time.time() - t), 3))
43
+ print("DONE", r, half, out[r], flush=True)
44
+ VOL.commit()
45
+ return out
46
+
47
+
48
+ @app.function(image=img, volumes={"/vol": VOL}, timeout=600)
49
+ def ls(cmd: str = "du -shL /vol/hf/hub/*"):
50
+ import subprocess
51
+ VOL.reload()
52
+ return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout
53
+
54
+
55
+ @app.local_entrypoint()
56
+ def main(group: str = "M"):
57
+ import json
58
+ print(json.dumps(dl.remote(GROUPS[group]), indent=1))
59
+
60
+
61
+ @app.local_entrypoint()
62
+ def show(cmd: str = "du -shL /vol/hf/hub/*"):
63
+ print(ls.remote(cmd))
@@ -0,0 +1,168 @@
1
+ """Lane P27 launcher.
2
+ modal run modal_p27.py --job t_tiny --arg '{}' one H100 (dev)
3
+ modal run modal_p27.py --job bench_k31 --gpus b300x8 --arg '{...}' 8 GPUs, SPMD ranks (torch.multiprocessing)
4
+ Job = /root/p27/<module>.py main(rank=, world=, **arg) (multi) or main(**arg) (dev). Engine core gpu/engine is
5
+ mounted at /root/engine. Weights: qllm-big-vol at /vol (HF_HOME=/vol/hf, read only). Results: qllm-p27-vol."""
6
+ import json
7
+ import os
8
+
9
+ import modal
10
+
11
+ HERE = os.path.dirname(os.path.abspath(__file__))
12
+ GPUDIR = os.path.dirname(HERE)
13
+ ROOT = os.path.dirname(GPUDIR)
14
+
15
+
16
+ def repo_path(*parts):
17
+ """original research-tree location, with the flat standalone-repo layout as fallback."""
18
+ a = os.path.join(ROOT, *parts)
19
+ return a if os.path.exists(a) else os.path.join(GPUDIR, *parts)
20
+ image = (
21
+ modal.Image.debian_slim(python_version="3.12")
22
+ .apt_install("git", "build-essential")
23
+ .pip_install("torch==2.14.0", index_url="https://download.pytorch.org/whl/cu130")
24
+ .pip_install("transformers==5.24.1", "safetensors", "huggingface_hub", "numpy", "einops", "fla-core==0.5.2",
25
+ "compressed-tensors==0.20.1", "tiktoken", "sentencepiece", "protobuf", "jinja2", "accelerate",
26
+ "blobfile", "pillow")
27
+ .env({"HF_HOME": "/vol/hf", "TOKENIZERS_PARALLELISM": "false",
28
+ "TRITON_CACHE_DIR": "/tmp/triton", "TORCH_NCCL_ASYNC_ERROR_HANDLING": "1"})
29
+ .add_local_file(repo_path("data", "input.txt"), "/root/data/shakespeare.txt")
30
+ .add_local_file(repo_path("data", "wikitext", "test.txt"), "/root/data/wikitext.txt")
31
+ .add_local_dir(os.path.join(GPUDIR, "engine"), "/root/engine", ignore=["__pycache__", "*.txt", "*.json"])
32
+ .add_local_dir(HERE, "/root/p27", ignore=["*.json", "*.log", "__pycache__", "*.txt", "logs", "out", "recipes",
33
+ "*.md"])
34
+ )
35
+ app = modal.App("qllm-p27-r11", image=image)
36
+ wvol = modal.Volume.from_name("qllm-big-vol")
37
+ rvol = modal.Volume.from_name("qllm-p27-vol", create_if_missing=True)
38
+ VOLS = {"/vol": wvol, "/rvol": rvol}
39
+
40
+
41
+ def _setup():
42
+ import sys
43
+ sys.path[:0] = ["/root/p27", "/root/engine"]
44
+
45
+
46
+ def _save(R, name):
47
+ os.makedirs("/rvol/results", exist_ok=True)
48
+ json.dump(R, open(f"/rvol/results/{name}.json", "w"), indent=1, default=str)
49
+ rvol.commit()
50
+
51
+
52
+ def _rank_main(rank, world, job, arg, port, q):
53
+ import sys
54
+ sys.path[:0] = ["/root/p27", "/root/engine"]
55
+ import importlib
56
+ import torch
57
+ import torch.distributed as dist
58
+ torch.cuda.set_device(rank)
59
+ import datetime
60
+ dist.init_process_group("nccl", init_method=f"tcp://127.0.0.1:{port}", rank=rank, world_size=world,
61
+ device_id=torch.device("cuda", rank), timeout=datetime.timedelta(minutes=8))
62
+ mod, _, fn = job.partition(":")
63
+ try:
64
+ R = getattr(importlib.import_module(mod), fn or "main")(rank=rank, world=world, **arg)
65
+ if rank == 0:
66
+ q.put(R)
67
+ except Exception:
68
+ import traceback
69
+ tb = traceback.format_exc()
70
+ print(f"[rank {rank}] FAILED\n{tb}", flush=True)
71
+ if rank == 0:
72
+ q.put({"error": tb})
73
+ finally:
74
+ # do not tear NCCL down (graphs may still hold communicators): flush and exit hard
75
+ import sys as _s
76
+ _s.stdout.flush()
77
+ q.close()
78
+ q.join_thread() # make sure rank 0's result left the queue feeder before the hard exit
79
+ torch.cuda.synchronize()
80
+ os._exit(0)
81
+
82
+
83
+ def _multi(job, arg, name):
84
+ import time
85
+ import torch
86
+ import torch.multiprocessing as mp
87
+ t = time.time()
88
+ world = torch.cuda.device_count()
89
+ ctx = mp.get_context("spawn")
90
+ q = ctx.Queue()
91
+ port = 29500 + int(time.time()) % 1000
92
+ procs = [ctx.Process(target=_rank_main, args=(r, world, job, json.loads(arg), port, q)) for r in range(world)]
93
+ for p in procs:
94
+ p.start()
95
+ R = None
96
+ while R is None and any(p.is_alive() for p in procs):
97
+ try:
98
+ R = q.get(timeout=10)
99
+ except Exception:
100
+ pass
101
+ for p in procs:
102
+ p.join(timeout=60)
103
+ if p.is_alive():
104
+ p.terminate()
105
+ if R is None:
106
+ R = {"error": "no result from rank 0", "exitcodes": [p.exitcode for p in procs]}
107
+ R["job_s"] = time.time() - t
108
+ _save(R, name)
109
+ return R
110
+
111
+
112
+ @app.function(gpu="H100!", timeout=3 * 3600, memory=131072, cpu=8, volumes=VOLS)
113
+ def dev(job: str, arg: str = "{}", name: str = ""):
114
+ import importlib
115
+ import time
116
+ _setup()
117
+ t = time.time()
118
+ mod, _, fn = job.partition(":")
119
+ try:
120
+ R = getattr(importlib.import_module(mod), fn or "main")(**json.loads(arg))
121
+ except Exception:
122
+ import traceback
123
+ R = {"error": traceback.format_exc()}
124
+ if isinstance(R, dict):
125
+ R["job_s"] = time.time() - t
126
+ _save(R, name or job.replace(":", "_"))
127
+ return R
128
+
129
+
130
+ MULTI_KW = dict(timeout=6 * 3600, memory=1024 * 1024, cpu=64, volumes=VOLS)
131
+
132
+
133
+ @app.function(gpu="B300:8", **MULTI_KW)
134
+ def b300x8(job: str, arg: str = "{}", name: str = ""):
135
+ return _multi(job, arg, name or job)
136
+
137
+
138
+ @app.function(gpu="B200:8", **MULTI_KW)
139
+ def b200x8(job: str, arg: str = "{}", name: str = ""):
140
+ return _multi(job, arg, name or job)
141
+
142
+
143
+ @app.function(gpu="H200:8", **MULTI_KW)
144
+ def h200x8(job: str, arg: str = "{}", name: str = ""):
145
+ return _multi(job, arg, name or job)
146
+
147
+
148
+ @app.function(gpu="H100:8", timeout=6 * 3600, memory=512 * 1024, cpu=32, volumes=VOLS)
149
+ def h100x8(job: str, arg: str = "{}", name: str = ""):
150
+ return _multi(job, arg, name or job)
151
+
152
+
153
+ @app.function(gpu="H100:2", timeout=2 * 3600, memory=128 * 1024, cpu=16, volumes=VOLS)
154
+ def h100x2(job: str, arg: str = "{}", name: str = ""):
155
+ return _multi(job, arg, name or job)
156
+
157
+
158
+ @app.local_entrypoint()
159
+ def main(job: str, arg: str = "{}", gpus: str = "dev", out: str = ""):
160
+ name = os.path.splitext(os.path.basename(out))[0] if out else job.replace(":", "_")
161
+ f = {"dev": dev, "b300x8": b300x8, "h200x8": h200x8, "b200x8": b200x8, "h100x8": h100x8, "h100x2": h100x2}[gpus]
162
+ R = f.remote(job, arg, name)
163
+ out = out or os.path.join(HERE, "out", f"res_{name}.json")
164
+ os.makedirs(os.path.dirname(out), exist_ok=True)
165
+ json.dump(R, open(out, "w"), indent=1, default=str)
166
+ s = json.dumps(R.get("summary", R) if isinstance(R, dict) else R, indent=1, default=str)
167
+ print(s[:8000])
168
+ print("wrote", out)
@@ -0,0 +1,49 @@
1
+ """Lane P27: which multi-GPU configurations does Modal give this workspace? modal run modal_probe.py --which b300
2
+ Each probe starts one container, prints nvidia-smi / NVLink topology / host RAM, and exits."""
3
+ import modal
4
+
5
+ img = modal.Image.debian_slim(python_version="3.11")
6
+ app = modal.App("qllm-p27-probe", image=img)
7
+ SH = ("nvidia-smi --query-gpu=index,name,memory.total,driver_version --format=csv; nvidia-smi topo -m | head -12; "
8
+ "free -g | head -2; nproc; df -h /tmp | tail -1")
9
+
10
+
11
+ def _run():
12
+ import subprocess
13
+ return subprocess.run(SH, shell=True, capture_output=True, text=True).stdout
14
+
15
+
16
+ @app.function(gpu="B300:8", timeout=600)
17
+ def b300():
18
+ return _run()
19
+
20
+
21
+ @app.function(gpu="B200:8", timeout=600)
22
+ def b200():
23
+ return _run()
24
+
25
+
26
+ @app.function(gpu="H200:8", timeout=600)
27
+ def h200():
28
+ return _run()
29
+
30
+
31
+ @app.function(gpu="H100:8", timeout=600)
32
+ def h100():
33
+ return _run()
34
+
35
+
36
+ # 2 x 8 x B200 clustered (modal.clustered(size=2, rdma=True)) cannot even be defined in this workspace:
37
+ # InvalidError("Cluster GPU count cannot exceed Workspace's max concurrent GPUs (10)") (09:19 UTC)
38
+
39
+
40
+ @app.local_entrypoint()
41
+ def main(which: str = "b300"):
42
+ import time
43
+ t = time.time()
44
+ f = {"b300": b300, "b200": b200, "h200": h200, "h100": h100}[which]
45
+ try:
46
+ print(f.remote())
47
+ except Exception as e:
48
+ print("PROBE FAILED", which, type(e).__name__, e)
49
+ print(f"probe {which} took {time.time() - t:.0f} s")
@@ -0,0 +1,29 @@
1
+ """Plug-in (gpu/engine/PLUGINS.txt): P27's MoE / MLA / KDA blocks as adapter rules of THE core engine, so
2
+ Engine(path) builds DeepSeek / Qwen-MoE / Kimi-style checkpoints with the core Model (T27 BUG-015). Rules are
3
+ inferred from weight names and config keys only; layers they do not recognise fall through to the core rules."""
4
+ import adapter
5
+ import pblocks # noqa: F401 (registers dense_glu_act / kda / mla / moe)
6
+ import pmodel as PM
7
+
8
+
9
+ def _names(W, prefix):
10
+ return sorted(k for k in W.map if k.startswith(prefix) and not k.endswith("inv_freq"))
11
+
12
+
13
+ @adapter.register_rule
14
+ def p27_rule(tc, W, lp, i, ltype):
15
+ out = {}
16
+ a = lp + "self_attn."
17
+ if (W.has(a + "f_a_proj.weight") and W.has(a + "A_log")) or W.has(a + "kv_a_proj_with_mqa.weight"):
18
+ mx = PM._mixer_spec(tc, W, a, tc["rms_norm_eps"], tc.get("linear_attn_config") or {}, i)
19
+ mx["names"] = _names(W, a)
20
+ out["mixer"] = mx
21
+ for mp in ("block_sparse_moe.", "mlp.", "feed_forward."):
22
+ if (W.has(lp + mp + "gate.weight") or W.has(lp + mp + "router.weight")) and any(
23
+ W.has(lp + mp + "experts.0." + n) for n in ("gate_proj.weight", "w1.weight", "w1.weight_packed")):
24
+ out["mlp"] = PM._mlp_spec(tc, W, lp, PM._act(tc), tc["rms_norm_eps"], i)
25
+ break
26
+ else:
27
+ if "mixer" in out and W.has(lp + "block_sparse_moe.gate_proj.weight"):
28
+ out["mlp"] = {"type": "dense_glu", "prefix": lp + "block_sparse_moe.", "act": tc.get("hidden_act", "silu")}
29
+ return out or None