Measure Qwen Q4 fused attention idle and under Strata load
This commit is contained in:
1 parent
f4cc0d1931
commit
064794240a
6 files changed
+2553
No files matched your search
@@ -0,0 +1,142 @@
|
||||
# Qwen Q4 CPU fused-attention A/B · 27 October 2026
|
||||
|
||||
Michael authorized comparing Qwen Q4 with CPU Fused Attention off/on, using
|
||||
the same Anna text, measuring speed and local STT both idle and with Strata
|
||||
load. The currently published TTS must remain unchanged. No production CPU
|
||||
policy, profile, model, endpoint, service or Mac app is changed by this test.
|
||||
|
||||
## Results and decision
|
||||
|
||||
**No useful throughput improvement demonstrated; leave production unchanged.**
|
||||
All eight renders completed. Same setting produced byte-identical PCM in all
|
||||
four repeats/conditions; enabling Fused Attention changes the waveform and
|
||||
speech length, as allowed by the runtime's floating-point caveat.
|
||||
|
||||
| Strata condition | Fused | Audio | Mean generation | Generation range | Weighted RTF | First PCM mean |
|
||||
| --- | --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Idle | off | 14.88 s | 14.550 s | 14.508–14.592 s | 0.9778 | 0.340 s |
|
||||
| Idle | on | 15.52 s | 15.105 s | 14.928–15.282 s | 0.9733 | 0.297 s |
|
||||
| Generating | off | 14.88 s | 18.932 s | 18.906–18.957 s | 1.2723 | 0.441 s |
|
||||
| Generating | on | 15.52 s | 18.897 s | 18.583–19.212 s | 1.2176 | 0.367 s |
|
||||
|
||||
Enabling fused attention increases raw idle synthesis time by3.81%; under load
|
||||
raw time differs by only0.18%, well within the observed on-run spread. Audio
|
||||
is4.30% longer with fused attention. The resulting RTF reduction is0.47% idle
|
||||
and4.30% under load; do not call this a4.3% raw-compute acceleration. Neither
|
||||
loaded condition meets sustained realtime. First PCM arrives43–74ms earlier,
|
||||
but maximum estimated extra buffer after first PCM is0.077/0.181s idle and
|
||||
3.838/3.475s under load (off/on). This is no demonstrated fix for live playback.
|
||||
|
||||
Strata generated during92.9–95.7% of measured loaded synthesis. Fifteen bounded
|
||||
synthetic requests produced7,680 output tokens in total. No monitor/resource
|
||||
guard fired; lowest observed host available memory was5.94GiB. The complete
|
||||
benchmark transient unit ran3min15s, cgroup peak2.1GiB, no swap. Local STT unit
|
||||
then ran9.56s, peak518MiB. These are measured units, not a whole-system peak.
|
||||
|
||||
**STT: all8/8 WAVs match all36 words after case/punctuation normalization,
|
||||
zero word edits.** This does not establish Anna identity or naturalness.
|
||||
RMS quiet fractions are30.04% off /30.61% on; longest below-threshold interval
|
||||
1.44/1.62s. The longer on output is not merely a doubled silent tail, but audio
|
||||
is still different; listening samples are supplied rather than claiming parity.
|
||||
|
||||
Afterwards all six production file hashes match, original worker PIDs and Deck
|
||||
start time match, same Strata model remains loaded, and published TTS/STT remain
|
||||
resident. No restart or GPU unload occurred. Both owned test units are inactive.
|
||||
No setting was activated in production. Raw metrics and every synthetic STT
|
||||
result are retained alongside this report; WAVs stay outside Git.
|
||||
|
||||
## Protocol
|
||||
|
||||
Eight scored renders: 2 settings × 2 load conditions × 2 repeats. Order:
|
||||
off-A idle/load, on-A idle/load, on-B load/idle, off-B load/idle. Same source
|
||||
recording excerpt A and synthetic 36-word story from the earlier three-Anna
|
||||
comparison. One identical short warmup per new native process; initialization,
|
||||
voice extraction, queue waiting and WAV writing are outside generation timing.
|
||||
|
||||
Existing CPU-only `realtimetts-qwen-native-cpu==0.4.2`, ABI5,
|
||||
native `4d80a09` (27 September 2026), Qwen3-TTS 0.6B Base Q4_K_M and Q8_0
|
||||
codec. The pinned public model/codec hashes are checked before any render;
|
||||
see [the reference comparison](../qwen-reference-comparison-2026-10-27/README.md).
|
||||
No weights, packages or voice recordings are downloaded or uploaded here.
|
||||
|
||||
The only A/B change is `QWENTTS_CPU_FLASH_ATTN=0/1`, set before native context
|
||||
initialization in separate owned processes. Both retain `use_fa=True`, float32
|
||||
CPU attention, no FP16 clamp, two generation and two codec threads, two-frame
|
||||
streaming (160 ms), speaker-embedding-only Anna, seed42, temperature0.9,
|
||||
top-k50, top-p1, repetition penalty1.05, 1,024 output tokens per sentence and
|
||||
Q4 onset profile off. Positive codec threads already enable decoder overlap;
|
||||
this is **not** a first-time overlap test.
|
||||
|
||||
Native diagnostics in both on-worker logs confirm `CPU fused attention
|
||||
requested`; off logs do not. Different arithmetic order can change generated
|
||||
audio despite identical seeds. RTF and raw generation time must therefore be
|
||||
reported together; longer audio or added silence must not masquerade as speed.
|
||||
|
||||
Owned transient systemd cgroup: MemoryMax4GiB, swap0, CPUQuota400%, Nice10,
|
||||
AllowedCPUs2-5,8-11, PrivateDevices, NoNewPrivileges, ProtectSystem=strict,
|
||||
ProtectHome, writable own directory only, 25-minute lifetime. Child native
|
||||
workers additionally have an 8GiB address-space limit and 65-second cooperative
|
||||
per-utterance limit. The existing native Python3.13.5 venv under
|
||||
`/data/experiments/qwen06-q8-native-cpu-20261019/venv` supplies inference.
|
||||
|
||||
Host admission requires 6GiB available for the 4GiB own budget plus 2GiB reserve.
|
||||
Owned synthesis is cancelled if reserve falls below 2GiB or unrelated endpoint
|
||||
requests/failed monitoring are observed. Each scored run begins only after
|
||||
three zero-active-request status samples. These checks are not an atomic
|
||||
maintenance lock; the monitor stops only the owned test on observed overlap.
|
||||
|
||||
Load uses the **already resident, unchanged** Strata dual-slot profile through
|
||||
the ordinary authenticated endpoint. Sequential synthetic number-list requests,
|
||||
max512 output tokens, temperature0, reasoning none, at most eight per render.
|
||||
Speech starts after Strata's first content token. On speech completion no more
|
||||
load requests are started, and the current owned request drains to completion.
|
||||
Only token/timing counters are retained, not model response text. Endpoint keys
|
||||
are transferred on stdin from the existing authorized Hermes credential scope,
|
||||
kept in memory, never put in arguments, logs, files or Git. No VPN paths or
|
||||
containers are inspected. No productive request is cancelled or worker unloaded.
|
||||
|
||||
The status API intentionally exposes counts, not private worker state. An early
|
||||
read-only probe was corrected to use that documented schema before measurements.
|
||||
|
||||
## Evaluation and artifacts
|
||||
|
||||
`analyze.py` runs the existing local Parakeet Redux CPU CLI v0.6.1 only after all
|
||||
own Qwen workers exit. Same text for each WAV; case/punctuation normalization,
|
||||
word edits reported separately from human listening. Ten-millisecond RMS blocks
|
||||
below0.003 provide silence diagnostics, not a perceived-quality score.
|
||||
First PCM measures native arrival, not audible onset on a device. The estimated
|
||||
extra playout buffer excludes network, Hermes, phone and Mac scheduling.
|
||||
|
||||
Only two repeats per cell and one fixed short passage: no broad quality,
|
||||
latency, concurrency guarantee or statistical significance is established.
|
||||
Bounded Strata requests have gaps; measured overlap coverage is reported.
|
||||
Anna identity/naturalness and client playback require human listening.
|
||||
|
||||
Private root `/data/athena-qwen-fused-attention-20261027`, mode0700, contains
|
||||
owned logs and synthetic Anna WAVs. Raw reference audio stays in its existing
|
||||
private location; it is read for authorized cloning and not copied/exported.
|
||||
Only synthetic text/transcripts and sanitized technical metrics enter Git.
|
||||
This pilot installs no profile, service, native installer or backup dependency.
|
||||
|
||||
## Reproduction on native Debian
|
||||
|
||||
Use the existing pinned native CPU environment and verified public Q4/Q8 files
|
||||
from the linked recipe. Recheck actual state/source/model/reference paths,
|
||||
Python ABI, memory and physical-core topology before adapting the constants in
|
||||
`run.py`. Supply the normal Athena endpoint key as stdin JSON. Start the
|
||||
controller with host Python under the stated transient systemd limits; it starts
|
||||
only its own native children. The normal production LLM must already be resident.
|
||||
No container supplies inference libraries; today's exact Deck container start
|
||||
time is inspected only as a no-restart diagnostic. A native service deployment
|
||||
would compare its service invocation/start time instead. Full native restore is
|
||||
not claimed. Keep all user data and credentials outside the repository.
|
||||
|
||||
After successful completion run `analyze.py` in a separate bounded CPU unit.
|
||||
On error stop only the owned unit/children; production needs no rollback because
|
||||
no production settings change. Verify settings/reference/source hashes, existing
|
||||
worker identities, loaded LLM/TTS/STT and unchanged Deck start time after the test.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Official runtime CPU scheduling and F32 fused attention](https://github.com/KoljaB/RealtimeTTS/blob/master/docs/qwen-cpu-scheduling.md)
|
||||
- [CPU native 0.4.2 package, pinned engine and ABI](https://pypi.org/project/realtimetts-qwen-native-cpu/0.4.2/)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Local ASR and aggregate metrics after all own synthesis workers have exited."""
|
||||
from pathlib import Path
|
||||
from array import array
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import wave
|
||||
from run import ROOT,TEXT
|
||||
|
||||
data=json.loads((ROOT/'result.json').read_text())
|
||||
assert data['phase']=='complete' and len(data['runs'])==8,'Do not score a partial/failed matrix'
|
||||
base=Path('/opt/athena-deck-dev/runtime/state/parakeet-runtime/v0.6.1')
|
||||
cli=base/'runtime/parakeet-v0.6.1-bin-linux-cpu-x64/parakeet-cli'
|
||||
expected=re.findall(r'\w+',TEXT.casefold())
|
||||
|
||||
def edits(a,b):
|
||||
prev=list(range(len(b)+1))
|
||||
for i,x in enumerate(a,1):
|
||||
row=[i]
|
||||
for j,y in enumerate(b,1):row.append(min(row[-1]+1,prev[j]+1,prev[j-1]+(x!=y)))
|
||||
prev=row
|
||||
return prev[-1]
|
||||
|
||||
rows=[]
|
||||
for run in data['runs']:
|
||||
path=ROOT/'outputs'/(run['label']+'.wav')
|
||||
with wave.open(str(path),'rb') as wav:
|
||||
assert (wav.getframerate(),wav.getnchannels(),wav.getsampwidth())==(24000,1,2)
|
||||
duration=wav.getnframes()/wav.getframerate()
|
||||
pcm=array('h');pcm.frombytes(wav.readframes(wav.getnframes()))
|
||||
assert abs(duration-run['duration_seconds'])<1e-6
|
||||
# Ten-millisecond RMS below 0.003 is a diagnostic only, not an intelligibility score.
|
||||
quiet=longest=current=0;total=0
|
||||
for start in range(0,len(pcm),240):
|
||||
chunk=pcm[start:start+240];total+=1
|
||||
rms=math.sqrt(sum((x/32768)**2 for x in chunk)/len(chunk))
|
||||
if rms<.003:quiet+=1;current+=1;longest=max(longest,current)
|
||||
else:current=0
|
||||
started=time.monotonic()
|
||||
stt=subprocess.run([str(cli),'transcribe','--model',str(base/'redux-packed.gguf'),
|
||||
'--input',str(path),'--lang','de','--threads','2','--json'],
|
||||
text=True,capture_output=True,timeout=90)
|
||||
row=dict(label=run['label'],stt_exit=stt.returncode,stt_seconds=time.monotonic()-started,
|
||||
quiet_fraction=quiet/total,longest_quiet_seconds=longest*.01,
|
||||
wav_sha256=hashlib.file_digest(path.open('rb'),'sha256').hexdigest())
|
||||
if stt.returncode==0:
|
||||
text=json.loads(stt.stdout)['text'];actual=re.findall(r'\w+',text.casefold())
|
||||
row.update(recognized=text,reference_words=len(expected),word_edits=edits(expected,actual),
|
||||
exact_word_match=actual==expected)
|
||||
else:row['error']='Local ASR failed; do not score as success'
|
||||
rows.append(row)
|
||||
(ROOT/'transcriptions.json').write_text(json.dumps(rows,indent=2,ensure_ascii=False))
|
||||
print(json.dumps(row,ensure_ascii=False),flush=True)
|
||||
|
||||
groups=[]
|
||||
for scenario in ('idle','load'):
|
||||
for fused in (False,True):
|
||||
runs=[r for r in data['runs'] if r['scenario']==scenario and r['fused']==fused]
|
||||
transcripts=[r for r in rows if any(r['label']==x['label'] for x in runs)]
|
||||
assert len(runs)==len(transcripts)==2
|
||||
groups.append(dict(scenario=scenario,fused=fused,n=2,
|
||||
mean_generation_seconds=statistics.mean(r['generation_seconds'] for r in runs),
|
||||
mean_audio_seconds=statistics.mean(r['duration_seconds'] for r in runs),
|
||||
weighted_rtf=sum(r['generation_seconds'] for r in runs)/sum(r['duration_seconds'] for r in runs),
|
||||
mean_first_pcm_seconds=statistics.mean(r['first_pcm_seconds'] for r in runs),
|
||||
generation_range=[min(r['generation_seconds'] for r in runs),max(r['generation_seconds'] for r in runs)],
|
||||
maximum_extra_buffer_seconds=max(r['extra_buffer_after_first_pcm_seconds'] for r in runs),
|
||||
llm_coverage_range=[min(r['llm_coverage'] for r in runs),max(r['llm_coverage'] for r in runs)],
|
||||
asr_successful=sum(r['stt_exit']==0 for r in transcripts),
|
||||
total_asr_word_edits=sum(r.get('word_edits',0) for r in transcripts),
|
||||
asr_exact_runs=sum(r.get('exact_word_match',False) for r in transcripts),
|
||||
longest_quiet_seconds=max(r['longest_quiet_seconds'] for r in transcripts)))
|
||||
|
||||
summary=dict(groups=groups,comparisons=[],preservation=data['preservation'],
|
||||
within_mode_pcm_consistent={str(fused):len({r['pcm_sha256'] for r in data['runs'] if r['fused']==fused})==1
|
||||
for fused in (False,True)},
|
||||
limitations=['one fixed synthetic passage, two repetitions per cell',
|
||||
'ASR proxy; human Anna identity/naturalness and native-client playback not established',
|
||||
'LLM load is bounded synthetic generation with gaps between requests'])
|
||||
for scenario in ('idle','load'):
|
||||
a=next(r for r in groups if r['scenario']==scenario and not r['fused'])
|
||||
b=next(r for r in groups if r['scenario']==scenario and r['fused'])
|
||||
summary['comparisons'].append(dict(scenario=scenario,
|
||||
reduction_in_mean_generation_percent=100*(1-b['mean_generation_seconds']/a['mean_generation_seconds']),
|
||||
reduction_in_weighted_rtf_percent=100*(1-b['weighted_rtf']/a['weighted_rtf']),
|
||||
matched_pcm_across_fused_modes=all(
|
||||
next(r for r in data['runs'] if r['scenario']==scenario and not r['fused'] and r['repetition']==rep)['pcm_sha256']==
|
||||
next(r for r in data['runs'] if r['scenario']==scenario and r['fused'] and r['repetition']==rep)['pcm_sha256']
|
||||
for rep in ('a','b'))))
|
||||
(ROOT/'summary.json').write_text(json.dumps(summary,indent=2,ensure_ascii=False))
|
||||
print(json.dumps(summary,ensure_ascii=False),flush=True)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,287 @@
|
||||
"""Isolated native Qwen Q4 F32 fused-attention A/B; production stays unchanged.
|
||||
|
||||
Controller: host Python, Athena API credential supplied on stdin only.
|
||||
Workers: existing CPU-only native venv, own transient cgroup, no listeners.
|
||||
Only synthetic test text/responses/ASR are recorded. Never execute model output.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import resource
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import wave
|
||||
|
||||
ROOT=Path('/data/athena-qwen-fused-attention-20261027')
|
||||
STATE=Path('/opt/athena-deck-dev/runtime/state')
|
||||
SOURCE=Path('/opt/athena-deck-dev/source')
|
||||
PYTHON=Path('/data/experiments/qwen06-q8-native-cpu-20261019/venv/bin/python')
|
||||
REFERENCE=Path('/data/athena-qwen-references-20261027/references/anna-reference-A-24k.wav')
|
||||
MODEL=STATE/'models/257b3c90803fb36e1bdc2567ae1164123887c2a3cdcbca82c0cfad6f071196ac/model.gguf'
|
||||
CODEC=STATE/'models/10d60d7e3bdfce97104c166362546fa115dfdb510c1c9b60b99ad8c9da47e40b/model.gguf'
|
||||
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.')
|
||||
CPUS={2,3,4,5,8,9,10,11}
|
||||
FILES=[STATE/n for n in ('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json')]
|
||||
FILES += [STATE/'speech-voices/Anna/reference.wav',SOURCE/'qwen_native_worker.py']
|
||||
|
||||
def available():
|
||||
return next(int(s.split()[1])*1024 for s in Path('/proc/meminfo').read_text().splitlines()
|
||||
if s.startswith('MemAvailable:'))
|
||||
|
||||
def hashes():
|
||||
return {str(p):hashlib.file_digest(p.open('rb'),'sha256').hexdigest() for p in FILES}
|
||||
|
||||
def production_pids():
|
||||
found={'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'):found['strata'].append(int(p.name))
|
||||
if any(a.endswith(b'/articulino_worker.py') for a in args):found['articulino'].append(int(p.name))
|
||||
if any(a.endswith(b'/qwen_native_worker.py') for a in args):found['qwen_tts'].append(int(p.name))
|
||||
return found
|
||||
|
||||
def atomic(path,data):
|
||||
tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(data,indent=2,ensure_ascii=False));tmp.replace(path)
|
||||
|
||||
def worker(fused):
|
||||
# Set this before the native context is initialized, independently of the
|
||||
# unchanged production CPU policy. CPU codec overlap stays enabled in both.
|
||||
os.environ.update(CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',
|
||||
HF_HUB_DISABLE_TELEMETRY='1',OMP_NUM_THREADS='2',OPENBLAS_NUM_THREADS='1',
|
||||
QWENTTS_CPU_FLASH_ATTN='1' if fused else '0')
|
||||
os.sched_setaffinity(0,CPUS)
|
||||
resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3))
|
||||
protocol=os.fdopen(os.dup(1),'w',buffering=1);os.dup2(2,1)
|
||||
def emit(obj):protocol.write(json.dumps(obj)+'\n');protocol.flush()
|
||||
import importlib.metadata
|
||||
import numpy as np
|
||||
import qwentts_cpp_cpu as q
|
||||
from contextlib import closing
|
||||
sys.path.insert(0,str(SOURCE))
|
||||
from tts_worker import spoken_chunks
|
||||
assert q.CPU_ONLY is True and q.QT_ABI_VERSION==5
|
||||
assert importlib.metadata.version('realtimetts-qwen-native-cpu')=='0.4.2'
|
||||
started=time.monotonic()
|
||||
engine=q.QwenTTS(str(MODEL),str(CODEC),cpu_threads=2,cpu_codec_threads=2,
|
||||
cpu_stream_frames=2,clamp_fp16=False,use_fa=True)
|
||||
load_seconds=time.monotonic()-started
|
||||
with wave.open(str(REFERENCE),'rb') as wav:
|
||||
assert (wav.getframerate(),wav.getnchannels(),wav.getsampwidth())==(24000,1,2)
|
||||
samples=np.frombuffer(wav.readframes(wav.getnframes()),dtype='<i2').astype(np.float32)/32768
|
||||
started=time.monotonic();voice=engine.extract_voice_ref(samples).ref_spk_emb
|
||||
emit(dict(event='ready',fused=fused,load_seconds=load_seconds,
|
||||
voice_seconds=time.monotonic()-started,native_version=q.QwenLibrary().version()))
|
||||
try:
|
||||
for line in sys.stdin:
|
||||
request=json.loads(line)
|
||||
if request['action']=='exit':break
|
||||
label=request['label'];assert re.fullmatch(r'(off|on)-(idle|load|warmup)-[ab]',label)
|
||||
cancel=threading.Event();done=threading.Event()
|
||||
def monitor():
|
||||
end=time.monotonic()+65
|
||||
while not done.wait(.1):
|
||||
if (ROOT/'cancel-own').exists() or available()<2*1024**3 or time.monotonic()>end:
|
||||
cancel.set();return
|
||||
watchdog=threading.Thread(target=monitor,daemon=True);watchdog.start()
|
||||
first=last=None;max_gap=reserve=0.;blocks=[];dur=0.;profiles=[]
|
||||
started=time.monotonic();emit(dict(event='started',at=started))
|
||||
try:
|
||||
text='Die Sprachausgabe ist bereit.' if 'warmup' in label else TEXT
|
||||
for sentence in spoken_chunks(dict(text=text,language='German')):
|
||||
with closing(engine.stream(text=sentence,lang='german',ref_spk_emb=voice,
|
||||
seed=42,do_sample=True,temperature=.9,top_k=50,top_p=1.,
|
||||
repetition_penalty=1.05,max_new_tokens=1024,onset_silence_profile='off',
|
||||
cancel_event=cancel)) as stream:
|
||||
for block,rate in stream:
|
||||
if cancel.is_set():raise RuntimeError('Own cancellation/deadline/memory guard')
|
||||
assert rate==24000 and np.isfinite(block).all()
|
||||
now=time.monotonic()
|
||||
if first is None:first=now
|
||||
else:max_gap=max(max_gap,now-last);reserve=max(reserve,now-first-dur)
|
||||
blocks.append(np.asarray(block).copy());dur+=len(block)/rate;last=now
|
||||
assert not engine.last_stream_profile.get('producer_alive_after_close')
|
||||
profiles.append({k:v for k,v in engine.last_stream_profile.items() if type(v) in (int,float,bool)})
|
||||
ended=time.monotonic()
|
||||
if cancel.is_set():raise RuntimeError('Own synthesis stopped')
|
||||
assert blocks and first is not None
|
||||
audio=np.concatenate(blocks)
|
||||
pcm=np.rint(np.clip(audio,-1,1)*32767).astype('<i2')
|
||||
path=ROOT/'outputs'/(label+'.wav')
|
||||
if 'warmup' not in label:
|
||||
with wave.open(str(path),'wb') as wav:
|
||||
wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(24000);wav.writeframes(pcm.tobytes())
|
||||
emit(dict(event='result',label=label,fused=fused,started=started,ended=ended,
|
||||
generation_seconds=ended-started,duration_seconds=dur,rtf=(ended-started)/dur,
|
||||
first_pcm_seconds=first-started,packets=len(blocks),longest_packet_gap_seconds=max_gap,
|
||||
extra_buffer_after_first_pcm_seconds=max(0.,reserve),peak=float(np.max(np.abs(audio))),
|
||||
clipped_fraction=float(np.mean(np.abs(audio)>=1)),rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
||||
pcm_sha256=hashlib.sha256(pcm.tobytes()).hexdigest(),native_profiles=profiles))
|
||||
finally:done.set();watchdog.join(2)
|
||||
finally:engine.close()
|
||||
|
||||
def controller(key,probe=False):
|
||||
os.umask(0o077)
|
||||
def api(path,body=None,timeout=10):
|
||||
port=8120 if path.startswith('/v1/') else 8108
|
||||
req=urllib.request.Request(f'http://127.0.0.1:{port}'+path,
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
|
||||
return urllib.request.urlopen(req,timeout=timeout)
|
||||
def status():
|
||||
with api('/api/v1/status') as response:return json.load(response)['endpoint']
|
||||
initial=status()
|
||||
summary=dict(active_requests=initial['active_requests'],llm_loaded=initial['counts']['llm']['loaded'],
|
||||
counts=initial['counts'],available_gib=available()/2**30)
|
||||
if probe:print(json.dumps(summary));return
|
||||
assert initial['counts']['llm']['loaded'],'No loaded production LLM; leave it untouched'
|
||||
assert available()>=6*1024**3,'Own 4GiB memory budget plus 2GiB host reserve unavailable'
|
||||
ROOT.mkdir(mode=0o700,exist_ok=True);(ROOT/'outputs').mkdir(mode=0o700,exist_ok=True)
|
||||
(ROOT/'logs').mkdir(mode=0o700,exist_ok=True)
|
||||
assert not (ROOT/'result.json').exists(),'Refuse to overwrite a completed/partial A/B'
|
||||
before=hashes()
|
||||
pids_before=production_pids()
|
||||
assert len(pids_before['strata'])==1,'Expected one existing production Strata engine'
|
||||
started_at=subprocess.check_output(['docker','inspect','--format','{{.State.StartedAt}}','athena-deck-dev'],text=True).strip()
|
||||
model_name=json.loads((STATE/'strata-worker/worker.json').read_text())['model_name']
|
||||
assert model_name=='flash-next-strata-iq3-dual'
|
||||
plan=json.loads((STATE/'cpu-partition.json').read_text())
|
||||
assert set(plan['qwen_tts'])==CPUS and plan['qwen_generation_threads']==plan['qwen_codec_threads']==2
|
||||
for p,digest in ((MODEL,'4b468ec7b1f62b90ef4ca316c0aa57deadfd54b2cf9651703ea753cedaf04226'),
|
||||
(CODEC,'1883beeed99348fc35e23dd225e9082f93f6f8c109330a33d935baa8acdbfd94')):
|
||||
assert hashlib.file_digest(p.open('rb'),'sha256').hexdigest()==digest
|
||||
result=dict(phase='waiting_idle',runs=[],warmups=[],protocol=dict(text=TEXT,reference='existing Anna excerpt A',
|
||||
model='Qwen3-TTS 0.6B Base Q4_K_M',codec='Q8_0',native='0.4.2',seed=42,threads=2,codec_threads=2,
|
||||
affinity=sorted(CPUS),stream_frames=2,do_sample=True,temperature=.9,top_k=50,top_p=1.,
|
||||
repetition_penalty=1.05,onset_profile='off',clamp_fp16=False,repetitions_per_cell=2,
|
||||
order=['off-a idle/load','on-a idle/load','on-b load/idle','off-b load/idle'],
|
||||
memory_max_gib=4,host_reserve_gib=2,cpu_quota=400,production_changes=False),initial=summary)
|
||||
def save(phase):
|
||||
result['phase']=phase;atomic(ROOT/'result.json',result);print(phase,flush=True)
|
||||
def idle():
|
||||
clean=0;end=time.monotonic()+300
|
||||
while time.monotonic()<end:
|
||||
if status()['active_requests']==0:
|
||||
clean+=1
|
||||
if clean>=3:return
|
||||
else:clean=0
|
||||
time.sleep(1)
|
||||
raise RuntimeError('Productive requests did not finish; no interruption')
|
||||
child=None;log=None
|
||||
try:
|
||||
for fused,rep,scenarios in ((False,'a',('idle','load')),(True,'a',('idle','load')),
|
||||
(True,'b',('load','idle')),(False,'b',('load','idle'))):
|
||||
save('waiting_idle');idle()
|
||||
label=('on' if fused else 'off')+'-'+rep
|
||||
events=queue.Queue()
|
||||
log=(ROOT/'logs'/(label+'.log')).open('w')
|
||||
child=subprocess.Popen([str(PYTHON),str(Path(__file__).resolve()),'--worker','1' if fused else '0'],
|
||||
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,text=True,bufsize=1,start_new_session=True)
|
||||
def reader(proc):
|
||||
try:
|
||||
for line in proc.stdout:events.put(json.loads(line))
|
||||
finally:events.put(None)
|
||||
threading.Thread(target=reader,args=(child,),daemon=True).start()
|
||||
def event(kind,timeout=90):
|
||||
obj=events.get(timeout=timeout)
|
||||
if obj is None or obj.get('event')!=kind:raise RuntimeError('Own worker protocol failure')
|
||||
return obj
|
||||
def send(obj):child.stdin.write(json.dumps(obj)+'\n');child.stdin.flush()
|
||||
setup=event('ready');print(json.dumps(dict(phase='worker_ready',arm=label,setup=setup)),flush=True)
|
||||
send(dict(action='speak',label=('on' if fused else 'off')+'-warmup-'+rep))
|
||||
event('started');result['warmups'].append(event('result'));save('warmed_'+label)
|
||||
for scenario in scenarios:
|
||||
idle();stop=threading.Event();own_request=threading.Event();ready=threading.Event()
|
||||
health={};rounds=[];minimum=[available()]
|
||||
def monitor():
|
||||
excess=0
|
||||
while not stop.wait(.3):
|
||||
try:
|
||||
minimum[0]=min(minimum[0],available())
|
||||
excess=excess+1 if status()['active_requests']>int(own_request.is_set()) else 0
|
||||
if excess>=2:health['external_request']=True
|
||||
if minimum[0]<2*1024**3:health['low_memory']=True
|
||||
if health:(ROOT/'cancel-own').touch()
|
||||
except Exception:
|
||||
health['monitor_failed']=True;(ROOT/'cancel-own').touch()
|
||||
def load():
|
||||
try:
|
||||
for number in range(8):
|
||||
if stop.is_set():return
|
||||
body=dict(model=model_name,messages=[dict(role='user',content=
|
||||
'Zähle alle ganzen Zahlen von eins bis fünfhundert vollständig in deutschen Wörtern auf. '
|
||||
'Lasse keine aus, benutze keine Abkürzung und keine Erklärung. Runde '+str(number+1)+'.')],
|
||||
max_tokens=512,reasoning_effort='none',temperature=0,stream=True,stream_options={'include_usage':True})
|
||||
own_request.set();start=time.monotonic();first=None;tokens=0;timings={}
|
||||
with api('/v1/chat/completions',body,timeout=90) as response:
|
||||
for line in response:
|
||||
if not line.startswith(b'data: ') or line.strip()==b'data: [DONE]':continue
|
||||
data=json.loads(line[6:]);tokens=(data.get('usage') or {}).get('completion_tokens',tokens)
|
||||
if data.get('timings'):timings=data['timings']
|
||||
if first is None and any(c.get('delta',{}).get('content') for c in data.get('choices',[])):
|
||||
first=time.monotonic();ready.set()
|
||||
rounds.append(dict(start=start,first=first,end=time.monotonic(),completion_tokens=tokens,timings=timings))
|
||||
own_request.clear()
|
||||
if not stop.is_set():raise RuntimeError('Synthetic load budget exhausted')
|
||||
except Exception:
|
||||
own_request.clear();health['load_failed']=True;ready.set();(ROOT/'cancel-own').touch()
|
||||
watch=threading.Thread(target=monitor,daemon=True);watch.start()
|
||||
load_thread=None
|
||||
try:
|
||||
if scenario=='load':
|
||||
load_thread=threading.Thread(target=load,daemon=True);load_thread.start()
|
||||
assert ready.wait(95) and not health,'Synthetic Strata load failed to start'
|
||||
name=('on' if fused else 'off')+'-'+scenario+'-'+rep
|
||||
save('measuring_'+name);send(dict(action='speak',label=name))
|
||||
event('started');row=event('result',timeout=80)
|
||||
finally:
|
||||
stop.set();watch.join(15)
|
||||
if load_thread:
|
||||
load_thread.join(100)
|
||||
if load_thread.is_alive():raise RuntimeError('Own bounded Strata request did not drain')
|
||||
overlap=sum(max(0.,min(r['end'],row['ended'])-max(r['first'] or r['end'],row['started'])) for r in rounds)
|
||||
row.update(scenario=scenario,repetition=rep,health=health,minimum_host_available_gib=minimum[0]/2**30,
|
||||
llm_coverage=overlap/row['generation_seconds'],llm_rounds=rounds)
|
||||
result['runs'].append(row);save('finished_'+name)
|
||||
print(json.dumps({k:row[k] for k in ('label','generation_seconds','duration_seconds','rtf','llm_coverage','health')}),flush=True)
|
||||
assert not health,'External request or resource/load guard; only own test stopped'
|
||||
send(dict(action='exit'));child.stdin.close();child.wait(20);assert child.returncode==0
|
||||
child=None;log.close();log=None
|
||||
save('complete')
|
||||
except Exception as exc:
|
||||
result['error_type']=type(exc).__name__;result['error']=str(exc)[:180];save('failed')
|
||||
raise
|
||||
finally:
|
||||
if child and child.poll() is None:
|
||||
(ROOT/'cancel-own').touch()
|
||||
try:
|
||||
child.stdin.write('{"action":"exit"}\n');child.stdin.flush();child.wait(15)
|
||||
except (BrokenPipeError,subprocess.TimeoutExpired):
|
||||
os.killpg(child.pid,signal.SIGTERM)
|
||||
try:child.wait(10)
|
||||
except subprocess.TimeoutExpired:os.killpg(child.pid,signal.SIGKILL);child.wait()
|
||||
if log:log.close()
|
||||
after=status();result['preservation']=dict(
|
||||
files_unchanged={Path(k).name:hashes()[k]==v for k,v in before.items()},
|
||||
deck_not_restarted=subprocess.check_output(['docker','inspect','--format','{{.State.StartedAt}}',
|
||||
'athena-deck-dev'],text=True).strip()==started_at,
|
||||
worker_ready=after['counts']['llm']['loaded'],
|
||||
same_chat_model=json.loads((STATE/'strata-worker/worker.json').read_text())['model_name']==model_name,
|
||||
production_worker_pids_unchanged=production_pids()==pids_before,
|
||||
tts_stt_counts=after['counts'],production_tts_changed=False)
|
||||
atomic(ROOT/'result.json',result)
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>1 and sys.argv[1]=='--worker':worker(sys.argv[2]=='1')
|
||||
else:controller(json.load(sys.stdin)['key'],probe='--probe' in sys.argv)
|
||||
@@ -0,0 +1,168 @@
|
||||
{
|
||||
"groups": [
|
||||
{
|
||||
"scenario": "idle",
|
||||
"fused": false,
|
||||
"n": 2,
|
||||
"mean_generation_seconds": 14.549943562495173,
|
||||
"mean_audio_seconds": 14.88000000000001,
|
||||
"weighted_rtf": 0.9778187878020943,
|
||||
"mean_first_pcm_seconds": 0.3396360935003031,
|
||||
"generation_range": [
|
||||
14.507760774999042,
|
||||
14.592126349991304
|
||||
],
|
||||
"maximum_extra_buffer_seconds": 0.07715133499179501,
|
||||
"llm_coverage_range": [
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"asr_successful": 2,
|
||||
"total_asr_word_edits": 0,
|
||||
"asr_exact_runs": 2,
|
||||
"longest_quiet_seconds": 1.44
|
||||
},
|
||||
{
|
||||
"scenario": "idle",
|
||||
"fused": true,
|
||||
"n": 2,
|
||||
"mean_generation_seconds": 15.105022294992523,
|
||||
"mean_audio_seconds": 15.52000000000001,
|
||||
"weighted_rtf": 0.9732617458113733,
|
||||
"mean_first_pcm_seconds": 0.29678761649120133,
|
||||
"generation_range": [
|
||||
14.928049911992275,
|
||||
15.28199467799277
|
||||
],
|
||||
"maximum_extra_buffer_seconds": 0.18068198799737667,
|
||||
"llm_coverage_range": [
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"asr_successful": 2,
|
||||
"total_asr_word_edits": 0,
|
||||
"asr_exact_runs": 2,
|
||||
"longest_quiet_seconds": 1.62
|
||||
},
|
||||
{
|
||||
"scenario": "load",
|
||||
"fused": false,
|
||||
"n": 2,
|
||||
"mean_generation_seconds": 18.931868446496082,
|
||||
"mean_audio_seconds": 14.88000000000001,
|
||||
"weighted_rtf": 1.2723029869957037,
|
||||
"mean_first_pcm_seconds": 0.44143865449586883,
|
||||
"generation_range": [
|
||||
18.906297855995945,
|
||||
18.95743903699622
|
||||
],
|
||||
"maximum_extra_buffer_seconds": 3.837839022992984,
|
||||
"llm_coverage_range": [
|
||||
0.9290130681191969,
|
||||
0.9530471220680273
|
||||
],
|
||||
"asr_successful": 2,
|
||||
"total_asr_word_edits": 0,
|
||||
"asr_exact_runs": 2,
|
||||
"longest_quiet_seconds": 1.44
|
||||
},
|
||||
{
|
||||
"scenario": "load",
|
||||
"fused": true,
|
||||
"n": 2,
|
||||
"mean_generation_seconds": 18.897186325499206,
|
||||
"mean_audio_seconds": 15.52000000000001,
|
||||
"weighted_rtf": 1.2176022116945358,
|
||||
"mean_first_pcm_seconds": 0.36744748199998867,
|
||||
"generation_range": [
|
||||
18.582593213999644,
|
||||
19.211779436998768
|
||||
],
|
||||
"maximum_extra_buffer_seconds": 3.474652216011881,
|
||||
"llm_coverage_range": [
|
||||
0.9304964217796763,
|
||||
0.9573140039586553
|
||||
],
|
||||
"asr_successful": 2,
|
||||
"total_asr_word_edits": 0,
|
||||
"asr_exact_runs": 2,
|
||||
"longest_quiet_seconds": 1.62
|
||||
}
|
||||
],
|
||||
"comparisons": [
|
||||
{
|
||||
"scenario": "idle",
|
||||
"reduction_in_mean_generation_percent": -3.814988904342931,
|
||||
"reduction_in_weighted_rtf_percent": 0.46604156593924584,
|
||||
"matched_pcm_across_fused_modes": false
|
||||
},
|
||||
{
|
||||
"scenario": "load",
|
||||
"reduction_in_mean_generation_percent": 0.18319439042634444,
|
||||
"reduction_in_weighted_rtf_percent": 4.2993513227798985,
|
||||
"matched_pcm_across_fused_modes": false
|
||||
}
|
||||
],
|
||||
"preservation": {
|
||||
"files_unchanged": {
|
||||
"profiles.json": true,
|
||||
"endpoint.json": true,
|
||||
"audio-policy.json": true,
|
||||
"cpu-partition.json": true,
|
||||
"reference.wav": true,
|
||||
"qwen_native_worker.py": true
|
||||
},
|
||||
"deck_not_restarted": true,
|
||||
"worker_ready": true,
|
||||
"same_chat_model": true,
|
||||
"production_worker_pids_unchanged": true,
|
||||
"tts_stt_counts": {
|
||||
"llm": {
|
||||
"enabled": 12,
|
||||
"available": 12,
|
||||
"loaded": true,
|
||||
"supported": true
|
||||
},
|
||||
"image": {
|
||||
"enabled": 1,
|
||||
"available": 1,
|
||||
"loaded": false,
|
||||
"supported": true
|
||||
},
|
||||
"tts": {
|
||||
"enabled": 1,
|
||||
"available": 1,
|
||||
"loaded": true,
|
||||
"supported": true
|
||||
},
|
||||
"stt": {
|
||||
"enabled": 1,
|
||||
"available": 1,
|
||||
"loaded": true,
|
||||
"supported": true
|
||||
},
|
||||
"music": {
|
||||
"enabled": 2,
|
||||
"available": 2,
|
||||
"loaded": false,
|
||||
"supported": true
|
||||
},
|
||||
"voice": {
|
||||
"enabled": 1,
|
||||
"available": 1,
|
||||
"loaded": false,
|
||||
"supported": true
|
||||
}
|
||||
},
|
||||
"production_tts_changed": false
|
||||
},
|
||||
"within_mode_pcm_consistent": {
|
||||
"False": true,
|
||||
"True": true
|
||||
},
|
||||
"limitations": [
|
||||
"one fixed synthetic passage, two repetitions per cell",
|
||||
"ASR proxy; human Anna identity/naturalness and native-client playback not established",
|
||||
"LLM load is bounded synthetic generation with gaps between requests"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
[
|
||||
{
|
||||
"label": "off-idle-a",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.1424123509932542,
|
||||
"quiet_fraction": 0.3004032258064516,
|
||||
"longest_quiet_seconds": 1.44,
|
||||
"wav_sha256": "006a1e479530a854539a2f34fdb9fbd23b6871186370e7a21bf8fb45b43627f1",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "off-load-a",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.1255118980043335,
|
||||
"quiet_fraction": 0.3004032258064516,
|
||||
"longest_quiet_seconds": 1.44,
|
||||
"wav_sha256": "006a1e479530a854539a2f34fdb9fbd23b6871186370e7a21bf8fb45b43627f1",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "on-idle-a",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.165787531004753,
|
||||
"quiet_fraction": 0.30605670103092786,
|
||||
"longest_quiet_seconds": 1.62,
|
||||
"wav_sha256": "1c4da1969252ebc1608be09d1ef15122380a36283d2bb3131d2fda030a247a01",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "on-load-a",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.173727831002907,
|
||||
"quiet_fraction": 0.30605670103092786,
|
||||
"longest_quiet_seconds": 1.62,
|
||||
"wav_sha256": "1c4da1969252ebc1608be09d1ef15122380a36283d2bb3131d2fda030a247a01",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "on-load-b",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.1771385519969044,
|
||||
"quiet_fraction": 0.30605670103092786,
|
||||
"longest_quiet_seconds": 1.62,
|
||||
"wav_sha256": "1c4da1969252ebc1608be09d1ef15122380a36283d2bb3131d2fda030a247a01",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "on-idle-b",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.1703413509967504,
|
||||
"quiet_fraction": 0.30605670103092786,
|
||||
"longest_quiet_seconds": 1.62,
|
||||
"wav_sha256": "1c4da1969252ebc1608be09d1ef15122380a36283d2bb3131d2fda030a247a01",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "off-load-b",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.1537215860007564,
|
||||
"quiet_fraction": 0.3004032258064516,
|
||||
"longest_quiet_seconds": 1.44,
|
||||
"wav_sha256": "006a1e479530a854539a2f34fdb9fbd23b6871186370e7a21bf8fb45b43627f1",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
},
|
||||
{
|
||||
"label": "off-idle-b",
|
||||
"stt_exit": 0,
|
||||
"stt_seconds": 1.154634927996085,
|
||||
"quiet_fraction": 0.3004032258064516,
|
||||
"longest_quiet_seconds": 1.44,
|
||||
"wav_sha256": "006a1e479530a854539a2f34fdb9fbd23b6871186370e7a21bf8fb45b43627f1",
|
||||
"recognized": "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.",
|
||||
"reference_words": 36,
|
||||
"word_edits": 0,
|
||||
"exact_word_match": true
|
||||
}
|
||||
]
|
||||
Reference in new issue
Block a user