120 lines
7.2 KiB
Python
120 lines
7.2 KiB
Python
"""CPU speed gate first; quality matrix only after the gate is observed to pass."""
|
|
import os
|
|
os.environ.update(CUDA_VISIBLE_DEVICES='', HF_HUB_OFFLINE='1',
|
|
HF_HUB_DISABLE_IMPLICIT_TOKEN='1', HF_HUB_DISABLE_TELEMETRY='1',
|
|
OMP_NUM_THREADS='4', MKL_NUM_THREADS='4', OPENBLAS_NUM_THREADS='1')
|
|
from pathlib import Path
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import resource
|
|
import statistics
|
|
import subprocess
|
|
import time
|
|
import numpy as np
|
|
import torch
|
|
from sopro import SoproTTS
|
|
|
|
ROOT = Path('/data/athena-sopro-cpu-20261027')
|
|
REFS = Path('/data/athena-articulino-references-20261027/references')
|
|
STATE = Path('/opt/athena-deck-dev/runtime/state')
|
|
FILES = [STATE/n for n in ('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json')]
|
|
FILES += [STATE/'speech-voices/Anna/reference.wav', Path('/opt/athena-deck-dev/source/qwen_native_worker.py')]
|
|
CASES = [dict(id='story', text='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.'),
|
|
dict(id='technical', text='Home Assistant läuft in Docker auf Unraid. Die SSD hat 47 Grad Celsius. Das Logfile enthält keinen Fehler. Die Datei ist 512 MiB groß und die Verbindung überträgt 100 Mbit pro Sekunde. Um 18:30 CEST startet der nächste Scan.')]
|
|
|
|
def write(path, data):
|
|
tmp = path.with_suffix('.tmp')
|
|
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False))
|
|
tmp.replace(path)
|
|
|
|
def available():
|
|
return next(int(s.split()[1])*1024 for s in Path('/proc/meminfo').read_text().splitlines() if s.startswith('MemAvailable:'))
|
|
|
|
def snapshot():
|
|
pids = dict(strata=[], articulino=[], qwen_tts=[])
|
|
for p in Path('/proc').iterdir():
|
|
if not p.name.isdigit(): continue
|
|
try: args = (p/'cmdline').read_bytes().split(b'\0')
|
|
except OSError: continue
|
|
if args and args[0].endswith(b'/engine/strata'): pids['strata'].append(int(p.name))
|
|
for key,name in [('articulino','articulino_worker.py'),('qwen_tts','qwen_native_worker.py')]:
|
|
if any(a.endswith(('/'+name).encode()) for a in args): pids[key].append(int(p.name))
|
|
return dict(hashes={str(p):hashlib.file_digest(p.open('rb'),'sha256').hexdigest() for p in FILES},
|
|
pids=pids, deck_started=subprocess.check_output(['docker','inspect','--format','{{.State.StartedAt}}','athena-deck-dev'],text=True).strip())
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('phase', choices=['speed','quality'])
|
|
parser.add_argument('--int8', action='store_true')
|
|
args = parser.parse_args()
|
|
os.umask(0o077)
|
|
torch.set_num_threads(4)
|
|
torch.set_num_interop_threads(1)
|
|
assert torch.version.cuda is None and not torch.cuda.is_available()
|
|
os.sched_setaffinity(0,{2,3,4,5,8,9,10,11})
|
|
assert available() >= 3*1024**3, 'Host memory reserve unavailable'
|
|
(ROOT/'outputs').mkdir(exist_ok=True, mode=0o700)
|
|
precision = 'int8-ar' if args.int8 else 'fp32'
|
|
target = ROOT/(args.phase+'-'+precision+'.json')
|
|
assert not target.exists(), 'Refuse to overwrite a previous run'
|
|
if args.phase == 'quality':
|
|
gate = json.loads((ROOT/('speed-'+precision+'.json')).read_text())
|
|
assert gate['phase'] == 'complete' and gate['speed_gate_passed'], 'No passed speed gate'
|
|
baseline = ROOT/'production-before.json'
|
|
if not baseline.exists(): write(baseline,snapshot())
|
|
result = dict(phase='loading', precision=precision, runs=[], references=[],
|
|
protocol=dict(device='cpu', threads=4, interop_threads=1, affinity=sorted(os.sched_getaffinity(0)),
|
|
seed=42, language='de', steps=2, max_seconds_per_segment=30, temperature=.8,
|
|
top_p=.9, top_k=25, api='offline synthesize', gate_maximum_rtf=.5,
|
|
cpu_quota_percent=400, memory_max_gib=4, private_reference_reused=True),
|
|
initial_available_gib=available()/2**30, initial_loadavg=os.getloadavg(),
|
|
torch=torch.__version__, cuda_build=torch.version.cuda)
|
|
write(target,result)
|
|
started=time.monotonic()
|
|
tts=SoproTTS.from_pretrained(ROOT/'model',device='cpu',dtype=torch.float32,
|
|
quantization='int8' if args.int8 else None)
|
|
result['model_load_seconds']=time.monotonic()-started
|
|
assert tts.device.type=='cpu' and tts.sample_rate==24000
|
|
work=[('A',CASES[0],1),('A',CASES[0],2)] if args.phase=='speed' else [(label,case,1) for label in 'ABC' for case in CASES]
|
|
current=None
|
|
for label,case,repetition in work:
|
|
assert available()>=2*1024**3, 'Host 2GiB reserve lost'
|
|
if current!=label:
|
|
refpath=REFS/f'anna-reference-{label}.wav'
|
|
started=time.monotonic()
|
|
ref=tts.prepare_reference(ref_audio_path=refpath)
|
|
result['references'].append(dict(label=label,preparation_seconds=time.monotonic()-started,
|
|
source_sha256=hashlib.file_digest(refpath.open('rb'),'sha256').hexdigest()))
|
|
current=label
|
|
torch.manual_seed(42)
|
|
started=time.monotonic()
|
|
wav=tts.synthesize(case['text'],ref=ref,lang='de',steps=2,temperature=.8,top_p=.9,top_k=25,max_seconds=30).cpu()
|
|
synthesis=time.monotonic()-started
|
|
assert wav.numel()>0 and torch.isfinite(wav).all()
|
|
duration=wav.shape[-1]/tts.sample_rate
|
|
name=f'sopro-{precision}-{args.phase}-{case["id"]}-{label}-{repetition}.wav'
|
|
file=ROOT/'outputs'/name
|
|
tts.save_wav(file,wav)
|
|
pcm=wav.numpy().reshape(-1)
|
|
row=dict(label=label,case=case['id'],repetition=repetition,text=case['text'],file=name,
|
|
generation_seconds=synthesis,write_seconds=time.monotonic()-started-synthesis,
|
|
duration_seconds=duration,rtf=synthesis/duration,realtime_multiple=duration/synthesis,
|
|
peak=float(np.max(np.abs(pcm))),clipped_fraction=float(np.mean(np.abs(pcm)>=1)),
|
|
peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
|
available_gib=available()/2**30,loadavg=os.getloadavg(),
|
|
sha256=hashlib.file_digest(file.open('rb'),'sha256').hexdigest())
|
|
result['runs'].append(row);result['phase']='running';write(target,result)
|
|
print(json.dumps(row,ensure_ascii=False),flush=True)
|
|
result['phase']='complete'
|
|
result['weighted_rtf']=sum(r['generation_seconds'] for r in result['runs'])/sum(r['duration_seconds'] for r in result['runs'])
|
|
result['speed_gate_passed']=all(r['rtf']<=.5 for r in result['runs']) if args.phase=='speed' else True
|
|
after=snapshot(); before=json.loads(baseline.read_text())
|
|
result['production_preservation']=dict(files_equal=before['hashes']==after['hashes'],
|
|
pids_equal=before['pids']==after['pids'],deck_start_equal=before['deck_started']==after['deck_started'])
|
|
write(ROOT/'production-after.json',after);write(target,result)
|
|
assert all(result['production_preservation'].values()), 'Production state changed independently; investigate'
|
|
print(json.dumps(dict(phase='complete',speed_gate_passed=result['speed_gate_passed'],weighted_rtf=result['weighted_rtf'],preservation=result['production_preservation'])),flush=True)
|
|
|
|
if __name__=='__main__': main()
|