okami.mom/strata

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

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

main
6.1 KiB114 linesraw
1"""Fresh ordinary-RoPE / YaRN retrieval using an unmodified Strata executable.
2
3Run from a configured Strata checkout, using its Python environment:
4python bench/results/2026-10-09-rope-yarn-long-context/probe.py \
5  --config strata.json --exe build/strata --tokens 1048576 --rope yarn --output /new/run
6Each invocation starts and closes an isolated engine. No server or saved cache.
7"""
8import argparse
9import hashlib
10import json
11import re
12import subprocess
13import sys
14import threading
15import time
16from pathlib import Path
17
18ROOT=Path(__file__).resolve().parents[3]
19sys.path[:0]=[str(ROOT),str(ROOT/'tools')]
20from serve.server import StrataEngine,child_env
21from serve.frontend import ChatTemplate
22import strata_tokenizer as ST
23
24
25def main():
26    p=argparse.ArgumentParser(description=__doc__)
27    p.add_argument('--config',required=True,type=Path)
28    p.add_argument('--exe',required=True,type=Path)
29    p.add_argument('--output',required=True,type=Path)
30    p.add_argument('--tokens',required=True,type=int)
31    p.add_argument('--rope',required=True,choices=('none','yarn'))
32    p.add_argument('--capacity',type=int,default=1048832)
33    a=p.parse_args()
34    if a.tokens+256>a.capacity:p.error('leave 256 tokens of capacity for output/internal headroom')
35    a.output.mkdir(parents=True,exist_ok=False)
36    cfg=json.loads(a.config.read_text());tp=Path(cfg['tokenizer'])
37    vocab=json.loads((tp/'vocab.json').read_text());v=[None]*len(vocab)
38    for text,i in vocab.items():v[i]=text
39    tok=ST.Tokenizer(v,(tp/'merges.txt').read_text().split('\n'),json.loads((tp/'token_type.json').read_text()))
40    template=ChatTemplate(tp/'chat_template.jinja')
41    def prompt(n):
42        content=('The first code is CEDAR-731.\n'+' apple'*(n//2)+
43                 '\nThe middle code is MARBLE-482.\n'+' orange'*(n-n//2)+
44                 '\nThe last code is QUARTZ-956.\nReturn all three codes in order separated by |. Nothing else.')
45        return tok.encode(template.render([{'role':'user','content':content}],tools=None,enable_thinking=False),parse_special=True)
46    lo,hi=0,a.tokens
47    while lo<hi:
48        mid=(lo+hi+1)//2
49        if len(prompt(mid))<=a.tokens:lo=mid
50        else:hi=mid-1
51    ids=prompt(lo)
52    assert len(ids)==a.tokens
53    token_json=json.dumps(ids)
54    (a.output/'tokens.json').write_text(token_json)
55    args=[];raw=cfg['args'];i=0
56    replace={'--max-context','--kv','--kv-resident','--mtp','--spec','--conversation-cache-mib','--rope-scaling',
57             '--rope-scale','--rope-freq-scale','--yarn-orig-ctx','--prefill','--suffix-draft'}
58    while i<len(raw):
59        if raw[i] in replace:i+=2
60        else:args.append(raw[i]);i+=1
61    args+=['--kv','fp16','--spec','2','--suffix-draft','0','--conversation-cache-mib','0',
62           '--prefill','8192','--max-context',str(a.capacity),'--rope-scaling',a.rope]
63    if a.rope=='yarn':args+=['--rope-scale','4','--yarn-orig-ctx','262144']
64    env=child_env(cfg);env['STRATA_PREFILL_CPU_SHARE']='0'
65    for key in ('STRATA_LOGPOS','STRATA_MIGRATION_LOGITS','STRATA_MIGRATION_LOGITS_FROM'):env.pop(key,None)
66    result=dict(input_tokens=len(ids),input_sha256=hashlib.sha256(token_json.encode()).hexdigest(),
67                rope=a.rope,capacity=a.capacity,argv=args,expected='CEDAR-731|MARBLE-482|QUARTZ-956',
68                executable_sha256=hashlib.sha256(a.exe.read_bytes()).hexdigest(),samples_per_condition=1)
69    engine=None;samples=[];stop=threading.Event()
70    def monitor():
71        while not stop.is_set():
72            sample={'time':time.time()}
73            try:
74                if engine and engine.proc:
75                    for line in Path('/proc',str(engine.proc.pid),'status').read_text().splitlines():
76                        if line.startswith(('VmHWM:','VmRSS:','VmSwap:')):
77                            key,_,value=line.partition(':');sample[key+'_kib']=int(value.split()[0])
78                gpu=subprocess.check_output(['nvidia-smi','--query-gpu=memory.used,utilization.gpu','--format=csv,noheader,nounits'],text=True,timeout=3).strip().split(',')
79                sample['gpu_mib']=int(gpu[0]);sample['gpu_utilization']=int(gpu[1])
80            except Exception as exc:sample['monitor_error']=str(exc)
81            samples.append(sample);stop.wait(1)
82    worker=threading.Thread(target=monitor,daemon=True);worker.start()
83    try:
84        start=time.perf_counter()
85        engine=StrataEngine(str(a.exe.resolve()),args,cwd=str(ROOT),log=str(a.output/'engine.log'),env=env)
86        result['startup_s']=time.perf_counter()-start
87        first=None;out=[];start=time.perf_counter()
88        for token in engine.generate(ids,64,{'temperature':0},threading.Event()):
89            if token is not None:
90                if first is None:first=time.perf_counter()
91                out.append(token)
92        result.update(ttft_s=first-start if first else None,total_request_s=time.perf_counter()-start,
93                      output_tokens=len(out),answer=tok.decode(out).replace('<|im_end|>',''),reused_tokens=engine.reused)
94        result['correct_code_pairs']=sum(x==y for x,y in zip(result['expected'].split('|'),result['answer'].split('|')))
95        result['complete']=True
96    except Exception as exc:
97        result.update(complete=False,error=repr(exc))
98        raise
99    finally:
100        if engine:engine.close()
101        stop.set();worker.join(timeout=5)
102        result['peak_gpu_gib']=max((s.get('gpu_mib',0) for s in samples),default=0)/1024
103        result['peak_engine_rss_gib']=max((s.get('VmHWM_kib',0) for s in samples),default=0)/1048576
104        log=a.output/'engine.log'
105        if log.exists():
106            matches=re.findall(r'prompt (\d+) tokens = (\d+) reused \+ (\d+) read in ([\d.]+) ms \(([\d.]+) tok/s\), (\d+) generated in ([\d.]+) ms \(([\d.]+) tok/s\)',log.read_text(errors='replace'))
107            if matches:
108                m=matches[-1];result.update(native_prompt_tokens=int(m[0]),native_reused_tokens=int(m[1]),prefill_s=float(m[3])/1000,prefill_tps=float(m[4]),decode_tps=float(m[7]))
109        (a.output/'resources.json').write_text(json.dumps(samples,indent=2))
110        (a.output/'results.json').write_text(json.dumps(result,indent=2))
111        print(json.dumps({k:v for k,v in result.items() if k!='argv'}),flush=True)
112
113
114if __name__=='__main__':main()