okami.mom/strata

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

Niko1221bench: community report, Intel Arc Pro B65 32 GB (SYCL), IQ2_XS (PR #955)98d1c8d4f

main
11.5 KiB218 linesraw
1#!/usr/bin/env python3
2"""Three fresh native runs; only numeric timing and hash receipts persist.
3
4Use under an independent GPU/resource guard, with the model router isolated.
5Run: python campaign.py --source SOURCE --profile profile.json --out OUTPUT
6RAM logs must live on tmpfs. No generated content is written by this script.
7"""
8import argparse
9import hashlib
10import json
11import os
12from pathlib import Path
13import re
14import signal
15import sys
16import threading
17import time
18
19TASKS = [
20 'Write a complete Python standard-library LRU cache module with expiry and locking, validation, iteration, detailed docstrings, demonstrations and boundary-case discussion. Write at least 1500 words of code and explanation.',
21 'Write a complete Python standard-library CSV import module with typed validation, error collection, transaction staging, provenance, test examples and extensive documentation. Write at least 1500 words of code and explanation.',
22 'Write a detailed story of at least 1500 words about a lighthouse keeper and marine biologist deciphering a research notebook. Develop their distinct voices, observations, uncertainty, and discoveries.',
23 'Explain accurate inventory audits, discrepancy investigation, provenance, reconciliation, and periodic checks in at least 1500 words with concrete examples and worked scenarios.',
24 'Act as an incident coordinator. Develop a detailed operational response plan for a failed local service: evidence collection, hypotheses, bounded tests, rollback, recovery verification and communication. Include worked scenarios and at least 1500 words.'
25]
26WARMUP = 'Write a detailed 1500-word guide to maintaining a community garden, with seasonal plans, worked examples and practical checklists.'
27FILLER = '\n'.join(f'Archive record {i}: shelf {i%17}, item {(i*37)%997}, status reviewed, source verified, date unknown. Preserve provenance and record uncertainty.' for i in range(900))
28
29def digest(value):
30    return hashlib.sha256(json.dumps(value).encode()).hexdigest()
31
32def main():
33    ap = argparse.ArgumentParser()
34    ap.add_argument('--source', type=Path, required=True)
35    ap.add_argument('--profile', type=Path, required=True)
36    ap.add_argument('--out', type=Path, required=True)
37    ap.add_argument('--ram', type=Path, default=Path(os.environ.get('STRATA_TEST_RAM', '/run/strata-community')))
38    ap.add_argument('--runs', type=int, default=3)
39    args = ap.parse_args()
40    assert 1 <= args.runs <= 3
41    assert str(args.ram.resolve()).startswith('/run/'), 'use a RAM-backed /run directory'
42    assert args.ram.is_dir()
43    args.out.mkdir(exist_ok=True)
44    assert not (args.out / 'requests.json').exists(), 'do not overwrite a consumed run'
45    sys.path[:0] = [str(args.source), str(args.source / 'tools')]
46    from serve.server import StrataEngine, ENGINE_REQUEST
47    from serve.frontend import ChatTemplate
48    from strata_tokenizer import Tokenizer
49
50    class MeasuredEngine(StrataEngine):
51        def _parse_done(self, line):
52            self.done_line = line
53            return super()._parse_done(line)
54
55    assert 'STRATA_DBG_NAN' not in os.environ, 'qualification diagnostic must be absent'
56    refs=json.loads((Path(__file__).parent/'reference-output-hashes.json').read_text())
57    profile = json.loads(args.profile.read_text())
58    native_args = [os.path.expandvars(x) for x in profile['args']]
59    binary = os.path.expandvars(profile['exe'])
60    cwd = os.path.expandvars(profile['cwd'])
61    tok = Tokenizer.from_gguf(Path(native_args[native_args.index('--native') + 1]))
62    tpl = ChatTemplate(Path(native_args[native_args.index('--pack') + 1]) / 'tokenizer/chat_template.jinja')
63    sampling = {'temperature': 0.0, 'seed': 17}
64    rows, runs = [], []
65    cancel = threading.Event()
66    interrupted = False
67    engine = None
68    failure = None
69
70    def stop(*_):
71        nonlocal interrupted
72        interrupted = True
73        cancel.set()
74
75    signal.signal(signal.SIGTERM, stop)
76    signal.signal(signal.SIGINT, stop)
77
78    def save():
79        for name, data in [('requests', rows), ('runs', runs)]:
80            (args.out / (name + '.json')).write_text(json.dumps(data, indent=2) + '\n')
81
82    def shaped(task, target):
83        rendered = tpl.render([
84            {'role': 'system', 'content': 'Follow the requested format and provide a thorough answer.'},
85            {'role': 'user', 'content': 'PAD_MARKER\n' + task}
86        ], enable_thinking=False)
87        before, after = rendered.split('PAD_MARKER')
88        a, b = tok.encode(before, parse_special=True), tok.encode(after, parse_special=True)
89        pad = tok.encode(FILLER)
90        assert 0 < target - len(a) - len(b) <= len(pad)
91        ids = a + pad[:target - len(a) - len(b)] + b
92        assert len(ids) == target
93        return ids
94
95    fixtures = {(i, n): shaped(task, n) for n in (512, 7000) for i, task in enumerate(TASKS + [WARMUP])}
96    (args.out / 'fixtures.json').write_text(json.dumps([
97        {'task_index': i, 'prompt_tokens': n, 'input_ids_sha256': digest(ids), 'warmup': i == 5}
98        for (i, n), ids in fixtures.items()
99    ], indent=2) + '\n')
100
101    def ask(ids, cap, label, measured=False, expected=None, json_check=False):
102        assert not interrupted
103        offset = log.stat().st_size
104        engine.done_line = None
105        start_utc = time.time()
106        started = time.monotonic()
107        arrivals, output = [], []
108        for token in engine.generate(ids, cap, sampling, cancel):
109            if token is not None:
110                arrivals.append(time.monotonic())
111                output.append(token)
112        elapsed = time.monotonic() - started
113        native = dict(engine.last)
114        text = tok.decode(output).replace('<|im_end|>', '').replace('<|endoftext|>', '').strip()
115        valid = (engine.done_line is not None and len(output) == native['generated']
116                 and native['prompt_tokens'] == len(ids) and native['reused'] == 0
117                 and native['prompt_read'] == len(ids) and bool(output))
118        if expected is not None:
119            valid &= text == expected
120        if json_check:
121            try:
122                obj = json.loads(text)
123                valid &= set(obj) == {'answer', 'ok'} and type(obj['answer']) is int and obj['ok'] is True
124            except (ValueError, TypeError):
125                valid = False
126        if measured or label.startswith('warm-shape'):
127            valid &= len(output) == cap and native['finish'] == 'length'
128        with log.open('r') as f:
129            f.seek(offset)
130            lines = f.read().splitlines()
131        timing = [line for line in lines if ENGINE_REQUEST.search(line)]
132        row = {'run': len(runs), 'label': label, 'measured': measured,
133               'started_utc': start_utc, 'input_tokens': len(ids), 'output_cap': cap,
134               'output_tokens': len(output), 'input_ids_sha256': digest(ids),
135               'output_ids_sha256': digest(output), 'output_sha256': hashlib.sha256(text.encode()).hexdigest(),
136               'sampling': sampling, 'native': native, 'native_done_line': engine.done_line,
137               'native_timing_lines': timing,
138               'prompt_tps': native['prompt_read'] * 1000 / native['prompt_ms'],
139               'decode_tps': native['generated'] * 1000 / native['decode_ms'],
140               'ttft_s': arrivals[0] - started if arrivals else None,
141               'post_first_tps': (len(output) - 1) / (arrivals[-1] - arrivals[0]) if len(output) > 1 else None,
142               'total_s': elapsed, 'valid': bool(valid)}
143        if label == 'json-quality':
144            row['math_answer_correct'] = json.loads(text).get('answer') == 50 if valid else False
145            row['math_answer_is_runtime_gate'] = False
146        if measured:
147            ref=refs[label]
148            row['matches_reference_output_ids']=all(row[k]==ref[k] for k in ref)
149            assert row['matches_reference_output_ids'], 'reference output stream changed: '+label
150        rows.append(row)
151        save()
152        print(json.dumps({'run': len(runs), 'label': label, 'measured': measured,
153                          'prompt_tps': row['prompt_tps'], 'decode_tps': row['decode_tps'],
154                          'valid': bool(valid)}), flush=True)
155        assert valid, 'protocol/length/isolation failure: ' + label
156        assert not interrupted, 'guard interruption'
157
158    try:
159        for run_index in range(args.runs):
160            log = args.ram / f'native-{run_index + 1}.log'
161            runs.append({'run': run_index + 1, 'binary_sha256': hashlib.file_digest(Path(binary).open('rb'), 'sha256').hexdigest(),
162                         'sampling': sampling, 'args': native_args})
163            save()
164            started = time.monotonic()
165            engine = MeasuredEngine(binary, native_args, cwd=cwd, log=str(log), env=dict(os.environ))
166            runs[-1]['startup_ready_s'] = time.monotonic() - started
167            runs[-1]['info'] = engine.info
168            save()
169            for label, prompt, expected, jc in [
170                ('isolation-a', 'Reply only with CANARY_MAPLE_73.', 'CANARY_MAPLE_73', False),
171                ('isolation-b', 'Reply only with CANARY_RIVER_29.', 'CANARY_RIVER_29', False),
172                ('json-quality', 'Calculate 2**5 + 6*3. Return exactly one JSON object with keys answer (the integer result) and ok (true), no markdown.', None, True)
173            ]:
174                ids = tok.encode(tpl.render([{'role': 'user', 'content': prompt}], enable_thinking=False), parse_special=True)
175                ask(ids, 64, label, expected=expected, json_check=jc)
176            for n in (512, 7000):
177                ask(fixtures[(5, n)], 640, f'warm-shape-{n}')
178                for i in range(5):
179                    ask(fixtures[(i, n)], 640, f'bench-{n}-{i}', measured=True)
180            ids = tok.encode(tpl.render([{'role': 'user', 'content': 'Reply only with CANARY_MAPLE_73.'}], enable_thinking=False), parse_special=True)
181            ask(ids, 64, 'post-long-isolation', expected='CANARY_MAPLE_73')
182            proc = engine.proc
183            started = time.monotonic()
184            proc.stdin.write('QUIT\n')
185            proc.stdin.flush()
186            proc.wait(timeout=75)
187            runs[-1]['native_exit'] = proc.returncode
188            runs[-1]['quit_exit_s'] = time.monotonic() - started
189            assert proc.returncode == 0
190            engine.close()
191            engine = None
192            raw = log.read_text()
193            assert not re.search(r'\b[1-9]\d* (?:of \d+ logits )?non-finite\b|\bnonfinite [1-9]\d*', raw)
194            runs[-1]['startup_lines'] = [line for line in raw.splitlines()
195                if re.match(r'^strata (?:generate|serve): (?:GPU \d+:|PCIe probe:|expert cache \d|\d+ of \d+ experts missing|\d+ MiB of VRAM free)', line)]
196            runs[-1]['native_log_sha256'] = hashlib.sha256(raw.encode()).hexdigest()
197            save()
198            for _ in range(5):
199                time.sleep(1)
200                assert not interrupted, 'guard interruption during delayed fault observation'
201    except BaseException as e:
202        failure = {'type': type(e).__name__, 'reason': str(e)}
203    finally:
204        if engine is not None:
205            proc = engine.proc
206            if proc is not None and proc.poll() is None:
207                proc.stdin.write('QUIT\n');proc.stdin.flush();proc.wait(timeout=75)
208            engine.close()
209            runs[-1]['native_exit'] = None if proc is None else proc.returncode
210        save()
211        (args.out / 'result.json').write_text(json.dumps({'failure': failure,
212            'run_count': len(runs), 'requests': len(rows), 'measured_requests': sum(r['measured'] for r in rows),
213            'generated_content_persisted': False}, indent=2) + '\n')
214    if failure:
215        raise SystemExit(1)
216
217if __name__ == '__main__':
218    main()