okami.mom/strata

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

Niko1221Merge f-141-fixb: Python, docs and bench fixes and portsef8071303

main
6.3 KiB122 linesraw
1#!/usr/bin/env python3
2"""Reproduce one recorded request fixture against an already-running Strata API."""
3import argparse
4import gzip
5import hashlib
6import json
7import os
8from pathlib import Path
9import time
10import urllib.request
11
12HERE = Path(__file__).resolve().parent
13
14
15def prompt_for(case, rep):
16    if case in ('coding', 'prose'):
17        prompts = json.loads((HERE / 'prompts.json').read_text())
18        name = 'agentcode' if case == 'coding' else 'longprose'
19        extra = (' Include all code, tests and detailed explanations with examples; write at least 3500 words.'
20                 if case == 'coding' else ' Write at least 3500 words of developed prose; keep the story moving.')
21        return f'[fn100-sustained-{name}-{rep}]\n' + prompts[name] + extra, 8192, 'medium', 1.0
22    name = 'full-window' if case == 'full' else 'depth-' + case[5:]
23    text = gzip.decompress((HERE / f'{name}-prompt.txt.gz').read_bytes()).decode()
24    return text, 504 if case == 'full' else 768, 'none', 0.0
25
26
27def measure(url, model, prompt, budget, thinking, temperature):
28    body = {'model': model, 'messages': [{'role': 'user', 'content': prompt}], 'max_tokens': budget,
29            'reasoning_effort': thinking, 'temperature': temperature, 'top_p': .95 if temperature else 1.0,
30            'top_k': 20 if temperature else 1, 'min_p': 0.0, 'presence_penalty': 0.0, 'seed': 314159,
31            'stream': True, 'stream_options': {'include_usage': True}}
32    headers = {'Content-Type': 'application/json'}
33    if os.environ.get('STRATA_BENCH_API_KEY'):
34        headers['Authorization'] = 'Bearer ' + os.environ['STRATA_BENCH_API_KEY']
35    request = urllib.request.Request(url.rstrip('/') + '/v1/chat/completions',
36                                     json.dumps(body).encode(), headers)
37    start = time.monotonic()
38    first = last = None
39    content, reasoning = [], []
40    timings = usage = finish = None
41    with urllib.request.urlopen(request, timeout=7200) as response:
42        for raw in response:
43            line = raw.decode().strip()
44            if not line.startswith('data:'):
45                continue
46            payload = line[5:].strip()
47            if payload == '[DONE]':
48                break
49            event = json.loads(payload)
50            if event.get('error'):
51                raise RuntimeError(event['error'])
52            timings = event.get('timings') or timings
53            usage = event.get('usage') or usage
54            for choice in event.get('choices') or []:
55                finish = choice.get('finish_reason') or finish
56                delta = choice.get('delta') or {}
57                visible, hidden = delta.get('content') or '', delta.get('reasoning_content') or ''
58                if visible or hidden:
59                    now = time.monotonic()
60                    first = now if first is None else first
61                    last = now
62                    content.append(visible)
63                    reasoning.append(hidden)
64    if not timings or timings.get('predicted_n', 0) <= 0:
65        raise RuntimeError('Missing successful engine generation timings')
66    row = {'measured_at': time.strftime('%Y-%m-%dT%H:%M:%S%z'), 'thinking': thinking,
67           'sampling': {k: body[k] for k in ('temperature', 'top_p', 'top_k', 'min_p', 'presence_penalty', 'seed')},
68           'max_tokens': budget, 'wall_s': time.monotonic() - start,
69           'ttft_s': first - start if first is not None else None,
70           'timings': timings, 'usage': usage, 'finish': finish,
71           'client_tg': (usage['completion_tokens'] - 1) / (last - first)
72                        if usage and first is not None and last > first else None}
73    return row, ''.join(reasoning) + '\n' + ''.join(content)
74
75
76def check_recorded():
77    records = json.loads((HERE / 'measurements.json').read_text())['arms']
78    coding = [r for r in records['q8il-combo-w15-s8'] if r['case'] == 'sustained-agentcode']
79    assert len(coding) == 3 and all(r['timings']['predicted_n'] == 8192 for r in coding)
80    assert sorted(r['timings']['predicted_per_second'] for r in coding) == [96.7, 97.0, 97.2]
81    for f, expected in json.loads((HERE / 'fixture-hashes.json').read_text()).items():
82        assert hashlib.sha256(gzip.decompress((HERE / f).read_bytes())).hexdigest() == expected
83    for r in json.loads((HERE / 'full-context.json').read_text()).values():
84        assert r['input_tokens'] + r['generated_tokens'] + r['api_reserved_tokens'] == 1048576
85        assert all(r['markers_found'].values()) and r['status'] == 'passed'
86    print('Recorded coding counts/rates, exact fixture hashes and full-context capacity checks passed.')
87
88
89def main():
90    parser = argparse.ArgumentParser(description=__doc__)
91    parser.add_argument('--url', default='http://127.0.0.1:8080')
92    parser.add_argument('--model', default='default-big')
93    parser.add_argument('--case', choices=['coding', 'prose', 'depth50000', 'depth130000', 'full'], default='coding')
94    parser.add_argument('--reps', type=int, default=1)
95    parser.add_argument('--out', type=Path, default=Path('new-measurements'))
96    parser.add_argument('--check-recorded', action='store_true')
97    args = parser.parse_args()
98    if args.check_recorded:
99        check_recorded()
100        return
101    if args.reps <= 0:
102        parser.error('--reps must be positive')
103    args.out.mkdir(parents=True, exist_ok=True)
104    for rep in range(1, args.reps + 1):
105        prompt, budget, thinking, temp = prompt_for(args.case, rep)
106        try:
107            row, text = measure(args.url, args.model, prompt, budget, thinking, temp)
108            row.update(case=args.case, rep=rep)
109            row['prompt_sha256'] = hashlib.sha256(prompt.encode()).hexdigest()
110            (args.out / f'{args.case}-{rep}.json').write_text(json.dumps(row, indent=2) + '\n')
111            (args.out / f'{args.case}-{rep}.txt').write_text(text)
112            print(args.case, rep, 'TG', row['timings']['predicted_per_second'],
113                  'PP', row['timings']['prompt_per_second'], 'counts', row['usage'])
114            if args.case not in ('coding', 'prose') and row['timings'].get('cache_n', 0):
115                raise RuntimeError('Prefix reuse: this request is not a cold PP comparison')
116        except Exception as error:
117            (args.out / f'{args.case}-{rep}-failure.json').write_text(json.dumps({'error': str(error)}, indent=2) + '\n')
118            raise
119
120
121if __name__ == '__main__':
122    main()