odant-work 1.0.50 → 1.0.52

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,16 +1,16 @@
1
1
  {
2
2
  "packageName": "odant-work",
3
- "version": "1.0.50",
3
+ "version": "1.0.52",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1795071890912,
5
+ "updatedAt": 1795078308370,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "5e435e21b575f4e8c987e06953a72742c8ee05bab9829f026a177329fb379e9a",
9
- "package-lock.json": "69f224952c3bda483af831d6f6cbfa6b50cf1d70b3c3f2a241379424e598250b",
8
+ "package.json": "9ddf28ca47a7d35f74ec1e61b6821793d010110caca23220223ef0cdf33fe831",
9
+ "package-lock.json": "ec288d8d4dd1b014a978068b65e02ad11f0b712dcd4ba120d563599e4e02752c",
10
10
  "sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
11
11
  "sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
12
12
  "sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
13
- "sources/client/folder.js": "bc0c2bd347598f7b6c17fc1c0aea7be1093e5b731f0ae8d0c2fa81a7f5b5fdcb",
13
+ "sources/client/folder.js": "138f78c7a04894f8dd87c4db4190b4be43d4fdf8d23e2075a2515c7db54e8e42",
14
14
  "sources/client/handler.js": "2da3c811e4f5d6c0060a0bde28d131da6736be6618e9ea20e243b984fc546bdd",
15
15
  "sources/client/index.js": "037ff635b149a617adf1219d34f0ba9dd936d5f60cea59e62d276a49468c3dc3",
16
16
  "sources/client/readme.md": "a50aa4aa3a90606b2f446e2d29166aa26175ae87539901299e9347322ae4a2fe",
@@ -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": "51bd79959607aad8b5bb8ed0aa9076c780371e7b801016f9b5a1872e32bbd825",
29
+ "sources/data/progress.md": "e5f3e52c1b015940a36416656f85fc238f6c1de26b082b3bd6bd2022d807a0ec",
30
30
  "sources/data/readme.md": "593fa2ae07aa91bc26d7542275da6953a9cd419240a9a49e00cb62fb9d5d8e36",
31
31
  "sources/data/reports.js": "0330f404860fe2589a7d46a2f0fe690ca23249bd841a062a26718742d4fd11d6",
32
32
  "sources/data/schema.js": "1c994f9adb76c156dc86601dd6b1046376b66549b041e1a58aa1727b5476bdbe",
@@ -67,7 +67,7 @@
67
67
  "sources/modules/agent/hooks.js": "b74e9d8f4b491b6d16d979891de69941955e50852289f55589c82997405c9048",
68
68
  "sources/modules/agent/index.js": "eeb1f34f9ca36e13749389ea544f23e385891d355f6050206bff3f6bd106ceeb",
69
69
  "sources/modules/agent/log.js": "03ae1979e2b00459178deda49847c30ed75937fc4f3eea9b778ca6c0f8c4ded0",
70
- "sources/modules/agent/loop.js": "efff4ddb13b77468c662a966fa4d6e3c8acf060d30d94f4b0132bcc9d30fba12",
70
+ "sources/modules/agent/loop.js": "c7e732fba6d180f1728c927d542901be064e950899541f18575c9e9eb6365a97",
71
71
  "sources/modules/agent/mcp-pool.js": "aa4e75e2fcfe07883f9b721b33cee642fbbe11b8f416f8cd6a81f9c1ab39edde",
72
72
  "sources/modules/agent/permissions.js": "b3a3b73feea646eb765a4c0b71f8c63ecb36c0d616cf237a9fb040fb19590fbc",
73
73
  "sources/modules/agent/plugins.js": "9aed13c2d7bbf66dcd165f23b3969874561aea470dc16dac1435d183696cfda5",
@@ -75,7 +75,7 @@
75
75
  "sources/modules/agent/recovery.js": "7a61dfdb2aef10b5049aee85d579379fdf98af3524f8509428ebc5a613bad92d",
76
76
  "sources/modules/agent/resources.js": "2a52a31b2a96e17c713a6e311cbf0fe31a6debf8cd596e8e8067c722e6299eb2",
77
77
  "sources/modules/agent/scheduler.js": "26cc6fffb9f570d501dbef5261b274323fe8e8165d1598097ff8f77d32cdd9cf",
78
- "sources/modules/agent/session.js": "1f5e9f224e4f1db8fc486861eb9f95478b5010a557db09f9af057d98ba3970d3",
78
+ "sources/modules/agent/session.js": "b972f93adecd2d669ec80ba6027db9638b225baa5e2fc3d75f11c77906b99b09",
79
79
  "sources/modules/agent/system.js": "ec1d0cf29c490b164b4adb0025a138bd12e037276d6286676a085eff2e29ec9b",
80
80
  "sources/modules/agent/taint.js": "bf6aee5cc7e8b15ac365525fa74645d4a92da5ce1bdbcdba012e80767b5c7063",
81
81
  "sources/modules/agent/tools/branch.js": "1ac9ccafcf292801575e8205ec7b63ab7dd6d53b03ad2a67cc3571092b716bcf",
@@ -111,7 +111,7 @@
111
111
  "sources/modules/agent/types.d.ts": "9d47168bb9fefb1d7c5506afb263c6a6f2e3609602ee78e50c98c02bc052831f",
112
112
  "sources/modules/agent/undo.js": "e46f3f1172c6d6e4055332bada74c546c0b0a0e585f1c96eac9b40e4d35b8544",
113
113
  "sources/modules/agent/util.js": "9bca6569c16cdfed0134dfec0c99347b3e999692afdc35719886f6083fed87c5",
114
- "sources/modules/agent/voice.js": "498f4b1cad8b3b211eb3dee7b362f95cfd3e5ac2c6d69edd517f219b5f582a1d",
114
+ "sources/modules/agent/voice.js": "02898af5fb4495e3bde42ecbc8ac7be63922c7cf33111efca476ae7aa75780ca",
115
115
  "sources/modules/ai-schema.js": "84ecc7a872dec42e521f9e05366f053e36ae19b185f35c552b945157f95c66f4",
116
116
  "sources/modules/bridge/chrome.js": "3bbba8c1726ef8341918bf94d9542093d47e57ec5364f600e863fe2500342e37",
117
117
  "sources/modules/bridge/hub.js": "4398d503ad2581fad763ec2f56a6893cd00ecc6f0c0af42523f77de43c4e5f45",
@@ -176,16 +176,16 @@
176
176
  "sources/modules/sandbox/vnc-proxy.js": "1c75c2b24d579f254de1c4727621fbbcc7e8a10360f638f4cf1c4bd91184d103",
177
177
  "sources/modules/trainer/dataset.js": "e631e1feda2958cf93436cb48a331958d7b029aa52bd42247865e87504b642f7",
178
178
  "sources/modules/trainer/downloader.js": "d9e96cb07e7bf64386558be8c2265c482af35a513f42954250add6d5fc87bdc4",
179
- "sources/modules/trainer/halogen.js": "f908f16f8481cdf22d3baff4890bc446c9791325123ee471359c9847b3bac899",
179
+ "sources/modules/trainer/halogen.js": "f2c8f09b756f12f0c81ceab9c283464e6ffe38325675e888c75c8e5954e4cd22",
180
180
  "sources/modules/trainer/huggingface.js": "0ee6434522be98301d72d90f6395a271f5de86acf92a176590a4141a92482e83",
181
- "sources/modules/trainer/index.js": "d03489c77918234d55d828b3e41b2e9de204e72e34584adcb9c460e00903b29f",
182
- "sources/modules/trainer/local-engine.js": "4d84c41e3d5e7459c840dae89a69f05991b01d36514f12ff67bddcc9044b9479",
181
+ "sources/modules/trainer/index.js": "d2f15d7507f1990d0509e56d14a08b43d214e28409d2b3de536cc485ae1b9a14",
182
+ "sources/modules/trainer/local-engine.js": "814f0bc17865cec36c70577b28fc2d250e0229834b1466d4bcf11afe681148fa",
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": "9328004b05adfb9b1f37f0f669a62f10f9015ae3873449d23a03512d537e29ed",
188
+ "sources/modules/trainer/worker/local_infer_worker.py": "b7d7924c0019af8ec72ec79b34e17aabe1281ea72c13448832f43838fc807eca",
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": "afd46409b9dfceaf989452727c3a549b6d531f88870b31910c4a68eb635e2bcf",
979
+ "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "50c677b727729a3fdcea165bbc4bbb94530f575ce92fc5026ccd9f5e96936ba3",
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",
@@ -250,6 +250,10 @@ export default {
250
250
  <span class="kv-label">Встроенный сервер (:8731):</span>
251
251
  <span class="kv-val">{{halogenServerLine}}</span>
252
252
  </div>
253
+ <div class="kv-row" ~if="resolvedProtocol === 'halogen' && halogenNpuLine">
254
+ <span class="kv-label">NPU (Ryzen AI):</span>
255
+ <span class="kv-val">{{halogenNpuLine}}</span>
256
+ </div>
253
257
  <div class="kv-row" ~if="resolvedProtocol === 'halogen' && halogenSpeculationLine">
254
258
  <span class="kv-label">Спекуляция (MTP):</span>
255
259
  <span class="kv-val">{{halogenSpeculationLine}}</span>
@@ -283,12 +287,12 @@ export default {
283
287
  <textarea rows="2" :value="testTtsText" placeholder="Текст для озвучивания…" @input="testTtsText = $this.value"></textarea>
284
288
  <div class="chips" style="gap:6px;" ~if="ttsKind !== 'base'">
285
289
  <button type="button" class="btn" ~for="ttsVoicePresets"
286
- :style="testTtsInstructions === $for.item.value ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
290
+ :style="(isCustomVoice06B ? testTtsVoice === $for.item.speaker : testTtsInstructions === $for.item.value) ? 'border-color:var(--accent-color,#4f46e5);color:var(--accent-color,#4f46e5);' : ''"
287
291
  @tap="selectTtsPreset($for.item)">
288
292
  {{$for.item.label}}
289
293
  </button>
290
294
  </div>
291
- <textarea rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «Мужской баритон, спокойная деловая интонация»…" @input="testTtsInstructions = $this.value"></textarea>
295
+ <textarea ~if="ttsKind === 'voice_design' || (ttsKind === 'custom_voice' && !isCustomVoice06B)" rows="2" :value="testTtsInstructions" placeholder="Описание голоса и манеры (instruct): например «Мужской баритон, спокойная деловая интонация»…" @input="testTtsInstructions = $this.value"></textarea>
292
296
  <input ~if="ttsKind === 'custom_voice'" :value="testTtsVoice" placeholder="Голос (speaker): Ryan, Aiden, Dylan, Serena, Vivian…" @input="testTtsVoice = $this.value">
293
297
  <div ~if="ttsKind === 'base'" style="font-size:12px;opacity:0.8;">Модель Base клонирует голос: для синтеза нужна эталонная запись (WAV) и её текст. Без эталона используйте VoiceDesign или CustomVoice.</div>
294
298
  </div>
@@ -314,6 +318,10 @@ export default {
314
318
  <input type="checkbox" :checked="testNoThinking" @change="testNoThinking = $event.target.checked">
315
319
  <span>Без рассуждений (чистый замер скорости)</span>
316
320
  </label>
321
+ <label class="toolbar" ~if="testModality === 'llm'" style="cursor:pointer;font-size:12px;opacity:0.85;">
322
+ <input type="checkbox" :checked="testPrefill4k" @change="testPrefill4k = $event.target.checked">
323
+ <span>Замер длинного Prefill (4K токенов)</span>
324
+ </label>
317
325
  </div>
318
326
  <div class="toolbar" ~if="testMetricsLine" style="font-size:12px;opacity:0.9;">
319
327
  <span class="pill">{{testMetricsLine}}</span>
@@ -327,6 +335,7 @@ export default {
327
335
  info: null,
328
336
  modelEnabled: true,
329
337
  testNoThinking: true,
338
+ testPrefill4k: false,
330
339
  provisionBanner: '',
331
340
  weightsRepair: null,
332
341
  testPrompt: 'Привет! Коротко в 3–4 предложениях расскажи, чем ты умеешь помогать в работе с документами, таблицами и кодом.',
@@ -384,6 +393,12 @@ export default {
384
393
  return 'base';
385
394
  return 'voice_design';
386
395
  },
396
+ get isCustomVoice06B() {
397
+ if (this.ttsKind !== 'custom_voice')
398
+ return false;
399
+ const id = String(this.info?.id || this.resolvedModelId || '').toLowerCase();
400
+ return id.includes('0.6b');
401
+ },
387
402
  selectTtsPreset(p) {
388
403
  if (!p)
389
404
  return;
@@ -441,11 +456,15 @@ export default {
441
456
  get halogenServerLine() {
442
457
  const setup = this.info?.engineSetup;
443
458
  const prof = setup?.running?.profile || setup?.settings?.profile || 'default';
444
- const npu = (setup?.running?.npuPrefill || setup?.engine?.npuReady) ? ' · NPU prefill' : '';
459
+ const npu = (setup?.running?.npuPrefill || setup?.engine?.npuActive) ? ' · NPU prefill' : '';
445
460
  if (this.info?.halogenOnline)
446
461
  return `Запущен (профиль ${prof}${npu})`;
447
462
  return `Автозапуск по первому запросу (профиль ${prof}${npu})`;
448
463
  },
464
+ get halogenNpuLine() {
465
+ const setup = this.info?.engineSetup;
466
+ return setup?.engine?.npuStatusText || '';
467
+ },
449
468
  get weightsRepairLine() {
450
469
  const r = this.weightsRepair || this.info?.weightsRepair;
451
470
  if (!r)
@@ -464,9 +483,10 @@ export default {
464
483
  return '';
465
484
  if (plan.summary)
466
485
  return plan.summary;
467
- if (plan.enabled || plan.mode === 'explicit' || plan.mode === 'weights-only') {
486
+ const hasMtpWeight = Boolean(setup?.sidecars?.mtp);
487
+ if (plan.enabled || plan.mode === 'explicit' || plan.mode === 'weights-only' || hasMtpWeight) {
468
488
  const parts = [
469
- plan.mode === 'explicit' ? 'MTP включён' : 'MTP (по весам)',
489
+ plan.mode === 'explicit' ? 'MTP включён' : (hasMtpWeight ? 'MTP (по весам)' : 'MTP'),
470
490
  plan.promptLookup ? 'Prompt Lookup вкл.' : 'Prompt Lookup выкл.',
471
491
  ];
472
492
  return parts.filter(Boolean).join(' · ');
@@ -487,6 +507,9 @@ export default {
487
507
  catch {
488
508
  inf = await this.$item.fetch('info');
489
509
  }
510
+ if (inf && typeof inf === 'object' && inf.DATA && !inf.engineSetup && !inf.weightFormat && (inf.DATA.engineSetup || inf.DATA.weightFormat || inf.DATA.speculation)) {
511
+ inf = { ...inf.DATA, id: inf.id || inf.DATA.id, label: inf.label || inf.DATA.label, path: inf.path || inf.DATA.path };
512
+ }
490
513
  this.info = inf;
491
514
  if (inf?.weightsRepair)
492
515
  this.weightsRepair = inf.weightsRepair;
@@ -586,7 +609,7 @@ export default {
586
609
  if (!this.$item)
587
610
  return;
588
611
  const m = this.testModality;
589
- if (m === 'llm' && !this.testPrompt.trim())
612
+ if (m === 'llm' && !this.testPrefill4k && !this.testPrompt.trim())
590
613
  return;
591
614
  this.testing = true;
592
615
  this.error = '';
@@ -616,13 +639,15 @@ export default {
616
639
  const body = { modality: m };
617
640
  if (m === 'llm') {
618
641
  body.messages = [{ role: 'user', content: this.testPrompt.trim() }];
619
- body.maxOutput = 256;
642
+ body.maxOutput = this.testPrefill4k ? 48 : 256;
643
+ if (this.testPrefill4k)
644
+ body.prefillBenchmark = true;
620
645
  if (this.hasEffortCap && this.testNoThinking)
621
646
  body.effort = 'off';
622
647
  }
623
648
  else if (m === 'tts') {
624
649
  body.text = this.testTtsText.trim();
625
- if (this.testTtsInstructions.trim())
650
+ if (!this.isCustomVoice06B && this.testTtsInstructions.trim())
626
651
  body.instructions = this.testTtsInstructions.trim();
627
652
  if (this.ttsKind === 'custom_voice' && this.testTtsVoice.trim())
628
653
  body.voice = this.testTtsVoice.trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.50",
3
+ "version": "1.0.52",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -267,7 +267,13 @@ export class $folder extends $item {
267
267
  || method === 'save_files'
268
268
  || method === 'state'
269
269
  || method === 'delete_log_entry'
270
- || (typeof method === 'string' && method.startsWith('sql_'))
270
+ || (typeof method === 'string' && (
271
+ method.startsWith('sql_')
272
+ || method.startsWith('trainer_')
273
+ || method.startsWith('provider_')
274
+ || method.startsWith('license_')
275
+ || method.startsWith('messenger_')
276
+ ))
271
277
  || (method === 'logs' && params.mode && params.mode !== 'folder' && params.mode !== 'files');
272
278
  return WORK.fetch?.(this.short || '/', method, params, post_data).then(res => {
273
279
  return isRawLogPayload ? res : WORK.__bind(res);
@@ -1,6 +1,15 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~12:45, 19.11] Фикс подмены ответов `trainer_model_info` в `WORK.__bind` (исчезали `Формат весов`, `NPU (Ryzen AI)` и появлялась ложная `Спекуляция (MTP): Отключена`) и полировка `Qwen3-TTS 0.6B CustomVoice` (`sources/client/folder.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `tests/halogen-speculation.test.js`, `odant-work@1.0.52`):
5
+ - **Причина бага в карточке модели:** `trainer_model_info` возвращал объект с полем `path` (`/MODELS/Local/...`), поэтому `$folder.prototype.fetch` прогонял его через `WORK.__bind(res)`, превращая plain JSON-ответ в узел дерева `CORE.$class` и пряча `weightFormat`, `engineSetup`, `speculation`, `halogenOnline` в `.DATA`. При рендере шаблона срабатывал `_onEmpty`, возвращая truthy `Promise` (отсюда `Спекуляция (MTP): Отключена`, скрытый `NPU (Ryzen AI)` и исчезнувший `Формат весов`).
6
+ - **Исправление:** `trainer_*`, `provider_*`, `license_*` и `messenger_*` исключены из `WORK.__bind` в `sources/client/folder.js` (они возвращают чистые JSON-структуры, а не узлы дерева), плюс добавлена страховка распаковки `.DATA` в `form/trainer` `reload()`.
7
+ - **`Qwen3-TTS 0.6B CustomVoice`:** в карточке и в `local_infer_worker.py` для `0.6B` больше не передаётся неподдерживаемый `instruct` (остаётся чистый выбор диктора `Ryan`, `Aiden`, `Serena`, `Vivian`).
8
+ - [~11:45, 19.11] Ускорение голоса, умная выгрузка памяти, перевод `Qwen3-4B`/`0.6B` на GPU ROCm, авто-заголовки задач, диагностика NPU и бенчмарк длинного Prefill 4K (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{local-engine,halogen,index}.js`, `sources/modules/agent/{voice,loop,session}.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.51`):
9
+ - **Ускорение синтеза речи (`local_infer_worker.py`, `agent/voice.js`):** при загрузке `Qwen3-TTS` на GPU `cuda:0` декодер вокодера `speech_tokenizer` переносится на CPU целиком один раз (`_move_qwen_tts_vocoder_to_cpu`), устраняя сотни мелких перебросов `cuda:0 ↔ cpu` внутри `_install_rocm_miopen_fallback`; в голосовом режиме задач (`localVoiceModel`) при наличии быстрой `Qwen3-TTS-12Hz-0.6B-CustomVoice` ей автоматически отдаётся приоритет.
10
+ - **Умная выгрузка тяжёлой диффузии по простою и нехватке памяти (`local_infer_worker.py`, `local-engine.js`):** добавлен `_evict_memory_if_needed` + фоновый таймер простоя для `("image", ...)` (выгрузка `Z-Image-Turbo` через `WORK_IMAGE_IDLE_SEC = 600` с или при свободной RAM `< 20 ГБ`), тогда как лёгкие модели (RAG, TTS, ASR, 0.6B/4B) остаются горячими до критического порога `< 10 ГБ`.
11
+ - **`LocalCausalLM` (`Qwen3-4B` / `Qwen3-0.6B`) переведён на GPU `cuda:0` + автоподключение в WORK (`local_infer_worker.py`, `local-engine.js`, `agent/loop.js`, `agent/session.js`):** `LocalCausalLM` загружает слои на `cuda:0` в `bfloat16` (с освобождением CPU-mmap и откатом на CPU при нехватке VRAM) и отдаёт `device`/`loadMs`; `loop.js` автоматически использует `compactLlm` (`Qwen3-4B` / `Qwen3-0.6B`) для сжатия контекста даже без явного `compactModel` в `ai/config.js`; `session.js` (`generateAutoTaskTitle` / `scheduleAutoTaskTitle`) в фоне генерирует короткие 3–6-словные заголовки новых задач через `classifierModel()` (`Qwen3-0.6B`).
12
+ - **Точная диагностика NPU и замер длинного Prefill 4K (`halogen.js`, `index.js`, `trainer.js`):** `describeEngineSetup` формирует `engine.npuStatusText` (активен или точная причина: нет `xrt-smi.exe`, нет `*.xclbin` или профиль), `halogenSpeculationLine` не показывает ложное «Отключена» при наличии MTP-весов, а в карточку LLM добавлена галочка **«Замер длинного Prefill (4K токенов)»** с уникальным ~4K-контекстом без попадания в KV-кэш.
4
13
  - [~10:30, 19.11] Устранение `miopenStatusInternalError` на GPU ROCm, фикс заморозки спиннера `work-loader` и пакетная подготовка окружения под все скачанные модели (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/{local-engine,index}.js`, `sources/client.js`, `oda/tools/styles/styles.js`, `MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.50`):
5
14
  - **Прозрачный перехват свёрток MIOpen на Windows ROCm (`_install_rocm_miopen_fallback` в `local_infer_worker.py`):** все матричные и трансформерные операции (`nn.Linear`, `SDPA` — 99.5 % вычислений в `Z-Image-Turbo`, `Qwen3-TTS`, `Qwen3-ASR`, `Qwen3-4B`) работают на полной скорости GPU `cuda:0` через `hipBLASLt`, а при отказе свёрточного ядра MIOpen (`miopenStatusInternalError` на `Conv1d/2d/3d` и `ConvTranspose1d/2d/3d` в декодере `VAE` и вокодере `speech_tokenizer`) свёртка прозрачно выполняется на CPU (в единой памяти Unified Memory) с возвратом тензора обратно на `cuda:0` и кэшированием ключа `(op, dtype)` без повторных сбойных вызовов. Плюс добавлено самовосстановление инференса `cuda:0 → cpu` в `handle_image`.
6
15
  - **Исправление заморозки и смещения глобального лоадера `work-loader` (`oda/tools/styles/styles.js`, `sources/client.js`):** из `@media (prefers-reduced-motion: reduce)` убраны `animation-duration: .01ms !important; animation-iteration-count: 1 !important`, которые в Windows 11 / RDP / VNC останавливали все бесконечные спиннеры (`work-loader`, `spinners:*`, `--rainbow`) на первом кадре; `top.loader` создаётся строго в контексте `top.document` с единым кросс-фреймовым счётчиком `top.__workLoaderState` и исключением фоновых поллингов (`trainer_provision_status`).
@@ -207,7 +207,7 @@ async function runLoopCore(opts) {
207
207
  }
208
208
  const system = typeof opts.system === 'function' ? await opts.system() : (opts.system ?? '');
209
209
  const toolsTokens = estimateTokens(schemas);
210
- const compactLlm = opts.ctx?.env?.config?.compactModel && typeof opts.ctx?.env?.compactLlm === 'function'
210
+ const compactLlm = typeof opts.ctx?.env?.compactLlm === 'function'
211
211
  ? await opts.ctx.env.compactLlm(llm.name).catch(() => llm)
212
212
  : llm;
213
213
  await maybeCompact({ llm: compactLlm, items, host, system, toolsTokens, hooks: opts.hooks, task: opts.ctx?.task, contextTokens: llm.contextTokens });
@@ -716,7 +716,10 @@ export async function prompt(file, params = {}) {
716
716
  body.items.push({ id: genId(), type: 'user', time: Date.now(), content: text, ...(voice ? { voice: true } : {}), ...(attachments.length ? { attachments } : {}) });
717
717
  if (!body.title) {
718
718
  const fallbackTitle = attachments.map(a => a?.name || String(a?.path || '').split('/').pop()).filter(Boolean).join(', ');
719
- body.title = (text.split('\n')[0] || fallbackTitle).slice(0, 80);
719
+ const rawSlice = (text.split('\n')[0] || fallbackTitle).slice(0, 80);
720
+ body.title = rawSlice;
721
+ if (text.length > 24 && !process.env.NODE_TEST_CONTEXT)
722
+ scheduleAutoTaskTitle(s, session, file, text, rawSlice);
720
723
  }
721
724
  }
722
725
  if (params.location && typeof params.location === 'object')
@@ -1138,3 +1141,52 @@ export async function idle(file) {
1138
1141
  export function isRunning(file) {
1139
1142
  return !!stateOf(file).running;
1140
1143
  }
1144
+
1145
+ /** Сгенерировать короткий осмысленный заголовок задачи (3–6 слов) через быструю локальную модель (`Qwen3-0.6B`).
1146
+ * @param {any} env
1147
+ * @param {string} text
1148
+ * @returns {Promise<string>}
1149
+ */
1150
+ export async function generateAutoTaskTitle(env, text) {
1151
+ const clean = String(text || '').trim();
1152
+ if (!clean || !env || typeof env.classifierModel !== 'function')
1153
+ return '';
1154
+ const model = await env.classifierModel().catch(() => null);
1155
+ if (!model || typeof model.streamChat !== 'function')
1156
+ return '';
1157
+ const promptText = 'Сформулируй очень короткий заголовок (3–6 слов, без кавычек, без точки в конце и без пояснений) для запроса пользователя:\n'
1158
+ + clean.slice(0, 600);
1159
+ let raw = '';
1160
+ for await (const chunk of model.streamChat({
1161
+ messages: [{ role: 'user', content: promptText }],
1162
+ max_tokens: 28,
1163
+ maxOutput: 28,
1164
+ temperature: 0.1,
1165
+ }, { effort: 'off' })) {
1166
+ if (typeof chunk === 'string')
1167
+ raw += chunk;
1168
+ }
1169
+ const title = raw
1170
+ .replace(/<think>[\s\S]*?<\/think>/gi, '')
1171
+ .replace(/^["'«»„“]+|["'«»„“.,:;!?]+$/g, '')
1172
+ .replace(/\s+/g, ' ')
1173
+ .trim()
1174
+ .slice(0, 80);
1175
+ return title.length >= 3 ? title : '';
1176
+ }
1177
+
1178
+ function scheduleAutoTaskTitle(s, session, file, text, expectedPrevTitle) {
1179
+ const place = file?.$class || file?.$owner || null;
1180
+ setTimeout(async () => {
1181
+ try {
1182
+ const env = await createEnv({ place, session });
1183
+ const title = await generateAutoTaskTitle(env, text);
1184
+ if (!title || !s?.body || s.body.title !== expectedPrevTitle)
1185
+ return;
1186
+ s.body.title = title;
1187
+ await save(s, session);
1188
+ send(s, session, { type: 'task.title', title });
1189
+ }
1190
+ catch { /* авто-заголовок необязателен */ }
1191
+ }, 50).unref?.();
1192
+ }
@@ -34,10 +34,12 @@ async function configFor(file) {
34
34
  return loadConfig(place);
35
35
  }
36
36
 
37
- /** Найти активную локальную модель в /MODELS/Local с заданной возможностью (stt/tts). */
37
+ /** Найти активную локальную модель в /MODELS/Local с заданной возможностью (stt/tts).
38
+ * Для интерактивного TTS-голоса при наличии быстрой 0.6B CustomVoice отдаём ей приоритет перед тяжёлой 1.7B VoiceDesign. */
38
39
  async function localVoiceModel(cap) {
39
40
  try {
40
41
  const local = await WORK.get_item('/MODELS/Local').catch(() => null);
42
+ const matches = [];
41
43
  for (const m of (await local?.items) || []) {
42
44
  if (!m || Array.isArray(m))
43
45
  continue;
@@ -45,8 +47,16 @@ async function localVoiceModel(cap) {
45
47
  if ((m.aiActive ?? m.DATA?.aiActive) === false || m.DATA?.enabled === false)
46
48
  continue;
47
49
  if (capsOf(m).includes(cap))
48
- return m;
50
+ matches.push(m);
49
51
  }
52
+ if (!matches.length)
53
+ return null;
54
+ if (cap === 'tts' && matches.length > 1) {
55
+ const fast = matches.find(m => /0\.6b|customvoice|kokoro/i.test(String(m.id || m.model || m.path || '')));
56
+ if (fast)
57
+ return fast;
58
+ }
59
+ return matches[0];
50
60
  }
51
61
  catch { /* ignore */ }
52
62
  return null;
@@ -929,7 +929,18 @@ export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {
929
929
 
930
930
  const xrtSmiPath = path.join(systemRoot, 'System32', 'AMD', 'xrt-smi.exe');
931
931
  const npuDriverInstalled = fs.existsSync(xrtSmiPath);
932
- const npuXclbinPath = path.join(buboRootDir, 'tools', 'npu', 'final_4096x2560x1024_128x64x128.xclbin');
932
+ let npuXclbinPath = path.join(buboRootDir, 'tools', 'npu', 'final_4096x2560x1024_128x64x128.xclbin');
933
+ if (!fs.existsSync(npuXclbinPath)) {
934
+ const npuDir = path.join(buboRootDir, 'tools', 'npu');
935
+ try {
936
+ if (fs.existsSync(npuDir)) {
937
+ const found = fs.readdirSync(npuDir).find(f => f.toLowerCase().endsWith('.xclbin'));
938
+ if (found)
939
+ npuXclbinPath = path.join(npuDir, found);
940
+ }
941
+ }
942
+ catch { /* ignore */ }
943
+ }
933
944
  const npuKernelsPresent = fs.existsSync(npuXclbinPath);
934
945
 
935
946
  const vcRedistInstalled = fs.existsSync(path.join(systemRoot, 'System32', 'vcruntime140.dll'));
@@ -1889,6 +1900,32 @@ export async function describeEngineSetup({
1889
1900
  return { path: p, name: path.basename(p), sizeGb };
1890
1901
  };
1891
1902
  const stateOnDisk = readEngineStateSync(rootDir);
1903
+ const runningNpu = _managedInfo ? Boolean(_managedInfo.npuPrefill) : Boolean(stateOnDisk?.pid && stateOnDisk.npuPrefill);
1904
+ const npuReady = Boolean(winEnv.npuDriverInstalled && winEnv.npuKernelsPresent);
1905
+ let npuStatusText = '';
1906
+ if (os.platform() === 'linux') {
1907
+ const hasAccel = fs.existsSync('/dev/accel/accel0');
1908
+ npuStatusText = hasAccel ? 'Доступен (/dev/accel/accel0)' : 'Не обнаружен (/dev/accel/accel0)';
1909
+ }
1910
+ else if (runningNpu) {
1911
+ npuStatusText = 'Активен (--npu-prefill on · Ryzen AI XRT)';
1912
+ }
1913
+ else if (!cfg.npuPrefill) {
1914
+ npuStatusText = 'Отключён в настройках движка (npuPrefill: false)';
1915
+ }
1916
+ else if (!winEnv.npuDriverInstalled) {
1917
+ npuStatusText = 'Не включён: не найден драйвер AMD XRT NPU (C:\\Windows\\System32\\AMD\\xrt-smi.exe)';
1918
+ }
1919
+ else if (!winEnv.npuKernelsPresent) {
1920
+ npuStatusText = 'Не включён: отсутствует AIE-ядро *.xclbin в папке bubo\\tools\\npu';
1921
+ }
1922
+ else if (['exact', 'stock', 'vanilla'].includes(String(_managedInfo?.profile || cfg.profile || ''))) {
1923
+ npuStatusText = `Отключён профилем ${_managedInfo?.profile || cfg.profile} (переключите на default)`;
1924
+ }
1925
+ else if (npuReady) {
1926
+ npuStatusText = 'Готов к запуску (--npu-prefill on, перезапустите движок при необходимости)';
1927
+ }
1928
+
1892
1929
  return {
1893
1930
  settings: cfg,
1894
1931
  weightsDir,
@@ -1914,7 +1951,11 @@ export async function describeEngineSetup({
1914
1951
  installed: Boolean(winEnv.buboInstalled || winEnv.gufoInstalled),
1915
1952
  runtime: winEnv.buboInstalled ? 'bubo.exe' : (winEnv.gufoInstalled ? 'gufo.exe' : ''),
1916
1953
  exePath,
1917
- npuReady: Boolean(winEnv.npuDriverInstalled && winEnv.npuKernelsPresent),
1954
+ npuReady,
1955
+ npuDriverInstalled: Boolean(winEnv.npuDriverInstalled),
1956
+ npuKernelsPresent: Boolean(winEnv.npuKernelsPresent),
1957
+ npuActive: runningNpu,
1958
+ npuStatusText,
1918
1959
  },
1919
1960
  running: _managedInfo ? {
1920
1961
  runtime: _managedInfo.runtime,
@@ -541,9 +541,27 @@ async function runSingleModelSmokeTest(ai, p = {}) {
541
541
  summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
542
542
  };
543
543
  }
544
- const messages = Array.isArray(p.messages) && p.messages.length
544
+ const prefillBenchmark = isTruthy(p.prefillBenchmark);
545
+ let messages = Array.isArray(p.messages) && p.messages.length
545
546
  ? p.messages
546
547
  : [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
548
+ if (prefillBenchmark) {
549
+ const nonce = Math.floor(Date.now() / 1000);
550
+ const rows = [];
551
+ let sum = 0;
552
+ // ~220 строк * ~18 токенов ≈ ~4 000 токенов уникального табличного контекста без попадания в KV-кэш
553
+ for (let i = 1; i <= 220; i++) {
554
+ const qty = ((i * 7 + (nonce % 13)) % 40) + 1;
555
+ const price = 100 + ((i * 31) % 900);
556
+ const total = qty * price;
557
+ sum += total;
558
+ rows.push(`Строка #${nonce}-${String(i).padStart(3, '0')}: Товарная позиция А-${i}, склад Основной, количество ${qty} шт., цена ${price} руб., сумма ${total} руб.`);
559
+ }
560
+ messages = [{
561
+ role: 'user',
562
+ content: `Бенчмарк длинного контекста #${nonce} (~4000 токенов):\n${rows.join('\n')}\n\nСколько товарных строк перечислено выше и какая контрольная сумма по первой строке? Ответь одной короткой строкой без пояснений.`,
563
+ }];
564
+ }
547
565
  const isHalo = ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen';
548
566
  const haloUrl = ai?.baseUrl || ai?.DATA?.baseUrl || HALOGEN_DEFAULT_BASE_URL;
549
567
  // Холодный запуск bubo.exe (загрузка 116 ГБ весов) не должен выглядеть как медленная генерация:
@@ -559,7 +577,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
559
577
  }
560
578
  const metricsBefore = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
561
579
  const genT0 = Date.now();
562
- const maxOut = Number(p.maxOutput || p.maxTokens) || 256;
580
+ const maxOut = prefillBenchmark ? 48 : (Number(p.maxOutput || p.maxTokens) || 256);
563
581
  const chatOpts = {
564
582
  messages,
565
583
  maxOutput: maxOut,
@@ -579,10 +597,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
579
597
  const metricsDelta = isHalo ? computeHalogenMetricsDelta(metricsBefore, metricsAfter) : null;
580
598
 
581
599
  const ttftMs = Number(usage?.ttftMs) || 0;
600
+ const loadMs = Number(usage?.loadMs) || 0;
601
+ const device = String(usage?.device || '');
582
602
  const clientTokPerSec = Number(usage?.tokPerSec) || 0;
583
603
  const serverTokPerSec = Number(metricsDelta?.serverDecodeTokPerSec) || 0;
584
604
  const tokPerSec = serverTokPerSec > 0 ? serverTokPerSec : clientTokPerSec;
585
- const promptTokPerSec = Number(metricsDelta?.serverPrefillTokPerSec || usage?.promptTokPerSec) || 0;
605
+ const fallbackPrefillTokSec = (Number(usage?.prompt_tokens) > 0 && ttftMs > 5)
606
+ ? +((Number(usage.prompt_tokens) * 1000) / ttftMs).toFixed(1)
607
+ : 0;
608
+ const promptTokPerSec = Number(metricsDelta?.serverPrefillTokPerSec || usage?.promptTokPerSec) || fallbackPrefillTokSec;
586
609
  const mtpAcceptPct = metricsDelta?.mtpAcceptPct ?? null;
587
610
  const mtpTokensPerStep = metricsDelta?.mtpTokensPerStep ?? null;
588
611
 
@@ -590,23 +613,29 @@ async function runSingleModelSmokeTest(ai, p = {}) {
590
613
  ok: true,
591
614
  modality: 'llm',
592
615
  text: text.trim(),
616
+ device,
617
+ loadMs,
593
618
  durationMs,
594
619
  ttftMs,
595
620
  tokPerSec,
596
621
  clientTokPerSec,
597
622
  serverDecodeTokPerSec: serverTokPerSec,
598
623
  promptTokPerSec,
624
+ prefillBenchmark,
599
625
  mtpAcceptPct,
600
626
  mtpTokensPerStep,
601
627
  usage,
602
628
  engineStartMs,
603
629
  totalMs: durationMs + engineStartMs,
604
630
  summary: [
631
+ device ? `${device}` : '',
605
632
  tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
633
+ promptTokPerSec > 0 && prefillBenchmark ? `Prefill ${promptTokPerSec} tok/s` : '',
606
634
  ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
607
635
  mtpAcceptPct !== null
608
636
  ? `MTP ${mtpAcceptPct}%${mtpTokensPerStep ? ` (${mtpTokensPerStep} ток/шаг)` : ''}`
609
637
  : '',
638
+ loadMs > 500 ? `загрузка ${(loadMs / 1000).toFixed(1)} с` : '',
610
639
  engineStartMs > 500 ? `старт движка ${(engineStartMs / 1000).toFixed(1)} с` : '',
611
640
  ].filter(Boolean).join(' · '),
612
641
  };
@@ -63,7 +63,7 @@ export function getLocalEngineStatus({ totalRamGb, halogenOnline = false } = {})
63
63
  halogenOnline: Boolean(halogenOnline),
64
64
  mode: highMem ? 'always-on' : 'on-demand',
65
65
  modeLabel: highMem
66
- ? (running ? 'В памяти постоянно (Halo 128–192 ГБ)' : 'Готов к запуску (Halo 128–192 ГБ)')
66
+ ? (running ? 'В памяти постоянно (Halo 128–192 ГБ, автовыгрузка диффузии по простою 10 мин)' : 'Готов к запуску (Halo 128–192 ГБ)')
67
67
  : (running ? `В памяти (автовыгрузка через ${idleTimeoutMin} мин простоя)` : `Автозапуск по запросу (выгрузка через ${idleTimeoutMin} мин)`),
68
68
  idleTimeoutMin: highMem ? 0 : idleTimeoutMin,
69
69
  lastActivityAt: _lastActivityAt,
@@ -584,6 +584,14 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
584
584
  const inputIds = Array.from(tokenizer.encode(promptText), Number);
585
585
 
586
586
  const runOnce = async function* () {
587
+ if (
588
+ !_autoProvisionOverride
589
+ && Date.now() > _rocmUpgradeCooldownUntil
590
+ && isStrixHaloGfx1151Host()
591
+ && !hasRocmGfx1151InVenvSync()
592
+ ) {
593
+ await ensurePythonForModality('llm', { weightsDir, upgradeRocmGfx1151: true }).catch(() => null);
594
+ }
587
595
  const proc = await ensureInferWorker({ modality: 'llm', weightsDir });
588
596
  proc.stdout?.ref?.();
589
597
  const reqId = 'req_' + crypto.randomUUID().slice(0, 8);
@@ -593,6 +601,8 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
593
601
  let finished = false;
594
602
  let workerErr = null;
595
603
  let missingDeps = null;
604
+ let workerDevice = '';
605
+ let workerLoadMs = 0;
596
606
 
597
607
  _pendingRequests.set(reqId, {
598
608
  onMessage(msg) {
@@ -600,6 +610,10 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
600
610
  queue.push(msg.token);
601
611
  }
602
612
  else if (msg.event === 'done') {
613
+ if (msg.device)
614
+ workerDevice = String(msg.device);
615
+ if (msg.loadMs != null)
616
+ workerLoadMs = Number(msg.loadMs) || 0;
603
617
  finished = true;
604
618
  }
605
619
  else if (msg.event === 'error') {
@@ -687,6 +701,8 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
687
701
  cached_tokens: cachedTokens,
688
702
  ttftMs,
689
703
  decodeMs,
704
+ ...(workerDevice ? { device: workerDevice } : {}),
705
+ ...(workerLoadMs > 0 ? { loadMs: workerLoadMs } : {}),
690
706
  ...(tokPerSec > 0 ? { tokPerSec } : {}),
691
707
  ...(sessionRes.fromStatus ? { halogen_from: sessionRes.fromStatus } : {}),
692
708
  };
@@ -5,6 +5,8 @@
5
5
  Общается с Node.js-сервером WORK по протоколу JSONL (stdin -> stdout), удерживая веса модели в памяти между запросами.
6
6
  """
7
7
  import base64
8
+ import ctypes
9
+ import gc
8
10
  import glob
9
11
  import io
10
12
  import json
@@ -12,6 +14,7 @@ import mmap
12
14
  import os
13
15
  import struct
14
16
  import sys
17
+ import threading
15
18
  import time
16
19
  import warnings
17
20
  import wave
@@ -227,39 +230,93 @@ class LocalCausalLM:
227
230
  self.rms_eps = float(self.cfg.get("rms_norm_eps", 1e-6))
228
231
  self.rope_theta = float(self.cfg.get("rope_theta", 1000000.0))
229
232
 
230
- self.embed_tokens = self.store.get("model.embed_tokens.weight")
231
- self.norm = self.store.get("model.norm.weight")
232
- self.lm_head = self.store.get("lm_head.weight")
233
- if self.lm_head is None:
234
- self.lm_head = self.embed_tokens
235
-
236
- self.compute_dtype = self.embed_tokens.dtype
237
-
238
- inv_freq = 1.0 / (
239
- self.rope_theta
240
- ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim)
241
- )
242
- self.inv_freq = inv_freq
243
-
244
- self.layers = []
245
- for i in range(self.num_layers):
246
- p = f"model.layers.{i}"
247
- self.layers.append({
248
- "in_norm": self.store.get(f"{p}.input_layernorm.weight"),
249
- "q_proj": self.store.get(f"{p}.self_attn.q_proj.weight"),
250
- "q_bias": self.store.get(f"{p}.self_attn.q_proj.bias"),
251
- "k_proj": self.store.get(f"{p}.self_attn.k_proj.weight"),
252
- "k_bias": self.store.get(f"{p}.self_attn.k_proj.bias"),
253
- "v_proj": self.store.get(f"{p}.self_attn.v_proj.weight"),
254
- "v_bias": self.store.get(f"{p}.self_attn.v_proj.bias"),
255
- "o_proj": self.store.get(f"{p}.self_attn.o_proj.weight"),
256
- "q_norm": self.store.get(f"{p}.self_attn.q_norm.weight"),
257
- "k_norm": self.store.get(f"{p}.self_attn.k_norm.weight"),
258
- "post_norm": self.store.get(f"{p}.post_attention_layernorm.weight"),
259
- "gate_proj": self.store.get(f"{p}.mlp.gate_proj.weight"),
260
- "up_proj": self.store.get(f"{p}.mlp.up_proj.weight"),
261
- "down_proj": self.store.get(f"{p}.mlp.down_proj.weight"),
262
- })
233
+ target_dev, _ = _best_device_and_dtype()
234
+ self.device = target_dev
235
+
236
+ def _build_weights(dev):
237
+ embed_t = self.store.get("model.embed_tokens.weight")
238
+ norm_t = self.store.get("model.norm.weight")
239
+ lm_t = self.store.get("lm_head.weight")
240
+ if lm_t is None:
241
+ lm_t = embed_t
242
+ dt = embed_t.dtype if embed_t is not None else torch.bfloat16
243
+ if str(dev).startswith("cuda") and dt not in (torch.bfloat16, torch.float16, torch.float32):
244
+ dt = torch.bfloat16
245
+
246
+ def _move(t):
247
+ if t is None:
248
+ return None
249
+ if str(dev) == "cpu":
250
+ return t
251
+ return t.to(device=dev, dtype=dt)
252
+
253
+ embed_m = _move(embed_t)
254
+ norm_m = _move(norm_t)
255
+ lm_m = embed_m if (lm_t is embed_t) else _move(lm_t)
256
+ inv_f = (1.0 / (
257
+ self.rope_theta
258
+ ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim)
259
+ )).to(device=dev)
260
+ layers_m = []
261
+ for i in range(self.num_layers):
262
+ p = f"model.layers.{i}"
263
+ layers_m.append({
264
+ "in_norm": _move(self.store.get(f"{p}.input_layernorm.weight")),
265
+ "q_proj": _move(self.store.get(f"{p}.self_attn.q_proj.weight")),
266
+ "q_bias": _move(self.store.get(f"{p}.self_attn.q_proj.bias")),
267
+ "k_proj": _move(self.store.get(f"{p}.self_attn.k_proj.weight")),
268
+ "k_bias": _move(self.store.get(f"{p}.self_attn.k_proj.bias")),
269
+ "v_proj": _move(self.store.get(f"{p}.self_attn.v_proj.weight")),
270
+ "v_bias": _move(self.store.get(f"{p}.self_attn.v_proj.bias")),
271
+ "o_proj": _move(self.store.get(f"{p}.self_attn.o_proj.weight")),
272
+ "q_norm": _move(self.store.get(f"{p}.self_attn.q_norm.weight")),
273
+ "k_norm": _move(self.store.get(f"{p}.self_attn.k_norm.weight")),
274
+ "post_norm": _move(self.store.get(f"{p}.post_attention_layernorm.weight")),
275
+ "gate_proj": _move(self.store.get(f"{p}.mlp.gate_proj.weight")),
276
+ "up_proj": _move(self.store.get(f"{p}.mlp.up_proj.weight")),
277
+ "down_proj": _move(self.store.get(f"{p}.mlp.down_proj.weight")),
278
+ })
279
+ return embed_m, norm_m, lm_m, dt, inv_f, layers_m
280
+
281
+ try:
282
+ (
283
+ self.embed_tokens,
284
+ self.norm,
285
+ self.lm_head,
286
+ self.compute_dtype,
287
+ self.inv_freq,
288
+ self.layers,
289
+ ) = _build_weights(self.device)
290
+ if str(self.device).startswith("cuda"):
291
+ # После переноса всех весов на GPU освобождаем CPU-mmap ссылки
292
+ self.store.tensors.clear()
293
+ for f_h, mm_h in self.store.files:
294
+ try:
295
+ mm_h.close()
296
+ except Exception:
297
+ pass
298
+ try:
299
+ f_h.close()
300
+ except Exception:
301
+ pass
302
+ self.store.files.clear()
303
+ except Exception:
304
+ if str(self.device).startswith("cuda"):
305
+ try:
306
+ torch.cuda.empty_cache()
307
+ except Exception:
308
+ pass
309
+ self.device = "cpu"
310
+ (
311
+ self.embed_tokens,
312
+ self.norm,
313
+ self.lm_head,
314
+ self.compute_dtype,
315
+ self.inv_freq,
316
+ self.layers,
317
+ ) = _build_weights("cpu")
318
+ else:
319
+ raise
263
320
 
264
321
  def _rope_cos_sin(self, positions, dtype):
265
322
  freqs = torch.outer(positions.to(torch.float32), self.inv_freq)
@@ -270,9 +327,11 @@ class LocalCausalLM:
270
327
 
271
328
  @_inference_mode_dec()
272
329
  def forward_step(self, input_ids, kv_cache, start_pos):
330
+ if input_ids.device != self.embed_tokens.device:
331
+ input_ids = input_ids.to(self.embed_tokens.device)
273
332
  seq_len = input_ids.shape[1]
274
333
  x = F.embedding(input_ids, self.embed_tokens) # [1, seq, hidden]
275
- positions = torch.arange(start_pos, start_pos + seq_len, dtype=torch.long)
334
+ positions = torch.arange(start_pos, start_pos + seq_len, dtype=torch.long, device=self.embed_tokens.device)
276
335
  cos, sin = self._rope_cos_sin(positions, self.compute_dtype)
277
336
 
278
337
  for idx, layer in enumerate(self.layers):
@@ -323,12 +382,13 @@ class LocalCausalLM:
323
382
  return logits[0]
324
383
 
325
384
  @_inference_mode_dec()
326
- def generate_stream(self, req_id, prompt_ids, max_new_tokens=384, temperature=0.6, top_p=0.9, repetition_penalty=1.08, eos_ids=None):
385
+ def generate_stream(self, req_id, prompt_ids, max_new_tokens=384, temperature=0.6, top_p=0.9, repetition_penalty=1.08, eos_ids=None, load_ms=0):
327
386
  eos_set = set(eos_ids or [151645, 151643])
328
387
  kv_cache = [None] * self.num_layers
329
388
  seen_tokens = list(prompt_ids)
389
+ dev = self.embed_tokens.device
330
390
 
331
- inp = torch.tensor([prompt_ids], dtype=torch.long)
391
+ inp = torch.tensor([prompt_ids], dtype=torch.long, device=dev)
332
392
  logits = self.forward_step(inp, kv_cache, 0)
333
393
  cur_pos = len(prompt_ids)
334
394
 
@@ -339,16 +399,22 @@ class LocalCausalLM:
339
399
  seen_tokens.append(next_token)
340
400
  print(json.dumps({"id": req_id, "event": "token", "token": next_token}), flush=True)
341
401
 
342
- inp_next = torch.tensor([[next_token]], dtype=torch.long)
402
+ inp_next = torch.tensor([[next_token]], dtype=torch.long, device=dev)
343
403
  logits = self.forward_step(inp_next, kv_cache, cur_pos)
344
404
  cur_pos += 1
345
405
 
346
- print(json.dumps({"id": req_id, "event": "done", "generated": cur_pos - len(prompt_ids)}), flush=True)
406
+ print(json.dumps({
407
+ "id": req_id,
408
+ "event": "done",
409
+ "generated": cur_pos - len(prompt_ids),
410
+ "device": _describe_torch_device(self.device),
411
+ "loadMs": int(load_ms or 0),
412
+ }), flush=True)
347
413
 
348
414
  def _sample(self, logits, seen_tokens, temperature, top_p, repetition_penalty):
349
415
  logits_f = logits.to(torch.float32).clone()
350
416
  if repetition_penalty and repetition_penalty != 1.0 and seen_tokens:
351
- uniq = torch.tensor(list(set(seen_tokens[-128:])), dtype=torch.long)
417
+ uniq = torch.tensor(list(set(seen_tokens[-128:])), dtype=torch.long, device=logits_f.device)
352
418
  vals = logits_f[uniq]
353
419
  logits_f[uniq] = torch.where(vals < 0, vals * repetition_penalty, vals / repetition_penalty)
354
420
 
@@ -1111,6 +1177,71 @@ def _call_tts_gen(fn, max_new_tokens, **kwargs):
1111
1177
  return fn(**kwargs)
1112
1178
 
1113
1179
 
1180
+ def _move_qwen_tts_vocoder_to_cpu(mdl):
1181
+ """Переносит декодер вокодера `speech_tokenizer` на CPU один раз при загрузке модели на GPU `cuda:0`.
1182
+
1183
+ Убирает сотни мелких перебросов `cuda:0 ↔ cpu` внутри `_install_rocm_miopen_fallback` для каждой
1184
+ отдельной Conv1d/ConvTranspose1d свёртки: коды 12 Гц кадров один раз уходят в Unified Memory на CPU
1185
+ и целиком декодируются в волну.
1186
+ """
1187
+ st = getattr(getattr(mdl, "model", None), "speech_tokenizer", None) or getattr(mdl, "speech_tokenizer", None)
1188
+ if st is None or getattr(st, "_work_cpu_vocoder_patched", False):
1189
+ return False
1190
+ inner = getattr(st, "model", None) or st
1191
+ decoder = getattr(inner, "decoder", None)
1192
+
1193
+ def _to_cpu_arg(v):
1194
+ if HAS_TORCH and torch is not None and isinstance(v, torch.Tensor):
1195
+ return v.detach().to("cpu")
1196
+ if isinstance(v, list):
1197
+ return [_to_cpu_arg(x) for x in v]
1198
+ if isinstance(v, tuple):
1199
+ return tuple(_to_cpu_arg(x) for x in v)
1200
+ if isinstance(v, dict):
1201
+ return {k: _to_cpu_arg(val) for k, val in v.items()}
1202
+ return v
1203
+
1204
+ if decoder is not None and callable(getattr(decoder, "forward", None)) and hasattr(decoder, "to"):
1205
+ try:
1206
+ cpu_dt = torch.float32 if (HAS_TORCH and torch is not None) else "float32"
1207
+ decoder.to(device="cpu", dtype=cpu_dt)
1208
+ orig_fwd = decoder.forward
1209
+
1210
+ def _cpu_decoder_fwd(*args, **kwargs):
1211
+ return orig_fwd(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1212
+
1213
+ decoder.forward = _cpu_decoder_fwd
1214
+ st._work_cpu_vocoder_patched = True
1215
+ return True
1216
+ except Exception:
1217
+ pass
1218
+
1219
+ dec = getattr(st, "decode", None)
1220
+ if not callable(dec):
1221
+ return False
1222
+ try:
1223
+ if hasattr(inner, "to"):
1224
+ cpu_dt = torch.float32 if (HAS_TORCH and torch is not None) else "float32"
1225
+ inner.to(device="cpu", dtype=cpu_dt)
1226
+ except Exception:
1227
+ return False
1228
+
1229
+ orig_dec = dec
1230
+
1231
+ def _cpu_decode(*args, **kwargs):
1232
+ return orig_dec(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1233
+
1234
+ try:
1235
+ st.decode = _cpu_decode
1236
+ orig_enc = getattr(st, "encode", None)
1237
+ if callable(orig_enc):
1238
+ st.encode = lambda *args, **kwargs: orig_enc(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1239
+ st._work_cpu_vocoder_patched = True
1240
+ return True
1241
+ except Exception:
1242
+ return False
1243
+
1244
+
1114
1245
  def _load_qwen_tts_model(weights_dir):
1115
1246
  from qwen_tts import Qwen3TTSModel
1116
1247
  device, dtype = _best_device_and_dtype()
@@ -1131,6 +1262,8 @@ def _load_qwen_tts_model(weights_dir):
1131
1262
  except Exception:
1132
1263
  mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=dev, dtype=dt)
1133
1264
  _install_fast_qwen_tts_code_predictor(mdl)
1265
+ if str(dev).startswith("cuda"):
1266
+ _move_qwen_tts_vocoder_to_cpu(mdl)
1134
1267
  mdl._work_device = dev
1135
1268
  return mdl
1136
1269
  except Exception as e:
@@ -1196,14 +1329,14 @@ def handle_tts(req, cache):
1196
1329
  "language": language,
1197
1330
  "speaker": _resolve_tts_speaker(mdl, req.get("voice")),
1198
1331
  }
1199
- if instructions:
1332
+ if instructions and "0.6b" not in weights_dir.lower():
1200
1333
  kwargs["instruct"] = instructions
1201
1334
  instruct_used = instructions
1202
1335
  try:
1203
1336
  wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
1204
1337
  except Exception as e:
1205
1338
  # CustomVoice 0.6B не принимает instruct — повторяем без него.
1206
- if "instruct" in kwargs and "instruct" in str(e).lower():
1339
+ if "instruct" in kwargs and ("instruct" in str(e).lower() or "0.6b" in weights_dir.lower()):
1207
1340
  kwargs.pop("instruct")
1208
1341
  instruct_used = ""
1209
1342
  wavs, sr = _call_tts_gen(mdl.generate_custom_voice, max_new_tokens, **kwargs)
@@ -1351,9 +1484,155 @@ def handle_stt(req, cache):
1351
1484
  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}
1352
1485
 
1353
1486
 
1487
+ def _get_free_ram_gb():
1488
+ """Кроссплатформенно определить объём свободной оперативной памяти в ГБ."""
1489
+ try:
1490
+ if sys.platform == "win32":
1491
+ class _MEMORYSTATUSEX(ctypes.Structure):
1492
+ _fields_ = [
1493
+ ("dwLength", ctypes.c_ulong),
1494
+ ("dwMemoryLoad", ctypes.c_ulong),
1495
+ ("ullTotalPhys", ctypes.c_ulonglong),
1496
+ ("ullAvailPhys", ctypes.c_ulonglong),
1497
+ ("ullTotalPageFile", ctypes.c_ulonglong),
1498
+ ("ullAvailPageFile", ctypes.c_ulonglong),
1499
+ ("ullTotalVirtual", ctypes.c_ulonglong),
1500
+ ("ullAvailVirtual", ctypes.c_ulonglong),
1501
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
1502
+ ]
1503
+ st = _MEMORYSTATUSEX()
1504
+ st.dwLength = ctypes.sizeof(_MEMORYSTATUSEX)
1505
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)):
1506
+ return float(st.ullAvailPhys) / (1024.0 ** 3)
1507
+ elif os.path.isfile("/proc/meminfo"):
1508
+ with open("/proc/meminfo", "r", encoding="utf-8") as f:
1509
+ for line in f:
1510
+ if line.startswith("MemAvailable:"):
1511
+ kb = float(line.split()[1])
1512
+ return kb / (1024.0 ** 2)
1513
+ except Exception:
1514
+ pass
1515
+ return None
1516
+
1517
+
1518
+ def _release_cached_item(obj):
1519
+ try:
1520
+ if isinstance(obj, tuple) and len(obj) >= 1 and hasattr(obj[0], "to"):
1521
+ try:
1522
+ obj[0].to("cpu")
1523
+ except Exception:
1524
+ pass
1525
+ elif hasattr(obj, "to"):
1526
+ try:
1527
+ obj.to("cpu")
1528
+ except Exception:
1529
+ pass
1530
+ except Exception:
1531
+ pass
1532
+
1533
+
1534
+ def _evict_memory_if_needed(
1535
+ mod_cache,
1536
+ mod_last_used,
1537
+ models,
1538
+ llm_last_used,
1539
+ cache_lock=None,
1540
+ keep_mod_key=None,
1541
+ keep_llm_key=None,
1542
+ now_ts=None,
1543
+ ):
1544
+ """Умная очистка памяти:
1545
+ - Тяжёлую диффузию (`image`, напр. Z-Image-Turbo) выгружаем через `WORK_IMAGE_IDLE_SEC` (10 мин)
1546
+ или при падении свободной RAM ниже `WORK_MIN_FREE_RAM_GB` (20 ГБ).
1547
+ - Лёгкие модели (embed, rerank, tts, stt, 0.6B/4B) держим постоянно горячими,
1548
+ выгружая по LRU только при критической нехватке RAM (`< WORK_CRIT_FREE_RAM_GB`, 10 ГБ).
1549
+ """
1550
+ now = float(now_ts if now_ts is not None else time.time())
1551
+ image_idle_sec = float(os.environ.get("WORK_IMAGE_IDLE_SEC", "600"))
1552
+ min_free_gb = float(os.environ.get("WORK_MIN_FREE_RAM_GB", "20"))
1553
+ crit_free_gb = float(os.environ.get("WORK_CRIT_FREE_RAM_GB", "10"))
1554
+ free_gb = _get_free_ram_gb()
1555
+ evicted = []
1556
+
1557
+ def _do():
1558
+ low_mem = free_gb is not None and free_gb < min_free_gb
1559
+ for k in list(mod_cache.keys()):
1560
+ if not (isinstance(k, tuple) and len(k) >= 1 and k[0] == "image"):
1561
+ continue
1562
+ if k == keep_mod_key:
1563
+ continue
1564
+ idle = now - float(mod_last_used.get(k, now))
1565
+ if idle >= image_idle_sec or low_mem:
1566
+ obj = mod_cache.pop(k, None)
1567
+ mod_last_used.pop(k, None)
1568
+ _release_cached_item(obj)
1569
+ evicted.append(k)
1570
+
1571
+ if free_gb is not None and free_gb < crit_free_gb:
1572
+ # Критическая нехватка памяти — выгружаем самую давно неиспользуемую неактивную модель
1573
+ candidates = []
1574
+ for k in list(mod_cache.keys()):
1575
+ if k != keep_mod_key:
1576
+ candidates.append(("mod", k, float(mod_last_used.get(k, 0.0))))
1577
+ for k in list(models.keys()):
1578
+ if k != keep_llm_key:
1579
+ candidates.append(("llm", k, float(llm_last_used.get(k, 0.0))))
1580
+ candidates.sort(key=lambda item: item[2])
1581
+ for kind, k, _ in candidates[:2]:
1582
+ if kind == "mod":
1583
+ obj = mod_cache.pop(k, None)
1584
+ mod_last_used.pop(k, None)
1585
+ _release_cached_item(obj)
1586
+ evicted.append(k)
1587
+ else:
1588
+ obj = models.pop(k, None)
1589
+ llm_last_used.pop(k, None)
1590
+ _release_cached_item(obj)
1591
+ evicted.append(("llm", k))
1592
+
1593
+ if cache_lock is not None:
1594
+ with cache_lock:
1595
+ _do()
1596
+ else:
1597
+ _do()
1598
+
1599
+ if evicted:
1600
+ try:
1601
+ gc.collect()
1602
+ except Exception:
1603
+ pass
1604
+ if HAS_TORCH and torch is not None and torch.cuda.is_available():
1605
+ try:
1606
+ torch.cuda.empty_cache()
1607
+ except Exception:
1608
+ pass
1609
+ return evicted
1610
+
1611
+
1354
1612
  def main():
1355
1613
  models = {}
1356
1614
  mod_cache = {}
1615
+ mod_last_used = {}
1616
+ llm_last_used = {}
1617
+ cache_lock = threading.Lock()
1618
+ idle_timers = {"image": None}
1619
+
1620
+ def _schedule_image_idle_eviction():
1621
+ try:
1622
+ prev = idle_timers.get("image")
1623
+ if prev is not None:
1624
+ prev.cancel()
1625
+ delay = max(5.0, float(os.environ.get("WORK_IMAGE_IDLE_SEC", "600")) + 1.0)
1626
+ t = threading.Timer(
1627
+ delay,
1628
+ lambda: _evict_memory_if_needed(mod_cache, mod_last_used, models, llm_last_used, cache_lock=cache_lock),
1629
+ )
1630
+ t.daemon = True
1631
+ t.start()
1632
+ idle_timers["image"] = t
1633
+ except Exception:
1634
+ pass
1635
+
1357
1636
  print(json.dumps({"event": "ready"}), flush=True)
1358
1637
 
1359
1638
  for line in sys.stdin:
@@ -1388,6 +1667,11 @@ def main():
1388
1667
  continue
1389
1668
  if op in ("embed", "rerank", "image", "tts", "stt"):
1390
1669
  t0 = time.time()
1670
+ mod_key = (op, str(req.get("weightsDir") or ""))
1671
+ _evict_memory_if_needed(
1672
+ mod_cache, mod_last_used, models, llm_last_used,
1673
+ cache_lock=cache_lock, keep_mod_key=mod_key,
1674
+ )
1391
1675
  fn = {
1392
1676
  "embed": handle_embed,
1393
1677
  "rerank": handle_rerank,
@@ -1395,7 +1679,11 @@ def main():
1395
1679
  "tts": handle_tts,
1396
1680
  "stt": handle_stt,
1397
1681
  }[op]
1398
- res = fn(req, mod_cache)
1682
+ with cache_lock:
1683
+ res = fn(req, mod_cache)
1684
+ mod_last_used[mod_key] = time.time()
1685
+ if op == "image":
1686
+ _schedule_image_idle_eviction()
1399
1687
  if "durationMs" not in res:
1400
1688
  res["durationMs"] = int((time.time() - t0) * 1000)
1401
1689
  print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
@@ -1407,15 +1695,26 @@ def main():
1407
1695
  temperature = float(req.get("temperature", 0.6))
1408
1696
  eos_ids = req.get("eosTokenIds", [151645, 151643])
1409
1697
 
1410
- if weights_dir not in models:
1411
- models[weights_dir] = LocalCausalLM(weights_dir)
1412
-
1413
- models[weights_dir].generate_stream(
1698
+ _evict_memory_if_needed(
1699
+ mod_cache, mod_last_used, models, llm_last_used,
1700
+ cache_lock=cache_lock, keep_llm_key=weights_dir,
1701
+ )
1702
+ load_ms = 0
1703
+ with cache_lock:
1704
+ if weights_dir not in models:
1705
+ t_l0 = time.time()
1706
+ models[weights_dir] = LocalCausalLM(weights_dir)
1707
+ load_ms = int((time.time() - t_l0) * 1000)
1708
+ llm_last_used[weights_dir] = time.time()
1709
+ mdl_ref = models[weights_dir]
1710
+
1711
+ mdl_ref.generate_stream(
1414
1712
  req_id=req_id,
1415
1713
  prompt_ids=prompt_ids,
1416
1714
  max_new_tokens=max_new_tokens,
1417
1715
  temperature=temperature,
1418
1716
  eos_ids=eos_ids,
1717
+ load_ms=load_ms,
1419
1718
  )
1420
1719
  except Exception as e:
1421
1720
  err_str = str(e)