Document native Qwen 0.6B Q8 CPU realtime measurements

This commit is contained in:
Mikei386 committed 2026-10-19 11:22:00 +02:00
1 parent 879131ce2b
commit bfd21c8548
12 files changed
+12693

No files matched your search

@@ -0,0 +1,116 @@
# Native Qwen3-TTS 0.6B Q8 CPU streaming — 19 October 2026
User requested a bounded CPU-only realtime feasibility test on Athena while
Strata remains loaded. No production profile, endpoint, GPU reservation, Hermes
setting or service startup configuration was changed. No LLM request was made.
## Environment and scope
- Athena: Ryzen 5 5600, 6 cores/12 threads, approximately 47 GiB host RAM.
- Existing Strata GPU allocations: approximately 11293 MiB RTX 3060 and
15410–15418 MiB RTX 5080. Strata remained loaded; this was **not** a controlled
concurrent LLM generation benchmark. GPU utilization snapshots were zero.
- Fresh native venv under `/data/experiments/qwen06-q8-native-cpu-20261019`;
host Python 3.13.5, `realtimetts-qwen-native-cpu==0.4.2`, ABI 5,
`qwentts_cpp_cpu.CPU_ONLY is True`. Package versions: `requirements.lock`.
- Directly exercises the public native API used by RealtimeTTS QwenCpuEngine;
no PyTorch, no wrapper server, no browser/device playback in this benchmark.
- Each transient systemd process: `MemoryMax=6G`, `MemorySwapMax=0`, `Nice=10`,
`PrivateDevices=yes`, `NoNewPrivileges=yes`, `RuntimeMaxSec=900`.
The first two thread comparisons use `CPUQuota=400%`; the final comparisons
use `600%`. CPU quota counts logical CPU time, not a physical-core reservation.
- CPU flash attention enabled; one or two codec frames per streamed block; speaker-only
cached Anna reference; fixed seed 42, greedy generation; max 768 audio tokens.
- Existing private Anna reference was copied only into the private test folder.
It and cached voice features are **not** included in Git. The generated text
is synthetic and present in `benchmark.py`.
## Public model assets
Native resolver selected `Serveurperso/Qwen3-TTS-GGUF`, pinned here to revision
`b7ee2e8c7459c3bea99da23e3d178125a7d1713c`, converted from Qwen's 0.6B Base.
The original download did not use any implicit Hugging Face credential.
| File | Bytes | SHA256 |
|---|---:|---|
| qwen-talker-0.6b-base-Q8_0.gguf | 992615488 | d54dbaf10591421fa764ed630d764efa717ae40cd959bd48c66d4eb1af226426 |
| qwen-tokenizer-12hz-Q8_0.gguf | 291150624 | 1883beeed99348fc35e23dd225e9082f93f6f8c109330a33d935baa8acdbfd94 |
## Measurements
| CPU quota | Generation/codec threads | Block size | Short RTF (two runs) | Technical RTF |
|---:|---:|---:|---:|---:|
| 400% | 2 / 2 | 80 ms | 1.399 / 1.320 | 1.298 |
| 400% | 4 / 2 | 80 ms | 1.271 / 1.265 | 1.270 |
| 600% | 4 / 2 | 80 ms | 1.090 / 1.085 | 1.078 |
| 600% | 4 / 4 | 80 ms | 1.019 / 1.022 | 1.032 |
| 600% | 4 / 4 | 160 ms | **0.948 / 0.955** | **0.945** |
The last configuration generated 6.32 s short audio in 5.993 / 6.033 s, with
first PCM at 0.281 / 0.286 s. Technical audio: 19.28 s in 18.211 s, first PCM
0.481 s. Estimated additional playout reserve: 62 / 65 ms for short text,
97 ms technical. These do not include client/network jitter. A conventional
160 ms startup buffer covers these recorded deficits, but actual Hermes
playback was **not** tested. Cold/warmup utterance remained slower (RTF 1.133).
Peak process RSS was 4024128 KiB, approximately 3.84 GiB. No TTS GPU allocation.
**Conclusion:** marginally faster than realtime in these warmed, isolated CPU
samples, with only about 5% throughput headroom. This is not evidence of robust
duplex operation while Strata actively decodes. The native CPU runtime is a
viable candidate for a later full-path trial, not an activated production fix.
All transient benchmark processes exited; loaded Strata allocations remained
11293 MiB / 15418 MiB in the final snapshot. Public model cache and isolated venv
remain in the dedicated experiment directory; private reference/audio are not
committed. Synthetic demonstration WAVs were copied to the task's local work
directory for user listening.
The final technical WAV was passed once through the existing local Athena STT
after CPU timing had finished. `technical-stt.json` retains the result: 28 errors,
35 percent, 46 repair notices and the intended numeric times remain recognizable;
STT renders times inconsistently (`0145`, `0912`, `0.3.16`). This is a limited
round-trip check, not a listening score or a claim of perfect pronunciation.
See `results-*.json` for exact per-run wall time, duration, first audio,
per-chunk arrival times and peak RSS. Warmup is recorded separately from the
two identical short-text runs and the longer technical-text run.
`RTF = generation wall time / generated audio duration`; below one means
faster than realtime **on average**. First chunk is native PCM arrival, not
sound from the user's speaker. `additional_buffer_needed_seconds` is a virtual
playout estimate from raw chunk arrival times starting at the first chunk;
it excludes network, Mac scheduling, Hermes segmentation, and device latency.
RTF and chunk-deadline measurements must be considered together. A startup
buffer can absorb a finite shortfall; it cannot fix sustained slower throughput
over an arbitrarily long utterance.
## Native Debian reproduction
Requires a compatible glibc Linux x86-64 host with AVX2/FMA/F16C/BMI2, Python
with `venv`, and systemd. Python 3.13.5 was used here; upstream recommends
Python 3.11/3.12 for its broader server installation. No Docker runtime is
required by this CPU engine. Installing to a different stage requires updating
the explicit paths in the scripts.
1. Create the dedicated stage and a fresh Python venv; install
`pip install -r requirements.lock` into that venv.
2. Copy `benchmark.py`, `prepare_models.py` and `run.sh` there. Run
`prepare_models.py` with that venv to download only the pinned public files.
Verify both SHA256 values above before measuring.
3. Restore the existing authorized Anna reference privately as
`anna-reference-original.wav` (24 kHz mono signed 16-bit WAV). No key,
production config or user chat is needed for this test.
4. Run `sh run.sh` as root to create a bounded transient systemd job. For the
six-CPU decoder comparison:
```sh
BENCH_CPU_QUOTA=6 BENCH_GEN_THREADS=4 BENCH_CODEC_THREADS=4 \
BENCH_STREAM_FRAMES=2 BENCH_OUTPUT=reproduction-6-4-4-160ms sh run.sh
```
The launcher checks more than 9 GiB `MemAvailable` before admitting its 6 GiB
budget. Jobs exit after measurements; no unit is enabled for boot, no HTTP
listener is created. This is a reproducible experiment, **not** a configured
production TTS provider or proof of a full Deck restore.
Sources: [RealtimeTTS CPU scheduling](https://github.com/KoljaB/RealtimeTTS/blob/v0.8.10/docs/qwen-cpu-scheduling.md),
[Qwen CPU engine](https://github.com/KoljaB/RealtimeTTS/blob/v0.8.10/docs/engines/qwen.md#cpu-engine).
@@ -0,0 +1,100 @@
"""Bounded CPU-only native Qwen 0.6B Q8 streaming test; synthetic texts only."""
import hashlib
import json
import os
from pathlib import Path
import resource
import time
import wave
ROOT = Path('/data/experiments/qwen06-q8-native-cpu-20261019')
OUTPUT = ROOT / os.environ.get('BENCH_OUTPUT', '.')
OUTPUT.mkdir(parents=True, exist_ok=True)
GEN_THREADS = int(os.environ.get('BENCH_GEN_THREADS', '2'))
CODEC_THREADS = int(os.environ.get('BENCH_CODEC_THREADS', '2'))
STREAM_FRAMES = int(os.environ.get('BENCH_STREAM_FRAMES', '1'))
report = {'phase': 'imports', 'runs': [], 'cpu_quota': int(os.environ.get('BENCH_CPU_QUOTA', '4')), 'memory_limit_gib': 6,
'production_changes': False, 'llm_requests': 0,
'generation_threads': GEN_THREADS, 'codec_threads': CODEC_THREADS,
'stream_frames': STREAM_FRAMES}
def save():
temp = OUTPUT / 'results.tmp'
temp.write_text(json.dumps(report, indent=2, ensure_ascii=False))
temp.replace(OUTPUT / 'results.json')
save()
try:
import numpy as np
import qwentts_cpp_cpu as q
assert q.CPU_ONLY is True
report.update(cpu_only=q.CPU_ONLY, abi=q.QT_ABI_VERSION)
paths = json.loads((ROOT / 'model-paths.json').read_text())
report['models'] = []
for name in paths:
p = Path(name)
with p.open('rb') as f:
digest = hashlib.file_digest(f, 'sha256').hexdigest()
report['models'].append({'name': p.name, 'bytes': p.stat().st_size, 'sha256': digest})
with wave.open(str(ROOT / 'anna-reference-original.wav'), 'rb') as w:
assert w.getframerate() == 24000 and w.getnchannels() == 1 and w.getsampwidth() == 2
ref_audio = np.frombuffer(w.readframes(w.getnframes()), dtype='<i2').astype(np.float32) / 32768
report['phase'] = 'loading'
save()
begin = time.monotonic()
engine = q.QwenTTS(*paths, cpu_threads=GEN_THREADS, cpu_codec_threads=CODEC_THREADS,
cpu_stream_frames=STREAM_FRAMES, clamp_fp16=False, use_fa=True)
report['load_seconds'] = time.monotonic() - begin
begin = time.monotonic()
voice = engine.extract_voice_ref(ref_audio)
report['voice_preparation_seconds'] = time.monotonic() - begin
report['phase'] = 'synthesis'
save()
texts = [
('warmup', 'Hallo Michael, die Sprachausgabe wird vorbereitet.'),
('short-1', 'Wenn du magst, erzähle ich dir eine kurze Geschichte. Anna öffnete das Fenster und hörte drei Vögel singen.'),
('short-2', 'Wenn du magst, erzähle ich dir eine kurze Geschichte. Anna öffnete das Fenster und hörte drei Vögel singen.'),
('technical', 'Der Heizkörper in der Küche antwortet nicht. Es gibt 28 Fehler, seit 01:45 Uhr, zuletzt um 09:12 Uhr. Die Batterie steht bei 35 Prozent. Die Konfiguration ist gültig. Alle 46 Reparaturhinweise sind inaktiv. Das Backup war heute um 03:16 Uhr erfolgreich.'),
]
for label, text in texts:
started = time.monotonic()
chunks, audio = [], []
samples = 0
first_non_silent = None
for data, rate in engine.stream(text=text, lang='german', ref_spk_emb=voice.ref_spk_emb,
seed=42, max_new_tokens=768, do_sample=False,
onset_silence_profile='qwen3_tts_12hz_0_6b_base_q8_v1'):
assert rate == 24000 and np.isfinite(data).all()
elapsed = time.monotonic() - started
peak = float(np.max(np.abs(data))) if data.size else 0
if first_non_silent is None and peak > .01:
first_non_silent = elapsed
chunks.append({'arrival_seconds': elapsed, 'samples': int(data.size), 'peak': peak,
'audio_before_seconds': samples / rate})
samples += data.size
audio.append(data)
elapsed = time.monotonic() - started
assert samples > 0
first = chunks[0]['arrival_seconds']
deficit = max(max(0, c['arrival_seconds'] - first - c['audio_before_seconds']) for c in chunks)
pcm = np.rint(np.clip(np.concatenate(audio), -1, 1) * 32767).astype('<i2')
with wave.open(str(OUTPUT / (label + '.wav')), 'wb') as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(24000); w.writeframes(pcm.tobytes())
run = dict(label=label, text=text, seconds=elapsed, audio_seconds=samples / 24000,
rtf=elapsed / (samples / 24000), first_chunk_seconds=first,
first_non_silent_chunk_seconds=first_non_silent,
additional_buffer_needed_seconds=deficit, chunks=chunks,
peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
report['runs'].append(run)
save()
print(json.dumps({k: v for k, v in run.items() if k not in ('chunks', 'text')}), flush=True)
engine.close()
report['phase'] = 'complete'
except Exception as exc:
report.update(phase='failed', error_type=type(exc).__name__, error=str(exc))
raise
finally:
report['peak_rss_kib'] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
save()
@@ -0,0 +1,21 @@
"""Fetch only the two pinned public Q8 assets; never use an implicit HF token."""
import json
import os
import hashlib
from pathlib import Path
os.environ['HF_HUB_DISABLE_IMPLICIT_TOKEN'] = '1'
from huggingface_hub import hf_hub_download
ROOT = Path('/data/experiments/qwen06-q8-native-cpu-20261019')
REVISION = 'b7ee2e8c7459c3bea99da23e3d178125a7d1713c'
paths = [hf_hub_download(
repo_id='Serveurperso/Qwen3-TTS-GGUF', revision=REVISION, filename=name,
cache_dir=ROOT / 'models', token=False,
) for name in ('qwen-talker-0.6b-base-Q8_0.gguf', 'qwen-tokenizer-12hz-Q8_0.gguf')]
expected = ['d54dbaf10591421fa764ed630d764efa717ae40cd959bd48c66d4eb1af226426',
'1883beeed99348fc35e23dd225e9082f93f6f8c109330a33d935baa8acdbfd94']
for path, digest in zip(paths, expected):
with open(path, 'rb') as f:
assert hashlib.file_digest(f, 'sha256').hexdigest() == digest, 'Model checksum mismatch'
(ROOT / 'model-paths.json').write_text(json.dumps(paths))
@@ -0,0 +1,17 @@
anyio==4.15.1
click==8.5.0
filelock==4.2.4
fsspec==2026.9.0
h11==0.16.0
hf-xet==1.7.0
httpcore2==2.14.0
httpx2==2.14.0
huggingface_hub==2.2.0
idna==3.20
numpy==2.5.4
packaging==26.3
PyYAML==6.0.3
realtimetts-qwen-native-cpu==0.4.2
tqdm==4.70.1
truststore==0.10.5
typing_extensions==4.16.0
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,24 @@
#!/bin/sh
# Native Debian/systemd reproduction. Existing production services stay untouched.
set -eu
stage=/data/experiments/qwen06-q8-native-cpu-20261019
quota=${BENCH_CPU_QUOTA:-4}
generation=${BENCH_GEN_THREADS:-4}
codec=${BENCH_CODEC_THREADS:-2}
frames=${BENCH_STREAM_FRAMES:-1}
output=${BENCH_OUTPUT:-reproduction}
case "$quota" in 4|6) ;; *) echo 'CPU quota must be 4 or 6' >&2; exit 1;; esac
"$stage/venv/bin/python" -c 'from pathlib import Path; available=next(int(x.split()[1]) for x in Path("/proc/meminfo").read_text().splitlines() if x.startswith("MemAvailable:")); assert available>9*1024**2, "Need more than 9 GiB available before admitting this 6 GiB test"'
exec systemd-run --unit="athena-qwen06-cpu-reproduction-$(date +%s)" \
--property="CPUQuota=${quota}00%" --property=MemoryMax=6G \
--property=MemorySwapMax=0 --property=Nice=10 --property=PrivateDevices=yes \
--property=NoNewPrivileges=yes --property=RuntimeMaxSec=900 \
--property="StandardOutput=append:$stage/reproduction.log" \
--property="StandardError=append:$stage/reproduction.log" \
--setenv="HOME=$stage" --setenv=HF_HUB_DISABLE_IMPLICIT_TOKEN=1 \
--setenv=HF_HUB_OFFLINE=1 --setenv=OMP_NUM_THREADS=4 \
--setenv=OPENBLAS_NUM_THREADS=1 --setenv=QWENTTS_CPU_FLASH_ATTN=1 \
--setenv="BENCH_GEN_THREADS=$generation" --setenv="BENCH_CODEC_THREADS=$codec" \
--setenv="BENCH_STREAM_FRAMES=$frames" \
--setenv="BENCH_CPU_QUOTA=$quota" --setenv="BENCH_OUTPUT=$output" \
"$stage/venv/bin/python" -u "$stage/benchmark.py"
@@ -0,0 +1 @@
{"success": true, "transcript": "Der Heizkörper in der Küche antwortet nicht. Es gibt 28 Fehler seit 0145, zuletzt um 0912 Uhr. Die Batterie steht bei 35%, die Konfiguration ist gültig. Alle 46 Reparaturhinweise sind inaktiv. Das Backup war heute um 0.3.16 Uhr erfolgreich.", "provider": "openai"}