okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
01529aaa8
main
1"""tools/pack_index.py - emit a flat index of the pack's dense tensors for the engine's loader. 2 3WHY AN INDEX AND NOT A JSON PARSER. The manifest is JSON and the engine is C++. A JSON parser in the engine 4would be a new, unaudited component whose failure mode is a wrong byte offset - which decodes to a plausible 5weight and produces plausible logits. Python already parses the manifest correctly and is already the tool 6that WROTE it, so this flattens what the loader needs into one line per tensor. 7 8WHY TEXT AND NOT BINARY. `pack/full/index.txt` is ~150 KB for 1,079 tensors. A fixed-size binary record 9would save 60 KB and cost a struct-packing contract between two languages that must agree on padding, 10endianness and field order - three ways to be wrong for no benefit at this size. Text is also readable when 11a load produces the wrong number, which is the only time this file matters. 12 13THE ENGINE LAYOUT IS NOT THE PACK LAYOUT, and that is the point of `dst_*`. Two independent differences: 14 151. A tensor whose source type is BF16 or F16 is stored in the pack PROMOTED to 32 bits, because that is 16lossless and it keeps the canonical decoder simple. A running engine does not have to hold it that way: 17re-rounding to 16 bits costs nothing at all, because the value came FROM 16 bits. That is 1.374 GiB of 18the 5.305 GiB dense file, and per `tools/pack_budget.py` it is the difference between the dense weights 19fitting in VRAM beside the expert cache and not fitting at all. 20 212. **A SCALE PLANE MAY BE 2 BYTES IN THE PACK AND IS ALWAYS 4 IN THE ENGINE.** This is the one that hid 22for a whole round. 90 of the 303 quantized tensors - every Q2_0 (all 58 expert tensors), Q4_0, Q5_0, 23Q8_0 and IQ4_NL - carry fp16 scales, because that is what the SOURCE ggml block stores (a Q5_0 block is 24`{fp16 d; ...}`). 213 tensors (IQ4_XS, Q3_K, Q4_K, Q5_K, Q6_K) carry f32 scales. The manifest has said 25which is which all along, in `scales_fp16`. 26 27`src/core/layer.cpp` did not read that field. It assumed 4 bytes per scale, so it computed a scale plane 28twice the real size, the three planes did not add up to the tensor, and the loader REFUSED - which is how 29this was found, and the refusal is the only reason it was not a silent wrong answer. The first diagnosis 30was "the manifest's `group_elems` must be wrong, the real group is 64". It is not: `group_elems` is 32 31and the scale plane is 2 bytes wide. **The unexamined input was the WIDTH, not the count.** An audit of 32all 303 tensors against `scales_fp16`/`offsets_fp16` found zero inconsistencies, which is what settled it. 33 34The engine widens fp16 scales to f32 at load. That is EXACT - fp16 is a subset of f32 - and it costs 3511,407,360 B (10.88 MiB) of the 4.5 GiB pool, against teaching three kernel families a second scale 36width. Note the asymmetry that makes this cheap and the BF16 re-rounding large: re-rounding loses 37precision and saves GiB; widening loses nothing and costs MiB. 38 39`offsets_fp16` is also read, and it is FALSE for all 54 tensors that have an offset plane. It is 40honoured anyway rather than assumed, because the next pack may not be. 41 42Columns: 43 44name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook 45has_offset codes_bytes scales_bytes offset_bytes scales_fp16 46 47`kind` is what the loader must DO, spelled out here rather than left for it to infer - the four cases are 48distinguishable in the manifest but only by combining `source_type` with `values_fp16`, and getting that 49combination wrong produces a plausible tensor: 50 510 VERBATIM copy straight through (BF16-free: F16 already 2 B/elem, F32, and the planes below) 521 BF16_IN_F32 the pack holds the bf16 value promoted to f32; take the HIGH 16 BITS. Exact, not a 53rounding: a bf16 value IS the top half of its f32 image. 542 F32 copy 4 B/elem 553 F16_IN_F32 the pack holds an f16 value promoted to f32; needs a real f32->f16 conversion with 56round-to-nearest-even, NOT a truncation 57 58`ne0`/`ne1` are the manifest's own shape in its own order, with ne0 the CONTIGUOUS axis. `form` is the 59canonical form letter from the manifest (P16/P32/S2/S4/S8); the SForm attributes are 0 for kinds 1-3. 60 61`codes_bytes`/`scales_bytes`/`offset_bytes` are the THREE ENGINE-FORM PLANE SIZES, in the order they sit in 62the destination. They are emitted rather than left for the loader to re-derive, because re-deriving is where 63the width bug lived: two places computing one layout is two places to disagree, and the loader cannot check a 64layout it invented. The loader instead checks what it was TOLD: `scales_bytes/2` when `scales_fp16`, and the 65three planes summing to both `src_bytes` (source widths) and `dst_bytes` (engine widths). Non-quantized 66tensors carry `codes_bytes == dst_bytes` and two zeroes. 67""" 68from __future__import annotations 69 70import argparse 71import json 72import os 73import sys 74 75sys .path .insert (0 ,os .path .dirname (os .path .abspath (__file__ ))) 76 77FILE_ID = {"dense.bin" :0 ,"embd.bin" :1 ,"experts.bin" :2 } 78VERBATIM ,BF16_IN_F32 ,F32_COPY ,F16_IN_F32 = 0 ,1 ,2 ,3 79 80# WHICH ACTIVATION THIS WEIGHT WANTS, decided HERE because it is a property of `source_type` and the engine's 81# `SForm` cannot recover it. The legacy formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0; the 82# K-quants and IQ4_XS have Q8_K. **NO COMBINATION OF THE S-FORM FIELDS TELLS THEM APART**: Q5_0 and Q5_K are 83# both 8-bit with bias -16 (only `has_offset` differs), and IQ4_NL and IQ4_XS are both 4-bit with the IQ4NL 84# codebook and no offset - they differ in NOTHING the S-form carries. That is why this column exists rather 85# than the engine re-deriving the rule from `code_bits`. 86ACT_Q8_0 ,ACT_Q8_K = 0 ,1 87VDT = { 88"Q2_0" :ACT_Q8_0 ,"Q4_0" :ACT_Q8_0 ,"Q5_0" :ACT_Q8_0 ,"Q8_0" :ACT_Q8_0 ,"IQ4_NL" :ACT_Q8_0 , 89"Q3_K" :ACT_Q8_K ,"Q4_K" :ACT_Q8_K ,"Q5_K" :ACT_Q8_K ,"Q6_K" :ACT_Q8_K ,"IQ4_XS" :ACT_Q8_K , 90} 91 92# The plane key is `offsets`, NOT `mins`. The first version of this list said `mins` - which is what ggml calls 93# the quantity conceptually, and the manifest does not - and a missing key in a loop like this is not an error, 94# it is a SHORTER SPAN: 54 Q4_K/Q5_K tensors loaded with their offset plane never copied. Keys now come from 95# the manifest, and the layout is verified against the recorded plane offsets rather than assumed. 96PLANE_KEYS = ("codes" ,"scales" ,"offsets" ) 97 98 99def main ()-> int : 100ap = argparse .ArgumentParser () 101ap .add_argument ("--pack" ,default = "pack/full" ) 102ap .add_argument ("-o" ,"--out" ,default = None ,help = "default: <pack>/index.txt" ) 103args = ap .parse_args () 104out_path = args .out or os .path .join (args .pack ,"index.txt" ) 105 106with open (os .path .join (args .pack ,"manifest.json" ),"r" ,encoding = "utf-8" )as fh : 107man = json .load (fh ) 108align = int (man .get ("align" ,64 )) 109 110def align_up (n :int )-> int : 111return (n + align - 1 )// align * align 112 113rows = [] 114dst = 0 115n_reduced = 0 116saved = 0 117widened = 0 118n_widened = 0 119kinds :dict [int ,int ]= {} 120for name ,v in man ["tensors" ].items (): 121f = v .get ("file" ) 122if f not in FILE_ID : 123"unknown file %r for %s" % (f ,name ),file = sys .stderr ) 124return 1 125shape = v .get ("shape" )or [0 ,0 ] 126ne0 = int (shape [0 ])if len (shape )> 0 else 0 127ne1 = int (shape [1 ])if len (shape )> 1 else 0 128elems = int (v .get ("elements" ,0 )) 129st = v .get ("source_type" )or "?" 130 131codes_bytes = scales_bytes = offset_bytes = 0 132scales_fp16 = 0 133widen_here = 0 134act_kind = ACT_Q8_0 135if "values" in v : 136src_off = int (v ["values" ]["offset" ]) 137src_bytes = int (v ["values" ]["bytes" ]) 138else : 139planes = [k for k in PLANE_KEYS if isinstance (v .get (k ),dict )] 140lo = min (int (v [k ]["offset" ])for k in planes ) 141hi = max (int (v [k ]["offset" ])+ int (v [k ].get ("bytes" ,0 ))for k in planes ) 142src_off ,src_bytes = lo ,hi - lo 143 144# the planes must be CONTIGUOUS, in order, because the loader reads them as one span. If a future 145# pack interleaves them this refuses; the alternative is reading the scale plane as offsets and 146# decoding a plausible weight. 147expect = src_off 148for k in PLANE_KEYS : 149if k not in planes : 150continue 151if int (v [k ]["offset" ])!= expect : 152"%s: plane %r starts at %d but %d was expected - planes are not contiguous" 153% (name ,k ,int (v [k ]["offset" ]),expect ),file = sys .stderr ) 154return 1 155expect += int (v [k ].get ("bytes" ,0 )) 156if expect != src_off + src_bytes : 157"%s: plane span %d does not end at %d" % (name ,expect ,src_off + src_bytes ), 158file = sys .stderr ) 159return 1 160 161if v .get ("has_offset" )and "offsets" not in planes : 162"%s says has_offset but has no `offsets` plane (found %s)" % (name ,planes ), 163file = sys .stderr ) 164return 1 165 166act_kind = VDT .get (st ,ACT_Q8_0 )# refuses below if the type is unknown 167code_bits = int (v .get ("code_bits" )or 0 ) 168group_elems = int (v .get ("group_elems" )or 0 ) 169if code_bits == 0 or group_elems == 0 : 170"%s: a quantized tensor with code_bits=%d group_elems=%d" % (name ,code_bits ,group_elems ), 171file = sys .stderr ) 172return 1 173if ne0 % group_elems : 174"%s: ne0 %d is not a multiple of group_elems %d" % (name ,ne0 ,group_elems ), 175file = sys .stderr ) 176return 1 177n_groups = ne0 // group_elems 178codes_bytes = elems * code_bits // 8 179scales_fp16 = 1 if v .get ("scales_fp16" )else 0 180offs_fp16 = 1 if v .get ("offsets_fp16" )else 0 181# engine-form plane sizes: ALWAYS 4 B per scale. fp16 in the pack is widened; the load is exact. 182scales_bytes = ne1 * n_groups * 4 183offset_bytes = ne1 * n_groups * 4 if v .get ("has_offset" )else 0 184src_planes = (codes_bytes 185+ ne1 * n_groups * (2 if scales_fp16 else 4 ) 186+ (ne1 * n_groups * (2 if offs_fp16 else 4 )if v .get ("has_offset" )else 0 )) 187if src_planes != int (v ["codes" ]["bytes" ])+ int (v ["scales" ]["bytes" ]) \ 188+ int (v .get ("offsets" , {}).get ("bytes" ,0 )): 189"%s: derived planes %d disagree with the manifest's own plane bytes %d" 190% (name ,src_planes ,int (v ["codes" ]["bytes" ])+ int (v ["scales" ]["bytes" ]) 191+ int (v .get ("offsets" , {}).get ("bytes" ,0 ))),file = sys .stderr ) 192return 1 193if src_planes != src_bytes : 194"%s: derived planes %d do not fill the span %d" % (name ,src_planes ,src_bytes ), 195file = sys .stderr ) 196return 1 197if scales_fp16 : 198widen_here = scales_bytes - ne1 * n_groups * 2 199widened += widen_here 200n_widened += 1 201 202# ---- the engine form, as an explicit KIND rather than a flag to interpret 203vf = bool (v .get ("values_fp16" )) 204if st == "BF16" : 205kind = BF16_IN_F32 206dst_bytes = elems * 2 207saved += src_bytes - dst_bytes 208n_reduced += 1 209elif st == "F16" and not vf : 210kind = F16_IN_F32 211dst_bytes = elems * 2 212saved += src_bytes - dst_bytes 213n_reduced += 1 214elif st == "F16" : 215kind = VERBATIM # already 2 bytes on disk 216dst_bytes = src_bytes 217elif st == "F32" : 218kind = F32_COPY 219dst_bytes = elems * 4 220else : 221kind = VERBATIM 222dst_bytes = codes_bytes + scales_bytes + offset_bytes 223# THE ENGINE FORM OF A QUANTIZED TENSOR DIFFERS FROM THE PACK BY EXACTLY THE WIDENING, and saying 224# so here is what makes the two plane sizes a CHECK rather than two independent guesses. 225if dst_bytes != src_bytes + widen_here : 226"%s: engine form %d != pack %d + widening %d" % (name ,dst_bytes ,src_bytes ,widen_here ), 227file = sys .stderr ) 228return 1 229 230cb = v .get ("codebook" ) 231rows .append ((name ,FILE_ID [f ],kind ,src_off ,src_bytes ,dst ,dst_bytes ,ne0 ,ne1 , 232int (v .get ("code_bits" )or 0 ),int (v .get ("code_bias" )or 0 ), 233int (v .get ("group_elems" )or 0 ),1 if cb == "IQ4NL" else 0 , 2341 if v .get ("has_offset" )else 0 , 235codes_bytes ,scales_bytes ,offset_bytes ,scales_fp16 ,act_kind )) 236dst = align_up (dst + dst_bytes ) 237kinds [kind ]= kinds .get (kind ,0 )+ 1 238 239with open (out_path ,"w" ,encoding = "utf-8" ,newline = "\n" )as fh : 240fh .write ("# strata pack index v3 -- generated by tools/pack_index.py; do not hand-edit\n" ) 241fh .write ("# align %d pool %d tensors %d\n" % (align ,dst ,len (rows ))) 242fh .write ("# name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias " 243"group_elems codebook has_offset codes_bytes scales_bytes offset_bytes scales_fp16 act_kind\n" ) 244for r in rows : 245fh .write ("%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n" % r ) 246 247names = {VERBATIM :"VERBATIM" ,BF16_IN_F32 :"BF16_IN_F32" ,F32_COPY :"F32" ,F16_IN_F32 :"F16_IN_F32" } 248"%s: %d tensors, engine pool %d B (%.3f GiB)" % (out_path ,len (rows ),dst ,dst / 2 ** 30 )) 249for k in sorted (kinds ): 250" kind %-12s %4d tensors" % (names [k ],kinds [k ])) 251" %d tensors re-rounded to 16 bits, saving %d B (%.3f GiB)" 252% (n_reduced ,saved ,saved / 2 ** 30 )) 253" %d tensors widened fp16 scales -> f32, costing %d B (%.3f GiB)" 254% (n_widened ,widened ,widened / 2 ** 30 )) 255" compare with tools/pack_budget.py: the pack's dense+embd engine figure should match this pool" ) 256return 0 257 258 259if __name__ == "__main__" : 260raise SystemExit (main ())