Files
Athena-Deck/docs/experiments/qwen06-native-cpu-2026-10-19/benchmark.py
T

101 lines
5.0 KiB
Python

"""Bounded CPU-only native Qwen 0.6B Q8 streaming test; synthetic texts only."""
import hashlib
import json
import os
from pathlib import Path
import resource
import time
import wave
ROOT = Path('/data/experiments/qwen06-q8-native-cpu-20261019')
OUTPUT = ROOT / os.environ.get('BENCH_OUTPUT', '.')
OUTPUT.mkdir(parents=True, exist_ok=True)
GEN_THREADS = int(os.environ.get('BENCH_GEN_THREADS', '2'))
CODEC_THREADS = int(os.environ.get('BENCH_CODEC_THREADS', '2'))
STREAM_FRAMES = int(os.environ.get('BENCH_STREAM_FRAMES', '1'))
report = {'phase': 'imports', 'runs': [], 'cpu_quota': int(os.environ.get('BENCH_CPU_QUOTA', '4')), 'memory_limit_gib': 6,
'production_changes': False, 'llm_requests': 0,
'generation_threads': GEN_THREADS, 'codec_threads': CODEC_THREADS,
'stream_frames': STREAM_FRAMES}
def save():
temp = OUTPUT / 'results.tmp'
temp.write_text(json.dumps(report, indent=2, ensure_ascii=False))
temp.replace(OUTPUT / 'results.json')
save()
try:
import numpy as np
import qwentts_cpp_cpu as q
assert q.CPU_ONLY is True
report.update(cpu_only=q.CPU_ONLY, abi=q.QT_ABI_VERSION)
paths = json.loads((ROOT / 'model-paths.json').read_text())
report['models'] = []
for name in paths:
p = Path(name)
with p.open('rb') as f:
digest = hashlib.file_digest(f, 'sha256').hexdigest()
report['models'].append({'name': p.name, 'bytes': p.stat().st_size, 'sha256': digest})
with wave.open(str(ROOT / 'anna-reference-original.wav'), 'rb') as w:
assert w.getframerate() == 24000 and w.getnchannels() == 1 and w.getsampwidth() == 2
ref_audio = np.frombuffer(w.readframes(w.getnframes()), dtype='<i2').astype(np.float32) / 32768
report['phase'] = 'loading'
save()
begin = time.monotonic()
engine = q.QwenTTS(*paths, cpu_threads=GEN_THREADS, cpu_codec_threads=CODEC_THREADS,
cpu_stream_frames=STREAM_FRAMES, clamp_fp16=False, use_fa=True)
report['load_seconds'] = time.monotonic() - begin
begin = time.monotonic()
voice = engine.extract_voice_ref(ref_audio)
report['voice_preparation_seconds'] = time.monotonic() - begin
report['phase'] = 'synthesis'
save()
texts = [
('warmup', 'Hallo Michael, die Sprachausgabe wird vorbereitet.'),
('short-1', 'Wenn du magst, erzähle ich dir eine kurze Geschichte. Anna öffnete das Fenster und hörte drei Vögel singen.'),
('short-2', 'Wenn du magst, erzähle ich dir eine kurze Geschichte. Anna öffnete das Fenster und hörte drei Vögel singen.'),
('technical', 'Der Heizkörper in der Küche antwortet nicht. Es gibt 28 Fehler, seit 01:45 Uhr, zuletzt um 09:12 Uhr. Die Batterie steht bei 35 Prozent. Die Konfiguration ist gültig. Alle 46 Reparaturhinweise sind inaktiv. Das Backup war heute um 03:16 Uhr erfolgreich.'),
]
for label, text in texts:
started = time.monotonic()
chunks, audio = [], []
samples = 0
first_non_silent = None
for data, rate in engine.stream(text=text, lang='german', ref_spk_emb=voice.ref_spk_emb,
seed=42, max_new_tokens=768, do_sample=False,
onset_silence_profile='qwen3_tts_12hz_0_6b_base_q8_v1'):
assert rate == 24000 and np.isfinite(data).all()
elapsed = time.monotonic() - started
peak = float(np.max(np.abs(data))) if data.size else 0
if first_non_silent is None and peak > .01:
first_non_silent = elapsed
chunks.append({'arrival_seconds': elapsed, 'samples': int(data.size), 'peak': peak,
'audio_before_seconds': samples / rate})
samples += data.size
audio.append(data)
elapsed = time.monotonic() - started
assert samples > 0
first = chunks[0]['arrival_seconds']
deficit = max(max(0, c['arrival_seconds'] - first - c['audio_before_seconds']) for c in chunks)
pcm = np.rint(np.clip(np.concatenate(audio), -1, 1) * 32767).astype('<i2')
with wave.open(str(OUTPUT / (label + '.wav')), 'wb') as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(24000); w.writeframes(pcm.tobytes())
run = dict(label=label, text=text, seconds=elapsed, audio_seconds=samples / 24000,
rtf=elapsed / (samples / 24000), first_chunk_seconds=first,
first_non_silent_chunk_seconds=first_non_silent,
additional_buffer_needed_seconds=deficit, chunks=chunks,
peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
report['runs'].append(run)
save()
print(json.dumps({k: v for k, v in run.items() if k not in ('chunks', 'text')}), flush=True)
engine.close()
report['phase'] = 'complete'
except Exception as exc:
report.update(phase='failed', error_type=type(exc).__name__, error=str(exc))
raise
finally:
report['peak_rss_kib'] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
save()