okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
27.8 KiB623 linesraw
1# Copyright (c) 2026 the Strata contributors (MIT).
2"""tools/dsv41/engram_iq4nl_bench.py - the Phase 1.3 IQ4_NL Engram reader: O_DIRECT row reads + host dequant.
3
4The Engram is a big IQ4_NL table (engram-IQ4_NL.gguf, 110.6 GB in helcig/tmp-oct26).  The engine, for one token,
5gathers 48 rows of it by hash (tools/dsv41/engram_hash.py gives the row ids), so the reader's job is:
6
7    random 2.3 KB row reads straight off the device (O_DIRECT: no page cache, the table does not fit in RAM),
8    dequantised on the host to f32.
9
10This is the Phase 1.3 skeleton: it does the two things the real run needs to be trusted before it is written into the
11engine - it checks the dequant against ggml's own block_IQ4_NL decode, bit for bit, and it measures the two access
12patterns (48 rows = one token; a prompt-chunk batch) on whatever file it is pointed at.
13
14The block (ggml's block_iq4_nl, third_party/ggml/ggml-common.h): 32 values, one fp16 scale `d`, 16 packed nibbles:
15
16    typedef struct { ggml_half d; uint8_t qs[16]; } block_iq4_nl;      // 18 bytes, QK4_NL = 32
17
18    y[base + j     ] = d * kvalues_iq4nl[qs[j] & 0x0F]     (j = 0..15)
19    y[base + j + 16] = d * kvalues_iq4nl[qs[j] >> 4]
20    kvalues_iq4nl = {-127,-104,-83,-65,-49,-35,-22,-10, 1, 13, 25, 38, 53, 69, 89, 113}
21
22so a row of n_embd values is (n_embd/32)*18 bytes.
23
24No model is needed to exercise it: `--make-synthetic` writes a valid GGUF with one IQ4_NL tensor (header, one tensor
25info, 32-byte alignment, random packed nibbles and small fp16 scales) of the size you ask for, and every mode runs
26against that.  What the real run needs is listed in REAL RUN below and printed by --help.
27
28    # on p1004 (no numpy there: this file is stdlib only)
29    python3 tools/dsv41/engram_iq4nl_bench.py --make-synthetic /tmp/engram-synth.gguf --size-gb 1.0
30    python3 tools/dsv41/engram_iq4nl_bench.py --gguf /tmp/engram-synth.gguf --mode all \\
31            --rows-per-token 48 --batch-tokens 256 --iters 20
32
33REAL RUN (what this needs that p1004 does not have today):
34  * the file: engram-IQ4_NL.gguf, 110.6 GB.  p1004 has 14 GB free on /data and 65 GB on /, so it needs ~50 GB freed
35    first (P1004.md's /data/launch-test + /data/rel023-amd is 71 GB).  It must sit on a real block device:
36    O_DIRECT works on ext4/xfs/nvme, not on tmpfs or overlayfs.
37  * the tensor geometry is read from the GGUF header (n_embd, n_rows); nothing is hardcoded here.
38  * `--ggml-dump`: a 3-line C++ program that calls ggml's dequantize_row_iq4_nl and prints the float bits, linked
39    against a built libggml-base.a (-I <llama.cpp>/ggml/include -I <llama.cpp>/ggml/src).  --build-ggml-dump writes
40    and compiles it from the source embedded below.  Without it the check is the script's scalar reference against
41    its own fast path, which is still bit-for-bit but not independent of this file.
42  * numpy: optional.  It is not installed on p1004, so dequant here is pure Python (~8k rows/s); the engine's dequant
43    is the C kernel in ds4_iq.cu / ds4_gg_cpu.cpp.  Use --dequant off for the I/O ceiling, --dequant sample (default)
44    for a measured dequant rate, --dequant all to dequantise the whole batch.
45  * the real 48-row gather per token is random over 110 GB: IOPS matter as much as MB/s.  --mode token is that
46    pattern; --mode batch is the prompt chunk; --mode seq is the device's sequential ceiling for reference.
47"""
48from __future__ import annotations
49
50import argparse
51import array
52import mmap
53import os
54import random
55import struct
56import subprocess
57import sys
58import tempfile
59import time
60
61# ---------------------------------------------------------------- ggml IQ4_NL
62
63QK4_NL = 32                    # values per block
64IQ4NL_ROW_DIV = 32             # n_embd must be a multiple of this
65IQ4NL_BLOCK_BYTES = 18         # fp16 d + 16 packed nibbles
66GGML_TYPE_IQ4_NL = 20          # ggml.h: IQ2_XXS 16, IQ2_XS 17, IQ3_XXS 18, IQ1_S 19, IQ4_NL 20, IQ3_S 21, IQ2_S 22
67KVALUES_IQ4NL = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
68
69
70def iq4nl_row_bytes(n_embd: int) -> int:
71    if n_embd % IQ4NL_ROW_DIV:
72        raise ValueError(f"n_embd {n_embd} is not a multiple of {IQ4NL_ROW_DIV}")
73    return (n_embd // QK4_NL) * IQ4NL_BLOCK_BYTES
74
75
76def dequant_row_iq4nl_ref(row: bytes, n_embd: int) -> array.array:
77    """ggml's dequantize_row_iq4_nl, literal: one fp16 scale per block, 16 low nibbles then 16 high ones.
78
79    Python floats are doubles; a float32 * a small integer is exact in a double (24 + 7 bits) and array('f') rounds
80    it once on store, so this reproduces ggml's float32 product bit for bit.
81    """
82    out = array.array("f")
83    nb = n_embd // QK4_NL
84    for b in range(nb):
85        base = b * IQ4NL_BLOCK_BYTES
86        d = struct.unpack_from("<e", row, base)[0]
87        qs = row[base + 2:base + IQ4NL_BLOCK_BYTES]
88        out.extend(d * KVALUES_IQ4NL[q & 0x0F] for q in qs)
89        out.extend(d * KVALUES_IQ4NL[q >> 4] for q in qs)
90    return out
91
92
93def dequant_row_iq4nl_fast(row: bytes, n_embd: int) -> array.array:
94    """The same result, with the block's 16 possible values built once: the reader's hot path."""
95    out = array.array("f")
96    nb = n_embd // QK4_NL
97    unpack = struct.unpack_from
98    kv = KVALUES_IQ4NL
99    extend = out.extend
100    for b in range(nb):
101        base = b * IQ4NL_BLOCK_BYTES
102        d = unpack("<e", row, base)[0]
103        tab = (d * kv[0], d * kv[1], d * kv[2], d * kv[3], d * kv[4], d * kv[5], d * kv[6], d * kv[7],
104               d * kv[8], d * kv[9], d * kv[10], d * kv[11], d * kv[12], d * kv[13], d * kv[14], d * kv[15])
105        qs = row[base + 2:base + IQ4NL_BLOCK_BYTES]
106        extend([tab[q & 0x0F] for q in qs])
107        extend([tab[q >> 4] for q in qs])
108    return out
109
110
111def f32_bits(vals) -> bytes:
112    return array.array("f", vals).tobytes()
113
114
115# ---------------------------------------------------------------- GGUF reader
116
117class Gguf:
118    """Just enough GGUF for one tensor: magic, version, the kv block, the tensor infos, the aligned data start."""
119
120    def __init__(self, path: str):
121        self.path = path
122        self.size = os.path.getsize(path)
123        self.tensors: list[dict] = []
124        self.meta: dict = {}
125        self.data_start = 0
126        self.alignment = 32
127        with open(path, "rb") as f:
128            magic = f.read(4)
129            if magic != b"GGUF":
130                raise ValueError(f"{path}: not a GGUF (magic {magic!r})")
131            version = struct.unpack("<I", f.read(4))[0]
132            if version not in (2, 3):
133                raise ValueError(f"{path}: GGUF v{version}, this reads v2 and v3")
134            self.version = version
135            n_tensors, n_kv = struct.unpack("<QQ", f.read(16))
136            for _ in range(n_kv):
137                k, v = self._kv(f)
138                self.meta[k] = v
139            self.alignment = int(self.meta.get("general.alignment", 32)) or 32
140            for _ in range(n_tensors):
141                name = self._str(f)
142                n_dims = struct.unpack("<I", f.read(4))[0]
143                dims = list(struct.unpack(f"<{n_dims}Q", f.read(8 * n_dims)))
144                ttype = struct.unpack("<I", f.read(4))[0]
145                off = struct.unpack("<Q", f.read(8))[0]
146                self.tensors.append({"name": name, "dims": dims, "type": ttype, "offset": off})
147            pos = f.tell()
148            self.data_start = (pos + self.alignment - 1) // self.alignment * self.alignment
149
150    @staticmethod
151    def _str(f) -> str:
152        n = struct.unpack("<Q", f.read(8))[0]
153        return f.read(n).decode("utf-8", "replace")
154
155    _SCALAR = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<B", 10: "<Q", 11: "<q", 12: "<d"}
156
157    def _kv(self, f):
158        key = self._str(f)
159        vtype = struct.unpack("<I", f.read(4))[0]
160        if vtype == 8:                                  # string
161            return key, self._str(f)
162        if vtype == 9:                                  # array
163            atype = struct.unpack("<I", f.read(4))[0]
164            n = struct.unpack("<Q", f.read(8))[0]
165            if atype == 8:
166                return key, [self._str(f) for _ in range(n)]
167            fmt = self._SCALAR[atype]
168            return key, list(struct.unpack(f"<{n}{fmt[1]}", f.read(struct.calcsize(fmt) * n)))
169        fmt = self._SCALAR[vtype]
170        return key, struct.unpack(fmt, f.read(struct.calcsize(fmt)))[0]
171
172    def tensor(self, name: str | None = None) -> dict:
173        if name is not None:
174            for t in self.tensors:
175                if t["name"] == name:
176                    return t
177            raise KeyError(f"{self.path}: no tensor {name!r}; have {[t['name'] for t in self.tensors]}")
178        for t in self.tensors:
179            if t["type"] == GGML_TYPE_IQ4_NL:
180                return t
181        raise KeyError(f"{self.path}: no IQ4_NL tensor")
182
183    def geometry(self, name: str | None = None) -> tuple[int, int, int]:
184        """(n_embd, n_rows, row_bytes) for an IQ4_NL table; dims[0] is the row length."""
185        t = self.tensor(name)
186        if t["type"] != GGML_TYPE_IQ4_NL:
187            raise ValueError(f"tensor {t['name']!r} is ggml type {t['type']}, not {GGML_TYPE_IQ4_NL} (IQ4_NL)")
188        n_embd = int(t["dims"][0])
189        n_rows = 1
190        for d in t["dims"][1:]:
191            n_rows *= int(d)
192        return n_embd, n_rows, iq4nl_row_bytes(n_embd)
193
194    def row_offset(self, t: dict, row: int) -> int:
195        """Absolute file offset of a row: the tensor's offset is relative to the data section."""
196        _, _, rb = self.geometry(t["name"])
197        return self.data_start + t["offset"] + row * rb
198
199
200# ---------------------------------------------------------------- O_DIRECT rows
201
202class RowReader:
203    """Aligned, unbuffered reads.  A row is 18*(n_embd/32) bytes (2304 for n_embd 4096), which is not a multiple of
204    the device's 512-byte block, so a row read is a 512-aligned window that is then sliced: the device moves up to
205    511 extra bytes per row and MB/s is reported both ways (payload and what the device was asked for).
206    """
207
208    def __init__(self, path: str, align: int = 512, odirect: bool = True):
209        self.path = path
210        self.align = align
211        self.size = os.path.getsize(path)
212        flags = os.O_RDONLY | (getattr(os, "O_DIRECT", 0) if odirect else 0)
213        self.odirect = bool(odirect and getattr(os, "O_DIRECT", 0))
214        try:
215            self.fd = os.open(path, flags)
216        except OSError as e:
217            if not self.odirect:
218                raise
219            print(f"  (O_DIRECT unavailable on {path}: {e}; falling back to buffered reads)", file=sys.stderr)
220            self.odirect = False
221            self.fd = os.open(path, os.O_RDONLY)
222        self._buf = None
223        self._buf_len = 0
224        self.device_bytes = 0
225
226    def _buffer(self, n: int):
227        if self._buf is None or self._buf_len < n:
228            self._buf = mmap.mmap(-1, n)          # page aligned, which is a multiple of any 512/4096 sector
229            self._buf_len = n
230        return self._buf
231
232    def read(self, off: int, length: int) -> bytes:
233        """The `length` bytes at `off`, in one aligned pread."""
234        if self.odirect:
235            a = self.align
236            start = off // a * a
237            end = min((off + length + a - 1) // a * a, self.size)
238            n = end - start
239            if n <= 0:
240                raise ValueError(f"read past end: off {off} len {length} size {self.size}")
241            buf = self._buffer(n)
242            got = os.preadv(self.fd, [memoryview(buf)[:n]], start)
243            self.device_bytes += n
244            if got != n:
245                raise OSError(f"short O_DIRECT read at {start}: {got} of {n}")
246            return bytes(memoryview(buf)[off - start:off - start + length])
247        data = os.pread(self.fd, length, off)
248        self.device_bytes += length
249        if len(data) != length:
250            raise OSError(f"short read at {off}: {len(data)} of {length}")
251        return data
252
253    def close(self):
254        if self._buf is not None:
255            self._buf.close()
256            self._buf = None
257        os.close(self.fd)
258
259
260# ---------------------------------------------------------------- synthetic file
261
262def make_synthetic(path: str, size_gb: float, n_embd: int = 4096, seed: int = 1, verbose: bool = True) -> tuple[int, int]:
263    """A valid GGUF v3 with one IQ4_NL tensor: header, one tensor info, 32-byte alignment, then the data.
264
265    The blocks are real blocks: fp16 scales in 0.002 .. 0.017 and random packed nibbles, so the dequant is exercised
266    on the file the benchmarks read.  Returns (n_rows, file bytes).
267    """
268    rb = iq4nl_row_bytes(n_embd)
269    n_rows = max(1, int(size_gb * 1e9) // rb)
270    rng = random.Random(seed)
271    scales = [0.002 + 0.001 * i for i in range(16)]
272    # 8 block templates per scale cycle, each 18 bytes: the fp16 d and 16 random nibble bytes
273    blobs = []
274    for s in scales:
275        parts = []
276        for _ in range(8):
277            parts.append(struct.pack("<e", s) + bytes(rng.getrandbits(8) for _ in range(16)))
278        blobs.append(b"".join(parts))              # 144 bytes = 8 whole blocks, so a repeat keeps block alignment
279
280    header = bytearray()
281    header += b"GGUF"
282    header += struct.pack("<I", 3)
283    header += struct.pack("<QQ", 1, 3)
284    for k, v in (("general.architecture", "engram"), ("general.name", "p1004-synthetic-iq4nl")):
285        header += struct.pack("<Q", len(k)) + k.encode()
286        header += struct.pack("<I", 8)
287        header += struct.pack("<Q", len(v)) + v.encode()
288    header += struct.pack("<Q", len("general.alignment")) + b"general.alignment"
289    header += struct.pack("<I", 4) + struct.pack("<I", 32)
290    name = b"engram.iq4nl"
291    header += struct.pack("<Q", len(name)) + name
292    header += struct.pack("<I", 2) + struct.pack("<QQ", n_embd, n_rows)
293    header += struct.pack("<I", GGML_TYPE_IQ4_NL) + struct.pack("<Q", 0)
294    header += b"\x00" * ((-len(header)) % 32)
295
296    if verbose:
297        print(f"synthetic: n_embd {n_embd} row_bytes {rb} n_rows {n_rows} data {(n_rows * rb) / 1e9:.3f} GB -> {path}")
298    chunk_rows = 64
299    written = 0
300    with open(path, "wb", buffering=1024 * 1024) as f:
301        f.write(header)
302        k = 0
303        t0 = time.time()
304        while written < n_rows:
305            rows = min(chunk_rows, n_rows - written)
306            blob = blobs[k % len(blobs)]
307            k += 1
308            buf = (blob * (rows * rb // len(blob) + 1))[:rows * rb]
309            f.write(buf)
310            written += rows
311            if verbose and written % (chunk_rows * 512) == 0:
312                print(f"\r  {written * rb / 1e9:.2f} GB", end="", file=sys.stderr)
313    total = os.path.getsize(path)
314    if verbose:
315        print(f"\r  wrote {total / 1e9:.3f} GB in {time.time() - t0:.1f} s" + " " * 20, file=sys.stderr)
316    return n_rows, total
317
318
319# ---------------------------------------------------------------- the ggml cross-check
320
321_GGML_DUMP_SRC = r"""
322// Read one IQ4_NL row from stdin, print ggml's own dequantise: one float per line, 8 hex digits of its bits.
323#include <cstdio>
324#include <cstdlib>
325#include <vector>
326extern "C" void dequantize_row_iq4_nl(const void * x, float * y, int64_t k);
327int main(int argc, char ** argv) {
328    if (argc < 2) { std::fprintf(stderr, "usage: iq4nl_dump N_EMBD < row.bin\n"); return 2; }
329    const int n = std::atoi(argv[1]);
330    const size_t rb = (size_t) (n / 32) * 18;
331    std::vector<unsigned char> row(rb);
332    if (std::fread(row.data(), 1, rb, stdin) != rb) { std::fprintf(stderr, "short read\n"); return 2; }
333    std::vector<float> y((size_t) n);
334    dequantize_row_iq4_nl(row.data(), y.data(), n);
335    for (int i = 0; i < n; ++i) {
336        unsigned int b; __builtin_memcpy(&b, &y[i], 4);
337        std::printf("%08x\n", b);
338    }
339    return 0;
340}
341"""
342
343
344def build_ggml_dump(build_dir: str, out: str | None = None) -> str:
345    """Compile the dumper against a built llama.cpp tree (ggml headers + libggml-base.a)."""
346    src_root = os.path.join(build_dir, "_deps", "strata_llamacpp-src", "ggml")
347    lib = os.path.join(build_dir, "ggml", "src", "libggml-base.a")
348    for p in (src_root, lib):
349        if not os.path.exists(p):
350            raise FileNotFoundError(f"{p} not found; pass --ggml-build-dir with a tree that built ggml")
351    out = out or os.path.join(tempfile.gettempdir(), "iq4nl_dump")
352    with open(out + ".cpp", "w") as f:
353        f.write(_GGML_DUMP_SRC)
354    cmd = ["g++", "-O2", "-std=c++17", "-I", os.path.join(src_root, "include"), "-I", os.path.join(src_root, "src"),
355           out + ".cpp", lib, "-o", out, "-lpthread", "-lm"]
356    subprocess.run(cmd, check=True)
357    return out
358
359
360def ggml_dequant_bits(dumper: str, row: bytes, n_embd: int) -> bytes:
361    """ggml's dequant of one row, as raw float32 bytes (the dumper prints the bits as %08x, so repack little-endian)."""
362    p = subprocess.run([dumper, str(n_embd)], input=row, stdout=subprocess.PIPE, check=True)
363    hx = b"".join(p.stdout.split()).decode()
364    if len(hx) != 8 * n_embd:
365        raise RuntimeError(f"the dumper printed {len(hx)} hex digits for {n_embd} values; check its n_embd argument")
366    return b"".join(struct.pack("<I", int(hx[i:i + 8], 16)) for i in range(0, len(hx), 8))
367
368
369# ---------------------------------------------------------------- benchmarks
370
371def _fmt(x, unit=""):
372    return f"{x:,.1f}{unit}" if isinstance(x, float) else f"{x:,}{unit}"
373
374
375def _dequant_rate(rows, n_embd: int, limit: int) -> tuple[float, int]:
376    """(seconds, rows) for the host dequant of rows already in memory: the CPU side, apart from the I/O."""
377    sel = rows[:limit]
378    if not sel:
379        return 0.0, 0
380    t0 = time.perf_counter()
381    for row in sel:
382        dequant_row_iq4nl_fast(row, n_embd)
383    return time.perf_counter() - t0, len(sel)
384
385
386def bench_token(gg: Gguf, t: dict, n_embd: int, n_rows: int, rb: int, args) -> dict:
387    """48 random rows per token, one aligned pread each: the decode-time pattern.  The reads are timed alone and
388    the dequant is timed afterwards on the rows already in RAM, so neither number hides the other."""
389    rnd = random.Random(args.seed)
390    tok_rows = [rnd.sample(range(n_rows), args.rows_per_token) for _ in range(args.iters)]
391    rd = RowReader(gg.path, align=args.align, odirect=args.odirect)
392    blobs = []
393    try:
394        rd.read(gg.row_offset(t, tok_rows[0][0]), rb)          # warm the path, not the cache (O_DIRECT)
395        t0 = time.perf_counter()
396        for rows in tok_rows:
397            for r in rows:
398                blobs.append(rd.read(gg.row_offset(t, r), rb))
399        dt = time.perf_counter() - t0
400    finally:
401        dev = rd.device_bytes
402        rd.close()
403    n = len(blobs)
404    out = {
405        "mode": f"token x{args.iters} ({args.rows_per_token} rows each)",
406        "seconds": dt,
407        "tokens_s": args.iters / dt,
408        "rows_s": n / dt,
409        "payload_mb_s": n * rb / dt / 1e6,
410        "device_mb_s": dev / dt / 1e6,
411        "reads": n,
412        "read_us": dt / n * 1e6,
413        "dequant": args.dequant,
414    }
415    if args.dequant != "off":
416        lim = n if args.dequant == "all" else args.rows_per_token * min(args.iters, 2)
417        ddt, dn = _dequant_rate(blobs, n_embd, lim)
418        out["dequant_rows"], out["dequant_rows_s"] = dn, dn / ddt if ddt else 0.0
419    return out
420
421
422def bench_batch(gg: Gguf, t: dict, n_embd: int, n_rows: int, rb: int, args) -> dict:
423    """A prompt chunk: batch_tokens x 48 rows, gathered at random like the engine will, plus the same rows read as
424    contiguous runs of the table (the best case: a chunk's hashes are unrelated, so the real pattern is the random
425    one).  Reads and dequant are timed apart, as in bench_token."""
426    rnd = random.Random(args.seed + 1)
427    n = args.batch_tokens * args.rows_per_token
428    rows = [rnd.randrange(n_rows) for _ in range(n)]
429    rd = RowReader(gg.path, align=args.align, odirect=args.odirect)
430    blobs = []
431    try:
432        t0 = time.perf_counter()
433        for r in rows:
434            blobs.append(rd.read(gg.row_offset(t, r), rb))
435        dt = time.perf_counter() - t0
436    finally:
437        dev = rd.device_bytes
438        rd.close()
439    out = {
440        "mode": f"batch gathered {args.batch_tokens} tokens = {n} rows",
441        "seconds": dt,
442        "tokens_s": args.batch_tokens / dt,
443        "rows_s": n / dt,
444        "payload_mb_s": n * rb / dt / 1e6,
445        "device_mb_s": dev / dt / 1e6,
446        "reads": n,
447        "read_us": dt / n * 1e6,
448        "dequant": args.dequant,
449    }
450    if args.dequant != "off":
451        lim = n if args.dequant == "all" else args.rows_per_token * 3
452        ddt, dn = _dequant_rate(blobs, n_embd, lim)
453        out["dequant_rows"], out["dequant_rows_s"] = dn, dn / ddt if ddt else 0.0
454    del blobs
455    # the same rows, contiguous: merge the sorted ids into runs and read each run with one pread
456    srows = sorted(rows)
457    runs = []
458    lo = prev = srows[0]
459    for r in srows[1:]:
460        if r == prev + 1:
461            prev = r
462            continue
463        runs.append((lo, prev))
464        lo = prev = r
465    runs.append((lo, prev))
466    rd = RowReader(gg.path, align=args.align, odirect=args.odirect)
467    try:
468        t0 = time.perf_counter()
469        got = 0
470        for lo, hi in runs:
471            got += len(rd.read(gg.row_offset(t, lo), (hi - lo + 1) * rb))
472        dt2 = time.perf_counter() - t0
473    finally:
474        dev2 = rd.device_bytes
475        rd.close()
476    out["contig"] = {
477        "mode": f"batch contiguous {args.batch_tokens} tokens = {len(runs)} runs",
478        "seconds": dt2,
479        "tokens_s": args.batch_tokens / dt2,
480        "rows_s": got / rb / dt2,
481        "payload_mb_s": got / dt2 / 1e6,
482        "device_mb_s": dev2 / dt2 / 1e6,
483        "reads": len(runs),
484        "read_us": dt2 / max(1, len(runs)) * 1e6,
485        "dequant": "off",
486    }
487    return out
488
489
490def bench_seq(gg: Gguf, rb: int, args) -> dict:
491    """The device's sequential ceiling through the same O_DIRECT path (rows/s is that ceiling in 2.3 KB rows)."""
492    mb = min(args.seq_mb, gg.size // (1024 * 1024))
493    rd = RowReader(gg.path, align=args.align, odirect=args.odirect)
494    chunk = args.align * 1024                              # 512 KiB
495    try:
496        rd.read(0, chunk)
497        t0 = time.perf_counter()
498        off = 0
499        total = 0
500        while total < mb * 1024 * 1024:
501            n = min(chunk, gg.size - off)
502            if n <= 0:
503                break
504            rd.read(off, n)
505            off += n
506            total += n
507        dt = time.perf_counter() - t0
508    finally:
509        dev = rd.device_bytes
510        rd.close()
511    return {"mode": f"sequential {total / 1e6:.0f} MB, {chunk // 1024} KiB reads", "seconds": dt,
512            "rows_s": total / rb / dt, "payload_mb_s": total / dt / 1e6, "device_mb_s": dev / dt / 1e6,
513            "reads": total // chunk, "read_us": dt / max(1, total // chunk) * 1e6, "dequant": "off"}
514
515
516# ---------------------------------------------------------------- main
517
518def main(argv=None) -> int:
519    ap = argparse.ArgumentParser(description=__doc__,
520                                 formatter_class=argparse.RawDescriptionHelpFormatter)
521    ap.add_argument("--gguf", help="the Engram GGUF (or a synthetic one)")
522    ap.add_argument("--tensor", default=None, help="tensor name (default: the first IQ4_NL tensor)")
523    ap.add_argument("--mode", default="all", choices=["header", "token", "batch", "seq", "all"])
524    ap.add_argument("--rows-per-token", type=int, default=48)
525    ap.add_argument("--batch-tokens", type=int, default=256)
526    ap.add_argument("--iters", type=int, default=20)
527    ap.add_argument("--seq-mb", type=int, default=512)
528    ap.add_argument("--align", type=int, default=512, help="O_DIRECT alignment (the device's logical block size)")
529    ap.add_argument("--odirect", action="store_true", default=True)
530    ap.add_argument("--no-odirect", dest="odirect", action="store_false")
531    ap.add_argument("--dequant", default="sample", choices=["off", "sample", "all"])
532    ap.add_argument("--seed", type=int, default=1)
533    ap.add_argument("--verify-rows", type=int, default=8, help="rows checked bit-exactly against ggml")
534    ap.add_argument("--ggml-dump", help="a compiled ggml IQ4_NL dequant dumper (see --build-ggml-dump)")
535    ap.add_argument("--build-ggml-dump", action="store_true", help="compile the dumper from the source embedded here")
536    ap.add_argument("--ggml-build-dir", default="/data/dsv41-build", help="a Strata build tree with ggml built")
537    ap.add_argument("--make-synthetic", metavar="PATH", help="write a synthetic IQ4_NL GGUF and exit (unless --gguf)")
538    ap.add_argument("--size-gb", type=float, default=1.0)
539    ap.add_argument("--n-embd", type=int, default=4096)
540    args = ap.parse_args(argv)
541
542    if args.make_synthetic:
543        make_synthetic(args.make_synthetic, args.size_gb, args.n_embd, args.seed)
544        if not args.gguf:
545            args.gguf = args.make_synthetic
546            if args.mode == "all":
547                args.mode = "header"
548    if not args.gguf:
549        ap.error("--gguf or --make-synthetic is required")
550
551    gg = Gguf(args.gguf)
552    t = gg.tensor(args.tensor)
553    n_embd, n_rows, rb = gg.geometry(args.tensor)
554    print(f"{gg.path}: {gg.size / 1e9:.3f} GB, GGUF v{gg.meta.get('general.version', 3)}, {len(gg.tensors)} tensor(s), "
555          f"alignment {gg.alignment}, data at {gg.data_start}")
556    print(f"  tensor {t['name']!r}: type {t['type']} (IQ4_NL), dims {t['dims']}, n_embd {n_embd}, n_rows {n_rows}, "
557          f"row_bytes {rb}, table {(n_rows * rb) / 1e9:.3f} GB")
558    if t["type"] != GGML_TYPE_IQ4_NL:
559        print(f"  not an IQ4_NL tensor: nothing to read", file=sys.stderr)
560        return 2
561
562    # the bit-exact check, always: the scalar reference against the fast path, then against ggml itself
563    rnd = random.Random(args.seed + 7)
564    dumper = args.ggml_dump
565    if args.build_ggml_dump:
566        dumper = build_ggml_dump(args.ggml_build_dir, dumper)
567        print(f"  built the ggml dumper: {dumper}")
568    rd = RowReader(gg.path, align=args.align, odirect=args.odirect)
569    bad = 0
570    checked = 0
571    try:
572        for _ in range(args.verify_rows):
573            r = rnd.randrange(n_rows)
574            row = rd.read(gg.row_offset(t, r), rb)
575            ref = dequant_row_iq4nl_ref(row, n_embd)
576            fast = dequant_row_iq4nl_fast(row, n_embd)
577            if f32_bits(ref) != f32_bits(fast):
578                bad += 1
579                print(f"  row {r}: the scalar reference and the fast path differ", file=sys.stderr)
580            if dumper:
581                gw = ggml_dequant_bits(dumper, row, n_embd)
582                if gw != f32_bits(ref):
583                    bad += 1
584                    print(f"  row {r}: ggml's dequant differs from the reference", file=sys.stderr)
585            checked += 1
586    finally:
587        rd.close()
588    print(f"  bit-exact: {checked - bad}/{checked} rows" + (" against ggml's dequantize_row_iq4_nl" if dumper else
589                                                             " (reference vs fast path; no --ggml-dump given)")
590          + ("  FAIL" if bad else "  OK"))
591    if bad:
592        return 1
593
594    if args.mode == "header":
595        return 0
596
597    results = []
598    if args.mode in ("seq", "all"):
599        results.append(bench_seq(gg, rb, args))
600    if args.mode in ("token", "all"):
601        results.append(bench_token(gg, t, n_embd, n_rows, rb, args))
602    if args.mode in ("batch", "all"):
603        b = bench_batch(gg, t, n_embd, n_rows, rb, args)
604        results.append(b["contig"])
605        results.append(b)
606        results.sort(key=lambda x: -x["payload_mb_s"])
607    print()
608    print(f"  {'pattern':44s} {'s':>8s} {'rows/s':>11s} {'tokens/s':>9s} {'MB/s payload':>12s} {'MB/s device':>11s} "
609          f"{'us/read':>8s} {'dequant rows/s':>14s}")
610    for r in results:
611        tok = f"{r['tokens_s']:.1f}" if "tokens_s" in r else "-"
612        dq = f"{r['dequant_rows_s']:,.0f} ({r['dequant_rows']} rows)" if r.get("dequant_rows_s") else r["dequant"]
613        print(f"  {r['mode']:44s} {r['seconds']:8.3f} {r['rows_s']:11,.0f} {tok:>9s} {r['payload_mb_s']:12,.1f} "
614              f"{r['device_mb_s']:11,.1f} {r['read_us']:8,.1f} {dq:>14s}")
615    print(f"\n  note: O_DIRECT {'on' if args.odirect else 'off'}, alignment {args.align} B; "
616          f"payload MB/s counts row bytes only, device MB/s what the reads actually asked for")
617    print("  the dequant rate is measured apart from the reads (rows/s of the host dequant); the engine's dequant is "
618          "the C kernel, not this Python")
619    return 0
620
621
622if __name__ == "__main__":
623    sys.exit(main())