okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1#!/usr/bin/env python3 2"""Run the fixed EVO-X2 report protocol. Requires exclusive GPU use, a prepared pack/MTP, and HIP build. 3 4This script controls only the Strata processes it starts. Stop other GPU servers first. 5""" 6import argparse 7import hashlib 8import json 9import os 10import pathlib 11import signal 12import subprocess 13import sys 14import threading 15import time 16import urllib .request 17 18ROOT = pathlib .Path (__file__ ).resolve ().parents [4 ] 19HERE = pathlib .Path (__file__ ).resolve ().parent 20ap = argparse .ArgumentParser (description = __doc__ ) 21for name in ['model' ,'build' ,'sdk' ,'out' ]:ap .add_argument ('--' + name ,type = pathlib .Path ,required = True ) 22ap .add_argument ('--port' ,type = int ,default = 18741 ) 23a = ap .parse_args ();a .out .mkdir (parents = True ,exist_ok = True ) 24url = f'http://127.0.0.1: { a . port } ' 25base_env = {** os .environ ,'PYTHONUNBUFFERED' :'1' ,'ROCM_PATH' :str (a .sdk ),'HIP_PATH' :str (a .sdk ),'HIP_PLATFORM' :'amd' ,'LD_LIBRARY_PATH' :':' .join (str (a .sdk / x )for x in ['lib' ,'lib/rocm_sysdeps/lib' ,'lib/llvm/lib' ]),'STRATA_HIPBLASLT_TUNING' :str (ROOT / 'tools/hip/gfx1151-hipblaslt-100401.txt' )} 26# Avoid inheriting unrelated engine experiments from the caller. 27base_env = {k :v for k ,v in base_env .items ()if not k .startswith ('STRATA_' )or k == 'STRATA_HIPBLASLT_TUNING' } 28FAST = dict (STRATA_PF_FUSED = '1' ,STRATA_PF_GEMM = '1' ,STRATA_HC_UPMIX = '1' ,STRATA_PA_FAST = '1' ,STRATA_HIP_WMMA = '1' ,STRATA_SELECT_WMMA = '1' ,STRATA_HC_Q8 = '1' ,STRATA_PF_SWITCH_MIN_T = '4096' ,STRATA_PREFILL_STREAM_MIN = '128' ) 29server = None ;server_log = None ;phase = 'initial' ;events = [];stop_event = threading .Event () 30def gtt_bytes (): 31return sum (int (p .read_text ())for p in pathlib .Path ('/sys/class/drm' ).glob ('card*/device/mem_info_gtt_used' )) 32initial_gtt = gtt_bytes () 33 34def event (kind ,** fields ): 35row = dict (timestamp = time .time (),phase = phase ,event = kind ,** fields );events .append (row ) 36with (a .out / 'events.jsonl' ).open ('a' )as f :f .write (json .dumps (row )+ '\n' ) 37json .dumps (row ),flush = True ) 38 39def group_stop (p ): 40if p is None :return 41try :os .killpg (p .pid ,signal .SIGTERM ) 42except ProcessLookupError :return 43try :p .wait (timeout = 45 ) 44except subprocess .TimeoutExpired : 45os .killpg (p .pid ,signal .SIGKILL );p .wait (timeout = 15 ) 46 47def stop_server (): 48global server ,server_log 49group_stop (server );server = None 50if server_log :server_log .close ();server_log = None 51# Do not start the next GPU process until KFD no longer attributes mappings to this engine. 52deadline = time .monotonic ()+ 60 53while time .monotonic ()< deadline : 54alive = [] 55for p in pathlib .Path ('/sys/class/kfd/kfd/proc' ).glob ('*' ): 56try : 57cmd = (pathlib .Path ('/proc' )/ p .name / 'cmdline' ).read_bytes () 58if str (a .build ).encode ()in cmd :alive .append (p .name ) 59except FileNotFoundError :continue 60if not alive and gtt_bytes ()<= initial_gtt + 512 * 1024 ** 2 :return 61time .sleep (1 ) 62raise RuntimeError ('Strata GPU mappings/GTT were not released' ) 63 64def get (path ): 65with urllib .request .urlopen (url + path ,timeout = 10 )as response :return json .load (response ) 66 67def config (name ,ctx ,fast = False ,parallel = 1 ,borrow = True ): 68args = ['--pack' ,str (a .model / 'pack' ),'--native' ,str (a .model / 'UD-IQ4_XS/Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf' ),'--expert-profile' ,str (ROOT / 'data/expert-profile.bin' ),'--expert-cache' ,'auto' ,'--resident-budget-gib' ,'55' ,'--prefill' ,'16384' if fast else 'auto' ,'--spec' ,'4' ,'--spec-min-p' ,'0.5' ,'--mtp' ,str (a .model / 'mtp/rt' ),'--max-context' ,str (ctx ),'--kv' ,'int8' ] 69if ctx >= 65536 :args += ['--kv-resident' ,'32768' ] 70if fast :args += ['--lookup-chain' ,'3' ,'--mtp-q4' ,'all' ] 71if not borrow :args += ['--no-prefill-borrow' ] 72cfg = dict (exe = str (a .build / 'strata' ),args = args ,cwd = str (ROOT ),tokenizer = str (a .model / 'pack/tokenizer' ),model_name = 'strata' ,log = str (a .out / (name + '-engine.log' )),host = '127.0.0.1' ,port = a .port ,parallel = parallel ,open_browser = False ) 73path = a .out / (name + '-config.json' );path .write_text (json .dumps (cfg ,indent = 2 ));return path 74 75def start (name ,ctx ,fast = False ,parallel = 1 ,borrow = True ,qfuse = None ): 76global server ,server_log ,phase 77stop_server ();phase = name 78cfg = config (name ,ctx ,fast ,parallel ,borrow ) 79env = {** base_env ,** (FAST if fast else {})} 80if qfuse is not None :env ['STRATA_QFUSE' ]= str (qfuse ) 81 (a .out / (name + '-env.json' )).write_text (json .dumps ({k :v for k ,v in env .items ()if k .startswith ('STRATA_' )},indent = 2 )) 82server_log = (a .out / (name + '-server.log' )).open ('w' ) 83server = subprocess .Popen ([sys .executable ,str (ROOT / 'serve/server.py' ),'--engine' ,'strata' ,'--config' ,str (cfg ),'--host' ,'127.0.0.1' ,'--port' ,str (a .port )],cwd = ROOT ,env = env ,stdout = server_log ,stderr = subprocess .STDOUT ,start_new_session = True ) 84event ('server-start' ,pid = server .pid ,config = str (cfg )) 85deadline = time .monotonic ()+ 600 86while time .monotonic ()< deadline : 87if server .poll ()is not None :raise RuntimeError (f' { name } : server exited { server . returncode } ' ) 88try : 89data = get ('/health' ) 90if data .get ('status' )in ['ok' ,'healthy' ,'ready' ]: 91 (a .out / (name + '-health.json' )).write_text (json .dumps (data ,indent = 2 ));event ('server-ready' );return cfg 92except (OSError ,ValueError ):pass 93time .sleep (2 ) 94raise TimeoutError (name + ' startup' ) 95 96def run (label ,script ,args ,timeout = 7200 ,extra = None ,allowed = (0 ,)): 97cmd = [sys .executable ,str (script ),* map (str ,args )];event ('command' ,label = label ,command = cmd ) 98with (a .out / (label + '.log' )).open ('w' )as f : 99p = subprocess .Popen (cmd ,cwd = ROOT ,env = {** base_env ,** (extra or {})},stdout = f ,stderr = subprocess .STDOUT ,start_new_session = True ) 100try :rc = p .wait (timeout = timeout ) 101except subprocess .TimeoutExpired :group_stop (p );rc = 124 102except BaseException : 103group_stop (p ) 104raise 105finally :group_stop (p ) 106event ('result' ,label = label ,returncode = rc ) 107if rc not in allowed :raise RuntimeError (f' { label } failed: { rc } ' ) 108return rc 109 110def telemetry (): 111with (a .out / 'telemetry.jsonl' ).open ('w' )as f : 112while not stop_event .is_set (): 113mem = {line .split (':' )[0 ]:int (line .split ()[1 ])* 1024 for line in pathlib .Path ('/proc/meminfo' ).read_text ().splitlines ()if ':' in line and line .split ()[1 ].isdigit ()} 114gpu = {} 115for d in pathlib .Path ('/sys/class/drm' ).glob ('card*/device' ): 116for key in ['mem_info_gtt_used' ,'mem_info_vram_used' ,'gpu_busy_percent' ]: 117p = d / key 118if p .exists ():gpu [str (d .parent .name )+ '/' + key ]= int (p .read_text ().strip ()) 119row = dict (timestamp = time .time (),phase = phase ,MemAvailable = mem ['MemAvailable' ],SwapFree = mem ['SwapFree' ],gpu = gpu ) 120f .write (json .dumps (row )+ '\n' );f .flush ();stop_event .wait (2 ) 121 122thread = threading .Thread (target = telemetry ,daemon = True );thread .start () 123def interrupted (signum ,frame ):raise KeyboardInterrupt 124signal .signal (signal .SIGTERM ,interrupted ) 125try : 126# Cold process, speed repeats in the same order/state as the public P40 study. 127start ('default-32k' ,32768 ) 128shared = ['--engine' ,'openai' ,'--base' ,url ,'--model' ,'strata' ,'--arm' ,'evo-x2-ud-iq4xs' ,'--think' ,'off' ,'--out' ,str (a .out / 'quality' )] 129run ('p40-speed' ,HERE / 'quality.py' ,shared + ['--suite' ,'speed' ,'--reps' ,'3' ]) 130run ('quality-69x2' ,HERE / 'quality.py' ,shared + ['--suite' ,'reasoning,code,tools,complete,longctx' ,'--reps' ,'2' ]) 131# Same public tokenizer-counted 4K/32K/128K workload in both arms, each with its own warmup. 132public = ROOT / 'bench/results/2026-10-04-community-v100-16gb-ram/benchmark.py' 133for fast in [False ,True ]: 134name = 'fast-long' if fast else 'default-long' ;start (name ,131072 ,fast = fast ) 135run (name + '-speed' ,public ,['--root' ,ROOT ,'--pack' ,a .model / 'pack' ,'--url' ,url ,'--out' ,a .out / name ,'--runs' ,'3' ]) 136start ('default-262k' ,262144 ) 137run ('needle' ,HERE / 'needle.py' ,['--url' ,url ,'--lengths' ,'32k,128k,262k' ,'--depths' ,'10,50,90' ,'--out' ,a .out / 'needles.json' ],extra = {'NEEDLE_REQUEST_DIR' :str (a .out / 'needle-requests' )},allowed = (0 ,1 )) 138# '262k' means 262*1024; the official script skips it at a 262144-token native limit. 139# 256k names that native limit correctly, without changing the script's length/depth construction. 140run ('needle-native' ,HERE / 'needle.py' ,['--url' ,url ,'--lengths' ,'256k' ,'--depths' ,'10,50,90' ,'--out' ,a .out / 'needles-native.json' ],extra = {'NEEDLE_REQUEST_DIR' :str (a .out / 'needle-native-requests' )},allowed = (0 ,1 )) 141stop_server ();phase = 'batch-exact' 142cfg = config ('batch-exact' ,131072 ,parallel = 1 ,borrow = False ) 143run ('batch-exact' ,ROOT / 'tools/batch_test.py' ,['--exe' ,a .build / 'strata' ,'--config' ,cfg ,'--batch' ,'2' ,'--n' ,'2' ,'--max-new' ,'150' ,'--dump' ,a .out / 'batch-exact.json' ,'--extra' ,'--pcie-frac 0 --adapt-every 1000000 --no-prefill-borrow' ],timeout = 1200 ,extra = {'BATCH_TEST_LOG' :str (a .out / 'batch-exact-engine.log' ),'STRATA_QFUSE' :'1' },allowed = (0 ,2 ,124 )) 144# All four cells retained. QFUSE off is diagnostic, never silently made the baseline. 145for qfuse in [1 ,0 ]: 146for borrow in [True ,False ]: 147name = f'parallel-qfuse { qfuse } -borrow { int ( borrow ) } ' ;start (name ,131072 ,parallel = 2 ,borrow = borrow ,qfuse = qfuse ) 148run (name ,HERE / 'parallel.py' ,['--pack' ,a .model / 'pack' ,'--url' ,url ,'--out' ,a .out / name ],timeout = 750 ,allowed = (0 ,1 ,124 )) 149event ('all-measurements-complete' ) 150finally : 151stop_event .set ();thread .join (timeout = 5 );stop_server ()