odant-work 1.0.49 → 1.0.51

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.
@@ -55,6 +55,7 @@ import {
55
55
  getPythonProvisionState,
56
56
  ensurePythonForModality,
57
57
  packagesForModality,
58
+ collectPackagesForAllInstalledModelsSync,
58
59
  isStrixHaloGfx1151Host,
59
60
  hasRocmGfx1151InVenvSync,
60
61
  AMD_ROCM_GFX1151_WHL_INDEX,
@@ -175,6 +176,7 @@ export {
175
176
  getPythonProvisionState,
176
177
  ensurePythonForModality,
177
178
  packagesForModality,
179
+ collectPackagesForAllInstalledModelsSync,
178
180
  isStrixHaloGfx1151Host,
179
181
  hasRocmGfx1151InVenvSync,
180
182
  AMD_ROCM_GFX1151_WHL_INDEX,
@@ -539,9 +541,27 @@ async function runSingleModelSmokeTest(ai, p = {}) {
539
541
  summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
540
542
  };
541
543
  }
542
- 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
543
546
  ? p.messages
544
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
+ }
545
565
  const isHalo = ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen';
546
566
  const haloUrl = ai?.baseUrl || ai?.DATA?.baseUrl || HALOGEN_DEFAULT_BASE_URL;
547
567
  // Холодный запуск bubo.exe (загрузка 116 ГБ весов) не должен выглядеть как медленная генерация:
@@ -557,7 +577,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
557
577
  }
558
578
  const metricsBefore = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
559
579
  const genT0 = Date.now();
560
- const maxOut = Number(p.maxOutput || p.maxTokens) || 256;
580
+ const maxOut = prefillBenchmark ? 48 : (Number(p.maxOutput || p.maxTokens) || 256);
561
581
  const chatOpts = {
562
582
  messages,
563
583
  maxOutput: maxOut,
@@ -577,10 +597,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
577
597
  const metricsDelta = isHalo ? computeHalogenMetricsDelta(metricsBefore, metricsAfter) : null;
578
598
 
579
599
  const ttftMs = Number(usage?.ttftMs) || 0;
600
+ const loadMs = Number(usage?.loadMs) || 0;
601
+ const device = String(usage?.device || '');
580
602
  const clientTokPerSec = Number(usage?.tokPerSec) || 0;
581
603
  const serverTokPerSec = Number(metricsDelta?.serverDecodeTokPerSec) || 0;
582
604
  const tokPerSec = serverTokPerSec > 0 ? serverTokPerSec : clientTokPerSec;
583
- 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;
584
609
  const mtpAcceptPct = metricsDelta?.mtpAcceptPct ?? null;
585
610
  const mtpTokensPerStep = metricsDelta?.mtpTokensPerStep ?? null;
586
611
 
@@ -588,23 +613,29 @@ async function runSingleModelSmokeTest(ai, p = {}) {
588
613
  ok: true,
589
614
  modality: 'llm',
590
615
  text: text.trim(),
616
+ device,
617
+ loadMs,
591
618
  durationMs,
592
619
  ttftMs,
593
620
  tokPerSec,
594
621
  clientTokPerSec,
595
622
  serverDecodeTokPerSec: serverTokPerSec,
596
623
  promptTokPerSec,
624
+ prefillBenchmark,
597
625
  mtpAcceptPct,
598
626
  mtpTokensPerStep,
599
627
  usage,
600
628
  engineStartMs,
601
629
  totalMs: durationMs + engineStartMs,
602
630
  summary: [
631
+ device ? `${device}` : '',
603
632
  tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
633
+ promptTokPerSec > 0 && prefillBenchmark ? `Prefill ${promptTokPerSec} tok/s` : '',
604
634
  ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
605
635
  mtpAcceptPct !== null
606
636
  ? `MTP ${mtpAcceptPct}%${mtpTokensPerStep ? ` (${mtpTokensPerStep} ток/шаг)` : ''}`
607
637
  : '',
638
+ loadMs > 500 ? `загрузка ${(loadMs / 1000).toFixed(1)} с` : '',
608
639
  engineStartMs > 500 ? `старт движка ${(engineStartMs / 1000).toFixed(1)} с` : '',
609
640
  ].filter(Boolean).join(' · '),
610
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
  };
@@ -1074,18 +1090,37 @@ function buildProxyEnv(rootDir = process.cwd()) {
1074
1090
  };
1075
1091
  }
1076
1092
 
1077
- function runSpawnCapture(cmd, args, timeoutMs = 900000, env = process.env) {
1093
+ function runSpawnCapture(cmd, args, timeoutMs = 900000, env = process.env, onLine = null) {
1078
1094
  return new Promise((resolve) => {
1079
1095
  const proc = spawn(cmd, args, { windowsHide: true, env, stdio: ['ignore', 'pipe', 'pipe'] });
1080
1096
  let out = '';
1081
1097
  let err = '';
1082
1098
  let timedOut = false;
1099
+ const emitChunk = (chunk) => {
1100
+ if (typeof onLine !== 'function')
1101
+ return;
1102
+ const lines = String(chunk || '').split(/[\r\n]+/);
1103
+ for (const line of lines) {
1104
+ const clean = line.replace(/\u001b\[[0-9;]*m/g, '').trim();
1105
+ if (clean) {
1106
+ try { onLine(clean); } catch { /* ignore */ }
1107
+ }
1108
+ }
1109
+ };
1083
1110
  const t = setTimeout(() => {
1084
1111
  timedOut = true;
1085
1112
  proc.kill();
1086
1113
  }, timeoutMs);
1087
- proc.stdout?.on('data', d => { out += String(d); if (out.length > 12000) out = out.slice(-12000); });
1088
- proc.stderr?.on('data', d => { err += String(d); if (err.length > 12000) err = err.slice(-12000); });
1114
+ proc.stdout?.on('data', d => {
1115
+ out += String(d);
1116
+ if (out.length > 12000) out = out.slice(-12000);
1117
+ emitChunk(d);
1118
+ });
1119
+ proc.stderr?.on('data', d => {
1120
+ err += String(d);
1121
+ if (err.length > 12000) err = err.slice(-12000);
1122
+ emitChunk(d);
1123
+ });
1089
1124
  proc.on('error', e => { clearTimeout(t); resolve({ ok: false, code: -1, out, err: String(e?.message || e) }); });
1090
1125
  proc.on('close', code => {
1091
1126
  clearTimeout(t);
@@ -1223,6 +1258,78 @@ export function getPythonProvisionState() {
1223
1258
  return { ..._pythonProvisionState };
1224
1259
  }
1225
1260
 
1261
+ function summarizeInstallActivityLine(line = '') {
1262
+ const s = String(line || '').trim();
1263
+ if (!s)
1264
+ return '';
1265
+ let m = /^(?:Downloading|Getting|Fetching)\s+([a-zA-Z0-9_.-]+)(?:\s*\(([^)]+)\))?/i.exec(s);
1266
+ if (m)
1267
+ return `скачивание ${m[1]}${m[2] ? ' (' + m[2] + ')' : ''}`;
1268
+ m = /^(?:Prepared|Building)\s+(.+)$/i.exec(s);
1269
+ if (m)
1270
+ return `распаковка (${m[1]})`;
1271
+ m = /^(?:Installed|Installing)\s+(.+)$/i.exec(s);
1272
+ if (m)
1273
+ return `установка (${m[1]})`;
1274
+ m = /^Resolved\s+(.+)$/i.exec(s);
1275
+ if (m)
1276
+ return `проверены зависимости (${m[1]})`;
1277
+ m = /^Collecting\s+([a-zA-Z0-9_.-]+)/i.exec(s);
1278
+ if (m)
1279
+ return `загрузка ${m[1]}`;
1280
+ return '';
1281
+ }
1282
+
1283
+ /**
1284
+ * Собрать полный набор Python-пакетов сразу для ВСЕХ уже скачанных локальных моделей в `MODELS/Local/*`,
1285
+ * чтобы в продакшене первичная подготовка среды ставила всё за один проход без повторных пауз при переключении моделей.
1286
+ */
1287
+ export function collectPackagesForAllInstalledModelsSync(rootDir = process.cwd()) {
1288
+ const out = new Set();
1289
+ const localDir = path.join(rootDir, 'MODELS', 'Local');
1290
+ if (!fs.existsSync(localDir))
1291
+ return [];
1292
+ try {
1293
+ for (const ent of fs.readdirSync(localDir, { withFileTypes: true })) {
1294
+ if (!ent.isDirectory() || ent.name.startsWith('$') || ent.name.startsWith('#') || ent.name.startsWith('.'))
1295
+ continue;
1296
+ const aiDir = path.join(localDir, ent.name, '$ai');
1297
+ const weightsDir = path.join(aiDir, '#weights');
1298
+ if (!fs.existsSync(weightsDir))
1299
+ continue;
1300
+ const wInsp = inspectWeightsDirectorySync(weightsDir);
1301
+ if (!wInsp.hasSafetensors && !hasOnnxModelSync(weightsDir))
1302
+ continue;
1303
+ let mod = '';
1304
+ const classFile = path.join(aiDir, 'class.js');
1305
+ if (fs.existsSync(classFile)) {
1306
+ try {
1307
+ const raw = fs.readFileSync(classFile, 'utf-8');
1308
+ if (/"tts"/i.test(raw)) mod = 'tts';
1309
+ else if (/"(stt|asr)"/i.test(raw)) mod = 'stt';
1310
+ else if (/"(image|text-to-image)"/i.test(raw)) mod = 'image';
1311
+ else if (/"rerank"/i.test(raw)) mod = 'rerank';
1312
+ else if (/"(embeddings|embed)"/i.test(raw)) mod = 'embed';
1313
+ }
1314
+ catch { /* ignore */ }
1315
+ }
1316
+ if (!mod) {
1317
+ const low = ent.name.toLowerCase();
1318
+ if (low.includes('tts')) mod = 'tts';
1319
+ else if (low.includes('asr') || low.includes('whisper')) mod = 'stt';
1320
+ else if (low.includes('image') || low.includes('flux') || low.includes('sd')) mod = 'image';
1321
+ else if (low.includes('rerank')) mod = 'rerank';
1322
+ else if (low.includes('bge') || low.includes('embed')) mod = 'embed';
1323
+ else mod = 'llm';
1324
+ }
1325
+ for (const pkg of packagesForModality(mod, weightsDir))
1326
+ out.add(pkg);
1327
+ }
1328
+ }
1329
+ catch { /* ignore */ }
1330
+ return [...out];
1331
+ }
1332
+
1226
1333
  export async function installLocalPythonDeps(packages = [], { rootDir = process.cwd(), upgradeRocmGfx1151 = false } = {}) {
1227
1334
  let clean = [...new Set((Array.isArray(packages) ? packages : [packages])
1228
1335
  .map(s => String(s || '').trim().toLowerCase())
@@ -1310,22 +1417,42 @@ export async function installLocalPythonDeps(packages = [], { rootDir = process.
1310
1417
  try { fs.writeFileSync(ovrFile, overrides.join('\n') + '\n', 'utf-8'); }
1311
1418
  catch { /* ignore */ }
1312
1419
 
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: '',
1420
+ const baseStage = useRocm
1421
+ ? `Установка GPU-ускорения AMD ROCm (gfx1151 iGPU) и пакетов (${clean.join(', ')})`
1422
+ : `Автоматическая установка пакетов (${clean.join(', ')})`;
1423
+ const attemptStart = Date.now();
1424
+ let currentDetail = 'подключение к репозиторию пакетов…';
1425
+ const updateLiveStage = () => {
1426
+ const elapsedSec = Math.max(1, Math.round((Date.now() - attemptStart) / 1000));
1427
+ _pythonProvisionState = {
1428
+ ..._pythonProvisionState,
1429
+ active: true,
1430
+ stage: `${baseStage} — ${currentDetail} (⏱ ${elapsedSec} с)`,
1431
+ packages: clean,
1432
+ };
1433
+ };
1434
+ updateLiveStage();
1435
+ const liveTimer = setInterval(updateLiveStage, 1000);
1436
+ liveTimer.unref?.();
1437
+ const onLine = (line) => {
1438
+ const summary = summarizeInstallActivityLine(line);
1439
+ if (summary) {
1440
+ currentDetail = summary;
1441
+ updateLiveStage();
1442
+ }
1321
1443
  };
1322
1444
 
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);
1445
+ try {
1446
+ if (uv && fs.existsSync(venvPy)) {
1447
+ const ovrArgs = fs.existsSync(ovrFile) ? ['--override', ovrFile] : [];
1448
+ return await runSpawnCapture(uv, ['pip', 'install', '--python', venvPy, '--upgrade', '--verbose', ...ovrArgs, ...indexArgs, ...installList], 900000, proxyEnv, onLine);
1449
+ }
1450
+ const pipIndexArgs = useRocm ? ['--extra-index-url', AMD_ROCM_GFX1151_WHL_INDEX] : indexArgs;
1451
+ return await runSpawnCapture(py.cmd, [...py.args, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'off', ...pipIndexArgs, ...installList], 900000, proxyEnv, onLine);
1452
+ }
1453
+ finally {
1454
+ clearInterval(liveTimer);
1326
1455
  }
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);
1329
1456
  };
1330
1457
 
1331
1458
  let res = await runInstallAttempt(wantRocmGfx1151);
@@ -1366,8 +1493,12 @@ export async function ensurePythonForModality(modality = 'llm', { weightsDir = '
1366
1493
  if (_autoProvisionOverride)
1367
1494
  return _autoProvisionOverride(modality, { weightsDir, extraPackages, upgradeRocmGfx1151, rootDir });
1368
1495
 
1496
+ const allInstalledPkgs = (!process.env.NODE_TEST_CONTEXT && !_autoProvisionOverride)
1497
+ ? collectPackagesForAllInstalledModelsSync(rootDir)
1498
+ : [];
1369
1499
  const targetPkgs = [...new Set([
1370
1500
  ...packagesForModality(modality, weightsDir),
1501
+ ...allInstalledPkgs,
1371
1502
  ...(Array.isArray(extraPackages) ? extraPackages : []),
1372
1503
  ])];
1373
1504