Files
Athena-Deck/docs/experiments/piper-cpu-2026-10-27/speed.py
T

103 lines
4.6 KiB
Python

"""Warm CPU speed gate before any private Anna preparation or training."""
import os
os.environ.update(CUDA_VISIBLE_DEVICES='', OMP_NUM_THREADS='4',
OPENBLAS_NUM_THREADS='1', MKL_NUM_THREADS='4')
from pathlib import Path
import argparse
import gc
import importlib.metadata
import json
import resource
import time
import wave
import numpy as np
import onnxruntime as ort
from piper import PiperVoice
from piper.config import PiperConfig, SynthesisConfig
ROOT = Path('/data/athena-piper-test-20261027')
parser=argparse.ArgumentParser()
parser.add_argument('--model',default=str(ROOT/'model/de_DE-thorsten-medium.onnx'))
parser.add_argument('--results',default=str(ROOT/'results.json'))
parser.add_argument('--prefix',default='piper-thorsten')
args=parser.parse_args()
model=Path(args.model)
OUT = ROOT / 'outputs'
OUT.mkdir(exist_ok=True)
STORY = ('Wenn du magst, erzähle ich dir eine kurze Geschichte. '
'Anna öffnete das Fenster und hörte drei Vögel singen. '
'Auf dem Tisch lagen sieben Bücher und eine rote Tasse. '
'Zum Schluss sagte sie: Das hat wunderbar funktioniert.')
TECH = ('Home Assistant läuft in einem Docker-Container auf Unraid. '
'Die SSD hat zwei Terabyte Kapazität. Das Backup ist abgeschlossen, '
'und im Log stehen keine Fehler.')
state = {'phase': 'loading', 'phase_started_monotonic': time.monotonic(),
'voice': args.prefix, 'threads': 4,
'affinity': sorted(os.sched_getaffinity(0)), 'runs': [],
'gate_max_rtf': .2,
'gate_note': 'Conservative >=5x-realtime first filter, not Articulino parity or user-specified exact threshold'}
def save():
Path(args.results).write_text(json.dumps(state, ensure_ascii=False, indent=2))
def phase(name):
state.update(phase=name, phase_started_monotonic=time.monotonic())
save()
save()
started = time.monotonic()
opts = ort.SessionOptions()
opts.intra_op_num_threads = 4
opts.inter_op_num_threads = 1
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
session = ort.InferenceSession(str(model),
sess_options=opts, providers=['CPUExecutionProvider'])
cfg = PiperConfig.from_dict(json.loads(Path(str(model)+'.json').read_text()))
voice = PiperVoice(session=session, config=cfg, download_dir=ROOT / 'cache')
assert session.get_providers() == ['CPUExecutionProvider']
state.update(load_seconds=time.monotonic()-started, providers=session.get_providers(),
sample_rate=cfg.sample_rate, piper_version=importlib.metadata.version('piper-tts'),
onnxruntime_version=ort.__version__, setup_warmups=[])
syn = SynthesisConfig(length_scale=1.0, noise_scale=.667, noise_w_scale=.8,
normalize_audio=True)
def generate(text, name):
chunks = []
first = None
start = time.monotonic()
for chunk in voice.synthesize(text, syn_config=syn):
if first is None:
first = time.monotonic()-start
assert np.isfinite(chunk.audio_float_array).all()
chunks.append(chunk.audio_int16_bytes)
elapsed = time.monotonic()-start
pcm = b''.join(chunks)
assert len(pcm) > 0
duration = len(pcm) / 2 / cfg.sample_rate
with wave.open(str(OUT / name), 'wb') as wav:
wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(cfg.sample_rate)
wav.writeframes(pcm)
samples = np.frombuffer(pcm, dtype='<i2').astype(np.float32) / 32768
return {'file': name, 'text': text, 'generation_seconds': elapsed,
'duration_seconds': duration, 'rtf': elapsed / duration,
'times_realtime': duration / elapsed, 'first_sentence_seconds': first,
'chunks': len(chunks), 'peak': float(np.max(np.abs(samples))),
'clipped_fraction': float(np.mean(np.abs(samples) >= .999)),
'peak_rss_kib': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss}
for i in range(2):
phase('warmup')
state['setup_warmups'].append(generate('Hallo.', f'{args.prefix}-warmup-{i+1}.wav'))
for label, text in [('story-1', STORY), ('story-2', STORY), ('technical', TECH)]:
phase('probe')
row = generate(text, f'{args.prefix}-{label}.wav')
state['runs'].append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
save()
if row['rtf'] > state['gate_max_rtf']:
state.update(phase='complete', decision='speed_gate_rejected')
save()
raise SystemExit(0)
state.update(phase='complete', decision='speed_gate_passed',
weighted_rtf=sum(x['generation_seconds'] for x in state['runs']) /
sum(x['duration_seconds'] for x in state['runs']))
save()
print(json.dumps({'decision': state['decision'], 'weighted_rtf': state['weighted_rtf']}), flush=True)