okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
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 7random 2.3 KB row reads straight off the device (O_DIRECT: no page cache, the table does not fit in RAM), 8dequantised 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 16typedef struct { ggml_half d; uint8_t qs[16]; } block_iq4_nl; // 18 bytes, QK4_NL = 32 17 18y[base + j ] = d * kvalues_iq4nl[qs[j] & 0x0F] (j = 0..15) 19y[base + j + 16] = d * kvalues_iq4nl[qs[j] >> 4] 20kvalues_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) 29python3 tools/dsv41/engram_iq4nl_bench.py --make-synthetic /tmp/engram-synth.gguf --size-gb 1.0 30python3 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 35first (P1004.md's /data/launch-test + /data/rel023-amd is 71 GB). It must sit on a real block device: 36O_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 39against a built libggml-base.a (-I <llama.cpp>/ggml/include -I <llama.cpp>/ggml/src). --build-ggml-dump writes 40and compiles it from the source embedded below. Without it the check is the script's scalar reference against 41its 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 43is the C kernel in ds4_iq.cu / ds4_gg_cpu.cpp. Use --dequant off for the I/O ceiling, --dequant sample (default) 44for 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 46pattern; --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 : 71if n_embd % IQ4NL_ROW_DIV : 72raise ValueError (f"n_embd { n_embd } is not a multiple of { IQ4NL_ROW_DIV } " ) 73return (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 79Python floats are doubles; a float32 * a small integer is exact in a double (24 + 7 bits) and array('f') rounds 80it once on store, so this reproduces ggml's float32 product bit for bit. 81""" 82out = array .array ("f" ) 83nb = n_embd // QK4_NL 84for b in range (nb ): 85base = b * IQ4NL_BLOCK_BYTES 86d = struct .unpack_from ("<e" ,row ,base )[0 ] 87qs = row [base + 2 :base + IQ4NL_BLOCK_BYTES ] 88out .extend (d * KVALUES_IQ4NL [q & 0x0F ]for q in qs ) 89out .extend (d * KVALUES_IQ4NL [q >> 4 ]for q in qs ) 90return 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.""" 95out = array .array ("f" ) 96nb = n_embd // QK4_NL 97unpack = struct .unpack_from 98kv = KVALUES_IQ4NL 99extend = out .extend 100for b in range (nb ): 101base = b * IQ4NL_BLOCK_BYTES 102d = unpack ("<e" ,row ,base )[0 ] 103tab = (d * kv [0 ],d * kv [1 ],d * kv [2 ],d * kv [3 ],d * kv [4 ],d * kv [5 ],d * kv [6 ],d * kv [7 ], 104d * kv [8 ],d * kv [9 ],d * kv [10 ],d * kv [11 ],d * kv [12 ],d * kv [13 ],d * kv [14 ],d * kv [15 ]) 105qs = row [base + 2 :base + IQ4NL_BLOCK_BYTES ] 106extend ([tab [q & 0x0F ]for q in qs ]) 107extend ([tab [q >> 4 ]for q in qs ]) 108return out 109 110 111def f32_bits (vals )-> bytes : 112return 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 120def __init__ (self ,path :str ): 121self .path = path 122self .size = os .path .getsize (path ) 123self .tensors :list [dict ]= [] 124self .meta :dict = {} 125self .data_start = 0 126self .alignment = 32 127with open (path ,"rb" )as f : 128magic = f .read (4 ) 129if magic != b"GGUF" : 130raise ValueError (f" { path } : not a GGUF (magic { magic !r } )" ) 131version = struct .unpack ("<I" ,f .read (4 ))[0 ] 132if version not in (2 ,3 ): 133raise ValueError (f" { path } : GGUF v { version } , this reads v2 and v3" ) 134self .version = version 135n_tensors ,n_kv = struct .unpack ("<QQ" ,f .read (16 )) 136for _ in range (n_kv ): 137k ,v = self ._kv (f ) 138self .meta [k ]= v 139self .alignment = int (self .meta .get ("general.alignment" ,32 ))or 32 140for _ in range (n_tensors ): 141name = self ._str (f ) 142n_dims = struct .unpack ("<I" ,f .read (4 ))[0 ] 143dims = list (struct .unpack (f"< { n_dims } Q" ,f .read (8 * n_dims ))) 144ttype = struct .unpack ("<I" ,f .read (4 ))[0 ] 145off = struct .unpack ("<Q" ,f .read (8 ))[0 ] 146self .tensors .append ({"name" :name ,"dims" :dims ,"type" :ttype ,"offset" :off }) 147pos = f .tell () 148self .data_start = (pos + self .alignment - 1 )// self .alignment * self .alignment 149 150@staticmethod 151def _str (f )-> str : 152n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 153return 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 157def _kv (self ,f ): 158key = self ._str (f ) 159vtype = struct .unpack ("<I" ,f .read (4 ))[0 ] 160if vtype == 8 :# string 161return key ,self ._str (f ) 162if vtype == 9 :# array 163atype = struct .unpack ("<I" ,f .read (4 ))[0 ] 164n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 165if atype == 8 : 166return key , [self ._str (f )for _ in range (n )] 167fmt = self ._SCALAR [atype ] 168return key ,list (struct .unpack (f"< { n } { fmt [ 1 ] } " ,f .read (struct .calcsize (fmt )* n ))) 169fmt = self ._SCALAR [vtype ] 170return key ,struct .unpack (fmt ,f .read (struct .calcsize (fmt )))[0 ] 171 172def tensor (self ,name :str | None = None )-> dict : 173if name is not None : 174for t in self .tensors : 175if t ["name" ]== name : 176return t 177raise KeyError (f" { self . path } : no tensor { name !r } ; have { [ t [ 'name' ] for t in self . tensors ] } " ) 178for t in self .tensors : 179if t ["type" ]== GGML_TYPE_IQ4_NL : 180return t 181raise KeyError (f" { self . path } : no IQ4_NL tensor" ) 182 183def 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.""" 185t = self .tensor (name ) 186if t ["type" ]!= GGML_TYPE_IQ4_NL : 187raise ValueError (f"tensor { t [ 'name' ]!r } is ggml type { t [ 'type' ] } , not { GGML_TYPE_IQ4_NL } (IQ4_NL)" ) 188n_embd = int (t ["dims" ][0 ]) 189n_rows = 1 190for d in t ["dims" ][1 :]: 191n_rows *= int (d ) 192return n_embd ,n_rows ,iq4nl_row_bytes (n_embd ) 193 194def 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" ]) 197return 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 204the device's 512-byte block, so a row read is a 512-aligned window that is then sliced: the device moves up to 205511 extra bytes per row and MB/s is reported both ways (payload and what the device was asked for). 206""" 207 208def __init__ (self ,path :str ,align :int = 512 ,odirect :bool = True ): 209self .path = path 210self .align = align 211self .size = os .path .getsize (path ) 212flags = os .O_RDONLY | (getattr (os ,"O_DIRECT" ,0 )if odirect else 0 ) 213self .odirect = bool (odirect and getattr (os ,"O_DIRECT" ,0 )) 214try : 215self .fd = os .open (path ,flags ) 216except OSError as e : 217if not self .odirect : 218raise 219f" (O_DIRECT unavailable on { path } : { e } ; falling back to buffered reads)" ,file = sys .stderr ) 220self .odirect = False 221self .fd = os .open (path ,os .O_RDONLY ) 222self ._buf = None 223self ._buf_len = 0 224self .device_bytes = 0 225 226def _buffer (self ,n :int ): 227if self ._buf is None or self ._buf_len < n : 228self ._buf = mmap .mmap (- 1 ,n )# page aligned, which is a multiple of any 512/4096 sector 229self ._buf_len = n 230return self ._buf 231 232def read (self ,off :int ,length :int )-> bytes : 233"""The `length` bytes at `off`, in one aligned pread.""" 234if self .odirect : 235a = self .align 236start = off // a * a 237end = min ((off + length + a - 1 )// a * a ,self .size ) 238n = end - start 239if n <= 0 : 240raise ValueError (f"read past end: off { off } len { length } size { self . size } " ) 241buf = self ._buffer (n ) 242got = os .preadv (self .fd , [memoryview (buf )[:n ]],start ) 243self .device_bytes += n 244if got != n : 245raise OSError (f"short O_DIRECT read at { start } : { got } of { n } " ) 246return bytes (memoryview (buf )[off - start :off - start + length ]) 247data = os .pread (self .fd ,length ,off ) 248self .device_bytes += length 249if len (data )!= length : 250raise OSError (f"short read at { off } : { len ( data ) } of { length } " ) 251return data 252 253def close (self ): 254if self ._buf is not None : 255self ._buf .close () 256self ._buf = None 257os .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 265The blocks are real blocks: fp16 scales in 0.002 .. 0.017 and random packed nibbles, so the dequant is exercised 266on the file the benchmarks read. Returns (n_rows, file bytes). 267""" 268rb = iq4nl_row_bytes (n_embd ) 269n_rows = max (1 ,int (size_gb * 1e9 )// rb ) 270rng = random .Random (seed ) 271scales = [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 273blobs = [] 274for s in scales : 275parts = [] 276for _ in range (8 ): 277parts .append (struct .pack ("<e" ,s )+ bytes (rng .getrandbits (8 )for _ in range (16 ))) 278blobs .append (b"" .join (parts ))# 144 bytes = 8 whole blocks, so a repeat keeps block alignment 279 280header = bytearray () 281header += b"GGUF" 282header += struct .pack ("<I" ,3 ) 283header += struct .pack ("<QQ" ,1 ,3 ) 284for k ,v in (("general.architecture" ,"engram" ), ("general.name" ,"p1004-synthetic-iq4nl" )): 285header += struct .pack ("<Q" ,len (k ))+ k .encode () 286header += struct .pack ("<I" ,8 ) 287header += struct .pack ("<Q" ,len (v ))+ v .encode () 288header += struct .pack ("<Q" ,len ("general.alignment" ))+ b"general.alignment" 289header += struct .pack ("<I" ,4 )+ struct .pack ("<I" ,32 ) 290name = b"engram.iq4nl" 291header += struct .pack ("<Q" ,len (name ))+ name 292header += struct .pack ("<I" ,2 )+ struct .pack ("<QQ" ,n_embd ,n_rows ) 293header += struct .pack ("<I" ,GGML_TYPE_IQ4_NL )+ struct .pack ("<Q" ,0 ) 294header += b"\x00" * ((- len (header ))% 32 ) 295 296if verbose : 297f"synthetic: n_embd { n_embd } row_bytes { rb } n_rows { n_rows } data { ( n_rows * rb ) / 1e9 :.3f } GB -> { path } " ) 298chunk_rows = 64 299written = 0 300with open (path ,"wb" ,buffering = 1024 * 1024 )as f : 301f .write (header ) 302k = 0 303t0 = time .time () 304while written < n_rows : 305rows = min (chunk_rows ,n_rows - written ) 306blob = blobs [k % len (blobs )] 307k += 1 308buf = (blob * (rows * rb // len (blob )+ 1 ))[:rows * rb ] 309f .write (buf ) 310written += rows 311if verbose and written % (chunk_rows * 512 )== 0 : 312f"\r { written * rb / 1e9 :.2f } GB" ,end = "" ,file = sys .stderr ) 313total = os .path .getsize (path ) 314if verbose : 315f"\r wrote { total / 1e9 :.3f } GB in { time . time () - t0 :.1f } s" + " " * 20 ,file = sys .stderr ) 316return 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) { 328if (argc < 2) { std::fprintf(stderr, "usage: iq4nl_dump N_EMBD < row.bin\n"); return 2; } 329const int n = std::atoi(argv[1]); 330const size_t rb = (size_t) (n / 32) * 18; 331std::vector<unsigned char> row(rb); 332if (std::fread(row.data(), 1, rb, stdin) != rb) { std::fprintf(stderr, "short read\n"); return 2; } 333std::vector<float> y((size_t) n); 334dequantize_row_iq4_nl(row.data(), y.data(), n); 335for (int i = 0; i < n; ++i) { 336unsigned int b; __builtin_memcpy(&b, &y[i], 4); 337std::printf("%08x\n", b); 338} 339return 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).""" 346src_root = os .path .join (build_dir ,"_deps" ,"strata_llamacpp-src" ,"ggml" ) 347lib = os .path .join (build_dir ,"ggml" ,"src" ,"libggml-base.a" ) 348for p in (src_root ,lib ): 349if not os .path .exists (p ): 350raise FileNotFoundError (f" { p } not found; pass --ggml-build-dir with a tree that built ggml" ) 351out = out or os .path .join (tempfile .gettempdir (),"iq4nl_dump" ) 352with open (out + ".cpp" ,"w" )as f : 353f .write (_GGML_DUMP_SRC ) 354cmd = ["g++" ,"-O2" ,"-std=c++17" ,"-I" ,os .path .join (src_root ,"include" ),"-I" ,os .path .join (src_root ,"src" ), 355out + ".cpp" ,lib ,"-o" ,out ,"-lpthread" ,"-lm" ] 356subprocess .run (cmd ,check = True ) 357return 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).""" 362p = subprocess .run ([dumper ,str (n_embd )],input = row ,stdout = subprocess .PIPE ,check = True ) 363hx = b"" .join (p .stdout .split ()).decode () 364if len (hx )!= 8 * n_embd : 365raise RuntimeError (f"the dumper printed { len ( hx ) } hex digits for { n_embd } values; check its n_embd argument" ) 366return 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 = "" ): 372return 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.""" 377sel = rows [:limit ] 378if not sel : 379return 0.0 ,0 380t0 = time .perf_counter () 381for row in sel : 382dequant_row_iq4nl_fast (row ,n_embd ) 383return 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 388the dequant is timed afterwards on the rows already in RAM, so neither number hides the other.""" 389rnd = random .Random (args .seed ) 390tok_rows = [rnd .sample (range (n_rows ),args .rows_per_token )for _ in range (args .iters )] 391rd = RowReader (gg .path ,align = args .align ,odirect = args .odirect ) 392blobs = [] 393try : 394rd .read (gg .row_offset (t ,tok_rows [0 ][0 ]),rb )# warm the path, not the cache (O_DIRECT) 395t0 = time .perf_counter () 396for rows in tok_rows : 397for r in rows : 398blobs .append (rd .read (gg .row_offset (t ,r ),rb )) 399dt = time .perf_counter ()- t0 400finally : 401dev = rd .device_bytes 402rd .close () 403n = len (blobs ) 404out = { 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 } 415if args .dequant != "off" : 416lim = n if args .dequant == "all" else args .rows_per_token * min (args .iters ,2 ) 417ddt ,dn = _dequant_rate (blobs ,n_embd ,lim ) 418out ["dequant_rows" ],out ["dequant_rows_s" ]= dn ,dn / ddt if ddt else 0.0 419return 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 424contiguous runs of the table (the best case: a chunk's hashes are unrelated, so the real pattern is the random 425one). Reads and dequant are timed apart, as in bench_token.""" 426rnd = random .Random (args .seed + 1 ) 427n = args .batch_tokens * args .rows_per_token 428rows = [rnd .randrange (n_rows )for _ in range (n )] 429rd = RowReader (gg .path ,align = args .align ,odirect = args .odirect ) 430blobs = [] 431try : 432t0 = time .perf_counter () 433for r in rows : 434blobs .append (rd .read (gg .row_offset (t ,r ),rb )) 435dt = time .perf_counter ()- t0 436finally : 437dev = rd .device_bytes 438rd .close () 439out = { 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 } 450if args .dequant != "off" : 451lim = n if args .dequant == "all" else args .rows_per_token * 3 452ddt ,dn = _dequant_rate (blobs ,n_embd ,lim ) 453out ["dequant_rows" ],out ["dequant_rows_s" ]= dn ,dn / ddt if ddt else 0.0 454del blobs 455# the same rows, contiguous: merge the sorted ids into runs and read each run with one pread 456srows = sorted (rows ) 457runs = [] 458lo = prev = srows [0 ] 459for r in srows [1 :]: 460if r == prev + 1 : 461prev = r 462continue 463runs .append ((lo ,prev )) 464lo = prev = r 465runs .append ((lo ,prev )) 466rd = RowReader (gg .path ,align = args .align ,odirect = args .odirect ) 467try : 468t0 = time .perf_counter () 469got = 0 470for lo ,hi in runs : 471got += len (rd .read (gg .row_offset (t ,lo ), (hi - lo + 1 )* rb )) 472dt2 = time .perf_counter ()- t0 473finally : 474dev2 = rd .device_bytes 475rd .close () 476out ["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 } 487return 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).""" 492mb = min (args .seq_mb ,gg .size // (1024 * 1024 )) 493rd = RowReader (gg .path ,align = args .align ,odirect = args .odirect ) 494chunk = args .align * 1024 # 512 KiB 495try : 496rd .read (0 ,chunk ) 497t0 = time .perf_counter () 498off = 0 499total = 0 500while total < mb * 1024 * 1024 : 501n = min (chunk ,gg .size - off ) 502if n <= 0 : 503break 504rd .read (off ,n ) 505off += n 506total += n 507dt = time .perf_counter ()- t0 508finally : 509dev = rd .device_bytes 510rd .close () 511return {"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 : 519ap = argparse .ArgumentParser (description = __doc__ , 520formatter_class = argparse .RawDescriptionHelpFormatter ) 521ap .add_argument ("--gguf" ,help = "the Engram GGUF (or a synthetic one)" ) 522ap .add_argument ("--tensor" ,default = None ,help = "tensor name (default: the first IQ4_NL tensor)" ) 523ap .add_argument ("--mode" ,default = "all" ,choices = ["header" ,"token" ,"batch" ,"seq" ,"all" ]) 524ap .add_argument ("--rows-per-token" ,type = int ,default = 48 ) 525ap .add_argument ("--batch-tokens" ,type = int ,default = 256 ) 526ap .add_argument ("--iters" ,type = int ,default = 20 ) 527ap .add_argument ("--seq-mb" ,type = int ,default = 512 ) 528ap .add_argument ("--align" ,type = int ,default = 512 ,help = "O_DIRECT alignment (the device's logical block size)" ) 529ap .add_argument ("--odirect" ,action = "store_true" ,default = True ) 530ap .add_argument ("--no-odirect" ,dest = "odirect" ,action = "store_false" ) 531ap .add_argument ("--dequant" ,default = "sample" ,choices = ["off" ,"sample" ,"all" ]) 532ap .add_argument ("--seed" ,type = int ,default = 1 ) 533ap .add_argument ("--verify-rows" ,type = int ,default = 8 ,help = "rows checked bit-exactly against ggml" ) 534ap .add_argument ("--ggml-dump" ,help = "a compiled ggml IQ4_NL dequant dumper (see --build-ggml-dump)" ) 535ap .add_argument ("--build-ggml-dump" ,action = "store_true" ,help = "compile the dumper from the source embedded here" ) 536ap .add_argument ("--ggml-build-dir" ,default = "/data/dsv41-build" ,help = "a Strata build tree with ggml built" ) 537ap .add_argument ("--make-synthetic" ,metavar = "PATH" ,help = "write a synthetic IQ4_NL GGUF and exit (unless --gguf)" ) 538ap .add_argument ("--size-gb" ,type = float ,default = 1.0 ) 539ap .add_argument ("--n-embd" ,type = int ,default = 4096 ) 540args = ap .parse_args (argv ) 541 542if args .make_synthetic : 543make_synthetic (args .make_synthetic ,args .size_gb ,args .n_embd ,args .seed ) 544if not args .gguf : 545args .gguf = args .make_synthetic 546if args .mode == "all" : 547args .mode = "header" 548if not args .gguf : 549ap .error ("--gguf or --make-synthetic is required" ) 550 551gg = Gguf (args .gguf ) 552t = gg .tensor (args .tensor ) 553n_embd ,n_rows ,rb = gg .geometry (args .tensor ) 554f" { gg . path } : { gg . size / 1e9 :.3f } GB, GGUF v { gg . meta . get ( 'general.version' , 3 ) } , { len ( gg . tensors ) } tensor(s), " 555f"alignment { gg . alignment } , data at { gg . data_start } " ) 556f" tensor { t [ 'name' ]!r } : type { t [ 'type' ] } (IQ4_NL), dims { t [ 'dims' ] } , n_embd { n_embd } , n_rows { n_rows } , " 557f"row_bytes { rb } , table { ( n_rows * rb ) / 1e9 :.3f } GB" ) 558if t ["type" ]!= GGML_TYPE_IQ4_NL : 559f" not an IQ4_NL tensor: nothing to read" ,file = sys .stderr ) 560return 2 561 562# the bit-exact check, always: the scalar reference against the fast path, then against ggml itself 563rnd = random .Random (args .seed + 7 ) 564dumper = args .ggml_dump 565if args .build_ggml_dump : 566dumper = build_ggml_dump (args .ggml_build_dir ,dumper ) 567f" built the ggml dumper: { dumper } " ) 568rd = RowReader (gg .path ,align = args .align ,odirect = args .odirect ) 569bad = 0 570checked = 0 571try : 572for _ in range (args .verify_rows ): 573r = rnd .randrange (n_rows ) 574row = rd .read (gg .row_offset (t ,r ),rb ) 575ref = dequant_row_iq4nl_ref (row ,n_embd ) 576fast = dequant_row_iq4nl_fast (row ,n_embd ) 577if f32_bits (ref )!= f32_bits (fast ): 578bad += 1 579f" row { r } : the scalar reference and the fast path differ" ,file = sys .stderr ) 580if dumper : 581gw = ggml_dequant_bits (dumper ,row ,n_embd ) 582if gw != f32_bits (ref ): 583bad += 1 584f" row { r } : ggml's dequant differs from the reference" ,file = sys .stderr ) 585checked += 1 586finally : 587rd .close () 588f" 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" )) 591if bad : 592return 1 593 594if args .mode == "header" : 595return 0 596 597results = [] 598if args .mode in ("seq" ,"all" ): 599results .append (bench_seq (gg ,rb ,args )) 600if args .mode in ("token" ,"all" ): 601results .append (bench_token (gg ,t ,n_embd ,n_rows ,rb ,args )) 602if args .mode in ("batch" ,"all" ): 603b = bench_batch (gg ,t ,n_embd ,n_rows ,rb ,args ) 604results .append (b ["contig" ]) 605results .append (b ) 606results .sort (key = lambda x :- x ["payload_mb_s" ]) 607f" { 'pattern' :44s } { 's' :>8s } { 'rows/s' :>11s } { 'tokens/s' :>9s } { 'MB/s payload' :>12s } { 'MB/s device' :>11s } " 609f" { 'us/read' :>8s } { 'dequant rows/s' :>14s } " ) 610for r in results : 611tok = f" { r [ 'tokens_s' ]:.1f } " if "tokens_s" in r else "-" 612dq = f" { r [ 'dequant_rows_s' ]:,.0f } ( { r [ 'dequant_rows' ] } rows)" if r .get ("dequant_rows_s" )else r ["dequant" ] 613f" { r [ 'mode' ]:44s } { r [ 'seconds' ]:8.3f } { r [ 'rows_s' ]:11,.0f } { tok :>9s } { r [ 'payload_mb_s' ]:12,.1f } " 614f" { r [ 'device_mb_s' ]:11,.1f } { r [ 'read_us' ]:8,.1f } { dq :>14s } " ) 615f"\n note: O_DIRECT { 'on' if args . odirect else 'off' } , alignment { args . align } B; " 616f"payload MB/s counts row bytes only, device MB/s what the reads actually asked for" ) 617" 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" ) 619return 0 620 621 622if __name__ == "__main__" : 623sys .exit (main ())