okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""Tuning history: what makes two measurements comparable. 2 3Checklist T06 asks that an engine, model, driver, workload or context change invalidates 4incompatible history, and that model identity is more than a name. Both matter for the same reason: 5a tuning result is only meaningful relative to the machine and the exact bytes it was measured on, 6and a history that silently mixes two configurations produces a confident recommendation from 7incomparable numbers. 8 9The design follows from that: 10 11* **Identity is a content hash, not a label.** A model is identified by the digest of its file(s), an 12engine by the digest of its binary. "qwen3.8-flash-next" and "the same filename" are not 13identities: a re-quantised model keeps its name and changes its behaviour. 14* **The comparison key is explicit and complete.** Engine + model + backend + workload + context + 15the machine. Any element changing makes two records incomparable, and the *reason* is reported 16rather than the record being quietly dropped. 17* **Nothing is deleted.** Incomparable history is retained and labelled. A previous sweep may still 18answer a question ("did that flag help on the old driver?"), so it is not the store's business to 19discard it — only to refuse to average it with the new numbers. 20* **Hashing a multi-gigabyte model is bounded.** A full digest of a 40 GB pack is not something to do 21casually, so a partial digest (size plus sampled regions) is used by default, and the method is 22recorded so two records can never be compared as though they used the same one. 23""" 24 25from __future__import annotations 26 27import hashlib 28import json 29import os 30from strata_control import sysinfo 31import time 32import uuid 33from dataclasses import asdict ,dataclass ,field 34from pathlib import Path 35from typing import Any 36 37SCHEMA_VERSION = 1 38 39#: How a file's identity was computed. Two records with different methods are not comparable, so the 40#: method travels with the digest. 41FULL = "sha256-full" 42SAMPLED = "sha256-sampled-head-tail-mid" 43 44#: Bytes read at each sampled region. 45SAMPLE_BYTES = 4 << 20 46 47 48def file_identity (path :Path ,* ,full :bool = False )-> dict [str ,Any ]: 49"""A content identity for a file, cheaply by default. 50 51A model pack is tens of gigabytes; hashing it fully on every CLI invocation would be its own kind 52of bug. The sampled digest reads the head, the middle and the tail plus the exact size, which 53catches a different quantisation, a truncated download and a swapped file in practice. `full=True` 54is available for a release-time record where the cost is acceptable. 55""" 56p = Path (path ) 57if not p .exists (): 58return {"path" :str (p ),"exists" :False ,"method" :None ,"digest" :None ,"bytes" :None } 59size = p .stat ().st_size 60h = hashlib .sha256 () 61if full : 62method = FULL 63with p .open ("rb" )as fh : 64for block in iter (lambda :fh .read (1 << 20 ),b"" ): 65h .update (block ) 66else : 67method = SAMPLED 68h .update (str (size ).encode ()) 69with p .open ("rb" )as fh : 70regions = [] 71if size <= 3 * SAMPLE_BYTES : 72regions .append ((0 ,size )) 73else : 74regions = [(0 ,SAMPLE_BYTES ), 75 (size // 2 ,SAMPLE_BYTES ), 76 (size - SAMPLE_BYTES ,SAMPLE_BYTES )] 77for offset ,length in regions : 78fh .seek (offset ) 79h .update (fh .read (length )) 80return {"path" :str (p ),"exists" :True ,"method" :method ,"digest" :h .hexdigest (), 81"bytes" :size } 82 83 84def machine_identity ()-> dict [str ,Any ]: 85"""The machine, at the granularity that makes measurements incomparable when it changes. 86 87The CPU/GPU model and the driver version are what matter; the hostname is not (a renamed machine 88is the same machine), so it is deliberately absent. 89""" 90return { 91"system" :sysinfo .system (), 92"release" :sysinfo .release (), 93"machine" :sysinfo .machine (), 94"processor" :sysinfo .processor (), 95"cpu_count" :os .cpu_count (), 96 } 97 98 99def comparison_key (* ,engine :dict [str ,Any ],model :dict [str ,Any ],backend :str , 100workload :dict [str ,Any ],context :int | None , 101machine :dict [str ,Any ]| None = None )-> dict [str ,Any ]: 102"""The tuple that two records must share to be comparable. 103 104Every element is either a digest or a fixed number, so an equality test on this dict is the whole 105comparability rule. A field that is unknown is `None` and therefore *not* equal to a known value, 106which is deliberate: an unknown is not evidence of sameness. 107""" 108return { 109"engine_digest" :engine .get ("digest" ), 110"engine_bytes" :engine .get ("bytes" ), 111"model_digest" :model .get ("digest" ), 112"model_bytes" :model .get ("bytes" ), 113"digest_method" :model .get ("method" ), 114"backend" :backend , 115"workload" :dict (sorted (workload .items ())), 116"context" :context , 117"machine" :dict (sorted ((machine or machine_identity ()).items ())), 118 } 119 120 121def incomparable_reasons (a :dict [str ,Any ],b :dict [str ,Any ])-> list [str ]: 122"""Why two comparison keys cannot be compared, in plain words. 123 124Returning the reasons rather than a boolean is what lets a report say *"the model changed, so the 125earlier sweep no longer applies"* instead of showing a recommendation built across a change. 126""" 127reasons :list [str ]= [] 128if a .get ("engine_digest" )!= b .get ("engine_digest" ): 129reasons .append ("a different engine build" ) 130if a .get ("model_digest" )!= b .get ("model_digest" ): 131reasons .append ("different model bytes" ) 132a_method ,b_method = a .get ("digest_method" ),b .get ("digest_method" ) 133if a_method != b_method : 134reasons .append (f"the identity was computed differently ( { a_method } vs { b_method } )" ) 135if a .get ("backend" )!= b .get ("backend" ): 136reasons .append (f"a different backend ( { a . get ( 'backend' ) } vs { b . get ( 'backend' ) } )" ) 137if a .get ("workload" )!= b .get ("workload" ): 138reasons .append ("a different workload" ) 139if a .get ("context" )!= b .get ("context" ): 140reasons .append (f"a different context ( { a . get ( 'context' ) } vs { b . get ( 'context' ) } )" ) 141if a .get ("machine" )!= b .get ("machine" ): 142reasons .append ("a different machine or driver" ) 143return reasons 144 145 146@dataclass 147class HistoryRecord : 148"""One completed sweep, as the history store keeps it.""" 149 150id :str 151recorded_at :float 152key :dict [str ,Any ] 153outcome :str # accepted | inconclusive | conflict | cancelled 154recommendation_args :dict [str ,str ]= field (default_factory = dict ) 155median :float | None = None 156baseline_median :float | None = None 157metric :str = "tokens_per_s" 158trials_run :int = 0 159combinations_total :int = 0 160engine_path :str = "" 161model_path :str = "" 162note :str = "" 163 164def to_dict (self )-> dict [str ,Any ]: 165return asdict (self ) 166 167 168class HistoryStore : 169"""Recorded sweeps, kept so a later one can say what it is and is not comparable to. 170 171The store is a directory of JSON records rather than a database: it is small, it is read whole by 172a human when something looks wrong, and it has no server to be unavailable. 173""" 174 175def __init__ (self ,root :Path )-> None : 176self .root = Path (root ) 177self .root .mkdir (parents = True ,exist_ok = True ) 178 179@property 180def index (self )-> Path : 181return self .root / "history.jsonl" 182 183def record (self ,* ,key :dict [str ,Any ],outcome :str ,recommendation_args :dict [str ,str ]| None = None , 184median :float | None = None ,baseline_median :float | None = None , 185metric :str = "tokens_per_s" ,trials_run :int = 0 ,combinations_total :int = 0 , 186engine_path :str = "" ,model_path :str = "" ,note :str = "" )-> HistoryRecord : 187rec = HistoryRecord ( 188id = uuid .uuid4 ().hex ,recorded_at = time .time (),key = key ,outcome = outcome , 189recommendation_args = dict (recommendation_args or {}),median = median , 190baseline_median = baseline_median ,metric = metric ,trials_run = trials_run , 191combinations_total = combinations_total ,engine_path = engine_path ,model_path = model_path , 192note = note ) 193with self .index .open ("a" ,encoding = "utf-8" )as fh : 194fh .write (json .dumps ({"schema_version" :SCHEMA_VERSION ,** rec .to_dict ()}, 195sort_keys = True )+ "\n" ) 196return rec 197 198def records (self )-> list [HistoryRecord ]: 199"""Every record, newest last. A damaged line is skipped, not fatal.""" 200if not self .index .exists (): 201return [] 202out :list [HistoryRecord ]= [] 203for line in self .index .read_text (encoding = "utf-8" ).splitlines (): 204if not line .strip (): 205continue 206try : 207data = json .loads (line ) 208except json .JSONDecodeError : 209continue 210if data .get ("schema_version" )!= SCHEMA_VERSION : 211continue 212data .pop ("schema_version" ,None ) 213try : 214out .append (HistoryRecord (** data )) 215except TypeError : 216continue 217return out 218 219def comparable (self ,key :dict [str ,Any ])-> tuple [list [HistoryRecord ],list [dict [str ,Any ]]]: 220"""Split the history into what *is* comparable and what is not, with reasons. 221 222Nothing is dropped: an incomparable record is returned with the reason it differs, because 223the honest answer to "is there relevant history?" is often "yes, but from a different model". 224""" 225usable :list [HistoryRecord ]= [] 226unusable :list [dict [str ,Any ]]= [] 227for rec in self .records (): 228reasons = incomparable_reasons (rec .key ,key ) 229if reasons : 230unusable .append ({"id" :rec .id ,"recorded_at" :rec .recorded_at ,"reasons" :reasons , 231"outcome" :rec .outcome }) 232else : 233usable .append (rec ) 234return usable ,unusable 235 236 237def summarise_history (store :HistoryStore ,key :dict [str ,Any ])-> dict [str ,Any ]: 238"""The block a report carries so a reader knows what the numbers sit next to.""" 239usable ,unusable = store .comparable (key ) 240return { 241"comparable_records" :len (usable ), 242"incomparable_records" :len (unusable ), 243"incomparable" :unusable [- 8 :],# the most recent few, with their reasons 244"note" : ("earlier sweeps on this exact engine, model, workload, context and machine" 245if usable else 246"no earlier sweep is comparable to this one" ), 247 }