Trinity / tools /wsp_activate.py
STAR-future's picture
Trinity: public release (history squashed)
f80e81a
Raw History Blame Contribute Delete
12.4 kB
"""Weight-space programming of LittleBoy's added experts (founder's decision, 2026-11-18): every new expert is an ACTIVE
merge of two different Kimi experts, not a masked copy.
For layer L and each of the m new experts j:
- pair (a_j, b_j): a_j = sources(896, m)[j]; b_j = the other expert whose router row is most similar to a_j's
(cosine on gate.weight), taken without repetition where possible;
- weights: 0.5 * (E_a + E_b), computed in dequantised MXFP4 (E2M1 values, one E8M0 scale per 32) and re-quantised;
- router row: the normalised mean of the two rows, rescaled to their mean norm; bias: the mean of the two biases.
The new expert is selectable: the model is NOT equivalent to Kimi any more. This is an untested hypothesis that a merged
expert interpolates its parents' specialisation; no output of the activated model has been measured.
python tools/littleboy/wsp_activate.py layer <in.safetensors> <out.safetensors> --layer L --m 256
python tools/littleboy/wsp_activate.py selftest <shard.safetensors> --layer L (round-trip and merge checks)
"""
import json
import struct
import sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import expand_kimi as X # noqa: E402
E2M1 = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], dtype=np.float32)
MAGS = E2M1[:8]
def dequant(packed: np.ndarray, scale: np.ndarray) -> np.ndarray:
lo, hi = packed & 0x0F, packed >> 4
vals = np.stack([E2M1[lo], E2M1[hi]], axis=-1).reshape(packed.shape[0], -1)
s = np.exp2(scale.astype(np.float32) - 127.0)
return vals * np.repeat(s, 32, axis=1)
MID = np.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], dtype=np.float32)
def quant(x: np.ndarray):
rows, cols = x.shape
blk = x.reshape(rows, cols // 32, 32).astype(np.float32)
amax = np.abs(blk).max(axis=2)
e0 = np.where(amax > 0, np.ceil(np.log2(np.maximum(amax, 1e-30) / 6.0)), -127.0).astype(np.float32)
best = None
for de in (0.0, -1.0): # per block, the scale with the smaller error (clipping allowed)
ee = np.clip(e0 + de, -127, 127)
y = blk * np.exp2(-ee)[..., None]
idx = np.searchsorted(MID, np.abs(y)).astype(np.uint8)
err = ((np.copysign(MAGS[idx], y) - y) ** 2).sum(axis=2) * np.exp2(2 * ee)
if best is None:
best = [ee, y, idx, err]
else:
pick = err < best[3]
best = [np.where(pick, ee, best[0]), np.where(pick[..., None], y, best[1]),
np.where(pick[..., None], idx, best[2]), np.minimum(err, best[3])]
e, y, idx, _ = best
code = np.where((y < 0) & (idx > 0), idx | 0x08, idx).astype(np.uint8).reshape(rows, cols)
packed = (code[:, 0::2] | (code[:, 1::2] << 4)).astype(np.uint8)
return packed, (e + 127).astype(np.uint8)
def _merge_one(args):
"""One new expert: dequantise both parents, average, re-quantise. Runs in a worker process."""
pa, sa, pb, sb, shp, sshp = args
xa = dequant(np.frombuffer(pa, np.uint8).reshape(shp), np.frombuffer(sa, np.uint8).reshape(sshp))
xb = dequant(np.frombuffer(pb, np.uint8).reshape(shp), np.frombuffer(sb, np.uint8).reshape(sshp))
pk, sc = quant(0.5 * (xa + xb))
return pk.tobytes(), sc.tobytes(), list(pk.shape), list(sc.shape)
def _read(f, off, spec):
a, b = spec["data_offsets"]
f.seek(off + a)
return f.read(b - a)
def _arr(raw, spec):
dt = {"U8": np.uint8, "F32": "<f4"}.get(spec["dtype"])
if spec["dtype"] == "BF16":
return (np.frombuffer(raw, "<u2").astype(np.uint32) << 16).view(np.float32).reshape(spec["shape"])
return np.frombuffer(raw, dt).reshape(spec["shape"])
def _bf16(x):
u = np.asarray(x, np.float32).view(np.uint32)
return ((u + 0x7FFF + ((u >> 16) & 1)) >> 16).astype("<u2").tobytes()
def pairs(gate: np.ndarray, m: int, e0: int = X.E0) -> list:
src = X.sources(e0, m)
g = gate / np.linalg.norm(gate, axis=1, keepdims=True)
sim = g @ g.T
np.fill_diagonal(sim, -np.inf)
used, out = set(), []
for a in src:
order = np.argsort(-sim[a])
b = next((int(o) for o in order if (min(a, o), max(a, o)) not in used), int(order[0]))
used.add((min(a, b), max(a, b)))
out.append((int(a), b))
return out
def layer(src: Path, dst: Path, L: int, m: int) -> dict:
hdr, off, meta = X.read_header(src)
p = X.PREFIX.format(L=L)
with open(src, "rb") as f:
gate = _arr(_read(f, off, hdr[p + "gate.weight"]), hdr[p + "gate.weight"])
bias = _arr(_read(f, off, hdr[p + "gate.e_score_correction_bias"]), hdr[p + "gate.e_score_correction_bias"]).astype(np.float64)
pr = pairs(gate, m)
jobs, keys = [], []
for j, (a, b) in enumerate(pr):
for w in ("w1", "w2", "w3"):
ka, kb = (f"{p}experts.{e}.{w}." for e in (a, b))
jobs.append((_read(f, off, hdr[ka + "weight_packed"]), _read(f, off, hdr[ka + "weight_scale"]),
_read(f, off, hdr[kb + "weight_packed"]), _read(f, off, hdr[kb + "weight_scale"]),
hdr[ka + "weight_packed"]["shape"], hdr[ka + "weight_scale"]["shape"]))
keys.append((f"{p}experts.{X.E0 + j}.{w}.", hdr[ka + "weight_packed"]["dtype"], hdr[ka + "weight_scale"]["dtype"]))
new = {}
import concurrent.futures as cf
import os
with cf.ProcessPoolExecutor(max_workers=os.cpu_count()) as ex:
for (kn, dp, ds), (pk, sc, shp, sshp) in zip(keys, ex.map(_merge_one, jobs, chunksize=4)):
new[kn + "weight_packed"] = (dp, shp, pk)
new[kn + "weight_scale"] = (ds, sshp, sc)
rows, biases = [], []
for a, b in pr:
v = gate[a] / np.linalg.norm(gate[a]) + gate[b] / np.linalg.norm(gate[b])
rows.append(v / np.linalg.norm(v) * 0.5 * (np.linalg.norm(gate[a]) + np.linalg.norm(gate[b])))
biases.append(0.5 * (bias[a] + bias[b]))
out_t = {}
for name, spec in hdr.items():
raw = _read(f, off, spec)
if name == p + "gate.weight":
out_t[name] = (spec["dtype"], [X.E0 + m, X.HIDDEN], raw + _bf16(np.stack(rows)))
elif name == p + "gate.e_score_correction_bias":
out_t[name] = (spec["dtype"], [X.E0 + m], raw + np.asarray(biases, "<f4").tobytes())
else:
out_t[name] = (spec["dtype"], spec["shape"], raw)
out_t.update(new)
header, o = {}, 0
for name, (dt, shape, raw) in out_t.items():
header[name] = {"dtype": dt, "shape": shape, "data_offsets": [o, o + len(raw)]}
o += len(raw)
if meta:
header["__metadata__"] = meta
hb = json.dumps(header, separators=(",", ":")).encode()
hb += b" " * (-len(hb) % 8)
with open(dst, "wb") as fo:
fo.write(struct.pack("<Q", len(hb)) + hb)
for _dt, _s, raw in out_t.values():
fo.write(raw)
return {"layer": L, "m": m, "pairs": pr, "new_bias_min_max": [min(biases), max(biases)], "old_bias_min_max": [float(bias.min()), float(bias.max())]}
def layer_stream(src: Path, dst: Path, L: int, m: int, batch: int = 48) -> dict:
"""Same bytes as layer(), in a few GB of RAM instead of the whole shard: the header is known before any merge (a
merged tensor has its parent's shape and dtype), the original tensors are copied in chunks, the merges are
computed in batches and written in order. Lets two shards build at once on a 32 GB machine."""
import concurrent.futures as cf
import os
hdr, off, meta = X.read_header(src)
p = X.PREFIX.format(L=L)
with open(src, "rb") as f:
gate = _arr(_read(f, off, hdr[p + "gate.weight"]), hdr[p + "gate.weight"])
bias = _arr(_read(f, off, hdr[p + "gate.e_score_correction_bias"]), hdr[p + "gate.e_score_correction_bias"]).astype(np.float64)
pr = pairs(gate, m)
rows, biases = [], []
for a, b in pr:
v = gate[a] / np.linalg.norm(gate[a]) + gate[b] / np.linalg.norm(gate[b])
rows.append(v / np.linalg.norm(v) * 0.5 * (np.linalg.norm(gate[a]) + np.linalg.norm(gate[b])))
biases.append(0.5 * (bias[a] + bias[b]))
extra = {p + "gate.weight": _bf16(np.stack(rows)), p + "gate.e_score_correction_bias": np.asarray(biases, "<f4").tobytes()}
layout, o = [], 0 # (name, dtype, shape, nbytes)
for name, spec in hdr.items():
a0, a1 = spec["data_offsets"]
n = a1 - a0 + len(extra.get(name, b""))
shape = ([X.E0 + m, X.HIDDEN] if name == p + "gate.weight" else [X.E0 + m] if name == p + "gate.e_score_correction_bias"
else spec["shape"])
layout.append((name, spec["dtype"], shape, n))
jobs = []
for j, (a, b) in enumerate(pr):
for w in ("w1", "w2", "w3"):
ka, kb = (f"{p}experts.{e}.{w}." for e in (a, b))
kn = f"{p}experts.{X.E0 + j}.{w}."
for part in ("weight_packed", "weight_scale"):
sp = hdr[ka + part]
layout.append((kn + part, sp["dtype"], sp["shape"], sp["data_offsets"][1] - sp["data_offsets"][0]))
jobs.append((ka, kb))
header = {}
for name, dt, shape, n in layout:
header[name] = {"dtype": dt, "shape": shape, "data_offsets": [o, o + n]}
o += n
if meta:
header["__metadata__"] = meta
hb = json.dumps(header, separators=(",", ":")).encode()
hb += b" " * (-len(hb) % 8)
with open(dst, "wb") as fo:
fo.write(struct.pack("<Q", len(hb)) + hb)
for name, spec in hdr.items():
a0, a1 = spec["data_offsets"]
f.seek(off + a0)
left = a1 - a0
while left:
chunk = f.read(min(left, 64 << 20))
fo.write(chunk)
left -= len(chunk)
fo.write(extra.get(name, b""))
with cf.ProcessPoolExecutor(max_workers=os.cpu_count()) as ex:
for s in range(0, len(jobs), batch):
args = []
for ka, kb in jobs[s:s + batch]:
args.append((_read(f, off, hdr[ka + "weight_packed"]), _read(f, off, hdr[ka + "weight_scale"]),
_read(f, off, hdr[kb + "weight_packed"]), _read(f, off, hdr[kb + "weight_scale"]),
hdr[ka + "weight_packed"]["shape"], hdr[ka + "weight_scale"]["shape"]))
for pk, sc, _shp, _sshp in ex.map(_merge_one, args, chunksize=4):
fo.write(pk)
fo.write(sc)
if dst.stat().st_size != 8 + len(hb) + o:
raise RuntimeError(f"{dst}: size {dst.stat().st_size}, expected {8 + len(hb) + o}")
return {"layer": L, "m": m, "pairs": pr, "new_bias_min_max": [min(biases), max(biases)], "old_bias_min_max": [float(bias.min()), float(bias.max())]}
def selftest(src: Path, L: int) -> dict:
hdr, off, _ = X.read_header(src)
p = X.PREFIX.format(L=L)
with open(src, "rb") as f:
k = f"{p}experts.0.w1."
pk = _arr(_read(f, off, hdr[k + "weight_packed"]), hdr[k + "weight_packed"])
sc = _arr(_read(f, off, hdr[k + "weight_scale"]), hdr[k + "weight_scale"])
x = dequant(pk, sc)
pk2, sc2 = quant(x)
x2 = dequant(pk2, sc2)
k1 = f"{p}experts.1.w1."
y = dequant(_arr(_read(f, off, hdr[k1 + "weight_packed"]), hdr[k1 + "weight_packed"]),
_arr(_read(f, off, hdr[k1 + "weight_scale"]), hdr[k1 + "weight_scale"]))
mpk, msc = quant(0.5 * (x + y))
mx = dequant(mpk, msc)
ref = 0.5 * (x + y)
return {"roundtrip_max_abs_err": float(np.abs(x2 - x).max()), "roundtrip_bytes_equal": float((pk2 == pk).mean()),
"merge_rel_err": float(np.linalg.norm(mx - ref) / np.linalg.norm(ref)), "shape": list(x.shape)}
if __name__ == "__main__":
a = sys.argv[1:]
if a[0] == "selftest":
print(json.dumps(selftest(Path(a[1]), int(a[a.index("--layer") + 1]))))
else:
print(json.dumps(layer(Path(a[1]), Path(a[2]), int(a[a.index("--layer") + 1]), int(a[a.index("--m") + 1]))))