149 lines
7.0 KiB
Python
149 lines
7.0 KiB
Python
"""Own CPU-only comparison. No production model, profile or endpoint writes."""
|
|
import os
|
|
os.environ.update(CUDA_VISIBLE_DEVICES="", HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1",
|
|
OMP_NUM_THREADS="4", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="4")
|
|
import gc
|
|
import json
|
|
import resource
|
|
import signal
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path('/data/athena-mini-tts-20261026')
|
|
ARM = sys.argv[1]
|
|
import numpy as np
|
|
import soundfile as sf
|
|
import torch
|
|
torch.set_num_threads(4)
|
|
torch.set_num_interop_threads(1)
|
|
|
|
def alarm(*_):
|
|
raise TimeoutError('Own synthetic case exceeded 180 seconds')
|
|
signal.signal(signal.SIGALRM, alarm)
|
|
|
|
out = ROOT / 'outputs' / ARM
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
cases = json.loads((ROOT / 'cases.json').read_text())
|
|
started = time.monotonic()
|
|
first_clock = [None]
|
|
|
|
if ARM == 'moss':
|
|
sys.path.insert(0, str(ROOT / 'moss'))
|
|
from onnx_tts_runtime import OnnxTtsRuntime
|
|
model = OnnxTtsRuntime(model_dir=ROOT / 'models', thread_count=4,
|
|
max_new_frames=375, do_sample=True, sample_mode='fixed',
|
|
execution_provider='cpu', output_dir=out)
|
|
load_seconds = time.monotonic() - started
|
|
t = time.monotonic()
|
|
codes = model.encode_reference_audio('/opt/athena-deck-dev/runtime/state/speech-voices/Anna/reference.wav')
|
|
reference_seconds = time.monotonic() - t
|
|
# Production-style reference caching, outside the timed synthesis calls.
|
|
model.resolve_prompt_audio_codes = lambda **kw: codes
|
|
original_decode = model.codec_streaming_session.run_frames
|
|
def timed_decode(frames):
|
|
result = original_decode(frames)
|
|
if result is not None and result[1] > 0 and first_clock[0] is None:
|
|
first_clock[0] = time.monotonic()
|
|
return result
|
|
model.codec_streaming_session.run_frames = timed_decode
|
|
providers = {name: session.get_providers() for name, session in model.sessions.items()}
|
|
assert all(p == ['CPUExecutionProvider'] for p in providers.values()), providers
|
|
else:
|
|
import onnxruntime as ort
|
|
original_session = ort.InferenceSession
|
|
def cpu_session(path, sess_options=None, providers=None, **kwargs):
|
|
options = sess_options or ort.SessionOptions()
|
|
options.intra_op_num_threads = 4
|
|
options.inter_op_num_threads = 1
|
|
return original_session(path, sess_options=options,
|
|
providers=['CPUExecutionProvider'], **kwargs)
|
|
ort.InferenceSession = cpu_session
|
|
from neutts import NeuTTS
|
|
model = NeuTTS(backbone_repo=str(ROOT/'models/neutts-nano-german-q8-gguf/neutts-nano-german-Q8_0.gguf'),
|
|
backbone_device='cpu', codec_repo=str(ROOT/'models/neucodec-onnx-decoder/model.onnx'),
|
|
codec_device='cpu', language='de', seed=42)
|
|
model.backbone._ctx.set_n_threads(4, 4)
|
|
model.backbone.n_threads = 4
|
|
model.backbone.n_threads_batch = 4
|
|
assert model.codec.session.get_providers() == ['CPUExecutionProvider']
|
|
load_seconds = time.monotonic() - started
|
|
codes = torch.from_numpy(np.load(ROOT/'anna-codes.npy'))
|
|
ref_text = json.loads((ROOT/'anna-stt.json').read_text())['text']
|
|
reference_seconds = json.loads((ROOT/'reference-encoding.json').read_text())['seconds']
|
|
providers = {'llama': 'n_gpu_layers=0', 'codec': model.codec.session.get_providers()}
|
|
|
|
info = dict(arm=ARM, load_seconds=load_seconds, reference_seconds=reference_seconds,
|
|
providers=providers, torch_cuda=torch.version.cuda,
|
|
cpu_affinity=sorted(os.sched_getaffinity(0)), threads=4)
|
|
assert torch.version.cuda is None
|
|
(out/'setup.json').write_text(json.dumps(info, indent=2))
|
|
print(json.dumps({'ready': info}), flush=True)
|
|
|
|
rows = []
|
|
for seed in (42, 43):
|
|
for case in cases:
|
|
name = f"{case['id']}-{seed}"
|
|
signal.alarm(180)
|
|
first_clock[0] = None
|
|
begin = time.monotonic()
|
|
row = dict(arm=ARM, case_id=case['id'], seed=seed, name=name)
|
|
print(json.dumps({'start': name}), flush=True)
|
|
try:
|
|
parts = []
|
|
chunks = case['chunks']
|
|
chunk_metrics = []
|
|
if ARM == 'moss':
|
|
model.rng = np.random.default_rng(seed)
|
|
else:
|
|
model._seed = seed
|
|
for index, text in enumerate(chunks):
|
|
chunk_start = time.monotonic()
|
|
if ARM == 'moss':
|
|
result = model.synthesize(text=text, voice='Anna',
|
|
output_audio_path=out/'chunk.wav', do_sample=True,
|
|
sample_mode='fixed', streaming=True, max_new_frames=375,
|
|
voice_clone_max_text_tokens=75, enable_wetext=False,
|
|
enable_normalize_tts_text=False)
|
|
pcm = result['waveform']
|
|
if len(pcm.shape) == 2:
|
|
pcm = pcm.mean(axis=1)
|
|
rate = result['sample_rate']
|
|
frames = [len(x['generated_frames']) for x in result['chunk_results']]
|
|
chunk_metrics.append(dict(index=index, frames=frames,
|
|
capped=any(n >= 375 for n in frames)))
|
|
else:
|
|
p = []
|
|
for pcm_part in model.infer_stream(text, codes, ref_text):
|
|
if first_clock[0] is None:
|
|
first_clock[0] = time.monotonic()
|
|
p.append(np.asarray(pcm_part, dtype=np.float32))
|
|
pcm = np.concatenate(p) if p else np.zeros(0, dtype=np.float32)
|
|
rate = model.sample_rate
|
|
chunk_metrics.append(dict(index=index, audio_seconds=len(pcm)/rate))
|
|
assert np.isfinite(pcm).all() and len(pcm) > 0
|
|
parts.append(pcm)
|
|
chunk_metrics[-1]['seconds'] = time.monotonic() - chunk_start
|
|
pcm = np.concatenate(parts)
|
|
# Time includes phonemization, generation, complete codec and PCM serialization.
|
|
sf.write(out/(name+'.wav'), pcm, rate, subtype='PCM_16')
|
|
wall = time.monotonic()-begin
|
|
row.update(ok=True, seconds=wall, audio_seconds=len(pcm)/rate,
|
|
rtf=wall/(len(pcm)/rate), sample_rate=rate, first_native_audio_seconds=(
|
|
first_clock[0]-begin if first_clock[0] else None),
|
|
rms=float(np.sqrt(np.mean(pcm.astype(float)**2))),
|
|
peak=float(np.max(np.abs(pcm))), chunks=chunk_metrics,
|
|
peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
|
|
except Exception as exc:
|
|
row.update(ok=False, seconds=time.monotonic()-begin,
|
|
error_type=type(exc).__name__, error=str(exc)[:400])
|
|
finally:
|
|
signal.alarm(0)
|
|
rows.append(row)
|
|
(out/'results.json').write_text(json.dumps(rows, ensure_ascii=False, indent=2))
|
|
print(json.dumps(row), flush=True)
|
|
gc.collect()
|
|
(out/'chunk.wav').unlink(missing_ok=True)
|
|
if ARM != 'moss':
|
|
model.backbone.close()
|