From 0e3ad518d3dc8af5e48798e2e9d5d0652e006706 Mon Sep 17 00:00:00 2001 From: Mikei386 <44135113+Mikei386@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:05:36 +0200 Subject: [PATCH] Support Q4 CPU speech and document Hermes default activation --- deploy/import_qwen_native.py | 5 +- docs/CURRENT_SYSTEM.md | 11 ++ docs/QWEN_NATIVE_CPU_TTS.md | 14 ++- .../tts-q8-q4-2026-10-22/README.md | 66 ++++++++++++ .../tts-speed-2026-10-19/README.md | 8 ++ docs/maintenance/2026-10-22-qwen-q4.md | 102 ++++++++++++++++++ execution_setup.py | 6 +- profiles.py | 2 +- qwen_native.py | 8 +- qwen_native_runtime.py | 16 ++- qwen_native_worker.py | 15 ++- test_qwen_native.py | 18 +++- tts-ui.js | 2 +- 13 files changed, 248 insertions(+), 25 deletions(-) create mode 100644 docs/experiments/tts-q8-q4-2026-10-22/README.md create mode 100644 docs/maintenance/2026-10-22-qwen-q4.md diff --git a/deploy/import_qwen_native.py b/deploy/import_qwen_native.py index 17d6e99..716ec9d 100644 --- a/deploy/import_qwen_native.py +++ b/deploy/import_qwen_native.py @@ -5,11 +5,12 @@ from pathlib import Path REPO='Serveurperso/Qwen3-TTS-GGUF' REVISION='b7ee2e8c7459c3bea99da23e3d178125a7d1713c' FILES=[('qwen-talker-0.6b-base-Q8_0.gguf','d54dbaf10591421fa764ed630d764efa717ae40cd959bd48c66d4eb1af226426'),('qwen-tokenizer-12hz-Q8_0.gguf','1883beeed99348fc35e23dd225e9082f93f6f8c109330a33d935baa8acdbfd94')] +Q4_FILE=('qwen-talker-0.6b-base-Q4_K_M.gguf','4b468ec7b1f62b90ef4ca316c0aa57deadfd54b2cf9651703ea753cedaf04226') def digest(path): with path.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() def main(): - p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path);p.add_argument('--cache',required=True,type=Path);a=p.parse_args();ids=[] - for name,expected in FILES: + p=argparse.ArgumentParser();p.add_argument('--state',required=True,type=Path);p.add_argument('--cache',required=True,type=Path);p.add_argument('--quant',choices=['Q8','Q4'],default='Q8');a=p.parse_args();ids=[] + for name,expected in ([Q4_FILE,FILES[1]] if a.quant=='Q4' else FILES): source=a.cache/('models--'+REPO.replace('/','--'))/'snapshots'/REVISION/name if digest(source)!=expected:raise ValueError('Qwen-Datei hat unerwartete SHA256.') ident=hashlib.sha256((REPO+REVISION+name).encode()).hexdigest();target=a.state/'models'/ident;target.mkdir(parents=True,exist_ok=True,mode=0o700) diff --git a/docs/CURRENT_SYSTEM.md b/docs/CURRENT_SYSTEM.md index 8d771bc..e2d9c9a 100644 --- a/docs/CURRENT_SYSTEM.md +++ b/docs/CURRENT_SYSTEM.md @@ -1,3 +1,14 @@ +## Qwen Q4 CPU speech ·22 October2026 + +Michael selected Qwen0.6B Q4_K_M with the existing Q8 codec and Anna reference. +Normal separate Deck profile`qwen-06b-q4-anna-cpu`,published and warm; original +Q8 profile/weights retained unpublished. All eight existing Hermes Q8 profiles +now explicitly select Q4 through the official CLI. No GPU/reserve/Strata profile +change. Small Deck app update at idle, existing native0.4.2 runtime reused. +[Activation and verification](maintenance/2026-10-22-qwen-q4.md). +Concurrent Strata/live-phone playback still needs acceptance; the single-text +Q4 listening test is not a blanket realtime guarantee. + ## Strata v0.2.2 / Engine0.1.47 · 21 October 2026, 23 Uhr (current runtime) Pinned011c9e600a93bbc9fd451c563501b5831c32bbca, CUDA13SM86/120, native in-place diff --git a/docs/QWEN_NATIVE_CPU_TTS.md b/docs/QWEN_NATIVE_CPU_TTS.md index ec7aad1..525e0bc 100644 --- a/docs/QWEN_NATIVE_CPU_TTS.md +++ b/docs/QWEN_NATIVE_CPU_TTS.md @@ -1,8 +1,8 @@ -# Qwen3-TTS 0.6B Q8 als natives CPU-Profil +# Qwen3-TTS 0.6B Q8/Q4 als natives CPU-Profil Das Profil verwendet `realtimetts-qwen-native-cpu==0.4.2` (ABI5) direkt, ohne PyTorch, CUDA, zusätzlichen dauerhaften Container oder Hermes-Anpassung. -Q8-Talker und Q8-Sprach-Codec werden in der normalen Deck-Bibliothek verwaltet. +Q8- oder Q4_K_M-Talker und Q8-Sprach-Codec werden in der normalen Deck-Bibliothek verwaltet. Die Stimme kommt aus der bestehenden privaten Referenz unter `speech-voices/Anna/reference.wav`; `speech-voices/default.json` bestimmt den neutralen API-Stimmnamen `default`. @@ -14,6 +14,7 @@ neutralen API-Stimmnamen `default`. 2. In der Bibliothek/Modellsuche `Serveurperso/Qwen3-TTS-GGUF` verwenden, Revision `b7ee2e8c7459c3bea99da23e3d178125a7d1713c`: `qwen-talker-0.6b-base-Q8_0.gguf` als Hauptmodell, + alternativ `qwen-talker-0.6b-base-Q4_K_M.gguf`, `qwen-tokenizer-12hz-Q8_0.gguf` als Sprach-Codec. Die Hashes stehen im [Messbericht](experiments/qwen06-native-cpu-2026-10-19/README.md). Andere Quantisierungen/Revisionen werden nicht ungeprüft freigegeben. @@ -28,6 +29,15 @@ neutralen API-Stimmnamen `default`. weiterhin `/v1/audio/speech`, Modell `tts`, Stimme `default`; kein neuer Client-Endpunkt und keine neuen Zugangsdaten. +Seit22.Oktober ist auf Michaels Installation **Qwen0.6B Q4 Anna CPU** ausgewählt, +API-ID `qwen-06b-q4-anna-cpu`. Q8 bleibt als separates, deaktiviertes Profil +erhalten. Hermes fordert die konkrete Q4-ID an; der allgemeine Alias `tts` +kann bei gleichzeitig veröffentlichter OmniVoice-Ausgabe mehrdeutig sein. +Q4 nutzt ausdrücklich `onset_silence_profile=off`; die vorhandene Q8-spezifische +Korrektur wird nicht auf Q4 übertragen. Beide verwenden denselben Q8-Codec, +dieselbe private Anna-Referenz und die bereits installierte CPU-Laufzeit0.4.2. +[Aktivierung, Prüfung und Rückfall](maintenance/2026-10-22-qwen-q4.md). + ## Ressourcen und Verhalten - Vier Generierungs- und vier Decoder-Threads, zwei Codec-Frames (160ms), diff --git a/docs/experiments/tts-q8-q4-2026-10-22/README.md b/docs/experiments/tts-q8-q4-2026-10-22/README.md new file mode 100644 index 0000000..34c6078 --- /dev/null +++ b/docs/experiments/tts-q8-q4-2026-10-22/README.md @@ -0,0 +1,66 @@ +# Qwen CPU Q8/Q4 listening comparison · 22 October 2026 + +Michael requested the same supplied German passage in both quantizations, using +Anna, with timing measurements. The private working directory contains the exact +input, scripts, complete PCM-arrival measurements and listening WAVs: +`/Users/mike_i386/Documents/ChatGPT/Athena Deck/work/tts-q8-q4-20261022`. +The supplied passage is test input, not an instruction to update any plugin. + +## Conditions + +Existing native CPU runtime0.4.2/ABI5 on Athena Ryzen5600. Original Qwen0.6B Base +Q8 talker compared with Q4_K_M from the same pinned revision; original Q8 codec +and Anna reference reused. Fixed greedy seed42,4generation/4codec threads, +2frame streaming, Flash Attention, noFP16clamp. Each model was loaded separately +and given the same short warmup before the requested passage. The production +speech normalizer/splitter supplied six text segments for each. + +The Q8-specific onset profile was enabled only for Q8; Q4 used the supported +`off` setting. This compares the available configurations, not quantization +alone with identical onset handling. CPU quota800%,Nice10,MemoryMax6GiB, +no swap, no GPU devices, bounded transient systemd units. Production Strata +and CPU TTS remained loaded with the same original processes. No extra Strata +generation load was started, and concurrent production load was not controlled. + +## Results + +| Configuration | First PCM | Generation time | Audio duration | RTF | Quiet duration* | Longest quiet interval* | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q8 talker/Q8 codec |0.410s|44.474s|42.56s|1.045|7.27s|0.51s| +| Q4 talker/Q8 codec |0.355s|30.363s|40.96s|0.741|7.04s|0.56s| + +*Quiet is10ms windows with RMS below0.003, including normal speech pauses; +not a linguistic silence annotation or a listening quality score. + +Model loading plus reference preparation took4.175s(Q8)/2.833s(Q4), excluded +from the warmed passage times. Q8 warmup took7.716s for3.60s audio; Q4 warmup +took2.275s for3.52s audio. These are sequential single samples, not replicated +performance or cold-start guarantees. The requested Q4 synthesis was31.7% +shorter in wall time. Its audio duration also differs, so RTF is included. + +Unlike the earlier short-text Q4 test, this passage has no very long quiet +interval according to the stated numeric detector. Subjective voice quality, +pronunciation and complete text fidelity remain for human listening; no ASR +or listening acceptance is claimed. Stable streaming under simultaneous Strata +generation is not established by this test. First PCM is not audible playback. + +## Files and cleanup + +Both downloaded WAVs were validated as24kHzmonoPCM16 and their sample counts +matched reported durations. Minimum host MemAvailable was6.08GiB(Q8) and +6.66GiB(Q4); neither memory/deadline guard fired. Both units exited successfully. +No production settings, profiles, model selection, priorities or services changed. +The temporary downloaded Q4 talker was removed after completion; original model +files and private reference were not modified. Results remain on Athena at +`/data/experiments/tts-q8-q4-20261022T1245`. + +Q4 file:628905056bytes, SHA256 +`4b468ec7b1f62b90ef4ca316c0aa57deadfd54b2cf9651703ea753cedaf04226`, verified +against the pinned previous test manifest. Source: +`Serveurperso/Qwen3-TTS-GGUF`, revision +`b7ee2e8c7459c3bea99da23e3d178125a7d1713c`. + +No persistent runtime/install/restore change was introduced. Native reproduction +uses the existing documented CPU runtime and public assets, restored authorized +voice, and the same temporary resource limits. This test is not a full restore +qualification or production approval for Q4. diff --git a/docs/experiments/tts-speed-2026-10-19/README.md b/docs/experiments/tts-speed-2026-10-19/README.md index 4aec743..e736264 100644 --- a/docs/experiments/tts-speed-2026-10-19/README.md +++ b/docs/experiments/tts-speed-2026-10-19/README.md @@ -79,3 +79,11 @@ Conclusion: real idle TTS gains about25% lower RTF and is comfortably faster than realtime on the tested text. Full concurrent Strata decoding still makes CPU TTS slower than realtime even with12logical CPUs. CPU tuning alone does not meet the live-talk target; no claim of a complete fix. + +Follow-up22October:the requested longer passage did not reproduce the very long +Q4 quiet intervals from this short-text trial. Q4 generated40.96s in30.36s, +longest quiet interval0.56s, versus Q8 42.56s in44.47s,0.51s. This limits the +earlier rejection to its tested samples; it is not evidence all Q4 text is poor. +Michael subsequently selected Q4 as the production default. See the +[comparison](../tts-q8-q4-2026-10-22/README.md) and +[activation](../../maintenance/2026-10-22-qwen-q4.md) for scope and caveats. diff --git a/docs/maintenance/2026-10-22-qwen-q4.md b/docs/maintenance/2026-10-22-qwen-q4.md new file mode 100644 index 0000000..c083e67 --- /dev/null +++ b/docs/maintenance/2026-10-22-qwen-q4.md @@ -0,0 +1,102 @@ +# Qwen Q4 as Hermes speech default ·22 October2026 + +Michael requested Q4 as the default for later Conduit telephone use after +listening to the requested Q8/Q4 comparison. The specific passage generated +40.96s audio in30.36s with Q4 versus42.56s in44.47s with Q8. This is one warmed +CPU comparison, not proof of smooth playback under concurrent Strata load. +See[comparison](../experiments/tts-q8-q4-2026-10-22/README.md). + +## Product change + +Deck explicitly supports both pinned0.6B GGUF talkers from +`Serveurperso/Qwen3-TTS-GGUF`, revision +`b7ee2e8c7459c3bea99da23e3d178125a7d1713c`. Q4_K_M SHA256: +`4b468ec7b1f62b90ef4ca316c0aa57deadfd54b2cf9651703ea753cedaf04226`. +The Q8 codec and Anna reference remain the existing files. Q4 never inherits +the Q8-only onset profile: its explicit setting is`off`. Unknown variants and +revisions remain rejected. No runtime dependency or GPU support was added. + +Q4 is a normal separate model/profile, not a relabeled Q8 entry. Import using +`deploy/import_qwen_native.py --quant Q4 --state STATE --cache HF_CACHE`. +The existing normal catalogue, component assignment, endpoint publication and +audio policy retain source/model identities for backup and restore. + +## Activation + +New image:`athena-deck-standalone:d77f747cd05983eb`. Only the existing Deck app +was updated, in the idle window Michael confirmed. Two authenticated ordinary +status checks observed0active requests before the stop. Existing installer +Dockerfile/allowlist and`launch`/`ready`/manifest routines were used; the117-layer +base was reused directly without the installer's100-layer compaction step. +No persistent installer override was introduced. The app update installed0new +OS packages and rebuilt no ML runtime. This is not a Hermes custom image. + +Q4 profile:`qwen-06b-q4-anna-cpu`, internal ID +`e6eddd10ef4142f78945e14882dc7a45`. Published; audio policy retains`warm` and +now points to Q4. Original Q8 profile and weights remain, unpublished. Other +existing profiles were verified unchanged as JSON data. Existing CPU8/RAM59GiB, +GPU order/reserves/layer split and private voice remain unchanged. + +The official Hermes CLI changed only`tts.openai.model` from the explicit Q8 ID +to Q4 in eight existing profiles:default,jean-luc-picode,william-t-time and the +five existing SSH profiles. Parsed configuration comparisons verified every +other setting unchanged. Endpoint, credential, voice and STT remain unchanged. +The model defaults for future profiles follow Hermes' own creation/cloning +behavior; no global profile-creation patch was added. + +The previous Strata dual-slot model was restored through one normal one-token +API request:HTTP200,48.21s including loading. The running native speech worker +command was verified to selectQ4. No Conduit pairing, app preference, plugin +code or Hermes gateway restart was changed. + +## Validation and limits + +117 focused tests ran:115 passed, with2 pre-existing skips. These cover Q4 model +recognition, keeping the Q8-only onset setting away from Q4, WAV/PCM routing, +cancellation, audio policy, profile identities and endpoint behavior. Python +compilation, JavaScript syntax and`git diff --check` passed. A broader attempted +Mac run included a nonexistent test module and was blocked from binding test +ports; the actual endpoint suite was rerun successfully with loopback access. +An unrelated pre-existing STT fixture in`test_audio_residency` lacks`model` and +was not modified or represented as passing. + +Live Hermes streaming acceptance passed for all three phone profiles: + +| Profile | First PCM | Generation | Audio duration | +| --- | ---: | ---: | ---: | +| default |2.080s|4.010s|3.60s| +| jean-luc-picode |0.366s|2.355s|3.60s| +| william-t-time |0.369s|2.359s|3.60s| + +The native`_load_tts_config`/`resolve_streaming_provider` selected the explicit +Q4 profile for each; complete PCM was nonempty, sample-aligned,24kHzmono. +An initial test incorrectly required each arbitrary network packet to end on +a16bit sample boundary. It stopped after a packet in the second request; +the probe was corrected to validate complete PCM, with no product change. +The initial default call after restart was slower:7.391s total for3.60s audio, +first PCM5.488s. These are individual warmup-sensitive measurements. + +A real +phone call, handset playback and sustained simultaneous Strata/TTS acceptance +remain user checks; no phone call was triggered by this maintenance. + +## Persistence and rollback + +Keep the application revision with Q4 support, existing native runtime recipe, +normal model catalogue entry, profiles, endpoint/audio policy and encrypted +private`speech-voices` backup. On native Debian use the same source modules, +existing pinned CPU venv, public Q4/codec assets and restored Anna reference. +No new native package, CUDA dependency or persistent auxiliary service is +required. Full fresh-Debian restore qualification remains an existing open task. + +To return to Q8, publish its original profile instead of Q4, set the warm TTS +policy to Q8, and set Hermes`tts.openai.model` back to +`qwen-06b-q8-anna-cpu` through the official per-profile CLI. No voice conversion +or model download is necessary. This known Q4 profile must not be loaded with +an older Deck build that supports only Q8. + +The maintenance work is explicitly recorded at +`/opt/athena-deck-dev/qwen-q4-activation-20261022`; its scoped selection rollback +contains only the three changed Deck settings files and the install manifest. +No broad data backup or private voice copy was created. Existing Hermes chats, +cron jobs, MCPs and plugin settings were not migrated or rewritten. diff --git a/execution_setup.py b/execution_setup.py index f7e811a..b0a8081 100644 --- a/execution_setup.py +++ b/execution_setup.py @@ -14,10 +14,10 @@ def _assess(model, installed, profile=None): result.update(state='component',label='Zusatzdatei',message='Diese Datei wird einem kompatiblen Modellprofil zugeordnet und benötigt keine eigene Laufzeit.') return result from pocket_runtime import supported as pocket_model - from qwen_native_runtime import supported as native_model + from qwen_native_runtime import supported as native_model,model_quant if native_model(model): ready=bool(installed.get('qwen_native')) - result.update(family='Qwen3-TTS 0.6B Q8',evidence='Gepinnter nativer CPU-Worker mit Q8-Talker und Codec',runtime='Qwen3-TTS · native CPU',route='#tts-runtime',installed=ready,state='setup' if ready else 'runtime_missing',label='Qwen3-TTS Q8 · CPU',components=['Q8-Sprach-Codec','Gespeicherte Referenzstimme'],message='Native CPU-Sprachausgabe ohne GPU-Speicher. Unter TTS → Einrichten Laufzeit installieren, im Profil Codec zuordnen, danach TTS → Testen verwenden.') + result.update(family='Qwen3-TTS 0.6B '+model_quant(model),evidence='Gepinnter nativer CPU-Worker mit Q8- oder Q4-Talker und Q8-Codec',runtime='Qwen3-TTS · native CPU',route='#tts-runtime',installed=ready,state='setup' if ready else 'runtime_missing',label='Qwen3-TTS '+model_quant(model)+' · CPU',components=['Q8-Sprach-Codec','Gespeicherte Referenzstimme'],message='Native CPU-Sprachausgabe ohne GPU-Speicher. Unter TTS → Einrichten Laufzeit installieren, im Profil Codec zuordnen, danach TTS → Testen verwenden.') if profile:result.update(state='ready' if profile.get('runnable') else 'profile_incomplete',blockers=profile.get('blockers',[])) return result if pocket_model(model): @@ -111,7 +111,7 @@ def _assess_candidates(model, installed, profile=None): result['candidates'].append(dict(id=id,label=label,installed=bool(installed.get(key)),route=route,installation_available=maintained,evidence=reason)) from qwen_native_runtime import supported as native_model if native_model(model): - add('qwen_native','Qwen3-TTS Q8 · CPU','qwen_native','#tts-runtime','Native CPU-only-Laufzeit, kein CUDA oder PyTorch') + add('qwen_native','Qwen3-TTS Q8/Q4 · CPU','qwen_native','#tts-runtime','Native CPU-only-Laufzeit, kein CUDA oder PyTorch') return result from pocket_runtime import supported as pocket_model if pocket_model(model): diff --git a/profiles.py b/profiles.py index 6f32cb4..f0a2193 100644 --- a/profiles.py +++ b/profiles.py @@ -429,7 +429,7 @@ class Profiles: except ValueError:pass candidates=[dict(f,repo=source.get('repo',info.get('repo',model['repo'])),revision=source['revision'],gated=source['gated'],auth_configured=source.get('auth_configured',False)) for name in info['files'] for f in source['files'] if f['name']==name] requirements.append(dict(role=role,label=info['label'],available=available,candidates=candidates)) - if native_model(model):return dict(supported=True,requirements=requirements,source='https://github.com/KoljaB/RealtimeTTS',license='Apache-2.0',runtime='Qwen3-TTS 0.6B Q8 · native CPU',runtime_installed=bool(getattr(self,'qwen_native_runtime_ready',lambda:False)()),runtime_route='#tts-runtime',worker_available=True,message='Gepinnter Q8-Sprach-Codec und gespeicherte Referenzstimme. CPU-only, keine GPU-Reservierung. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke.') + if native_model(model):return dict(supported=True,requirements=requirements,source='https://github.com/KoljaB/RealtimeTTS',license='Apache-2.0',runtime='Qwen3-TTS 0.6B Q8/Q4 · native CPU',runtime_installed=bool(getattr(self,'qwen_native_runtime_ready',lambda:False)()),runtime_route='#tts-runtime',worker_available=True,message='Gepinnter Q8-Sprach-Codec und gespeicherte Referenzstimme. CPU-only, keine GPU-Reservierung. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke.') if pocket_model(model):return dict(supported=True,requirements=requirements,source='https://github.com/kyutai-labs/pocket-tts',license='cc-by-4.0',runtime='Pocket TTS · CPU · Deutsch',runtime_installed=bool(getattr(self,'pocket_runtime_ready',lambda:False)()),runtime_route='#tts-runtime',worker_available=True,message='Gepinnter deutscher Tokenizer und gespeicherte Pocket-Stimme. CPU-Betrieb ohne GPU-Reservierung.') if omni_recipe(model):return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='OmniVoice · Python/PyTorch',runtime_installed=bool(getattr(self,'omnivoice_runtime_ready',lambda:False)()),runtime_route='#omnivoice-runtime',worker_available=True,message='Originale OmniVoice-Laufzeit mit Audio- und Text-Tokenizer. Komponenten derselben Quellversion zuordnen. Stimmklonen benötigt Referenz-Audio und dessen Transkript; keine zusätzlichen ASR-Gewichte werden automatisch geladen.') if voice_recipe(model):return dict(supported=True,requirements=requirements,source='https://huggingface.co/'+model['repo']+'/blob/'+model['revision']+'/README.md',license=source['license'],runtime='VoxCPM · eigene Python/PyTorch-Laufzeit',runtime_installed=bool(getattr(self,'voxcpm_runtime_ready',lambda:False)()),runtime_route='#voxcpm-runtime',worker_available=True,message='VoxCPM2 benötigt genau diese fünf Zusatzdateien derselben Quellversion. Ein separater Textencoder und ein Vision-Projektor werden nicht benötigt. tokenizer.json und tokenizer_config.json gehören zusammen, sie sind keine doppelten Modelle. Vorhandene Dateien werden wiederverwendet. Die passende Laufzeit kann unter Einstellungen → Laufzeiten → VoxCPM installiert werden. Nach Zuordnung dieser Dateien unter Stimmwerkzeuge → Testen Sprache erzeugen oder eine WAV-Referenz für Stimmklonen verwenden.') diff --git a/qwen_native.py b/qwen_native.py index 65e5109..1564d0f 100644 --- a/qwen_native.py +++ b/qwen_native.py @@ -2,10 +2,10 @@ import json,os,select,subprocess from pathlib import Path from pocket import Pocket -from qwen_native_runtime import supported +from qwen_native_runtime import supported,model_quant class QwenNative(Pocket): - name='Qwen3-TTS Q8' + name='Qwen3-TTS' cooperative_cancel=True def cancel_job(self,ident): with self.lock: @@ -33,7 +33,7 @@ class QwenNative(Pocket): if not path.is_file():raise ValueError('Gespeicherte Qwen-Referenzstimme '+name+' fehlt.') return path.resolve() def blockers(self,p): - if not supported(p.get('model')):return ['Dieses native Qwen-Modell ist noch nicht qualifiziert. Das geprüfte 0.6B-Q8-Rezept verwenden.'] + if not supported(p.get('model')):return ['Dieses native Qwen-Modell ist noch nicht qualifiziert. Das gepinnte 0.6B-Q8- oder Q4-Rezept verwenden.'] errors=[] if not self.runtime.status()['installed']:errors.append('Native Qwen-CPU-Laufzeit unter TTS → Einrichten installieren.') try:self.profiles._component(p['model'],'codec',p.get('components',{}).get('codec')) @@ -62,7 +62,7 @@ class QwenNative(Pocket): codec_path=self.profiles.catalog.root/codec['id']/'model.gguf' env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','LLAMA_','DECK_','OPENAI_'))} env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='1',QWENTTS_CPU_FLASH_ATTN='1',HOME=str(self.root)) - process=subprocess.Popen([str(self.runtime.paths()[0]),str(Path(__file__).with_name('qwen_native_worker.py')),str(model),str(codec_path),str(voice)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True,bufsize=1) + process=subprocess.Popen([str(self.runtime.paths()[0]),str(Path(__file__).with_name('qwen_native_worker.py')),str(model),str(codec_path),str(voice),model_quant(p['model'])],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True,bufsize=1) with self.lock:self.process=process;self.profile_id=p['id'] if not select.select([process.stdout],[],[],120)[0]:self.unload_idle();raise ValueError('Zeitlimit beim Laden von Qwen-CPU.') try:ready=json.loads(process.stdout.readline()) diff --git a/qwen_native_runtime.py b/qwen_native_runtime.py index f246575..6ed0944 100644 --- a/qwen_native_runtime.py +++ b/qwen_native_runtime.py @@ -1,4 +1,4 @@ -"""Pinned native Qwen3-TTS Q8 CPU runtime; weights remain in the model library.""" +"""Pinned native Qwen3-TTS CPU runtime; explicit Q8/Q4 recipes in the library.""" import json,os,shutil,sys from pathlib import Path from ltx_original_runtime import LTXOriginalRuntime @@ -7,14 +7,22 @@ VERSION='0.4.2' REPO='Serveurperso/Qwen3-TTS-GGUF' REVISION='b7ee2e8c7459c3bea99da23e3d178125a7d1713c' MODEL_FILE='qwen-talker-0.6b-base-Q8_0.gguf' +MODEL_FILES={ + MODEL_FILE:dict(quant='Q8',sha256='d54dbaf10591421fa764ed630d764efa717ae40cd959bd48c66d4eb1af226426'), + 'qwen-talker-0.6b-base-Q4_K_M.gguf':dict(quant='Q4',sha256='4b468ec7b1f62b90ef4ca316c0aa57deadfd54b2cf9651703ea753cedaf04226'), +} CODEC_FILE='qwen-tokenizer-12hz-Q8_0.gguf' COMPONENTS={'codec':dict(label='Qwen Sprach-Codec · Q8_0',revision=REVISION,files=[CODEC_FILE])} def supported(model): - return bool(model and model.get('kind')=='audio' and model.get('repo')==REPO and model.get('revision')==REVISION and model.get('file')==MODEL_FILE) + return bool(model and model.get('kind')=='audio' and model.get('repo')==REPO and model.get('revision')==REVISION and model.get('file') in MODEL_FILES) + +def model_quant(model): + if not supported(model):raise ValueError('Unbekanntes natives Qwen-CPU-Modell.') + return MODEL_FILES[model['file']]['quant'] class QwenNativeRuntime(LTXOriginalRuntime): - name='Qwen3-TTS 0.6B Q8 · CPU' + name='Qwen3-TTS 0.6B Q8/Q4 · CPU' def __init__(self,root):super().__init__(root,None) def paths(self): try: @@ -42,7 +50,7 @@ class QwenNativeRuntime(LTXOriginalRuntime): if self.cancel.is_set():raise InterruptedError() (base/'ready').write_text(VERSION) temp=self.root/'active.tmp';temp.write_text(json.dumps({'id':base.name}));temp.replace(self.root/'active.json') - state='complete';phase='Native Qwen-CPU-Laufzeit bereit · Q8-Modell und Sprach-Codec im Profil zuordnen' + state='complete';phase='Native Qwen-CPU-Laufzeit bereit · Q8- oder Q4-Modell und Q8-Sprach-Codec im Profil zuordnen' except InterruptedError:state='cancelled';phase='Einrichtung abgebrochen.' except Exception as exc:phase=str(exc) finally: diff --git a/qwen_native_worker.py b/qwen_native_worker.py index 05894a1..c68e67d 100644 --- a/qwen_native_worker.py +++ b/qwen_native_worker.py @@ -1,4 +1,4 @@ -"""Persistent Q8 CPU worker. Native stdout is excluded from the JSON protocol.""" +"""Persistent Q8/Q4 CPU worker. Native stdout is excluded from the JSON protocol.""" import json,os,resource,sys,time,wave from pathlib import Path from contextlib import closing @@ -7,10 +7,17 @@ class JobCancellation: def __init__(self,root):self.marker=root/'cancel' def is_set(self):return self.marker.exists() +def onset_profile(quant): + if quant=='Q8':return 'qwen3_tts_12hz_0_6b_base_q8_v1' + if quant=='Q4':return 'off' + raise ValueError('Unbekannte Qwen-Quantisierung.') + def main(): protocol=os.fdopen(os.dup(1),'w',buffering=1);os.dup2(2,1) def emit(value):protocol.write(json.dumps(value)+'\n');protocol.flush() try: + quant=sys.argv[4] if len(sys.argv)>4 else 'Q8' + onset=onset_profile(quant) os.nice(10) resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3)) import numpy as np @@ -29,7 +36,7 @@ def main(): return voices[key] # Prepare the configured default voice before declaring residency ready. voice_for(sys.argv[3]) - emit(dict(ready=True,cpu_only=True)) + emit(dict(ready=True,cpu_only=True,quant=quant)) except Exception as exc: emit(dict(ready=False,error='Qwen-CPU konnte nicht laden ('+type(exc).__name__+').'));return 1 for line in sys.stdin: @@ -38,7 +45,7 @@ def main(): voice=voice_for(request['voice']);parts=[];first=None;index=0;total=0;cancel=JobCancellation(root) for text in spoken_chunks(dict(text=request['text'],language='German')): if cancel.is_set():break - with closing(model.stream(text=text,lang='german',ref_spk_emb=voice,seed=42,do_sample=False,max_new_tokens=1024,onset_silence_profile='qwen3_tts_12hz_0_6b_base_q8_v1',cancel_event=cancel)) as stream: + with closing(model.stream(text=text,lang='german',ref_spk_emb=voice,seed=42,do_sample=False,max_new_tokens=1024,onset_silence_profile=onset,cancel_event=cancel)) as stream: for chunk,rate in stream: if cancel.is_set():break if rate!=24000 or not np.isfinite(chunk).all():raise ValueError('Ungültige Qwen-Audiodaten.') @@ -52,7 +59,7 @@ def main(): if not parts:raise ValueError('Keine Audiodaten erzeugt.') with wave.open(str(root/'result.wav'),'wb') as w: w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(b''.join(parts)) - result=dict(ok=True,duration=total/48000,sample_rate=24000,seconds=time.monotonic()-start,first_chunk_seconds=first) + result=dict(ok=True,quant=quant,duration=total/48000,sample_rate=24000,seconds=time.monotonic()-start,first_chunk_seconds=first) except InterruptedError:result=dict(ok=True,cancelled=True,seconds=time.monotonic()-start) except Exception as exc:result=dict(ok=False,error='Native Qwen-Spracherzeugung fehlgeschlagen ('+type(exc).__name__+').') tmp=root/'result.tmp';tmp.write_text(json.dumps(result));tmp.replace(root/'result.json') diff --git a/test_qwen_native.py b/test_qwen_native.py index 5470d5a..3a3522e 100644 --- a/test_qwen_native.py +++ b/test_qwen_native.py @@ -2,20 +2,30 @@ import json,tempfile,unittest from pathlib import Path from unittest.mock import Mock,patch from qwen_native import QwenNative -from qwen_native_runtime import supported,REPO,REVISION,MODEL_FILE +from qwen_native_runtime import supported,model_quant,REPO,REVISION,MODEL_FILE from endpoint import APIHandler import test_pocket MODEL=dict(kind='audio',repo=REPO,revision=REVISION,file=MODEL_FILE) class NativeQwenTests(unittest.TestCase): - def test_only_pinned_q8_model_has_native_cpu_recipe(self): + def test_only_pinned_q8_and_q4_models_have_native_cpu_recipe(self): from profiles import component_recipe self.assertTrue(supported(MODEL));self.assertFalse(supported(dict(MODEL,revision='0'*40))) self.assertEqual(set(component_recipe(MODEL)),{'codec'}) from execution_setup import assess result=assess(MODEL,{'qwen_native':True},{'runnable':True,'blockers':[]}) self.assertEqual(result['state'],'ready');self.assertEqual(result['candidates'][0]['id'],'qwen_native') + q4=dict(MODEL,file='qwen-talker-0.6b-base-Q4_K_M.gguf') + self.assertTrue(supported(q4));self.assertEqual(model_quant(q4),'Q4');self.assertEqual(model_quant(MODEL),'Q8') + self.assertEqual(component_recipe(q4),component_recipe(MODEL)) + self.assertFalse(supported(dict(q4,revision='0'*40))) + self.assertFalse(supported(dict(q4,file='qwen-talker-0.6b-base-Q5_K_M.gguf'))) + def test_q4_never_inherits_q8_only_onset_profile(self): + from qwen_native_worker import onset_profile + self.assertEqual(onset_profile('Q4'),'off') + self.assertEqual(onset_profile('Q8'),'qwen3_tts_12hz_0_6b_base_q8_v1') + with self.assertRaises(ValueError):onset_profile('Q5') def test_private_reference_stays_inside_voice_folder(self): with tempfile.TemporaryDirectory() as d: root=Path(d);voice=root/'speech-voices/Anna';voice.mkdir(parents=True);(voice/'reference.wav').touch() @@ -32,9 +42,9 @@ class NativeQwenTests(unittest.TestCase): worker._profile=Mock(return_value={'id':'native'});worker._ensure_cpu=Mock() worker.warm('native');worker.acquire.assert_not_called() def test_alias_and_pcm_select_native_worker(self): - for fmt in ('wav','pcm'): + for fmt,file in ((fmt,file) for fmt in ('wav','pcm') for file in (MODEL_FILE,'qwen-talker-0.6b-base-Q4_K_M.gguf')): h,ep,pocket,row=test_pocket.SpeechRoutingTests().fixture() - row.update(model=MODEL,api_id='qwen-native-anna');ep.qwen_native=Mock();ep.qwen_native.start.return_value={'id':'job'} + row.update(model=dict(MODEL,file=file),api_id='qwen-native-anna');ep.qwen_native=Mock();ep.qwen_native.start.return_value={'id':'job'} ep.qwen_native.status.return_value=pocket.status.return_value ep.qwen_native.job_status.return_value=pocket.job_status.return_value ep.qwen_native.audio.return_value=b'RIFF-native' diff --git a/tts-ui.js b/tts-ui.js index 8861be4..6bedad3 100644 --- a/tts-ui.js +++ b/tts-ui.js @@ -1,7 +1,7 @@ window.TTSUI=(()=>{ const e=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); async function api(path='',data){const r=await fetch('/api/v1/'+path,(data===undefined)?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const x=await r.json();if(!r.ok)throw Error(x.error||'TTS-Anfrage fehlgeschlagen');return x;} - function html(setup=false){return `

${setup?'TTS einrichten':'Sprache ausprobieren'}

${setup?'

Qwen3-TTS 0.6B Q8 · CPU

Native CPU-Laufzeit mit gespeicherter Anna-Referenz, ohne GPU-Speicher. Benötigt Talker und Q8-Sprach-Codec als Bibliotheksdateien. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke. Die Installation lädt keine Gewichte oder privaten Stimmen.

Pocket TTS · CPU

Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.

Qwen3-TTS · GPU

Die Einrichtung installiert eine eigene CUDA-Laufzeit und das offizielle Qwen3-TTS 1.7B Base mit den Preset-Stimmen des bisherigen Routers. Dafür werden mehrere GB heruntergeladen. MLX-Dateien sind für Apple-Geräte; vorhandene Dateien werden nicht gelöscht.

Vorhandenes TTS-Profil verbinden

Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.

Textaufbereitung am API-Endpunkt

Gemeinsam für alle am Endpunkt freigegebenen TTS-Profile. Experimentell: entfernt Markdown und spricht ausgewählte Zeichen und Abkürzungen aus; verhindert keine Modellschleifen oder Auslassungen. Andere explizite Sprachen bleiben unverändert. Gilt für API-Aufrufe, nicht für das direkte Testformular.

Speicherverhalten

Automatisch lädt das einzige am Endpunkt freigegebene TTS-Profil im LLM-Betrieb vor und hält es bereit: Qwen 1.7B auf der RTX 3060, natives Qwen Q8 und Pocket auf der CPU. Immer bereit lädt das gewählte Profil im LLM-Betrieb vor, soweit Ressourcen frei sind. Nach jeder Anfrage entladen gibt Speicher sofort frei.

':'

Qwen 1.7B nutzt die RTX 3060; natives Qwen Q8 und Pocket nutzen die CPU. Andere Deck-Modellaufträge werden koordiniert; fremde Dienste werden nicht gestoppt. Text wird nicht dauerhaft gespeichert. Ergebnisdateien bleiben auf Athena.

'}
`;} + function html(setup=false){return `

${setup?'TTS einrichten':'Sprache ausprobieren'}

${setup?'

Qwen3-TTS 0.6B Q8/Q4 · CPU

Native CPU-Laufzeit mit gespeicherter Anna-Referenz, ohne GPU-Speicher. Benötigt Talker und Q8-Sprach-Codec als Bibliotheksdateien. Vier Generierungs-/vier Decoder-Threads, 160-ms-Blöcke. Die Installation lädt keine Gewichte oder privaten Stimmen.

Pocket TTS · CPU

Deutsch mit gespeicherter Anna-Stimme, ohne GPU-Speicher. Die Laufzeitinstallation lädt keine Modelle oder privaten Stimmen.

Qwen3-TTS · GPU

Die Einrichtung installiert eine eigene CUDA-Laufzeit und das offizielle Qwen3-TTS 1.7B Base mit den Preset-Stimmen des bisherigen Routers. Dafür werden mehrere GB heruntergeladen. MLX-Dateien sind für Apple-Geräte; vorhandene Dateien werden nicht gelöscht.

Vorhandenes TTS-Profil verbinden

Ersetzt im ausgewählten Profil die Modellzuordnung durch die eingerichtete CUDA-Variante. Der Profilname bleibt erhalten.

Textaufbereitung am API-Endpunkt

Gemeinsam für alle am Endpunkt freigegebenen TTS-Profile. Experimentell: entfernt Markdown und spricht ausgewählte Zeichen und Abkürzungen aus; verhindert keine Modellschleifen oder Auslassungen. Andere explizite Sprachen bleiben unverändert. Gilt für API-Aufrufe, nicht für das direkte Testformular.

Speicherverhalten

Automatisch lädt das einzige am Endpunkt freigegebene TTS-Profil im LLM-Betrieb vor und hält es bereit: Qwen 1.7B auf der RTX 3060, natives Qwen Q8/Q4 und Pocket auf der CPU. Immer bereit lädt das gewählte Profil im LLM-Betrieb vor, soweit Ressourcen frei sind. Nach jeder Anfrage entladen gibt Speicher sofort frei.

':'

Qwen 1.7B nutzt die RTX 3060; natives Qwen Q8/Q4 und Pocket nutzen die CPU. Andere Deck-Modellaufträge werden koordiniert; fremde Dienste werden nicht gestoppt. Text wird nicht dauerhaft gespeichert. Ergebnisdateien bleiben auf Athena.

'}
`;} function bind(setup=false){const root=document.querySelector('#tts-panel');if(!root)return;const el=id=>root.querySelector('#'+id);let state,profiles=[],busy=false,lastResult='',backend='tts';const error=x=>{if(root.isConnected)el('tts-error').textContent=x;}; async function refresh(){try{state=await api(setup?'tts':backend);if(!root.isConnected)return;const rt=state.runtime,j=state.job;el('tts-status').textContent=setup?(rt.job?.phase||(rt.installed?'TTS ist eingerichtet.':'Noch nicht eingerichtet.')):(j?.phase||'Profil wählen und Text eingeben.')+` · ${backend!=='tts'?'CPU':'RTX 3060'} ${state.loaded?'geladen':'nicht geladen'}`; if(setup){el('tts-install').disabled=busy||rt.installed||rt.job?.state==='running';el('tts-install-cancel').disabled=rt.job?.state!=='running';el('tts-assign').disabled=busy||!rt.installed||!profiles.length;}