mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-06 16:29:04 +00:00
- Deleted: the DFly drafter model code (five-layer drafter forward, screen head, D-cut, taps, load_dfly, DflyWeights, the manifest drafter fields), the DFly flags (--spec dfly,
--spec-cut / ctx / rerank / tap / tc / q8 / split / fuse / diag, --dump-taps, --dump-taps-jobs, --dump-cache), its unit tests, python references and fixtures.
The engine no longer loads model.dfly.* or dfly_screen_head (about 320 MB of VRAM); the file layout is untouched, the engine skips those tensors.
- Kept: the shared speculative infrastructure in the new ling32_spec.{hpp,cu} (cycle record, on-GPU accept / rejection sampling, KDA rollback, position advance, the MTP
drafting helpers, top-K), the verify graph, the per-token KDA snapshots, the adaptive controller; --spec mtp --mtp FILE is the only way to speculate (--spec dfly answers
with a pointer to it). ling32_spec_test (the sampling kernel's KL gate) builds and passes.
722 lines
34 KiB
Python
722 lines
34 KiB
Python
#!/usr/bin/env python3
|
|
"""ling32_pyref.py - an independent float64 NumPy reference of Ling-3.2-Air for the `.strata v1.1` layout, a fixture writer,
|
|
and the S4_K / S5_K / S6_K / S8_K codecs, written from docs 02/05 of the hand-off pack and python_golden_ref (the maths is
|
|
the pack's; the code is ours). Needs numpy and zstandard only.
|
|
|
|
python ling32_pyref.py make-fixture OUT.strata [--seed N]
|
|
python ling32_pyref.py ref FILE.strata --ids 1,2,3 --out DIR [--clamp-order silu_first|clamp_first]
|
|
python ling32_pyref.py codec-vectors OUT_DIR # random superblocks of all four codecs + their decodes (bit-exact test)
|
|
python ling32_pyref.py info FILE.strata
|
|
|
|
`ref` writes DIR/<name>.f32 (raw little-endian float32) for: embed, x_in_<il> (the residual entering layer il), x_out_<il>,
|
|
route_idx_<il> (int32 [T,8]), route_w_<il> (f32 [T,8]), logits [T,V]. The C++ engine's `--dump DIR` writes the same names.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
import struct
|
|
import sys
|
|
|
|
import numpy as np
|
|
import zstandard as zstd
|
|
|
|
MAGIC = b"STRATA\x00\x01"
|
|
PAGE = 16384
|
|
QK_S, SUB_G = 256, 64
|
|
SB_BYTES = {4: 134, 5: 166, 6: 198, 8: 262}
|
|
SEC_FMT = "<QQ32sIIQ"
|
|
EXP_FMT = "<HBBHHQIIII"
|
|
|
|
|
|
# --------------------------------------------------------------------------------------------------- codecs
|
|
def encode_sk(w: np.ndarray, code: int) -> bytes:
|
|
"""S4_K / S5_K / S6_K / S8_K encoder (superblock = fp16 D, u8 u[4], payload), the layout of ling32_squant_codecs_v11.encode_sk_gpu."""
|
|
w = np.asarray(w, dtype=np.float32).reshape(-1, 4, 64)
|
|
nsb = w.shape[0]
|
|
amax_sub = np.abs(w).max(axis=2)
|
|
if code == 8:
|
|
amax_sb = amax_sub.max(axis=1)
|
|
d16 = (amax_sb / np.float32(127.0)).astype(np.float16)
|
|
else:
|
|
half = np.float32(((1 << code) - 1) / 2.0)
|
|
amax_sb = amax_sub.max(axis=1)
|
|
d16 = (amax_sb / half).astype(np.float16)
|
|
d_eff = d16.astype(np.float32)
|
|
denom = np.where(amax_sb > 0, amax_sb, np.float32(1.0))[:, None]
|
|
u = np.clip(np.rint(amax_sub / denom * np.float32(255.0)), 0, 255).astype(np.uint8)
|
|
u = np.where((amax_sub > 0) & (u == 0), 1, u).astype(np.uint8)
|
|
eff = (d_eff[:, None] * (u.astype(np.float32) / np.float32(255.0)))[:, :, None]
|
|
inv = np.where(eff > 0, np.float32(1.0) / np.where(eff > 0, eff, 1), 0).astype(np.float32)
|
|
if code == 8:
|
|
q = np.clip(np.rint(w * inv), -127, 127).astype(np.int8).reshape(nsb, 256)
|
|
pl = q.view(np.uint8)
|
|
else:
|
|
levels = 1 << code
|
|
half = np.float32((levels - 1) / 2.0)
|
|
qu = np.clip(np.floor(w * inv + half + np.float32(0.5)), 0, levels - 1).astype(np.uint8).reshape(nsb, 256)
|
|
lo = (qu & 0x0F).reshape(nsb, 128, 2)
|
|
p_lo = lo[..., 0] | (lo[..., 1] << 4)
|
|
if code == 4:
|
|
pl = p_lo
|
|
elif code == 5:
|
|
hi = ((qu >> 4) & 1).reshape(nsb, 32, 8)
|
|
p_hi = np.zeros((nsb, 32), np.uint8)
|
|
for b in range(8):
|
|
p_hi |= (hi[..., b] << b).astype(np.uint8)
|
|
pl = np.concatenate([p_lo, p_hi], axis=1)
|
|
else:
|
|
hi = ((qu >> 4) & 3).reshape(nsb, 64, 4)
|
|
p_hi = hi[..., 0] | (hi[..., 1] << 2) | (hi[..., 2] << 4) | (hi[..., 3] << 6)
|
|
pl = np.concatenate([p_lo, p_hi.astype(np.uint8)], axis=1)
|
|
out = np.concatenate([d16.view(np.uint8).reshape(nsb, 2), u, pl], axis=1)
|
|
assert out.shape[1] == SB_BYTES[code]
|
|
return out.tobytes()
|
|
|
|
|
|
def decode_sk(raw, code: int) -> np.ndarray:
|
|
"""float32 values of an S_K stream (bit-exact with ling32_squant_codecs_v11.decode_sk_gpu: q * (D * (u / 255)))."""
|
|
sb = SB_BYTES[code]
|
|
blocks = np.frombuffer(raw, dtype=np.uint8).reshape(-1, sb)
|
|
nsb = blocks.shape[0]
|
|
D = blocks[:, :2].copy().view(np.float16).reshape(nsb).astype(np.float32)
|
|
u = blocks[:, 2:6].astype(np.float32)
|
|
eff = (D[:, None] * (u / np.float32(255.0)))[:, :, None]
|
|
pl = blocks[:, 6:]
|
|
if code == 8:
|
|
q = pl.copy().view(np.int8).astype(np.float32).reshape(nsb, 4, 64)
|
|
return (q * eff).reshape(nsb * QK_S)
|
|
half = np.float32(((1 << code) - 1) / 2.0)
|
|
p_lo = pl[:, :128]
|
|
lo = np.stack([p_lo & 0x0F, (p_lo >> 4) & 0x0F], axis=2).reshape(nsb, 256)
|
|
if code == 4:
|
|
q = lo
|
|
elif code == 5:
|
|
p_hi = pl[:, 128:160]
|
|
hi = np.stack([(p_hi >> j) & 1 for j in range(8)], axis=2).reshape(nsb, 256)
|
|
q = lo | (hi << 4)
|
|
else:
|
|
p_hi = pl[:, 128:192]
|
|
hi = np.stack([(p_hi >> (2 * j)) & 3 for j in range(4)], axis=2).reshape(nsb, 256)
|
|
q = lo | (hi << 4)
|
|
qf = q.astype(np.float32).reshape(nsb, 4, 64) - half
|
|
return (qf * eff).reshape(nsb * QK_S)
|
|
|
|
|
|
def hadamard128() -> np.ndarray:
|
|
h = np.array([[1.0]])
|
|
for _ in range(7):
|
|
h = np.block([[h, h], [h, -h]])
|
|
return h / math.sqrt(128.0)
|
|
|
|
|
|
H128 = hadamard128()
|
|
|
|
|
|
def fwht128(x: np.ndarray) -> np.ndarray:
|
|
sh = x.shape
|
|
return (x.reshape(-1, 128) @ H128).reshape(sh)
|
|
|
|
|
|
# --------------------------------------------------------------------------------------------------- container
|
|
def pad16k(b: bytes) -> bytes:
|
|
rem = len(b) % PAGE
|
|
return b if rem == 0 else b + b"\x00" * (PAGE - rem)
|
|
|
|
|
|
class StrataV11:
|
|
"""Reader for .strata v1.1 (16 KiB layout)."""
|
|
|
|
def __init__(self, path: str):
|
|
self.path = path
|
|
with open(path, "rb") as f:
|
|
frame = f.read(PAGE)
|
|
assert frame[:8] == MAGIC, "bad magic"
|
|
probe = struct.unpack_from("<Q", frame, 0x10)[0]
|
|
off = 0x20 if probe < 4096 else 0x10
|
|
self.layout16k = off == 0x20
|
|
self.sec = []
|
|
for i in range(6):
|
|
o, ln, sha, sid, fl, _ = struct.unpack_from(SEC_FMT, frame, off + 64 * i)
|
|
self.sec.append({"off": o, "len": ln, "sha": sha, "id": sid, "flags": fl})
|
|
f.seek(self.sec[0]["off"])
|
|
raw = f.read(self.sec[0]["len"])
|
|
self.manifest = json.loads(zstd.ZstdDecompressor().stream_reader(raw).read().decode("utf-8"))
|
|
self.cfg = self.manifest["config"]["text_config"]
|
|
self.trunk = {t["name"]: t for t in self.manifest["trunk_tensors"]}
|
|
self.sec2 = {t["name"]: t for t in self.manifest.get("section2_tensors", [])}
|
|
self._f = open(path, "rb")
|
|
n_moe = int(self.manifest["n_moe_layers"])
|
|
n_exp = int(self.manifest["n_experts_per_layer"])
|
|
self._f.seek(self.sec[3]["off"])
|
|
s3 = self._f.read(n_moe * n_exp * 32)
|
|
self.experts = []
|
|
for i in range(n_moe * n_exp):
|
|
self.experts.append(struct.unpack_from(EXP_FMT, s3, 32 * i))
|
|
|
|
def _read(self, base: int, t: dict) -> bytes:
|
|
self._f.seek(self.sec[base]["off"] + t["offset"])
|
|
return self._f.read(t["bytes"])
|
|
|
|
def tensor(self, name: str, sec: int = 1) -> np.ndarray:
|
|
t = (self.trunk if sec == 1 else self.sec2)[name]
|
|
raw = self._read(sec, t)
|
|
fmt, shape = t["format"], tuple(t["shape"])
|
|
if fmt == "F32":
|
|
return np.frombuffer(raw, np.float32).reshape(shape).copy()
|
|
if fmt == "BF16":
|
|
u = np.frombuffer(raw, np.uint16).astype(np.uint32) << 16
|
|
return u.view(np.float32).reshape(shape).copy()
|
|
if fmt == "U16":
|
|
return np.frombuffer(raw, np.uint16).reshape(shape).copy()
|
|
if fmt == "I32":
|
|
return np.frombuffer(raw, np.int32).reshape(shape).copy()
|
|
return decode_sk(raw, int(fmt[1])).reshape(shape)
|
|
|
|
def expert(self, moe_i: int, eid: int):
|
|
"""(S_xd float32[inter], W_gu float32[2*inter, D], W_dn float32[D, inter], gu_code, dn_code)."""
|
|
e = self.experts[moe_i * int(self.manifest["n_experts_per_layer"]) + eid]
|
|
_, gc, dc, _, _, body_off, body_bytes, dn_off, _, _ = e
|
|
inter = int(self.cfg["moe_intermediate_size"])
|
|
D = int(self.cfg["hidden_size"])
|
|
self._f.seek(self.sec[4]["off"] + body_off)
|
|
buf = self._f.read(body_bytes)
|
|
sxd = np.frombuffer(buf[: 2 * inter], np.float16).astype(np.float32)
|
|
gu_len = (2 * inter * D // QK_S) * SB_BYTES[gc]
|
|
dn_len = (D * inter // QK_S) * SB_BYTES[dc]
|
|
wgu = decode_sk(buf[2 * inter : 2 * inter + gu_len], gc).reshape(2 * inter, D)
|
|
wdn = decode_sk(buf[dn_off : dn_off + dn_len], dc).reshape(D, inter)
|
|
return sxd, wgu, wdn, gc, dc
|
|
|
|
|
|
# --------------------------------------------------------------------------------------------------- fixture
|
|
FIXTURE_CFG = dict(
|
|
num_hidden_layers=6, first_k_dense_replace=2, layer_group_size=3, hidden_size=256, intermediate_size=512,
|
|
moe_intermediate_size=256, moe_shared_expert_intermediate_size=256, vocab_size=512, num_attention_heads=4,
|
|
head_dim=64, kv_lora_rank=128, qk_nope_head_dim=64, qk_rope_head_dim=64, v_head_dim=64, num_experts=64,
|
|
num_experts_per_tok=8, n_group=8, topk_group=4, routed_scaling_factor=2.5, rms_norm_eps=1e-6, rope_theta=6000000,
|
|
short_conv_kernel_size=4, kda_safe_gate=True, kda_lower_bound=-5.0, eos_token_id=3, pad_token_id=0,
|
|
expert_swiglu_limit_list=[0, 0, 0, 0, 4, 4], share_expert_swiglu_limit_list=[0, 0, 0, 3, 3, 5],
|
|
)
|
|
|
|
|
|
# the head geometry of the real model (KDA head dim 128, kv_lora 512, nope 128, v 128) on 2 heads: exercises the HD = 128 KDA kernel and the 512-wide latent
|
|
FIXTURE_CFG_WIDE = dict(FIXTURE_CFG, num_attention_heads=2, head_dim=128, kv_lora_rank=512, qk_nope_head_dim=128, v_head_dim=128)
|
|
|
|
|
|
def build_fixture(out_path: str, seed: int = 20261130, wide: bool = False) -> None:
|
|
rng = np.random.default_rng(seed)
|
|
c = FIXTURE_CFG_WIDE if wide else FIXTURE_CFG
|
|
D, I_d, I_m, V = c["hidden_size"], c["intermediate_size"], c["moe_intermediate_size"], c["vocab_size"]
|
|
H, hd = c["num_attention_heads"], c["head_dim"]
|
|
KL, NOPE, ROPE, VH = c["kv_lora_rank"], c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"]
|
|
NL, FK, NE = c["num_hidden_layers"], c["first_k_dense_replace"], c["num_experts"]
|
|
n_moe = NL - FK
|
|
C = H * hd
|
|
|
|
sec1, idx1 = bytearray(), []
|
|
|
|
def add1(name, fmt, arr):
|
|
arr = np.asarray(arr)
|
|
pad = (-len(sec1)) % 64
|
|
sec1.extend(b"\x00" * pad)
|
|
off = len(sec1)
|
|
if fmt == "F32":
|
|
raw = arr.astype(np.float32).tobytes()
|
|
elif fmt == "BF16":
|
|
raw = (arr.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16).tobytes()
|
|
else:
|
|
raw = encode_sk(arr, int(fmt[1]))
|
|
sec1.extend(raw)
|
|
idx1.append({"name": name, "format": fmt, "shape": list(arr.shape), "offset": off, "bytes": len(raw)})
|
|
|
|
def rn(*shape, s=0.02):
|
|
return (rng.standard_normal(shape) * s).astype(np.float32)
|
|
|
|
def norm_w(n):
|
|
return (1.0 + 0.1 * rng.standard_normal(n)).astype(np.float32)
|
|
|
|
add1("model.word_embeddings.weight", "S8_K", rn(V, D, s=0.5))
|
|
add1("model.norm.weight", "F32", norm_w(D))
|
|
add1("lm_head.weight", "S8_K", rn(V, D, s=0.1))
|
|
for il in range(NL):
|
|
p, pa = f"model.layers.{il}", f"model.layers.{il}.attention"
|
|
add1(f"{p}.input_layernorm.weight", "F32", norm_w(D))
|
|
add1(f"{p}.post_attention_layernorm.weight", "F32", norm_w(D))
|
|
if (il + 1) % c["layer_group_size"] == 0:
|
|
add1(f"{pa}.q_proj.weight", "S8_K", rn(H * (NOPE + ROPE), D, s=0.08))
|
|
add1(f"{pa}.kv_a_proj_with_mqa.weight", "S8_K", rn(KL + ROPE, D, s=0.08))
|
|
add1(f"{pa}.kv_a_layernorm.weight", "F32", norm_w(KL))
|
|
add1(f"{pa}.kv_b_proj.weight", "BF16", rn(H * (NOPE + VH), KL, s=0.12))
|
|
add1(f"{pa}.g_proj.weight", "F32", rn(H, D, s=0.1))
|
|
add1(f"{pa}.dense.weight", "S8_K", rn(D, H * VH, s=0.08))
|
|
else:
|
|
for proj in ("q_proj", "k_proj", "v_proj", "f_proj", "g_proj"):
|
|
add1(f"{pa}.{proj}.weight", "S8_K", rn(C, D, s=0.1))
|
|
add1(f"{pa}.o_proj.weight", "S8_K", rn(D, C, s=0.08))
|
|
for cv in ("q_conv1d", "k_conv1d", "v_conv1d"):
|
|
add1(f"{pa}.{cv}.weight", "F32", rn(C, 1, 4, s=0.4))
|
|
add1(f"{pa}.b_proj.weight", "F32", rn(H, D, s=0.15))
|
|
add1(f"{pa}.o_norm.weight", "F32", norm_w(hd))
|
|
add1(f"{pa}.A_log", "F32", np.log(rng.uniform(0.5, 2.0, H)).astype(np.float32))
|
|
add1(f"{pa}.dt_bias", "F32", rn(C, s=0.7))
|
|
if il < FK:
|
|
add1(f"{p}.mlp.gate_proj.weight", "S8_K", rn(I_d, D, s=0.1))
|
|
add1(f"{p}.mlp.up_proj.weight", "S8_K", rn(I_d, D, s=0.1))
|
|
add1(f"{p}.mlp.down_proj.weight", "S8_K", rn(D, I_d, s=0.08))
|
|
else:
|
|
add1(f"{p}.mlp.gate.weight", "F32", rn(NE, D, s=0.12))
|
|
add1(f"{p}.mlp.gate.expert_bias", "F32", rn(NE, s=0.05))
|
|
sh_s = 0.3 if c["share_expert_swiglu_limit_list"][il] > 0 else 0.1
|
|
add1(f"{p}.mlp.shared_experts.gate_proj.weight", "S8_K", rn(I_m, D, s=sh_s))
|
|
add1(f"{p}.mlp.shared_experts.up_proj.weight", "S8_K", rn(I_m, D, s=sh_s))
|
|
add1(f"{p}.mlp.shared_experts.down_proj.weight", "S8_K", rn(D, I_m, s=0.08))
|
|
sec1_b = pad16k(bytes(sec1))
|
|
|
|
# Section 3 + 4: slabs in (rank r, moe layer) order, rank_to_eid a random permutation per layer
|
|
r2e = np.stack([rng.permutation(NE) for _ in range(n_moe)]).astype(np.uint16)
|
|
e2r = np.zeros_like(r2e)
|
|
for m in range(n_moe):
|
|
e2r[m, r2e[m]] = np.arange(NE, dtype=np.uint16)
|
|
sec3 = bytearray(n_moe * NE * 32)
|
|
sec4 = bytearray()
|
|
codes = (4, 5, 6, 8)
|
|
for r in range(NE):
|
|
for m in range(n_moe):
|
|
il = FK + m
|
|
eid = int(r2e[m, r])
|
|
gc, dc = int(rng.choice(codes)), int(rng.choice(codes))
|
|
g_s = 0.25 if c["expert_swiglu_limit_list"][il] > 0 else 0.1
|
|
sxd = (0.5 + rng.random(I_m)).astype(np.float16)
|
|
gu = encode_sk(rn(2 * I_m, D, s=g_s), gc)
|
|
dn = encode_sk(rn(D, I_m, s=0.1), dc)
|
|
dn_off = 2 * I_m + len(gu)
|
|
slab = pad16k(sxd.tobytes() + gu + dn)
|
|
b_off = len(sec4)
|
|
sec4.extend(slab)
|
|
struct.pack_into(EXP_FMT, sec3, (m * NE + eid) * 32, eid, gc, dc, 0, 0, b_off, len(slab), dn_off, r, 0)
|
|
sec3_b, sec4_b = pad16k(bytes(sec3)), pad16k(bytes(sec4))
|
|
|
|
# Section 2: rank map + lookahead routers
|
|
sec2, idx2 = bytearray(), []
|
|
|
|
def add2(name, fmt, shape, raw):
|
|
sec2.extend(b"\x00" * ((-len(sec2)) % 64))
|
|
idx2.append({"name": name, "format": fmt, "shape": shape, "offset": len(sec2), "bytes": len(raw)})
|
|
sec2.extend(raw)
|
|
|
|
add2("sq.rank_map.rank_to_eid", "U16", [n_moe, NE], r2e.tobytes())
|
|
add2("sq.rank_map.eid_to_rank", "U16", [n_moe, NE], e2r.tobytes())
|
|
add2("sq.rank_map.freq_prob", "F32", [n_moe, NE], np.full((n_moe, NE), 8.0 / NE, np.float32).tobytes())
|
|
for tag in ("k2", "k4"):
|
|
for il in range(FK, NL):
|
|
add2(f"lookahead_router_{tag}.layers.{il}.weight", "S8_K", [NE, D], encode_sk(rn(NE, D, s=0.12), 8))
|
|
add2(f"lookahead_router_{tag}.layers.{il}.bias", "F32", [NE], rn(NE, s=0.05).tobytes())
|
|
sec2_b = pad16k(bytes(sec2))
|
|
|
|
# Section 5: golden self-check (docs: build_selfcheck_section_v11): 2560 weights per codec, x, dots
|
|
g5 = np.random.default_rng(20261128)
|
|
w5 = (g5.standard_normal(2560) * 0.04).astype(np.float32)
|
|
x5 = g5.standard_normal(2560).astype(np.float32)
|
|
x5h = fwht128(x5.astype(np.float64)).astype(np.float32)
|
|
recs, blob = [], bytearray()
|
|
for cn in (4, 5, 6, 8):
|
|
enc = encode_sk(w5, cn)
|
|
dec = decode_sk(enc, cn)
|
|
eo = len(blob)
|
|
blob.extend(enc)
|
|
do = len(blob)
|
|
blob.extend(dec.astype(np.float16).tobytes())
|
|
recs.append({"code": f"S{cn}_K", "code_id": cn, "sb_bytes": SB_BYTES[cn], "n_elems": 2560, "enc_offset": eo,
|
|
"enc_bytes": len(enc), "dec_f16_offset": do,
|
|
"dot_f32": float(np.dot(dec.astype(np.float64), x5.astype(np.float64))),
|
|
"dot_fwht128": float(np.dot(dec.astype(np.float64), x5h.astype(np.float64)))})
|
|
x_off = len(blob)
|
|
blob.extend(x5.tobytes())
|
|
hdr = json.dumps({"version": 11, "seed": 20261128, "x_offset": x_off, "records": recs}).encode()
|
|
sec5_b = pad16k(struct.pack("<I", len(hdr)) + hdr + bytes(blob))
|
|
|
|
chat_template = "{{ messages }}" # stand-in when the repo's copy of the real template is not next to this file
|
|
tpl = os.environ.get("LING32_CHAT_TEMPLATE") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "terminal", "tests", "data", "ling32", "chat_template.jinja")
|
|
if os.path.exists(tpl):
|
|
chat_template = open(tpl, encoding="utf-8", newline="").read()
|
|
manifest = {
|
|
"format": "strata/1.1", "page_alignment_bytes": PAGE, "strata_family": "bailing_moe_v3", "build": "FIXTURE",
|
|
"universal_tiered_container": True, "mla_absorbable": True,
|
|
"config": {"model_type": "bailing_moe_v3_vl", "text_config": c},
|
|
"n_moe_layers": n_moe, "n_experts_per_layer": NE,
|
|
"chat_template": chat_template, "tokenizer_json": '{"version":"1.0"}',
|
|
"trunk_tensors": idx1, "section2_tensors": idx2,
|
|
}
|
|
comp = zstd.ZstdCompressor(level=3, write_content_size=True).compress(json.dumps(manifest).encode())
|
|
rem = len(comp) % PAGE
|
|
if rem:
|
|
need = PAGE - rem
|
|
if need < 8:
|
|
need += PAGE
|
|
comp += struct.pack("<II", 0x184D2A50, need - 8) + b"\x00" * (need - 8) # trailing skippable alignment frame
|
|
order = [(1, sec1_b), (2, sec2_b), (3, sec3_b), (4, sec4_b), (5, sec5_b), (0, comp)]
|
|
cur, ents = PAGE, {}
|
|
for sid, sb in order:
|
|
ents[sid] = struct.pack(SEC_FMT, cur, len(sb), hashlib.sha256(sb).digest(), sid, 0, 0)
|
|
cur += len(sb)
|
|
hdrb = bytearray(PAGE)
|
|
hdrb[0:8] = MAGIC
|
|
struct.pack_into("<IHH", hdrb, 8, 1, 0, 6)
|
|
struct.pack_into("<H", hdrb, 0x10, 1)
|
|
for sid in range(6):
|
|
hdrb[0x20 + 64 * sid : 0x20 + 64 * (sid + 1)] = ents[sid]
|
|
with open(out_path, "wb") as f:
|
|
f.write(hdrb)
|
|
for _, sb in order:
|
|
f.write(sb)
|
|
print(f"fixture {out_path}: {os.path.getsize(out_path)} B, sections {[len(b) for _, b in order]}")
|
|
|
|
|
|
def build_mtp_fixture(out_path: str, seed: int = 20261201, wide: bool = False) -> None:
|
|
"""A tiny Ling-3.2-Air-MTP.strata (kind mtp_sidecar) for the fixture geometry: the MTP layer (MLA + MoE) with random weights, experts in codes S4 / S8 (mixed)."""
|
|
rng = np.random.default_rng(seed)
|
|
c = FIXTURE_CFG_WIDE if wide else FIXTURE_CFG
|
|
D, I_m = c["hidden_size"], c["moe_intermediate_size"]
|
|
H = c["num_attention_heads"]
|
|
KL, NOPE, ROPE, VH = c["kv_lora_rank"], c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"]
|
|
NE = c["num_experts"]
|
|
sec1, idx1 = bytearray(), []
|
|
|
|
def add1(name, fmt, arr):
|
|
arr = np.asarray(arr)
|
|
sec1.extend(b"\x00" * ((-len(sec1)) % 256))
|
|
off = len(sec1)
|
|
if fmt == "F32":
|
|
raw = arr.astype(np.float32).tobytes()
|
|
elif fmt == "BF16":
|
|
raw = (arr.astype(np.float32).view(np.uint32) >> 16).astype(np.uint16).tobytes()
|
|
else:
|
|
raw = encode_sk(arr, int(fmt[1]))
|
|
sec1.extend(raw)
|
|
idx1.append({"name": "mtp." + name, "format": fmt, "shape": list(arr.shape), "offset": off, "bytes": len(raw)})
|
|
|
|
def rn(*shape, s=0.02):
|
|
return (rng.standard_normal(shape) * s).astype(np.float32)
|
|
|
|
def norm_w(n):
|
|
return (1.0 + 0.1 * rng.standard_normal(n)).astype(np.float32)
|
|
|
|
for nm in ("input_layernorm", "post_attention_layernorm", "enorm", "hnorm", "final_layernorm"):
|
|
add1(nm + ".weight", "F32", norm_w(D))
|
|
add1("eh_proj.weight", "S8_K", rn(D, 2 * D, s=0.07))
|
|
pa = "attention"
|
|
add1(f"{pa}.q_proj.weight", "S8_K", rn(H * (NOPE + ROPE), D, s=0.08))
|
|
add1(f"{pa}.kv_a_proj_with_mqa.weight", "S8_K", rn(KL + ROPE, D, s=0.08))
|
|
add1(f"{pa}.kv_a_layernorm.weight", "F32", norm_w(KL))
|
|
add1(f"{pa}.kv_b_proj.weight", "BF16", rn(H * (NOPE + VH), KL, s=0.12))
|
|
add1(f"{pa}.g_proj.weight", "F32", rn(H, D, s=0.1))
|
|
add1(f"{pa}.dense.weight", "S8_K", rn(D, H * VH, s=0.08))
|
|
add1("mlp.gate.weight", "F32", rn(NE, D, s=0.12))
|
|
add1("mlp.gate.expert_bias", "F32", rn(NE, s=0.05))
|
|
add1("mlp.shared_experts.gate_proj.weight", "S8_K", rn(I_m, D, s=0.1))
|
|
add1("mlp.shared_experts.up_proj.weight", "S8_K", rn(I_m, D, s=0.1))
|
|
add1("mlp.shared_experts.down_proj.weight", "S8_K", rn(D, I_m, s=0.08))
|
|
sec1_b = pad16k(bytes(sec1))
|
|
sec3 = bytearray(NE * 32)
|
|
sec4 = bytearray()
|
|
for eid in range(NE):
|
|
gc, dc = int(rng.choice((4, 8))), int(rng.choice((4, 8)))
|
|
sxd = (0.5 + rng.random(I_m)).astype(np.float16)
|
|
gu = encode_sk(rn(2 * I_m, D, s=0.1), gc)
|
|
dn = encode_sk(rn(D, I_m, s=0.1), dc)
|
|
dn_off = 2 * I_m + len(gu)
|
|
slab = pad16k(sxd.tobytes() + gu + dn)
|
|
b_off = len(sec4)
|
|
sec4.extend(slab)
|
|
struct.pack_into(EXP_FMT, sec3, eid * 32, eid, gc, dc, 0, 0, b_off, len(slab), dn_off, eid, 0)
|
|
sec3_b, sec4_b = pad16k(bytes(sec3)), pad16k(bytes(sec4))
|
|
manifest = {
|
|
"format": "strata/1.1", "page_alignment_bytes": PAGE, "strata_family": "bailing_moe_v3", "kind": "mtp_sidecar", "build": "MTP-FIXTURE",
|
|
"license": {"spdx": "MIT", "text": "fixture", "attribution": "fixture"}, "mtp": {"layer_index": c["num_hidden_layers"], "gu_code": "S4_K", "dn_code": "S4_K", "dense_code": "S8_K"},
|
|
"config": {"model_type": "bailing_moe_v3_vl", "text_config": c}, "trunk_tensors": idx1, "n_moe_layers": 1, "n_experts_per_layer": NE,
|
|
}
|
|
comp = zstd.ZstdCompressor(level=3, write_content_size=True).compress(json.dumps(manifest).encode())
|
|
rem = len(comp) % PAGE
|
|
if rem:
|
|
need = PAGE - rem
|
|
if need < 8:
|
|
need += PAGE
|
|
comp += struct.pack("<II", 0x184D2A50, need - 8) + b"\x00" * (need - 8)
|
|
order = [(1, sec1_b), (2, b""), (3, sec3_b), (4, sec4_b), (5, b""), (0, comp)]
|
|
cur, ents = PAGE, {}
|
|
for sid, sb in order:
|
|
ents[sid] = struct.pack(SEC_FMT, cur, len(sb), hashlib.sha256(sb).digest(), sid, 0, 0)
|
|
cur += len(sb)
|
|
hdrb = bytearray(PAGE)
|
|
hdrb[0:8] = MAGIC
|
|
struct.pack_into("<IHH", hdrb, 8, 1, 0, 6)
|
|
struct.pack_into("<H", hdrb, 0x10, 1)
|
|
for sid in range(6):
|
|
hdrb[0x20 + 64 * sid : 0x20 + 64 * (sid + 1)] = ents[sid]
|
|
with open(out_path, "wb") as f:
|
|
f.write(hdrb)
|
|
for _, sb in order:
|
|
f.write(sb)
|
|
print(f"mtp fixture {out_path}: {os.path.getsize(out_path)} B")
|
|
|
|
|
|
# --------------------------------------------------------------------------------------------------- reference model
|
|
def rms(x, w, eps):
|
|
y = x / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps)
|
|
return y * w if w is not None else y
|
|
|
|
|
|
def sigmoid(x):
|
|
return 1.0 / (1.0 + np.exp(-x))
|
|
|
|
|
|
def silu(x):
|
|
return x * sigmoid(x)
|
|
|
|
|
|
def rope_interleaved(x, pos, theta):
|
|
"""x [..., R] pair-interleaved rotation (x[2j], x[2j+1]) at position pos."""
|
|
R = x.shape[-1]
|
|
inv = 1.0 / theta ** (np.arange(0, R, 2) / R)
|
|
a = pos * inv
|
|
c, s = np.cos(a), np.sin(a)
|
|
xe, xo = x[..., 0::2], x[..., 1::2]
|
|
out = np.empty_like(x)
|
|
out[..., 0::2] = xe * c - xo * s
|
|
out[..., 1::2] = xo * c + xe * s
|
|
return out
|
|
|
|
|
|
def swiglu(g, u, limit, clamp_order):
|
|
if limit and limit > 0:
|
|
if clamp_order == "silu_first": # python_golden_ref clamped_swiglu: silu(g) then clamp(max=limit)
|
|
a = np.minimum(silu(g), limit)
|
|
else: # doc 02 / 05: clamp g, then silu
|
|
a = silu(np.minimum(g, limit))
|
|
return a * np.clip(u, -limit, limit)
|
|
return silu(g) * u
|
|
|
|
|
|
def alf_lb_route(logits, bias, n_group, topk_group, top_k, scale):
|
|
sig = sigmoid(logits)
|
|
sb = sig + bias
|
|
ne = sig.shape[-1]
|
|
per = ne // n_group
|
|
g = np.sort(sb.reshape(n_group, per), axis=1)[:, -2:].sum(axis=1)
|
|
keep = np.argsort(-g, kind="stable")[:topk_group]
|
|
mask = np.zeros(ne, bool)
|
|
for gi in keep:
|
|
mask[gi * per : (gi + 1) * per] = True
|
|
ms = np.where(mask, sb, -np.inf)
|
|
idx = np.argsort(-ms, kind="stable")[:top_k]
|
|
raw = sig[idx]
|
|
return idx, raw / (raw.sum() + 1e-20) * scale, ms
|
|
|
|
|
|
class Ling32Ref:
|
|
def __init__(self, path: str, clamp_order: str = "silu_first"):
|
|
self.st = StrataV11(path)
|
|
self.c = self.st.cfg
|
|
self.clamp_order = clamp_order
|
|
c = self.c
|
|
self.NL, self.D = c["num_hidden_layers"], c["hidden_size"]
|
|
self.H, self.hd = c["num_attention_heads"], c["head_dim"]
|
|
self.eps = c["rms_norm_eps"]
|
|
self._cache = {}
|
|
|
|
def T(self, name):
|
|
if name not in self._cache:
|
|
self._cache[name] = self.st.tensor(name).astype(np.float64)
|
|
return self._cache[name]
|
|
|
|
def is_mla(self, il):
|
|
return (il + 1) % self.c["layer_group_size"] == 0
|
|
|
|
def forward(self, ids, dump=None, lookahead=False):
|
|
c, D, H, hd, eps = self.c, self.D, self.H, self.hd, self.eps
|
|
T = len(ids)
|
|
x = self.T("model.word_embeddings.weight")[np.asarray(ids)].copy()
|
|
if dump is not None:
|
|
dump["embed"] = x.astype(np.float32)
|
|
st = {}
|
|
x_in_all = []
|
|
for il in range(getattr(self, 'max_layers', None) or self.NL):
|
|
x_in_all.append(x.copy())
|
|
if dump is not None:
|
|
dump[f"x_in_{il}"] = x.astype(np.float32)
|
|
p, pa = f"model.layers.{il}", f"model.layers.{il}.attention"
|
|
h = rms(x, self.T(f"{p}.input_layernorm.weight"), eps)
|
|
if self.is_mla(il):
|
|
y = self._mla(il, h, pa)
|
|
else:
|
|
y = self._kda(il, h, pa)
|
|
x = x + y
|
|
cur = rms(x, self.T(f"{p}.post_attention_layernorm.weight"), eps)
|
|
if il < c["first_k_dense_replace"]:
|
|
f = swiglu(cur @ self.T(f"{p}.mlp.gate_proj.weight").T, cur @ self.T(f"{p}.mlp.up_proj.weight").T, 0, self.clamp_order)
|
|
x = x + f @ self.T(f"{p}.mlp.down_proj.weight").T
|
|
else:
|
|
x = x + self._moe(il, cur, p, dump)
|
|
if dump is not None:
|
|
dump[f"x_out_{il}"] = x.astype(np.float32)
|
|
if getattr(self, 'max_layers', None):
|
|
return x
|
|
hN = rms(x, self.T("model.norm.weight"), eps)
|
|
logits = hN @ self.T("lm_head.weight").T
|
|
if dump is not None:
|
|
dump["logits"] = logits.astype(np.float32)
|
|
self.x_in_all = x_in_all
|
|
return logits
|
|
|
|
# ---- KDA (sequential recurrence, the maths of kda_step_decode)
|
|
def _kda(self, il, h, pa):
|
|
c, H, hd, eps = self.c, self.H, self.hd, self.eps
|
|
T, C = h.shape[0], H * hd
|
|
ql, kl, vl = h @ self.T(f"{pa}.q_proj.weight").T, h @ self.T(f"{pa}.k_proj.weight").T, h @ self.T(f"{pa}.v_proj.weight").T
|
|
fr, go = h @ self.T(f"{pa}.f_proj.weight").T, h @ self.T(f"{pa}.g_proj.weight").T
|
|
beta = sigmoid(h @ self.T(f"{pa}.b_proj.weight").T)
|
|
def conv(xl, wn):
|
|
w = self.T(f"{pa}.{wn}.weight").reshape(C, 4)
|
|
pad = np.vstack([np.zeros((3, C)), xl])
|
|
y = sum(pad[j : j + T] * w[:, j] for j in range(4))
|
|
return silu(y)
|
|
qc, kc, vc = conv(ql, "q_conv1d"), conv(kl, "k_conv1d"), conv(vl, "v_conv1d")
|
|
A = np.exp(self.T(f"{pa}.A_log"))
|
|
dt = self.T(f"{pa}.dt_bias").reshape(H, hd)
|
|
onorm = self.T(f"{pa}.o_norm.weight")
|
|
lb = c["kda_lower_bound"]
|
|
S = np.zeros((H, hd, hd))
|
|
out = np.zeros((T, C))
|
|
for t in range(T):
|
|
q = qc[t].reshape(H, hd); k = kc[t].reshape(H, hd); v = vc[t].reshape(H, hd)
|
|
q = q / np.sqrt((q * q).sum(axis=-1, keepdims=True) + 1e-6) * hd ** -0.5 # fla l2norm: x * rsqrt(sum(x^2) + eps)
|
|
k = k / np.sqrt((k * k).sum(axis=-1, keepdims=True) + 1e-6)
|
|
g = lb * sigmoid(A[:, None] * (fr[t].reshape(H, hd) + dt))
|
|
S = S * np.exp(g)[:, :, None]
|
|
pred = np.einsum("hd,hdv->hv", k, S)
|
|
S = S + np.einsum("hd,hv->hdv", beta[t][:, None] * k, v - pred)
|
|
o = np.einsum("hd,hdv->hv", q, S)
|
|
og = rms(o, onorm, eps) * sigmoid(go[t].reshape(H, hd))
|
|
out[t] = og.reshape(C)
|
|
return out @ self.T(f"{pa}.o_proj.weight").T
|
|
|
|
# ---- MLA, expanded formulation (the python golden); the engine runs the absorbed one
|
|
def _mla(self, il, h, pa):
|
|
c, H, eps = self.c, self.H, self.eps
|
|
NOPE, ROPE, VH, KL = c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"], c["kv_lora_rank"]
|
|
T = h.shape[0]
|
|
q = (h @ self.T(f"{pa}.q_proj.weight").T).reshape(T, H, NOPE + ROPE)
|
|
ckv = h @ self.T(f"{pa}.kv_a_proj_with_mqa.weight").T
|
|
lat = rms(ckv[:, :KL], self.T(f"{pa}.kv_a_layernorm.weight"), eps)
|
|
kv = (lat @ self.T(f"{pa}.kv_b_proj.weight").T).reshape(T, H, NOPE + VH)
|
|
gate = sigmoid(h @ self.T(f"{pa}.g_proj.weight").T)
|
|
th = float(c["rope_theta"])
|
|
qn = q[:, :, :NOPE]
|
|
qp = np.stack([rope_interleaved(q[t, :, NOPE:], t, th) for t in range(T)])
|
|
kp = np.stack([rope_interleaved(ckv[t, KL:], t, th) for t in range(T)])
|
|
kn, vv = kv[:, :, :NOPE], kv[:, :, NOPE:]
|
|
sc = (NOPE + ROPE) ** -0.5
|
|
out = np.zeros((T, H, VH))
|
|
for t in range(T):
|
|
s = (np.einsum("hd,jhd->hj", qn[t], kn[: t + 1]) + np.einsum("hd,jd->hj", qp[t], kp[: t + 1])) * sc
|
|
s = s - s.max(axis=1, keepdims=True)
|
|
w = np.exp(s)
|
|
w /= w.sum(axis=1, keepdims=True)
|
|
out[t] = np.einsum("hj,jhv->hv", w, vv[: t + 1])
|
|
out = out * gate[:, :, None]
|
|
return out.reshape(T, H * VH) @ self.T(f"{pa}.dense.weight").T
|
|
|
|
# ---- MoE (ALF-LB router, FWHT-128 routed experts, S8_K shared expert)
|
|
def _moe(self, il, cur, p, dump):
|
|
c = self.c
|
|
T, D, I = cur.shape[0], self.D, c["moe_intermediate_size"]
|
|
wg, eb = self.T(f"{p}.mlp.gate.weight"), self.T(f"{p}.mlp.gate.expert_bias")
|
|
rlim, slim = c["expert_swiglu_limit_list"][il], c["share_expert_swiglu_limit_list"][il]
|
|
y = np.zeros((T, D))
|
|
K = c["num_experts_per_tok"]
|
|
ridx = np.zeros((T, K), np.int32)
|
|
rw = np.zeros((T, K), np.float32)
|
|
rw64 = np.zeros((T, K))
|
|
for t in range(T):
|
|
idx, w, _ = alf_lb_route(wg @ cur[t], eb, c["n_group"], c["topk_group"], K, c["routed_scaling_factor"])
|
|
ridx[t], rw[t], rw64[t] = idx, w, w
|
|
xh_all = fwht128(cur) # [T, D]
|
|
for e in np.unique(ridx): # one decode per expert, its tokens batched
|
|
toks, slots = np.where(ridx == e)
|
|
sxd, wgu, wdn, _, _ = self.st.expert(il - c["first_k_dense_replace"], int(e))
|
|
gu = xh_all[toks] @ wgu.astype(np.float64).T # [m, 2I]
|
|
a = swiglu(gu[:, :I], gu[:, I:], rlim, self.clamp_order)
|
|
hin = fwht128(a / sxd.astype(np.float64))
|
|
ye = hin @ wdn.astype(np.float64).T
|
|
np.add.at(y, toks, rw64[toks, slots][:, None] * ye)
|
|
sg = self.T(f"{p}.mlp.shared_experts.gate_proj.weight"); su = self.T(f"{p}.mlp.shared_experts.up_proj.weight")
|
|
sd = self.T(f"{p}.mlp.shared_experts.down_proj.weight")
|
|
y += swiglu(cur @ sg.T, cur @ su.T, slim, self.clamp_order) @ sd.T
|
|
if dump is not None:
|
|
dump[f"route_idx_{il}"], dump[f"route_w_{il}"] = ridx, rw
|
|
return y
|
|
|
|
# ---- lookahead router (Section 2): ranked expert ids for layer il predicted from x_in[max(0, il-k)]
|
|
def lookahead_rank(self, il, k, x_in_s):
|
|
c = self.c
|
|
tag = f"k{k}"
|
|
W = self.st.tensor(f"lookahead_router_{tag}.layers.{il}.weight", 2).astype(np.float64)
|
|
b = self.st.tensor(f"lookahead_router_{tag}.layers.{il}.bias", 2).astype(np.float64)
|
|
eb = self.T(f"model.layers.{il}.mlp.gate.expert_bias")
|
|
u = rms(x_in_s, None, 1e-6)
|
|
logits = W @ u + b
|
|
_, _, ms = alf_lb_route(logits, eb, c["n_group"], c["topk_group"], c["num_experts_per_tok"], c["routed_scaling_factor"])
|
|
return np.argsort(-ms, kind="stable")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
sp = ap.add_subparsers(dest="cmd", required=True)
|
|
a = sp.add_parser("make-fixture"); a.add_argument("out"); a.add_argument("--seed", type=int, default=20261130); a.add_argument("--wide", action="store_true")
|
|
b = sp.add_parser("ref"); b.add_argument("file"); b.add_argument("--ids", required=True); b.add_argument("--out", required=True)
|
|
b.add_argument("--clamp-order", default="silu_first"); b.add_argument("--max-layers", type=int, default=0)
|
|
m = sp.add_parser("make-mtp-fixture"); m.add_argument("out"); m.add_argument("--seed", type=int, default=20261201); m.add_argument("--wide", action="store_true")
|
|
d = sp.add_parser("codec-vectors"); d.add_argument("out")
|
|
i = sp.add_parser("info"); i.add_argument("file")
|
|
args = ap.parse_args()
|
|
if args.cmd == "make-mtp-fixture":
|
|
build_mtp_fixture(args.out, args.seed, args.wide)
|
|
elif args.cmd == "make-fixture":
|
|
build_fixture(args.out, args.seed, args.wide)
|
|
elif args.cmd == "info":
|
|
s = StrataV11(args.file)
|
|
print(json.dumps({"sections": [{k: (v.hex()[:16] if k == "sha" else v) for k, v in x.items()} for x in s.sec],
|
|
"trunk": len(s.trunk), "sec2": len(s.sec2), "experts": len(s.experts)}, indent=1))
|
|
elif args.cmd == "codec-vectors":
|
|
os.makedirs(args.out, exist_ok=True)
|
|
r = np.random.default_rng(7)
|
|
for cn in (4, 5, 6, 8):
|
|
w = (r.standard_normal(256 * 64) * (0.01 + r.random(256 * 64) * 0.05)).astype(np.float32)
|
|
enc = encode_sk(w, cn)
|
|
open(os.path.join(args.out, f"s{cn}.bin"), "wb").write(enc)
|
|
open(os.path.join(args.out, f"s{cn}.f32"), "wb").write(decode_sk(enc, cn).tobytes())
|
|
print("wrote", args.out)
|
|
elif args.cmd == "ref":
|
|
ids = [int(t) for t in args.ids.split(",")]
|
|
os.makedirs(args.out, exist_ok=True)
|
|
m = Ling32Ref(args.file, args.clamp_order)
|
|
m.max_layers = args.max_layers
|
|
dump = {}
|
|
m.forward(ids, dump)
|
|
c = m.c
|
|
for il in range(c['first_k_dense_replace'], 0 if args.max_layers else m.NL): # the Section 2 lookahead predictions, ranked, top 32 (engine: lookahead_rank)
|
|
for k in (2, 4):
|
|
s_ = max(0, il - k)
|
|
dump[f'pred_k{k}_{il}'] = np.stack([m.lookahead_rank(il, k, m.x_in_all[s_][t])[:32] for t in range(len(ids))]).astype(np.int32)
|
|
for k, v in dump.items():
|
|
v.tofile(os.path.join(args.out, f"{k}.f32" if v.dtype == np.float32 else f"{k}.i32"))
|
|
print("reference written:", args.out, "layers", m.NL, "tokens", len(ids))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|