Files
Athena-Deck/docs/experiments/deepseek-iq2-2026-10-24/measure.py
T

125 lines
6.9 KiB
Python

#!/usr/bin/env python3
"""Synthetic requests to an already running isolated loopback test worker only."""
import argparse
import json
import os
from pathlib import Path
import time
import urllib.parse
import urllib.request
from mock_tools import tool_result
def request(url, body, deadline):
headers = {'Content-Type': 'application/json'}
if os.environ.get('TEST_API_KEY'):
headers['Authorization'] = 'Bearer ' + os.environ['TEST_API_KEY']
req = urllib.request.Request(url + '/v1/chat/completions', data=json.dumps(body).encode(), headers=headers)
start = time.monotonic()
text, calls, usage, timings, finish, ttft, first_event = '', {}, {}, {}, None, None, None
done = False
with urllib.request.urlopen(req, timeout=120) as response:
for line in response:
if time.monotonic() > deadline:
raise TimeoutError('synthetic request deadline')
if not line.startswith(b'data:'):
continue
raw = line[5:].strip()
if raw == b'[DONE]':
done = True
break
data = json.loads(raw)
if 'error' in data:
raise RuntimeError('backend stream error')
usage = data.get('usage') or usage
timings = data.get('timings') or data.get('backend_timings') or timings
for choice in data.get('choices', []):
finish = choice.get('finish_reason') or finish
delta = choice.get('delta', {})
if first_event is None and any(delta.get(k) for k in ('content', 'reasoning_content', 'reasoning', 'tool_calls')):
first_event = time.monotonic() - start
if delta.get('content'):
if ttft is None:
ttft = time.monotonic() - start
text += delta['content']
for item in delta.get('tool_calls', []):
call = calls.setdefault(item.get('index', 0), dict(id='', type='function', function=dict(name='', arguments='')))
if item.get('id'):
call['id'] = item['id']
for key in ('name', 'arguments'):
call['function'][key] += item.get('function', {}).get(key, '')
if not done:
raise RuntimeError('incomplete stream')
return text, list(calls.values()), dict(usage=usage, timings=timings, finish=finish,
ttft_answer_s=ttft, ttft_any_s=first_event, wall_s=time.monotonic() - start)
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--url', default='http://127.0.0.1:19084')
ap.add_argument('--arm', choices=['deepseek', 'qwen'], required=True)
ap.add_argument('--output', type=Path, required=True)
ap.add_argument('--speed-only', action='store_true', help='Two identical short requests, thinking off, 256 output tokens.')
ap.add_argument('--run', action='store_true', help='Explicitly allow inference; this script never starts/stops workers.')
a = ap.parse_args()
u = urllib.parse.urlparse(a.url)
if u.scheme != 'http' or u.hostname != '127.0.0.1' or u.port is None or u.port in (8120, 8108):
ap.error('Use an explicitly prepared isolated loopback worker, not the production API.')
cases = json.loads(Path(__file__).with_name('cases.json').read_text())
if a.speed_only:
prompt = 'Schreibe einen ausführlichen sachlichen deutschen Text über zuverlässige Datensicherung. Schreibe mindestens 800 Wörter.'
cases = [dict(id='speed-' + label, category='speed', prompt=prompt) for label in ('first', 'repeat')]
if not a.run:
print(f'Validated {len(cases)} fixtures; no inference performed. Pass --run only after a safe manual model switch.')
return
with a.output.open('x') as out:
for case in cases:
row = dict(arm=a.arm, case_id=case['id'], category=case['category'], steps=[], tool_checks=[], answer='', error=None)
messages = [dict(role='system', content='Antworte auf Deutsch, sofern nicht anders gefordert. Bearbeite ausschließlich diese synthetische Aufgabe. Werkzeuge liefern nur simulierte Daten; behaupte keine realen Prüfungen.'), dict(role='user', content=case['prompt'])]
deadline = time.monotonic() + 900
try:
for turn in range(4):
body = dict(model='synthetic-comparison', messages=messages, stream=True,
stream_options={'include_usage': True}, temperature=1.0,
top_p=1.0 if a.arm == 'deepseek' else 0.95, seed=42,
reasoning_effort='low' if a.arm == 'deepseek' else 'medium',
reasoning_budget_tokens=1024, max_tokens=2048)
if a.arm == 'qwen':
body.update(top_k=20, min_p=0, presence_penalty=0, repeat_penalty=1, frequency_penalty=0,
strata_tune={'aux_cpus': 1})
if a.speed_only:
body.update(temperature=0, top_p=1, reasoning_effort='none', max_tokens=256)
body.pop('reasoning_budget_tokens', None)
row['generation_parameters'] = {k: v for k, v in body.items() if k not in ('messages', 'model', 'stream', 'stream_options')}
if case.get('tools'):
body.update(tools=case['tools'], tool_choice='auto')
text, calls, metrics = request(a.url, body, deadline)
row['steps'].append(metrics)
if not calls:
row['answer'] = text
break
messages.append(dict(role='assistant', content=text or None, tool_calls=calls))
for call in calls:
args = json.loads(call['function']['arguments'])
result, valid = tool_result(case, call['function']['name'], args)
row['tool_checks'].append(dict(name=call['function']['name'], arguments=args, valid=valid))
if not valid:
raise ValueError('Invalid/forbidden mock tool call')
messages.append(dict(role='tool', tool_call_id=call['id'], content=json.dumps(result)))
else:
raise RuntimeError('tool-round limit')
if case.get('tools') and not row['tool_checks']:
raise RuntimeError('required mock tool not used')
if not row['answer']:
raise RuntimeError('no final answer')
row['truncated'] = any(x['finish'] == 'length' for x in row['steps'])
except Exception as exc:
row['error'] = str(exc)
out.write(json.dumps(row, ensure_ascii=False) + '\n')
out.flush()
print(case['id'], row['error'] or 'response recorded', flush=True)
if __name__ == '__main__':
main()