okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
9.0 KiB151 linesraw
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():
31    return 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):
35    row=dict(timestamp=time.time(),phase=phase,event=kind,**fields);events.append(row)
36    with (a.out/'events.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
37    print(json.dumps(row),flush=True)
38
39def group_stop(p):
40    if p is None:return
41    try:os.killpg(p.pid,signal.SIGTERM)
42    except ProcessLookupError:return
43    try:p.wait(timeout=45)
44    except subprocess.TimeoutExpired:
45        os.killpg(p.pid,signal.SIGKILL);p.wait(timeout=15)
46
47def stop_server():
48    global server,server_log
49    group_stop(server);server=None
50    if 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.
52    deadline=time.monotonic()+60
53    while time.monotonic()<deadline:
54        alive=[]
55        for p in pathlib.Path('/sys/class/kfd/kfd/proc').glob('*'):
56            try:
57                cmd=(pathlib.Path('/proc')/p.name/'cmdline').read_bytes()
58                if str(a.build).encode() in cmd:alive.append(p.name)
59            except FileNotFoundError:continue
60        if not alive and gtt_bytes() <= initial_gtt + 512*1024**2:return
61        time.sleep(1)
62    raise RuntimeError('Strata GPU mappings/GTT were not released')
63
64def get(path):
65    with urllib.request.urlopen(url+path,timeout=10) as response:return json.load(response)
66
67def config(name,ctx,fast=False,parallel=1,borrow=True):
68    args=['--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']
69    if ctx>=65536:args+=['--kv-resident','32768']
70    if fast:args+=['--lookup-chain','3','--mtp-q4','all']
71    if not borrow:args+=['--no-prefill-borrow']
72    cfg=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)
73    path=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):
76    global server,server_log,phase
77    stop_server();phase=name
78    cfg=config(name,ctx,fast,parallel,borrow)
79    env={**base_env,**(FAST if fast else {})}
80    if 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))
82    server_log=(a.out/(name+'-server.log')).open('w')
83    server=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)
84    event('server-start',pid=server.pid,config=str(cfg))
85    deadline=time.monotonic()+600
86    while time.monotonic()<deadline:
87        if server.poll() is not None:raise RuntimeError(f'{name}: server exited {server.returncode}')
88        try:
89            data=get('/health')
90            if 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
92        except (OSError,ValueError):pass
93        time.sleep(2)
94    raise TimeoutError(name+' startup')
95
96def run(label,script,args,timeout=7200,extra=None,allowed=(0,)):
97    cmd=[sys.executable,str(script),*map(str,args)];event('command',label=label,command=cmd)
98    with (a.out/(label+'.log')).open('w') as f:
99        p=subprocess.Popen(cmd,cwd=ROOT,env={**base_env,**(extra or {})},stdout=f,stderr=subprocess.STDOUT,start_new_session=True)
100        try:rc=p.wait(timeout=timeout)
101        except subprocess.TimeoutExpired:group_stop(p);rc=124
102        except BaseException:
103            group_stop(p)
104            raise
105        finally:group_stop(p)
106    event('result',label=label,returncode=rc)
107    if rc not in allowed:raise RuntimeError(f'{label} failed: {rc}')
108    return rc
109
110def telemetry():
111    with (a.out/'telemetry.jsonl').open('w') as f:
112        while not stop_event.is_set():
113            mem={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()}
114            gpu={}
115            for d in pathlib.Path('/sys/class/drm').glob('card*/device'):
116                for key in ['mem_info_gtt_used','mem_info_vram_used','gpu_busy_percent']:
117                    p=d/key
118                    if p.exists():gpu[str(d.parent.name)+'/'+key]=int(p.read_text().strip())
119            row=dict(timestamp=time.time(),phase=phase,MemAvailable=mem['MemAvailable'],SwapFree=mem['SwapFree'],gpu=gpu)
120            f.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.
127    start('default-32k',32768)
128    shared=['--engine','openai','--base',url,'--model','strata','--arm','evo-x2-ud-iq4xs','--think','off','--out',str(a.out/'quality')]
129    run('p40-speed',HERE/'quality.py',shared+['--suite','speed','--reps','3'])
130    run('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.
132    public=ROOT/'bench/results/2026-10-04-community-v100-16gb-ram/benchmark.py'
133    for fast in [False,True]:
134        name='fast-long' if fast else 'default-long';start(name,131072,fast=fast)
135        run(name+'-speed',public,['--root',ROOT,'--pack',a.model/'pack','--url',url,'--out',a.out/name,'--runs','3'])
136    start('default-262k',262144)
137    run('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.
140    run('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))
141    stop_server();phase='batch-exact'
142    cfg=config('batch-exact',131072,parallel=1,borrow=False)
143    run('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.
145    for qfuse in [1,0]:
146        for borrow in [True,False]:
147            name=f'parallel-qfuse{qfuse}-borrow{int(borrow)}';start(name,131072,parallel=2,borrow=borrow,qfuse=qfuse)
148            run(name,HERE/'parallel.py',['--pack',a.model/'pack','--url',url,'--out',a.out/name],timeout=750,allowed=(0,1,124))
149    event('all-measurements-complete')
150finally:
151    stop_event.set();thread.join(timeout=5);stop_server()