Files
Athena-Deck/docs/experiments/tts-cpu-threads-2026-10-22/bench.py
T

95 lines
5.7 KiB
Python

"""Bounded synthetic load and PCM arrival timing; no user text/audio is read."""
import concurrent.futures,json,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];base='http://127.0.0.1:8120/v1/'
headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'}
def api(name,body):return urllib.request.urlopen(urllib.request.Request(base+name,data=json.dumps(body).encode(),headers=headers),timeout=180)
def idle():
req=urllib.request.Request('http://127.0.0.1:8108/api/v1/status',headers=headers)
with urllib.request.urlopen(req,timeout=10) as r:
if json.load(r)['endpoint']['active_requests']!=0:raise RuntimeError('Real request active; test deferred')
def processes():
root=int(sys.argv[sys.argv.index('--deck-pid')+1]) if '--deck-pid' in sys.argv else json.loads(subprocess.check_output(['docker','inspect','athena-deck-dev']))[0]['State']['Pid'];pending=[root];seen=set();out={}
while pending:
pid=pending.pop()
if pid in seen:continue
seen.add(pid)
try:
for child_list in Path(f'/proc/{pid}/task').glob('*/children'):
try:pending.extend(int(n) for n in child_list.read_text().split())
except OSError:pass
cmd=Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0')
role='qwen_tts' if any(a.endswith(b'/qwen_native_worker.py') for a in cmd) else 'strata' if cmd[0].endswith(b'/engine/strata') else None
if role:out[role]=pid
except (OSError,ValueError):pass
return out
def observe(pids):
found={}
for role,pid in pids.items():
for f in Path(f'/proc/{pid}/task').glob('*/status'):
try:
d={s.split(':',1)[0]:s.split(':',1)[1].strip() for s in f.read_text().splitlines() if ':' in s}
found.setdefault(role,set()).add((d['Name'],d['Cpus_allowed_list']))
except (OSError,KeyError):pass
return found
idle();pids=processes()
if set(pids)!={'strata','qwen_tts'}:raise RuntimeError('Expected both warm workers')
masks={};running_cpus={};stop=threading.Event();stop_load=threading.Event();ready=threading.Event();state={};rounds=[]
def monitor():
while not stop.is_set():
for role,values in observe(pids).items():masks.setdefault(role,set()).update(values)
for role,pid in pids.items():
for f in Path(f'/proc/{pid}/task').glob('*/stat'):
try:
fields=f.read_text().rsplit(')',1)[1].split()
if fields[0]=='R':
n=int(fields[36]);counts=running_cpus.setdefault(role,{})
counts[n]=counts.get(n,0)+1
except (OSError,ValueError,IndexError):pass
stop.wait(.1)
def llm():
deadline=time.monotonic()+90
for n in range(8):
if stop_load.is_set():break
if time.monotonic()>deadline:raise RuntimeError('Synthetic load deadline')
start=time.monotonic();first=None;tokens=0
try:
with api('chat/completions',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(n+1)+'.')],max_tokens=512,reasoning_effort='none',temperature=0,stream=True,stream_options=dict(include_usage=True))) as r:
for line in r:
if not line.startswith(b'data: ') or line.strip()==b'data: [DONE]':continue
d=json.loads(line[6:]);tokens=(d.get('usage') or {}).get('completion_tokens',tokens)
if any(c.get('delta',{}).get('content') for c in d.get('choices',[])) and first is None:
first=time.monotonic();ready.set()
rounds.append(dict(start=start,end=time.monotonic(),first=first,completion_tokens=tokens))
except Exception:
state['load_failed']=True;ready.set();raise
if not stop_load.is_set():raise RuntimeError('Synthetic load ended before TTS')
def tts():
if not ready.wait(100) or state.get('load_failed'):raise RuntimeError('LLM did not begin')
start=time.monotonic();state['tts_start']=start;first=None;received=0;latest=None;maxgap=0;deficit=0;chunks=0
with api('audio/speech',dict(model='qwen-06b-q4-anna-cpu',voice='default',response_format='pcm',input='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.')) as r:
while True:
b=r.read1(16384)
if not b:break
now=time.monotonic()
if now-start>60:raise TimeoutError('Synthetic speech exceeded the 60-second comparison limit')
if first is None:first=now
else:
maxgap=max(maxgap,now-latest);deficit=max(deficit,now-first-received/48000)
received+=len(b);latest=now;chunks+=1
end=time.monotonic();state['tts_end']=end
if received%2 or not received:raise RuntimeError('Invalid complete PCM stream')
return dict(seconds=end-start,first_pcm_seconds=first-start,audio_seconds=received/48000,rtf=(end-start)/(received/48000),bytes=received,packets=chunks,longest_packet_gap_seconds=maxgap,required_buffer_after_first_pcm_seconds=max(0,deficit))
thread=threading.Thread(target=monitor,daemon=True);thread.start()
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
lf=pool.submit(llm)
try:speech=tts()
finally:stop_load.set()
lf.result()
overlap=sum(max(0,min(r['end'],state['tts_end'])-max(r['first'] or r['end'],state['tts_start'])) for r in rounds)
result=dict(arm=arm,tts=speech,llm_rounds=[dict(seconds=r['end']-r['start'],completion_tokens=r['completion_tokens']) for r in rounds],llm_overlap_seconds=overlap,llm_coverage=overlap/speech['seconds'],thread_affinities={role:[dict(name=n,cpus=c) for n,c in sorted(values)] for role,values in masks.items()},running_cpu_samples=running_cpus)
(stage/(arm+'.json')).write_text(json.dumps(result,indent=2));print(json.dumps(result),flush=True)
finally:stop.set();thread.join(2)