okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
10.0 KiB234 linesraw
1"""A minimal GGUF v3 WRITER, including `Q2_0`.
2
3Why this exists
4---------------
5P1.S1 of the plan says the tiny synthetic model is "written as a real GGUF via `gguf-py`" using
6"at least `Q2_0`". That does not work: `gguf-py` has no `GGMLQuantizationType` member for type 42, so
7`GGMLQuantizationType(42)` raises `ValueError`. Verified in round 39 and again here.
8
9`src/artifact/` needs a writer regardless - P1.S2 requires a reader with no ggml dependency, and the
10writer is its companion - so this is that writer in Python, where it can be validated immediately
11against `tools/gguf_reader.py` and against llama.cpp.
12
13Scope: enough to build the P1.S1 tiny model. It is NOT a general-purpose quantizer; the only
14quantizer implemented is `Q2_0`, and its contract is `docs/q2_0-contract.md`:
15    block = 64 elements, fp16 scale, 16 bytes of 2-bit codes, LSB-first, 4 codes per byte
16    d = amax, code = clamp(round(w/d) + 1, 0, 3), symbol = code - 1  ->  {-1, 0, +1, +2}
17
18Self-checking: `python tools/gguf_writer.py` writes a synthetic v3 file, reads it back with
19`gguf_reader.py`, and asserts the tensors and metadata survived byte-exactly.
20"""
21from __future__ import annotations
22
23import dataclasses
24import pathlib
25import struct
26import sys
27
28import numpy as np
29
30sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
31from gguf_reader import GGUF_MAGIC, GGUFFile  # noqa: E402
32
33# ggml_type ids we can write. Values match GGML_TYPES in gguf_reader.py.
34TYPE_IDS = {"F32": 0, "F16": 1, "Q2_0": 42}
35DEFAULT_ALIGNMENT = 32
36
37_META_IDS = {"u8": 0, "i8": 1, "u16": 2, "i16": 3, "u32": 4, "i32": 5, "f32": 6,
38             "bool": 7, "string": 8, "array": 9, "u64": 10, "i64": 11, "f64": 12}
39
40
41# ------------------------------------------------------------------ Q2_0, per docs/q2_0-contract.md
42def quantize_q2_0(w: np.ndarray) -> bytes:
43    """(n,) float32 -> concatenated 18-byte blocks. n must be a multiple of 64."""
44    w = np.asarray(w, dtype=np.float32).reshape(-1)
45    if w.size % 64:
46        raise ValueError(f"Q2_0 needs a multiple of 64 elements, got {w.size}")
47    blocks = w.reshape(-1, 64)
48    out = bytearray()
49    for b in blocks:
50        amax = float(np.max(np.abs(b)))
51        d = amax
52        # d = amax (NOT amax/2) - the grid is asymmetric, symbols land in {-1,0,+1,+2}.
53        code = np.zeros(64, dtype=np.uint8) if d == 0 else \
54            np.clip(np.rint(b / d).astype(np.int32) + 1, 0, 3).astype(np.uint8)
55        packed = np.zeros(16, dtype=np.uint8)
56        # j -> byte j//4, bit (j%4)*2 ;  four codes per byte, least significant first.
57        for j in range(64):
58            packed[j // 4] |= np.uint8(code[j] << ((j % 4) * 2))
59        out += struct.pack("<e", d)      # fp16 scale
60        out += packed.tobytes()
61    return bytes(out)
62
63
64def dequantize_q2_0(raw: bytes) -> np.ndarray:
65    """Inverse of the above, for the round-trip check. Mirrors `dequantize_row_q2_0`."""
66    nblocks = len(raw) // 18
67    out = np.empty(nblocks * 64, dtype=np.float32)
68    for i in range(nblocks):
69        d = struct.unpack_from("<e", raw, i * 18)[0]
70        qs = raw[i * 18 + 2: i * 18 + 18]
71        for j in range(64):
72            c = (qs[j // 4] >> ((j % 4) * 2)) & 0x03
73            out[i * 64 + j] = (c - 1) * d
74    return out
75
76
77# ------------------------------------------------------------------ writer
78@dataclasses.dataclass
79class _Tensor:
80    name: str
81    shape: list[int]          # GGUF order: dim 0 varies fastest
82    type_name: str
83    data: bytes
84
85
86class GGUFWriter:
87    def __init__(self, alignment: int = DEFAULT_ALIGNMENT):
88        self.alignment = alignment
89        self.metadata: dict[str, tuple[str, object]] = {}
90        self.tensors: list[_Tensor] = []
91
92    # ---- metadata
93    def add(self, key: str, value, type_name: str | None = None) -> None:
94        if type_name is None:
95            type_name = {bool: "bool", int: "i64", float: "f64", str: "string"}.get(type(value))
96        if type_name is None:
97            if isinstance(value, list) and value:
98                elem = {bool: "bool", int: "i32", float: "f32", str: "string"}.get(type(value[0]))
99                if elem is None:
100                    raise TypeError(f"unsupported array element {type(value[0])} for {key}")
101                type_name = "array:" + elem
102            else:
103                raise TypeError(f"cannot infer a GGUF type for {key}")
104        self.metadata[key] = (type_name, value)
105
106    # ---- tensors
107    def add_f32(self, name: str, arr: np.ndarray) -> None:
108        a = np.ascontiguousarray(arr, dtype="<f4")
109        self.tensors.append(_Tensor(name, list(a.shape), "F32", a.tobytes()))
110
111    def add_q2_0(self, name: str, arr: np.ndarray, shape: list[int]) -> None:
112        """`arr` is (rows, in_features) row-major with every row `shape[0]` long; `shape` is the FULL
113        GGUF shape. The shape must be passed explicitly, not inferred as [in, rows]: a fused expert
114        tensor is [in, out, experts], and inferring 2-D produced `[64, 4096]` where llama.cpp expects
115        `[64, 256, 16]`. Q2_0 blocks run along dim 0 only, so the extra axes are just a layout.
116        """
117        a = np.asarray(arr, dtype=np.float32)
118        in_features = shape[0]
119        if a.ndim != 2 or a.shape[1] != in_features:
120            raise ValueError(f"{name}: expected (rows, {in_features}), got {a.shape}")
121        if a.shape[0] * in_features != int(np.prod(shape)):
122            raise ValueError(f"{name}: {a.shape} does not cover shape {shape}")
123        per_row = quantize_q2_0(a.reshape(-1))          # row-major: row 0 first
124        self.tensors.append(_Tensor(name, list(shape), "Q2_0", per_row))
125
126    # ---- serialisation
127    def _kv_bytes(self, key: str, type_name: str, value) -> bytes:
128        out = bytearray()
129        out += struct.pack("<Q", len(key)) + key.encode("utf-8")
130        if type_name.startswith("array:"):
131            elem = type_name.split(":", 1)[1]
132            out += struct.pack("<I", _META_IDS["array"])
133            out += struct.pack("<I", _META_IDS[elem])
134            out += struct.pack("<Q", len(value))
135            for v in value:
136                out += self._scalar(elem, v)
137            return bytes(out)
138        out += struct.pack("<I", _META_IDS[type_name])
139        out += self._scalar(type_name, value)
140        return bytes(out)
141
142    @staticmethod
143    def _scalar(type_name: str, v) -> bytes:
144        if type_name == "string":
145            b = v.encode("utf-8")
146            return struct.pack("<Q", len(b)) + b
147        fmt = {"u8": "<B", "i8": "<b", "u16": "<H", "i16": "<h", "u32": "<I", "i32": "<i",
148               "f32": "<f", "bool": "<?", "u64": "<Q", "i64": "<q", "f64": "<d"}[type_name]
149        return struct.pack(fmt, v)
150
151    def write(self, path) -> pathlib.Path:
152        path = pathlib.Path(path)
153        body = bytearray()
154        body += struct.pack("<I", GGUF_MAGIC)
155        body += struct.pack("<I", 3)                       # GGUF v3
156        body += struct.pack("<Q", len(self.tensors))
157        body += struct.pack("<Q", len(self.metadata))
158        for k, (t, v) in self.metadata.items():
159            body += self._kv_bytes(k, t, v)
160
161        # Tensor directory: offsets are relative to the start of the data section.
162        offset = 0
163        infos = bytearray()
164        for t in self.tensors:
165            infos += struct.pack("<Q", len(t.name)) + t.name.encode("utf-8")
166            infos += struct.pack("<I", len(t.shape))
167            infos += struct.pack(f"<{len(t.shape)}Q", *t.shape)
168            infos += struct.pack("<I", TYPE_IDS[t.type_name])
169            infos += struct.pack("<Q", offset)
170            offset += len(t.data)
171            offset = (offset + self.alignment - 1) // self.alignment * self.alignment
172        body += infos
173
174        pad = (-len(body)) % self.alignment
175        body += b"\0" * pad
176        for t in self.tensors:
177            body += t.data
178            pad = (-len(t.data)) % self.alignment
179            body += b"\0" * pad
180
181        path.write_bytes(bytes(body))
182        return path
183
184
185# ------------------------------------------------------------------ self-check
186def _selfcheck() -> int:
187    rng = np.random.default_rng(7)
188    w = GGUFWriter()
189    w.add("general.architecture", "qwen4exp")
190    w.add("qwen4exp.block_count", 8, "u32")
191    w.add("qwen4exp.test.array", [1, 2, 3, 4], "array:i32")
192    w.add("general.name", "strata tiny")
193
194    A = rng.standard_normal((16, 64)).astype(np.float32)
195    B = rng.standard_normal((4, 8)).astype(np.float32)
196    w.add_q2_0("blk.0.ffn_gate_exps.weight", A, 64)
197    w.add_f32("blk.0.ssm_a", B)
198
199    p = pathlib.Path(__file__).resolve().parent.parent / "bench" / "tiny-selftest.gguf"
200    w.write(p)
201    print(f"wrote {p.name}  ({p.stat().st_size} B)")
202
203    g = GGUFFile(p)
204    ok = True
205    print(f"  version {g.version}  tensors {len(g.tensors)}  metadata {len(g.metadata)}")
206    if g.metadata.get("general.architecture") != "qwen4exp": print("  FAIL arch"); ok = False
207    if g.metadata.get("qwen4exp.block_count") != 8:         print("  FAIL u32"); ok = False
208    if g.metadata.get("qwen4exp.test.array") != [1, 2, 3, 4]: print("  FAIL array"); ok = False
209
210    by = {t.name: t for t in g.tensors}
211    t = by.get("blk.0.ffn_gate_exps.weight")
212    if t is None or t.type_name != "Q2_0" or t.shape != [64, 16]:
213        print(f"  FAIL tensor dir: {t}"); ok = False
214    else:
215        with p.open("rb") as fh:
216            fh.seek(g.data_start + t.offset)
217            raw = fh.read(16 * 18)
218        back = dequantize_q2_0(raw)
219        err = np.abs(back - A.reshape(-1)).max()
220        rel = float(np.abs(back - A.reshape(-1)).mean() / np.abs(A).mean())
221        print(f"  Q2_0 round trip: max abs {err:.4f}  mean rel {rel*100:.2f}%  "
222              f"(quantization error, not a write bug)")
223        # The real check: re-quantizing the DEQUANTIZED values must be a fixed point.
224        again = dequantize_q2_0(quantize_q2_0(back))
225        if not np.array_equal(again, back):
226            print("  FAIL Q2_0 is not a fixed point under requantization"); ok = False
227        else:
228            print("  Q2_0 fixed point: PASS (requantizing the dequantized values is exact)")
229    print("SELF-CHECK " + ("PASS" if ok else "FAIL"))
230    return 0 if ok else 1
231
232
233if __name__ == "__main__":
234    raise SystemExit(_selfcheck())