okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0479b72e9
main
1#!/usr/bin/env python3 2"""The answers rule for Qwen3.6: greedy picture answers of strata-q36 (the engine protocol, one engine for every arm) for embeddings made by different readers. 3 4python3 answers_q36.py --engine <strata-q36> --model <Qwen3.6 .gguf> --vc <dir with shapes.png.q0.llama.log / .q1.llama.log> --out <dir> 5[--n 48] [--engine-args "--max-context 4096 --vision"] --arm mtmd-cpu=<dir of .sve> --arm own-cpu=<dir> --arm mtmd-gpu=<dir> --arm own-gpu=<dir> 6[--pictures a.png b.png ...] 7 8Every arm is a folder of <picture name>.sve files (strata-vision outputs of one reader for the same pictures at the same token limit). The prompt ids are the 9chat template's: the text before the picture, the picture's pad tokens (as many as the .sve has rows), then the text after it with the question. The two 10questions are the ones q36_vision_cmp.py asks (their token ids are read from llama.cpp's logs of shapes.png, which the question's tokens do not depend on). 11The engine decodes greedily; the ids are turned back into text with the model's own vocabulary (byte-level BPE). Prints the pairwise counts of identical 12answers and every differing answer with all arms side by side. Exit 0 when every answer is identical, 1 otherwise. Standard library plus tools/qwen35/q36_harness.py. 13""" 14import argparse 15import json 16import os 17import struct 18import sys 19 20PAD = 248056 21 22 23def read_tokens (gguf ): 24"""The vocabulary (token strings) of a GGUF: a stdlib reader of the header's tokenizer.ggml.tokens array.""" 25f = open (gguf ,"rb" ) 26 27def u (fmt ): 28n = struct .calcsize (fmt ) 29return struct .unpack ("<" + fmt ,f .read (n ))[0 ] 30 31def s (): 32return f .read (u ("Q" )) 33 34sizes = {0 :"B" ,1 :"b" ,2 :"H" ,3 :"h" ,4 :"I" ,5 :"i" ,6 :"f" ,7 :"?" ,10 :"Q" ,11 :"q" ,12 :"d" } 35 36def val (t ,keep ): 37if t == 8 : 38return s ().decode ("utf8" ,"replace" )if keep else s ()and None 39if t == 9 : 40et ,n = u ("I" ),u ("Q" ) 41if et == 8 : 42items = [s ()for _ in range (n )] 43return [x .decode ("utf8" ,"replace" )for x in items ]if keep else None 44sz = struct .calcsize (sizes [et ]) 45f .seek (n * sz ,1 ) 46return None 47return u (sizes [t ]) 48 49assert f .read (4 )== b"GGUF" 50u ("I" ) 51u ("Q" ) 52nk = u ("Q" ) 53for _ in range (nk ): 54k = s ().decode () 55t = u ("I" ) 56v = val (t ,k == "tokenizer.ggml.tokens" ) 57if k == "tokenizer.ggml.tokens" : 58return v 59raise SystemExit ("no vocabulary in " + gguf ) 60 61 62def byte_decoder (): 63bs = list (range (ord ("!" ),ord ("~" )+ 1 ))+ list (range (ord ("\xa1" ),ord ("\xac" )+ 1 ))+ list (range (ord ("\xae" ),ord ("\xff" )+ 1 )) 64cs = bs [:] 65n = 0 66for b in range (256 ): 67if b not in bs : 68bs .append (b ) 69cs .append (256 + n ) 70n += 1 71return {chr (c ):b for b ,c in zip (bs ,cs )} 72 73 74def decode (ids ,vocab ,bd ): 75out = bytearray () 76for i in ids : 77t = vocab [i ]if 0 <= i < len (vocab )else "" 78if t .startswith ("<|" )and t .endswith ("|>" ): 79continue # special tokens (the end of the turn) are not text 80out += bytes (bd .get (ch ,ord ("?" ))for ch in t ) 81return out .decode ("utf8" ,"replace" ) 82 83 84def chunks (logfile ): 85"""(text before the picture, text after it) of a llama.cpp dump log: the 'text:' lines around the 'image:' line.""" 86before ,after ,seen = [], [],False 87for line in open (logfile ): 88if line .startswith ("text:" ): 89 (after if seen else before ).extend (int (x )for x in line .split (":" ,1 )[1 ].split ()) 90elif line .startswith ("image:" ): 91seen = True 92return before ,after 93 94 95def main (): 96ap = argparse .ArgumentParser () 97ap .add_argument ("--engine" ,required = True ) 98ap .add_argument ("--model" ,required = True ) 99ap .add_argument ("--vc" ,required = True ) 100ap .add_argument ("--out" ,required = True ) 101ap .add_argument ("--n" ,type = int ,default = 48 ) 102ap .add_argument ("--engine-args" ,default = "--max-context 4096 --vision" ) 103ap .add_argument ("--arm" ,action = "append" ,required = True ,help = "label=<dir of .sve files>" ) 104ap .add_argument ("--pictures" ,nargs = "*" ,default = []) 105a = ap .parse_args () 106sys .path .insert (0 ,os .path .join (os .path .dirname (os .path .abspath (__file__ )),".." ,".." ,"qwen35" )) 107from q36_harness import Eng # noqa: E402 108 109os .makedirs (a .out ,exist_ok = True ) 110arms = [x .split ("=" ,1 )for x in a .arm ] 111pics = a .pictures or sorted (n [:- 4 ]for n in os .listdir (arms [0 ][1 ])if n .endswith (".sve" )) 112questions = [] 113q = 0 114while os .path .isfile (os .path .join (a .vc ,"shapes.png.q%d.llama.log" % q )):# q0, q1, ... : one log per question 115questions .append (chunks (os .path .join (a .vc ,"shapes.png.q%d.llama.log" % q ))) 116q += 1 117vocab ,bd = read_tokens (a .model ),byte_decoder () 118eng = Eng (a .engine , ["--model" ,a .model ]+ a .engine_args .split (),log = os .path .join (a .out ,"engine.log" )) 119"engine ready after %.0f s" % eng .load_s ,flush = True ) 120res = {label : {}for label ,_ in arms } 121for pic in pics : 122for label ,d in arms : 123sve = os .path .join (d ,pic + ".sve" ) 124if not os .path .isfile (sve ): 125continue 126n_img = struct .unpack ("<5i" ,open (sve ,"rb" ).read (20 ))[1 ] 127for qi , (pre ,post )in enumerate (questions ): 128ids = pre + [PAD ]* n_img + post 129try : 130toks ,done ,_ ,wall = eng .solo (ids ,a .n ,emb = sve ) 131text = decode (toks ,vocab ,bd ) 132err = None 133except SystemExit as e :# the engine said ERR for this request 134text ,err = "" ,str (e ) 135res [label ]["%s|q%d" % (pic ,qi )]= {"text" :text ,"ids" :toks if err is None else [],"err" :err } 136"%-10s %-24s q%d: %r%s" % (label ,pic ,qi ,text [:90 ]," ERR " + err if err else "" ),flush = True ) 137json .dump (res ,open (os .path .join (a .out ,"answers.json" ),"w" ),indent = 1 ) 138 139labels = [l for l ,_ in arms ] 140keys = list (res [labels [0 ]]) 141ok = lambda l ,k :k in res [l ]and not res [l ][k ]["err" ]# noqa: E731 142"ANSWERS, pair by pair (identical / compared):" ) 143for i ,la in enumerate (labels ): 144for lb in labels [i + 1 :]: 145same = sum (1 for k in keys if ok (la ,k )and ok (lb ,k )and res [la ][k ]["ids" ]== res [lb ][k ]["ids" ]) 146" %-10s vs %-10s %d / %d" % (la ,lb ,same ,len (keys ))) 147differing = [k for k in keys if len ({tuple (res [l ][k ]["ids" ])if ok (l ,k )else None for l in labels })> 1 ] 148"%d of %d answers differ between some readers; all of them:" % (len (differing ),len (keys ))) 149for k in differing : 150"DIFFERS %s" % k ) 151for l in labels : 152" %-10s: %r" % (l ,res [l ][k ]["text" ]if ok (l ,k )else "ERR" )) 153eng .send ("QUIT" ) 154return 0 if not differing else 1 155 156 157if __name__ == "__main__" : 158sys .exit (main ())