diff --git a/README.md b/README.md index c016ce8..805533c 100644 --- a/README.md +++ b/README.md @@ -299,3 +299,7 @@ Unter **KI-Werkzeuge → Embeddings** können Feature-Extraction-Modelle gesucht EmbeddingGemma 300M QAT Q8_0 (`ggml-org/embeddinggemma-300m-qat-q8_0-GGUF`, `embeddinggemma-300m-qat-Q8_0.gguf`) ist ausführbar. Tokenizer und Konfiguration sind in der GGUF-Datei enthalten; keine separaten Pflichtkomponenten. Vorhandenes llama.cpp wird auf CPU genutzt (0 GPU-Layer, CUDA-Geräte deaktiviert), unabhängig vom GPU-Modus. Einstellungen entsprechen dem alten Dienst: mean pooling, Kontext 4096 insgesamt, vier Slots, Batch 4096, Microbatch 1024, acht CPU-Threads. Der Worker bleibt nach Anfragen geladen und wird beim Endpunkt-Stopp beendet. Profil speichern und am Endpunkt freigeben. `POST /v1/embeddings` am gleichen authentifizierten API-Port wie Chat erwartet `model` (freigegebener Profilname) und `input` (Text oder bis zu 32 Texte). Unterstützt wird `encoding_format=float`; maximal etwa 1024 Token je Text, von llama.cpp geprüft. `GET /v1/embeddings/models` listet ausschließlich freigegebene Embedding-Profile. `/v1/models` bleibt die Chat-Liste. Andere Embedding-Familien sind ausdrücklich ungeprüft. Modellquellen und Profile werden über den bestehenden Backup/Restore-Pfad wiederhergestellt; der CPU-Prozess selbst wird bei Bedarf neu gestartet. + +Qwen-TTS verwendet wieder den Torch-CUDA-Graph-Pfad mit `faster-qwen3-tts==0.3.0`, derselben Beschleuniger-Version wie der alte Router. Die bestehende CustomVoice-Gewichtsdatei, Sprache und Stimme bleiben erhalten. Graphen werden beim Vorladen erfasst; die Bereitschaftsmeldung erfolgt erst danach. Modell und Graph-Pools bleiben zwischen Sätzen resident. Die serielle TTS-Warteschlange bleibt erhalten. + +Neuinstallationen installieren den Beschleuniger unter den bestehenden CUDA-/Transformers-Constraints. Bestehende TTS-Umgebungen werden vor dem nächsten Workerstart einmal geprüft und bei Bedarf automatisch ergänzt; `pip check` und ein Importtest müssen erfolgreich sein. Der Laufzeitstatus meldet Backend und Version. Ein Installationsfehler wird angezeigt, statt unbemerkt auf den langsamen Pfad zurückzufallen. Dazu ist beim ersten Upgrade Internetzugang nötig, danach läuft die Synthese offline. Kein zusätzlicher Container. Diese Beschleunigung ersetzt kein durchgängiges Audio-Streaming im Client und verändert nicht den Akzent der gewählten Stimme. diff --git a/benchmarks/tts-cuda-graphs-20261006.json b/benchmarks/tts-cuda-graphs-20261006.json new file mode 100644 index 0000000..baa5676 --- /dev/null +++ b/benchmarks/tts-cuda-graphs-20261006.json @@ -0,0 +1,31 @@ +{ + "gpu": "RTX 3060", + "model": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice", + "speaker": "Serena", + "language": "German", + "backend_version": "0.3.0", + "baseline_seconds": [ + 4.263, + 6.115, + 11.223 + ], + "baseline_audio_seconds": [ + 2.8, + 4.88, + 8.72 + ], + "cuda_graph_seconds": [ + 1.403, + 2.455, + 4.309 + ], + "cuda_graph_audio_seconds": [ + 2.88, + 5.04, + 9.04 + ], + "baseline_load_seconds": 7.07, + "cuda_graph_load_including_codec_warmup_seconds": 11.542, + "cuda_graph_observed_gpu_mib": 4714, + "note": "Synthetic German sentences, same text each pair. Sampling makes audio duration vary. Direct persistent worker timings, not end-to-end voice conversation latency; extra OmniVoice worker remained resident. No LLM was loaded during this benchmark." +} diff --git a/deploy/tts-requirements.lock b/deploy/tts-requirements.lock index 446c349..e5925a0 100644 --- a/deploy/tts-requirements.lock +++ b/deploy/tts-requirements.lock @@ -104,3 +104,5 @@ typing-inspection==0.4.4 typing_extensions==4.16.0 urllib3==2.8.0 uvicorn==0.54.0 + +faster-qwen3-tts==0.3.0 diff --git a/test_audio_residency.py b/test_audio_residency.py index 00f5588..04a5f21 100644 --- a/test_audio_residency.py +++ b/test_audio_residency.py @@ -25,7 +25,7 @@ class ResidencyTests(unittest.TestCase): script=Path(d)/'worker.py' script.write_text('import json,sys,pathlib\nprint(json.dumps({"ready":True}),flush=True)\nfor line in sys.stdin:\n q=json.loads(line);p=pathlib.Path(q["output"]);(p/"result.wav").write_bytes(b"synthetic wav");(p/"result.json").write_text(json.dumps({"ok":True}))\n') (Path(d)/'model').mkdir();(Path(d)/'model'/'model.safetensors').write_bytes(b'synthetic weights') - runtime=SimpleNamespace(paths=lambda:(Path(sys.executable),Path(d)/'model'),status=lambda:{'installed':True}) + runtime=SimpleNamespace(ensure_fast_backend=lambda:None,paths=lambda:(Path(sys.executable),Path(d)/'model'),status=lambda:{'installed':True}) profile=dict(id='p',kind='audio',runnable=True,parameters={'speed':1}) manager=TTSTests(Path(d)/'jobs',SimpleNamespace(status=lambda:{'profiles':[profile]}),runtime) worker=SimpleNamespace(stop=lambda:None) diff --git a/test_tts.py b/test_tts.py index 17be64b..bd866cd 100644 --- a/test_tts.py +++ b/test_tts.py @@ -41,16 +41,36 @@ class TTSTestsValidation(unittest.TestCase): class Model: @classmethod def from_pretrained(cls,*args,**kwargs):print('Library startup notice');return cls() + def _warmup(self,**kwargs):print('Graph capture notice') def generate_custom_voice(self,**kwargs):print('Library generation notice');return [[.1]*10],24000 with tempfile.TemporaryDirectory() as d: stdout=io.StringIO();stderr=io.StringIO() request=json.dumps(dict(output=d,text='Test',speaker='Ryan',language='German',speed=1))+'\n' - modules={'torch':SimpleNamespace(bfloat16='bf16',cuda=SimpleNamespace(empty_cache=lambda:None)),'soundfile':SimpleNamespace(write=lambda *a,**k:None),'qwen_tts':SimpleNamespace(Qwen3TTSModel=Model)} + modules={'torch':SimpleNamespace(set_float32_matmul_precision=lambda x:None,bfloat16='bf16',cuda=SimpleNamespace(empty_cache=lambda:None)),'soundfile':SimpleNamespace(write=lambda *a,**k:None),'faster_qwen3_tts':SimpleNamespace(FasterQwen3TTS=Model)} with patch.dict(sys.modules,modules),patch.object(sys,'argv',['worker','model']),patch.object(sys,'stdin',io.StringIO(request)),patch.object(sys,'stdout',stdout),patch.object(sys,'stderr',stderr): self.assertEqual(tts_worker.main(),0) self.assertEqual([json.loads(line) for line in stdout.getvalue().splitlines()],[{'ready':True}]) - self.assertIn('startup notice',stderr.getvalue());self.assertIn('generation notice',stderr.getvalue()) + self.assertIn('Graph capture notice',stderr.getvalue());self.assertIn('startup notice',stderr.getvalue());self.assertIn('generation notice',stderr.getvalue()) self.assertTrue(json.loads(Path(d,'result.json').read_text())['ok']) + def test_existing_environment_gets_pinned_accelerator_once(self): + from unittest.mock import patch + from tts_runtime import FAST_VERSION + with tempfile.TemporaryDirectory() as d: + root=Path(d);base=root/('a'*32);(base/'python/bin').mkdir(parents=True);(base/'python/bin/python').touch();(base/'model').mkdir();(base/'model/ready').touch();(root/'active.json').write_text('{"id":"'+base.name+'"}') + runtime=TTSRuntime(root) + with patch('tts_runtime.subprocess.run',side_effect=[SimpleNamespace(returncode=1),SimpleNamespace(returncode=0),SimpleNamespace(returncode=0),SimpleNamespace(returncode=0)]) as run: + runtime.ensure_fast_backend();runtime.ensure_fast_backend() + self.assertEqual(run.call_count,4) + self.assertIn('faster-qwen3-tts=='+FAST_VERSION,run.call_args_list[1].args[0]) + self.assertTrue(runtime.status()['backend_ready']) + def test_failed_upgrade_does_not_claim_fast_backend_is_ready(self): + from unittest.mock import patch + with tempfile.TemporaryDirectory() as d: + root=Path(d);base=root/('a'*32);(base/'python/bin').mkdir(parents=True);(base/'python/bin/python').touch();(base/'model').mkdir();(root/'active.json').write_text('{"id":"'+base.name+'"}') + runtime=TTSRuntime(root) + with patch('tts_runtime.subprocess.run',return_value=SimpleNamespace(returncode=1)): + with self.assertRaises(ValueError):runtime.ensure_fast_backend() + self.assertFalse(runtime.status()['backend_ready']);self.assertFalse(runtime.backend_checked) def test_long_text_chunks_preserve_all_words(self): from tts_worker import text_chunks text=('Dies ist ein längerer Satz mit mehreren Wörtern. '*25).strip() diff --git a/tts_runtime.py b/tts_runtime.py index a2c771a..933da89 100644 --- a/tts_runtime.py +++ b/tts_runtime.py @@ -1,12 +1,28 @@ """Own CUDA environment and pinned official CustomVoice model, installable via GUI.""" -import json,sys,time,os,uuid,shutil,threading,hashlib +import json,sys,time,os,uuid,shutil,threading,hashlib,subprocess from pathlib import Path from image_runtime import ImageRuntime +FAST_VERSION='0.3.0' REPO='Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice' REVISION='0c0e3051f131929182e2c023b9537f8b1c68adfe' SPEAKERS=['Vivian','Serena','Uncle_Fu','Dylan','Eric','Ryan','Aiden','Ono_Anna','Sohee'] LANGUAGES=['Auto','German','English','Chinese','Japanese','Korean','French','Russian','Portuguese','Spanish','Italian'] class TTSRuntime(ImageRuntime): + def __init__(self,root): + super().__init__(root);self.backend_lock=threading.Lock();self.backend_checked=False + def ensure_fast_backend(self): + # Upgrade existing writable environments as well as newly installed ones. + # Constraints keep CUDA, Transformers and the original model implementation unchanged. + with self.backend_lock: + if self.backend_checked:return + python,model=self.paths() + if not python.is_file():raise ValueError('Zuerst TTS einrichten.') + check='from importlib.metadata import version; assert version("faster-qwen3-tts")=='+repr(FAST_VERSION)+'; from faster_qwen3_tts import FasterQwen3TTS' + def run(args):return subprocess.run([str(a) for a in args],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=3600) + if run([python,'-c',check]).returncode: + if run([python,'-m','pip','install','--no-cache-dir','-c',Path(__file__).parent/'deploy/tts-requirements.lock','faster-qwen3-tts=='+FAST_VERSION]).returncode:raise ValueError('TTS-Beschleuniger konnte nicht installiert werden. Internetzugang und freien Speicher prüfen.') + if run([python,'-m','pip','check']).returncode or run([python,'-c',check]).returncode:raise ValueError('TTS-Beschleuniger: Laufzeitprüfung fehlgeschlagen.') + marker=model.parent/'fast-backend.tmp';marker.write_text(FAST_VERSION);marker.replace(model.parent/'fast-backend.version');self.backend_checked=True def paths(self): marker=self.root/'active.json' if marker.exists(): @@ -16,7 +32,7 @@ class TTSRuntime(ImageRuntime): def status(self): with self.lock: python,model=self.paths() - return dict(installed=python.is_file() and (model/'ready').exists(),job=dict(self.job) if self.job else None,repo=REPO,revision=REVISION,speakers=SPEAKERS,languages=LANGUAGES) + return dict(installed=python.is_file() and (model/'ready').exists(),job=dict(self.job) if self.job else None,backend='faster-qwen3-tts',backend_version=FAST_VERSION,backend_ready=(model.parent/'fast-backend.version').is_file() and (model.parent/'fast-backend.version').read_text()==FAST_VERSION,repo=REPO,revision=REVISION,speakers=SPEAKERS,languages=LANGUAGES) def ensure_library(self): if not self.status()['installed']:raise ValueError('Zuerst TTS einrichten.') _,model=self.paths();ident=hashlib.sha256((REPO+REVISION+'model.safetensors').encode()).hexdigest();target=self.root.parent/'models'/ident;target.mkdir(parents=True,exist_ok=True,mode=0o700) @@ -43,16 +59,17 @@ class TTSRuntime(ImageRuntime): base.mkdir(mode=0o700) self._phase('Eigene TTS-Python-Umgebung erstellen');self._command([sys.executable,'-m','venv',base/'python']) self._phase('CUDA-PyTorch installieren');self._command([python,'-m','pip','install','--no-cache-dir','torch==2.11.0','torchaudio==2.11.0','--index-url','https://download.pytorch.org/whl/cu128']) - self._phase('Qwen-TTS 0.1.1 installieren');self._command([python,'-m','pip','install','--no-cache-dir','-c',Path(__file__).parent/'deploy/tts-requirements.lock','qwen-tts==0.1.1']) + self._phase('Qwen-TTS 0.1.1 installieren');self._command([python,'-m','pip','install','--no-cache-dir','-c',Path(__file__).parent/'deploy/tts-requirements.lock','qwen-tts==0.1.1','faster-qwen3-tts=='+FAST_VERSION]) self._command([python,'-m','pip','check']) self._phase('Offizielles CUDA-Modell und Sprach-Tokenizer laden · rund 4,5 GB') code='from huggingface_hub import snapshot_download; snapshot_download(repo_id='+repr(REPO)+',revision='+repr(REVISION)+',local_dir='+repr(str(model))+',allow_patterns=["*.json","*.txt","*.safetensors"],max_workers=2)' self._command([python,'-c',code]) - self._phase('Dateien und Laufzeit prüfen');self._command([python,'-c','from qwen_tts import Qwen3TTSModel; import torch,soundfile; assert torch.version.cuda']) + self._phase('Dateien und Laufzeit prüfen');self._command([python,'-c','from qwen_tts import Qwen3TTSModel; from faster_qwen3_tts import FasterQwen3TTS; import torch,soundfile; assert torch.version.cuda']) for name in ['model.safetensors','config.json','merges.txt','vocab.json','tokenizer_config.json','speech_tokenizer/model.safetensors']: if not (model/name).is_file():raise RuntimeError('Modelldatei fehlt: '+name) if self.cancel.is_set():raise InterruptedError() (model/'ready').write_text(REVISION) + (base/'fast-backend.version').write_text(FAST_VERSION) marker=self.root/'active.tmp';marker.write_text(json.dumps(dict(id=base.name)));marker.replace(self.root/'active.json') self.ensure_library() state='complete';phase='TTS bereit · CUDA-Modell mit eingebauten Stimmen installiert' diff --git a/tts_test.py b/tts_test.py index 934a804..3533a83 100644 --- a/tts_test.py +++ b/tts_test.py @@ -76,6 +76,7 @@ class TTSTests: if directory.is_dir():(directory/'job.json').write_text(json.dumps(self.job)) finally:release() def _ensure(self,gpu): + self.runtime.ensure_fast_backend() python,model=self.runtime.paths() with self.lock: if self.cancel.is_set():raise InterruptedError() @@ -90,7 +91,7 @@ class TTSTests: if not ready.get('ready'):raise ValueError(ready.get('error','TTS-Modell konnte nicht geladen werden.')) return process def _required_vram_mib(self): - # Measured alongside the LLM: ~3767 MiB peak for ~3656 MiB weights. + # CUDA-graph worker measured at ~4.7 GiB for ~3656 MiB weights. # Leave 1.5 GiB for bounded sentence workspace and allocation variance. _,model=self.runtime.paths() try:return math.ceil((model/'model.safetensors').stat().st_size/1024**2)+1536 diff --git a/tts_worker.py b/tts_worker.py index 54d417b..1de1b6c 100644 --- a/tts_worker.py +++ b/tts_worker.py @@ -18,8 +18,13 @@ def main(): try: with contextlib.redirect_stdout(sys.stderr): import torch,soundfile as sf - from qwen_tts import Qwen3TTSModel - model=Qwen3TTSModel.from_pretrained(model_path,device_map='cuda:0',dtype=torch.bfloat16,attn_implementation='sdpa',local_files_only=True) + from faster_qwen3_tts import FasterQwen3TTS + torch.set_float32_matmul_precision('high') + model=FasterQwen3TTS.from_pretrained(model_path,device='cuda:0',dtype=torch.bfloat16,attn_implementation='sdpa',backend='torch',local_files_only=True) + # Pinned 0.3.0 uses this entry point; capture before advertising readiness. + model._warmup(prefill_len=100) + # Initialize the codec too, so its first-use cost stays out of live replies. + model.generate_custom_voice(text="Hallo.",language="German",speaker="Ryan",max_new_tokens=32) except Exception as exc: print(json.dumps(dict(ready=False,error='CUDA-Speicher reicht nicht aus.' if 'outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower() else 'TTS-Modell konnte nicht geladen werden.')),flush=True) return 1 @@ -34,8 +39,7 @@ def main(): waves,current_rate=model.generate_custom_voice(text=text,language=request['language'],speaker=request['speaker'],max_new_tokens=1024) if rate is not None and rate!=current_rate:raise ValueError('Inconsistent sample rate') rate=current_rate;pieces.append(waves[0]) - # Release temporary allocator blocks between sentences; weights stay loaded. - torch.cuda.empty_cache() + # Keep captured graph pools and model weights resident across sentences. if len(pieces)==1:wave=pieces[0] else: import numpy as np