File size: 15,053 Bytes
f80e81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""Add experts to Kimi K3.1 Pro in its NATIVE checkpoint format, so that an unmodified SGLang/vLLM can serve the result
(DEC-028: expansion decided; S.T.A.R. ships the tool, whoever owns the hardware runs it).

What it does to one MoE layer shard, byte for byte and in streaming (no tensor is decoded, nothing is held in RAM):
  - every original tensor is copied unchanged;
  - m new experts are appended as `experts.{896+j}.*`, each an exact byte copy of a source expert (evenly spaced);
  - the router `gate.weight [896, 7168]` gains m rows, copies of the source rows;
  - `gate.e_score_correction_bias [896]` gains m entries equal to min(bias) - MARGIN.
Why that keeps the model's function EXACTLY at initialisation (routing rule read in sglang b8555f91 kimi_k3.py ->
grouped top-k, sigmoid scores, the bias only chooses, weights = original scores renormalised over the chosen):
a selection key is sigmoid(.) + b with sigmoid in [0, 1]; for a new expert it is at most 1 + min(b) - MARGIN, which is
below min(b) <= every original key when MARGIN > 1. The new experts are never chosen, so the output is unchanged.
They also receive no gradient while masked: training them needs the recipe in TRAINING.md (stochastic swap), not this tool.

    python tools/littleboy/expand_kimi.py plan --m 192
    python tools/littleboy/expand_kimi.py layer <in.safetensors> <out.safetensors> --layer L --m 192
    python tools/littleboy/expand_kimi.py verify <in.safetensors> <out.safetensors> --layer L --m 192 [--tokens 4096]
    python tools/littleboy/expand_kimi.py finalize <model_dir> <out_dir> --m 192     (config.json + index for the new shards)
"""
import hashlib
import json
import struct
import sys
from pathlib import Path

E0, HIDDEN = 896, 7168
MARGIN = 2.0
CHUNK = 64 * 1024 * 1024
PREFIX = "language_model.model.layers.{L}.block_sparse_moe."
EXPERT_PARTS = ("w1.weight_packed", "w1.weight_scale", "w2.weight_packed", "w2.weight_scale", "w3.weight_packed", "w3.weight_scale")
DTYPE_BYTES = {"BF16": 2, "F32": 4, "U8": 1, "F16": 2, "I32": 4}


class ExpandError(ValueError):
    pass


def read_header(path: Path):
    with open(path, "rb") as f:
        n = struct.unpack("<Q", f.read(8))[0]
        header = json.loads(f.read(n))
    meta = header.pop("__metadata__", None)
    return header, 8 + n, meta


def sources(e0: int, m: int) -> list:
    """m source experts, evenly spaced over 0..e0-1, distinct when m <= e0."""
    if not 0 < m <= e0:
        raise ExpandError(f"m must be in 1..{e0}")
    return [(j * e0) // m for j in range(m)]


def _nbytes(spec: dict) -> int:
    n = DTYPE_BYTES[spec["dtype"]]
    for d in spec["shape"]:
        n *= d
    return n


def _copy(fin, start: int, length: int, fout, h) -> None:
    fin.seek(start)
    left = length
    while left:
        buf = fin.read(min(CHUNK, left))
        if not buf:
            raise ExpandError("source file ended early")
        fout.write(buf)
        h.update(buf)
        left -= len(buf)


def expand_layer(src: Path, dst: Path, layer: int, m: int, e0: int = E0, hidden: int = HIDDEN) -> dict:
    """Write dst = src + m experts on `layer`. Returns a record with the mapping and the output hash."""
    header, data0, meta = read_header(src)
    pre = PREFIX.format(L=layer)
    gate, bias = pre + "gate.weight", pre + "gate.e_score_correction_bias"
    for name, shape, dtype in ((gate, [e0, hidden], "BF16"), (bias, [e0], "F32")):
        if name not in header or header[name]["shape"] != shape or header[name]["dtype"] != dtype:
            raise ExpandError(f"{name}: expected {dtype} {shape}, found {header.get(name)}")
    if pre + f"experts.{e0}.w1.weight_packed" in header:
        raise ExpandError("the layer already has more than the base experts: refusing to expand twice")
    src_ids = sources(e0, m)
    with open(src, "rb") as f:
        f.seek(data0 + header[bias]["data_offsets"][0])
        b = struct.unpack(f"<{e0}f", f.read(4 * e0))
        f.seek(data0 + header[gate]["data_offsets"][0])
        gate_bytes = f.read(_nbytes(header[gate]))
    new_bias = min(b) - MARGIN
    row = hidden * 2
    plan = []                                          # (name, spec, kind, payload)
    for name, spec in sorted(header.items(), key=lambda kv: kv[1]["data_offsets"][0]):
        if name == gate:
            extra = b"".join(gate_bytes[s * row:(s + 1) * row] for s in src_ids)
            plan.append((name, {"dtype": "BF16", "shape": [e0 + m, hidden]}, "bytes", gate_bytes + extra))
        elif name == bias:
            raw = struct.pack(f"<{e0}f", *b) + struct.pack(f"<{m}f", *([new_bias] * m))
            plan.append((name, {"dtype": "F32", "shape": [e0 + m]}, "bytes", raw))
        else:
            plan.append((name, spec, "copy", spec["data_offsets"]))
    for j, s in enumerate(src_ids):
        for part in EXPERT_PARTS:
            sname = pre + f"experts.{s}.{part}"
            if sname not in header:
                raise ExpandError(f"missing source tensor {sname}")
            plan.append((pre + f"experts.{e0 + j}.{part}", {k: header[sname][k] for k in ("dtype", "shape")}, "copy",
                         header[sname]["data_offsets"]))
    out_header, offset = {}, 0
    for name, spec, kind, payload in plan:
        n = len(payload) if kind == "bytes" else payload[1] - payload[0]
        if n != _nbytes(spec):
            raise ExpandError(f"{name}: {n} bytes for {spec}")
        out_header[name] = {"dtype": spec["dtype"], "shape": spec["shape"], "data_offsets": [offset, offset + n]}
        offset += n
    if meta is not None:
        out_header["__metadata__"] = meta
    hbytes = json.dumps(out_header, separators=(",", ":")).encode("utf-8")
    hbytes += b" " * ((8 - len(hbytes) % 8) % 8)
    h = hashlib.sha256()
    dst.parent.mkdir(parents=True, exist_ok=True)
    tmp = dst.with_suffix(dst.suffix + ".partial")
    with open(src, "rb") as fin, open(tmp, "wb") as fout:
        for piece in (struct.pack("<Q", len(hbytes)), hbytes):
            fout.write(piece)
            h.update(piece)
        for name, spec, kind, payload in plan:
            if kind == "bytes":
                fout.write(payload)
                h.update(payload)
            else:
                _copy(fin, data0 + payload[0], payload[1] - payload[0], fout, h)
    tmp.replace(dst)
    return {"layer": layer, "m": m, "sources": src_ids, "new_bias": new_bias, "min_old_bias": min(b), "max_old_bias": max(b),
            "tensors": len(plan), "bytes": dst.stat().st_size, "sha256": h.hexdigest()}


def _hash_range(f, start: int, length: int) -> str:
    h = hashlib.sha256()
    f.seek(start)
    left = length
    while left:
        buf = f.read(min(CHUNK, left))
        h.update(buf)
        left -= len(buf)
    return h.hexdigest()


def verify_layer(src: Path, dst: Path, layer: int, m: int, tokens: int = 4096, e0: int = E0, hidden: int = HIDDEN,
                 top_k: int = 16, seed: int = 20261117) -> dict:
    """Bytes: every original tensor unchanged, every new expert equal to its source, router rows and bias as specified.
    Function: on random hidden states, the expanded router selects the same experts with the same weights."""
    import torch
    ho, do, _ = read_header(src)
    hn, dn, _ = read_header(dst)
    pre = PREFIX.format(L=layer)
    gate, bias = pre + "gate.weight", pre + "gate.e_score_correction_bias"
    src_ids = sources(e0, m)
    bad = []
    with open(src, "rb") as fo, open(dst, "rb") as fn:
        for name, spec in ho.items():
            if name in (gate, bias):
                continue
            if name not in hn or hn[name]["dtype"] != spec["dtype"] or hn[name]["shape"] != spec["shape"]:
                bad.append(f"changed or missing: {name}")
                continue
            a = _hash_range(fo, do + spec["data_offsets"][0], spec["data_offsets"][1] - spec["data_offsets"][0])
            b_ = _hash_range(fn, dn + hn[name]["data_offsets"][0], hn[name]["data_offsets"][1] - hn[name]["data_offsets"][0])
            if a != b_:
                bad.append(f"bytes differ: {name}")
        for j, s in enumerate(src_ids):
            for part in EXPERT_PARTS:
                o, n = ho[pre + f"experts.{s}.{part}"], hn.get(pre + f"experts.{e0 + j}.{part}")
                if n is None:
                    bad.append(f"missing new expert {e0 + j}.{part}")
                    continue
                if _hash_range(fo, do + o["data_offsets"][0], o["data_offsets"][1] - o["data_offsets"][0]) != \
                        _hash_range(fn, dn + n["data_offsets"][0], n["data_offsets"][1] - n["data_offsets"][0]):
                    bad.append(f"new expert {e0 + j}.{part} is not a copy of expert {s}")
        extra = [k for k in hn if k not in ho and not any(k == pre + f"experts.{e0 + j}.{p}" for j in range(m) for p in EXPERT_PARTS)]
        if extra:
            bad.append(f"unexpected tensors: {extra[:3]}")

        def load(f, d0, spec, dtype):
            f.seek(d0 + spec["data_offsets"][0])
            raw = bytearray(f.read(spec["data_offsets"][1] - spec["data_offsets"][0]))
            return torch.frombuffer(raw, dtype=dtype).reshape(spec["shape"])
        go = load(fo, do, ho[gate], torch.bfloat16).float()
        gn = load(fn, dn, hn[gate], torch.bfloat16).float()
        bo = load(fo, do, ho[bias], torch.float32)
        bn = load(fn, dn, hn[bias], torch.float32)
    if not torch.equal(gn[:e0], go) or not torch.equal(bn[:e0], bo):
        bad.append("router rows or bias of the original experts changed")
    if not torch.equal(gn[e0:], go[src_ids]):
        bad.append("new router rows are not copies of the source rows")
    if not bool((bn[e0:] == bo.min() - MARGIN).all()):
        bad.append("new bias entries are not min(bias) - MARGIN")
    g = torch.Generator().manual_seed(seed)
    x = torch.randn(tokens, hidden, generator=g) * 4.0          # wide spread: scores near 0 and near 1 both occur

    def route(logits, b):
        s = torch.sigmoid(logits)
        ids = torch.topk(s + b, k=top_k, dim=-1)[1]
        w = s.gather(1, ids)
        ids, order = ids.sort(dim=-1)
        w = w.gather(1, order)
        return ids, w / w.sum(dim=-1, keepdim=True)
    lo = x @ go.T
    io, wo = route(lo, bo)
    # structural: the original logits, plus the new rows' logits computed apart -> must be bit-identical
    i_s, w_s = route(torch.cat([lo, x @ gn[e0:].T], dim=1), bn)
    structural = bool(torch.equal(io, i_s) and torch.equal(wo, w_s))
    # numeric: one wider GEMM, as an engine would run it; summation order may change the last bits of the logits
    i_n, w_n = route(x @ gn.T, bn)
    same_ids = bool(torch.equal(io, i_n))
    max_dw = float((wo - w_n).abs().max()) if same_ids else float("inf")
    same_w = max_dw <= 1e-6
    if not structural:
        bad.append("structural routing differs: the expansion itself changes the selection or the weights")
    if not (same_ids and same_w):
        bad.append(f"numeric routing differs: ids equal {same_ids}, max weight difference {max_dw:.3e}")
    key_gap = float((bo.min() - (1.0 + bn[e0:].max())).item())
    return {"layer": layer, "m": m, "tokens_checked": tokens, "problems": bad, "structural_exact": structural,
            "same_selection": same_ids, "same_weights": same_w, "max_weight_difference_wide_gemm": max_dw,
            "worst_new_key_below_best_case_old_key_by": key_gap, "verdict": "EQUIVALENT" if not bad else "NOT_EQUIVALENT"}


def routing_problems(text_config: dict) -> list:
    """Why the equivalence argument would NOT hold for this model's router (empty list = it holds).
    The argument: sigmoid scores lie in [0, 1], the correction bias only selects, the weights are renormalised over the
    selected experts, and every expert competes in one group. With several groups and fewer groups selected, appending
    experts changes the group of the old ones (read in sglang b8555f91 grouped top-k; Kimi K3.1 has 1 and 1)."""
    problems = []
    groups, chosen = text_config.get("num_expert_group", 1), text_config.get("topk_group", 1)
    if groups != 1 and chosen < groups:
        problems.append(f"num_expert_group = {groups} with topk_group = {chosen}: appended experts would regroup the old ones")
    if text_config.get("moe_router_activation_func", "sigmoid") != "sigmoid":
        problems.append(f"router activation {text_config.get('moe_router_activation_func')!r}: the bias margin is proved for sigmoid only")
    if not text_config.get("moe_renormalize", False):
        problems.append("moe_renormalize is false: the weights would not be renormalised over the selected experts")
    return problems


def finalize(model_dir: Path, out_dir: Path, m: int, e0: int = E0) -> dict:
    """config.json with num_experts = e0 + m and an index that maps every tensor of the new shards."""
    cfg = json.loads((model_dir / "config.json").read_text(encoding="utf-8"))
    if cfg["text_config"]["num_experts"] != e0:
        raise ExpandError(f"config has {cfg['text_config']['num_experts']} experts, expected {e0}")
    problems = routing_problems(cfg["text_config"])
    if problems:
        raise ExpandError("the expansion is not proved equivalent for this router: " + "; ".join(problems))
    cfg["text_config"]["num_experts"] = e0 + m
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "config.json").write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
    index = json.loads((model_dir / "model.safetensors.index.json").read_text(encoding="utf-8"))
    total = 0
    for shard in sorted({v for v in index["weight_map"].values()}):
        p = out_dir / shard if (out_dir / shard).exists() else model_dir / shard
        header, _, _ = read_header(p)
        for name, spec in header.items():
            index["weight_map"][name] = shard
            total += spec["data_offsets"][1] - spec["data_offsets"][0]
    index["metadata"]["total_size"] = total
    (out_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2) + "\n", encoding="utf-8")
    return {"num_experts": e0 + m, "tensors": len(index["weight_map"]), "total_size": total}


def main(argv: list) -> int:
    opt = {argv[i][2:]: argv[i + 1] for i in range(len(argv) - 1) if argv[i].startswith("--")}
    pos = [a for i, a in enumerate(argv) if not a.startswith("--") and (i == 0 or not argv[i - 1].startswith("--"))]
    m = int(opt.get("m", 192))
    if pos[0] == "plan":
        print(json.dumps({"m": m, "sources": sources(E0, m), "margin": MARGIN}))
        return 0
    if pos[0] == "layer":
        print(json.dumps(expand_layer(Path(pos[1]), Path(pos[2]), int(opt["layer"]), m)))
        return 0
    if pos[0] == "verify":
        r = verify_layer(Path(pos[1]), Path(pos[2]), int(opt["layer"]), m, int(opt.get("tokens", 4096)))
        print(json.dumps(r, indent=1))
        return 0 if r["verdict"] == "EQUIVALENT" else 1
    if pos[0] == "finalize":
        print(json.dumps(finalize(Path(pos[1]), Path(pos[2]), m)))
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))