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
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
"""Declarative model adapter: HF config.json + safetensors index -> ModelSpec (a list of generic blocks).
|
|
2
|
+
|
|
3
|
+
Nothing in the engine core branches on a model name. The adapter infers the layer structure from the config and
|
|
4
|
+
the weight names; the only per-family data is FAMILY below (facts that are not in config.json, e.g. that Qwen3.5's
|
|
5
|
+
RMSNorm multiplies by (1 + w)). A new model of a supported family needs no code; a new layer type is one block in
|
|
6
|
+
blocks.py registered with @register.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
# facts not stated in config.json, keyed by HF model_type (data, not code paths)
|
|
14
|
+
FAMILY = {
|
|
15
|
+
"qwen3_5": {"norm_offset": 1.0, "mtp": {"prefix": "mtp.", "fc": "fc", "norm_emb": "pre_fc_norm_embedding",
|
|
16
|
+
"norm_hid": "pre_fc_norm_hidden", "norm": "norm", "layers": "layers"}},
|
|
17
|
+
"qwen3_5_text": "qwen3_5",
|
|
18
|
+
"qwen3_next": "qwen3_5",
|
|
19
|
+
"qwen3_5_moe": "qwen3_5",
|
|
20
|
+
"qwen3_5_moe_text": "qwen3_5",
|
|
21
|
+
"qwen3": {"norm_offset": 0.0},
|
|
22
|
+
"llama": {"norm_offset": 0.0},
|
|
23
|
+
"mistral": {"norm_offset": 0.0},
|
|
24
|
+
"qwen2": {"norm_offset": 0.0},
|
|
25
|
+
"gemma": {"norm_offset": 1.0, "embed_sqrt": True},
|
|
26
|
+
"gemma2": {"norm_offset": 1.0, "embed_sqrt": True},
|
|
27
|
+
"gemma3_text": {"norm_offset": 1.0, "embed_sqrt": True},
|
|
28
|
+
"olmo2": {"norm_offset": 0.0},
|
|
29
|
+
"granite": {"norm_offset": 0.0},
|
|
30
|
+
"phi3": {"norm_offset": 0.0},
|
|
31
|
+
"cohere2": {"norm_offset": 0.0, "norm": "layer", "rope_interleave": True, "parallel": True, "nope_full": True},
|
|
32
|
+
"starcoder2": {"norm_offset": 0.0, "norm": "layer"},
|
|
33
|
+
"jamba": {"norm_offset": 0.0, "nope_all": True},
|
|
34
|
+
"glm4": {"norm_offset": 0.0, "rope_interleave": True},
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class WeightIndex:
|
|
39
|
+
"""name -> file over a HF snapshot directory (sharded or single safetensors)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, path):
|
|
42
|
+
self.path = path
|
|
43
|
+
idx = os.path.join(path, "model.safetensors.index.json")
|
|
44
|
+
if os.path.exists(idx):
|
|
45
|
+
wm = json.load(open(idx))["weight_map"]
|
|
46
|
+
else:
|
|
47
|
+
from safetensors import safe_open
|
|
48
|
+
f = "model.safetensors"
|
|
49
|
+
with safe_open(os.path.join(path, f), "pt") as h:
|
|
50
|
+
wm = {k: f for k in h.keys()}
|
|
51
|
+
self.map = wm
|
|
52
|
+
self._open = {}
|
|
53
|
+
self.scale = {} # name -> float or per-row list: multipliers folded into weights at load (muP, Falcon-H1)
|
|
54
|
+
|
|
55
|
+
def _scaled(self, name, t, shard):
|
|
56
|
+
sc = self.scale.get(name)
|
|
57
|
+
if sc is None:
|
|
58
|
+
return t
|
|
59
|
+
import torch
|
|
60
|
+
if not isinstance(sc, float):
|
|
61
|
+
if shard is not None and shard[2] > 1:
|
|
62
|
+
raise NotImplementedError(f"row-scaled weight {name} under sharding")
|
|
63
|
+
sc = torch.as_tensor(sc, dtype=torch.float32, device=t.device).view(-1, *([1] * (t.dim() - 1)))
|
|
64
|
+
Bk = sys.modules.get("blocks")
|
|
65
|
+
keep32 = Bk is not None and getattr(Bk, "ACT", None) == torch.float32 # f32a: no re-rounding to bf16
|
|
66
|
+
return t.float() * sc if keep32 else (t.float() * sc).to(t.dtype)
|
|
67
|
+
|
|
68
|
+
def has(self, name):
|
|
69
|
+
return name in self.map
|
|
70
|
+
|
|
71
|
+
def get(self, name, device=None, shard=None):
|
|
72
|
+
"""shard=(dim, rank, world): only that rank's contiguous slice along dim is read."""
|
|
73
|
+
from safetensors import safe_open
|
|
74
|
+
from dev import DEV, CUDA
|
|
75
|
+
if device is None: # P27 R1: the current CUDA device of this rank, not cuda:0
|
|
76
|
+
import torch
|
|
77
|
+
device = f"cuda:{torch.cuda.current_device()}" if CUDA else DEV
|
|
78
|
+
f = self.map[name]
|
|
79
|
+
key = (f, device)
|
|
80
|
+
if key not in self._open:
|
|
81
|
+
self._open[key] = safe_open(os.path.join(self.path, f), "pt", device=device)
|
|
82
|
+
h = self._open[key]
|
|
83
|
+
if shard is None or shard[2] == 1:
|
|
84
|
+
return self._scaled(name, h.get_tensor(name), shard)
|
|
85
|
+
dim, rank, world = shard
|
|
86
|
+
sl = h.get_slice(name)
|
|
87
|
+
n = sl.get_shape()[dim]
|
|
88
|
+
assert n % world == 0, (name, n, world)
|
|
89
|
+
c = n // world
|
|
90
|
+
idx = [slice(None)] * len(sl.get_shape())
|
|
91
|
+
idx[dim] = slice(rank * c, (rank + 1) * c)
|
|
92
|
+
return self._scaled(name, sl[tuple(idx)].to(device), shard)
|
|
93
|
+
|
|
94
|
+
def get_row_range(self, name, a, b, device=None):
|
|
95
|
+
"""rows [a, b) of a 2-D weight, regardless of the full-tensor TP sharding."""
|
|
96
|
+
from safetensors import safe_open
|
|
97
|
+
from dev import DEV, CUDA
|
|
98
|
+
if device is None:
|
|
99
|
+
import torch
|
|
100
|
+
device = f"cuda:{torch.cuda.current_device()}" if CUDA else DEV
|
|
101
|
+
f = self.map[name]
|
|
102
|
+
key = (f, device)
|
|
103
|
+
if key not in self._open:
|
|
104
|
+
self._open[key] = safe_open(os.path.join(self.path, f), "pt", device=device)
|
|
105
|
+
sl = self._open[key].get_slice(name)
|
|
106
|
+
return self._scaled(name, sl[a:b].to(device), None)
|
|
107
|
+
|
|
108
|
+
def close(self):
|
|
109
|
+
self._open = {}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
RULES = []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def register_rule(fn):
|
|
116
|
+
"""fn(tc, W, layer_prefix, layer_index, layer_type) -> {"mixer": spec?, "mlp": spec?} or None. Plug-ins (MoE,
|
|
117
|
+
MLA, Mamba ...) add inference rules here instead of editing the core; rules run before the built-in ones."""
|
|
118
|
+
RULES.append(fn)
|
|
119
|
+
return fn
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _family(mt):
|
|
123
|
+
f = FAMILY.get(mt, {"norm_offset": 0.0})
|
|
124
|
+
while isinstance(f, str):
|
|
125
|
+
f = FAMILY[f]
|
|
126
|
+
return f
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def build_spec(path):
|
|
130
|
+
"""Returns (spec dict, WeightIndex). spec: d, vocab, eps, norm_offset, rope, prefix, layers[...], mtp."""
|
|
131
|
+
cfg = json.load(open(os.path.join(path, "config.json")))
|
|
132
|
+
top_mt = cfg.get("model_type")
|
|
133
|
+
tc = cfg.get("text_config", cfg)
|
|
134
|
+
mt = tc.get("model_type", top_mt)
|
|
135
|
+
fam = _family(top_mt) if top_mt in FAMILY else _family(mt)
|
|
136
|
+
W = WeightIndex(path)
|
|
137
|
+
# weight prefix of the decoder stack: the key that precedes "layers.0."
|
|
138
|
+
pre = None
|
|
139
|
+
for k in W.map:
|
|
140
|
+
m = re.match(r"(.*?)layers\.0\.", k)
|
|
141
|
+
if m and not k.startswith("mtp.") and "visual" not in k and "vision" not in k:
|
|
142
|
+
if pre is None or len(m.group(1)) < len(pre):
|
|
143
|
+
pre = m.group(1)
|
|
144
|
+
nl = tc["num_hidden_layers"]
|
|
145
|
+
d = tc["hidden_size"]
|
|
146
|
+
hd = tc.get("head_dim") or d // tc.get("num_attention_heads", 1)
|
|
147
|
+
rp = tc.get("rope_parameters") or {}
|
|
148
|
+
# per-layer-type RoPE (Gemma 3: rope_parameters = {"full_attention": {...}, "sliding_attention": {...}})
|
|
149
|
+
rope_per = {k: v for k, v in rp.items() if isinstance(v, dict)}
|
|
150
|
+
if rope_per:
|
|
151
|
+
if any((v.get("rope_type") or "default") != "default" for v in rope_per.values()):
|
|
152
|
+
raise NotImplementedError("per-layer-type RoPE with non-default rope_type")
|
|
153
|
+
rp = rope_per.get("full_attention") or next(iter(rope_per.values()))
|
|
154
|
+
theta = rp.get("rope_theta", tc.get("rope_theta", 10000.0))
|
|
155
|
+
prf = rp.get("partial_rotary_factor", tc.get("partial_rotary_factor", 1.0))
|
|
156
|
+
rope = {"theta": float(theta), "rot": int(tc.get("rotary_dim") or hd * prf), "hd": hd}
|
|
157
|
+
if fam.get("rope_interleave"):
|
|
158
|
+
rope["interleave"] = True
|
|
159
|
+
rs = tc.get("rope_scaling") or {}
|
|
160
|
+
rtype = rp.get("rope_type") or rs.get("rope_type") or rs.get("type") or "default"
|
|
161
|
+
if rtype != "default":
|
|
162
|
+
# any HF RoPE variant (llama3, yarn, linear, longrope ...): inv_freq + attention scale from transformers' own
|
|
163
|
+
# init function on this config -- the same numbers the HF reference uses. "dynamic" depends on the live
|
|
164
|
+
# sequence length and is refused.
|
|
165
|
+
if rtype == "dynamic":
|
|
166
|
+
raise NotImplementedError("dynamic NTK RoPE (sequence-length dependent) not supported")
|
|
167
|
+
rope.update(_hf_rope(path, rtype))
|
|
168
|
+
_guard_config(tc)
|
|
169
|
+
ltypes = tc.get("layer_types") or ["full_attention"] * nl
|
|
170
|
+
# NoPE layers (SmolLM3 / Llama-4 style): rope off on some layers (T27 BUG-016)
|
|
171
|
+
nope = tc.get("no_rope_layers")
|
|
172
|
+
if nope is None and tc.get("no_rope_layer_interval"):
|
|
173
|
+
iv = tc["no_rope_layer_interval"]
|
|
174
|
+
nope = [int((i + 1) % iv != 0) for i in range(nl)]
|
|
175
|
+
layers = []
|
|
176
|
+
for i in range(nl):
|
|
177
|
+
lp = f"{pre}layers.{i}."
|
|
178
|
+
L = {"prefix": lp}
|
|
179
|
+
for fn in RULES:
|
|
180
|
+
r = fn(tc, W, lp, i, ltypes[i])
|
|
181
|
+
if r:
|
|
182
|
+
L.update(r)
|
|
183
|
+
if "mixer" in L:
|
|
184
|
+
pass
|
|
185
|
+
elif W.has(lp + "mixer.A_log") or W.has(lp + "mamba.A_log"): # Mamba / Mamba-2 / Jamba selective SSM
|
|
186
|
+
mp = lp + ("mixer." if W.has(lp + "mixer.A_log") else "mamba.")
|
|
187
|
+
if tc.get("use_bias") or tc.get("mamba_proj_bias"):
|
|
188
|
+
raise NotImplementedError("mamba in_proj/out_proj bias")
|
|
189
|
+
v2 = W.has(mp + "dt_bias")
|
|
190
|
+
L["mixer"] = {"type": "ssm", "prefix": mp, "version": 2 if v2 else 1,
|
|
191
|
+
"state": W.get(mp + "A_log").shape[-1] if not v2 else tc.get("state_size", tc.get("mamba_d_state")),
|
|
192
|
+
"conv": W.get(mp + "conv1d.weight").shape[-1],
|
|
193
|
+
"eps": tc.get("layer_norm_epsilon", tc.get("rms_norm_eps", 1e-5)),
|
|
194
|
+
"d_inner": W.get(mp + "out_proj.weight").shape[1],
|
|
195
|
+
"dt_rank": W.get(mp + "dt_proj.weight").shape[1] if not v2 else None,
|
|
196
|
+
"heads": W.get(mp + "A_log").shape[0] if v2 else None,
|
|
197
|
+
"groups": tc.get("n_groups", tc.get("mamba_n_groups", 1)),
|
|
198
|
+
"dt_limit": [float(t["__float__"] if isinstance(t, dict) else t)
|
|
199
|
+
for t in (tc.get("time_step_limit") or (0.0, float("inf")))],
|
|
200
|
+
"names": sorted(k for k in W.map if k.startswith(mp))}
|
|
201
|
+
if v2: # gated norm order: Mamba-2 norm(y*silu(z)); Falcon-H1 norm(y)*silu(z) or no norm, y*silu(z)
|
|
202
|
+
rn = tc.get("mamba_rms_norm", True)
|
|
203
|
+
L["mixer"]["gate"] = ("gate" if not rn else "norm_gate" if tc.get("mamba_norm_before_gate")
|
|
204
|
+
else "gate_norm")
|
|
205
|
+
L["mixer"]["norm_groups"] = tc.get("mamba_n_groups", 1) if "mamba_n_groups" in tc else 1
|
|
206
|
+
if W.has(lp + "self_attn.q_proj.weight"): # attention + SSM on the same normed input, summed (Falcon-H1)
|
|
207
|
+
ssm = L["mixer"]
|
|
208
|
+
ap = lp + "self_attn."
|
|
209
|
+
att = _attn_spec(tc, W, ap, rope, ltypes[i])
|
|
210
|
+
L["mixer"] = {"type": "par_mix", "parts": [att, ssm], "prefix": lp,
|
|
211
|
+
"names": sorted(k for k in W.map if k.startswith(ap)) + ssm["names"]}
|
|
212
|
+
# muP multipliers folded into the weights they scale (exact in fp32: every projection is bias-free)
|
|
213
|
+
ain = float(tc.get("attention_in_multiplier", 1.0))
|
|
214
|
+
for n, m in (("q_proj", ain), ("k_proj", ain * float(tc.get("key_multiplier", 1.0))),
|
|
215
|
+
("v_proj", ain), ("o_proj", float(tc.get("attention_out_multiplier", 1.0)))):
|
|
216
|
+
if m != 1.0:
|
|
217
|
+
W.scale[ap + n + ".weight"] = m
|
|
218
|
+
if tc.get("projectors_bias") or tc.get("attention_bias"):
|
|
219
|
+
raise NotImplementedError("Falcon-H1 projector / attention biases")
|
|
220
|
+
sm = tc.get("ssm_multipliers") or [1.0] * 5
|
|
221
|
+
si = float(tc.get("ssm_in_multiplier", 1.0))
|
|
222
|
+
di, gn, nh = ssm["d_inner"], ssm["groups"] * ssm["state"], ssm["heads"]
|
|
223
|
+
vec = [m * si for m, n in zip(sm, (di, di, gn, gn, nh)) for _ in range(n)]
|
|
224
|
+
if any(v != 1.0 for v in vec):
|
|
225
|
+
W.scale[mp + "in_proj.weight"] = vec
|
|
226
|
+
so = float(tc.get("ssm_out_multiplier", 1.0))
|
|
227
|
+
if so != 1.0:
|
|
228
|
+
W.scale[mp + "out_proj.weight"] = so
|
|
229
|
+
mm = tc.get("mlp_multipliers") or [1.0, 1.0]
|
|
230
|
+
for n, m in (("gate_proj", mm[0]), ("down_proj", mm[1])):
|
|
231
|
+
if m != 1.0:
|
|
232
|
+
W.scale[lp + "feed_forward." + n + ".weight"] = float(m)
|
|
233
|
+
if W.has(lp + "norm.weight"): # pure Mamba block: norm -> mixer -> residual, no MLP
|
|
234
|
+
L["mlp"] = {"type": "none", "prefix": lp + "mlp.", "names": []}
|
|
235
|
+
L["norm1"], L["norm2"] = lp + "norm.weight", None
|
|
236
|
+
elif W.has(lp + "linear_attn.in_proj_qkv.weight") or W.has(lp + "linear_attn.in_proj_qkvz.weight"):
|
|
237
|
+
L["mixer"] = {"type": "gdn", "prefix": lp + "linear_attn.", "hk": tc["linear_num_key_heads"],
|
|
238
|
+
"hv": tc["linear_num_value_heads"], "dk": tc["linear_key_head_dim"],
|
|
239
|
+
"dv": tc["linear_value_head_dim"], "conv": tc["linear_conv_kernel_dim"],
|
|
240
|
+
"eps": tc["rms_norm_eps"]}
|
|
241
|
+
elif W.has(lp + "self_attn.q_proj.weight") or W.has(lp + "self_attn.qkv_proj.weight"):
|
|
242
|
+
r_i = rope if (nope is None or nope[i]) else {**rope, "rot": 0, "type": "nope"}
|
|
243
|
+
if fam.get("nope_all"): # no positional encoding at all (Jamba)
|
|
244
|
+
r_i = {**rope, "rot": 0, "type": "nope"}
|
|
245
|
+
if fam.get("nope_full") and ltypes[i] == "full_attention": # Cohere 2: RoPE on sliding layers only
|
|
246
|
+
r_i = {**rope, "rot": 0, "type": "nope"}
|
|
247
|
+
if rope_per.get(ltypes[i]) and r_i is rope:
|
|
248
|
+
r_i = {**rope, "theta": float(rope_per[ltypes[i]]["rope_theta"])}
|
|
249
|
+
L["mixer"] = _attn_spec(tc, W, lp + "self_attn.", r_i, ltypes[i])
|
|
250
|
+
if W.has(lp + "self_attn.indexer.q_proj.weight"): # lightning-indexer block-sparse attention (MiniMax-M3)
|
|
251
|
+
L["mixer"]["indexer"] = {"nh": tc["index_n_heads"], "hd": tc["index_head_dim"],
|
|
252
|
+
"block": tc["index_block_size"], "topk": tc["index_topk_blocks"],
|
|
253
|
+
"local": tc.get("index_local_blocks", 0)}
|
|
254
|
+
elif W.has(lp + "attn.wkv.weight") and W.has(lp + "attn.wo_a.weight"): # DeepSeek-V4 layer
|
|
255
|
+
ap, fp = lp + "attn.", lp + "ffn."
|
|
256
|
+
cr_leg = tc.get("compress_ratios") # legacy per-layer ints (published V4 checkpoints): 0 / 4 / 128
|
|
257
|
+
lt = (tc.get("layer_types") or [{0: "sliding_attention", 4: "compressed_sparse_attention",
|
|
258
|
+
128: "heavily_compressed_attention"}[r] for r in cr_leg])[i]
|
|
259
|
+
rpl = rope_per.get("main" if lt == "sliding_attention" else "compress") or {}
|
|
260
|
+
cr = ({"compressed_sparse_attention": 4, "heavily_compressed_attention": 128}
|
|
261
|
+
| (tc.get("compress_rates") or {})).get(lt)
|
|
262
|
+
L["mixer"] = {"type": "ds4_attn", "prefix": ap, "nh": tc["num_attention_heads"], "hd": hd,
|
|
263
|
+
"eps": tc["rms_norm_eps"], "window": tc["sliding_window"], "rate": cr,
|
|
264
|
+
"csa": W.has(ap + "indexer.wq_b.weight"),
|
|
265
|
+
"theta": float(rpl.get("rope_theta", theta)),
|
|
266
|
+
"ctheta": float((rope_per.get("compress") or {}).get("rope_theta",
|
|
267
|
+
tc.get("compress_rope_theta", theta))),
|
|
268
|
+
"rot": int(hd * rpl.get("partial_rotary_factor", prf)), "groups": tc["o_groups"],
|
|
269
|
+
"ihd": tc.get("index_head_dim"), "itopk": tc.get("index_topk"),
|
|
270
|
+
"names": sorted(k for k in W.map if k.startswith(ap))}
|
|
271
|
+
if bool(cr) != W.has(ap + "compressor.wkv.weight"):
|
|
272
|
+
raise NotImplementedError(f"layer {i}: layer type {lt} vs compressor weights disagree")
|
|
273
|
+
nh_ = tc.get("num_hash_layers", 3) # HF DeepseekV4Config: first num_hash_layers (default 3) hash-routed
|
|
274
|
+
hashed = (tc.get("mlp_layer_types") or ["hash_moe"] * nh_ + ["moe"] * nl)[i] == "hash_moe"
|
|
275
|
+
if hashed != W.has(fp + "gate.tid2eid"):
|
|
276
|
+
raise NotImplementedError(f"layer {i}: mlp_layer_types vs gate.tid2eid disagree")
|
|
277
|
+
L["mlp"] = {"type": "moe_ds4", "prefix": fp, "E": tc["n_routed_experts"], "top_k": tc["num_experts_per_tok"],
|
|
278
|
+
"score": tc.get("scoring_func", "softmax"), "hash": hashed,
|
|
279
|
+
"routed_scale": float(tc.get("routed_scaling_factor") or 1.0),
|
|
280
|
+
"limit": float(tc.get("swiglu_limit") or float("inf")),
|
|
281
|
+
"shared": W.has(fp + "shared_experts.w1.weight"),
|
|
282
|
+
"names": sorted(k for k in W.map if k.startswith(fp))}
|
|
283
|
+
if (tc.get("n_shared_experts") or 0) > 1:
|
|
284
|
+
raise NotImplementedError("more than one shared expert")
|
|
285
|
+
L["norm1"], L["norm2"] = lp + "attn_norm.weight", lp + "ffn_norm.weight"
|
|
286
|
+
L["hc"] = {"attn": lp + "hc_attn_", "ffn": lp + "hc_ffn_", "n": tc["hc_mult"],
|
|
287
|
+
"iters": tc["hc_sinkhorn_iters"], "eps": tc["hc_eps"],
|
|
288
|
+
"names": [lp + f"hc_{a}_{n}" for a in ("attn", "ffn") for n in ("fn", "base", "scale")]}
|
|
289
|
+
else:
|
|
290
|
+
raise NotImplementedError(f"layer {i}: unknown mixer ({lp}*)")
|
|
291
|
+
if "mlp" not in L:
|
|
292
|
+
L["mlp"] = _mlp_spec(tc, W, lp)
|
|
293
|
+
if L["mlp"] is None:
|
|
294
|
+
raise NotImplementedError(f"layer {i}: MoE / other MLP not implemented")
|
|
295
|
+
if W.has(lp + "pre_feedforward_layernorm.weight"): # sandwich norms (Gemma 2/3)
|
|
296
|
+
L.setdefault("norm1", lp + "input_layernorm.weight")
|
|
297
|
+
L.setdefault("post1", lp + "post_attention_layernorm.weight")
|
|
298
|
+
L.setdefault("norm2", lp + "pre_feedforward_layernorm.weight")
|
|
299
|
+
L.setdefault("post2", lp + "post_feedforward_layernorm.weight")
|
|
300
|
+
elif W.has(lp + "post_self_attn_layernorm.weight"): # GLM-4 sandwich
|
|
301
|
+
L.setdefault("norm1", lp + "input_layernorm.weight")
|
|
302
|
+
L.setdefault("post1", lp + "post_self_attn_layernorm.weight")
|
|
303
|
+
L.setdefault("norm2", lp + "post_attention_layernorm.weight")
|
|
304
|
+
L.setdefault("post2", lp + "post_mlp_layernorm.weight")
|
|
305
|
+
elif not W.has(lp + "input_layernorm.weight") and W.has(lp + "post_feedforward_layernorm.weight"):
|
|
306
|
+
L.setdefault("norm1", None) # post-norm only (OLMo 2)
|
|
307
|
+
L.setdefault("post1", lp + "post_attention_layernorm.weight")
|
|
308
|
+
L.setdefault("norm2", None)
|
|
309
|
+
L.setdefault("post2", lp + "post_feedforward_layernorm.weight")
|
|
310
|
+
if W.has(lp + "pre_ff_layernorm.weight"):
|
|
311
|
+
L.setdefault("norm2", lp + "pre_ff_layernorm.weight")
|
|
312
|
+
if fam.get("parallel"): # one input norm feeds attention and MLP: x + attn(n(x)) + mlp(n(x))
|
|
313
|
+
L.setdefault("norm1", lp + "input_layernorm.weight")
|
|
314
|
+
L.setdefault("norm2", None)
|
|
315
|
+
L["parallel"] = True
|
|
316
|
+
L.setdefault("norm1", lp + "input_layernorm.weight")
|
|
317
|
+
L.setdefault("norm2", lp + "post_attention_layernorm.weight")
|
|
318
|
+
L["extra"] = [n[:-len("weight")] + "bias" for n in (L.get("norm1"), L.get("norm2"), L.get("post1"),
|
|
319
|
+
L.get("post2")) if n and W.has(n[:-len("weight")] + "bias")]
|
|
320
|
+
L.setdefault("resid_mult", float(tc.get("residual_multiplier") or 1.0))
|
|
321
|
+
layers.append(L)
|
|
322
|
+
spec = {"d": d, "vocab": tc["vocab_size"], "eps": tc.get("rms_norm_eps", tc.get("layer_norm_epsilon")), "norm_offset": 1.0 if tc.get("use_gemma_norm") else fam["norm_offset"],
|
|
323
|
+
"rope": rope, "prefix": pre, "layers": layers, "embed": pre + ("embed_tokens.weight" if W.has(pre + "embed_tokens.weight") else "embeddings.weight"),
|
|
324
|
+
"final_norm": pre + next((n for n in ("norm.weight", "norm_f.weight", "final_layernorm.weight")
|
|
325
|
+
if W.has(pre + n)), "norm.weight"),
|
|
326
|
+
"head": "lm_head.weight" if W.has("lm_head.weight") else "head.weight" if W.has("head.weight") else pre + ("embed_tokens.weight" if W.has(pre + "embed_tokens.weight") else "embeddings.weight"),
|
|
327
|
+
"model_type": mt, "max_pos": tc.get("max_position_embeddings"),
|
|
328
|
+
"embed_scale": (d ** 0.5) if fam.get("embed_sqrt") else float(tc.get("embedding_multiplier") or 1.0),
|
|
329
|
+
"logit_div": float(tc.get("logits_scaling") or 1.0),
|
|
330
|
+
"logit_softcap": tc.get("final_logit_softcapping"),
|
|
331
|
+
"logit_mult": float(tc.get("logit_scale") or tc.get("lm_head_multiplier") or 1.0), # Cohere: logits * logit_scale
|
|
332
|
+
"norm_type": fam.get("norm", "rms"),
|
|
333
|
+
"final_norm_bias": pre + "norm.bias" if W.has(pre + "norm.bias") else None}
|
|
334
|
+
if W.has(pre + "hc_head.hc_fn"): # hyper-connection stream collapse before the final norm (DeepSeek-V4)
|
|
335
|
+
spec["hc_head"] = {"prefix": pre + "hc_head.", "n": tc["hc_mult"], "eps": tc["hc_eps"]}
|
|
336
|
+
if fam.get("norm") == "layer":
|
|
337
|
+
spec["eps"] = tc.get("layer_norm_eps", tc.get("norm_epsilon", tc.get("rms_norm_eps")))
|
|
338
|
+
nm = tc.get("mtp_num_hidden_layers", tc.get("num_nextn_predict_layers", 0)) or 0
|
|
339
|
+
if nm and "mtp" in fam and W.has(fam["mtp"]["prefix"] + fam["mtp"]["fc"] + ".weight"):
|
|
340
|
+
f = fam["mtp"]
|
|
341
|
+
p = f["prefix"]
|
|
342
|
+
ml = []
|
|
343
|
+
for i in range(nm):
|
|
344
|
+
lp = f"{p}{f['layers']}.{i}."
|
|
345
|
+
mlp = _mlp_spec(tc, W, lp) or {"type": "dense_glu", "prefix": lp + "mlp.", "act": tc.get("hidden_act", "silu")}
|
|
346
|
+
for fn in RULES: # plug-in MLPs (MoE MTP heads, e.g. Qwen3.6-A3B)
|
|
347
|
+
r = fn(tc, W, lp, nl + i, "full_attention") or {}
|
|
348
|
+
if r.get("mlp"):
|
|
349
|
+
mlp = r["mlp"]
|
|
350
|
+
break
|
|
351
|
+
ml.append({"prefix": lp, "mixer": _attn_spec(tc, W, lp + "self_attn.", rope, "full_attention"),
|
|
352
|
+
"mlp": mlp,
|
|
353
|
+
"norm1": lp + "input_layernorm.weight", "norm2": lp + "post_attention_layernorm.weight"})
|
|
354
|
+
spec["mtp"] = {"fc": p + f["fc"] + ".weight", "norm_emb": p + f["norm_emb"] + ".weight",
|
|
355
|
+
"norm_hid": p + f["norm_hid"] + ".weight", "norm": p + f["norm"] + ".weight", "layers": ml}
|
|
356
|
+
check_coverage(spec, W)
|
|
357
|
+
return spec, W
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _mlp_spec(tc, W, lp):
|
|
361
|
+
"""the MLP block of one layer from its weight names (shared by the main stack and MTP heads); None = unknown."""
|
|
362
|
+
M = None
|
|
363
|
+
# clamped SwiGLU (up+1) * g * sigmoid(alpha g), g <= limit, |up| <= limit (gpt-oss / MiniMax-M3)
|
|
364
|
+
clamp = [float(tc.get("swiglu_alpha", 1.702)), float(tc["swiglu_limit"])] if tc.get("swiglu_limit") else None
|
|
365
|
+
if W.has(lp + "mlp.router.weight") and (W.has(lp + "mlp.experts.gate_up_proj")
|
|
366
|
+
or W.has(lp + "mlp.experts.gate_up_proj_blocks")): # gpt-oss (dense | MXFP4)
|
|
367
|
+
mp = lp + "mlp."
|
|
368
|
+
M = {"type": "moe_oss", "prefix": mp, "top_k": tc["num_experts_per_tok"],
|
|
369
|
+
"alpha": float(tc.get("swiglu_alpha", 1.702)), "limit": float(tc.get("swiglu_limit", 7.0)),
|
|
370
|
+
"names": sorted(k for k in W.map if k.startswith(mp))}
|
|
371
|
+
elif W.has(lp + "mlp.gate.weight") and W.has(lp + "mlp.experts.gate_up_proj"): # fused 3-D experts, [gate|up]
|
|
372
|
+
mp = lp + "mlp."
|
|
373
|
+
M = {"type": "moe_fused", "prefix": mp, "top_k": tc["num_experts_per_tok"],
|
|
374
|
+
"sigmoid": tc.get("scoring_func", "softmax") == "sigmoid",
|
|
375
|
+
"norm": tc.get("norm_topk_prob") is not False, "routed_scale": float(tc.get("routed_scaling_factor") or 1.0),
|
|
376
|
+
"clamp": clamp, "names": sorted(k for k in W.map if k.startswith(mp))}
|
|
377
|
+
for sp in ("shared_experts.", "shared_expert."):
|
|
378
|
+
if W.has(mp + sp + "gate_up_proj.weight") or W.has(mp + sp + "gate_proj.weight"):
|
|
379
|
+
M["shared"] = {"type": "dense_glu", "prefix": mp + sp, "act": "silu", "clamp": clamp}
|
|
380
|
+
if W.has(mp + "shared_expert_gate.weight"): # sigmoid(x . g) * shared(x) (Qwen3.5/3.6-MoE)
|
|
381
|
+
M["shared_gate"] = mp + "shared_expert_gate.weight"
|
|
382
|
+
elif W.has(lp + "mlp.c_fc.weight"): # non-gated MLP (Starcoder 2)
|
|
383
|
+
mp = lp + "mlp."
|
|
384
|
+
M = {"type": "dense_mlp", "prefix": mp, "act": tc.get("hidden_act", "gelu_pytorch_tanh"),
|
|
385
|
+
"names": [mp + n for n in ("c_fc.weight", "c_proj.weight", "c_fc.bias", "c_proj.bias")
|
|
386
|
+
if W.has(mp + n)]}
|
|
387
|
+
elif W.has(lp + "feed_forward.gate_proj.weight"): # Jamba / Falcon-H1 naming
|
|
388
|
+
M = {"type": "dense_glu", "prefix": lp + "feed_forward.", "act": tc.get("hidden_act", "silu")}
|
|
389
|
+
elif W.has(lp + "mlp.gate_proj.weight") or W.has(lp + "mlp.gate_up_proj.weight"):
|
|
390
|
+
M = {"type": "dense_glu", "prefix": lp + "mlp.", "clamp": clamp,
|
|
391
|
+
"act": tc.get("hidden_act", tc.get("hidden_activation", "silu"))}
|
|
392
|
+
return M
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
UNSUPPORTED = { # config keys whose non-neutral value changes the computation in ways no block implements yet
|
|
396
|
+
"rope_local_base_freq": (None,), "mlp_bias": (None, False),
|
|
397
|
+
"use_qk_norm_in_gdn": (None, False), "normalize_embedding": (None, False),
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _guard_config(tc):
|
|
402
|
+
for k, ok in UNSUPPORTED.items():
|
|
403
|
+
if k in tc and tc[k] not in ok:
|
|
404
|
+
raise NotImplementedError(f"config {k}={tc[k]!r} not implemented by any block (refusing, not silent)")
|
|
405
|
+
act = tc.get("hidden_act", tc.get("hidden_activation", "silu"))
|
|
406
|
+
if act not in ACTS:
|
|
407
|
+
raise NotImplementedError(f"activation {act!r}")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
ACTS = ("silu", "gelu_pytorch_tanh", "gelu")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _hf_rope(path, rtype):
|
|
414
|
+
from transformers import AutoConfig
|
|
415
|
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
|
416
|
+
c = AutoConfig.from_pretrained(path)
|
|
417
|
+
c = getattr(c, "text_config", None) or c
|
|
418
|
+
inv, scale = ROPE_INIT_FUNCTIONS[rtype](c, "cpu")
|
|
419
|
+
return {"inv_freq": [float(x) for x in inv], "attn_scale": float(scale), "type": rtype}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def expected_names(spec, W):
|
|
423
|
+
"""weight names the built-in blocks will read (for the coverage check)."""
|
|
424
|
+
out = {spec["embed"], spec["final_norm"], spec["head"]} | ({spec["final_norm_bias"]} if spec.get("final_norm_bias")
|
|
425
|
+
else set())
|
|
426
|
+
for L in spec["layers"] + (spec.get("mtp", {}).get("layers", []) if spec.get("mtp") else []):
|
|
427
|
+
out |= {L[k] for k in ("norm1", "norm2", "post1", "post2") if L.get(k)} | set(L.get("extra", ()))
|
|
428
|
+
out |= set(L.get("hc", {}).get("names", ()))
|
|
429
|
+
for blk in (L["mixer"], L["mlp"]):
|
|
430
|
+
if "names" in blk:
|
|
431
|
+
out |= set(blk["names"])
|
|
432
|
+
continue
|
|
433
|
+
p = blk["prefix"]
|
|
434
|
+
if blk["type"] == "attn":
|
|
435
|
+
out |= {p + n + ".weight" for n in (("qkv_proj", "o_proj") if W.has(p + "qkv_proj.weight")
|
|
436
|
+
else ("q_proj", "k_proj", "v_proj", "o_proj"))}
|
|
437
|
+
if blk["qk_norm"]:
|
|
438
|
+
out |= {p + "q_norm.weight", p + "k_norm.weight"}
|
|
439
|
+
out |= {p + n + ".bias" for n in ("q_proj", "k_proj", "v_proj", "o_proj") if W.has(p + n + ".bias")}
|
|
440
|
+
out |= {p + "sinks"} if W.has(p + "sinks") else set()
|
|
441
|
+
if blk.get("indexer"):
|
|
442
|
+
out |= {p + "indexer." + n + ".weight" for n in ("q_proj", "k_proj", "q_norm", "k_norm")}
|
|
443
|
+
elif blk["type"] == "gdn":
|
|
444
|
+
proj = (("in_proj_qkvz.weight", "in_proj_ba.weight") if W.has(p + "in_proj_qkvz.weight") else
|
|
445
|
+
("in_proj_qkv.weight", "in_proj_z.weight", "in_proj_b.weight", "in_proj_a.weight"))
|
|
446
|
+
out |= {p + n for n in proj + ("conv1d.weight", "A_log", "dt_bias", "norm.weight", "out_proj.weight")}
|
|
447
|
+
elif blk["type"] == "dense_glu":
|
|
448
|
+
out |= {p + n + ".weight" for n in (("gate_up_proj", "down_proj") if W.has(p + "gate_up_proj.weight")
|
|
449
|
+
else ("gate_proj", "up_proj", "down_proj"))}
|
|
450
|
+
else:
|
|
451
|
+
return None # plug-in block without a names list: coverage not checkable
|
|
452
|
+
if spec.get("hc_head"):
|
|
453
|
+
out |= {spec["hc_head"]["prefix"] + n for n in ("hc_fn", "hc_base", "hc_scale")}
|
|
454
|
+
if spec.get("mtp"):
|
|
455
|
+
m = spec["mtp"]
|
|
456
|
+
out |= {m["fc"], m["norm_emb"], m["norm_hid"], m["norm"]}
|
|
457
|
+
return out
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def check_coverage(spec, W):
|
|
461
|
+
"""Refuse (NotImplementedError) when the checkpoint has text-stack weights no block reads: a layer feature the
|
|
462
|
+
adapter does not know (extra norms, biases, ...) must never be silently ignored."""
|
|
463
|
+
exp = expected_names(spec, W)
|
|
464
|
+
if exp is None:
|
|
465
|
+
return
|
|
466
|
+
pre = spec["prefix"]
|
|
467
|
+
have = {k for k in W.map if k.startswith(pre) and "visual" not in k and "vision" not in k}
|
|
468
|
+
have |= {k for k in W.map if k == "lm_head.weight"}
|
|
469
|
+
if spec.get("mtp"):
|
|
470
|
+
have |= {k for k in W.map if k.startswith("mtp.")}
|
|
471
|
+
extra = sorted(k for k in have - exp if not k.endswith("rotary_emb.inv_freq"))
|
|
472
|
+
if extra:
|
|
473
|
+
raise NotImplementedError(f"{len(extra)} checkpoint weights no block reads, e.g. {extra[:4]}")
|
|
474
|
+
missing = sorted(k for k in exp if not W.has(k))
|
|
475
|
+
if missing:
|
|
476
|
+
raise NotImplementedError(f"{len(missing)} expected weights missing, e.g. {missing[:4]} (other layer layout)")
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _attn_spec(tc, W, ap, rope, ltype):
|
|
480
|
+
nh, nkv = tc["num_attention_heads"], tc["num_key_value_heads"]
|
|
481
|
+
hd = rope["hd"]
|
|
482
|
+
qrows = W_shape0(W, ap + "q_proj.weight") if W.has(ap + "q_proj.weight") else nh * hd # fused qkv_proj: no gate
|
|
483
|
+
gate = bool(tc.get("attn_output_gate", False)) or (qrows == 2 * nh * hd)
|
|
484
|
+
# sliding window: with layer_types only on "sliding_attention" layers; without layer_types (Mistral / Mixtral /
|
|
485
|
+
# Qwen2 style) on every layer when config.sliding_window is set and use_sliding_window is not False (T27 BUG-002)
|
|
486
|
+
win = None
|
|
487
|
+
sw = tc.get("sliding_window")
|
|
488
|
+
if tc.get("layer_types"):
|
|
489
|
+
if ltype == "sliding_attention":
|
|
490
|
+
win = sw
|
|
491
|
+
elif sw and tc.get("use_sliding_window", True) is not False:
|
|
492
|
+
win = sw
|
|
493
|
+
return {"type": "attn", "prefix": ap, "nh": nh, "nkv": nkv, "hd": hd, "gate": gate,
|
|
494
|
+
"qk_norm": W.has(ap + "q_norm.weight"), "window": win, "rope": rope,
|
|
495
|
+
"sinks": W.has(ap + "sinks"),
|
|
496
|
+
# score scale: Gemma query_pre_attn_scalar**-0.5, Granite attention_multiplier, else hd**-0.5
|
|
497
|
+
"scale": (tc["query_pre_attn_scalar"] ** -0.5 if tc.get("query_pre_attn_scalar")
|
|
498
|
+
else tc.get("attention_multiplier")),
|
|
499
|
+
"softcap": tc.get("attn_logit_softcapping")}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def W_shape0(W, name):
|
|
503
|
+
from safetensors import safe_open
|
|
504
|
+
with safe_open(os.path.join(W.path, W.map[name]), "pt") as h:
|
|
505
|
+
return h.get_slice(name).get_shape()[0]
|