Persist disjoint Strata and Qwen CPU placement with bounded TTS threads
This commit is contained in:
1 parent
0e3ad518d3
commit
ba4904ea78
13 files changed
+356
-11
No files matched your search
@@ -9,6 +9,7 @@ from catalog import repo_id,file_role,KINDS
|
||||
from profiles import SCHEMAS,CHAT_GPU_DEFAULTS,chat_parameters,FLOAT_PARAMETERS,ACE_COMPONENTS,qwen_clone_model
|
||||
SETTINGS=('soulx_singer-data/settings.json','xvc-data/settings.json','applio-data/settings.json','separator-profiles.json','profiles.json','reasoning-budget.json','endpoint.json','audio-policy.json','video/comfy-selection.json','models/huggingface.json','video/comfy-client-token','video/original-work/settings.json')
|
||||
MAX_HISTORY=40*1024**2
|
||||
SETTINGS+=('cpu-partition.json',)
|
||||
VERSION=1
|
||||
# Exact byte hash verified against official Hub metadata, not a filename heuristic.
|
||||
LOCAL_SOURCES={'83ee4f4f205fa514161778c41df1ea14144faa0f713510893b63c2395f5c2d53':dict(repo='unsloth/Qwen3.8-27B-GGUF',revision='4ca720788d1e01f1bff70c033e0d0028fd02e502',file='mmproj-BF16.gguf')}
|
||||
@@ -85,6 +86,9 @@ def validate(doc):
|
||||
pids.add(p['id']);names.add(name)
|
||||
settings=doc.get('settings')
|
||||
if not isinstance(settings,dict) or set(settings)-set(SETTINGS):raise ValueError('Unbekannte Einstellungsdateien.')
|
||||
if 'cpu-partition.json' in settings:
|
||||
from cpu_partition import validate as validate_cpu_partition
|
||||
validate_cpu_partition(settings['cpu-partition.json'])
|
||||
if 'reasoning-budget.json' in settings:
|
||||
from api_compat import reasoning_policy
|
||||
reasoning_policy(settings['reasoning-budget.json'])
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Opt-in Linux worker placement, stored alongside Deck's other settings."""
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
|
||||
NAME='cpu-partition.json'
|
||||
|
||||
def validate(value):
|
||||
if not isinstance(value,dict) or set(value)-{'version','strata','qwen_tts','qwen_generation_threads','qwen_codec_threads','qwen_cpu_flash_attention'} or not {'version','strata','qwen_tts'}<=set(value) or type(value['version']) is not int or value['version']!=1:raise ValueError('Ungültige CPU-Aufteilung.')
|
||||
for role in ('strata','qwen_tts'):
|
||||
ids=value[role]
|
||||
if not isinstance(ids,list) or not ids or any(type(n) is not int or not 0<=n<64 for n in ids) or len(set(ids))!=len(ids):raise ValueError('CPU-Aufteilung benötigt eindeutige CPU-IDs von 0 bis 63.')
|
||||
if set(value['strata']) & set(value['qwen_tts']):raise ValueError('Strata und Qwen-TTS dürfen keine CPU teilen.')
|
||||
for field in ('qwen_generation_threads','qwen_codec_threads'):
|
||||
n=value.get(field,4)
|
||||
if type(n) is not int or not 1<=n<=4:raise ValueError('Qwen-Threadzahlen müssen zwischen 1 und 4 liegen.')
|
||||
if type(value.get('qwen_cpu_flash_attention',True)) is not bool:raise ValueError('Qwen-CPU-Flash-Attention muss ein Wahrheitswert sein.')
|
||||
return value
|
||||
|
||||
def topology():
|
||||
result={}
|
||||
for cpu in sorted(os.sched_getaffinity(0)):
|
||||
root=Path('/sys/devices/system/cpu')/f'cpu{cpu}'/'topology'
|
||||
result[cpu]=(int((root/'physical_package_id').read_text()),int((root/'core_id').read_text()))
|
||||
return result
|
||||
|
||||
def placement(value,cores):
|
||||
"""Reject changed hardware and SMT siblings shared by the two workers."""
|
||||
validate(value)
|
||||
if not (set(value['strata'])|set(value['qwen_tts']))<=set(cores):raise ValueError('CPU-Aufteilung passt nicht zu den verfügbaren CPUs; Hardwarezuordnung prüfen.')
|
||||
a={cores[n] for n in value['strata']};b={cores[n] for n in value['qwen_tts']}
|
||||
if a & b:raise ValueError('Strata und Qwen-TTS dürfen keine SMT-Threads desselben Kerns teilen.')
|
||||
for role,selected in (('strata',a),('qwen_tts',b)):
|
||||
if {n for n,c in cores.items() if c in selected}!=set(value[role]):raise ValueError('CPU-Aufteilung muss alle verfügbaren SMT-Threads eines ausgewählten Kerns enthalten.')
|
||||
physical=[]
|
||||
for n in sorted(value['strata']):
|
||||
if all(cores[n]!=cores[p] for p in physical):physical.append(n)
|
||||
if len(physical)<2:raise ValueError('Strata benötigt mindestens zwei zugeordnete echte Kerne.')
|
||||
aux=sorted(set(value['strata'])-set(physical))
|
||||
if not aux:raise ValueError('Diese Strata-Aufteilung benötigt zusätzliche SMT-Threads für Hilfsthreads.')
|
||||
return dict(strata=sorted(value['strata']),qwen_tts=sorted(value['qwen_tts']),qwen_generation_threads=value.get('qwen_generation_threads',4),qwen_codec_threads=value.get('qwen_codec_threads',4),qwen_cpu_flash_attention=value.get('qwen_cpu_flash_attention',True),strata_arguments=['--host-core','first','--pool-cores',','.join(map(str,physical[1:])),'--pool-workers',str(len(physical)-1),'--aux-cpus',','.join(map(str,aux))])
|
||||
|
||||
def load(state):
|
||||
path=Path(state)/NAME
|
||||
if not path.exists():return None
|
||||
if not hasattr(os,'sched_setaffinity'):raise ValueError('CPU-Aufteilung benötigt Linux.')
|
||||
return placement(json.loads(path.read_text()),topology())
|
||||
|
||||
def command(argv,cpus):
|
||||
# A small exec launcher avoids preexec_fn in the multithreaded Deck server.
|
||||
return [sys.executable,str(Path(__file__).resolve()),','.join(map(str,cpus)),*map(str,argv)] if cpus else argv
|
||||
|
||||
def main():
|
||||
ids={int(n) for n in sys.argv[1].split(',')}
|
||||
if not ids or not ids<=os.sched_getaffinity(0):raise ValueError('Angeforderte CPUs sind für den Worker nicht verfügbar.')
|
||||
os.sched_setaffinity(0,ids)
|
||||
os.execv(sys.argv[2],sys.argv[2:])
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -9,6 +9,10 @@ Athena-Endpunkt und dessen Zugangsschutz. Kein separater Strata-Container oder
|
||||
|
||||
## Nativer Aufbau
|
||||
|
||||
Die optionale [CPU-Aufteilung](../docs/CPU_PARTITION.md) reserviert für Strata und
|
||||
Qwen-TTS getrennte Kernmengen. Sie verwendet die offiziellen nativen Strata-
|
||||
Startparameter; die upstream Engine und deren Server bleiben unverändert.
|
||||
|
||||
Debian 12/13 x86_64, AVX2, NVIDIA-Treiber kompatibel mit CUDA 13 (>=580), zwei
|
||||
NVIDIA-GPUs, Python >=3.12 samt venv, git, g++, make, CA-Zertifikate. Debian 12
|
||||
benötigt eine separat provisionierte unterstützte Python-3.12-Version; kein
|
||||
|
||||
@@ -22,6 +22,7 @@ FILES += ['soulx_singer.py','soulx_singer_runtime.py','soulx-singer-ui.js','depl
|
||||
FILES += sorted(str(p.relative_to(ROOT)) for folder in ('soulx-singer-web','soulx-singer-svc') for p in (ROOT/'deploy'/folder).rglob('*') if p.is_file() and '__pycache__' not in p.parts)
|
||||
FILES += ['xvc.py','xvc_runtime.py','xvc_sources.json','xvc-ui.js','deploy/xvc-requirements.lock','deploy/prepare_xvc.py']
|
||||
FILES += ['cuda_overlay.py','remix.py','remix_runtime.py','remix_worker.py','remix_sources.json','clearvoice_worker.py','deploy/ladypoly/patch_remix.py']
|
||||
FILES += ['cpu_partition.py']
|
||||
FILES += ['deploy/read_backup_snapshot.py','speech_text.py','tts_text_enhancer.py','strata_runtime.py','strata_worker.py','strata-ui.js','strata_sources.json','deploy/install_strata.py','deploy/strata_toolkit.py','deploy/strata-cuda13.lock.json','deploy/STRATA_NATIVE.md']
|
||||
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/xvc-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
|
||||
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/applio-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# CPU-Zuordnung für Strata und Qwen-TTS
|
||||
|
||||
Die optionale Datei `DECK_STATE_DIR/cpu-partition.json` trennt die Linux-CPU-
|
||||
Zuordnung beider Worker. Ohne diese Datei bleibt das bisherige Verhalten erhalten.
|
||||
Auf Athena (Ryzen 5 5600, sechs echte Kerne, zwölf SMT-Threads) ist vorgesehen:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"strata": [0, 1, 2, 3, 6, 7, 8, 9],
|
||||
"qwen_tts": [4, 5, 10, 11],
|
||||
"qwen_generation_threads": 2,
|
||||
"qwen_codec_threads": 2,
|
||||
"qwen_cpu_flash_attention": false
|
||||
}
|
||||
```
|
||||
|
||||
Die IDs sind **logische CPUs**, keine Anzahl echter Kerne. Die SMT-Paare dieses
|
||||
Hosts lauten 0/6, 1/7, 2/8, 3/9, 4/10 und 5/11. Strata erhält vier echte Kerne,
|
||||
Qwen-TTS zwei. Diese Host-Zuordnung nicht ungeprüft auf einen anderen Rechner
|
||||
übertragen. Deck prüft verfügbare IDs, Überschneidungen und vollständige SMT-Paare
|
||||
vor dem Start; eine ungültige Zuordnung wird nicht still ignoriert.
|
||||
|
||||
## Umsetzung und Grenzen
|
||||
|
||||
`cpu_partition.py` setzt die Startaffinität vor `exec`, ohne `preexec_fn` im
|
||||
mehrthreadigen Deck-Server. Der Strata-Python-Server und seine Kinder erben die
|
||||
Strata-Zuordnung. Zusätzlich verwendet die unveränderte offizielle Engine ihre
|
||||
dokumentierten Optionen: Host auf CPU0, Expertenpool auf1/2/3, Hilfsthreads auf
|
||||
6/7/8/9 (`--host-core`, `--pool-cores`, `--pool-workers`, `--aux-cpus`). Bei
|
||||
aktivierter Aufteilung hält Deck `strata_tune.aux_cpus=1` gesetzt, weil ein
|
||||
requestseitiges Abschalten die native Hilfsthread-Zuordnung aufheben würde.
|
||||
Die übrigen Sampling-, GPU-, Kontext- und Slot-Einstellungen bleiben erhalten.
|
||||
|
||||
Qwen erbt den gesamten TTS-CPU-Bereich ohne zusätzliche Bindung jedes einzelnen
|
||||
Bibliotheksthreads. Threadzahlen und CPU-Flash-Attention sind ausdrücklich in
|
||||
derselben Datei gespeichert; auf zwei echten Kernen werden zwei Generierungs-
|
||||
und zwei Codec-Threads verwendet, CPU-Flash-Attention aus. Zwei Codec-Frames
|
||||
und Nice10 bleiben erhalten. Die vorherigen vier plus vier Threads waren im
|
||||
Zweikern-Test deutlich langsamer. Eine andere optionale Einstellung wird nicht
|
||||
aus einem versteckten Hook oder einer veränderten Bibliothek geladen.
|
||||
Ohne Aufteilungsdatei bleiben vier plus vier Threads und CPU-Flash-Attention an.
|
||||
|
||||
Das sind Affinitätseinstellungen für diese beiden Worker, **keine exklusive
|
||||
Host-Cpuset-Partition**. Betriebssystem, andere Dienste und Deck-Hilfsprozesse
|
||||
können diese CPUs weiterhin verwenden. Native Bibliotheken könnten Affinität
|
||||
selbst verändern; deshalb bei Laufzeitupdates alle Threadmasken unter echter
|
||||
Last erneut prüfen. Die Strata-Optionen decken auch ihre eigens gepinnten
|
||||
Pool-, Host- und Hilfsthreads ab. Keine Bibliothek wurde dafür gepatcht.
|
||||
|
||||
## Installation, Neustart und Wiederherstellung
|
||||
|
||||
Die Datei gehört dem Deck-Dienstbenutzer (0600). Änderungen im Leerlauf
|
||||
vornehmen und die Worker regulär neu laden. Laufende Arbeit nicht abbrechen.
|
||||
Die aktuelle Containerinstallation benötigt insgesamt `cpu_limit:12` in ihrer
|
||||
Host-`installation.json`; das gemeinsame Acht-CPU-Limit würde beide Worker
|
||||
weiterhin zusammen drosseln. `deploy/install.py` übernimmt diesen bestehenden
|
||||
Manifestwert bei jeder Neuerstellung. Die CPU-Datei liegt im persistenten
|
||||
Zustandsvolume und ist in Decks validierter, verschlüsselter
|
||||
Konfigurationssicherung enthalten.
|
||||
|
||||
Für den nativen Debian/systemd-Betrieb dieselbe Datei in die ausdrücklich
|
||||
konfigurierte Zustandswurzel zurückspielen, Dienstbenutzerrechte erhalten und
|
||||
den aktualisierten Deck-Code einschließlich `cpu_partition.py` installieren.
|
||||
Der übergeordnete Dienst muss alle zugeordneten CPUs erreichen dürfen:
|
||||
auf diesem Host `CPUQuota=1200%`, kein übergeordnetes `AllowedCPUs`, das einen
|
||||
der beiden Bereiche ausschließt. Die Worker brauchen weder Docker-Zugriff noch
|
||||
einen zusätzlichen Dienst. Vor dem Start auf neuer Hardware die reale Topologie
|
||||
prüfen und die Zuordnung anpassen. Der vollständige native Neuaufbau bleibt
|
||||
innerhalb der bestehenden [Installationsanforderungen](../deploy/NATIVE_INSTALL_REQUIREMENTS.md)
|
||||
noch separat abzunehmen; diese Änderung behauptet keinen vollständigen Host-Restore.
|
||||
|
||||
Rückfall im Leerlauf: `cpu-partition.json` aus der aktiven Zustandswurzel entfernen
|
||||
und Worker regulär neu starten. Die Quota kann anschließend auf den vorherigen
|
||||
Manifestwert8 zurückgesetzt werden. Ein Rückfall auf ein älteres Deck-Image
|
||||
benötigt ebenfalls das Entfernen dieser Datei, da ältere Versionen sie nicht
|
||||
auswerten. Keine Profile, Stimmen, Modelle oder Zugangsdaten dafür löschen.
|
||||
@@ -1,3 +1,17 @@
|
||||
## Strata/TTS CPU allocation ·22 October2026
|
||||
|
||||
Saved allocation:Strata0–3/6–9(four physical cores/eight SMT threads),
|
||||
Qwen-TTS4–5/10–11(two physical cores/four SMT threads). Shared Deck quota12,
|
||||
RAM59GiB and GPU settings unchanged. Qwen uses explicitly saved2generation/
|
||||
2codec threads, CPU-Flash-Attention off; no native per-thread pinning.
|
||||
No Hermes configuration or extra persistent service was introduced.
|
||||
This is worker affinity, not host-wide exclusive CPUs or a guarantee of smooth
|
||||
Conduit playback. Final live TTS test:17.76s audio in22.07s (RTF1.243), all
|
||||
observed worker affinities disjoint. Two physical TTS cores still fall short of
|
||||
realtime. Earlier CPU8 entries below describe their historical state.
|
||||
[Configuration/native restore](CPU_PARTITION.md) ·
|
||||
[Activation and test limitations](maintenance/2026-10-22-cpu-partition.md).
|
||||
|
||||
## Qwen Q4 CPU speech ·22 October2026
|
||||
|
||||
Michael selected Qwen0.6B Q4_K_M with the existing Q8 codec and Anna reference.
|
||||
|
||||
@@ -40,8 +40,13 @@ dieselbe private Anna-Referenz und die bereits installierte CPU-Laufzeit0.4.2.
|
||||
|
||||
## Ressourcen und Verhalten
|
||||
|
||||
- Vier Generierungs- und vier Decoder-Threads, zwei Codec-Frames (160ms),
|
||||
CPU-Fused-Attention; feste deterministische Sampling-Einstellungen wie im Test.
|
||||
Optionale feste Trennung von Strata und Qwen auf vollständige physische Kerne:
|
||||
[CPU-Zuordnung, native Einrichtung und Rückfall](CPU_PARTITION.md).
|
||||
|
||||
- Ohne CPU-Aufteilungsdatei vier Generierungs- und vier Decoder-Threads,
|
||||
CPU-Fused-Attention. Die optionale Aufteilungsdatei speichert abweichende
|
||||
Threadzahlen und den CPU-Attention-Modus ausdrücklich. Zwei Codec-Frames
|
||||
(160ms) und feste deterministische Sampling-Einstellungen bleiben erhalten.
|
||||
- Gespeicherte Referenzmerkmale werden im persistenten Worker einmal vorbereitet.
|
||||
Referenzdaten verlassen Athena nicht. Native Bibliotheksausgaben gelangen
|
||||
nicht in das JSON-Steuerprotokoll; Prompts werden nicht protokolliert.
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Strata/TTS CPU partition ·22 October2026
|
||||
|
||||
Michael requested eight logical CPUs for Strata and the remaining four for
|
||||
Qwen-TTS, without sharing physical cores between them. Ryzen5 5600 has six
|
||||
physical cores and twelve SMT threads. The saved allocation is Strata0–3/6–9
|
||||
(four physical cores), Qwen4–5/10–11(two physical cores).
|
||||
|
||||
The shared Deck quota must be12, not8. Otherwise a cgroup-wide eight-CPU time
|
||||
budget still couples the two workers. The host install manifest persists12;
|
||||
`DECK_STATE_DIR/cpu-partition.json` persists their independent placements.
|
||||
RAM remains59GiB; GPU order, split16, reserves1024MiB each, Strata IQ3 dual
|
||||
slots/context, QwenQ4/codec/Anna and all Hermes settings are unchanged.
|
||||
|
||||
## Implementation and persistence
|
||||
|
||||
Deck's small exec launcher sets initial Linux affinity. Official Strata flags
|
||||
place its host on the first allowed core, pool workers on1/2/3, helpers on6–9.
|
||||
The installed engine expects `--host-core first`, not a numericCPU ID. An
|
||||
initial numeric argument caused startup rejection; the previous container and
|
||||
manifest were restored before the corrected version was activated. No user
|
||||
chat/profile/model files were changed during that recovery.
|
||||
|
||||
The original upstream engine/server and native Qwen library remain unmodified.
|
||||
Qwen inherits its process affinity; its separate native per-thread masks remain
|
||||
off. The final explicit settings use2generation/2codec threads and disable
|
||||
CPU-Flash-Attention on this two-core allocation, preserving2codecframes/Nice10.
|
||||
Without a partition file, the old4/4/CPU-Flash-Attention defaults remain intact.
|
||||
Deck holds Strata's helper placement on per request.
|
||||
Settings validation rejects shared physical cores, missing SMT siblings,
|
||||
unavailable IDs and malformed masks. No partition file means previous behavior.
|
||||
The new file is part of validated encrypted settings backup; its real settings
|
||||
restore and removal when restoring an older backup were tested locally.
|
||||
|
||||
Maintenance stage:`/opt/athena-deck-dev/cpu-partition-20261022`. Public source
|
||||
transfers have old/new SHA256 checks; originals are scoped code-only copies.
|
||||
The only private rollback artifact is the previous installation manifest.
|
||||
No broad state/appdata backup, private audio copy or new auxiliary service.
|
||||
Activation checks the normal authenticated API twice for0active requests.
|
||||
Only the existing Deck container is restarted. A minimal code-only image layer
|
||||
uses the normal explicit installer FILES list on the current runtime; no apt,
|
||||
compiler, model download, image flattening or Hermes image build is involved.
|
||||
Prior image remains available; stale stopped maintenance containers are removed
|
||||
after successful verification.
|
||||
|
||||
See[CPU configuration and native restore](../CPU_PARTITION.md) for the complete
|
||||
file, Linux/systemd requirements, host-affinity limitations and rollback. The
|
||||
full native installer/host restore remains an existing open qualification.
|
||||
|
||||
## Validation
|
||||
|
||||
32 focused CPU/Qwen/Strata/settings-backup tests passed with the existing
|
||||
bundled Python/cryptography runtime. The broader98-test attempt passed the
|
||||
streaming/endpoint tests with2pre-existing skips; its2backup cases initially
|
||||
needed the already installed cryptography dependency and then passed in the
|
||||
focused run. Python compilation and diff whitespace checks passed.
|
||||
|
||||
The bounded benchmark sends synthetic LLM and TTS requests through the existing
|
||||
normal Athena API. It discards PCM after counting bytes/arrival times; no user
|
||||
utterance or recording is inspected. `before.json` and `after.json` contain
|
||||
technical results only. It is not an actual Conduit phone/playback test.
|
||||
|
||||
Before partitioning:18.08s PCM in18.855s (RTF1.043), firstPCM0.660s,
|
||||
longest arrival gap1.500s, computed additional startup reserve6.718s. Strata
|
||||
ran10.764s/566completion tokens, with10.032s overlap. The initial process-tree
|
||||
observer missed thread-owned children and recorded no baseline masks; that
|
||||
observer was fixed before the final affinity test. Baseline timing is unaffected.
|
||||
This single request pair is not a replicated causal throughput benchmark.
|
||||
|
||||
The initial partition trial with4/4threads and native per-thread masks produced
|
||||
the same18.08s PCM in133.568s (RTF7.388); the trace confirmed all Strata threads
|
||||
stayed on0–3/6–9 and Qwen on4–5/10–11. Allowing the existing Qwen threads to
|
||||
move within its four logical CPUs did not fix it:163.544s/18.08s, RTF9.046.
|
||||
These intermediate worker settings were rejected. They must not be documented
|
||||
as successful realtime speech merely because the CPU sets were disjoint.
|
||||
|
||||
A separate bounded native CPU test with2/2threads, no explicit per-thread mask
|
||||
and no CPU-Flash-Attention environment override generated18.08s in22.488s
|
||||
(RTF1.244), firstPCM0.384s, load3.032s. It used the existing host CPU venv,
|
||||
the same public Q4/Q8-codec files and existing private Anna reference in place,
|
||||
without copying/saving audio. The transient unit was limited to90s,6GiB/no swap,
|
||||
the same four TTS logical CPUs, private devices/network andNice10. This host
|
||||
Python test is not identical to the production container runtime or evidence
|
||||
of a complete Conduit fix. An additional2/1test with explicit CPU-Flash-Attention
|
||||
did not finish successfully within its bounded probe;1/1was therefore not run.
|
||||
Thread count and the CPU attention path were not independently isolated in
|
||||
these trials, so do not assign their speed difference to only one setting.
|
||||
|
||||
## Final production verification
|
||||
|
||||
Active image:`athena-deck-standalone:c7daa70ee03cd944`, shared quota12,
|
||||
saved2/2thread/CPU-Flash-Attention-off settings. Original Strata dual model
|
||||
reloaded through the normal one-token API:HTTP200,46.292s including loading.
|
||||
The final test sent only the synthetic TTS passage because an existing Strata
|
||||
request was active and Michael said“jetzt los”. No additional LLM request was
|
||||
started; the existing request was not read or cancelled. Its exact generation
|
||||
overlap and load characteristics were not measured, so this is not a matched
|
||||
comparison with the earlier synthetic pair.
|
||||
|
||||
Final TTS:17.76s PCM in22.068s, RTF1.243, firstPCM0.571s, longest packet gap
|
||||
0.425s, calculated extra startup reserve3.875s. All observed Qwen threads had
|
||||
mask4–5/10–11. Strata host0, experts1/2/3, all other observed native threads6–9.
|
||||
No observed physical-core overlap. This verifies the requested partition;
|
||||
**two physical TTS cores still did not sustain realtime speech**. No actual
|
||||
Conduit call/handset playback was triggered or claimed fixed. The separate
|
||||
thread/attention tuning changed the sample's duration slightly; no audio-
|
||||
identity or perceptual-quality equivalence claim is made.
|
||||
+8
-3
@@ -3,6 +3,7 @@ import json,os,select,subprocess
|
||||
from pathlib import Path
|
||||
from pocket import Pocket
|
||||
from qwen_native_runtime import supported,model_quant
|
||||
import cpu_partition
|
||||
|
||||
class QwenNative(Pocket):
|
||||
name='Qwen3-TTS'
|
||||
@@ -48,7 +49,10 @@ class QwenNative(Pocket):
|
||||
def _ensure_cpu(self,p):
|
||||
codec=self.profiles._component(p['model'],'codec',p.get('components',{}).get('codec'))
|
||||
voice=self.voice_path('default')
|
||||
key=(p['id'],p['revision'],codec['id'],str(self.runtime.paths()[0]),str(voice),voice.stat().st_mtime_ns)
|
||||
layout=cpu_partition.load(self.root.parent);cpus=layout['qwen_tts'] if layout else []
|
||||
gen,decoder=(layout['qwen_generation_threads'],layout['qwen_codec_threads']) if layout else (4,4)
|
||||
flash=layout['qwen_cpu_flash_attention'] if layout else True
|
||||
key=(p['id'],p['revision'],codec['id'],str(self.runtime.paths()[0]),str(voice),voice.stat().st_mtime_ns,tuple(cpus),gen,decoder,flash)
|
||||
if self.process and self.process.poll() is None and self.session_key==key:return self.process
|
||||
mem=Path('/host/proc/meminfo')
|
||||
if not mem.is_file():mem=Path('/proc/meminfo')
|
||||
@@ -61,8 +65,9 @@ class QwenNative(Pocket):
|
||||
model=self.profiles.catalog.root/p['model']['id']/'model.gguf'
|
||||
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),model_quant(p['model'])],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env,start_new_session=True,text=True,bufsize=1)
|
||||
env.update(CUDA_VISIBLE_DEVICES='',HF_HUB_OFFLINE='1',HF_HUB_DISABLE_IMPLICIT_TOKEN='1',OMP_NUM_THREADS=str(gen),OPENBLAS_NUM_THREADS='1',QWENTTS_CPU_FLASH_ATTN='1' if flash else '0',HOME=str(self.root))
|
||||
argv=[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']),','.join(map(str,cpus)),str(gen),str(decoder)]
|
||||
process=subprocess.Popen(cpu_partition.command(argv,cpus),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())
|
||||
|
||||
+10
-2
@@ -12,19 +12,27 @@ def onset_profile(quant):
|
||||
if quant=='Q4':return 'off'
|
||||
raise ValueError('Unbekannte Qwen-Quantisierung.')
|
||||
|
||||
def thread_options(generation=4,codec=4):
|
||||
if any(type(n) is not int or not 1<=n<=4 for n in (generation,codec)):raise ValueError('Ungültige Qwen-Threadzahl.')
|
||||
return dict(cpu_threads=generation,cpu_codec_threads=codec)
|
||||
|
||||
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)
|
||||
cpus=sys.argv[5] if len(sys.argv)>5 else ''
|
||||
threads=thread_options(int(sys.argv[6]),int(sys.argv[7])) if len(sys.argv)>7 else thread_options()
|
||||
os.nice(10)
|
||||
resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3))
|
||||
import numpy as np
|
||||
import qwentts_cpp_cpu as q
|
||||
from tts_worker import spoken_chunks
|
||||
assert q.CPU_ONLY is True and q.QT_ABI_VERSION==5
|
||||
model=q.QwenTTS(sys.argv[1],sys.argv[2],cpu_threads=4,cpu_codec_threads=4,cpu_stream_frames=2,clamp_fp16=False,use_fa=True)
|
||||
# Inherit the process's TTS CPU set. Additional per-thread native pinning
|
||||
# oversubscribes two physical cores when generation and codec overlap.
|
||||
model=q.QwenTTS(sys.argv[1],sys.argv[2],cpu_stream_frames=2,clamp_fp16=False,use_fa=True,**threads)
|
||||
voices={}
|
||||
def voice_for(path):
|
||||
path=Path(path);key=(str(path),path.stat().st_mtime_ns)
|
||||
@@ -36,7 +44,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,quant=quant))
|
||||
emit(dict(ready=True,cpu_only=True,quant=quant,cpu_allowed=cpus,**threads))
|
||||
except Exception as exc:
|
||||
emit(dict(ready=False,error='Qwen-CPU konnte nicht laden ('+type(exc).__name__+').'));return 1
|
||||
for line in sys.stdin:
|
||||
|
||||
+11
-4
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from image_test import probe
|
||||
from inference import InferenceError,MemoryAdmissionError
|
||||
from strata_runtime import RECIPE
|
||||
import cpu_partition
|
||||
def performance_tuning(quant,devices,parameters,cpu=None):
|
||||
"""Apply measured tuning only to the qualified hardware and layer layout."""
|
||||
tuning=RECIPE.get("performance",{}).get(quant,{})
|
||||
@@ -16,7 +17,7 @@ def performance_tuning(quant,devices,parameters,cpu=None):
|
||||
|
||||
class StrataWorker:
|
||||
def __init__(self,root,catalog,runtime):
|
||||
self.root=Path(root);self.catalog=catalog;self.runtime=runtime;self.lock=threading.RLock();self.process=None;self.profile=None;self.port=None;self.key=None;self.devices=[];self.state='stopped';self.error=None;self.phase='Gestoppt';self.memory_plan=None
|
||||
self.root=Path(root);self.catalog=catalog;self.runtime=runtime;self.lock=threading.RLock();self.process=None;self.profile=None;self.port=None;self.key=None;self.devices=[];self.state='stopped';self.error=None;self.phase='Gestoppt';self.memory_plan=None;self.cpu_layout=None
|
||||
def blockers(self,p):
|
||||
try:
|
||||
if not self.runtime.status()['installed']:raise ValueError('Strata-Laufzeit fehlt. Unter Laufzeiten → Strata installieren.')
|
||||
@@ -27,7 +28,7 @@ class StrataWorker:
|
||||
def status(self):
|
||||
with self.lock:
|
||||
if self.process and self.process.poll() is not None:self.state='failed';self.error='Strata-Modellprozess beendet. Speicher und eigenes Worker-Protokoll prüfen.'
|
||||
return dict(runtime='strata',state=self.state,profile_id=self.profile['id'] if self.profile else None,profile_name=self.profile['name'] if self.profile else None,port=self.port,error=self.error,gpus=self.devices,memory_plan=self.memory_plan,phase=self.phase)
|
||||
return dict(runtime='strata',state=self.state,profile_id=self.profile['id'] if self.profile else None,profile_name=self.profile['name'] if self.profile else None,port=self.port,error=self.error,gpus=self.devices,memory_plan=self.memory_plan,phase=self.phase,cpu_allowed=self.cpu_layout['strata'] if self.cpu_layout else None)
|
||||
def plan(self,p,cancel=lambda:False):
|
||||
errors=self.blockers(p)
|
||||
if errors:raise InferenceError('; '.join(errors))
|
||||
@@ -43,8 +44,10 @@ class StrataWorker:
|
||||
return self.memory_plan
|
||||
def ensure(self,p,cancel=lambda:False):
|
||||
with self.lock:
|
||||
if self.process and self.process.poll() is None and self.profile and (p['id'],p['revision'])==(self.profile['id'],self.profile['revision']):return
|
||||
layout=cpu_partition.load(self.root.parent)
|
||||
if self.process and self.process.poll() is None and self.profile and (p['id'],p['revision'])==(self.profile['id'],self.profile['revision']) and layout==self.cpu_layout:return
|
||||
self.stop();self.plan(p,cancel);self.state='loading';self.error=None;self.phase='Strata-Modell laden'
|
||||
self.cpu_layout=layout
|
||||
params=p['parameters'];entry=self.catalog.entry(p['model_id']);q,m=self.runtime.prepared(entry);python,source=self.runtime.paths();data=self.runtime.storage
|
||||
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
with socket.socket() as s:s.bind(('127.0.0.1',0));self.port=s.getsockname()[1]
|
||||
@@ -57,6 +60,7 @@ class StrataWorker:
|
||||
if flag in args:
|
||||
i=args.index(flag);del args[i:i+2]
|
||||
args += [flag,str(value)]
|
||||
if layout:args+=layout['strata_arguments']
|
||||
if params['strata_experts']=='resident':args.append('--resident-experts')
|
||||
else:args.append('--mmap-experts')
|
||||
config=dict(exe=str(source/'engine/strata'),args=args,cwd=str(source),tokenizer=str(data/m['pack']/'tokenizer'),model_name=p['api_id'],host='127.0.0.1',port=self.port,api_key=self.key,gpu=[i for uuid in self.devices for i,g in enumerate(probe()) if g['uuid']==uuid],gpu_order='as_given',layer_split=str(params['strata_layer_split']),vram_elastic=False,open_browser=False,log=str(self.root/'engine.log'))
|
||||
@@ -72,7 +76,7 @@ class StrataWorker:
|
||||
libs=self.runtime.root/'cuda/lib64'
|
||||
if libs.is_dir() or (self.runtime.root/'cuda/lib').is_dir():env['LD_LIBRARY_PATH']=str(libs)+os.pathsep+str(self.runtime.root/'cuda/lib')+os.pathsep+env.get('LD_LIBRARY_PATH','')
|
||||
self.profile=p
|
||||
with (self.root/'server.log').open('w') as output:self.process=subprocess.Popen(self.command(python,source,path,self.port),cwd=source,env=env,stdout=output,stderr=subprocess.STDOUT,start_new_session=True)
|
||||
with (self.root/'server.log').open('w') as output:self.process=subprocess.Popen(cpu_partition.command(self.command(python,source,path,self.port),layout['strata'] if layout else None),cwd=source,env=env,stdout=output,stderr=subprocess.STDOUT,start_new_session=True)
|
||||
try:
|
||||
deadline=time.monotonic()+600
|
||||
while time.monotonic()<deadline:
|
||||
@@ -115,6 +119,9 @@ class StrataWorker:
|
||||
def connect(self):return http.client.HTTPConnection('127.0.0.1',self.port,timeout=120),self.key
|
||||
def prepare_request(self,body):
|
||||
body=dict(body);options=body.pop('chat_template_kwargs',{})
|
||||
# Keep the official native helper-thread placement active while partitioned.
|
||||
# A request's aux_cpus=0 would otherwise undo it (including checkpoint threads).
|
||||
if self.cpu_layout:body['strata_tune']={**body.get('strata_tune',{}),'aux_cpus':1}
|
||||
if options.get('enable_thinking') is False:body['reasoning_effort']='none'
|
||||
elif 'reasoning_effort' not in body:body['reasoning_effort']='high'
|
||||
if body.get('reasoning_effort')=='xhigh':body['reasoning_effort']='high'
|
||||
|
||||
@@ -75,6 +75,19 @@ class RestoreTests(unittest.TestCase):
|
||||
validate(doc)
|
||||
bad=copy.deepcopy(doc);bad['settings']['profiles.json'][0]['components']['codec']='0'*64
|
||||
with self.assertRaises(ValueError):validate(bad)
|
||||
def test_cpu_partition_survives_settings_backup_and_rejects_overlap(self):
|
||||
from test_cpu_partition import PLAN
|
||||
(self.root/'cpu-partition.json').write_text(json.dumps(PLAN))
|
||||
doc=self.server.backup.snapshot(include_history=False);validate(doc)
|
||||
self.assertEqual(doc['settings']['cpu-partition.json'],PLAN)
|
||||
restored=open_backup(seal(doc,'backup secure password'),'backup secure password')
|
||||
self.assertEqual(restored['settings']['cpu-partition.json'],PLAN)
|
||||
(self.root/'cpu-partition.json').unlink();self.server.backup._apply_settings(restored)
|
||||
self.assertEqual(json.loads((self.root/'cpu-partition.json').read_text()),PLAN)
|
||||
legacy=copy.deepcopy(restored);legacy['settings'].pop('cpu-partition.json')
|
||||
self.server.backup._apply_settings(legacy);self.assertFalse((self.root/'cpu-partition.json').exists())
|
||||
bad=copy.deepcopy(doc);bad['settings']['cpu-partition.json']['qwen_tts'].append(0)
|
||||
with self.assertRaises(ValueError):validate(bad)
|
||||
def test_remix_runtime_recipe_and_restore(self):
|
||||
from remix_runtime import VERSION
|
||||
self.server.remix_runtime.status=Mock(return_value=dict(installed=True,version=VERSION,job=None))
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import copy,json,sys,tempfile,unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock,patch
|
||||
import cpu_partition as cpu
|
||||
|
||||
PLAN=dict(version=1,strata=[0,1,2,3,6,7,8,9],qwen_tts=[4,5,10,11],qwen_generation_threads=2,qwen_codec_threads=2,qwen_cpu_flash_attention=False)
|
||||
CORES={n:(0,n%6) for n in range(12)}
|
||||
|
||||
class CPUPlacementTests(unittest.TestCase):
|
||||
def test_complete_physical_cores_and_native_strata_roles(self):
|
||||
p=cpu.placement(PLAN,CORES);args=p['strata_arguments']
|
||||
self.assertEqual(args,['--host-core','first','--pool-cores','1,2,3','--pool-workers','3','--aux-cpus','6,7,8,9'])
|
||||
self.assertEqual({CORES[n] for n in p['qwen_tts']},{(0,4),(0,5)})
|
||||
self.assertFalse(set(p['strata']) & set(p['qwen_tts']))
|
||||
def test_reject_shared_physical_core_missing_sibling_and_changed_hardware(self):
|
||||
for change,cores in ((dict(strata=[0,1,2,3,6,7,8],qwen_tts=[4,5,9,10,11]),CORES),(dict(qwen_tts=[4,5]),CORES),({}, {n:c for n,c in CORES.items() if n!=11})):
|
||||
with self.subTest(change=change),self.assertRaises(ValueError):cpu.placement({**PLAN,**change},cores)
|
||||
def test_reject_invalid_or_overlapping_ids(self):
|
||||
for change in (dict(version=True),dict(strata=[True]),dict(strata=[0,0]),dict(qwen_tts=[64]),dict(qwen_tts=[3,4,5,10,11]),dict(extra='unknown'),dict(qwen_generation_threads=0),dict(qwen_codec_threads=True),dict(qwen_cpu_flash_attention=0)):
|
||||
with self.subTest(change=change),self.assertRaises(ValueError):cpu.validate({**PLAN,**change})
|
||||
def test_opt_in_and_roundtrip_load(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
self.assertIsNone(cpu.load(tmp))
|
||||
(Path(tmp)/cpu.NAME).write_text(json.dumps(PLAN))
|
||||
with patch.object(cpu,'topology',return_value=CORES),patch.object(cpu.os,'sched_setaffinity',create=True):self.assertEqual(cpu.load(tmp),cpu.placement(PLAN,CORES))
|
||||
def test_exec_wrapper_applies_affinity_before_replacing_itself(self):
|
||||
argv=['python','4,5,10,11','/runtime/python','worker.py','a path with spaces']
|
||||
with patch.object(sys,'argv',argv),patch.object(cpu.os,'sched_getaffinity',return_value=set(range(12)),create=True),patch.object(cpu.os,'sched_setaffinity',create=True) as pin,patch.object(cpu.os,'execv') as execute:
|
||||
cpu.main();pin.assert_called_once_with(0,{4,5,10,11});execute.assert_called_once_with('/runtime/python',argv[2:])
|
||||
with patch.object(sys,'argv',argv),patch.object(cpu.os,'sched_getaffinity',return_value={0,1},create=True),patch.object(cpu.os,'execv') as execute,self.assertRaises(ValueError):cpu.main()
|
||||
execute.assert_not_called()
|
||||
def test_qwen_thread_budget_and_strata_cannot_disable_helper_placement(self):
|
||||
from qwen_native_worker import thread_options
|
||||
from strata_worker import StrataWorker
|
||||
self.assertEqual(thread_options(2,1),dict(cpu_threads=2,cpu_codec_threads=1));self.assertEqual(thread_options(),dict(cpu_threads=4,cpu_codec_threads=4))
|
||||
self.assertEqual(cpu.placement(PLAN,CORES)['qwen_generation_threads'],2)
|
||||
for n in (True,0,5,'2'):
|
||||
with self.assertRaises(ValueError):thread_options(n,1)
|
||||
worker=StrataWorker('/unused',Mock(),Mock());worker.cpu_layout=cpu.placement(PLAN,CORES)
|
||||
body=dict(strata_tune=dict(aux_cpus=0,pcie_frac=.5));before=copy.deepcopy(body)
|
||||
self.assertEqual(worker.prepare_request(body)['strata_tune'],dict(aux_cpus=1,pcie_frac=.5));self.assertEqual(body,before)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user