quantuminfer 0.0.0-stage → 0.1.1
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.
- package/LICENSE +9 -0
- package/README.md +96 -2
- package/bin/quantuminfer.js +61 -0
- package/c27/adapters.py +161 -0
- package/c27/harness27.py +349 -0
- package/data/input.txt +40000 -0
- package/data/wikitext/test.txt +7249 -0
- package/engine/API.txt +208 -0
- package/engine/PLUGINS.txt +4 -0
- package/engine/__init__.py +82 -0
- package/engine/adapter.py +505 -0
- package/engine/blocks.py +1180 -0
- package/engine/c12.py +324 -0
- package/engine/c12cu.py +1074 -0
- package/engine/ctx.py +87 -0
- package/engine/dev.py +11 -0
- package/engine/ds4.py +389 -0
- package/engine/kernels.py +833 -0
- package/engine/model.py +281 -0
- package/engine/record.py +140 -0
- package/engine/server.py +183 -0
- package/engine/spec.py +1030 -0
- package/engine/wcode.py +122 -0
- package/p27/SPEC.txt +66 -0
- package/p27/STATUS.txt +91 -0
- package/p27/bench_glm.py +354 -0
- package/p27/bench_multi.py +76 -0
- package/p27/mkfinal.py +98 -0
- package/p27/modal_comp.py +173 -0
- package/p27/modal_dl.py +63 -0
- package/p27/modal_p27.py +168 -0
- package/p27/modal_probe.py +49 -0
- package/p27/p27rules.py +29 -0
- package/p27/pblocks.py +1242 -0
- package/p27/pmodel.py +402 -0
- package/p27/pref.py +151 -0
- package/p27/prof_glm.py +34 -0
- package/p27/quant.py +850 -0
- package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
- package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
- package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
- package/p27/recipes/vllm_default_gb300.md +281 -0
- package/p27/recipes/vllm_glm53_h200.md +301 -0
- package/p27/run_window1.sh +21 -0
- package/p27/run_window2.sh +13 -0
- package/p27/sweep_glm.py +64 -0
- package/p27/t_align.py +42 -0
- package/p27/t_combine.py +28 -0
- package/p27/t_echo.py +31 -0
- package/p27/t_fp8dense.py +59 -0
- package/p27/t_fp8speed.py +48 -0
- package/p27/t_glm.py +340 -0
- package/p27/t_glu.py +30 -0
- package/p27/t_gsuf.py +23 -0
- package/p27/t_jac.py +22 -0
- package/p27/t_moebm.py +30 -0
- package/p27/t_nccl.py +36 -0
- package/p27/t_online_jac.py +31 -0
- package/p27/t_probe.py +4 -0
- package/p27/t_router.py +28 -0
- package/p27/t_symm.py +50 -0
- package/p27/t_tiny.py +116 -0
- package/package.json +34 -4
- package/results/ANALYSIS.md +160 -0
- package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
- package/results/glm53_b300x8_opt4.json +624 -0
- package/results/res_glm_c32w3_b300.json +638 -0
- package/results/res_glm_final_c32_b300.json +652 -0
- package/results/res_glm_multi_final_b300.json +1821 -0
- package/results/res_glm_online_b300.json +638 -0
- package/results/res_glm_online_fixed_b300.json +638 -0
- package/results/res_glm_opt4_b300.json +624 -0
- package/results/res_glm_t1_j8_b300.json +340 -0
- package/results/res_glm_text_plain_batch_b300.json +5792 -0
- package/results/res_glm_text_w1_b300.json +1635 -0
- package/results/res_glm_text_w3_b300.json +1639 -0
- package/results/res_sweep_echo_b300.json +129 -0
- package/results/res_sweep_final_b300.json +153 -0
- package/results/res_sweep_glm_b300.json +153 -0
- package/results/res_techo.json +29 -0
- package/results/res_tgsuf.json +21 -0
- package/results/res_tjac.json +17 -0
- package/results/res_tonline_jac.json +13 -0
package/p27/pmodel.py
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
"""Lane P27: parallel decoder for the one engine. Spec inference (adapter extension), residual wiring schemes,
|
|
2
|
+
tensor / expert parallel loading, vocab-sharded head. Exposes the same interface as gpu/engine/model.Model
|
|
3
|
+
(prefill / tree / commit / logits / final / reset / blocks / mtp), so the core SpecEngine, the record sampler and
|
|
4
|
+
batched decoding run on it unchanged. Nothing here branches on a model name: the layer types are inferred from the
|
|
5
|
+
weight names and config keys (generic rules), facts not in the config come from adapter.FAMILY-style data.
|
|
6
|
+
|
|
7
|
+
Residual schemes (declared from config):
|
|
8
|
+
standard x += mix(norm1(x)); x += mlp(norm2(x))
|
|
9
|
+
attn_res block attention residuals (config attn_res_block_size): every layer reads a softmax-weighted mix of the
|
|
10
|
+
block snapshots taken every `block` layers and the running in-block sum (Kimi AttnRes); see _ares().
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
import torch.nn.functional as F
|
|
18
|
+
|
|
19
|
+
import blocks as Bk
|
|
20
|
+
from adapter import WeightIndex
|
|
21
|
+
from blocks import rms, LINEAR
|
|
22
|
+
from ctx import RowCtx
|
|
23
|
+
import pblocks as PB
|
|
24
|
+
|
|
25
|
+
BF = torch.bfloat16
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ------------------------------------------------------------------------------------------- spec inference
|
|
29
|
+
def _act(tc):
|
|
30
|
+
a = tc.get("hidden_act", "silu")
|
|
31
|
+
if a == "situ":
|
|
32
|
+
return ["situ", float(tc.get("activation_situ_beta") or 1.0), tc.get("activation_situ_linear_beta")]
|
|
33
|
+
assert a == "silu", a
|
|
34
|
+
return ["silu"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _qfmt(W, key_base):
|
|
38
|
+
if W.has(key_base + ".weight_packed"):
|
|
39
|
+
return "mxfp4"
|
|
40
|
+
if W.has(key_base + ".weight_scale_inv"):
|
|
41
|
+
return "fp8blk"
|
|
42
|
+
return "bf16"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_spec_ext(path):
|
|
46
|
+
cfg = json.load(open(os.path.join(path, "config.json")))
|
|
47
|
+
tc = cfg.get("text_config", cfg)
|
|
48
|
+
W = WeightIndex(path)
|
|
49
|
+
_get = W.get
|
|
50
|
+
|
|
51
|
+
def get_here(name, device=None, shard=None): # safetensors "cuda" means cuda:0; load onto this rank's device
|
|
52
|
+
return _get(name, device=device or f"cuda:{torch.cuda.current_device()}", shard=shard)
|
|
53
|
+
W.get = get_here
|
|
54
|
+
pre = None
|
|
55
|
+
for k in W.map:
|
|
56
|
+
m = re.match(r"(.*?)layers\.0\.", k)
|
|
57
|
+
if m and "mtp" not in k and "vision" not in k and "visual" not in k:
|
|
58
|
+
if pre is None or len(m.group(1)) < len(pre):
|
|
59
|
+
pre = m.group(1)
|
|
60
|
+
nl = tc["num_hidden_layers"]
|
|
61
|
+
d = tc["hidden_size"]
|
|
62
|
+
eps = tc["rms_norm_eps"]
|
|
63
|
+
act = _act(tc)
|
|
64
|
+
lac = tc.get("linear_attn_config") or {}
|
|
65
|
+
layers = []
|
|
66
|
+
for i in range(nl):
|
|
67
|
+
lp = f"{pre}layers.{i}."
|
|
68
|
+
L = {"prefix": lp, "norm1": lp + "input_layernorm.weight", "norm2": lp + "post_attention_layernorm.weight"}
|
|
69
|
+
a = lp + "self_attn."
|
|
70
|
+
L["mixer"] = _mixer_spec(tc, W, a, eps, lac, i)
|
|
71
|
+
L["mlp"] = _mlp_spec(tc, W, lp, act, eps, i)
|
|
72
|
+
if W.has(lp + "self_attention_res_proj.weight"):
|
|
73
|
+
L["ares"] = {"n1": lp + "self_attention_res_norm.weight", "p1": lp + "self_attention_res_proj.weight",
|
|
74
|
+
"n2": lp + "mlp_res_norm.weight", "p2": lp + "mlp_res_proj.weight"}
|
|
75
|
+
layers.append(L)
|
|
76
|
+
nm = tc.get("num_nextn_predict_layers") or 0
|
|
77
|
+
mtp = None
|
|
78
|
+
if nm and W.has(f"{pre}layers.{nl}.eh_proj.weight"):
|
|
79
|
+
lp = f"{pre}layers.{nl}." # DeepSeek-style MTP layer appended after the decoder stack
|
|
80
|
+
mtp = {"fc": lp + "eh_proj.weight", "norm_emb": lp + "enorm.weight", "norm_hid": lp + "hnorm.weight",
|
|
81
|
+
"norm": lp + "shared_head.norm.weight",
|
|
82
|
+
"layers": [{"prefix": lp, "norm1": lp + "input_layernorm.weight",
|
|
83
|
+
"norm2": lp + "post_attention_layernorm.weight",
|
|
84
|
+
"mixer": _mixer_spec(tc, W, lp + "self_attn.", eps, lac, nl),
|
|
85
|
+
"mlp": _mlp_spec(tc, W, lp, act, eps, nl)}]}
|
|
86
|
+
head = [k for k in W.map if k.endswith("lm_head.weight")]
|
|
87
|
+
spec = {"d": d, "vocab": tc["vocab_size"], "eps": eps, "norm_offset": 0.0, "prefix": pre, "layers": layers,
|
|
88
|
+
"embed": pre + "embed_tokens.weight", "final_norm": pre + "norm.weight",
|
|
89
|
+
"head": head[0] if head else pre + "embed_tokens.weight", "model_type": tc.get("model_type"),
|
|
90
|
+
"residual": "standard", "qblock": (cfg.get("quantization_config") or tc.get("quantization_config") or
|
|
91
|
+
{}).get("weight_block_size")}
|
|
92
|
+
if mtp:
|
|
93
|
+
spec["mtp"] = mtp
|
|
94
|
+
if tc.get("attn_res_block_size"):
|
|
95
|
+
spec["residual"] = "attn_res"
|
|
96
|
+
spec["ares_block"] = tc["attn_res_block_size"]
|
|
97
|
+
spec["ares_out"] = {"n": pre + "output_attn_res_norm.weight", "p": pre + "output_attn_res_proj.weight"}
|
|
98
|
+
return spec, W, cfg
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _rope_of(tc):
|
|
102
|
+
rp = tc.get("rope_parameters") or {}
|
|
103
|
+
theta = rp.get("rope_theta", tc.get("rope_theta", 10000.0))
|
|
104
|
+
rt = rp.get("rope_type", "default")
|
|
105
|
+
rs = tc.get("rope_scaling")
|
|
106
|
+
scaling = None
|
|
107
|
+
if rt not in ("default", None) or (rs and rs.get("rope_type", rs.get("type")) not in ("default", None)):
|
|
108
|
+
scaling = rs or rp
|
|
109
|
+
style = "interleave" if tc.get("rope_interleave", True) else "half"
|
|
110
|
+
return {"theta": float(theta), "style": style, "scaling": scaling}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _mixer_spec(tc, W, a, eps, lac, i):
|
|
114
|
+
if W.has(a + "f_a_proj.weight") and W.has(a + "A_log"):
|
|
115
|
+
if not lac.get("num_heads"): # Kimi-Linear configs: flat linear_* keys instead of linear_attn_config
|
|
116
|
+
lac = {"num_heads": tc["linear_num_heads"], "head_dim": tc["linear_head_dim"],
|
|
117
|
+
"short_conv_kernel_size": tc.get("linear_conv_kernel_dim", 4)}
|
|
118
|
+
return {"type": "kda", "prefix": a, "heads": lac["num_heads"], "head_dim": lac["head_dim"],
|
|
119
|
+
"conv": lac.get("short_conv_kernel_size", 4), "lower_bound": lac.get("gate_lower_bound"), "eps": eps}
|
|
120
|
+
if W.has(a + "kv_a_proj_with_mqa.weight"):
|
|
121
|
+
# Kimi-Linear's MLA layers are NoPE (the HF reference never rotates k_rot); others opt in via mla_use_nope
|
|
122
|
+
rope = None if tc.get("mla_use_nope", tc.get("model_type") == "kimi_linear") else _rope_of(tc)
|
|
123
|
+
dq = tc["qk_nope_head_dim"] + tc["qk_rope_head_dim"]
|
|
124
|
+
scale = dq ** -0.5
|
|
125
|
+
if rope and rope["scaling"] and rope["scaling"].get("mscale_all_dim"):
|
|
126
|
+
import math
|
|
127
|
+
f = rope["scaling"]["factor"]
|
|
128
|
+
ms = 0.1 * rope["scaling"]["mscale_all_dim"] * math.log(f) + 1.0 if f > 1 else 1.0
|
|
129
|
+
scale = scale * ms * ms
|
|
130
|
+
ix = None
|
|
131
|
+
if tc.get("index_topk"):
|
|
132
|
+
own = W.has(a + "indexer.wk.weight")
|
|
133
|
+
ix = {"own": own, "topk": tc["index_topk"], "heads": tc.get("index_n_heads"),
|
|
134
|
+
"dim": tc.get("index_head_dim")}
|
|
135
|
+
return {"type": "mla", "prefix": a, "heads": tc["num_attention_heads"], "qk_nope": tc["qk_nope_head_dim"],
|
|
136
|
+
"qk_rope": tc["qk_rope_head_dim"], "v_head": tc["v_head_dim"], "kv_lora": tc["kv_lora_rank"],
|
|
137
|
+
"q_lora": tc.get("q_lora_rank"), "gate": W.has(a + "g_proj.weight"), "rope": rope, "eps": eps,
|
|
138
|
+
"scale": scale, "indexer": ix}
|
|
139
|
+
raise NotImplementedError(f"layer {i}: unknown mixer at {a}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _mlp_spec(tc, W, lp, act, eps, i):
|
|
143
|
+
for mp in ("block_sparse_moe.", "mlp.", "feed_forward."):
|
|
144
|
+
mo = lp + mp
|
|
145
|
+
rn = "gate" if W.has(mo + "gate.weight") else "router" # router module name (Jamba: router)
|
|
146
|
+
if W.has(mo + rn + ".weight") and (W.has(mo + "experts.0.w1.weight_packed") or
|
|
147
|
+
W.has(mo + "experts.0.gate_proj.weight") or W.has(mo + "experts.0.w1.weight")):
|
|
148
|
+
E = tc.get("num_experts") or tc.get("n_routed_experts") or tc.get("num_local_experts")
|
|
149
|
+
# correction bias lives on the router (DeepSeek) or beside it (MiniMax-M2)
|
|
150
|
+
rb = next((n for n in (rn + ".e_score_correction_bias", "e_score_correction_bias") if W.has(mo + n)), None)
|
|
151
|
+
ek = "experts"
|
|
152
|
+
names = (["w1", "w3", "w2"] if (W.has(mo + "experts.0.w1.weight") or W.has(mo + "experts.0.w1.weight_packed"))
|
|
153
|
+
else ["gate_proj", "up_proj", "down_proj"])
|
|
154
|
+
m = {"type": "moe", "prefix": mo, "n_experts": E,
|
|
155
|
+
"top_k": tc.get("num_experts_per_token") or tc.get("num_experts_per_tok"),
|
|
156
|
+
"score": (tc.get("moe_router_activation_func") or tc.get("scoring_func") or
|
|
157
|
+
("sigmoid" if rb else "softmax")),
|
|
158
|
+
"renorm": bool(tc.get("moe_renormalize", tc.get("norm_topk_prob", tc.get("model_type") != "jamba"))),
|
|
159
|
+
"routed_scale": float(tc.get("routed_scaling_factor") or 1.0), "router": rn,
|
|
160
|
+
"router_bias": rb is not None, "router_bias_name": rb,
|
|
161
|
+
"n_group": tc.get("num_expert_group") or tc.get("n_group") or 1, "topk_group": tc.get("topk_group", 1),
|
|
162
|
+
"experts_key": ek, "expert_names": names, "expert_format": _qfmt(W, f"{mo}{ek}.0.{names[0]}"),
|
|
163
|
+
"act": act, "eps": eps}
|
|
164
|
+
if W.has(mo + "routed_expert_down_proj.weight"):
|
|
165
|
+
m["latent"] = {"down": "routed_expert_down_proj.weight", "up": "routed_expert_up_proj.weight",
|
|
166
|
+
"norm": "routed_expert_norm.weight" if W.has(mo + "routed_expert_norm.weight") else None}
|
|
167
|
+
for sp in ("shared_experts.", "shared_expert."):
|
|
168
|
+
if W.has(mo + sp + "gate_proj.weight"):
|
|
169
|
+
m["shared"] = {"prefix": sp, "gate": "gate_proj.weight", "up": "up_proj.weight",
|
|
170
|
+
"down": "down_proj.weight"}
|
|
171
|
+
if W.has(mo + "shared_expert_gate.weight"):
|
|
172
|
+
m["shared"]["gate_w"] = "shared_expert_gate.weight"
|
|
173
|
+
m["names"] = sorted(k for k in W.map if k.startswith(mo) and not k.endswith("inv_freq"))
|
|
174
|
+
return m
|
|
175
|
+
if W.has(lp + "mlp.gate_proj.weight"):
|
|
176
|
+
return {"type": "dense_glu_act", "prefix": lp + "mlp.", "gate": "gate_proj.weight", "up": "up_proj.weight",
|
|
177
|
+
"down": "down_proj.weight", "act": act}
|
|
178
|
+
raise NotImplementedError(f"layer {i}: unknown MLP at {lp}")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _first(W, base):
|
|
182
|
+
for suf in (".weight", ".weight_packed"):
|
|
183
|
+
if W.has(base + suf):
|
|
184
|
+
return base + suf
|
|
185
|
+
return base + ".weight"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------------------------------- model
|
|
189
|
+
class PLayer:
|
|
190
|
+
def __init__(self, L, W, g, idx):
|
|
191
|
+
self.idx = idx
|
|
192
|
+
self.n1 = PB.full_w(W, L["norm1"])
|
|
193
|
+
self.n2 = PB.full_w(W, L["norm2"])
|
|
194
|
+
self.mix = Bk.make(L["mixer"], W, g)
|
|
195
|
+
self.mlp = Bk.make(L["mlp"], W, g)
|
|
196
|
+
self.g = g
|
|
197
|
+
self.eps, self.off = g["eps"], g["norm_offset"]
|
|
198
|
+
self.ares = None
|
|
199
|
+
if "ares" in L:
|
|
200
|
+
a = L["ares"]
|
|
201
|
+
# score weight = norm.weight * proj.weight (fp32), exactly as the reference forms it
|
|
202
|
+
self.ares = ((W.get(a["n1"]).float() * W.get(a["p1"]).float().reshape(-1)),
|
|
203
|
+
(W.get(a["n2"]).float() * W.get(a["p2"]).float().reshape(-1)))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _ares(prefix, blocks_, sw, eps):
|
|
207
|
+
"""attention residual over depth: v = [blocks..., prefix] (R, nb+1, d); softmax over rmsnorm(v) . sw."""
|
|
208
|
+
v = torch.stack(blocks_ + [prefix], 1).float()
|
|
209
|
+
k = v * torch.rsqrt(v.pow(2).mean(-1, keepdim=True) + eps)
|
|
210
|
+
p = (k * sw).sum(-1).softmax(-1)
|
|
211
|
+
return torch.matmul(p[:, None], v)[:, 0].to(prefix.dtype)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
LAYER_THREADS = 4
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class _GatherHead:
|
|
218
|
+
def __init__(self, w, g):
|
|
219
|
+
self.w, self.g = w, g
|
|
220
|
+
|
|
221
|
+
def lin(self, x):
|
|
222
|
+
return PB.all_gather_last(F.linear(x, self.w), self.g)
|
|
223
|
+
|
|
224
|
+
def nbytes(self):
|
|
225
|
+
return self.w.numel() * self.w.element_size()
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class PModel:
|
|
229
|
+
def __init__(self, path, B=1, smax=4096, tp=None, expert_shard="ep", layers=None, verbose=True, load_mtp=True):
|
|
230
|
+
import time
|
|
231
|
+
t0 = time.time()
|
|
232
|
+
spec, W, cfg = build_spec_ext(path)
|
|
233
|
+
self.spec, self.path, self.cfg = spec, path, cfg
|
|
234
|
+
self.Widx, self.head_name = W, spec["head"]
|
|
235
|
+
self._draft_heads = {}
|
|
236
|
+
self.tp = tp or {"rank": 0, "world": 1, "group": None}
|
|
237
|
+
if spec.get("qblock"):
|
|
238
|
+
PB.QBLOCK.update(qn=spec["qblock"][0], qk=spec["qblock"][1])
|
|
239
|
+
Bk.ALLREDUCE = PB.all_reduce # core hook: core Layer (MTP head) all-reduces partial outputs
|
|
240
|
+
self.g = {"eps": spec["eps"], "norm_offset": spec["norm_offset"], "tp": self.tp}
|
|
241
|
+
for L in spec["layers"] + (spec["mtp"]["layers"] if spec.get("mtp") else []):
|
|
242
|
+
if L["mlp"]["type"] == "moe":
|
|
243
|
+
L["mlp"]["shard"] = expert_shard
|
|
244
|
+
self.embed = W.get(spec["embed"])
|
|
245
|
+
r, w = self.tp["rank"], self.tp["world"]
|
|
246
|
+
self.head_shard = W.get(spec["head"], shard=(0, r, w)) if w > 1 else W.get(spec["head"])
|
|
247
|
+
# `head` is what the core's proposers multiply by (blocks.LINEAR(h, m.head)): a vocab-sharded head that
|
|
248
|
+
# all-gathers, so every rank sees the same full-vocabulary logits (identical drafts on every rank)
|
|
249
|
+
self.head = _GatherHead(self.head_shard, self.g) if w > 1 else self.head_shard
|
|
250
|
+
self.fnorm = W.get(spec["final_norm"])
|
|
251
|
+
rng = range(len(spec["layers"])) if layers is None else layers
|
|
252
|
+
# layers are read concurrently (I/O bound; each expert set uses its own reader threads); collectives
|
|
253
|
+
# (EP -> TP expert re-layout) run afterwards in layer order on every rank
|
|
254
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
255
|
+
dev = torch.cuda.current_device()
|
|
256
|
+
done = [0]
|
|
257
|
+
|
|
258
|
+
def build(i):
|
|
259
|
+
torch.cuda.set_device(dev)
|
|
260
|
+
Ly = PLayer(spec["layers"][i], W, self.g, i)
|
|
261
|
+
done[0] += 1
|
|
262
|
+
if verbose and self.tp["rank"] == 0 and done[0] % 8 == 0:
|
|
263
|
+
print(f" {done[0]} layers loaded {time.time() - t0:.0f}s mem {torch.cuda.memory_allocated() / 1e9:.1f} GB",
|
|
264
|
+
flush=True)
|
|
265
|
+
return Ly
|
|
266
|
+
with ThreadPoolExecutor(LAYER_THREADS) as ex:
|
|
267
|
+
self.layers = list(ex.map(build, list(rng)))
|
|
268
|
+
self.read_s = time.time() - t0
|
|
269
|
+
for Ly in self.layers:
|
|
270
|
+
if getattr(Ly.mlp, "_pending_tp", None):
|
|
271
|
+
Ly.mlp.ex.ep_to_tp(Ly.mlp._pending_tp)
|
|
272
|
+
Ly.mlp._pending_tp = None
|
|
273
|
+
torch.cuda.empty_cache()
|
|
274
|
+
self.residual = spec["residual"]
|
|
275
|
+
if self.residual == "attn_res":
|
|
276
|
+
self.ablock = spec["ares_block"]
|
|
277
|
+
ao = spec["ares_out"]
|
|
278
|
+
self.ares_out = W.get(ao["n"]).float() * W.get(ao["p"]).float().reshape(-1)
|
|
279
|
+
self.mtp = None
|
|
280
|
+
if load_mtp and spec.get("mtp"):
|
|
281
|
+
from model import MTPHead
|
|
282
|
+
self.mtp = MTPHead(spec["mtp"], W, self)
|
|
283
|
+
for Ly in self.mtp.layers:
|
|
284
|
+
if getattr(Ly.mlp, "_pending_tp", None):
|
|
285
|
+
Ly.mlp.ex.ep_to_tp(Ly.mlp._pending_tp)
|
|
286
|
+
Ly.mlp._pending_tp = None
|
|
287
|
+
W.close()
|
|
288
|
+
torch.cuda.empty_cache()
|
|
289
|
+
self.d, self.V = spec["d"], spec["vocab"]
|
|
290
|
+
self.load_s = time.time() - t0
|
|
291
|
+
self.alloc(B, smax)
|
|
292
|
+
|
|
293
|
+
# ---- state
|
|
294
|
+
def alloc(self, B, smax):
|
|
295
|
+
self.B, self.smax = B, smax
|
|
296
|
+
for L in self.layers:
|
|
297
|
+
L.mix.alloc(B, smax)
|
|
298
|
+
if self.mtp:
|
|
299
|
+
self.mtp.alloc(B, smax)
|
|
300
|
+
|
|
301
|
+
def reset(self, b=None):
|
|
302
|
+
for L in self.layers:
|
|
303
|
+
L.mix.reset(b)
|
|
304
|
+
if self.mtp:
|
|
305
|
+
for L in self.mtp.layers:
|
|
306
|
+
L.mix.reset(b)
|
|
307
|
+
|
|
308
|
+
def blocks(self):
|
|
309
|
+
return [L.mix for L in self.layers]
|
|
310
|
+
|
|
311
|
+
def fork(self, src, dst, L):
|
|
312
|
+
"""copy user src's committed state (positions < L) into users dst: one prefill, many worlds."""
|
|
313
|
+
for Ly in self.layers:
|
|
314
|
+
m = Ly.mix
|
|
315
|
+
if hasattr(m, "cache"):
|
|
316
|
+
m.fork(src, dst, L)
|
|
317
|
+
else:
|
|
318
|
+
m.fork(src, dst)
|
|
319
|
+
|
|
320
|
+
def weight_bytes(self):
|
|
321
|
+
n = 0
|
|
322
|
+
for L in self.layers:
|
|
323
|
+
for blk in (L.mix, L.mlp):
|
|
324
|
+
for v in blk.weights().values():
|
|
325
|
+
n += v.numel() * v.element_size() if isinstance(v, torch.Tensor) else v.nbytes()
|
|
326
|
+
if hasattr(L.mlp, "ex"):
|
|
327
|
+
n += L.mlp.ex.nbytes()
|
|
328
|
+
return n
|
|
329
|
+
|
|
330
|
+
def state_bytes(self):
|
|
331
|
+
return sum(L.mix.state_bytes() for L in self.layers)
|
|
332
|
+
|
|
333
|
+
# ---- forward
|
|
334
|
+
def _stack(self, x, ctx, fn):
|
|
335
|
+
AR = PB.all_reduce
|
|
336
|
+
if self.residual == "standard":
|
|
337
|
+
if PB.FAST and x.dtype == BF:
|
|
338
|
+
from kernels import rms_fused # residual add + RMSNorm in one kernel (x updated in place)
|
|
339
|
+
x = x.contiguous().clone()
|
|
340
|
+
pend = None
|
|
341
|
+
for L in self.layers:
|
|
342
|
+
h = rms_fused(x, L.n1, L.eps, L.off, y=pend)
|
|
343
|
+
a = AR(getattr(L.mix, fn)(h, ctx), self.g)
|
|
344
|
+
h2 = rms_fused(x, L.n2, L.eps, L.off, y=a)
|
|
345
|
+
pend = AR(L.mlp(h2), self.g)
|
|
346
|
+
return x + pend
|
|
347
|
+
for L in self.layers:
|
|
348
|
+
x = x + AR(getattr(L.mix, fn)(rms(x, L.n1, L.eps, L.off), ctx), self.g)
|
|
349
|
+
x = x + AR(L.mlp(rms(x, L.n2, L.eps, L.off)), self.g)
|
|
350
|
+
return x
|
|
351
|
+
# attn_res (reference: KimiDecoderLayer._forward_attn_residual)
|
|
352
|
+
blocks_ = []
|
|
353
|
+
prefix = x
|
|
354
|
+
for L in self.layers:
|
|
355
|
+
h = _ares(prefix, blocks_, L.ares[0], L.eps) if blocks_ else prefix
|
|
356
|
+
if L.idx % self.ablock == 0:
|
|
357
|
+
blocks_.append(prefix)
|
|
358
|
+
prefix = None
|
|
359
|
+
a = AR(getattr(L.mix, fn)(rms(h, L.n1, L.eps, L.off), ctx), self.g)
|
|
360
|
+
prefix = a if prefix is None else prefix + a
|
|
361
|
+
h = _ares(prefix, blocks_, L.ares[1], L.eps)
|
|
362
|
+
m = AR(L.mlp(rms(h, L.n2, L.eps, L.off)), self.g)
|
|
363
|
+
prefix = prefix + m
|
|
364
|
+
return _ares(prefix, blocks_, self.ares_out, self.g["eps"])
|
|
365
|
+
|
|
366
|
+
def final(self, x):
|
|
367
|
+
return PB.rmsn(x, self.fnorm, self.g["eps"], self.g["norm_offset"])
|
|
368
|
+
|
|
369
|
+
def logits(self, h):
|
|
370
|
+
return PB.all_gather_last(F.linear(h, self.head_shard), self.g)
|
|
371
|
+
|
|
372
|
+
def draft_head(self, n):
|
|
373
|
+
"""vocab-truncated proposer head: only the first n token ids are draftable; verification still uses logits()."""
|
|
374
|
+
if not n or n >= self.V:
|
|
375
|
+
return self.head
|
|
376
|
+
w = self.tp["world"]
|
|
377
|
+
assert n % w == 0, (n, w)
|
|
378
|
+
if n not in self._draft_heads:
|
|
379
|
+
c = n // w
|
|
380
|
+
a = self.tp["rank"] * c
|
|
381
|
+
sub = self.Widx.get_row_range(self.head_name, a, a + c)
|
|
382
|
+
self._draft_heads[n] = _GatherHead(sub, self.g) if w > 1 else sub
|
|
383
|
+
return self._draft_heads[n]
|
|
384
|
+
|
|
385
|
+
@torch.no_grad()
|
|
386
|
+
def prefill(self, toks, b=0, pos0=0, chunk=8192, keep_hidden=True):
|
|
387
|
+
outs = []
|
|
388
|
+
T = toks.shape[0]
|
|
389
|
+
for s in range(0, T, chunk):
|
|
390
|
+
t = toks[s:s + chunk]
|
|
391
|
+
ctx = RowCtx("prefill", b=b, pos0=pos0 + s)
|
|
392
|
+
h = self.final(self._stack(self.embed[t], ctx, "prefill"))
|
|
393
|
+
outs.append(h if keep_hidden else h[-1:])
|
|
394
|
+
return torch.cat(outs, 0)
|
|
395
|
+
|
|
396
|
+
def tree(self, tok, ctx):
|
|
397
|
+
h = self.final(self._stack(self.embed[tok.reshape(-1)], ctx, "tree"))
|
|
398
|
+
return h
|
|
399
|
+
|
|
400
|
+
def commit(self, ctx):
|
|
401
|
+
for L in self.layers:
|
|
402
|
+
L.mix.commit(ctx)
|
package/p27/pref.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Lane P27: fp32 teacher-forced reference = the model's own HF implementation, on dequantised weights.
|
|
2
|
+
|
|
3
|
+
Generic: the decoder class is the text config's `architectures[0]`, found in the repo's *.py files (or in a pinned
|
|
4
|
+
modeling source dir when the checkpoint ships none - Kimi-K3.1-Pro: the K3 reference modeling pinned by
|
|
5
|
+
tiny-random/kimi-k3.1-pro). Quantised weights are decoded with quant.py's torch decoders (exact: mxfp4 values are
|
|
6
|
+
representable in fp32). Linear-attention kernels that would use tf32 dots are replaced by an fp32 recurrence
|
|
7
|
+
(naive_kda) - the same math in fp32, no tf32 (torch.backends.*.allow_tf32 = False).
|
|
8
|
+
|
|
9
|
+
full_ref(path) whole model on one GPU (tiny / small models)
|
|
10
|
+
streamed_ref(...) layer-streamed: one decoder layer module at a time, experts decoded on demand
|
|
11
|
+
"""
|
|
12
|
+
import glob
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import shutil
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
|
|
21
|
+
import quant as Q
|
|
22
|
+
|
|
23
|
+
torch.backends.cuda.matmul.allow_tf32 = False
|
|
24
|
+
torch.backends.cudnn.allow_tf32 = False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def naive_kda(q, k, v, g, beta, A_log=None, dt_bias=None, initial_state=None, output_final_state=True,
|
|
28
|
+
use_qk_l2norm_in_kernel=True, use_gate_in_kernel=False, use_beta_sigmoid_in_kernel=True,
|
|
29
|
+
safe_gate=False, lower_bound=None, transpose_state_layout=False, cu_seqlens=None, scale=None, **kw):
|
|
30
|
+
"""fp32 recurrence of fla's KDA (B, T, H, D) inputs; g = log decay per key channel (gate already applied)."""
|
|
31
|
+
assert not use_gate_in_kernel and cu_seqlens is None
|
|
32
|
+
B, T, H, K = q.shape
|
|
33
|
+
V = v.shape[-1]
|
|
34
|
+
q, k, v, g, beta = (x.double() for x in (q, k, v, g, beta))
|
|
35
|
+
if use_qk_l2norm_in_kernel:
|
|
36
|
+
q = q / torch.sqrt((q * q).sum(-1, keepdim=True) + 1e-6)
|
|
37
|
+
k = k / torch.sqrt((k * k).sum(-1, keepdim=True) + 1e-6)
|
|
38
|
+
if use_beta_sigmoid_in_kernel:
|
|
39
|
+
beta = torch.sigmoid(beta)
|
|
40
|
+
sc = scale if scale is not None else K ** -0.5
|
|
41
|
+
S = torch.zeros(B, H, K, V, dtype=torch.float64, device=q.device)
|
|
42
|
+
if initial_state is not None:
|
|
43
|
+
S = initial_state.double().clone()
|
|
44
|
+
if transpose_state_layout:
|
|
45
|
+
S = S.transpose(-1, -2)
|
|
46
|
+
o = torch.empty(B, T, H, V, dtype=torch.float64, device=q.device)
|
|
47
|
+
for t in range(T):
|
|
48
|
+
S = S * torch.exp(g[:, t])[..., None]
|
|
49
|
+
u = beta[:, t][..., None] * (v[:, t] - torch.einsum("bhkv,bhk->bhv", S, k[:, t]))
|
|
50
|
+
S = S + k[:, t][..., None] * u[..., None, :]
|
|
51
|
+
o[:, t] = torch.einsum("bhkv,bhk->bhv", S, q[:, t] * sc)
|
|
52
|
+
st = S.transpose(-1, -2) if transpose_state_layout else S
|
|
53
|
+
return o.to(torch.float32), (st.to(torch.float32) if output_final_state else None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def find_arch_module(srcdir, arch):
|
|
57
|
+
for f in sorted(glob.glob(os.path.join(srcdir, "*.py"))):
|
|
58
|
+
if re.search(rf"^class {arch}\(", open(f).read(), re.M):
|
|
59
|
+
return os.path.splitext(os.path.basename(f))[0]
|
|
60
|
+
raise FileNotFoundError(f"class {arch} not found in {srcdir}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def ref_repo(path, modeling_src=None):
|
|
64
|
+
"""A directory holding the checkpoint's config + code (+ pinned modeling files if the checkpoint has none)."""
|
|
65
|
+
d = f"/tmp/refrepo_{abs(hash(path)) % 10**8}"
|
|
66
|
+
os.makedirs(d, exist_ok=True)
|
|
67
|
+
for f in glob.glob(os.path.join(path, "*.py")) + [os.path.join(path, "config.json")]:
|
|
68
|
+
shutil.copy(f, d)
|
|
69
|
+
if modeling_src:
|
|
70
|
+
for f in glob.glob(os.path.join(modeling_src, "modeling_*.py")):
|
|
71
|
+
if not os.path.exists(os.path.join(d, os.path.basename(f))):
|
|
72
|
+
shutil.copy(f, d)
|
|
73
|
+
return d
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def ref_classes(path, modeling_src=None):
|
|
77
|
+
from transformers import AutoConfig
|
|
78
|
+
from transformers.dynamic_module_utils import get_class_from_dynamic_module
|
|
79
|
+
d = ref_repo(path, modeling_src)
|
|
80
|
+
cfg = AutoConfig.from_pretrained(d, trust_remote_code=True)
|
|
81
|
+
tc = getattr(cfg, "text_config", cfg)
|
|
82
|
+
arch = (tc.architectures or cfg.architectures)[0]
|
|
83
|
+
modname = find_arch_module(d, arch)
|
|
84
|
+
LM = get_class_from_dynamic_module(f"{modname}.{arch}", d)
|
|
85
|
+
mod = sys.modules[LM.__module__]
|
|
86
|
+
if hasattr(mod, "chunk_kda"):
|
|
87
|
+
mod.chunk_kda = naive_kda
|
|
88
|
+
mod.fused_recurrent_kda = naive_kda
|
|
89
|
+
for k in ("quantization_config",):
|
|
90
|
+
if hasattr(tc, k):
|
|
91
|
+
delattr(tc, k)
|
|
92
|
+
tc._attn_implementation = "eager"
|
|
93
|
+
return tc, LM, mod
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def deq(W, name, dtype=torch.float32, device="cuda"):
|
|
97
|
+
"""weight `name` (…weight) decoded exactly to dtype, whatever its published code."""
|
|
98
|
+
base = name[:-len(".weight")] if name.endswith(".weight") else name
|
|
99
|
+
if W.has(base + ".weight_packed"):
|
|
100
|
+
return Q.mxfp4_dequant(W.get(base + ".weight_packed", device=device), W.get(base + ".weight_scale",
|
|
101
|
+
device=device), dtype)
|
|
102
|
+
if W.has(base + ".weight_scale_inv"):
|
|
103
|
+
return Q.fp8blk_dequant(W.get(name, device=device), W.get(base + ".weight_scale_inv", device=device), dtype)
|
|
104
|
+
return W.get(name, device=device).to(dtype)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _lm_prefix(W, head_key):
|
|
108
|
+
return head_key[:-len("lm_head.weight")]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def full_ref(path, modeling_src=None, device="cuda"):
|
|
112
|
+
from adapter import WeightIndex
|
|
113
|
+
tc, LM, mod = ref_classes(path, modeling_src)
|
|
114
|
+
torch.set_default_dtype(torch.float32)
|
|
115
|
+
with torch.device("meta"):
|
|
116
|
+
m = LM(tc)
|
|
117
|
+
W = WeightIndex(path)
|
|
118
|
+
head = [k for k in W.map if k.endswith("lm_head.weight")][0]
|
|
119
|
+
pre = _lm_prefix(W, head)
|
|
120
|
+
sd = {}
|
|
121
|
+
names = set()
|
|
122
|
+
for k in W.map:
|
|
123
|
+
if not k.startswith(pre):
|
|
124
|
+
continue
|
|
125
|
+
k2 = k[len(pre):]
|
|
126
|
+
if k2.endswith(".weight_scale") or k2.endswith(".weight_scale_inv"):
|
|
127
|
+
continue
|
|
128
|
+
if k2.endswith(".weight_packed"):
|
|
129
|
+
k2 = k2[:-len("_packed")]
|
|
130
|
+
k = k[:-len("_packed")]
|
|
131
|
+
names.add((k2, k))
|
|
132
|
+
for k2, k in names:
|
|
133
|
+
sd[k2] = deq(W, k, torch.float32, device)
|
|
134
|
+
m = m.to_empty(device=device)
|
|
135
|
+
missing, unexpected = m.load_state_dict(sd, strict=False)
|
|
136
|
+
m.eval()
|
|
137
|
+
return m, {"missing": [x for x in missing if "indexer" not in x][:20], "unexpected": unexpected[:20],
|
|
138
|
+
"ignored_indexer": [x for x in sd if "indexer" in x][:3]}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@torch.no_grad()
|
|
142
|
+
def ref_logits(m, ids):
|
|
143
|
+
"""ids (T,) -> fp32 logits (T, V), teacher forced, no cache."""
|
|
144
|
+
out = m(input_ids=ids[None], use_cache=False)
|
|
145
|
+
return out.logits[0].float()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def gaps(logits, toks):
|
|
149
|
+
"""certificate: gap[t] = max_v z[t, v] - z[t, toks[t]] for the token emitted at row t."""
|
|
150
|
+
z = logits.float()
|
|
151
|
+
return (z.max(-1).values - z.gather(1, toks[:, None].long())[:, 0])
|
package/p27/prof_glm.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""CUDA-profile a captured GLM speculative decode pass; rank 0 returns the top kernels/ops."""
|
|
2
|
+
import time
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main(rank=0, world=1, model="/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844",
|
|
7
|
+
reps=3, fast=True, ar32=True, align_triton=True, D=3, C=8, E=0, EW=1, W=1):
|
|
8
|
+
import pmodel
|
|
9
|
+
import pblocks as PB
|
|
10
|
+
import quant as Q
|
|
11
|
+
import spec as SP
|
|
12
|
+
PB.FAST = fast
|
|
13
|
+
PB.AR32 = ar32
|
|
14
|
+
Q.ALIGN_TRITON = align_triton
|
|
15
|
+
t0 = time.time()
|
|
16
|
+
tp = {"rank": rank, "world": world, "group": None}
|
|
17
|
+
m = pmodel.PModel(model, B=1, smax=512, tp=tp, expert_shard="ep_tp", verbose=(rank == 0))
|
|
18
|
+
eng = SP.SpecEngine(m, D=D, C=C, W=W, T=0.0, E=E, EW=EW)
|
|
19
|
+
ids = torch.randint(100, 100000, (64,), generator=torch.Generator().manual_seed(0)).tolist()
|
|
20
|
+
eng.capture(use_graph=True)
|
|
21
|
+
out = eng.generate(ids, 8)
|
|
22
|
+
torch.cuda.synchronize()
|
|
23
|
+
from torch.profiler import profile, ProfilerActivity
|
|
24
|
+
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
|
|
25
|
+
for _ in range(reps):
|
|
26
|
+
eng.graph.replay()
|
|
27
|
+
torch.cuda.synchronize()
|
|
28
|
+
rows = []
|
|
29
|
+
for e in prof.key_averages():
|
|
30
|
+
ct = getattr(e, 'device_time_total', 0) or getattr(e, 'cuda_time_total', 0)
|
|
31
|
+
rows.append({"key": e.key[:160], "count": e.count, "cuda_ms": ct / 1000, "cpu_ms": e.cpu_time_total / 1000})
|
|
32
|
+
rows.sort(key=lambda x: x["cuda_ms"], reverse=True)
|
|
33
|
+
return {"load_s": time.time() - t0, "tok_per_pass": out.get("tok_per_pass"), "top": rows[:80],
|
|
34
|
+
"total_cuda_ms": sum(x["cuda_ms"] for x in rows)}
|