okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1#!/usr/bin/env python3 2"""engram_fold.py - the Engram tensors a pack needs, folded out of the quant's own shards, so a pack built around their 3`engram-IQ4_NL.gguf` uses none of our substitutes. 4 5The IST-DAS sets keep the Engram as three per-layer tensors (`blk.N.engram_k`, `engram_q`, `engram_wkv`); the engine's 6layout wants `engram.gate` (k*q folded, [4, 5120] F32) and `engram.wkv` ([25600, 6144] BF16). Theirs are stored the other 7way round - their `engram_wkv` is `[6144, 25600]` and their `k/q` are `[5120, 4]` - so this tool dequantises, transposes and 8writes the engine's layout: 9 10gate = transpose(k) * transpose(q) F32 11wkv = transpose(dequant(wkv)) BF16 12 13Output is a `dense_requant.py`-style folder (dense.json + dense.bin) for `pack_gguf.py --dense-override`. 14 15usage: 16engram_fold.py --model /data/helcig/set200/2.00bpw --out /data/helcig/engram_fold_200 [--layers 1,14] 17pack_gguf.py --model <set> --out <pack> --engram <their engram dir> \ 18--skip-tensors 'attn_output_a|engram_(k|q|wkv)\\.' --dense-override <fold dir> ... 19""" 20from __future__import annotations 21 22import argparse 23import json 24import os 25import pathlib 26import re 27import sys 28 29import numpy as np 30 31sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 32import pack_gguf # noqa: E402 (its GGUF reader and its type table) 33 34 35def shards (model :pathlib .Path ): 36return [pack_gguf .Gguf (p )for p in sorted (model .glob ("*.gguf" ))] 37 38 39def find (gs ,name ): 40for g in gs : 41for t in g .tensors : 42if t [0 ]== name : 43return g ,t 44return None ,None 45 46 47def nbytes (typ :int ,dims )-> int : 48tname ,per ,bpb = pack_gguf .TYPES [typ ] 49nel = 1 50for d in dims : 51nel *= int (d ) 52return nel // per * bpb if per > 1 else nel * bpb 53 54 55def dequant_q5k (raw :np .ndarray ,nblocks :int )-> np .ndarray : 56"""ggml block_q5_K (176 B, 256 values): f16 d, f16 dmin, uint8 scales[12], qh[32], qs[128].""" 57b = raw .reshape (nblocks ,176 ) 58d = b [:,0 :2 ].copy ().view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 59dmin = b [:,2 :4 ].copy ().view (np .float16 ).astype (np .float32 ).reshape (- 1 ) 60scales ,qh ,qs = b [:,4 :16 ].astype (np .int32 ),b [:,16 :48 ].astype (np .int32 ),b [:,48 :176 ].astype (np .int32 ) 61sc = np .empty ((nblocks ,8 ),np .float32 ) 62mn = np .empty ((nblocks ,8 ),np .float32 ) 63# ggml's get_scale_min_k4: the first four 6-bit scales are bytes 0..3 (low) and 4..7 (mins); 64# the last four take the top two bits of bytes 0..3 plus the low/high nibbles of 8..11 65for j in range (8 ): 66if j < 4 : 67sc [:,j ]= scales [:,j ]& 63 68mn [:,j ]= scales [:,j + 4 ]& 63 69else : 70sc [:,j ]= (scales [:,j + 4 ]& 0xF )| ((scales [:,j - 4 ]>> 6 )<< 4 ) 71mn [:,j ]= (scales [:,j + 4 ]>> 4 )| ((scales [:,j ]>> 6 )<< 4 ) 72out = np .empty ((nblocks ,256 ),dtype = np .float32 ) 73for j in range (4 ): 74for half in range (2 ): 75d1 = d * sc [:,j * 2 + half ] 76m1 = dmin * mn [:,j * 2 + half ] 77q = qs [:,j * 32 :(j + 1 )* 32 ] 78h = (qh >> (j * 2 + half ))& 1 79nib = ((q & 0xF )if half == 0 else (q >> 4 ))+ (h << 4 ) 80out [:,j * 64 + half * 32 :j * 64 + half * 32 + 32 ]= d1 [:,None ]* nib - m1 [:,None ] 81return out .reshape (- 1 ) 82 83 84def dequant (g ,t )-> np .ndarray : 85name ,typ ,dims ,off = t 86tname = pack_gguf .TYPES [typ ][0 ] 87nb = nbytes (typ ,dims ) 88# Gguf's tensor offsets are relative to the shard's data section; pack_gguf adds data_start when it writes a pack 89raw = np .fromfile (g .path ,dtype = np .uint8 ,count = nb ,offset = g .data_start + off ) 90if tname == "Q5_K" : 91return dequant_q5k (raw ,nb // 176 ).astype (np .float64 ) 92if tname == "Q4_K" : 93raise SystemExit ("%s: Q4_K not handled by the fold yet (Q5_K, F32, F16, BF16 are)" % name ) 94if tname == "F32" : 95return raw .view (np .float32 ).astype (np .float64 ) 96if tname == "BF16" : 97return (raw .view (np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ).astype (np .float64 ) 98if tname == "F16" : 99return raw .view (np .float16 ).astype (np .float64 ) 100raise SystemExit ("%s: type %s is not one the fold reads" % (name ,tname )) 101 102 103def to_bf16_bytes (v :np .ndarray )-> bytes : 104"""F32 -> BF16, round to nearest even (what ggml's ggml_compute_fp32_to_bf16 does).""" 105u = v .astype (np .float32 ).view (np .uint32 ) 106lsb = (u >> 16 )& 1 107rounded = (u + 0x7FFF + lsb )>> 16 108return rounded .astype (np .uint16 ).tobytes () 109 110 111def main ()-> int : 112ap = argparse .ArgumentParser () 113ap .add_argument ("--model" ,required = True ,help = "the folder of the quant's GGUF shards" ) 114ap .add_argument ("--out" ,required = True ,help = "the override folder to write (dense.json + dense.bin)" ) 115ap .add_argument ("--layers" ,default = "" ,help = "comma list of Engram layers; default: every layer with an engram_k" ) 116ap .add_argument ("--gate-kv-from" ,default = "" ,help = "a known-good pack to copy engram.gate/wkv from (the ple table stays the only difference)" ) 117a = ap .parse_args () 118model = pathlib .Path (a .model ).expanduser ().resolve () 119out = pathlib .Path (a .out ).expanduser ().resolve () 120gs = shards (model ) 121if not gs : 122raise SystemExit ("%s: no .gguf files" % model ) 123names = {t [0 ]for g in gs for t in g .tensors } 124if a .layers : 125layers = [int (x )for x in a .layers .split ("," )if x .strip ()] 126else : 127layers = sorted ({int (n .split ("." )[1 ])for n in names if n .startswith ("blk." )and ".engram_k." in n }) 128out .mkdir (parents = True ,exist_ok = True ) 129idx :dict [str ,list ]= {} 130blobs :list [bytes ]= [] 131off = 0 132 133def add (name :str ,tname :str ,data :bytes ,shape :list [int ])-> None : 134nonlocal off 135pad = (- off )% 64 136if pad : 137blobs .append (b"\0" * pad ) 138off += pad 139blobs .append (data ) 140idx [name ]= [tname ,"dense.bin" ,off ,len (data ),shape ] 141off += len (data ) 142 143# --gate-kv-from PACK: take the gate and the kv from a pack that is known good (the engine's own layout, already in the 144# right orientation) instead of deriving them from their k/q/wkv. That leaves the ple table as the only difference 145# between the two packs, which is the only way to score their IQ4_NL Engram against our MXFP8 one. 146if a .gate_kv_from : 147src = pathlib .Path (a .gate_kv_from ).expanduser ().resolve () 148md = [l .split (None ,1 )[1 ]for l in (src / "ds4.txt" ).read_text ().splitlines ()if l .startswith ("model_dir " )][0 ] 149files ,want = {}, {} 150for line in (src / "tensors.txt" ).read_text ().splitlines (): 151f = line .split () 152if not f : 153continue 154if f [0 ]== "file" : 155files [int (f [1 ])]= " " .join (f [2 :]) 156elif f [0 ]== "t" and re .match (r"layers\.\d+\.engram\.(gate|wkv)\.weight$" ,f [1 ]): 157want [f [1 ]]= (f [2 ],int (f [3 ]),int (f [4 ]),int (f [5 ]), [int (x )for x in f [6 :]]) 158for name , (tname ,fi ,o ,nb ,shape )in sorted (want .items ()): 159p = (pathlib .Path (md )/ files [fi ]).resolve () 160add (name ,tname ,np .fromfile (p ,dtype = np .uint8 ,count = nb ,offset = o ).tobytes (),shape ) 161"%s: copied from %s (%s, %d bytes)" % (name ,src .name ,tname ,nb )) 162 (out / "dense.bin" ).write_bytes (b"" .join (blobs )) 163json .dump (idx ,open (out / "dense.json" ,"w" ),indent = 1 ) 164"wrote %s (%.2f MB), dense.json with %d tensors" % (out / "dense.bin" ,os .path .getsize (out / "dense.bin" )/ 1e6 ,len (idx ))) 165return 0 166 167for il in layers : 168kg ,kt = find (gs ,"blk.%d.engram_k.weight" % il ) 169qg ,qt = find (gs ,"blk.%d.engram_q.weight" % il ) 170wg ,wt = find (gs ,"blk.%d.engram_wkv.weight" % il ) 171if kt is None or qt is None : 172"layer %d: no engram_k/q in these shards, skipped" % il ) 173continue 174# their k/q are [5120, 4] (ne0 = 5120): the engine's gate is [4, 5120] 175k = dequant (kg ,kt ).reshape (kt [2 ][1 ],kt [2 ][0 ]).T 176q = dequant (qg ,qt ).reshape (qt [2 ][1 ],qt [2 ][0 ]).T 177if k .shape != q .shape : 178raise SystemExit ("layer %d: k %s and q %s differ after the transpose" % (il ,k .shape ,q .shape )) 179gate = (k * q ).astype (np .float32 ) 180add ("layers.%d.engram.gate.weight" % il ,"F32" ,gate .tobytes (), [gate .shape [1 ],gate .shape [0 ]]) 181note = "MISSING" 182if wt is not None : 183w = dequant (wg ,wt ).reshape (wt [2 ][1 ],wt [2 ][0 ]).T .astype (np .float32 ) 184add ("layers.%d.engram.wkv.weight" % il ,"BF16" ,to_bf16_bytes (w ), [w .shape [1 ],w .shape [0 ]]) 185note = "BF16 [%d, %d]" % (w .shape [1 ],w .shape [0 ]) 186"layer %d: gate [%d, %d] F32, wkv %s" % (il ,gate .shape [1 ],gate .shape [0 ],note )) 187 188 (out / "dense.bin" ).write_bytes (b"" .join (blobs )) 189json .dump (idx ,open (out / "dense.json" ,"w" ),indent = 1 ) 190"wrote %s (%.2f MB), dense.json with %d tensors" % (out / "dense.bin" ,os .path .getsize (out / "dense.bin" )/ 1e6 ,len (idx ))) 191return 0 192 193 194if __name__ == "__main__" : 195sys .exit (main ())