okami.mom/strata

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

Niko1221bench: community report, Intel Arc Pro B65 32 GB (SYCL), IQ2_XS (PR #955)98d1c8d4f

main
7.9 KiB131 linesraw
1#!/usr/bin/env python3
2"""Three fresh benchy-fixture runs; content lives only in RAM and process memory."""
3import argparse, hashlib, importlib.util, json, os, re, signal, sys, threading, time
4from pathlib import Path
5
6R = Path(__file__).resolve().parent
7
8def digest(x):
9    return hashlib.sha256(json.dumps(x).encode()).hexdigest()
10
11def main():
12    ap = argparse.ArgumentParser()
13    ap.add_argument('--source',type=Path,required=True)
14    ap.add_argument('--profile',type=Path,required=True)
15    ap.add_argument('--ram',type=Path,required=True)
16    ap.add_argument('--out',type=Path,required=True)
17    a = ap.parse_args()
18    ram=a.ram;out=a.out;SOURCE=a.source
19    assert str(ram.resolve()).startswith('/run/') and ram.is_dir()
20    out.mkdir(parents=True,exist_ok=False)
21    sys.path[:0] = [str(SOURCE), str(SOURCE / 'tools')]
22    from serve.server import StrataEngine, ENGINE_REQUEST
23    from serve.frontend import ChatTemplate
24    from strata_tokenizer import Tokenizer
25    cfg=json.loads(a.profile.read_text())
26    cfg['exe']=os.path.expandvars(cfg['exe']);cfg['cwd']=os.path.expandvars(cfg['cwd'])
27    cfg['args']=[os.path.expandvars(x) for x in cfg['args']]
28    tok = Tokenizer.from_gguf(Path(cfg['args'][cfg['args'].index('--native') + 1]))
29    tpl = ChatTemplate(Path(cfg['args'][cfg['args'].index('--pack') + 1]) / 'tokenizer/chat_template.jinja')
30    public = [int(x) for x in (R / 'benchy-long.ids').read_text().strip().split(',')]
31    assert len(public) == 2185
32    canary = tok.encode(tpl.render([{'role':'user','content':'Reply only with CANARY_MAPLE_73.'}], enable_thinking=False), parse_special=True)
33    env = dict(os.environ); env['STRATA_TRACE']='1'; assert 'STRATA_DBG_NAN' not in env
34    short=[int(x) for x in (R/'benchy-short.ids').read_text().strip().split(',')]; assert len(short)==20
35    class Engine(StrataEngine):
36        def _parse_done(self, line):
37            self.done_line = line
38            return super()._parse_done(line)
39    cancel = threading.Event()
40    signal.signal(signal.SIGTERM, lambda *_: cancel.set())
41    signal.signal(signal.SIGINT, lambda *_: cancel.set())
42    engine = None; rows = []; failure = None; life = {}
43    streams = {}
44    log = ram / 'native.log'
45    def save():
46        (out / 'requests.json').write_text(json.dumps(rows, indent=2)+'\n')
47        (out / 'lifecycle.json').write_text(json.dumps(life, indent=2)+'\n')
48    def io():
49        return {k:int(v) for k,v in (x.split(':',1) for x in Path(f'/proc/{engine.proc.pid}/io').read_text().splitlines())}
50    def ask(ids, cap, label, expected=None):
51        assert not cancel.is_set()
52        offset = log.stat().st_size; before = io(); engine.done_line = None
53        arrivals = []; output = []; start = time.monotonic()
54        for t in engine.generate(ids, cap, {'temperature':0.,'seed':17}, cancel):
55            if t is not None: arrivals.append(time.monotonic()); output.append(t)
56        elapsed = time.monotonic()-start; after=io(); n=dict(engine.last)
57        text = tok.decode(output).replace('<|im_end|>','').replace('<|endoftext|>','').strip()
58        assert engine.done_line and n['generated']==len(output) and n['prompt_tokens']==len(ids)
59        assert n['prompt_read']==len(ids) and n['reused']==0 and output and not cancel.is_set()
60        if expected: assert text==expected
61        with log.open() as f: f.seek(offset); raw=f.read()
62        assert not re.search(r'\b[1-9]\d* (?:of \d+ logits )?non-finite\b|\bnonfinite [1-9]\d*',raw)
63        allowed = [x for x in raw.splitlines() if ENGINE_REQUEST.search(x) or
64                   re.match(r'^strata (?:trace: (?:read \d|lent \d|refilled \d|prompt chunk)|prefill timing:|prefill timing \(|serve: prompt|generate: prompt)',x)]
65        row={'label':label,'input_tokens':len(ids),'output_cap':cap,'output_tokens':len(output),
66             'input_ids_sha256':digest(ids),'output_ids_sha256':digest(output),'native':n,
67             'native_done_line':engine.done_line,'prompt_tps':len(ids)*1000/n['prompt_ms'],
68             'decode_tps':len(output)*1000/n['decode_ms'],'ttft_s':arrivals[0]-start,
69             'total_s':elapsed,'process_io_delta':{k:after[k]-before[k] for k in before},
70             'numeric_trace':allowed,'valid':True}
71        prefixes={}
72        for k in (64,128,256,512,640):
73            if len(output)>=k:
74                prefixes[str(k)]={'ids_sha256':digest(output[:k]),'post_first_tps':None if k<2 else (k-1)/(arrivals[k-1]-arrivals[0]),'after_prompt_elapsed_ms':(arrivals[k-1]-start)*1000-n['prompt_ms']}
75        row['prefixes']=prefixes
76        if label.startswith('public2185'):
77            if 'public2185' in streams:
78                row['matches_previous_prefix']=streams['public2185']==output[:len(streams['public2185'])]
79                assert row['matches_previous_prefix']
80            else: streams['public2185']=output
81        row['target']=label.rsplit('-r',1)[0]
82        if row['target'].startswith('public'):
83            ref=json.loads((R/'reference-public-hashes.json').read_text())[row['target']]
84            row['matches_prior_qualified_ids']=row['output_ids_sha256']==ref
85            assert row['matches_prior_qualified_ids'] and row['output_tokens']==256
86        for prior in rows:
87            if prior.get('target')==row['target']:
88                assert prior['output_ids_sha256']==row['output_ids_sha256']
89                row['matches_previous_repeat']=True
90        rows.append(row);save()
91        print(json.dumps({k:row[k] for k in ['label','input_tokens','output_tokens','prompt_tps','ttft_s','total_s']}),flush=True)
92    try:
93        life={'mode':'qualified-native-serving','binary_sha256':hashlib.file_digest(Path(cfg['exe']).open('rb'),'sha256').hexdigest(),
94              'args':cfg['args'],'diagnostic_env':{k:env[k] for k in ['STRATA_TRACE','STRATA_STAGER_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']},
95              'intermediate_tensor_diagnostic':env.get('STRATA_DBG_NAN'), 'instrumented':False}
96        life['launches']=[]
97        for rep in range(1,4):
98            assert not cancel.is_set();streams.clear()
99            log=ram/('native-'+str(rep)+'.log')
100            start=time.monotonic()
101            engine=Engine(cfg['exe'],cfg['args'],cwd=cfg['cwd'],log=str(log),env=env)
102            launch={'repeat':rep,'startup_ready_s':time.monotonic()-start,'info':engine.info}
103            life['launches'].append(launch);save()
104            ask(public,256,'public2185-256-r'+str(rep))
105            ask(short,256,'public20-256-r'+str(rep))
106            ask(canary,64,'canary-end-r'+str(rep),'CANARY_MAPLE_73')
107            p=engine.proc;start=time.monotonic();p.stdin.write('QUIT\n');p.stdin.flush();p.wait(timeout=75)
108            launch.update(native_exit=p.returncode,quit_exit_s=time.monotonic()-start);assert p.returncode==0
109            engine.close();engine=None
110            for _ in range(5):time.sleep(1);assert not cancel.is_set()
111            raw=log.read_text()
112            launch['startup_geometry']=[x for x in raw.splitlines() if re.match(r'^strata (?:generate|serve): (?:GPU \d+:|expert cache \d|\d+ of \d+ experts missing|\d+ MiB of VRAM free|prompt path|session is up)',x)]
113            save()
114        life['native_exit']=0
115    except BaseException as e:
116        failure={'type':type(e).__name__,'reason':str(e)}
117    finally:
118        if engine is not None:
119            try:
120                p=engine.proc;start=time.monotonic();p.stdin.write('QUIT\n');p.stdin.flush();p.wait(timeout=75)
121                life.update(native_exit=p.returncode,quit_exit_s=time.monotonic()-start)
122                assert p.returncode==0
123                engine.close();engine=None
124                for _ in range(5): time.sleep(1);assert not cancel.is_set()
125            except BaseException as e:
126                failure=failure or {'type':type(e).__name__,'reason':str(e)}
127        save()
128        (out/'result.json').write_text(json.dumps({'failure':failure,'requests':len(rows),'native_exit':life.get('native_exit'),'content_persisted':False},indent=2)+'\n')
129    if failure:raise SystemExit(1)
130
131if __name__=='__main__':main()