okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1#!/usr/bin/env python3 2"""Fixed-token, single-session native engine baseline. TTFT here excludes HTTP/SSE.""" 3import argparse 4import hashlib 5import json 6import os 7from pathlib import Path 8import subprocess 9import sys 10import threading 11import time 12 13from single_gpu import ISOLATION ,ROOT ,validate_config 14from resource_sampler import ResourceSampler 15 16sys .path [:0 ]= [str (ROOT ),str (ROOT / "tools" )] 17from serve .frontend import ChatTemplate 18from serve .server import StrataEngine ,child_env 19from conversation_cache_parity import load_tokenizer ,state_hashes 20 21 22def save (path ,data ): 23tmp = path .with_suffix (path .suffix + ".tmp" ) 24tmp .write_text (json .dumps (data ,ensure_ascii = False ,indent = 2 )+ "\n" ) 25tmp .replace (path ) 26 27 28def gpu_fdinfo (pid ): 29"""Per-DRM-device counters; amd-smi may list one KFD process on every card.""" 30records = {} 31for path in (Path ("/proc" )/ str (pid )/ "fdinfo" ).iterdir (): 32try : 33text = path .read_text () 34if "drm-" in text : 35records [path .name ]= text 36except FileNotFoundError : 37continue 38return records 39 40 41def make_fixtures (cfg ,lengths ): 42directory = Path (cfg ["tokenizer" ]) 43tok = load_tokenizer (directory ) 44tpl = ChatTemplate (directory / "chat_template.jinja" ) 45marker = "STRATA_FIXTURE_DOCUMENT_MARKER" 46template = tpl .render ([{"role" :"user" ,"content" :"Read the following numbered records.\n" + marker 47+ "\nSummarize the record format, then write Python code to parse and validate it. " 48"Explain duplicate IDs and invalid integers." }],enable_thinking = False ) 49before ,after = template .split (marker ) 50prefix ,suffix = (tok .encode (text ,parse_special = True )for text in (before ,after )) 51corpus = "\n" .join (f"record { i :06d } : color= { ( 'red' , 'green' , 'blue' )[ i % 3 ] } , value= { i * 17 % 997 } ;" 52for i in range (max (lengths )// 8 + 100 )) 53body = tok .encode (corpus ) 54fixtures = [] 55for length in lengths : 56count = length - len (prefix )- len (suffix ) 57if count <= 0 or count > len (body ): 58raise ValueError ("fixture length outside corpus bounds" ) 59ids = prefix + body [:count ]+ suffix 60fixtures .append ({"name" :f"records- { length } " ,"tokens" :length ,"ids" :ids , 61"text" :tok .decode (ids ), 62"ids_sha256" :hashlib .sha256 (json .dumps (ids ).encode ()).hexdigest ()}) 63return {"schema" :1 ,"description" :"Exact native protocol token IDs; performance fixtures, not quality gates." , 64"tokenizer" :str (directory ),"fixtures" :fixtures } 65 66 67def main (): 68parser = argparse .ArgumentParser (description = __doc__ ) 69parser .add_argument ("--config" ,type = Path ,required = True ) 70parser .add_argument ("--fixtures" ,type = Path ,required = True ) 71parser .add_argument ("--make-fixtures" ,action = "store_true" ) 72parser .add_argument ("--lengths" ,type = int ,nargs = "+" ,default = [4096 ,32768 ,131072 ]) 73parser .add_argument ("--out" ,type = Path ) 74parser .add_argument ("--max-new" ,type = int ,default = 256 ) 75parser .add_argument ("--repeats" ,type = int ,default = 1 ) 76parser .add_argument ("--shape-warmups" ,type = int ,default = 0 , 77help = "full generations per selected shape, recorded but excluded from measurement" ) 78args = parser .parse_args () 79if args .repeats < 1 or args .shape_warmups < 0 or args .max_new < 1 : 80parser .error ("repeats/max-new must be positive; shape-warmups must be nonnegative" ) 81cfg = json .loads (args .config .read_text ()) 82validate_config (cfg ) 83if args .make_fixtures : 84if args .fixtures .exists (): 85parser .error ("fixture already exists; use it unchanged or choose a new path" ) 86save (args .fixtures ,make_fixtures (cfg ,args .lengths )) 87return 88if args .out is None : 89parser .error ("--out is required for measurement" ) 90if any (os .environ .get (k )!= v for k ,v in ISOLATION .items ()): 91parser .error ("launch measurements through single_gpu.py" ) 92args .out .mkdir (parents = True ,exist_ok = False ) 93fixtures = json .loads (args .fixtures .read_text ())["fixtures" ] 94selected = [f for f in fixtures if f ["tokens" ]in args .lengths ] 95if {f ["tokens" ]for f in selected }!= set (args .lengths ): 96parser .error ("missing requested fixture length" ) 97for fixture in selected : 98if (len (fixture ["ids" ])!= fixture ["tokens" ]or fixture ["ids_sha256" ]!= 99hashlib .sha256 (json .dumps (fixture ["ids" ]).encode ()).hexdigest ()): 100raise ValueError ("fixture token count or hash changed" ) 101env = child_env (cfg ) 102if any (env .get (k )!= v for k ,v in ISOLATION .items ()): 103raise ValueError ("child environment changed GPU isolation" ) 104manifest = {"config" :cfg ,"config_sha256" :hashlib .sha256 (args .config .read_bytes ()).hexdigest (), 105"fixtures_path" :str (args .fixtures .resolve ()), 106"fixtures_sha256" :hashlib .sha256 (args .fixtures .read_bytes ()).hexdigest (), 107"binary_sha256" :hashlib .sha256 (Path (cfg ["exe" ]).read_bytes ()).hexdigest (), 108"sampling" : {"temperature" :0 ,"top_k" :1 ,"top_p" :1 ,"min_p" :0 ,"seed" :42 }, 109"max_new" :args .max_new ,"timing_scope" :"native engine; excludes HTTP/SSE" , 110"warmup" : {"short" :1 ,"per_shape" :args .shape_warmups , 111"max_new" :args .max_new ,"exclude_phases" : ["short_warmup" ,"shape_warmup" ]}, 112"records" : []} 113save (args .out / "results.json" ,manifest ) 114start = time .perf_counter () 115engine = StrataEngine (cfg ["exe" ],cfg ["args" ],cwd = cfg ["cwd" ], 116log = str (args .out / "engine.log" ),env = env ) 117manifest .update (load_s = time .perf_counter ()- start ,engine_info = dict (engine .info ),pid = engine .proc .pid ) 118save (args .out / "results.json" ,manifest ) 119resources = ResourceSampler (engine .proc .pid ) 120try : 121proc = Path (f"/proc/ { engine . proc . pid } " ) 122 (args .out / "process-status.txt" ).write_text ((proc / "status" ).read_text ()) 123save (args .out / "thread-affinity.json" , { 124path .name : {k :v .strip ()for line in (path / "status" ).read_text ().splitlines () 125if ":" in line for k ,v in [line .split (":" ,1 )] 126if k in {"Name" ,"Cpus_allowed_list" ,"Mems_allowed_list" }} 127for path in (proc / "task" ).iterdir ()}) 128 (args .out / "loaded-maps.txt" ).write_text ((proc / "maps" ).read_text ()) 129 (args .out / "numastat.txt" ).write_text (subprocess .check_output (["numastat" ,"-p" ,str (engine .proc .pid )],text = True )) 130save (args .out / "gpu-fdinfo-ready.json" ,gpu_fdinfo (engine .proc .pid )) 131tok = load_tokenizer (Path (cfg ["tokenizer" ])) 132tpl = ChatTemplate (Path (cfg ["tokenizer" ])/ "chat_template.jinja" ) 133warm_ids = tok .encode (tpl .render ([{"role" :"user" ,"content" :"请用一句话解释什么是质数。" }], 134enable_thinking = False ),parse_special = True ) 135manifest ["warmup_ids" ]= warm_ids 136work = [{"name" :"warmup" ,"ids" :warm_ids ,"tokens" :len (warm_ids ),"phase" :"short_warmup" }] 137work += [dict (f ,repeat = n ,phase = "shape_warmup" ) 138for n in range (args .shape_warmups )for f in selected ] 139work += [dict (f ,repeat = n ,phase = "measurement" )for n in range (args .repeats )for f in selected ] 140for fixture in work : 141begin ,first ,output = time .perf_counter (),None , [] 142for token in engine .generate (fixture ["ids" ],args .max_new ,manifest ["sampling" ],threading .Event ()): 143if token is not None : 144if first is None : 145first = time .perf_counter () 146output .append (token ) 147record = {"name" :fixture ["name" ],"repeat" :fixture .get ("repeat" ), 148"phase" :fixture ["phase" ], 149"start_monotonic_s" :begin ,"end_monotonic_s" :time .perf_counter (), 150"input_tokens" :len (fixture ["ids" ]),"input_ids_sha256" : 151hashlib .sha256 (json .dumps (fixture ["ids" ]).encode ()).hexdigest (), 152"wall_s" :time .perf_counter ()- begin ,"ttft_s" :first - begin if first else None , 153"output_ids" :output ,"text" :tok .decode (output ),** engine .last } 154manifest ["records" ].append (record ) 155if env .get ("STRATA_STATE_HASH" )is not None : 156hashes = state_hashes ((args .out / "engine.log" ).read_text ()) 157if len (hashes )!= len (manifest ["records" ]): 158save (args .out / "results.json" ,manifest ) 159raise RuntimeError ("requested state hash was not emitted; this engine requires --prompt-cache > 0" ) 160record ["state" ]= hashes [- 1 ] 161save (args .out / "results.json" ,manifest ) 162save (args .out / f"gpu-fdinfo- { len ( manifest [ 'records' ]) } .json" ,gpu_fdinfo (engine .proc .pid )) 163json .dumps ({k :v for k ,v in record .items ()if k not in ("text" ,"output_ids" )}),flush = True ) 164if not output or record ["finish" ]not in ("stop" ,"length" ): 165raise RuntimeError ("generation did not finish normally" ) 166if record ["prompt_tokens" ]!= len (fixture ["ids" ]): 167raise RuntimeError ("engine prompt length does not match fixed fixture" ) 168if fixture ["name" ]!= "warmup" and record .get ("reused" )!= 0 : 169raise RuntimeError ("fresh baseline reused prompt tokens" ) 170finally : 171save (args .out / "resources.json" ,resources .close ()) 172engine .close () 173 174 175if __name__ == "__main__" : 176main ()