okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
6.7 KiB137 linesraw
1"""One fresh prompt and one cached continuation; restart the server between invocations.
2
3Use the same engine/config with STRATA_SCORES_THREAD=0 or 1 at server startup.
4Model loading is excluded. This measures request latency, not streaming TTFT or coding quality.
5"""
6import argparse
7import gzip
8import hashlib
9import importlib.util
10import json
11import os
12from pathlib import Path
13import time
14import urllib.error
15import urllib.request
16
17HERE = Path(__file__).resolve().parent
18REPO = HERE.parents[2]
19
20
21def digest(data):
22    return hashlib.sha256(data).hexdigest()
23
24
25def load_tokenizer(folder):
26    spec = importlib.util.spec_from_file_location('qsa_bench_tokenizer', REPO / 'tools/strata_tokenizer.py')
27    module = importlib.util.module_from_spec(spec)
28    spec.loader.exec_module(module)
29    vocab = json.loads((folder / 'vocab.json').read_text())
30    tokens = [None] * len(vocab)
31    for token, index in vocab.items():
32        tokens[index] = token
33    return module.Tokenizer(tokens, (folder / 'merges.txt').read_text().split('\n'),
34                            json.loads((folder / 'token_type.json').read_text()))
35
36
37def make_requests(tokenizer, source, length, model, follow_tokens):
38    ids = tokenizer.encode(source)
39    if not ids or not 0 <= follow_tokens <= len(ids):
40        raise ValueError('Empty source or invalid continuation size')
41    text = tokenizer.decode((ids * (length // len(ids) + 1))[:length - 128])
42    body = dict(model=model, temperature=0, top_p=1, top_k=1, seed=6300,
43                reasoning_effort='none', max_tokens=1, messages=[
44        dict(role='system', content='You are a precise coding assistant.'),
45        dict(role='user', content=text + '\nReview the numerical implementation and synchronization in detail.')])
46    follow = json.loads(json.dumps(body))
47    follow['messages'].extend([
48        dict(role='assistant', content='I will inspect the numerical implementation.'),
49        dict(role='user', content='Continue with a detailed review of synchronization and memory lifetime.')])
50    if follow_tokens:
51        follow['messages'][-1]['content'] += '\nADDITIONAL_SOURCE\n' + tokenizer.decode(ids[-follow_tokens:])
52    return [('fresh-' + str(length), body), ('follow-' + str(length), follow)]
53
54
55def fetch(url, body=None):
56    headers = {'Content-Type': 'application/json'}
57    key = os.environ.get('STRATA_API_KEY')
58    if key:
59        headers['Authorization'] = 'Bearer ' + key
60    req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
61                                 headers=headers)
62    with urllib.request.urlopen(req, timeout=900) as response:
63        return json.load(response)
64
65
66def main():
67    parser = argparse.ArgumentParser(description=__doc__)
68    parser.add_argument('--url', default='http://127.0.0.1:8080')
69    parser.add_argument('--tokenizer', type=Path, required=True)
70    parser.add_argument('--model', default='strata-qwen38-iq3s-uncensored')
71    parser.add_argument('--length', type=int, choices=[131072, 240000], required=True)
72    parser.add_argument('--follow-tokens', type=int, default=2048)
73    parser.add_argument('--source', type=Path, default=HERE / 'prompt-source.txt.gz')
74    parser.add_argument('--variant', choices=['off', 'on'], required=True)
75    parser.add_argument('--output', type=Path, required=True)
76    parser.add_argument('--prepare-only', action='store_true')
77    args = parser.parse_args()
78    source = gzip.decompress(args.source.read_bytes()) if args.source.suffix == '.gz' else args.source.read_bytes()
79    requests = make_requests(load_tokenizer(args.tokenizer), source.decode(), args.length,
80                             args.model, args.follow_tokens)
81    receipt = dict(variant=args.variant, length=args.length, output_cap=1, seed=6300,
82                   temperature=0, reasoning_effort='none', follow_source_tokens=args.follow_tokens,
83                   source_sha256=digest(source), script_sha256=digest(Path(__file__).read_bytes()),
84                   prepare_only=args.prepare_only, rows=[], status='prepared')
85    # Refuse to overwrite previous observations, including failed attempts.
86    with args.output.open('x') as output:
87        def save():
88            output.seek(0)
89            json.dump(receipt, output, indent=2)
90            output.write('\n')
91            output.truncate()
92            output.flush()
93        try:
94            save()
95            if args.prepare_only:
96                receipt['request_hashes'] = {case: digest(json.dumps(body).encode()) for case, body in requests}
97                save()
98                return
99            health = fetch(args.url.rstrip('/') + '/health')
100            if not health.get('loaded') or health.get('max_context') != 262144:
101                raise RuntimeError('Requires an already loaded 262144-context server')
102            for case, body in requests:
103                started = time.monotonic()
104                response = fetch(args.url.rstrip('/') + '/v1/chat/completions', body)
105                elapsed = time.monotonic() - started
106                metrics = fetch(args.url.rstrip('/') + '/metrics?requests=all')
107                native = max(metrics['requests'], key=lambda row: row['time'])
108                choice = response['choices'][0]
109                message = choice.get('message', {})
110                row = dict(case=case, seconds=elapsed, usage=response.get('usage'),
111                           finish_reason=choice['finish_reason'],
112                           request_sha256=digest(json.dumps(body).encode()),
113                           output_sha256=digest(((message.get('reasoning_content') or '') + '\n' +
114                                                 (message.get('content') or '')).encode()),
115                           native={k: native.get(k) for k in (
116                               'prompt_tokens', 'reused', 'prompt_read', 'output_tokens', 'engine_generated',
117                               'prompt_ms', 'decode_ms', 'drafts_offered', 'drafts_accepted',
118                               'hit_rate', 'ram_blobs', 'file_blobs', 'file_mb')})
119                receipt['rows'].append(row)
120                save()
121                if choice['finish_reason'] not in ('length', 'stop'):
122                    raise RuntimeError('Request did not complete normally')
123                if case.startswith('fresh-') and native.get('reused') != 0:
124                    raise RuntimeError('Fresh prompt reused a prefix: restart the server and use a NEW output file')
125            receipt['status'] = 'complete'
126            save()
127        except Exception as error:
128            receipt['status'] = 'failed'
129            receipt['error'] = str(error)
130            if isinstance(error, urllib.error.HTTPError):
131                receipt['http_status'] = error.code
132            save()
133            raise
134
135
136if __name__ == '__main__':
137    main()