Files
Athena-Deck/docs/experiments/tts-codec-q4-2026-10-22/bench.py
T

191 lines
9.0 KiB
Python

"""Isolated codec A/B with bounded synthetic Strata load; no production changes."""
import concurrent.futures, json, os, queue, subprocess, sys, threading, time, urllib.request
from pathlib import Path
key = json.load(sys.stdin)['key']
stage = Path(__file__).resolve().parent
arm = sys.argv[1]
assert arm in ('q8-a', 'q4-a', 'q4-b', 'q8-b')
headers = {'Authorization':'Bearer '+key, 'Content-Type':'application/json'}
state_root = Path('/opt/athena-deck-dev/runtime/state')
experiment = state_root/'experiments/tts-codec-q4-20261022'
container_root = Path('/var/lib/deck/experiments/tts-codec-q4-20261022')
text = ('Dies ist ein Test mit fest aufgeteilten Prozessorkernen. Während Strata eine Antwort berechnet, '
'erzeugt Anna diese Sprachausgabe. Wir prüfen, ob die Sprache gleichmäßig und schneller als in Echtzeit ankommt.')
def status():
req = urllib.request.Request('http://127.0.0.1:8108/api/v1/status', headers=headers)
with urllib.request.urlopen(req, timeout=10) as response:
return json.load(response)['endpoint']
def idle():
for _ in range(2):
assert status()['active_requests'] == 0, 'Real request active; test deferred'
time.sleep(1)
def workers():
root = int(subprocess.check_output(['docker','inspect','--format','{{.State.Pid}}','athena-deck-dev']))
pending, seen, result = [root], set(), {}
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
for children in Path(f'/proc/{pid}/task').glob('*/children'):
try:
pending.extend(map(int, children.read_text().split()))
except OSError:
pass
cmd = [x.decode() for x in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0') if x]
if not cmd:
continue
if '/app/qwen_native_worker.py' in cmd:
result['qwen'] = (pid, cmd)
elif cmd[0].endswith('/engine/strata'):
result['strata'] = (pid, cmd)
except (OSError, ValueError):
pass
return root, result
idle()
deck_pid, before = workers()
assert set(before) == {'qwen','strata'}
cmd = before['qwen'][1]
assert cmd[5] == 'Q4' and cmd[7:] == ['2','2']
assert cmd[3].startswith('/var/lib/deck/') and Path(cmd[3]).name == 'model.gguf'
plan_bytes = (state_root/'cpu-partition.json').read_bytes()
plan = json.loads(plan_bytes)
assert plan['qwen_tts'] == [2,3,4,5,8,9,10,11]
assert plan['qwen_cpu_flash_attention'] is False
cg = Path('/sys/fs/cgroup')/Path(f'/proc/{deck_pid}/cgroup').read_text().strip().split(':',2)[2].lstrip('/')
def headroom():
available = next(int(s.split()[1])*1024 for s in Path('/proc/meminfo').read_text().splitlines() if s.startswith('MemAvailable:'))
return available, int((cg/'memory.max').read_text())-int((cg/'memory.current').read_text())
available, cgroup_free = headroom()
assert available >= 7*1024**3 and cgroup_free >= 6*1024**3, 'Insufficient headroom for isolated test'
events_before = (cg/'memory.events').read_text()
codec = cmd[3] if arm.startswith('q8') else str(container_root/'qwen-tokenizer-12hz-Q4_K_M.gguf')
script = str(container_root/'worker.py')
child = subprocess.Popen(['docker','exec','-i','-u','65534:65534','-w','/app','athena-deck-dev',cmd[0],script],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True, bufsize=1)
messages = queue.Queue()
inside_pid = None
def read_worker():
try:
for line in child.stdout:
messages.put(json.loads(line))
finally:
messages.put(None)
reader = threading.Thread(target=read_worker, daemon=True)
reader.start()
def read_event(expected, timeout=90):
value = messages.get(timeout=timeout)
if value is None:
raise RuntimeError('Isolated codec worker exited')
if value.get('event') != expected:
raise RuntimeError('Unexpected benchmark protocol event: '+json.dumps(value))
return value
def send(value):
child.stdin.write(json.dumps(value)+'\n')
child.stdin.flush()
stop = threading.Event()
ready = threading.Event()
rounds = []
health = {}
def load():
deadline = time.monotonic()+90
for number in range(8):
if stop.is_set():
return
assert time.monotonic() < deadline, 'Synthetic LLM load limit'
body = dict(model='flash-next-strata-iq3-dual',
messages=[dict(role='user', content='Zähle alle ganzen Zahlen von eins bis fünfhundert vollständig in deutschen Wörtern auf. Lasse keine aus, benutze keine Abkürzung und keine Erklärung. Runde '+str(number+1)+'.')],
max_tokens=512, reasoning_effort='none', temperature=0,
stream=True, stream_options=dict(include_usage=True))
request = urllib.request.Request('http://127.0.0.1:8120/v1/chat/completions',
data=json.dumps(body).encode(), headers=headers)
start, first, tokens = time.monotonic(), None, 0
try:
with urllib.request.urlopen(request, timeout=120) as response:
for line in response:
if not line.startswith(b'data: ') or line.strip() == b'data: [DONE]':
continue
data = json.loads(line[6:])
tokens = (data.get('usage') or {}).get('completion_tokens',tokens)
if first is None and any(c.get('delta',{}).get('content') for c in data.get('choices',[])):
first = time.monotonic()
ready.set()
rounds.append(dict(start=start, first=first, end=time.monotonic(), completion_tokens=tokens))
except Exception:
health['load_failed'] = True
ready.set()
raise
assert stop.is_set(), 'Synthetic load ended before speech'
def monitor():
while not stop.wait(.5):
try:
if status()['active_requests'] > 1:
health['external_request_overlap'] = True
if min(headroom()) < 1536*1024**2:
health['low_memory'] = True
except Exception:
health['monitor_failed'] = True
try:
send(dict(model=cmd[2], codec=codec, voice=cmd[4], cpus=plan['qwen_tts']))
loaded = read_event('ready')
inside_pid = loaded['pid']
print(json.dumps(dict(arm=arm, phase='isolated_worker_ready', load_seconds=loaded['load_seconds'])), flush=True)
send(dict(action='speak', label='warmup', text='Die Sprachausgabe ist bereit.'))
read_event('started')
warmup = read_event('result')
idle()
monitor_thread = threading.Thread(target=monitor, daemon=True)
monitor_thread.start()
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(load)
try:
assert ready.wait(100) and not health.get('load_failed'), 'Strata did not start'
send(dict(action='speak', label=arm, text=text))
read_event('started')
speech = read_event('result', timeout=75)
finally:
stop.set()
future.result()
finally:
stop.set()
monitor_thread.join(12)
overlap = sum(max(0,min(r['end'],speech['ended'])-max(r['first'] or r['end'],speech['started'])) for r in rounds)
after = workers()[1]
assert {k:v[0] for k,v in before.items()} == {k:v[0] for k,v in after.items()}, 'Production worker changed'
assert (state_root/'cpu-partition.json').read_bytes() == plan_bytes
result = dict(arm=arm, codec_quant='Q8_0' if arm.startswith('q8') else 'Q4_K_M',
generation_threads=2, codec_threads=2, native_runtime='0.4.2',
tts={k:v for k,v in speech.items() if k not in ('event','started','ended')},
llm_rounds=[dict(seconds=r['end']-r['start'],completion_tokens=r['completion_tokens']) for r in rounds],
llm_coverage=overlap/speech['seconds'], health=health,
production_workers_unchanged=True, cpu_policy_unchanged=True,
memory_events_unchanged=(cg/'memory.events').read_text()==events_before)
(stage/(arm+'.json')).write_text(json.dumps(result, indent=2)+'\n')
print(json.dumps(result), flush=True)
finally:
stop.set()
try:
if child.poll() is None:
send(dict(action='exit'))
child.stdin.close()
child.wait(timeout=20)
except (BrokenPipeError, subprocess.TimeoutExpired):
if inside_pid is not None:
# Verify this exact experiment script before terminating only it.
terminate = "import os,signal;from pathlib import Path;p="+str(inside_pid)+";assert "+repr(script.encode())+" in Path(f'/proc/{p}/cmdline').read_bytes().split(b'\\0');os.kill(p,signal.SIGTERM)"
subprocess.run(['docker','exec','-u','65534:65534','athena-deck-dev',cmd[0],'-c',terminate],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
child.wait(timeout=15)