okami.mom/strata

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

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

main
4.3 KiB80 linesraw
1#!/usr/bin/env python3
2"""Two simultaneous, distinct ~19.6K prompts for issue #1356 (not its unpublished original prompts).
3
4Reuse the public V100 report's synthetic-Python filler/template and sampling.
5Save exact requests, partial SSE, usage, elapsed time and server metrics.
6"""
7import argparse
8import concurrent.futures
9import json
10import pathlib
11import sys
12import time
13import urllib.request
14
15ROOT = pathlib.Path(__file__).resolve().parents[4]
16sys.path[:0] = [str(ROOT), str(ROOT/'tools')]
17from strata_tokenizer import Tokenizer
18from serve.frontend import ChatTemplate, openai_to_messages
19
20
21def main():
22    ap = argparse.ArgumentParser()
23    ap.add_argument('--pack', type=pathlib.Path, required=True)
24    ap.add_argument('--url', required=True)
25    ap.add_argument('--out', type=pathlib.Path, required=True)
26    a = ap.parse_args()
27    a.out.mkdir(parents=True, exist_ok=True)
28    d=a.pack/'tokenizer'; vocab=json.loads((d/'vocab.json').read_text())
29    tokens=[None]*len(vocab)
30    for token, number in vocab.items(): tokens[number]=token
31    tok=Tokenizer(tokens,(d/'merges.txt').read_text().splitlines(),json.loads((d/'token_type.json').read_text()))
32    template=ChatTemplate(d/'chat_template.jinja')
33    filler='\n'.join(f'def task_{i:05d}(value: int) -> int: return (value * {(i%97)+1} + {i}) % 100003' for i in range(12000))
34    ending='\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.'
35    def payload(text):
36        return dict(model='strata',messages=[dict(role='user',content=text)],temperature=0,
37                    reasoning_effort='none',max_tokens=256,stream=True,stream_options=dict(include_usage=True))
38    requests=[]
39    for n in range(2):
40        prefix=f'Benchmark nonce: parallel-1356-trial-{n}.\nReview this synthetic Python module:\n'
41        lo,hi=0,len(filler)
42        def count(body):
43            m,t,k=openai_to_messages(body);return len(tok.encode(template.render(m,t,**k),parse_special=True))
44        while lo<hi:
45            mid=(lo+hi+1)//2
46            if count(payload(prefix+filler[:mid]+ending))<=19600:lo=mid
47            else:hi=mid-1
48        body=payload(prefix+filler[:lo]+ending); requests.append(body)
49        (a.out/f'request-{n}.json').write_text(json.dumps(body))
50        (a.out/f'count-{n}.json').write_text(json.dumps({'prompt_tokens':count(body)}))
51    import threading
52    barrier=threading.Barrier(2)
53    def ask(n):
54        chunks=[];row={'slot':n};barrier.wait();start=time.monotonic()
55        try:
56            req=urllib.request.Request(a.url+'/v1/chat/completions',data=json.dumps(requests[n]).encode(),headers={'Content-Type':'application/json'})
57            with urllib.request.urlopen(req,timeout=600) as response, (a.out/f'sse-{n}.jsonl').open('w') as f:
58                for line in response:
59                    if not line.startswith(b'data:'):continue
60                    data=line[5:].strip()
61                    if data==b'[DONE]':break
62                    chunk=json.loads(data);chunks.append(chunk);f.write(json.dumps(chunk)+'\n');f.flush()
63                    if 'first_token_s' not in row and any(c.get('delta',{}).get('content') for c in chunk.get('choices',[])):
64                        row['first_token_s']=time.monotonic()-start
65            row['text']=''.join(c.get('delta',{}).get('content') or '' for ch in chunks for c in ch.get('choices',[]))
66            row['usage']=next((ch['usage'] for ch in reversed(chunks) if ch.get('usage')),None)
67            row['finish_reason']=next((c['finish_reason'] for ch in reversed(chunks) for c in ch.get('choices',[]) if c.get('finish_reason')),None)
68        except Exception as ex:
69            row['error']=f'{type(ex).__name__}: {ex}'
70        row['elapsed_s']=time.monotonic()-start
71        (a.out/f'result-{n}.json').write_text(json.dumps(row,indent=2))
72        print(json.dumps(row),flush=True)
73        return row
74    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex: rows=list(ex.map(ask,range(2)))
75    with urllib.request.urlopen(a.url+'/metrics',timeout=10) as response:metrics=json.load(response)
76    (a.out/'metrics.json').write_text(json.dumps(metrics,indent=2))
77    return int(any(r.get('error') or not r.get('text') for r in rows))
78
79
80if __name__=='__main__':sys.exit(main())