odant-work 1.0.47 → 1.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "packageName": "odant-work",
3
- "version": "1.0.47",
3
+ "version": "1.0.49",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1795012231137,
5
+ "updatedAt": 1795016868560,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "42630d9dd46c5c9cafa94ead32ee6887239062a0393c3f65276ed3c88dc781c1",
9
- "package-lock.json": "9a106f9ee1f709acbf492fb70f2735f3336811050ca80920c0b0b716a8b8f6a4",
8
+ "package.json": "2868a28f1ae1b26fc37ce43b103d2dd034a1d436696a233b5c19e8fb669dd1a8",
9
+ "package-lock.json": "483a06dd5554286174fe87b73f02d0b7ded7e41a7bdb32e000e25c8ee632201f",
10
10
  "sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
11
11
  "sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
12
12
  "sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
@@ -26,7 +26,7 @@
26
26
  "sources/data/objects.js": "23f51d5b00cd766fe27879b874738bc9bd9056bd6e27285fb7a52926c0dbc6a8",
27
27
  "sources/data/posting.js": "6595bb9ec632539ae7629504db327d25a491e61c1cdc598bb43d08ea0d45548d",
28
28
  "sources/data/print.js": "704f0f2fc80c6466a4196e4650d763150cf9b592eab14ea67ece85d51100107c",
29
- "sources/data/progress.md": "abbf7d9fb5567537a5bae359d0db8d8bfcab039e83b61e8f36c9690ea50016a7",
29
+ "sources/data/progress.md": "0fa7958cf664995de41eaad1dacc42d21133d3511fc26a8aa8ff170f9489f0a6",
30
30
  "sources/data/readme.md": "593fa2ae07aa91bc26d7542275da6953a9cd419240a9a49e00cb62fb9d5d8e36",
31
31
  "sources/data/reports.js": "0330f404860fe2589a7d46a2f0fe690ca23249bd841a062a26718742d4fd11d6",
32
32
  "sources/data/schema.js": "1c994f9adb76c156dc86601dd6b1046376b66549b041e1a58aa1727b5476bdbe",
@@ -178,14 +178,14 @@
178
178
  "sources/modules/trainer/downloader.js": "d9e96cb07e7bf64386558be8c2265c482af35a513f42954250add6d5fc87bdc4",
179
179
  "sources/modules/trainer/halogen.js": "f908f16f8481cdf22d3baff4890bc446c9791325123ee471359c9847b3bac899",
180
180
  "sources/modules/trainer/huggingface.js": "0ee6434522be98301d72d90f6395a271f5de86acf92a176590a4141a92482e83",
181
- "sources/modules/trainer/index.js": "54588530503210daf25e3294d05a9a68ea9216ba69027b28e89047401ca792be",
182
- "sources/modules/trainer/local-engine.js": "fbb691dfce0d463a2613e80aed656cdbf9401aebafc156336986c471d81827c1",
181
+ "sources/modules/trainer/index.js": "97a22039fa8fef5820130c1a28eb71fd772495e444afee5c5c553fdba1ebe11d",
182
+ "sources/modules/trainer/local-engine.js": "3047d16c3070c7bab112f404c9bf87f112a7c287344c480721c1c6739a8676f4",
183
183
  "sources/modules/trainer/paths.js": "a9afeebe65a5843d2c073c7884e6121beb31b93c18b68256fe1a95a201a7826a",
184
184
  "sources/modules/trainer/providers.js": "56ffd2de03449ecaa13751a7e82c615cf5f84e6f02bb0b34c4432c3d85db28da",
185
185
  "sources/modules/trainer/runner.js": "328843672fe0c1bd7e8c35c2e25285c31a9f749e04814e64c32e8cae74086024",
186
186
  "sources/modules/trainer/tar-stream.js": "52f1739579a01818b53d04a93fd05a91c49a0716019f309a6fca951ba112794f",
187
187
  "sources/modules/trainer/transfer.js": "2c603d538e0f85e1794e2f304081fac136f0ff72f85d8b00c2141c7402b3a1fb",
188
- "sources/modules/trainer/worker/local_infer_worker.py": "b43a178f90403fbd913b5dc58d71cb883e8b289cc7d2280f50df3cc612a7dff6",
188
+ "sources/modules/trainer/worker/local_infer_worker.py": "ff21a029d19ab77df4cea90b572a5507fe2f40bc13368518daadc92067d2a028",
189
189
  "sources/modules/trainer/worker/unsloth_train.py": "7774d94ffa6f60eed20c57a8dfdc12621d5d9f74d594c605dff32ff70e321e33",
190
190
  "sources/modules/user-profile/user-profile.js": "5c8fd002809848b204aee83a44161375e8144bffcc048fde748f4f778162bbef",
191
191
  "sources/modules/user-profile/user-token.js": "3797685232684e9e80261a2e63f70cbff4ef1bcc3ded6f755800804e9848d7d9",
@@ -976,7 +976,7 @@
976
976
  "MODULES/Register/STRUCTS/Паспорт/$struct/class.js": "4a50808e4db7741b0384a775177545d71686a680ccda7ef0ec68bf81f9c988b5",
977
977
  "MODELS/$ai/$folder/$class/$ai/class.js": "fd9214a926ad7466d1ae17cec095ca46144d4db75112ec6b893140ca05f21fd2",
978
978
  "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/class.js": "fe5ba834156495c28a34acd4b70a6b6b3bdfccb67ec7bf99e92a292afbb66d19",
979
- "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "0f7320a726098be0f99f5a874ab733302d1e6aa5353dbf5dfe47499aa67de102",
979
+ "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "2bdf20e21b8fab14e292ee50ced62d2c4f0e25fd0d5d1abce17929f73516851a",
980
980
  "MODELS/$ai/$folder/$class/$ai/methods/chat/$method/class.js": "02fbb40d8ce93fbf568a6a8036c199e2af815be3d63d81f815aeb1da999db717",
981
981
  "MODELS/$ai/$folder/$class/$provider/class.js": "069073501b93a95bb9d77e59ce71e53c7a8bcab2564c391b551f68a2453ac486",
982
982
  "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/class.js": "8d327820cefd696d351ac4fa7998994039e4d57ef7a9f8ae297209e4dd1b0a9e",
@@ -277,10 +277,10 @@ export default {
277
277
  <div class="vertical" style="gap:8px;" ~if="testModality === 'tts'">
278
278
  <textarea rows="2" :value="testTtsText" placeholder="Текст для озвучивания…" @input="testTtsText = $this.value"></textarea>
279
279
  <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base'">
280
- <button type="button" class="btn" ~for="p of ttsVoicePresets"
281
- :style="testTtsInstructions === p.value ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
282
- @tap="selectTtsPreset(p)">
283
- {{p.label}}
280
+ <button type="button" class="btn" ~for="ttsVoicePresets"
281
+ :style="testTtsInstructions === $for.item.value ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
282
+ @tap="selectTtsPreset($for.item)">
283
+ {{$for.item.label}}
284
284
  </button>
285
285
  </div>
286
286
  <textarea rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «Мужской баритон, спокойная деловая интонация»…" @input="testTtsInstructions = $this.value"></textarea>
@@ -642,6 +642,8 @@ export default {
642
642
  if (this.info?.weightsRepair)
643
643
  this.info = { ...this.info, weightsRepair: null };
644
644
  const parts = [];
645
+ if (res.device)
646
+ parts.push(`Вычислитель: ${res.device}`);
645
647
  if (res.engineStartMs > 500)
646
648
  parts.push(`Старт движка: ${(res.engineStartMs / 1000).toFixed(1)} с`);
647
649
  if (res.loadMs > 500)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.47",
3
+ "version": "1.0.49",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,7 +1,11 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
- - [~16:40, 18.11] Стабильный мужской голос и ускорение Qwen3-TTS, нормализация языка в Qwen3-ASR и мгновенная локальная раскладка 32.8 ГБ весов Z-Image-Turbo по подпапкам (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{huggingface,local-engine,index}.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `tests/trainer-weights-layout.test.js`, `odant-work@1.0.47`):
4
+ - [~17:15, 18.11] Перевод Python-воркера на GPU AMD ROCm 7.13 (`gfx1151`) для Strix Halo и ускорение внутреннего цикла `code_predictor` в `Qwen3-TTS` (`sources/modules/trainer/local-engine.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/index.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.49`):
5
+ - **Автоматический переход с CPU PyTorch на официальный AMD ROCm 7.13 для `gfx1151` (`local-engine.js`):** добавлены `isStrixHaloGfx1151Host` и `hasRocmGfx1151InVenvSync`. На машинах AMD Strix Halo (Ryzen AI Max+ 395 / 495, Radeon 8060S / 8065S) среда `MODELS/Local/$provider/#runtime/venv` при первом вызове модели автоматически устанавливает/апгрейдит `torch==2.10.0+rocm7.13.0`, `torchaudio==2.10.0+rocm7.13.0`, `rocm-sdk-core==7.13.0`, `rocm-sdk-libraries-gfx1151==7.13.0` с официального индекса `https://repo.amd.com/rocm/whl/gfx1151/` (`--index-strategy unsafe-best-match`) и файл `uv-overrides.txt` (`transformers>=4.57.3,<4.58.0`, устраняющий конфликт зависимостей между `qwen-tts` и `qwen-asr`). Благодаря этому `torch.cuda.is_available()` становится `True` (`device = "cuda:0"`), и все локальные PyTorch-модели (`Qwen3-TTS 1.7B`, `Qwen3-ASR 1.7B`, `Z-Image-Turbo 6B`, `Qwen3-4B`, `Qwen3-0.6B`) исполняются на iGPU Radeon 8060S с прозрачным откатом на CPU при нехватке VRAM.
6
+ - **Ускорение внутреннего 15-шагового цикла `code_predictor` в `Qwen3-TTS` (`local_infer_worker.py`):** в штатном `qwen_tts` на каждом 12 Гц аудиокадре (72 раза на фразу) вызывался полный `GenerationMixin.generate()` с `deepcopy(generation_config)`, `torch.sort` по всему словарю и аллокацией 75 неиспользуемых тензоров `output_hidden_states=True` (5 400 тензоров на фразу). Функция `_install_fast_qwen_tts_code_predictor` заменяет его на прямой 15-шаговый цикл по `lm_head[step]` с `subtalker_dosample=False` и `DynamicCache` без обвязки `GenerationMixin`.
7
+ - **Индикация активного вычислителя в карточке модели (`trainer.js`, `index.js`):** во всех проверках выводится фактическое устройство исполнения (`Вычислитель: GPU (AMD Radeon 8060S)` / `ONNX (DirectML/NPU)` / `CPU (BF16)`).
8
+ - [~16:50, 18.11] Стабильный мужской голос и ускорение Qwen3-TTS, нормализация языка в Qwen3-ASR, мгновенная локальная раскладка 32.8 ГБ весов Z-Image-Turbo по подпапкам и фикс директивы `~for` в карточке модели (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{huggingface,local-engine,index}.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `tests/trainer-weights-layout.test.js`, `odant-work@1.0.48`):
5
9
  - **Стабильный мужской голос по умолчанию и русские описания тембра в `Qwen3-TTS VoiceDesign` (`local_infer_worker.py`, карточка модели):** добавлен переводчик русских и коротких описаний голоса `_normalize_voice_design_instruct` в развёрнутый английский акустический профиль (`Male/Female`, возраст, тембр `baritone/bass/tenor/alto/soprano`, подача `announcer/calm/energetic`, темп). По умолчанию установлен спокойный мужской баритон (`Male, 35 years old, deep warm baritone voice…`), перед генерацией фиксируется детерминированный `torch.manual_seed(seed=42)` (один и тот же `instruct` всегда даёт один и тот же голос), а в карточку TTS добавлены 4 быстрых чипа-пресета («Мужской баритон», «Мужской диктор», «Женский спокойный», «Женский живой»).
6
10
  - **Ускорение синтеза речи и генерации картинок + раздельный замер холодной загрузки (`local_infer_worker.py`, `local-engine.js`, `index.js`, `huggingface.js`):** в Python-воркере задействованы все 16 физических ядер Zen 5 (`torch.set_num_threads` + `mkldnn`), подключён `attn_implementation="sdpa"`, для TTS введён динамический `max_new_tokens` по длине текста, для `Z-Image-Turbo` по умолчанию установлено `4 шага` (`guidance_scale=0.0`). Во всех операциях воркера (`tts`, `stt`, `image`, `embed`, `rerank`) время холодной загрузки весов в память (`Загрузка модели: X.X с`) отделено от чистого времени инференса (`Синтез / Генерация: Y.Y с`). В каталог `/MODELS/Local` добавлена быстрая модель `Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice` (9 фиксированных голосов).
7
11
  - **Исправление `Unsupported language: Ru` в `Qwen3-ASR 1.7B` (`local_infer_worker.py`):** в `handle_stt` подключён нормализатор `_asr_language` по 30 поддерживаемым языкам `qwen-asr` (`'ru' / 'Ru' / 'rus' / 'русский' → 'Russian'`, `'auto' / ''` и любые незнакомые коды → `None` для автоопределения + автоматический повтор с `language=None` при отказе).
@@ -55,6 +55,10 @@ import {
55
55
  getPythonProvisionState,
56
56
  ensurePythonForModality,
57
57
  packagesForModality,
58
+ isStrixHaloGfx1151Host,
59
+ hasRocmGfx1151InVenvSync,
60
+ AMD_ROCM_GFX1151_WHL_INDEX,
61
+ ROCM_GFX1151_TORCH_VERSION,
58
62
  _setAutoProvisionForTest,
59
63
  } from './local-engine.js';
60
64
  import {
@@ -171,6 +175,10 @@ export {
171
175
  getPythonProvisionState,
172
176
  ensurePythonForModality,
173
177
  packagesForModality,
178
+ isStrixHaloGfx1151Host,
179
+ hasRocmGfx1151InVenvSync,
180
+ AMD_ROCM_GFX1151_WHL_INDEX,
181
+ ROCM_GFX1151_TORCH_VERSION,
174
182
  _setAutoProvisionForTest,
175
183
  SOURCE_PRESETS,
176
184
  THREAD_OPTIONS,
@@ -440,6 +448,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
440
448
  return {
441
449
  ok: true,
442
450
  modality,
451
+ device: buf?.device || '',
443
452
  loadMs,
444
453
  durationMs,
445
454
  totalMs,
@@ -461,6 +470,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
461
470
  return {
462
471
  ok: true,
463
472
  modality,
473
+ device: res?.device || '',
464
474
  loadMs,
465
475
  durationMs,
466
476
  totalMs,
@@ -477,6 +487,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
477
487
  return {
478
488
  ok: true,
479
489
  modality,
490
+ device: pic?.device || '',
480
491
  loadMs,
481
492
  durationMs,
482
493
  totalMs,
@@ -498,6 +509,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
498
509
  return {
499
510
  ok: true,
500
511
  modality,
512
+ device: res?.device || '',
501
513
  loadMs,
502
514
  durationMs,
503
515
  totalMs,
@@ -519,6 +531,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
519
531
  return {
520
532
  ok: true,
521
533
  modality,
534
+ device: res?.device || '',
522
535
  loadMs,
523
536
  durationMs,
524
537
  totalMs,
@@ -781,7 +781,79 @@ async function runWorkerOpOnce(payload, timeoutMs = 120000) {
781
781
  });
782
782
  }
783
783
 
784
+ export const AMD_ROCM_GFX1151_WHL_INDEX = 'https://repo.amd.com/rocm/whl/gfx1151/';
785
+ export const ROCM_GFX1151_TORCH_VERSION = '2.10.0+rocm7.13.0';
786
+ export const ROCM_GFX1151_SDK_VERSION = '7.13.0';
787
+
788
+ let _rocmUpgradeCooldownUntil = 0;
789
+
790
+ /**
791
+ * Определить, работает ли сервер на машине AMD Strix Halo (`gfx1151` — Ryzen AI Max+ 395 / 495, Radeon 8060S / 8065S).
792
+ */
793
+ export function isStrixHaloGfx1151Host(rootDir = process.cwd()) {
794
+ if (process.env.WORK_ROCM_GFX1151 === '1')
795
+ return true;
796
+ if (process.env.WORK_ROCM_GFX1151 === '0' || process.env.WORK_DISABLE_AUTO_PYTHON === '1' || process.env.NODE_TEST_CONTEXT)
797
+ return false;
798
+ const platform = os.platform();
799
+ if (platform !== 'win32' && platform !== 'linux')
800
+ return false;
801
+ try {
802
+ const cpuModel = String(os.cpus()?.[0]?.model || '');
803
+ if (/Ryzen\s+AI\s+Max|\b(395|495|390|385)\b|Strix\s+Halo|Radeon\s+80[56]0S/i.test(cpuModel))
804
+ return true;
805
+ const rt = runtimeRoot(rootDir);
806
+ if (
807
+ fs.existsSync(path.join(rt, 'bubo', 'bubo.exe'))
808
+ || fs.existsSync(path.join(rt, 'bubo', 'runtime', 'rocm-10.0.0-gfx1151'))
809
+ ) {
810
+ return true;
811
+ }
812
+ if (/AMD|Ryzen/i.test(cpuModel) && os.totalmem() >= 90 * (1024 ** 3))
813
+ return true;
814
+ }
815
+ catch { /* ignore */ }
816
+ return false;
817
+ }
818
+
819
+ /**
820
+ * Проверить, установлены ли уже в `#runtime/venv` GPU-библиотеки AMD ROCm для `gfx1151`.
821
+ */
822
+ export function hasRocmGfx1151InVenvSync(rootDir = process.cwd()) {
823
+ const rt = runtimeRoot(rootDir);
824
+ const venvDir = path.join(rt, 'venv');
825
+ if (!fs.existsSync(venvDir))
826
+ return false;
827
+ if (fs.existsSync(path.join(venvDir, '.rocm-gfx1151-ok')))
828
+ return true;
829
+ const sitePkgs = os.platform() === 'win32'
830
+ ? path.join(venvDir, 'Lib', 'site-packages')
831
+ : path.join(venvDir, 'lib', 'python3.11', 'site-packages');
832
+ return (
833
+ fs.existsSync(path.join(sitePkgs, '_rocm_sdk_libraries_gfx1151'))
834
+ || fs.existsSync(path.join(sitePkgs, 'rocm_sdk_libraries_gfx1151'))
835
+ );
836
+ }
837
+
784
838
  async function runWorkerOp(payload, timeoutMs = 120000) {
839
+ // На машинах Strix Halo (gfx1151) автоматически апгрейдим CPU-only torch до GPU ROCm 7.13 (Radeon 8060S/8065S),
840
+ // чтобы Qwen3-TTS 1.7B, Qwen3-ASR 1.7B, Z-Image-Turbo 6B и локальные LLM работали на iGPU в 5–10 раз быстрее.
841
+ const op = String(payload?.op || 'llm');
842
+ const usesOnnxFastPath = (op === 'embed' || op === 'rerank') && hasOnnxModelSync(payload?.weightsDir || '');
843
+ if (
844
+ op !== 'check_deps'
845
+ && !usesOnnxFastPath
846
+ && !_autoProvisionOverride
847
+ && Date.now() > _rocmUpgradeCooldownUntil
848
+ && isStrixHaloGfx1151Host()
849
+ && !hasRocmGfx1151InVenvSync()
850
+ ) {
851
+ await ensurePythonForModality(op, {
852
+ weightsDir: payload?.weightsDir || '',
853
+ upgradeRocmGfx1151: true,
854
+ }).catch(() => null);
855
+ }
856
+
785
857
  try {
786
858
  return await runWorkerOpOnce(payload, timeoutMs);
787
859
  }
@@ -823,6 +895,7 @@ export async function localEmbed(ai, params = {}) {
823
895
  model: String(ai?.model || ai?.id || 'local-embed'),
824
896
  data: (res.embeddings || []).map((embedding, index) => ({ object: 'embedding', index, embedding })),
825
897
  dimensions: res.dimensions || 0,
898
+ device: res.device || '',
826
899
  loadMs: Number(res.loadMs) || 0,
827
900
  genMs: Number(res.genMs || res.durationMs) || 0,
828
901
  durationMs: Number(res.genMs || res.durationMs) || 0,
@@ -843,6 +916,7 @@ export async function localRerank(ai, params = {}) {
843
916
  return {
844
917
  model: String(ai?.model || ai?.id || 'local-rerank'),
845
918
  results: res.results || [],
919
+ device: res.device || '',
846
920
  loadMs: Number(res.loadMs) || 0,
847
921
  genMs: Number(res.genMs || res.durationMs) || 0,
848
922
  durationMs: Number(res.genMs || res.durationMs) || 0,
@@ -868,6 +942,7 @@ export async function localGenerateImage(ai, params = {}) {
868
942
  mime: res.mime || 'image/png',
869
943
  base64: res.base64,
870
944
  model: String(ai?.model || ai?.id || 'local-image'),
945
+ device: res.device || '',
871
946
  loadMs: Number(res.loadMs) || 0,
872
947
  genMs: Number(res.genMs || res.durationMs) || 0,
873
948
  durationMs: Number(res.genMs || res.durationMs) || 0,
@@ -895,6 +970,7 @@ export async function localSpeak(ai, params = {}) {
895
970
  buf.genMs = Number(res.genMs || res.durationMs) || 0;
896
971
  buf.ttsKind = res.ttsKind || '';
897
972
  buf.instructUsed = res.instructUsed || '';
973
+ buf.device = res.device || '';
898
974
  return buf;
899
975
  }
900
976
 
@@ -912,6 +988,7 @@ export async function localTranscribe(ai, params = {}) {
912
988
  return {
913
989
  text: String(res.text || '').trim(),
914
990
  model: String(ai?.model || ai?.id || 'local-stt'),
991
+ device: res.device || '',
915
992
  loadMs: Number(res.loadMs) || 0,
916
993
  genMs: Number(res.genMs || res.durationMs) || 0,
917
994
  durationMs: Number(res.genMs || res.durationMs) || 0,
@@ -966,6 +1043,9 @@ export async function checkLocalPythonDeps() {
966
1043
 
967
1044
  const ALLOWED_PYTHON_DEPS = new Set([
968
1045
  'torch',
1046
+ 'torchaudio',
1047
+ 'rocm-sdk-core',
1048
+ 'rocm-sdk-libraries-gfx1151',
969
1049
  'transformers',
970
1050
  'diffusers',
971
1051
  'accelerate',
@@ -1143,7 +1223,7 @@ export function getPythonProvisionState() {
1143
1223
  return { ..._pythonProvisionState };
1144
1224
  }
1145
1225
 
1146
- export async function installLocalPythonDeps(packages = [], { rootDir = process.cwd() } = {}) {
1226
+ export async function installLocalPythonDeps(packages = [], { rootDir = process.cwd(), upgradeRocmGfx1151 = false } = {}) {
1147
1227
  let clean = [...new Set((Array.isArray(packages) ? packages : [packages])
1148
1228
  .map(s => String(s || '').trim().toLowerCase())
1149
1229
  .filter(p => ALLOWED_PYTHON_DEPS.has(p)))];
@@ -1177,7 +1257,7 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1177
1257
  if (!clean.length)
1178
1258
  clean = ['torch', 'transformers', 'accelerate', 'safetensors'];
1179
1259
 
1180
- const usesOnnxOnly = clean.some(p => p.startsWith('onnxruntime')) && !clean.includes('torch');
1260
+ const usesOnnxOnly = clean.some(p => p.startsWith('onnxruntime')) && !clean.includes('torch') && !upgradeRocmGfx1151;
1181
1261
  if (!usesOnnxOnly && !clean.includes('torch') && clean.some(p => p !== 'safetensors' && p !== 'numpy'))
1182
1262
  clean.unshift('torch');
1183
1263
 
@@ -1190,31 +1270,84 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1190
1270
  }
1191
1271
 
1192
1272
  const { env: proxyEnv } = buildProxyEnv(rootDir);
1193
- // На Linux без явного индекса PyPI тянет 2.8 ГБ NVIDIA CUDA; фиксируем лёгкий CPU-индекс PyTorch
1194
- const extraIndexArgs = (os.platform() === 'linux' && clean.includes('torch'))
1195
- ? ['--extra-index-url', 'https://download.pytorch.org/whl/cpu']
1196
- : [];
1197
-
1198
- _pythonProvisionState = {
1199
- active: true,
1200
- stage: `Автоматическая установка пакетов (${clean.join(', ')})…`,
1201
- packages: clean,
1202
- startedAt: _pythonProvisionState.startedAt || Date.now(),
1203
- lastError: '',
1273
+ const rtDir = runtimeRoot(rootDir);
1274
+ fs.mkdirSync(rtDir, { recursive: true });
1275
+ const ovrFile = path.join(rtDir, 'uv-overrides.txt');
1276
+
1277
+ const wantRocmGfx1151 = (upgradeRocmGfx1151 || isStrixHaloGfx1151Host(rootDir))
1278
+ && clean.includes('torch')
1279
+ && Date.now() > _rocmUpgradeCooldownUntil;
1280
+
1281
+ const runInstallAttempt = async (useRocm) => {
1282
+ const overrides = [
1283
+ 'transformers>=4.57.3,<4.58.0',
1284
+ 'accelerate>=1.12.0',
1285
+ ];
1286
+ let installList = [...clean];
1287
+ let indexArgs = [];
1288
+ if (useRocm) {
1289
+ overrides.push(
1290
+ `torch==${ROCM_GFX1151_TORCH_VERSION}`,
1291
+ `torchaudio==${ROCM_GFX1151_TORCH_VERSION}`,
1292
+ );
1293
+ installList = installList.flatMap(p => p === 'torch'
1294
+ ? [
1295
+ `torch==${ROCM_GFX1151_TORCH_VERSION}`,
1296
+ `torchaudio==${ROCM_GFX1151_TORCH_VERSION}`,
1297
+ `rocm-sdk-core==${ROCM_GFX1151_SDK_VERSION}`,
1298
+ `rocm-sdk-libraries-gfx1151==${ROCM_GFX1151_SDK_VERSION}`,
1299
+ ]
1300
+ : [p]);
1301
+ indexArgs = [
1302
+ '--extra-index-url', AMD_ROCM_GFX1151_WHL_INDEX,
1303
+ '--index-strategy', 'unsafe-best-match',
1304
+ ];
1305
+ }
1306
+ else if (os.platform() === 'linux' && clean.includes('torch')) {
1307
+ // На обычном Linux без GPU-индекса фиксируем лёгкий CPU-индекс PyTorch (вместо 2.8 ГБ NVIDIA CUDA)
1308
+ indexArgs = ['--extra-index-url', 'https://download.pytorch.org/whl/cpu'];
1309
+ }
1310
+ try { fs.writeFileSync(ovrFile, overrides.join('\n') + '\n', 'utf-8'); }
1311
+ catch { /* ignore */ }
1312
+
1313
+ _pythonProvisionState = {
1314
+ active: true,
1315
+ stage: useRocm
1316
+ ? `Установка GPU-ускорения AMD ROCm (gfx1151 iGPU) и пакетов (${clean.join(', ')})…`
1317
+ : `Автоматическая установка пакетов (${clean.join(', ')})…`,
1318
+ packages: clean,
1319
+ startedAt: _pythonProvisionState.startedAt || Date.now(),
1320
+ lastError: '',
1321
+ };
1322
+
1323
+ if (uv && fs.existsSync(venvPy)) {
1324
+ const ovrArgs = fs.existsSync(ovrFile) ? ['--override', ovrFile] : [];
1325
+ return await runSpawnCapture(uv, ['pip', 'install', '--python', venvPy, '--upgrade', ...ovrArgs, ...indexArgs, ...installList], 900000, proxyEnv);
1326
+ }
1327
+ const pipIndexArgs = useRocm ? ['--extra-index-url', AMD_ROCM_GFX1151_WHL_INDEX] : indexArgs;
1328
+ return await runSpawnCapture(py.cmd, [...py.args, '-m', 'pip', 'install', '--upgrade', ...pipIndexArgs, ...installList], 900000, proxyEnv);
1204
1329
  };
1205
1330
 
1206
- let res;
1207
- if (uv && fs.existsSync(venvPy)) {
1208
- res = await runSpawnCapture(uv, ['pip', 'install', '--python', venvPy, '--upgrade', ...extraIndexArgs, ...clean], 600000, proxyEnv);
1209
- }
1210
- else {
1211
- res = await runSpawnCapture(py.cmd, [...py.args, '-m', 'pip', 'install', '--upgrade', ...extraIndexArgs, ...clean], 600000, proxyEnv);
1331
+ let res = await runInstallAttempt(wantRocmGfx1151);
1332
+ if (!res.ok && wantRocmGfx1151) {
1333
+ // Если индекс AMD ROCm временно недоступен — ставим кулдаун и прозрачно откатываемся на стандартный PyPI,
1334
+ // чтобы модель гарантированно заработала без блокировки пользователя.
1335
+ _rocmUpgradeCooldownUntil = Date.now() + 30 * 60 * 1000;
1336
+ if (!upgradeRocmGfx1151)
1337
+ res = await runInstallAttempt(false);
1212
1338
  }
1339
+
1213
1340
  if (res.ok) {
1341
+ if (wantRocmGfx1151 && Date.now() > _rocmUpgradeCooldownUntil) {
1342
+ try {
1343
+ fs.writeFileSync(path.join(rtDir, 'venv', '.rocm-gfx1151-ok'), ROCM_GFX1151_TORCH_VERSION, 'utf-8');
1344
+ }
1345
+ catch { /* ignore */ }
1346
+ }
1214
1347
  closeInferWorker();
1215
1348
  resetPythonCache();
1216
1349
  _pythonProvisionState = { active: false, stage: '', packages: [], startedAt: 0, lastError: '' };
1217
- return { ok: true, packages: clean, log: res.out };
1350
+ return { ok: true, packages: clean, rocmGfx1151: wantRocmGfx1151 && Date.now() > _rocmUpgradeCooldownUntil, log: res.out };
1218
1351
  }
1219
1352
  const rawErr = (res.err || res.out || `Установка завершилась с кодом ${res.code}`).trim();
1220
1353
  const isOffline = /Failed to fetch|Temporary failure|ConnectionError|ConnectTimeout|ENOTFOUND|network/i.test(rawErr);
@@ -1229,9 +1362,9 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1229
1362
  * Единая сериализованная точка автоподготовки Python 3.11 + нужных библиотек под модальность модели.
1230
1363
  * Если параллельно пришло несколько вызовов — все они ждут одну общую установку (до 10 минут).
1231
1364
  */
1232
- export async function ensurePythonForModality(modality = 'llm', { weightsDir = '', extraPackages = [], rootDir = process.cwd() } = {}) {
1365
+ export async function ensurePythonForModality(modality = 'llm', { weightsDir = '', extraPackages = [], upgradeRocmGfx1151 = false, rootDir = process.cwd() } = {}) {
1233
1366
  if (_autoProvisionOverride)
1234
- return _autoProvisionOverride(modality, { weightsDir, extraPackages, rootDir });
1367
+ return _autoProvisionOverride(modality, { weightsDir, extraPackages, upgradeRocmGfx1151, rootDir });
1235
1368
 
1236
1369
  const targetPkgs = [...new Set([
1237
1370
  ...packagesForModality(modality, weightsDir),
@@ -1241,13 +1374,15 @@ export async function ensurePythonForModality(modality = 'llm', { weightsDir = '
1241
1374
  const runTask = async () => {
1242
1375
  _pythonProvisionState = {
1243
1376
  active: true,
1244
- stage: `Подготовка среды Python (${targetPkgs.join(', ')})…`,
1377
+ stage: upgradeRocmGfx1151
1378
+ ? 'Установка GPU-ускорения AMD ROCm (gfx1151 iGPU) для PyTorch…'
1379
+ : `Подготовка среды Python (${targetPkgs.join(', ')})…`,
1245
1380
  packages: targetPkgs,
1246
1381
  startedAt: Date.now(),
1247
1382
  lastError: '',
1248
1383
  };
1249
1384
  try {
1250
- return await installLocalPythonDeps(targetPkgs, { rootDir });
1385
+ return await installLocalPythonDeps(targetPkgs, { rootDir, upgradeRocmGfx1151 });
1251
1386
  }
1252
1387
  finally {
1253
1388
  if (_pythonProvisionState.active) {
@@ -294,10 +294,23 @@ def _best_device_and_dtype():
294
294
  "missingDeps": ["torch"],
295
295
  }))
296
296
  if torch.cuda.is_available():
297
- return "cuda", torch.bfloat16
297
+ return "cuda:0", torch.bfloat16
298
298
  return "cpu", (torch.bfloat16 if _cpu_supports_bf16() else torch.float32)
299
299
 
300
300
 
301
+ def _describe_torch_device(device="cpu"):
302
+ dev_str = str(device or "cpu")
303
+ if HAS_TORCH and dev_str.startswith("cuda") and torch.cuda.is_available():
304
+ try:
305
+ name = str(torch.cuda.get_device_name(0) or "").strip()
306
+ return f"GPU ({name})" if name else "GPU"
307
+ except Exception:
308
+ return "GPU"
309
+ if dev_str == "ort":
310
+ return "ONNX (DirectML/NPU)"
311
+ return "CPU (BF16)" if _cpu_supports_bf16() else "CPU"
312
+
313
+
301
314
  def _onnx_external_data_ok(onnx_path):
302
315
  """Внешние тензоры ONNX лежат рядом с графом (`model.onnx_data` / `model.onnx.data`)."""
303
316
  return os.path.isfile(onnx_path + "_data") or os.path.isfile(onnx_path + ".data")
@@ -488,7 +501,7 @@ def handle_embed(req, cache):
488
501
  norms = np.clip(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12, None)
489
502
  arr = (vecs / norms).tolist()
490
503
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
491
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
504
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
492
505
  with torch.inference_mode():
493
506
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="pt")
494
507
  encoded = {k: v.to(device) for k, v in encoded.items()}
@@ -500,7 +513,7 @@ def handle_embed(req, cache):
500
513
  vecs = F.normalize(summed / counts, p=2, dim=1)
501
514
  arr = vecs.cpu().tolist()
502
515
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
503
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
516
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
504
517
 
505
518
 
506
519
  def _load_rerank_model(weights_dir, cache):
@@ -575,7 +588,7 @@ def handle_rerank(req, cache):
575
588
  if top_n > 0:
576
589
  ranked = ranked[:top_n]
577
590
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
578
- return {"results": ranked, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
591
+ return {"results": ranked, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
579
592
 
580
593
 
581
594
  def _load_image_pipeline(weights_dir, cache):
@@ -601,7 +614,16 @@ def _load_image_pipeline(weights_dir, cache):
601
614
  pipe = None
602
615
  if pipe is None:
603
616
  pipe = diffusers.AutoPipelineForText2Image.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
604
- pipe.to(device)
617
+ try:
618
+ pipe.to(device)
619
+ except Exception:
620
+ if str(device).startswith("cuda") and HAS_TORCH:
621
+ try:
622
+ torch.cuda.empty_cache()
623
+ except Exception:
624
+ pass
625
+ device = "cpu"
626
+ pipe.to(device)
605
627
  cache[key] = (pipe, device)
606
628
  return cache[key]
607
629
 
@@ -632,7 +654,7 @@ def handle_image(req, cache):
632
654
  buf = io.BytesIO()
633
655
  img.save(buf, format="PNG")
634
656
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
635
- return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
657
+ return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
636
658
 
637
659
 
638
660
  def _pcm_to_wav_base64(samples, sample_rate):
@@ -871,11 +893,138 @@ def _seed_torch_deterministic(seed_val):
871
893
  pass
872
894
 
873
895
 
896
+ def _install_fast_qwen_tts_code_predictor(mdl):
897
+ """Ускоряет внутренний 15-шаговый цикл `code_predictor` в Qwen3-TTS (вызывается на каждом 12 Гц кадре).
898
+
899
+ Штатный `qwen_tts` на каждом 12 Гц шаге вызывает полный `GenerationMixin.generate()`,
900
+ делая `deepcopy(generation_config)`, `torch.sort` по всему словарю и сохраняя 75 неиспользуемых
901
+ тензоров `output_hidden_states=True`. Прямой цикл по 15 головам `lm_head[step]` делает ту же
902
+ математику без обвязки `GenerationMixin` и лишних аллокаций.
903
+ """
904
+ cp = getattr(getattr(getattr(mdl, "model", None), "talker", None), "code_predictor", None)
905
+ if cp is None or getattr(cp, "_work_fast_patched", False):
906
+ return
907
+ orig_generate = cp.generate
908
+
909
+ class _FastPredictorOut:
910
+ __slots__ = ("sequences", "hidden_states")
911
+
912
+ def __init__(self, sequences):
913
+ self.sequences = sequences
914
+ self.hidden_states = None
915
+
916
+ def _fast_generate(
917
+ inputs_embeds=None,
918
+ max_new_tokens=None,
919
+ do_sample=False,
920
+ top_p=1.0,
921
+ top_k=50,
922
+ temperature=0.9,
923
+ **kwargs,
924
+ ):
925
+ if inputs_embeds is None:
926
+ return orig_generate(
927
+ inputs_embeds=inputs_embeds,
928
+ max_new_tokens=max_new_tokens,
929
+ do_sample=do_sample,
930
+ top_p=top_p,
931
+ top_k=top_k,
932
+ temperature=temperature,
933
+ **kwargs,
934
+ )
935
+ try:
936
+ from transformers.cache_utils import DynamicCache
937
+ steps = int(max_new_tokens or (cp.config.num_code_groups - 1))
938
+ past_kv = DynamicCache()
939
+ cur_embeds = cp.small_to_mtp_projection(inputs_embeds)
940
+ embs = cp.model.get_input_embeddings()
941
+ heads = cp.lm_head
942
+ tokens = []
943
+ temp = float(temperature) if (temperature and float(temperature) > 0) else 1.0
944
+ k = int(top_k) if top_k else 0
945
+ for step in range(steps):
946
+ out = cp.model(
947
+ input_ids=None,
948
+ inputs_embeds=cur_embeds,
949
+ past_key_values=past_kv,
950
+ use_cache=True,
951
+ output_attentions=False,
952
+ output_hidden_states=False,
953
+ )
954
+ last_h = out.last_hidden_state[:, -1, :]
955
+ logits = heads[step](last_h)
956
+ if not do_sample:
957
+ next_tok = torch.argmax(logits, dim=-1, keepdim=True)
958
+ else:
959
+ if temp != 1.0:
960
+ logits = logits / temp
961
+ if 0 < k < logits.size(-1):
962
+ top_vals, top_idx = torch.topk(logits, k, dim=-1)
963
+ probs = F.softmax(top_vals, dim=-1)
964
+ pick = torch.multinomial(probs, num_samples=1)
965
+ next_tok = top_idx.gather(-1, pick)
966
+ else:
967
+ probs = F.softmax(logits, dim=-1)
968
+ next_tok = torch.multinomial(probs, num_samples=1)
969
+ tokens.append(next_tok)
970
+ if step + 1 < steps:
971
+ cur_embeds = cp.small_to_mtp_projection(embs[step](next_tok))
972
+ return _FastPredictorOut(torch.cat(tokens, dim=-1))
973
+ except Exception:
974
+ return orig_generate(
975
+ inputs_embeds=inputs_embeds,
976
+ max_new_tokens=max_new_tokens,
977
+ do_sample=do_sample,
978
+ top_p=top_p,
979
+ top_k=top_k,
980
+ temperature=temperature,
981
+ **kwargs,
982
+ )
983
+
984
+ cp.generate = _fast_generate
985
+ cp._work_fast_patched = True
986
+
987
+
874
988
  def _call_tts_gen(fn, max_new_tokens, **kwargs):
875
989
  try:
876
- return fn(max_new_tokens=max_new_tokens, **kwargs)
990
+ return fn(max_new_tokens=max_new_tokens, subtalker_dosample=False, **kwargs)
877
991
  except TypeError:
878
- return fn(**kwargs)
992
+ try:
993
+ return fn(max_new_tokens=max_new_tokens, **kwargs)
994
+ except TypeError:
995
+ return fn(**kwargs)
996
+
997
+
998
+ def _load_qwen_tts_model(weights_dir):
999
+ from qwen_tts import Qwen3TTSModel
1000
+ device, dtype = _best_device_and_dtype()
1001
+ candidates = [(device, dtype)]
1002
+ if str(device).startswith("cuda"):
1003
+ cpu_dtype = torch.bfloat16 if _cpu_supports_bf16() else torch.float32
1004
+ candidates.append(("cpu", cpu_dtype))
1005
+ last_err = None
1006
+ for dev, dt in candidates:
1007
+ try:
1008
+ try:
1009
+ mdl = Qwen3TTSModel.from_pretrained(
1010
+ weights_dir,
1011
+ device_map=dev,
1012
+ dtype=dt,
1013
+ attn_implementation="sdpa",
1014
+ )
1015
+ except Exception:
1016
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=dev, dtype=dt)
1017
+ _install_fast_qwen_tts_code_predictor(mdl)
1018
+ mdl._work_device = dev
1019
+ return mdl
1020
+ except Exception as e:
1021
+ last_err = e
1022
+ if str(dev).startswith("cuda") and HAS_TORCH:
1023
+ try:
1024
+ torch.cuda.empty_cache()
1025
+ except Exception:
1026
+ pass
1027
+ raise last_err
879
1028
 
880
1029
 
881
1030
  def handle_tts(req, cache):
@@ -884,39 +1033,31 @@ def handle_tts(req, cache):
884
1033
  language = _tts_language(req.get("language") or "Russian")
885
1034
  instructions = str(req.get("instructions") or "").strip()
886
1035
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
887
- # 12 Гц аудио-токенизатор: динамический потолок шагов декодера под реальную длину текста
888
- max_new_tokens = max(128, min(1024, int(len(text) * 4.5) + 96))
1036
+ # 12.5 Гц аудио-токенизатор (~0.93 кадра на символ речи): компактный потолок без холостых хвостов
1037
+ max_new_tokens = max(72, min(768, int(len(text) * 2.0) + 48))
889
1038
  key = ("tts", weights_dir)
890
1039
  was_cached = key in cache
891
1040
  t_load0 = time.time()
892
1041
  if not was_cached:
893
1042
  try:
894
- from qwen_tts import Qwen3TTSModel
1043
+ from qwen_tts import Qwen3TTSModel # noqa: F401
895
1044
  except Exception as e:
896
1045
  raise RuntimeError(json.dumps(_missing_pkg_error(e, {
897
1046
  "qwen_tts": "qwen-tts",
898
1047
  "soundfile": "soundfile",
899
1048
  })))
900
- device, dtype = _best_device_and_dtype()
901
1049
  try:
902
- try:
903
- mdl = Qwen3TTSModel.from_pretrained(
904
- weights_dir,
905
- device_map=device,
906
- dtype=dtype,
907
- attn_implementation="sdpa",
908
- )
909
- except Exception:
910
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
1050
+ cache[key] = _load_qwen_tts_model(weights_dir)
911
1051
  except Exception as e:
912
1052
  # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
913
1053
  # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
914
1054
  raise RuntimeError(json.dumps({
915
1055
  "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
916
1056
  }))
917
- cache[key] = mdl
918
1057
  load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
919
1058
  mdl = cache[key]
1059
+ _install_fast_qwen_tts_code_predictor(mdl)
1060
+ active_dev = getattr(mdl, "_work_device", None) or str(getattr(mdl, "device", "cpu"))
920
1061
  kind = _tts_model_kind(weights_dir, mdl, instructions)
921
1062
  _seed_torch_deterministic(seed)
922
1063
  t_gen0 = time.time()
@@ -993,6 +1134,7 @@ def handle_tts(req, cache):
993
1134
  "sampleRate": int(sr),
994
1135
  "ttsKind": kind,
995
1136
  "instructUsed": instruct_used,
1137
+ "device": _describe_torch_device(active_dev),
996
1138
  "loadMs": load_ms,
997
1139
  "genMs": gen_ms,
998
1140
  "durationMs": gen_ms,
@@ -1009,31 +1151,47 @@ def handle_stt(req, cache):
1009
1151
  t_load0 = time.time()
1010
1152
  if not was_cached:
1011
1153
  device, dtype = _best_device_and_dtype()
1154
+ candidates = [(device, dtype)]
1155
+ if str(device).startswith("cuda"):
1156
+ cpu_dtype = torch.bfloat16 if _cpu_supports_bf16() else torch.float32
1157
+ candidates.append(("cpu", cpu_dtype))
1012
1158
  errors = []
1013
1159
  try:
1014
1160
  from qwen_asr import Qwen3ASRModel
1015
- try:
1161
+ for dev, dt in candidates:
1016
1162
  try:
1017
- loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device, attn_implementation="sdpa")
1018
- except Exception:
1019
- loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device)
1020
- cache[key] = ("qwen_asr", loaded)
1021
- except Exception as e:
1022
- errors.append(f"qwen-asr: {e}")
1163
+ try:
1164
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dt, device_map=dev, attn_implementation="sdpa")
1165
+ except Exception:
1166
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dt, device_map=dev)
1167
+ loaded._work_device = dev
1168
+ cache[key] = ("qwen_asr", loaded)
1169
+ break
1170
+ except Exception as e:
1171
+ errors.append(f"qwen-asr ({dev}): {e}")
1172
+ if str(dev).startswith("cuda") and HAS_TORCH:
1173
+ try:
1174
+ torch.cuda.empty_cache()
1175
+ except Exception:
1176
+ pass
1023
1177
  except Exception as e:
1024
1178
  errors.append(f"qwen-asr (нет пакета): {e}")
1025
1179
  if key not in cache:
1026
1180
  try:
1027
1181
  from transformers import pipeline
1028
- try:
1029
- cache[key] = ("hf_asr", pipeline(
1030
- "automatic-speech-recognition",
1031
- model=weights_dir,
1032
- device=0 if device == "cuda" else -1,
1033
- torch_dtype=dtype,
1034
- ))
1035
- except Exception as e:
1036
- errors.append(f"transformers: {e}")
1182
+ for dev, dt in candidates:
1183
+ try:
1184
+ p_obj = pipeline(
1185
+ "automatic-speech-recognition",
1186
+ model=weights_dir,
1187
+ device=0 if str(dev).startswith("cuda") else -1,
1188
+ torch_dtype=dt,
1189
+ )
1190
+ p_obj._work_device = dev
1191
+ cache[key] = ("hf_asr", p_obj)
1192
+ break
1193
+ except Exception as e:
1194
+ errors.append(f"transformers ({dev}): {e}")
1037
1195
  except Exception as e:
1038
1196
  errors.append(f"transformers (нет пакета): {e}")
1039
1197
  if key not in cache:
@@ -1049,6 +1207,7 @@ def handle_stt(req, cache):
1049
1207
  }))
1050
1208
  load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1051
1209
  kind, mdl = cache[key]
1210
+ active_dev = getattr(mdl, "_work_device", None) or str(getattr(mdl, "device", "cpu"))
1052
1211
  import tempfile
1053
1212
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
1054
1213
  tf.write(raw)
@@ -1073,7 +1232,7 @@ def handle_stt(req, cache):
1073
1232
  except Exception:
1074
1233
  pass
1075
1234
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1076
- return {"text": str(txt or "").strip(), "language": language or "Auto", "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
1235
+ return {"text": str(txt or "").strip(), "language": language or "Auto", "device": _describe_torch_device(active_dev), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
1077
1236
 
1078
1237
 
1079
1238
  def main():