okami.mom/strata

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

Niko1221Merge the AMD HIP backend (PR #121 by Konstantinos Korres, rebased onto 0.1.24) and its setup support36ef9d6e6

main
3.8 KiB75 linesraw
1#!/usr/bin/env python3
2"""Matched fresh/follow-up prefill probe against an otherwise idle local Strata server.
3
4Does not start/stop services. Use a dedicated server and its engine log, restart
5between build/configuration arms, and keep model/template/settings identical.
6"""
7import argparse
8import json
9import os
10from pathlib import Path
11import re
12import time
13import urllib.request
14
15PATTERN = re.compile(r'prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([0-9.]+) tok/s\), (\d+) generated in (\d+) ms \(([0-9.]+) tok/s\)')
16FIELDS = ('prompt_tokens', 'reused', 'fresh', 'prefill_ms', 'prefill_tps', 'generated', 'decode_ms', 'decode_tps')
17
18
19def main():
20    p = argparse.ArgumentParser(description=__doc__)
21    p.add_argument('--url', default='http://127.0.0.1:8080')
22    p.add_argument('--model', required=True)
23    p.add_argument('--engine-log', type=Path, required=True)
24    p.add_argument('--output', type=Path, required=True)
25    p.add_argument('--label', required=True)
26    args = p.parse_args()
27    results = []
28
29    def request(messages, kind, trial):
30        offset = args.engine_log.stat().st_size
31        body = dict(model=args.model, messages=messages, max_tokens=128,
32                    temperature=0, top_k=1, top_p=1, min_p=0, seed=42,
33                    reasoning_effort='none')
34        headers = {'Content-Type': 'application/json'}
35        if os.environ.get('STRATA_API_KEY'):
36            headers['Authorization'] = 'Bearer ' + os.environ['STRATA_API_KEY']
37        req = urllib.request.Request(args.url.rstrip('/') + '/v1/chat/completions',
38                                     data=json.dumps(body).encode(), headers=headers)
39        start = time.monotonic()
40        with urllib.request.urlopen(req, timeout=360) as response:
41            data = json.load(response)
42        elapsed = time.monotonic() - start
43        # The API response may arrive just before stderr's completion line is flushed.
44        deadline = time.monotonic() + 2
45        while True:
46            with args.engine_log.open('rb') as log:
47                log.seek(offset)
48                matches = PATTERN.findall(log.read().decode(errors='replace'))
49            if matches or time.monotonic() >= deadline:
50                break
51            time.sleep(0.02)
52        if len(matches) != 1:
53            raise RuntimeError('Expected exactly one completed engine timing line; check idle server and log path')
54        metrics = dict(zip(FIELDS, map(float, matches[0])))
55        if kind == 'fresh' and metrics['reused'] != 0:
56            raise RuntimeError('Fresh prompt reused cached tokens; restart this arm before comparison')
57        choice = data['choices'][0]
58        results.append(dict(label=args.label, kind=kind, trial=trial, wall_s=elapsed,
59                            metrics=metrics, usage=data.get('usage'),
60                            finish_reason=choice.get('finish_reason'), message=choice['message']))
61        args.output.write_text(json.dumps(results, indent=2) + '\n')
62        print(json.dumps(results[-1]), flush=True)
63        return choice['message']
64
65    request([{'role': 'user', 'content': 'Reply READY.'}], 'warmup', 0)
66    for trial, n in enumerate((140, 280, 140, 280), 1):
67        code = '\n'.join(f'export function rule{i}(x) {{ return x === {i} ? x + {i+1} : x - {i}; }}' for i in range(n))
68        messages = [{'role': 'user', 'content': f'CASE {trial}: Review this source and describe its behavior precisely in a paragraph.\n' + code}]
69        reply = request(messages, 'fresh', trial)
70        messages += [reply, {'role': 'user', 'content': 'Explain the most relevant boundary case and the smallest useful regression test. ' + 'Focus on integer equality, zero, negative input, unexpected types, and caller assumptions. ' * 5}]
71        request(messages, 'followup', trial)
72
73
74if __name__ == '__main__':
75    main()