okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
7.1 KiB133 linesraw
1"""tools/iq_fixture.py - deterministic i-quant fixtures for src/kernels/iq_parity.cpp (TODO 24).
2
3For each of the ten types iq_parity tests, writes `<out>/<name>.bin` (int32 header: the KERNEL type id,
4rows, cols - then the raw GGUF block bytes) and `<out>/<name>.f32` (rows*cols float32 reference values,
5dequantized by the same library the comparison treats as ground truth):
6
7    python tools/iq_fixture.py --out build/iq_fixture
8    python tools/iq_fixture.py --out build/iq_fixture --seed 7 --rows 32 --cols 256
9
10Generation is deterministic: an explicit seed and fixed dimensions, and every random choice comes from
11numpy's RandomState under that seed.  The blocks are synthetic on purpose: the i-quant formats have no
12published quantizer in gguf-py (it dequantizes only), so each block combines sane half-precision scales
13(written at the layout's scale offsets, see SCALE_OFFSETS below) with seeded index/sub-scale bytes - the
14dequantized reference covers real codebook values either way, which is what the parity compares.
15
16Dependencies: python3 and numpy (the dequantizers are tools/strata_quants.py, proven bit-identical to llama.cpp's gguf-py by
17tools/test_strata_gguf.py; STRATA_GGUF_PY=<gguf-py folder> uses gguf-py's instead).  Q2_0 is this repository's own format
18(GGML type 42): its codec comes from tools/gguf_writer.py.
19
20The kernel ids in the .bin headers are the repo's i-quant dispatch table (iq_kernels.cu is_iq /
21iq_row_bytes) and match the vendored gguf-py's enum ids one for one - the layout table below is the
22same GGML_QUANT_SIZES both sides compile in.
23"""
24from __future__ import annotations
25
26import argparse
27import struct
28import sys
29from pathlib import Path
30
31import numpy as np
32
33ROOT = Path(__file__).resolve().parents[1]
34sys.path.insert(0, str(ROOT / "tools"))
35
36try:
37    from _paths import gguf_lib
38    gguf = gguf_lib()                       # tools/strata_gguf.py (STRATA_GGUF_PY selects llama.cpp's gguf-py)
39    gguf_dequantize = gguf.quants.dequantize
40    from gguf_writer import dequantize_q2_0, quantize_q2_0
41except ImportError as e:  # a missing numpy must be explicit, not a traceback
42    sys.stderr.write(f"iq_fixture: missing dependency: {e}\nnumpy is required.\n")
43    sys.exit(3)
44
45QT = gguf.GGMLQuantizationType
46# name -> (block values, block bytes, the fp16 scale offsets inside a block).  The layouts mirror
47# gguf-py's dequantize_blocks implementations: every one of these formats keeps its half-precision
48# scale(s) at fixed offsets (IQ*_X*: offset 0; Q3_K: after the 32-byte hmask, 64-byte qs and the
49# 12 scale bytes) - the rest of the block is indices and sub-scales, which are seeded random bytes.
50LAYOUT = {   # (block values, block bytes) == the vendored gguf-py's GGML_QUANT_SIZES == the kernels' sizes
51    "IQ2_XXS": (256,  66),
52    "IQ2_XS":  (256,  74),
53    "IQ2_S":   (256,  82),
54    "IQ3_XXS": (256,  98),
55    "IQ3_S":   (256, 110),
56    "IQ1_M":   (256,  56),
57    "IQ4_NL":   (32,  18),
58    "IQ4_XS":  (256, 136),
59    "Q3_K":    (256, 110),
60}
61HALF_ONE = struct.pack("<e", 1.0)      # fp16 1.0 = 0x3c00: a tame, exactly-representable scale
62
63
64def repair_scales(name: str, raw: np.ndarray) -> None:
65    """Overwrite the fp16 scale bits of every block with a sane value, in place.  The index and
66    sub-scale bytes stay seeded-random (their values are bounded by construction).  Layouts mirror
67    gguf-py's dequantize_blocks: IQ*_X* and IQ4_* keep the fp16 scale at block offset 0; Q3_K keeps
68    it after the 32-byte hmask, 64-byte qs and 12 scale bytes; IQ1_M is "the only one which stores
69    the f16 scale in multiple parts" - the fp16 bits are the HIGH NIBBLES of the four uint16s at
70    bytes 48..56, so a 1.0 scale is nibbles 3, C, 0, 0 on bytes 49, 51, 54, 55."""
71    if name == "Q3_K":
72        raw[:, 108:110] = np.frombuffer(HALF_ONE, dtype=np.uint8)
73        return
74    if name == "IQ1_M":
75        raw[:, 48:56] &= np.uint8(0x0F)            # clear the four scale nibbles
76        for byte, nib in ((49, 0x30), (51, 0xC0), (54, 0x00), (55, 0x00)):
77            raw[:, byte] |= np.uint8(nib)
78        return
79    raw[:, 0:2] = np.frombuffer(HALF_ONE, dtype=np.uint8)
80# name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id)
81KERNEL_IDS = {"IQ2_XXS": 16, "IQ2_XS": 17, "IQ2_S": 22, "IQ3_XXS": 18, "IQ3_S": 21,
82              "IQ1_M": 29, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11}
83
84
85def build(name: str, rows: int, cols: int, seed: int):
86    """The .bin body (header + raw blocks) and the .f32 reference for one type."""
87    kernel_type = KERNEL_IDS[name]
88    n = rows * cols
89    rng = np.random.RandomState((seed, hash(name) & 0xFFFF) if False else (seed, KERNEL_IDS[name]))
90    if name == "Q2_0":                                 # the repository's own codec, gguf-py has no type 42
91        w = rng.standard_normal(n).astype(np.float32)
92        raw = np.frombuffer(quantize_q2_0(w), dtype=np.uint8)
93        ref = dequantize_q2_0(raw.tobytes()).astype(np.float32)
94        flat = raw
95    else:
96        block_values, block_bytes = LAYOUT[name]
97        blocks = n // block_values
98        raw = rng.randint(0, 256, (blocks, block_bytes), dtype=np.uint8)
99        repair_scales(name, raw)                       # sane fp16 scales; indices stay seeded-random
100        flat = raw.reshape(-1)
101        ref = np.asarray(gguf_dequantize(flat, getattr(QT, name)), dtype=np.float32)
102    if not np.isfinite(ref).all() or float(np.abs(ref).max()) > 1e4:
103        raise RuntimeError(f"{name}: the dequantized reference is not finite/tame - the layout table "
104                           f"(block bytes, scale offsets) does not match gguf-py's dequantizer")
105    header = struct.pack("<3i", kernel_type, rows, cols)
106    return header + flat.tobytes(), ref
107
108
109def main() -> int:
110    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
111                                 formatter_class=argparse.RawDescriptionHelpFormatter)
112    ap.add_argument("--out", default="logs/iq_fixture", help="the fixture directory (created; may live in the "
113                                                             "build directory - the source tree is not written)")
114    ap.add_argument("--seed", type=int, default=7, help="the fixture RNG seed (deterministic generation)")
115    ap.add_argument("--rows", type=int, default=32, help="weight rows (rows*cols stays a multiple of 256)")
116    ap.add_argument("--cols", type=int, default=256, help="the reduction dimension, a multiple of 256")
117    args = ap.parse_args()
118    if args.cols % 256 or args.rows * args.cols % 256:
119        ap.error("--cols must be a multiple of 256 and rows*cols a multiple of 256")
120    out = Path(args.out)
121    out.mkdir(parents=True, exist_ok=True)
122    for name in KERNEL_IDS:
123        blob, ref = build(name, args.rows, args.cols, args.seed)
124        (out / f"{name}.bin").write_bytes(blob)
125        (out / f"{name}.f32").write_bytes(np.ascontiguousarray(ref, dtype="<f4").tobytes())
126        print(f"  {name:<8} type {KERNEL_IDS[name]:>2}  {args.rows} x {args.cols}  "
127              f"{len(blob) - 12} block bytes, {ref.size} reference floats")
128    print(f"iq_fixture: {len(KERNEL_IDS)} fixtures in {out} (seed {args.seed})")
129    return 0
130
131
132if __name__ == "__main__":
133    sys.exit(main())