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
14.1 KiB260 linesraw
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
15  1. A tensor whose source type is BF16 or F16 is stored in the pack PROMOTED to 32 bits, because that is
16     lossless and it keeps the canonical decoder simple.  A running engine does not have to hold it that way:
17     re-rounding to 16 bits costs nothing at all, because the value came FROM 16 bits.  That is 1.374 GiB of
18     the 5.305 GiB dense file, and per `tools/pack_budget.py` it is the difference between the dense weights
19     fitting in VRAM beside the expert cache and not fitting at all.
20
21  2. **A SCALE PLANE MAY BE 2 BYTES IN THE PACK AND IS ALWAYS 4 IN THE ENGINE.**  This is the one that hid
22     for a whole round.  90 of the 303 quantized tensors - every Q2_0 (all 58 expert tensors), Q4_0, Q5_0,
23     Q8_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
25     which 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
28     twice the real size, the three planes did not add up to the tensor, and the loader REFUSED - which is how
29     this was found, and the refusal is the only reason it was not a silent wrong answer.  The first diagnosis
30     was "the manifest's `group_elems` must be wrong, the real group is 64".  It is not: `group_elems` is 32
31     and the scale plane is 2 bytes wide.  **The unexamined input was the WIDTH, not the count.**  An audit of
32     all 303 tensors against `scales_fp16`/`offsets_fp16` found zero inconsistencies, which is what settled it.
33
34     The engine widens fp16 scales to f32 at load.  That is EXACT - fp16 is a subset of f32 - and it costs
35     11,407,360 B (10.88 MiB) of the 4.5 GiB pool, against teaching three kernel families a second scale
36     width.  Note the asymmetry that makes this cheap and the BF16 re-rounding large: re-rounding loses
37     precision 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
40     honoured anyway rather than assumed, because the next pack may not be.
41
42Columns:
43
44    name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook
45    has_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
51    0  VERBATIM       copy straight through (BF16-free: F16 already 2 B/elem, F32, and the planes below)
52    1  BF16_IN_F32    the pack holds the bf16 value promoted to f32; take the HIGH 16 BITS.  Exact, not a
53                      rounding: a bf16 value IS the top half of its f32 image.
54    2  F32            copy 4 B/elem
55    3  F16_IN_F32     the pack holds an f16 value promoted to f32; needs a real f32->f16 conversion with
56                      round-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:
100    ap = argparse.ArgumentParser()
101    ap.add_argument("--pack", default="pack/full")
102    ap.add_argument("-o", "--out", default=None, help="default: <pack>/index.txt")
103    args = ap.parse_args()
104    out_path = args.out or os.path.join(args.pack, "index.txt")
105
106    with open(os.path.join(args.pack, "manifest.json"), "r", encoding="utf-8") as fh:
107        man = json.load(fh)
108    align = int(man.get("align", 64))
109
110    def align_up(n: int) -> int:
111        return (n + align - 1) // align * align
112
113    rows = []
114    dst = 0
115    n_reduced = 0
116    saved = 0
117    widened = 0
118    n_widened = 0
119    kinds: dict[int, int] = {}
120    for name, v in man["tensors"].items():
121        f = v.get("file")
122        if f not in FILE_ID:
123            print("unknown file %r for %s" % (f, name), file=sys.stderr)
124            return 1
125        shape = v.get("shape") or [0, 0]
126        ne0 = int(shape[0]) if len(shape) > 0 else 0
127        ne1 = int(shape[1]) if len(shape) > 1 else 0
128        elems = int(v.get("elements", 0))
129        st = v.get("source_type") or "?"
130
131        codes_bytes = scales_bytes = offset_bytes = 0
132        scales_fp16 = 0
133        widen_here = 0
134        act_kind = ACT_Q8_0
135        if "values" in v:
136            src_off = int(v["values"]["offset"])
137            src_bytes = int(v["values"]["bytes"])
138        else:
139            planes = [k for k in PLANE_KEYS if isinstance(v.get(k), dict)]
140            lo = min(int(v[k]["offset"]) for k in planes)
141            hi = max(int(v[k]["offset"]) + int(v[k].get("bytes", 0)) for k in planes)
142            src_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.
147            expect = src_off
148            for k in PLANE_KEYS:
149                if k not in planes:
150                    continue
151                if int(v[k]["offset"]) != expect:
152                    print("%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)
154                    return 1
155                expect += int(v[k].get("bytes", 0))
156            if expect != src_off + src_bytes:
157                print("%s: plane span %d does not end at %d" % (name, expect, src_off + src_bytes),
158                      file=sys.stderr)
159                return 1
160
161            if v.get("has_offset") and "offsets" not in planes:
162                print("%s says has_offset but has no `offsets` plane (found %s)" % (name, planes),
163                      file=sys.stderr)
164                return 1
165
166            act_kind = VDT.get(st, ACT_Q8_0)   # refuses below if the type is unknown
167            code_bits = int(v.get("code_bits") or 0)
168            group_elems = int(v.get("group_elems") or 0)
169            if code_bits == 0 or group_elems == 0:
170                print("%s: a quantized tensor with code_bits=%d group_elems=%d" % (name, code_bits, group_elems),
171                      file=sys.stderr)
172                return 1
173            if ne0 % group_elems:
174                print("%s: ne0 %d is not a multiple of group_elems %d" % (name, ne0, group_elems),
175                      file=sys.stderr)
176                return 1
177            n_groups = ne0 // group_elems
178            codes_bytes = elems * code_bits // 8
179            scales_fp16 = 1 if v.get("scales_fp16") else 0
180            offs_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.
182            scales_bytes = ne1 * n_groups * 4
183            offset_bytes = ne1 * n_groups * 4 if v.get("has_offset") else 0
184            src_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))
187            if src_planes != int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) \
188                    + int(v.get("offsets", {}).get("bytes", 0)):
189                print("%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)
192                return 1
193            if src_planes != src_bytes:
194                print("%s: derived planes %d do not fill the span %d" % (name, src_planes, src_bytes),
195                      file=sys.stderr)
196                return 1
197            if scales_fp16:
198                widen_here = scales_bytes - ne1 * n_groups * 2
199                widened += widen_here
200                n_widened += 1
201
202        # ---- the engine form, as an explicit KIND rather than a flag to interpret
203        vf = bool(v.get("values_fp16"))
204        if st == "BF16":
205            kind = BF16_IN_F32
206            dst_bytes = elems * 2
207            saved += src_bytes - dst_bytes
208            n_reduced += 1
209        elif st == "F16" and not vf:
210            kind = F16_IN_F32
211            dst_bytes = elems * 2
212            saved += src_bytes - dst_bytes
213            n_reduced += 1
214        elif st == "F16":
215            kind = VERBATIM                      # already 2 bytes on disk
216            dst_bytes = src_bytes
217        elif st == "F32":
218            kind = F32_COPY
219            dst_bytes = elems * 4
220        else:
221            kind = VERBATIM
222            dst_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.
225            if dst_bytes != src_bytes + widen_here:
226                print("%s: engine form %d != pack %d + widening %d" % (name, dst_bytes, src_bytes, widen_here),
227                      file=sys.stderr)
228                return 1
229
230        cb = v.get("codebook")
231        rows.append((name, FILE_ID[f], kind, src_off, src_bytes, dst, dst_bytes, ne0, ne1,
232                     int(v.get("code_bits") or 0), int(v.get("code_bias") or 0),
233                     int(v.get("group_elems") or 0), 1 if cb == "IQ4NL" else 0,
234                     1 if v.get("has_offset") else 0,
235                     codes_bytes, scales_bytes, offset_bytes, scales_fp16, act_kind))
236        dst = align_up(dst + dst_bytes)
237        kinds[kind] = kinds.get(kind, 0) + 1
238
239    with open(out_path, "w", encoding="utf-8", newline="\n") as fh:
240        fh.write("# strata pack index v3  --  generated by tools/pack_index.py; do not hand-edit\n")
241        fh.write("# align %d pool %d tensors %d\n" % (align, dst, len(rows)))
242        fh.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")
244        for r in rows:
245            fh.write("%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n" % r)
246
247    names = {VERBATIM: "VERBATIM", BF16_IN_F32: "BF16_IN_F32", F32_COPY: "F32", F16_IN_F32: "F16_IN_F32"}
248    print("%s: %d tensors, engine pool %d B (%.3f GiB)" % (out_path, len(rows), dst, dst / 2**30))
249    for k in sorted(kinds):
250        print("   kind %-12s %4d tensors" % (names[k], kinds[k]))
251    print("   %d tensors re-rounded to 16 bits, saving %d B (%.3f GiB)"
252          % (n_reduced, saved, saved / 2**30))
253    print("   %d tensors widened fp16 scales -> f32, costing %d B (%.3f GiB)"
254          % (n_widened, widened, widened / 2**30))
255    print("   compare with tools/pack_budget.py: the pack's dense+embd engine figure should match this pool")
256    return 0
257
258
259if __name__ == "__main__":
260    raise SystemExit(main())