okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
5.6 KiB122 linesraw
1"""Strata P0.S9 - build the pack-layout expert arena from the real GGUF.
2
3The architecture (§3.2) defines one expert blob as 1,382,400 bytes:
4
5    gate_up.codes   2 x 640 rows x 640 B   rows interleaved g0,u0,g1,u1,...  (share input x)
6    down.codes      2,560 rows x 160 B
7    gate_up.scales  2 x 640 x 40 x FP16
8    down.scales     2,560 x 10 x FP16
9
10and that totals exactly 819,200 + 409,600 + 102,400 + 51,200 = 1,382,400 B, matching the artifact's
11Q2_0 expert size to the byte. The conversion is a pure relayout: Q2_0 codes and their FP16 block
12scale are copied unchanged, so dequant(pack) == dequant(ggml) bit-exactly.
13
14Why build this at all rather than read the GGUF in place: the GGUF stores gate, up and down as three
15separate tensors, so a fused gate/up pass would read two streams from three arrays. The pack
16interleaves gate and up ROWS so one pass over the activation vector serves both, which is the whole
17point of the blob layout.
18
19Expert index is the LAST axis of [in, out, experts] (P0.S6), and ne[0] varies fastest, so expert `e`
20is one CONTIGUOUS 460,800-byte run inside each role tensor. Extraction is a strided copy.
21
22Run: python tools/pack_layer.py [n_layers]     (default 1; 48 = the full 34 GB arena)
23"""
24from __future__ import annotations
25
26import json
27import pathlib
28import sys
29
30import numpy as np
31
32sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
33from gguf_reader import GGUFFile  # noqa: E402
34
35REPO = pathlib.Path(__file__).resolve().parents[1]
36STRATA = REPO.parents[min(1, len(REPO.parents) - 1)]   # the dev layout's default shards (setup.py passes --gguf)
37SHARD1 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
38
39H, FF, NE = 2560, 640, 512
40QK, BLOCK_BYTES = 64, 18          # Q2_0
41ROW_BYTES_GU = H * 2 // 8         # 640 B of codes for one 2,560-wide row
42ROW_BYTES_D = FF * 2 // 8         # 160 B of codes for one 640-wide row
43SCALES_GU = H // QK               # 40 blocks per gate/up row
44SCALES_D = FF // QK               # 10 blocks per down row
45ROLE_BYTES = H * FF * BLOCK_BYTES // QK     # 460,800 B per role per expert
46BLOB_BYTES = 3 * ROLE_BYTES                 # 1,382,400
47
48assert BLOB_BYTES == 1_382_400, BLOB_BYTES
49assert 2 * 640 * ROW_BYTES_GU + 2560 * ROW_BYTES_D + 2 * 640 * SCALES_GU * 2 \
50    + 2560 * SCALES_D * 2 == BLOB_BYTES
51
52
53def blob_offsets() -> dict[str, int]:
54    gu_codes = 0
55    d_codes = gu_codes + 2 * FF * ROW_BYTES_GU
56    gu_scales = d_codes + H * ROW_BYTES_D
57    d_scales = gu_scales + 2 * FF * SCALES_GU * 2
58    end = d_scales + H * SCALES_D * 2
59    assert end == BLOB_BYTES, end
60    return {"gate_up_codes": gu_codes, "down_codes": d_codes,
61            "gate_up_scales": gu_scales, "down_scales": d_scales}
62
63
64OFF = blob_offsets()
65
66
67def build(n_layers: int, out_path: pathlib.Path) -> dict:
68    g = GGUFFile(SHARD1)
69    by_name = {t.name: t for t in g.tensors}
70    src = open(SHARD1, "rb")
71    manifest = {"blob_bytes": BLOB_BYTES, "offsets": OFF, "layers": [], "n_layers": n_layers}
72    total = n_layers * NE * BLOB_BYTES
73    out_path.parent.mkdir(parents=True, exist_ok=True)
74
75    with out_path.open("wb") as out:
76        for layer in range(n_layers):
77            roles = {}
78            for role in ("gate", "up", "down"):
79                t = by_name[f"blk.{layer}.ffn_{role}_exps.weight"]
80                roles[role] = t
81                assert t.type_name == "Q2_0", t.type_name
82                # expert e is a contiguous run inside the role tensor
83                per_expert = t.elements // NE
84                assert per_expert * BLOCK_BYTES // QK == ROLE_BYTES, per_expert
85            layer_off = out.tell()
86            # vectorized over the layer's 512 experts (the same bytes the per-block loop wrote; tools/strata_pack.py
87            # verify checks them): each role is (512 experts, rows, blocks per row, 18 bytes)
88            def role_blocks(role, rows, per_row):
89                t = roles[role]
90                n = NE * ROLE_BYTES
91                src.seek(g.data_start + t.offset)
92                a = np.frombuffer(src.read(n), dtype=np.uint8)
93                assert a.size == n, (role, a.size)
94                return a.reshape(NE, rows, per_row, BLOCK_BYTES)
95            gate = role_blocks("gate", FF, SCALES_GU)
96            up = role_blocks("up", FF, SCALES_GU)
97            down = role_blocks("down", H, SCALES_D)
98            gu = np.stack([gate, up], axis=2).reshape(NE, 2 * FF, SCALES_GU, BLOCK_BYTES)   # rows g0,u0,g1,u1,...
99            blobs = np.concatenate([
100                gu[:, :, :, 2:].reshape(NE, -1),        # gate/up codes
101                down[:, :, :, 2:].reshape(NE, -1),      # down codes
102                gu[:, :, :, :2].reshape(NE, -1),        # gate/up fp16 scales
103                down[:, :, :, :2].reshape(NE, -1),      # down fp16 scales
104            ], axis=1)
105            assert blobs.shape == (NE, BLOB_BYTES), blobs.shape
106            out.write(blobs.tobytes())
107            manifest["layers"].append({"layer": layer, "offset": layer_off,
108                                       "role_offsets": {r: by_name[f"blk.{layer}.ffn_{r}_exps.weight"].offset
109                                                        for r in ("gate", "up", "down")}})
110            print(f"  layer {layer}: wrote {NE} blobs at {layer_off}")
111    src.close()
112    manifest["total_bytes"] = total
113    (out_path.with_suffix(".json")).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
114    return manifest
115
116
117if __name__ == "__main__":
118    n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
119    dest = REPO / "pack" / ("layer0.bin" if n == 1 else f"experts-{n}l.bin")
120    print(f"building {n} layer(s) -> {dest}  ({(n*NE*BLOB_BYTES)/2**30:.2f} GiB)")
121    m = build(n, dest)
122    print(f"done: {m['total_bytes']/2**30:.2f} GiB, {n*NE} blobs")