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

131 lines
7.2 KiB
Python

"""Temporary localhost-only upstream Vulkan server and Anna streaming test."""
import base64, json, os, socket, subprocess, threading, time, urllib.error, urllib.request, wave
from pathlib import Path
root = Path('/var/tmp/athena-qwen-rx470-20261022')
unit = 'athena-qwen-rx470-test-20261022.service'
base = 'http://127.0.0.1:18129'
gpu_root = Path('/sys/class/drm/card0/device')
reference = root/'anna-reference.wav'
stop = threading.Event()
gpu_samples = []
results = []
before = json.loads((root/'baseline.json').read_text())
parts = ['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 emit(value): print(json.dumps(value), flush=True)
def request(path, data=None, timeout=90):
return urllib.request.urlopen(urllib.request.Request(base+path,
data=json.dumps(data).encode() if data is not None else None,
headers={'Content-Type':'application/json'}),timeout=timeout)
def monitor():
while not stop.is_set():
try:
gpu_samples.append(dict(at=time.monotonic(),busy=int((gpu_root/'gpu_busy_percent').read_text()),
vram_bytes=int((gpu_root/'mem_info_vram_used').read_text())))
except OSError: pass
stop.wait(.2)
def service_state():
return subprocess.check_output(['systemctl','show','athena-helper-tts-api.service','athena-helper-tts.service',
'-p','ActiveState','-p','SubState','-p','MainPID','-p','UnitFileState','-p','ExecMainStartTimestamp'],text=True)
def speech(label, inputs):
started = time.monotonic();first=latest=None;total=packets=0;maxgap=deficit=0.0;pcm=[]
for text in inputs:
data=dict(model='rx470-qwen-q4-test',voice='Anna',language='german',
input=text,response_format='pcm',seed=42,temperature=0,
subtalker_temperature=0,max_new_tokens=1024,repetition_penalty=1.05)
with request('/v1/audio/speech',data,timeout=100) as response:
assert response.headers.get('Content-Type','').startswith('audio/pcm')
while True:
block=response.read1(16384)
if not block: break
now=time.monotonic()
if now-started>90: raise TimeoutError('Bounded speech test exceeded90seconds')
if first is None: first=now
else:
maxgap=max(maxgap,now-latest)
deficit=max(deficit,now-first-total/48000)
pcm.append(block);total+=len(block);latest=now;packets+=1
assert total<32*1024**2
elapsed=time.monotonic()-started
assert total and total%2==0 and first is not None
if label!='warmup':
with wave.open(str(root/(label+'.wav')),'wb') as output:
output.setnchannels(1);output.setsampwidth(2);output.setframerate(24000)
output.writeframes(b''.join(pcm))
result=dict(label=label,seconds=elapsed,audio_seconds=total/48000,rtf=elapsed/(total/48000),
first_pcm_seconds=first-started,bytes=total,packets=packets,
longest_packet_gap_seconds=maxgap,required_buffer_after_first_pcm_seconds=max(0,deficit))
emit(result)
return result
started_unit=False
report=dict(upstream_revision='5916bf7c79dbb4e66fc059cdc507a79a23a28bb4',
device='Vulkan0',model_quant='Q4_K_M',codec_quant='Q8_0',
loopback_only=True,production_connection_unchanged=True,runs=results)
try:
assert service_state()==before['services'], 'Existing TTS service changed before test'
assert int((gpu_root/'gpu_busy_percent').read_text())<=5, 'GPU is busy; test deferred'
with socket.socket() as probe: probe.bind(('127.0.0.1',18129))
command=['systemd-run','--quiet','--collect','--unit='+unit,
'--property=User=athena-tts','--property=Group=athena-tts',
'--property=WorkingDirectory='+str(root),'--property=MemoryMax=6G',
'--property=MemorySwapMax=0','--property=TasksMax=128','--property=Nice=10',
'--property=RuntimeMaxSec=600','--property=NoNewPrivileges=yes',
'--property=StandardOutput=append:'+str(root/'server.log'),
'--property=StandardError=append:'+str(root/'server.log'),
'--setenv=XDG_CACHE_HOME='+str(root/'cache'),
'--setenv=MESA_SHADER_CACHE_DIR='+str(root/'cache/mesa'),
str(root/'build/tts-server'),'--model',str(root/'models/qwen-talker-0.6b-base-Q4_K_M.gguf'),
'--codec',str(root/'models/qwen-tokenizer-12hz-Q8_0.gguf'),
'--device','Vulkan0','--no-fa','--lang','german','--host','127.0.0.1',
'--port','18129','--alias','rx470-qwen-q4-test','--max-batch','1']
subprocess.run(command,check=True,timeout=15);started_unit=True
watcher=threading.Thread(target=monitor,daemon=True);watcher.start()
start=time.monotonic()
while time.monotonic()-start<180:
try:
with request('/health',timeout=2) as response:
assert response.status==200
break
except (OSError,urllib.error.URLError):
active=subprocess.run(['systemctl','is-active','--quiet',unit]).returncode==0
if not active: raise RuntimeError('Temporary Vulkan server failed to start; see its own log')
time.sleep(1)
else:raise TimeoutError('Vulkan server startup deadline')
report['load_seconds']=time.monotonic()-start
emit(dict(phase='server_ready',seconds=report['load_seconds']))
# The existing private voice is used only by this explicitly requested test.
# Its base64 payload is memory-only, never printed, logged or written to Git.
start=time.monotonic()
with request('/v1/audio/voices',dict(name='Anna',wav_b64=base64.b64encode(reference.read_bytes()).decode()),timeout=180) as response:
assert response.status in (200,201)
response.read()
report['voice_preparation_seconds']=time.monotonic()-start
reference.unlink()
emit(dict(phase='anna_registered',seconds=report['voice_preparation_seconds'],temporary_reference_removed=True))
warmup=speech('warmup',['Die Sprachausgabe ist bereit.'])
report['warmup']=warmup
for label in ('run-1','run-2'):
results.append(speech(label,parts))
(root/'results.json').write_text(json.dumps(report,indent=2)+'\n')
except Exception as error:
report.update(failed=True,error_type=type(error).__name__,error=str(error))
raise
finally:
if started_unit:subprocess.run(['systemctl','stop',unit],check=False,timeout=25,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
stop.set()
if 'watcher' in locals():watcher.join(2)
reference.unlink(missing_ok=True)
report['existing_tts_service_state_unchanged']=service_state()==before['services']
report['gpu_peak_vram_bytes']=max((r['vram_bytes'] for r in gpu_samples),default=0)
report['gpu_peak_busy_percent']=max((r['busy'] for r in gpu_samples),default=0)
report['temporary_reference_removed']=not reference.exists()
report['gpu_after']={k:(gpu_root/k).read_text().strip() for k in ('gpu_busy_percent','mem_info_vram_used')}
(root/'gpu-samples.json').write_text(json.dumps(gpu_samples,indent=2)+'\n')
(root/'results.json').write_text(json.dumps(report,indent=2)+'\n')
emit(dict(phase='final',**report))