@simplexai/localmodels-darwin-arm64 0.1.0-dev.48 → 0.1.0-dev.50

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.
Files changed (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -9,6 +9,7 @@ const EXACT_ZH = {
9
9
  "give two of params, format and file size": "请提供总参数、量化格式和权重文件大小中的至少两项",
10
10
  "context must be at least 1 token": "上下文长度至少为 1 token",
11
11
  "slots must be at least 1": "并发槽位数至少为 1",
12
+ "exl bits per weight must be between 1 and 16": "EXL3 自定义位数需在 1–16 bpw 之间",
12
13
  };
13
14
 
14
15
  function zhMsg(msg) {
@@ -46,6 +47,13 @@ if (typeof document !== "undefined") (() => {
46
47
  const GiB = 1073741824;
47
48
  const $ = (id) => document.getElementById(id);
48
49
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
50
+ const setClass = (el, cls, on) => { if (el?.classList) el.classList[on ? "add" : "remove"](cls); };
51
+ const announce = (msg) => {
52
+ const live = $("live-status");
53
+ if (!live) return;
54
+ live.textContent = "";
55
+ live.textContent = msg;
56
+ };
49
57
 
50
58
  const TIER_ZH = {
51
59
  phone: ["手机", "8–16 GB;安卓单个 App 上限 5–10 GiB"],
@@ -70,6 +78,38 @@ if (typeof document !== "undefined") (() => {
70
78
  float: "浮点原版", gguf: "GGUF(llama.cpp)", mlx: "MLX(Apple)", awq: "AWQ", gptq: "GPTQ",
71
79
  fp8: "FP8", nvfp4: "NVFP4", mxfp4: "MXFP4", exl: "EXL2 / EXL3", bnb: "bitsandbytes",
72
80
  };
81
+ const SUPPORT_ZH = {
82
+ native: ["原生", "该设备支持此格式的原生计算 kernel,可直接运行"],
83
+ fallback: ["回退", "可运行但走回退 / weight-only 路径(如 Ampere 卡运行 FP8 Marlin)"],
84
+ convert: ["需转换", "该设备不直接支持此格式,按同等体积换算为 GGUF / MLX 后估算"],
85
+ };
86
+ const BASIS_ZH = {
87
+ file: ["实测文件", "llama.cpp README 中 Llama-3.1-8B 整文件实测平均 bpw(含高精输出层与嵌入)"],
88
+ block: ["块公式", "按 ggml / 分组块结构推算,整文件通常高 0.2–0.8 bpw"],
89
+ derived: ["推导", "按张量量化结构加 16-bit 嵌入与输出头,针对 30B 级模型推算"],
90
+ exact: ["精确", "未量化浮点格式的名义精确位宽"],
91
+ target: ["目标值", "可变码率格式的目标平均位数,不含 16-bit 嵌入层"],
92
+ };
93
+ const FMT_NOTE_ZH = {
94
+ "the usual released checkpoint": "主流开源发布的原始权重格式",
95
+ "E4M3 + fp32 block scales, 16-bit embeddings; Ada/Hopper+": "E4M3 + fp32 分块缩放,16-bit 嵌入;需 Ada / Hopper 及以上",
96
+ "32 int8 + f16 scale per block": "每块 32 个 int8 + f16 缩放因子",
97
+ "group 64, scale + bias; embeddings quantized too": "每组 64 权重,含缩放与偏置;嵌入层也量化",
98
+ "the common default": "最常用的默认平衡量化",
99
+ "also the usual QAT release format": "也是常见的量化感知训练(QAT)发布格式",
100
+ "FP4 + E4M3 scale per 16, 16-bit embeddings; Blackwell": "每 16 权重配 E4M3 缩放,16-bit 嵌入;Blackwell 原生",
101
+ "int4 g128 is 4.16; 16-bit embeddings: 8B 5.7, 70B 4.5": "int4 (g128) 纯块 4.16 bpw;含 16-bit 嵌入:8B 约 5.7、70B 约 4.5",
102
+ "bitsandbytes 4-bit 4.5 (4.127 double-quant), bf16 embeddings": "bitsandbytes 4-bit 约 4.5(双重量化 4.127),bf16 嵌入",
103
+ "gpt-oss-120b: MXFP4 experts, Q8_0 elsewhere": "gpt-oss-120b 实测:专家层 MXFP4,其余层 Q8_0",
104
+ "IQ1/IQ2 keep the output at Q5_K": "IQ1 / IQ2 会将输出层保留在 Q5_K",
105
+ "ExLlama: embeddings stay 16-bit": "ExLlama 可变码率,嵌入层保留 16-bit",
106
+ };
107
+ const PRESET_GROUPS = [
108
+ { id: "light", label: "轻量 3–8B", match: (p) => p.params < 15 },
109
+ { id: "main", label: "主力 20–70B", match: (p) => p.params >= 15 && p.params < 100 },
110
+ { id: "mega", label: "超大 MoE 120B+", match: (p) => p.params >= 100 },
111
+ ];
112
+ const DEVICE_META = Object.fromEntries(D.devices.map((x) => [x.id, x]));
73
113
  const CONTEXTS = [4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576];
74
114
 
75
115
  // Public model shapes from sizecalc.EXAMPLES; the CLI fills catalog sizes from catalog.json.
@@ -101,9 +141,16 @@ if (typeof document !== "undefined") (() => {
101
141
  .map((f) => `<option value="${esc(f.name)}">${esc(f.name)} · ${f.bits} bpw</option>`).join("")}</optgroup>`)
102
142
  .join("") + `<optgroup label="其它"><option value="custom-exl">EXL3 / EXL2,自定义 bpw</option><option value="custom">其它,自定义 bpw</option></optgroup>`;
103
143
  sel.value = "Q4_K_M";
104
- $("presets").innerHTML = PRESETS.map((p) => `<button type="button" data-id="${p.id}" aria-pressed="false">${esc(p.name)}</button>`).join("");
144
+ $("presets").innerHTML = PRESET_GROUPS.map((grp) => {
145
+ const items = PRESETS.filter(grp.match);
146
+ if (!items.length) return "";
147
+ return `<div class="preset-group" data-group="${grp.id}">
148
+ <span class="preset-glabel">${esc(grp.label)}</span>
149
+ <div class="preset-chips">${items.map((p) => `<button type="button" data-id="${p.id}" aria-pressed="false">${esc(p.name)}</button>`).join("")}</div>
150
+ </div>`;
151
+ }).join("");
105
152
  $("presets").addEventListener("click", (e) => {
106
- const b = e.target.closest("button");
153
+ const b = e.target.closest?.("button");
107
154
  if (b) applyPreset(PRESETS.find((p) => p.id === b.dataset.id));
108
155
  });
109
156
  }
@@ -141,18 +188,21 @@ if (typeof document !== "undefined") (() => {
141
188
  function readInputs() {
142
189
  const moe = $("k-moe").checked;
143
190
  const quant = $("quant").value;
144
- const bits = String(num("custom-bits") ?? 4);
191
+ const customBits = num("custom-bits");
192
+ const bits = String(customBits ?? 4);
145
193
  const fmt = quant === "custom" ? bits : quant === "custom-exl" ? `EXL3-${bits}` : quant;
146
194
  const params = num("params");
147
195
  const file = num("filesize");
148
196
  const inferParams = file != null && $("i-params").checked;
197
+ const inferBits = file != null && !inferParams && !fromPreset.filesize;
149
198
  const kv = num("kvpt");
150
199
  return {
151
- moe, quant, fmt,
200
+ moe, quant, customBits, fmt,
152
201
  params: params != null ? Math.round(params * 1e9) : null,
153
202
  active: moe && num("active") != null ? Math.round(num("active") * 1e9) : null,
154
203
  fileBytes: file != null ? Math.round(file * 1e9) : null,
155
204
  inferParams,
205
+ inferBits,
156
206
  attention: $("attention").value,
157
207
  kvPerToken: kv != null && kv > 0 ? Math.round(kv * 1024) : null,
158
208
  context: CONTEXTS[Number($("ctx").value)],
@@ -173,7 +223,17 @@ if (typeof document !== "undefined") (() => {
173
223
  // ── render ────────────────────────────────────────────────────────
174
224
  let selected = null;
175
225
  let last = null;
226
+ let lastInputs = null;
176
227
  let pinned = null;
228
+ let devFilter = "all";
229
+ let devQuery = "";
230
+
231
+ function ensureSelected(r) {
232
+ if (!selected || !r.devices.some((d) => d.device === selected)) {
233
+ const t = r.tiers.find((x) => x.verdict === "fits") || r.tiers.find((x) => x.verdict === "offload");
234
+ selected = t ? t.device : r.devices[r.devices.length - 1].device;
235
+ }
236
+ }
177
237
 
178
238
  function tierIndex(t) {
179
239
  const idx = D.tiers.findIndex(([id]) => id === t);
@@ -257,7 +317,8 @@ if (typeof document !== "undefined") (() => {
257
317
  <span class="delta-chip ${runCls}">运行:${esc(fmtDelta(dr, "GiB"))}</span>
258
318
  ${tierChip}
259
319
  ${decodeChip}
260
- </div>`;
320
+ </div>
321
+ <button type="button" class="compare-unpin" id="compare-unpin" data-action="unpin">× 取消对比</button>`;
261
322
  }
262
323
 
263
324
  function parseHashMap() {
@@ -306,7 +367,8 @@ if (typeof document !== "undefined") (() => {
306
367
  if (q === "custom" || q === "custom-exl") {
307
368
  $("quant").value = q;
308
369
  const b = Number(bitsRaw);
309
- if (bitsRaw != null && Number.isFinite(b) && b >= 1 && b <= 32) $("custom-bits").value = String(b);
370
+ const maxB = q === "custom-exl" ? 16 : 32;
371
+ if (bitsRaw != null && Number.isFinite(b) && b >= 1 && b <= maxB) $("custom-bits").value = String(b);
310
372
  return;
311
373
  }
312
374
  const upper = q.toUpperCase();
@@ -317,7 +379,7 @@ if (typeof document !== "undefined") (() => {
317
379
  }
318
380
  if (upper.startsWith("EXL2-") || upper.startsWith("EXL3-")) {
319
381
  const b = Number(q.slice(5));
320
- if (Number.isFinite(b) && b >= 1 && b <= 32) {
382
+ if (Number.isFinite(b) && b >= 1 && b <= 16) {
321
383
  $("quant").value = "custom-exl";
322
384
  $("custom-bits").value = String(b);
323
385
  }
@@ -330,8 +392,7 @@ if (typeof document !== "undefined") (() => {
330
392
  }
331
393
  }
332
394
 
333
- function syncHash(i) {
334
- if (typeof history === "undefined" || typeof history.replaceState !== "function") return;
395
+ function buildHash(i) {
335
396
  const pairs = [];
336
397
  const add = (key, val) => {
337
398
  if (val != null && String(val) !== "") {
@@ -340,40 +401,105 @@ if (typeof document !== "undefined") (() => {
340
401
  };
341
402
  if (presetId) add("preset", presetId);
342
403
  add("kind", i.moe ? "moe" : "dense");
343
- add("params", $("params").value.trim());
404
+ if (!i.inferParams) add("params", $("params").value.trim());
344
405
  if (i.moe) add("active", $("active").value.trim());
345
406
  add("att", i.attention);
346
407
  add("kvpt", $("kvpt").value.trim());
347
- add("quant", i.quant);
348
- if (i.quant.startsWith("custom")) add("bits", $("custom-bits").value.trim());
349
- add("file", $("filesize").value.trim());
350
- if ($("filesize").value.trim() !== "") add("infer", i.inferParams ? "params" : "bits");
408
+ if (!i.inferBits) {
409
+ add("quant", i.quant);
410
+ if (i.quant.startsWith("custom")) add("bits", $("custom-bits").value.trim());
411
+ }
412
+ const fileRaw = $("filesize").value.trim();
413
+ add("file", fileRaw);
414
+ if (fileRaw !== "") add("infer", i.inferParams ? "params" : "bits");
351
415
  add("ctx", i.context);
352
416
  add("slots", $("slots").value.trim());
353
417
  add("kv", i.kvType);
354
418
  add("ram", $("hostram").value.trim());
355
- const next = "#" + pairs.join("&");
419
+ return "#" + pairs.join("&");
420
+ }
421
+
422
+ function syncHash(i) {
423
+ if (typeof history === "undefined" || typeof history.replaceState !== "function") return;
424
+ const next = buildHash(i);
356
425
  if (typeof location === "undefined" || location.hash !== next) {
357
- history.replaceState(null, "", next);
426
+ try { history.replaceState(null, "", next); } catch { /* ignore file:// history restrictions */ }
358
427
  }
359
428
  }
360
429
 
430
+ function shareUrl() {
431
+ const hash = lastInputs ? buildHash(lastInputs) : (typeof location !== "undefined" && location.hash ? location.hash : "");
432
+ if (typeof location !== "undefined" && location.href) {
433
+ return location.href.split("#")[0] + hash;
434
+ }
435
+ return hash;
436
+ }
437
+
438
+ function clearFileSize(focusId) {
439
+ $("filesize").value = "";
440
+ fromPreset.filesize = false;
441
+ presetId = null;
442
+ $("i-bits").checked = true;
443
+ $("i-params").checked = false;
444
+ update();
445
+ if (focusId) $(focusId)?.focus?.();
446
+ }
447
+
448
+ function syncInferenceControls(i, hasFile) {
449
+ $("infer-seg").hidden = !hasFile;
450
+ const clearBtn = $("clear-file");
451
+ if (clearBtn) clearBtn.hidden = !hasFile;
452
+ $("active-field").hidden = !$("k-moe").checked;
453
+ const isCustomExl = i.quant === "custom-exl";
454
+ $("custom-field").hidden = i.inferBits || !i.quant.startsWith("custom");
455
+ const customBitsEl = $("custom-bits");
456
+ if (customBitsEl) {
457
+ const maxB = isCustomExl ? "16" : "32";
458
+ customBitsEl.max = maxB;
459
+ customBitsEl.setAttribute("max", maxB);
460
+ }
461
+ const customHint = $("custom-bits-hint");
462
+ if (customHint) customHint.textContent = isCustomExl ? "1–16 bpw" : "1–32 bpw";
463
+
464
+ const paramsEl = $("params");
465
+ paramsEl.disabled = i.inferParams;
466
+ paramsEl.setAttribute("aria-disabled", String(i.inferParams));
467
+ setClass($("params-field"), "is-inferred", i.inferParams);
468
+ const paramsInf = $("params-inferred");
469
+ if (paramsInf) paramsInf.hidden = !i.inferParams;
470
+ if (i.inferParams && $("params-inferred-text")) $("params-inferred-text").textContent = "由文件大小反推";
471
+
472
+ const quantEl = $("quant");
473
+ quantEl.disabled = i.inferBits;
474
+ quantEl.setAttribute("aria-disabled", String(i.inferBits));
475
+ setClass($("quant-field"), "is-inferred", i.inferBits);
476
+ const quantInf = $("quant-inferred");
477
+ if (quantInf) quantInf.hidden = !i.inferBits;
478
+ if (i.inferBits && $("quant-inferred-text")) $("quant-inferred-text").textContent = "由文件大小反推";
479
+ }
480
+
361
481
  function update() {
362
482
  for (const b of $("presets").querySelectorAll("button")) b.setAttribute("aria-pressed", String(b.dataset.id === presetId));
363
- $("active-field").hidden = !$("k-moe").checked;
364
- $("custom-field").hidden = !$("quant").value.startsWith("custom");
365
- $("infer-seg").hidden = num("filesize") == null;
483
+ const hasFile = num("filesize") != null;
366
484
  const i = readInputs();
367
- $("ctx-val").textContent = `${ctxLabel(i.context)} tokens`;
485
+ syncInferenceControls(i, hasFile);
486
+ const ctxText = `${ctxLabel(i.context)} tokens`;
487
+ $("ctx-val").textContent = ctxText;
488
+ $("ctx").setAttribute("aria-valuetext", ctxText);
368
489
  const resultsEl = document.querySelector(".results");
369
490
  let r;
370
491
  try {
371
492
  if (i.slots != null && (!Number.isFinite(i.slots) || i.slots < 1)) throw new Error("slots must be at least 1");
493
+ if (!i.inferBits && i.quant === "custom-exl") {
494
+ if (i.customBits == null || !Number.isFinite(i.customBits) || i.customBits < 1 || i.customBits > 16) {
495
+ throw new Error("exl bits per weight must be between 1 and 16");
496
+ }
497
+ }
372
498
  const slots = Math.max(1, Math.round(i.slots ?? 1));
373
499
  const { shape, notes } = calc.shape({
374
500
  params: i.inferParams ? null : i.params,
375
501
  active: i.active,
376
- fmt: i.fmt,
502
+ fmt: i.inferBits ? null : i.fmt,
377
503
  fileBytes: i.fileBytes,
378
504
  attention: i.attention,
379
505
  kvPerToken: i.kvPerToken,
@@ -386,14 +512,27 @@ if (typeof document !== "undefined") (() => {
386
512
  $("err").hidden = true;
387
513
  $("stale-note").hidden = true;
388
514
  resultsEl?.classList.remove("is-stale");
515
+ setClass($("mobile-summary"), "is-stale", false);
389
516
  } catch (e) {
390
517
  $("err").textContent = zhMsg(e.message);
391
518
  $("err").hidden = false;
392
519
  $("stale-note").hidden = false;
393
520
  resultsEl?.classList.add("is-stale");
521
+ setClass($("mobile-summary"), "is-stale", true);
394
522
  return;
395
523
  }
396
524
  last = r;
525
+ lastInputs = i;
526
+ ensureSelected(r);
527
+ if (i.inferParams && $("params-inferred-text")) {
528
+ $("params-inferred-text").textContent = `由文件大小反推 ≈ ${(r.model.params / 1e9).toFixed(1)}B`;
529
+ }
530
+ if (i.inferBits && $("quant-inferred-text")) {
531
+ const nearMatch = String(r.format.note || "").match(/^nearest listed:\s*(.+)$/);
532
+ $("quant-inferred-text").textContent = nearMatch
533
+ ? `由文件大小反推 · ${r.format.bits_per_weight} bpw(近 ${nearMatch[1]})`
534
+ : `由文件大小反推 · ${r.format.bits_per_weight} bpw`;
535
+ }
397
536
  $("kv-val").textContent = `${(r.kv_bytes_per_token / 1024).toFixed(0)} KiB/token`;
398
537
  $("bits-val").textContent = `${r.format.bits_per_weight} bpw`;
399
538
  renderReadouts(r, i);
@@ -431,10 +570,16 @@ if (typeof document !== "undefined") (() => {
431
570
  if (r.kv_source !== "given") notes.push(`KV 每 token 是按参数估的(${zhMsg(r.kv_source)});知道真实值就填进去,或用 memcalc 读 config.json。`);
432
571
  if (i.context > 131072) notes.push("上下文超过 128K:很多模型训练长度到不了这里,先查模型的 max_position_embeddings。");
433
572
  $("notes").innerHTML = notes.map((n) => `<p>· ${esc(n)}</p>`).join("");
573
+ const msTier = $("ms-tier");
574
+ const msRun = $("ms-run");
575
+ const msFile = $("ms-file");
576
+ if (msTier) msTier.textContent = tierName(m.fits);
577
+ if (msRun) msRun.textContent = `运行 ${gib(rt.total)} GiB`;
578
+ if (msFile) msFile.textContent = `权重 ${gb(r.file_bytes)} GB`;
434
579
  renderCompare(r);
435
580
  }
436
581
 
437
- function renderRuler(r) {
582
+ function renderRuler(r, restoreDotIds = null) {
438
583
  const wrap = $("ruler-wrap");
439
584
  const W = Math.max(300, wrap.clientWidth);
440
585
  const narrow = W < 620;
@@ -447,6 +592,7 @@ if (typeof document !== "undefined") (() => {
447
592
  const hi = Math.max(2048 * GiB, need * 1.3);
448
593
  const x0 = gutter, x1 = W - 14;
449
594
  const X = (b) => x0 + ((Math.log2(Math.max(b, lo)) - Math.log2(lo)) / (Math.log2(hi) - Math.log2(lo))) * (x1 - x0);
595
+ const xn = X(need), xw = X(weights);
450
596
  const parts = [];
451
597
  // grid
452
598
  for (let g = 1; g * GiB <= hi; g *= 2) {
@@ -455,7 +601,7 @@ if (typeof document !== "undefined") (() => {
455
601
  parts.push(`<line x1="${x}" x2="${x}" y1="${top - 6}" y2="${H - 22}" stroke="var(--line)" stroke-width="1"/>`);
456
602
  if (major || !narrow) parts.push(`<text x="${x}" y="${H - 6}" text-anchor="middle">${g >= 1024 ? `${g / 1024}T` : `${g}G`}</text>`);
457
603
  }
458
- // rows
604
+ // tier baselines & labels
459
605
  const rows = r.devices;
460
606
  D.tiers.forEach(([tier], idx) => {
461
607
  const y = top + idx * rowH + rowH / 2 + (narrow ? 8 : 0);
@@ -463,7 +609,13 @@ if (typeof document !== "undefined") (() => {
463
609
  parts.push(`<line x1="${x0}" x2="${x1}" y1="${y}" y2="${y}" stroke="var(--line-2)" stroke-width="1"/>`);
464
610
  if (narrow) parts.push(`<text class="tl" x="${x0}" y="${y - 24}">${esc(label)}</text>`);
465
611
  else parts.push(`<text class="tl" x="0" y="${y + 4}">${esc(label)}</text>`);
466
- // devices of this tier, merged when their usable memory is within 4%
612
+ });
613
+ // vertical reference lines drawn below device dots & haloed labels
614
+ parts.push(`<line x1="${xw}" x2="${xw}" y1="${top - 4}" y2="${H - 22}" stroke="var(--muted)" stroke-width="1.5" stroke-dasharray="4 3"/>`);
615
+ parts.push(`<line x1="${xn}" x2="${xn}" y1="${top - 10}" y2="${H - 22}" stroke="var(--ink)" stroke-width="2"/>`);
616
+ // devices of each tier, merged when their usable memory is within 4%
617
+ D.tiers.forEach(([tier], idx) => {
618
+ const y = top + idx * rowH + rowH / 2 + (narrow ? 8 : 0);
467
619
  const mine = rows.filter((d) => d.tier === tier).sort((a, b) => a.usable_bytes - b.usable_bytes);
468
620
  const groups = [];
469
621
  for (const d of mine) {
@@ -476,68 +628,153 @@ if (typeof document !== "undefined") (() => {
476
628
  const best = g.find((d) => d.verdict === "fits") || g.find((d) => d.verdict === "offload") || g[0];
477
629
  const x = X(g[0].usable_bytes);
478
630
  const color = best.verdict === "fits" ? "var(--good)" : best.verdict === "offload" ? "var(--s-off)" : "var(--none)";
479
- const side = gi % 2;
480
- const ly = side ? y + 17 : y - 9;
481
631
  const text = g.map((d) => SHORT[d.device] || d.device).join("/");
482
632
  const w = [...text].reduce((n, ch) => n + (ch.charCodeAt(0) > 0x2e80 ? 10.5 : 6.2), 0);
483
- const showLabel = x - w / 2 > lastRight[side] + 6;
484
- if (showLabel) lastRight[side] = x + w / 2;
485
- parts.push(`<g class="dev" tabindex="0" data-ids="${g.map((d) => d.device).join(",")}">
486
- <circle cx="${x}" cy="${y}" r="6" fill="${color}" stroke="var(--surface)" stroke-width="2"/>
487
- ${showLabel ? `<text class="dl halo" x="${x}" y="${ly}" text-anchor="middle">${esc(text)}</text>` : ""}</g>`);
633
+ const tryPlace = (sideIdx) => {
634
+ let lx = x;
635
+ let anchor = "middle";
636
+ let left = lx - w / 2;
637
+ let right = lx + w / 2;
638
+ if (left < x0) { left = x0; right = x0 + w; lx = x0; anchor = "start"; }
639
+ else if (right > x1) { right = x1; left = x1 - w; lx = x1; anchor = "end"; }
640
+ // Shift away from the vertical need line when a label would cross xn
641
+ if (left < xn + 5 && right > xn - 5) {
642
+ if (x <= xn && xn - 6 - w >= x0) {
643
+ anchor = "end";
644
+ lx = xn - 6;
645
+ right = lx;
646
+ left = lx - w;
647
+ } else if (x > xn && xn + 6 + w <= x1) {
648
+ anchor = "start";
649
+ lx = xn + 6;
650
+ left = lx;
651
+ right = lx + w;
652
+ }
653
+ }
654
+ if (left > lastRight[sideIdx] + 6) return { sideIdx, lx, anchor, right };
655
+ return null;
656
+ };
657
+ const placed = tryPlace(gi % 2) || tryPlace(1 - (gi % 2));
658
+ if (placed) lastRight[placed.sideIdx] = placed.right;
659
+ const ly = placed ? (placed.sideIdx ? y + 17 : y - 9) : y - 9;
660
+ const isSelDot = g.some((d) => d.device === selected);
661
+ const ariaLabel = g.map((d) => {
662
+ const status = VERDICT_ZH[d.verdict] + (d.offload_bytes ? `(${gib(d.offload_bytes)} GiB 进内存)` : "");
663
+ return `${d.name},可用 ${gib(d.usable_bytes)} GiB,需要 ${gib(d.need.total)} GiB,${status}`;
664
+ }).join(";");
665
+ parts.push(`<g class="dev${isSelDot ? " is-selected" : ""}" role="button" tabindex="0" data-ids="${g.map((d) => d.device).join(",")}" aria-label="${esc(ariaLabel)}" aria-pressed="${isSelDot ? "true" : "false"}">
666
+ ${isSelDot ? `<circle class="sel-ring" cx="${x}" cy="${y}" r="9.5"/>` : ""}
667
+ <circle class="dot" cx="${x}" cy="${y}" r="6" fill="${color}" stroke="var(--surface)" stroke-width="2"/>
668
+ ${placed ? `<text class="dl halo" aria-hidden="true" x="${placed.lx}" y="${ly}" text-anchor="${placed.anchor}">${esc(text)}</text>` : ""}</g>`);
488
669
  });
489
670
  });
490
- // need lines
491
- const xn = X(need), xw = X(weights);
492
- parts.push(`<line x1="${xw}" x2="${xw}" y1="${top - 4}" y2="${H - 22}" stroke="var(--muted)" stroke-width="1.5" stroke-dasharray="4 3"/>`);
493
- parts.push(`<line x1="${xn}" x2="${xn}" y1="${top - 10}" y2="${H - 22}" stroke="var(--ink)" stroke-width="2"/>`);
494
- const anchor = xn > W - 120 ? "end" : xn < x0 + 60 ? "start" : "middle";
671
+ const anchor = xn > W - 95 ? "end" : xn < x0 + 75 ? "start" : "middle";
495
672
  parts.push(`<text class="need halo" x="${xn}" y="${top - 16}" text-anchor="${anchor}">需要 ${gib(need)} GiB</text>`);
496
673
  const svg = $("ruler");
497
674
  svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
498
675
  svg.setAttribute("width", W);
499
676
  svg.setAttribute("height", H);
500
677
  svg.innerHTML = parts.join("");
678
+ if (restoreDotIds) {
679
+ svg.querySelector?.(`g.dev[data-ids="${restoreDotIds}"]`)?.focus?.({ preventScroll: true });
680
+ }
501
681
  }
502
682
 
503
683
  function devTip(ids, evt) {
504
- const rows = ids.map((id) => last.devices.find((d) => d.device === id));
684
+ const rows = ids.map((id) => last.devices.find((d) => d.device === id)).filter(Boolean);
685
+ if (!rows.length) return;
505
686
  const tip = $("tip");
506
- tip.innerHTML = rows.map((d) => `<div class="th">${esc(d.name)}</div>
687
+ tip.innerHTML = rows.map((d, idx) => {
688
+ const isCur = d.device === selected;
689
+ return `<div class="tip-dev${idx > 0 ? " tip-sep" : ""}">
690
+ <div class="th">${esc(d.name)}${rows.length > 1 && isCur ? '<span class="tip-cur">当前</span>' : ""}</div>
507
691
  <div class="tr"><span>可用</span><span>${gib(d.usable_bytes)} GiB</span></div>
508
692
  <div class="tr"><span>需要(${esc(d.engine)})</span><span>${gib(d.need.total)} GiB</span></div>
509
693
  <div class="tr"><span>结论</span><span>${VERDICT_ZH[d.verdict]}${d.offload_bytes ? `,${gib(d.offload_bytes)} GiB 进内存` : ""}</span></div>
510
- ${d.decode_ceiling_tok_s ? `<div class="tr"><span>decode 上限</span><span>${tok(d.decode_ceiling_tok_s)} tok/s</span></div>` : ""}`).join("");
694
+ ${d.decode_ceiling_tok_s ? `<div class="tr"><span>decode 上限</span><span>${tok(d.decode_ceiling_tok_s)} tok/s</span></div>` : ""}
695
+ </div>`;
696
+ }).join("") + (rows.length > 1 ? `<div class="tip-hint">点击圆点依次切换这 ${rows.length} 台设备</div>` : "");
511
697
  tip.hidden = false;
512
698
  const wrap = $("ruler-wrap").getBoundingClientRect();
513
- const box = (evt.target.closest("g") || evt.target).getBoundingClientRect();
514
- let left = box.left - wrap.left + 14;
515
- if (left + 220 > wrap.width) left = Math.max(0, box.left - wrap.left - 224);
516
- tip.style.left = `${left}px`;
517
- tip.style.top = `${box.top - wrap.top + 12}px`;
699
+ const targetNode = evt.target?.closest?.("g") || evt.target;
700
+ if (!targetNode || typeof targetNode.getBoundingClientRect !== "function") return;
701
+ const box = targetNode.getBoundingClientRect();
702
+ const tipW = tip.offsetWidth || 220;
703
+ const tipH = tip.offsetHeight || 120;
704
+ const dotX = box.left - wrap.left + (box.width || 0) / 2;
705
+ const dotY = box.top - wrap.top + (box.height || 0) / 2;
706
+ let left = dotX + 12;
707
+ if (left + tipW > wrap.width - 4) left = dotX - tipW - 12;
708
+ left = Math.max(4, Math.min(left, Math.max(4, wrap.width - tipW - 4)));
709
+ const viewH = typeof window !== "undefined" && window.innerHeight ? window.innerHeight : wrap.top + wrap.height;
710
+ let top = dotY + 12;
711
+ if (top + tipH > wrap.height - 4 || wrap.top + top + tipH > viewH - 8) {
712
+ top = dotY - tipH - 12;
713
+ }
714
+ top = Math.max(4, Math.min(top, Math.max(4, wrap.height - tipH - 4)));
715
+ tip.style.left = `${Math.round(left)}px`;
716
+ tip.style.top = `${Math.round(top)}px`;
717
+ }
718
+
719
+ function matchesDevFilter(d) {
720
+ if (devFilter === "runnable" && d.verdict === "no") return false;
721
+ const q = devQuery.trim().toLowerCase();
722
+ if (!q) return true;
723
+ const tierInfo = TIER_ZH[d.tier] || ["", ""];
724
+ const backend = DEVICE_META[d.device]?.backend || "";
725
+ const hay = `${d.name} ${d.device} ${SHORT[d.device] || ""} ${d.engine} ${backend} ${tierInfo[0]} ${tierInfo[1]}`.toLowerCase();
726
+ return q.split(/\s+/).every((token) => hay.includes(token));
518
727
  }
519
728
 
520
- function renderDevices(r) {
729
+ function renderDevices(r, restoreFocusId = null) {
730
+ const table = $("devtable");
731
+ const activeEl = typeof document !== "undefined" ? document.activeElement : null;
732
+ const activeRow = activeEl && typeof activeEl.closest === "function" ? activeEl.closest("tr.dev") : null;
733
+ const inTable = activeRow && (typeof table.contains !== "function" || table.contains(activeRow));
734
+ const focusId = restoreFocusId || (inTable ? activeRow.dataset?.id : null);
735
+ ensureSelected(r);
521
736
  const byTier = {};
522
- for (const d of r.devices) (byTier[d.tier] = byTier[d.tier] || []).push(d);
523
- if (!selected || !r.devices.some((d) => d.device === selected)) {
524
- const t = r.tiers.find((x) => x.verdict === "fits") || r.tiers.find((x) => x.verdict === "offload");
525
- selected = t ? t.device : r.devices[r.devices.length - 1].device;
737
+ const visibleIds = new Set();
738
+ let runnableCount = 0;
739
+ for (const d of r.devices) {
740
+ if (d.verdict !== "no") runnableCount++;
741
+ if (!matchesDevFilter(d)) continue;
742
+ (byTier[d.tier] = byTier[d.tier] || []).push(d);
743
+ visibleIds.add(d.device);
526
744
  }
527
- const supportTag = (s) => `<span class="tag ${s}">${s}</span>`;
745
+ const supportTag = (s) => {
746
+ const [label, tip] = SUPPORT_ZH[s] || [s, ""];
747
+ return `<span class="tag ${esc(s)}" data-support="${esc(s)}"${tip ? ` title="${esc(tip)}"` : ""}>${esc(label)}</span>`;
748
+ };
528
749
  const html = [];
529
750
  for (const [tier] of D.tiers) {
751
+ const rows = byTier[tier] || [];
752
+ if (!rows.length) continue;
530
753
  const [label, detail] = TIER_ZH[tier];
531
754
  html.push(`<tr class="tierhead"><td colspan="7">${esc(label)}<span>${esc(detail)}</span></td></tr>`);
532
- for (const d of byTier[tier] || []) {
755
+ for (const d of rows) {
756
+ const isSel = d.device === selected;
533
757
  const verdict = `<span class="pill ${d.verdict}">${VERDICT_ZH[d.verdict]}</span>${d.offload_bytes ? ` <span class="hint">${gib(d.offload_bytes)} GiB 进内存</span>` : ""}`;
534
- html.push(`<tr class="dev${d.device === selected ? " cur" : ""}" data-id="${d.device}" tabindex="0">
758
+ html.push(`<tr class="dev${isSel ? " cur" : ""}" data-id="${d.device}" tabindex="0" aria-selected="${isSel ? "true" : "false"}">
535
759
  <td>${esc(d.name)}</td><td>${esc(d.engine)}</td><td>${supportTag(d.format_support)}</td>
536
760
  <td class="n">${gib(d.need.total)}</td><td class="n">${gib(d.usable_bytes)}</td><td>${verdict}</td>
537
761
  <td class="n">${tok(d.decode_ceiling_tok_s)}</td></tr>`);
538
762
  }
539
763
  }
540
- $("devtable").querySelector("tbody").innerHTML = html.join("");
764
+ if (!visibleIds.size) {
765
+ html.push('<tr class="empty-row"><td colspan="7">没有匹配的设备 <button type="button" class="link-btn" data-action="reset-dev-filter">清除筛选</button></td></tr>');
766
+ }
767
+ table.querySelector("tbody").innerHTML = html.join("");
768
+ const countEl = $("dev-filter-count");
769
+ if (countEl) {
770
+ const filtered = devFilter !== "all" || devQuery.trim() !== "";
771
+ countEl.textContent = filtered
772
+ ? `显示 ${visibleIds.size} / ${r.devices.length} 台`
773
+ : `可运行 ${runnableCount} / ${r.devices.length} 台`;
774
+ }
775
+ if (focusId && visibleIds.has(focusId)) {
776
+ table.querySelector?.(`tr.dev[data-id="${focusId}"]`)?.focus?.({ preventScroll: true });
777
+ }
541
778
  renderBar(r.devices.find((d) => d.device === selected), r);
542
779
  }
543
780
 
@@ -545,6 +782,8 @@ if (typeof document !== "undefined") (() => {
545
782
  const n = d.need;
546
783
  const onHost = d.offload_bytes || 0;
547
784
  const hostKv = d.host_kv_bytes || 0;
785
+ const hostWeights = d.host_weights_bytes ?? Math.max(0, onHost - hostKv);
786
+ const hostRoom = d.host_room_bytes || 0;
548
787
  const scale = Math.max(d.usable_bytes, n.total - onHost, 1);
549
788
  const pct = (b) => `${Math.max(0, (b / scale) * 100)}%`;
550
789
  const weightsCard = n.weights - (d.host_weights_bytes || 0);
@@ -556,33 +795,68 @@ if (typeof document !== "undefined") (() => {
556
795
  ];
557
796
  const used = weightsCard + kvCard + n.overhead;
558
797
  const free = Math.max(0, d.usable_bytes - used);
798
+ const over = Math.max(0, used - d.usable_bytes);
559
799
  const um = (d.usable_bytes / scale) * 100;
560
800
  const markCls = um > 85 ? "end" : um < 15 ? "start" : "";
801
+ let hostSection = "";
802
+ if (onHost > 0) {
803
+ const hostScale = Math.max(hostRoom, onHost, 1);
804
+ const hpct = (b) => `${Math.max(0, (b / hostScale) * 100)}%`;
805
+ const hostFree = Math.max(0, hostRoom - onHost);
806
+ const hum = (hostRoom / hostScale) * 100;
807
+ const hMarkCls = hum > 85 ? "end" : hum < 15 ? "start" : "";
808
+ const hostSegs = [[hostWeights, "var(--s-off)", "卸载权重"]];
809
+ if (hostKv > 0) hostSegs.push([hostKv, "color-mix(in srgb, var(--s-off) 55%, var(--s-kv))", "卸载 KV"]);
810
+ const hostAria = `卸载到系统内存 ${gib(onHost)} GiB(权重 ${gib(hostWeights)}${hostKv ? `,KV ${gib(hostKv)}` : ""}),主机可用 ${gib(hostRoom)} GiB`;
811
+ hostSection = `
812
+ <div class="bar-label host-label"><span>系统内存卸载</span><span>已用 <b>${gib(onHost)}</b> / 主机可用 ${gib(hostRoom)} GiB(权重 ${gib(hostWeights)}${hostKv ? ` + KV ${gib(hostKv)}` : ""})</span></div>
813
+ <div class="bar host-bar" role="img" aria-label="${esc(hostAria)}">
814
+ ${hostSegs.map(([b, c, t]) => `<div title="${t} ${gib(b)} GiB" style="width:${hpct(b)};background:${c}"></div>`).join("")}
815
+ ${hostFree ? `<div class="free" style="width:${hpct(hostFree)}"></div>` : ""}
816
+ <div class="mark ${hMarkCls}" style="left:${hum}%"><span>主机可用 ${gib(hostRoom)} GiB</span></div>
817
+ </div>`;
818
+ }
561
819
  $("dev-title").textContent = `设备明细 · ${d.name}`;
562
820
  $("mbar").innerHTML = `
563
821
  <div class="mh"><span><b>${esc(d.name)}</b> · ${esc(d.engine)} · ${VERDICT_ZH[d.verdict]}</span>
564
- <span>卡上 / 统一内存里 <b>${gib(used)}</b> GiB,可用 ${gib(d.usable_bytes)} GiB${onHost ? `;另有 <b>${gib(onHost)}</b> GiB 放在系统内存(权重 ${gib(onHost - hostKv)}${hostKv ? ` + KV ${gib(hostKv)}` : ""},可用 ${gib(d.host_room_bytes)})` : ""}</span></div>
565
- <div class="bar" role="img" aria-label="权重 ${gib(weightsCard)},KV ${gib(kvCard)},引擎 ${gib(n.overhead)} GiB,可用 ${gib(d.usable_bytes)} GiB">
822
+ <span>${onHost
823
+ ? `卡上 <b>${gib(used)}</b> GiB + 卸载到内存 <b>${gib(onHost)}</b> GiB / 主机可用 ${gib(hostRoom)} GiB`
824
+ : `卡上 / 统一内存里 <b>${gib(used)}</b> GiB,可用 ${gib(d.usable_bytes)} GiB${over ? ` <b class="oom-note">(超出 ${gib(over)} GiB)</b>` : ""}`}</span></div>
825
+ ${onHost ? `<div class="bar-label"><span>卡上显存</span><span>已用 <b>${gib(used)}</b> / 可用 ${gib(d.usable_bytes)} GiB</span></div>` : ""}
826
+ <div class="bar${over ? " is-over" : ""}" role="img" aria-label="权重 ${gib(weightsCard)},KV ${gib(kvCard)},引擎 ${gib(n.overhead)} GiB,可用 ${gib(d.usable_bytes)} GiB${over ? `,超出 ${gib(over)} GiB` : ""}">
566
827
  ${segs.map(([b, c, t]) => `<div title="${t} ${gib(b)} GiB" style="width:${pct(b)};background:${c}"></div>`).join("")}
567
828
  ${free ? `<div class="free" style="width:${pct(free)}"></div>` : ""}
829
+ ${over ? `<div class="over" title="超出可用内存 ${gib(over)} GiB" style="left:${um}%;width:${Math.max(0, 100 - um)}%"></div>` : ""}
568
830
  <div class="mark ${markCls}" style="left:${um}%"><span>可用 ${gib(d.usable_bytes)} GiB</span></div>
569
- </div>
570
- <div class="legend"><span><i class="sq" style="background:var(--s-w)"></i>权重 ${gib(weightsCard)}</span><span><i class="sq" style="background:var(--s-kv)"></i>KV ${gib(kvCard)}(${ctxLabel(r.posture.context)} × ${r.posture.slots},${r.posture.kvType})</span><span><i class="sq" style="background:var(--s-ov)"></i>引擎 ${gib(n.overhead)}</span>${d.decode_ceiling_tok_s ? `<span>decode 上限 ≈ ${tok(d.decode_ceiling_tok_s)} tok/s</span>` : ""}</div>`;
831
+ </div>${hostSection}
832
+ <div class="legend"><span><i class="sq" style="background:var(--s-w)"></i>权重 ${gib(weightsCard)}</span><span><i class="sq" style="background:var(--s-kv)"></i>KV ${gib(kvCard)}(${ctxLabel(r.posture.context)} × ${r.posture.slots},${r.posture.kvType})</span><span><i class="sq" style="background:var(--s-ov)"></i>引擎 ${gib(n.overhead)}</span>${onHost ? `<span><i class="sq" style="background:var(--s-off)"></i>卸载到内存 ${gib(onHost)}(权重 ${gib(hostWeights)}${hostKv ? ` + KV ${gib(hostKv)}` : ""})</span>` : ""}${over ? `<span><i class="sq over-swatch"></i>超出 ${gib(over)} GiB</span>` : ""}${d.decode_ceiling_tok_s ? `<span>decode 上限 ≈ ${tok(d.decode_ceiling_tok_s)} tok/s</span>` : ""}</div>`;
571
833
  }
572
834
 
573
835
  function renderLadder(r) {
574
836
  const max = Math.max(...r.ladder.map((l) => l.file_bytes));
575
- $("ladder").innerHTML = r.ladder.map((l) => `<div class="lr${l.current ? " on" : ""}">
837
+ const listed = new Set(D.formats.map((f) => f.name));
838
+ $("ladder").innerHTML = r.ladder.map((l) => {
839
+ const selectable = listed.has(l.format);
840
+ const attrs = selectable
841
+ ? ` role="button" tabindex="0" data-fmt="${esc(l.format)}" aria-pressed="${l.current ? "true" : "false"}" title="切换到 ${esc(l.format)}"`
842
+ : "";
843
+ return `<div class="lr${l.current ? " on" : ""}${selectable ? " clickable" : ""}"${attrs}>
576
844
  <span class="ln">${esc(l.format)}<small>${l.bits}</small></span>
577
845
  <span class="lb"><div style="width:${(l.file_bytes / max) * 100}%"></div><em>${gb(l.file_bytes)} GB</em></span>
578
- <span class="lt">${esc(tierName(l.fits))}${l.fits && l.fits_as_is !== l.fits ? `(需转格式;原样:${esc(tierName(l.fits_as_is))})` : ""}${l.runs && l.runs !== l.fits ? ` · 卸载:${esc(tierName(l.runs))}` : ""}</span></div>`).join("");
846
+ <span class="lt">${esc(tierName(l.fits))}${l.fits && l.fits_as_is !== l.fits ? `(需转格式;原样:${esc(tierName(l.fits_as_is))})` : ""}${l.runs && l.runs !== l.fits ? ` · 卸载:${esc(tierName(l.runs))}` : ""}</span></div>`;
847
+ }).join("");
579
848
  }
580
849
 
581
850
  function renderFormats() {
851
+ const basisTag = (b) => {
852
+ const [label, tip] = BASIS_ZH[b] || [b, ""];
853
+ return `<span class="tag" data-basis="${esc(b)}"${tip ? ` title="${esc(tip)}"` : ""}>${esc(label)}</span>`;
854
+ };
855
+ const fmtNote = (note) => (note ? (FMT_NOTE_ZH[note] || note) : "");
582
856
  $("fmttable").querySelector("tbody").innerHTML = D.formats.map((f) => `<tr>
583
857
  <td class="mono">${esc(f.name)}</td><td>${esc(FAMILY_ZH[f.family] || f.family)}</td>
584
- <td class="n">${f.bits}</td><td><span class="tag">${esc(f.basis)}</span></td><td class="n">${(f.bits / 8).toFixed(2)} GB</td>
585
- <td>${esc(D.default_engine[f.family])}</td><td class="hint">${esc(f.note)}</td></tr>`).join("");
858
+ <td class="n">${f.bits}</td><td>${basisTag(f.basis)}</td><td class="n">${(f.bits / 8).toFixed(2)} GB</td>
859
+ <td>${esc(D.default_engine[f.family])}</td><td class="hint">${esc(fmtNote(f.note))}</td></tr>`).join("");
586
860
  $("refs").innerHTML = REFS.map(([t, u]) => `<li><a href="${esc(u)}" target="_blank" rel="noopener">${esc(t)}</a></li>`).join("");
587
861
  }
588
862
 
@@ -590,7 +864,7 @@ if (typeof document !== "undefined") (() => {
590
864
  const a = ["localmodels sizecalc"];
591
865
  if (!i.inferParams && i.params != null) a.push(`--params ${paramArg(i.params)}`);
592
866
  if (i.active != null) a.push(`--active ${paramArg(i.active)}`);
593
- a.push(`--quant ${i.fmt}`);
867
+ if (!i.inferBits) a.push(`--quant ${i.fmt}`);
594
868
  if (i.fileBytes != null) a.push(`--file-size ${sizeArg(i.fileBytes)}`);
595
869
  if (i.attention !== "full") a.push(`--attention ${i.attention}`);
596
870
  if (i.kvPerToken != null) a.push(`--kv-per-token ${+(i.kvPerToken / 1024).toFixed(1)}KiB`);
@@ -601,6 +875,138 @@ if (typeof document !== "undefined") (() => {
601
875
  $("cmd").textContent = a.join(" ");
602
876
  }
603
877
 
878
+ // ── clipboard & theme helpers ─────────────────────────────────────
879
+ async function copyText(text, fallbackEl = null) {
880
+ if (typeof navigator !== "undefined" && navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
881
+ try {
882
+ await navigator.clipboard.writeText(text);
883
+ return "copied";
884
+ } catch { /* fall through to execCommand fallback */ }
885
+ }
886
+ if (typeof document !== "undefined" && typeof document.createElement === "function" && document.body && typeof document.body.appendChild === "function") {
887
+ const ta = document.createElement("textarea");
888
+ ta.value = text;
889
+ ta.setAttribute?.("readonly", "");
890
+ if (ta.style) {
891
+ ta.style.position = "fixed";
892
+ ta.style.top = "-9999px";
893
+ ta.style.left = "-9999px";
894
+ ta.style.opacity = "0";
895
+ }
896
+ document.body.appendChild(ta);
897
+ try {
898
+ ta.focus?.();
899
+ ta.select?.();
900
+ ta.setSelectionRange?.(0, text.length);
901
+ if (typeof document.execCommand === "function" && document.execCommand("copy")) {
902
+ return "copied";
903
+ }
904
+ } catch { /* fall through to selection fallback */ }
905
+ finally {
906
+ ta.remove?.();
907
+ }
908
+ }
909
+ if (fallbackEl && typeof window !== "undefined" && typeof window.getSelection === "function" && typeof document.createRange === "function") {
910
+ try {
911
+ const range = document.createRange();
912
+ range.selectNodeContents(fallbackEl);
913
+ const sel = window.getSelection();
914
+ sel?.removeAllRanges?.();
915
+ sel?.addRange?.(range);
916
+ return "selected";
917
+ } catch { /* ignore */ }
918
+ }
919
+ return "failed";
920
+ }
921
+
922
+ function bindCopyButton(btn, getText, defaultLabel, opts = {}) {
923
+ if (!btn) return;
924
+ let resetTimer = null;
925
+ btn.addEventListener("click", async () => {
926
+ if (typeof clearTimeout === "function" && resetTimer != null) {
927
+ clearTimeout(resetTimer);
928
+ resetTimer = null;
929
+ }
930
+ const res = await copyText(getText(), opts.fallbackEl || null);
931
+ if (res === "copied") {
932
+ btn.textContent = opts.okLabel || "已复制";
933
+ btn.classList.add("done");
934
+ announce(opts.okAnnounce || "已复制到剪贴板");
935
+ } else if (res === "selected") {
936
+ btn.textContent = "已选中,请 Ctrl+C";
937
+ btn.classList.remove("done");
938
+ announce("未能自动复制,已选中文本,请按 Ctrl+C 复制");
939
+ } else {
940
+ btn.textContent = opts.failLabel || "复制失败";
941
+ btn.classList.remove("done");
942
+ announce(opts.failAnnounce || "复制失败");
943
+ }
944
+ if (typeof setTimeout === "function") {
945
+ resetTimer = setTimeout(() => {
946
+ btn.textContent = defaultLabel;
947
+ btn.classList.remove("done");
948
+ resetTimer = null;
949
+ }, 1600);
950
+ }
951
+ });
952
+ }
953
+
954
+ function readSavedTheme() {
955
+ try {
956
+ if (typeof localStorage !== "undefined" && typeof localStorage.getItem === "function") {
957
+ const saved = localStorage.getItem("lm-theme");
958
+ if (saved === "light" || saved === "dark") return saved;
959
+ }
960
+ } catch { /* ignore storage errors on file:// or private browsing */ }
961
+ return null;
962
+ }
963
+
964
+ function saveTheme(mode) {
965
+ try {
966
+ if (typeof localStorage !== "undefined" && typeof localStorage.setItem === "function") {
967
+ localStorage.setItem("lm-theme", mode);
968
+ }
969
+ } catch { /* ignore */ }
970
+ }
971
+
972
+ function isDarkTheme() {
973
+ const root = document.documentElement;
974
+ if (root?.dataset?.theme === "dark") return true;
975
+ if (root?.dataset?.theme === "light") return false;
976
+ try {
977
+ return typeof matchMedia === "function" && Boolean(matchMedia("(prefers-color-scheme: dark)").matches);
978
+ } catch {
979
+ return false;
980
+ }
981
+ }
982
+
983
+ function syncThemeButton() {
984
+ const btn = $("theme");
985
+ if (!btn) return;
986
+ const dark = isDarkTheme();
987
+ btn.textContent = dark ? "深色 · 切浅色" : "浅色 · 切深色";
988
+ const label = dark ? "当前为深色主题,点击切换为浅色" : "当前为浅色主题,点击切换为深色";
989
+ btn.title = label;
990
+ btn.setAttribute("aria-label", label);
991
+ }
992
+
993
+ function selectLadderFormat(fmt, restoreFocus = false) {
994
+ if (!fmt || !D.formats.some((f) => f.name === fmt)) return;
995
+ const inferring = num("filesize") != null && $("i-params").checked;
996
+ presetId = null;
997
+ if (!inferring && num("filesize") != null) {
998
+ $("filesize").value = "";
999
+ fromPreset.filesize = false;
1000
+ } else if (inferring) {
1001
+ fromPreset.filesize = false;
1002
+ }
1003
+ $("quant").value = fmt;
1004
+ update();
1005
+ if (restoreFocus) {
1006
+ $("ladder").querySelector?.(`.lr[data-fmt="${fmt}"]`)?.focus?.({ preventScroll: true });
1007
+ }
1008
+ }
1009
+
604
1010
  // ── wiring ────────────────────────────────────────────────────────
605
1011
  fillControls();
606
1012
  renderFormats();
@@ -611,13 +1017,14 @@ if (typeof document !== "undefined") (() => {
611
1017
  if (!posture) presetId = null;
612
1018
  // Parameters are inferred from the file when its size is given and "infer parameters" is on.
613
1019
  const inferring = num("filesize") != null && $("i-params").checked;
1020
+ const isInferRadio = id === "i-bits" || id === "i-params" || el.name === "infer";
614
1021
  const formatMoves = id === "quant" || id === "custom-bits";
615
1022
  const paramsMove = ["params", "active", "k-dense", "k-moe"].includes(id) ||
616
- el.name === "infer" || (inferring && (formatMoves || id === "filesize"));
1023
+ isInferRadio || (inferring && (formatMoves || id === "filesize"));
617
1024
  // A preset's file belongs to its parameters and format, unless it is the input the
618
1025
  // parameters are inferred from; its KV per token belongs to its layer layout.
619
- if (id === "filesize") fromPreset.filesize = false;
620
- else if (fromPreset.filesize && !inferring && el.name !== "infer" && (paramsMove || formatMoves)) {
1026
+ if (id === "filesize" || id === "i-bits" || (inferring && formatMoves)) fromPreset.filesize = false;
1027
+ else if (fromPreset.filesize && !inferring && !isInferRadio && (paramsMove || formatMoves)) {
621
1028
  $("filesize").value = "";
622
1029
  fromPreset.filesize = false;
623
1030
  }
@@ -629,47 +1036,165 @@ if (typeof document !== "undefined") (() => {
629
1036
  update();
630
1037
  });
631
1038
  }
1039
+ function syncDevFilterButtons() {
1040
+ $("dev-filter-all")?.setAttribute("aria-pressed", String(devFilter === "all"));
1041
+ $("dev-filter-runnable")?.setAttribute("aria-pressed", String(devFilter === "runnable"));
1042
+ }
1043
+ function setDevFilter(mode) {
1044
+ if ((mode !== "all" && mode !== "runnable") || devFilter === mode) return;
1045
+ devFilter = mode;
1046
+ syncDevFilterButtons();
1047
+ if (last) renderDevices(last);
1048
+ }
1049
+ function resetDevFilters() {
1050
+ devFilter = "all";
1051
+ devQuery = "";
1052
+ const searchEl = $("dev-search");
1053
+ if (searchEl) searchEl.value = "";
1054
+ const clearSearch = $("dev-search-clear");
1055
+ if (clearSearch) clearSearch.hidden = true;
1056
+ syncDevFilterButtons();
1057
+ if (last) renderDevices(last);
1058
+ }
1059
+ function clearPin() {
1060
+ if (!pinned) return;
1061
+ pinned = null;
1062
+ syncPinButton();
1063
+ if (last) renderCompare(last);
1064
+ announce("已取消对比");
1065
+ }
1066
+ function pickRulerDot(ids, { restoreFocus = false, refreshTip = false } = {}) {
1067
+ if (!ids.length || !last) return;
1068
+ const idx = ids.indexOf(selected);
1069
+ selected = idx >= 0 ? ids[(idx + 1) % ids.length] : ids[0];
1070
+ const rawIds = ids.join(",");
1071
+ renderRuler(last, restoreFocus ? rawIds : null);
1072
+ renderDevices(last);
1073
+ if (refreshTip && !$("tip").hidden) {
1074
+ const freshG = $("ruler").querySelector?.(`g.dev[data-ids="${rawIds}"]`);
1075
+ if (freshG && typeof freshG.getBoundingClientRect === "function") devTip(ids, { target: freshG });
1076
+ }
1077
+ }
1078
+
1079
+ $("clear-file")?.addEventListener("click", () => clearFileSize("filesize"));
1080
+ $("clear-file-params")?.addEventListener("click", () => clearFileSize("params"));
1081
+ $("clear-file-quant")?.addEventListener("click", () => clearFileSize("quant"));
1082
+ $("dev-filter-all")?.addEventListener("click", () => setDevFilter("all"));
1083
+ $("dev-filter-runnable")?.addEventListener("click", () => setDevFilter("runnable"));
1084
+ $("dev-filter-bar")?.addEventListener("click", (e) => {
1085
+ const btn = e.target?.closest?.("button[data-filter]");
1086
+ if (btn) setDevFilter(btn.dataset.filter);
1087
+ });
1088
+ $("dev-search")?.addEventListener("input", () => {
1089
+ devQuery = $("dev-search").value || "";
1090
+ const clearSearch = $("dev-search-clear");
1091
+ if (clearSearch) clearSearch.hidden = !devQuery;
1092
+ if (last) renderDevices(last);
1093
+ });
1094
+ $("dev-search")?.addEventListener("keydown", (e) => {
1095
+ if (e.key === "Escape" && devQuery) {
1096
+ e.preventDefault?.();
1097
+ devQuery = "";
1098
+ $("dev-search").value = "";
1099
+ const clearSearch = $("dev-search-clear");
1100
+ if (clearSearch) clearSearch.hidden = true;
1101
+ if (last) renderDevices(last);
1102
+ }
1103
+ });
1104
+ $("dev-search-clear")?.addEventListener("click", () => {
1105
+ devQuery = "";
1106
+ const searchEl = $("dev-search");
1107
+ if (searchEl) searchEl.value = "";
1108
+ $("dev-search-clear").hidden = true;
1109
+ if (last) renderDevices(last);
1110
+ searchEl?.focus?.();
1111
+ });
1112
+ $("compare-bar")?.addEventListener("click", (e) => {
1113
+ if (e.target?.closest?.("[data-action='unpin']")) clearPin();
1114
+ });
1115
+ $("ms-jump")?.addEventListener("click", () => {
1116
+ const resultsEl = document.querySelector(".results");
1117
+ let reduce = false;
1118
+ try {
1119
+ reduce = typeof matchMedia === "function" && Boolean(matchMedia("(prefers-reduced-motion: reduce)").matches);
1120
+ } catch { /* ignore */ }
1121
+ resultsEl?.scrollIntoView?.({ behavior: reduce ? "auto" : "smooth", block: "start" });
1122
+ });
632
1123
  $("devtable").addEventListener("click", (e) => {
633
- const tr = e.target.closest("tr.dev");
634
- if (tr) { selected = tr.dataset.id; renderDevices(last); }
1124
+ if (e.target?.closest?.("[data-action='reset-dev-filter']")) { resetDevFilters(); return; }
1125
+ const tr = e.target?.closest?.("tr.dev");
1126
+ if (tr) { selected = tr.dataset.id; if (last) { renderRuler(last); renderDevices(last); } }
635
1127
  });
636
1128
  $("devtable").addEventListener("keydown", (e) => {
637
- const tr = e.target.closest("tr.dev");
638
- if (tr && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); selected = tr.dataset.id; renderDevices(last); }
1129
+ const tr = e.target?.closest?.("tr.dev");
1130
+ if (tr && (e.key === "Enter" || e.key === " ")) {
1131
+ e.preventDefault?.();
1132
+ selected = tr.dataset.id;
1133
+ if (last) { renderRuler(last); renderDevices(last, tr.dataset.id); }
1134
+ }
1135
+ });
1136
+ $("ladder").addEventListener("click", (e) => {
1137
+ const row = e.target.closest?.(".lr[data-fmt]");
1138
+ if (row) selectLadderFormat(row.dataset.fmt, false);
1139
+ });
1140
+ $("ladder").addEventListener("keydown", (e) => {
1141
+ const row = e.target.closest?.(".lr[data-fmt]");
1142
+ if (row && (e.key === "Enter" || e.key === " ")) { e.preventDefault?.(); selectLadderFormat(row.dataset.fmt, true); }
639
1143
  });
640
1144
  const ruler = $("ruler");
641
- const showTip = (e) => { const g = e.target.closest("g.dev"); if (g) devTip(g.dataset.ids.split(","), e); };
1145
+ const showTip = (e) => { const g = e.target?.closest?.("g.dev"); if (g) devTip(g.dataset.ids.split(","), e); };
642
1146
  ruler.addEventListener("mouseover", showTip);
643
1147
  ruler.addEventListener("focusin", showTip);
644
1148
  ruler.addEventListener("mouseout", () => { $("tip").hidden = true; });
645
1149
  ruler.addEventListener("focusout", () => { $("tip").hidden = true; });
646
1150
  ruler.addEventListener("click", (e) => {
647
- const g = e.target.closest("g.dev");
648
- if (g) { selected = g.dataset.ids.split(",")[0]; renderDevices(last); }
1151
+ const g = e.target?.closest?.("g.dev");
1152
+ if (g) pickRulerDot(g.dataset.ids.split(","), { refreshTip: true });
649
1153
  });
650
1154
  ruler.addEventListener("keydown", (e) => {
651
- const g = e.target.closest("g.dev");
1155
+ const g = e.target?.closest?.("g.dev");
652
1156
  if (g && (e.key === "Enter" || e.key === " ")) {
653
- e.preventDefault();
654
- selected = g.dataset.ids.split(",")[0];
655
- renderDevices(last);
656
- $("devtable").querySelector(`tr[data-id="${selected}"]`)?.scrollIntoView({ block: "nearest" });
1157
+ e.preventDefault?.();
1158
+ const ids = g.dataset.ids.split(",");
1159
+ pickRulerDot(ids, { restoreFocus: true, refreshTip: true });
1160
+ if (ids.length === 1) {
1161
+ $("devtable").querySelector?.(`tr[data-id="${selected}"]`)?.scrollIntoView?.({ block: "nearest" });
1162
+ }
657
1163
  }
658
1164
  });
659
- $("copy").addEventListener("click", async () => {
660
- try { await navigator.clipboard.writeText($("cmd").textContent); $("copy").textContent = "已复制"; }
661
- catch { $("copy").textContent = "复制失败"; }
662
- setTimeout(() => { $("copy").textContent = "复制"; }, 1400);
1165
+ bindCopyButton($("copy"), () => $("cmd").textContent, "复制", {
1166
+ fallbackEl: $("cmd"),
1167
+ okLabel: "已复制",
1168
+ okAnnounce: "命令已复制到剪贴板",
1169
+ failAnnounce: "复制命令失败",
1170
+ });
1171
+ bindCopyButton($("share-btn"), shareUrl, "复制链接", {
1172
+ okLabel: "已复制链接",
1173
+ okAnnounce: "当前方案链接已复制到剪贴板",
1174
+ failLabel: "请复制地址栏",
1175
+ failAnnounce: "未能自动复制链接,请直接复制浏览器地址栏",
663
1176
  });
1177
+ const savedTheme = readSavedTheme();
1178
+ if (savedTheme && document.documentElement?.dataset) {
1179
+ document.documentElement.dataset.theme = savedTheme;
1180
+ }
1181
+ syncThemeButton();
1182
+ try {
1183
+ const mq = typeof matchMedia === "function" ? matchMedia("(prefers-color-scheme: dark)") : null;
1184
+ if (mq && typeof mq.addEventListener === "function") mq.addEventListener("change", syncThemeButton);
1185
+ } catch { /* ignore */ }
664
1186
  $("theme").addEventListener("click", () => {
665
- const root = document.documentElement;
666
- const dark = root.dataset.theme ? root.dataset.theme === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
667
- root.dataset.theme = dark ? "light" : "dark";
1187
+ const next = isDarkTheme() ? "light" : "dark";
1188
+ if (document.documentElement?.dataset) document.documentElement.dataset.theme = next;
1189
+ saveTheme(next);
1190
+ syncThemeButton();
668
1191
  });
669
1192
  $("pin-btn")?.addEventListener("click", () => {
670
1193
  if (pinned) {
671
- pinned = null;
672
- } else if (last) {
1194
+ clearPin();
1195
+ return;
1196
+ }
1197
+ if (last) {
673
1198
  const dev = comparisonDevice(last);
674
1199
  pinned = {
675
1200
  label: currentLabel(last),
@@ -756,11 +1281,14 @@ if (typeof document !== "undefined") (() => {
756
1281
  const fVal = Number(map.file);
757
1282
  if (Number.isFinite(fVal) && fVal > 0) {
758
1283
  $("filesize").value = map.file;
759
- if (!preset || fVal !== preset.file) fromPreset.filesize = false;
1284
+ if (!preset || fVal !== preset.file) {
1285
+ fromPreset.filesize = false;
1286
+ presetId = null;
1287
+ }
760
1288
  }
761
1289
  }
762
1290
  }
763
- if (map.infer === "params") { $("i-params").checked = true; $("i-bits").checked = false; }
1291
+ if (map.infer === "params") { $("i-params").checked = true; $("i-bits").checked = false; presetId = null; }
764
1292
  else if (map.infer === "bits") { $("i-bits").checked = true; $("i-params").checked = false; }
765
1293
  const ctxIdx = parseCtxIndex(map.ctx);
766
1294
  if (ctxIdx != null) $("ctx").value = String(ctxIdx);