123 lines
6.7 KiB
Python
123 lines
6.7 KiB
Python
"""Fixed six-case Audio8 CPU audition; no production API or settings writes."""
|
|
import os
|
|
os.environ.update(CUDA_VISIBLE_DEVICES='', HF_HUB_OFFLINE='1',
|
|
HF_HUB_DISABLE_TELEMETRY='1', OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='4')
|
|
from pathlib import Path
|
|
import hashlib
|
|
import json
|
|
import resource
|
|
import re
|
|
import sys
|
|
import threading
|
|
import time
|
|
import numpy as np
|
|
import soundfile as sf
|
|
|
|
ROOT = Path('/data/athena-audio8-cpu-20261027')
|
|
OUT = ROOT/'outputs';OUT.mkdir(mode=0o700,exist_ok=True)
|
|
sys.path.insert(0,str(ROOT/'source/onnx_runtime_0_1b_int8'))
|
|
from arktts_runtime import ArkTtsRuntime
|
|
cases = json.loads((ROOT/'cases.json').read_text())
|
|
def available():
|
|
return next(int(x.split()[1])*1024 for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemAvailable:'))
|
|
report = dict(phase='admission', runs=[], admission_available_bytes=available(),
|
|
cpu_threads=4,cpu_quota=400,precision='u8u8',codec_precision='fp16',
|
|
test_memory_max_bytes=3584*1024**2,host_reserve_bytes=2*1024**3,
|
|
seed=42,temperature=.7,top_p=.9,top_k=50,max_new_tokens=1024,
|
|
output_mode='official synthesize, one sentence per call, PCM concatenated',original_source_unmodified=True,
|
|
compatibility='Equivalent U8U8 MatMulInteger representation; see compatibility-manifest.json')
|
|
def save():
|
|
(ROOT/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
|
|
save()
|
|
if available() <= report['test_memory_max_bytes']+report['host_reserve_bytes']:
|
|
report.update(phase='deferred_memory',error='Own 3.5 GiB hard budget plus 2 GiB host reserve unavailable')
|
|
save()
|
|
raise RuntimeError(report['error'])
|
|
resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3))
|
|
stop = threading.Event();cancel = threading.Event()
|
|
minimum_available = [available()]
|
|
def monitor():
|
|
while not stop.wait(.25):
|
|
now = available();minimum_available[0] = min(minimum_available[0],now)
|
|
if now < 2*1024**3:cancel.set()
|
|
watch=threading.Thread(target=monitor,daemon=True);watch.start()
|
|
try:
|
|
report['phase']='loading';save()
|
|
start=time.monotonic()
|
|
runtime=ArkTtsRuntime(ROOT/'model-u8u8',ROOT/'voices',precision='u8u8',codec_precision='fp16',threads=4)
|
|
report['load_seconds']=time.monotonic()-start
|
|
report['providers']={name:getattr(runtime,name).get_providers() for name in ['slow','fast','decoder']}
|
|
assert all(p==['CPUExecutionProvider'] for p in report['providers'].values())
|
|
report['sample_rate']=rate=int(runtime.manifest['sample_rate'])
|
|
assert rate==44100
|
|
timings={name:dict(seconds=0.,calls=0) for name in ['slow','fast','decoder']}
|
|
class TimedSession:
|
|
def __init__(self,name,session):self.name=name;self.session=session
|
|
def __getattr__(self,name):return getattr(self.session,name)
|
|
def run(self,*args,**kwargs):
|
|
started=time.monotonic()
|
|
try:return self.session.run(*args,**kwargs)
|
|
finally:
|
|
timings[self.name]['seconds']+=time.monotonic()-started
|
|
timings[self.name]['calls']+=1
|
|
for name in timings:setattr(runtime,name,TimedSession(name,getattr(runtime,name)))
|
|
report['phase']='synthesis';save()
|
|
for label in 'ABC':
|
|
for case in cases:
|
|
if cancel.is_set():raise RuntimeError('Own memory/time guard fired')
|
|
name=case['id']+'-'+label
|
|
codes,meta=runtime.voices.load('anna-'+label)
|
|
prompt=runtime.prompt_builder.build(case['text'],meta['reference_text'],codes)
|
|
cap=min(1024,int(runtime.manifest['max_seq_len'])-prompt.shape[2])
|
|
row=dict(name=name,label=label,case=case['id'],seed=42,prompt_positions=int(prompt.shape[2]),frame_cap=cap)
|
|
sentences=re.split(r'(?<=[.!?])\s+',case['text'].strip())
|
|
assert ' '.join(sentences)==case['text']
|
|
row['sentence_count']=len(sentences)
|
|
timer=threading.Timer(180,cancel.set);timer.start()
|
|
for value in timings.values():value.update(seconds=0.,calls=0)
|
|
start=time.monotonic()
|
|
try:
|
|
parts=[];frame_counts=[];limit_hit=False;first_sentence=None
|
|
for text in sentences:
|
|
segment,generated=runtime.synthesize(text=text,voice='anna-'+label,
|
|
max_new_tokens=1024,temperature=.7,top_p=.9,top_k=50,seed=42,stop_event=cancel)
|
|
if first_sentence is None:first_sentence=time.monotonic()-start
|
|
assert len(segment) and np.isfinite(segment).all()
|
|
parts.append(segment)
|
|
frame_counts.append(int(generated.shape[1]))
|
|
segment_prompt=runtime.prompt_builder.build(text,meta['reference_text'],codes)
|
|
limit_hit=limit_hit or generated.shape[1]>=min(1024,int(runtime.manifest['max_seq_len'])-segment_prompt.shape[2])
|
|
if cancel.is_set():raise RuntimeError('Own memory/time guard fired')
|
|
pcm=np.concatenate(parts)
|
|
first=time.monotonic()-start
|
|
codeframes=sum(frame_counts)
|
|
if cancel.is_set():raise RuntimeError('Own memory/time guard fired')
|
|
assert len(pcm) and np.isfinite(pcm).all() and codeframes
|
|
target=OUT/(name+'.wav')
|
|
sf.write(target,pcm,rate,subtype='PCM_16')
|
|
elapsed=time.monotonic()-start
|
|
row.update(ok=True,file=target.name,generation_seconds=elapsed,
|
|
audio_seconds=len(pcm)/rate,rtf=elapsed/(len(pcm)/rate),
|
|
complete_audio_ready_seconds=first,codec_frames=codeframes,
|
|
first_complete_sentence_seconds=first_sentence,codec_frames_per_sentence=frame_counts,
|
|
token_limit_hit=bool(limit_hit),peak=float(np.max(np.abs(pcm))),
|
|
clipped_fraction=float(np.mean(np.abs(pcm)>=1)),
|
|
sha256=hashlib.sha256(target.read_bytes()).hexdigest(),
|
|
peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
|
onnx_run_times={k:dict(v) for k,v in timings.items()})
|
|
except Exception as exc:
|
|
row.update(ok=False,seconds=time.monotonic()-start,error_type=type(exc).__name__,error=str(exc)[:300])
|
|
finally:timer.cancel()
|
|
report['runs'].append(row)
|
|
report['minimum_available_bytes']=minimum_available[0]
|
|
save();print(json.dumps(row),flush=True)
|
|
if cancel.is_set():raise RuntimeError('Own memory/time guard fired')
|
|
report['phase']='complete'
|
|
except Exception as exc:
|
|
report.update(phase='failed',error_type=type(exc).__name__,error=str(exc)[:300])
|
|
raise
|
|
finally:
|
|
stop.set();watch.join(timeout=2)
|
|
report['minimum_available_bytes']=minimum_available[0]
|
|
save()
|