aiinfra-tools 0.3.0 → 0.5.0

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 (65) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +43 -0
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/deploy/shadow-live/README.md +8 -0
  6. package/fleetops/deploy/shadow-live/kit.yaml +2 -0
  7. package/fleetops/deploy/shadow-live/run.sh +6 -1
  8. package/fleetops/docs/SHADOW.md +25 -2
  9. package/fleetops/package.json +1 -1
  10. package/fleetops/src/api.mjs +8 -0
  11. package/fleetops/src/ingest.mjs +9 -2
  12. package/fleetops/src/schema.mjs +3 -0
  13. package/fleetops/src/serving.mjs +11 -1
  14. package/fleetops/src/shadow-quality.mjs +107 -0
  15. package/fleetops/src/shadow.mjs +12 -6
  16. package/fleetops/tools/cmd/help.mjs +4 -1
  17. package/fleetops/tools/cmd/shadow.mjs +14 -2
  18. package/fleetscope/build.mjs +4 -0
  19. package/fleetscope/dist/index.html +809 -4
  20. package/fleetscope/package.json +1 -1
  21. package/fleetscope/src/engine.js +19 -2
  22. package/fleetscope/src/index.src.html +23 -1
  23. package/gpu-health/package.json +1 -1
  24. package/gpu-ledger/package.json +1 -1
  25. package/harness-ledger/README.md +48 -0
  26. package/harness-ledger/integrations/README.md +11 -0
  27. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  28. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  29. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  30. package/harness-ledger/package.json +1 -1
  31. package/harness-ledger/src/advise.mjs +410 -0
  32. package/harness-ledger/src/assess.mjs +66 -0
  33. package/harness-ledger/src/doctor.mjs +202 -0
  34. package/harness-ledger/src/engine-metrics.mjs +35 -0
  35. package/harness-ledger/src/importers.mjs +14 -3
  36. package/harness-ledger/src/lint.mjs +115 -0
  37. package/harness-ledger/src/mooncake.mjs +83 -0
  38. package/harness-ledger/src/profile.mjs +164 -0
  39. package/harness-ledger/src/record.mjs +2 -2
  40. package/harness-ledger/src/suggest.mjs +177 -0
  41. package/harness-ledger/src/trajectory.mjs +81 -0
  42. package/harness-ledger/src/workload-demo.mjs +100 -0
  43. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  44. package/hybrid-tracing/package.json +1 -1
  45. package/inference-sizer/build.mjs +1 -0
  46. package/inference-sizer/dist/index.html +192 -17
  47. package/inference-sizer/docs/CATALOG.md +71 -0
  48. package/inference-sizer/docs/METHOD.md +1 -1
  49. package/inference-sizer/package.json +1 -1
  50. package/inference-sizer/src/accelerators.js +23 -1
  51. package/inference-sizer/src/catalog.js +49 -3
  52. package/inference-sizer/src/index.src.html +7 -0
  53. package/inference-sizer/src/model.js +29 -9
  54. package/inference-sizer/src/suggest.js +70 -0
  55. package/inference-sizer/src/ui.js +14 -4
  56. package/inference-sizer/tools/validate-agentx.mjs +8 -2
  57. package/inference-sizer/tools/validate-inferencex.mjs +1 -1
  58. package/mcp/README.md +3 -0
  59. package/mcp/server.mjs +22 -0
  60. package/package.json +3 -1
  61. package/schemas/README.md +3 -0
  62. package/schemas/commands.mjs +7 -0
  63. package/schemas/harness-ledger.advise.schema.json +1102 -0
  64. package/schemas/harness-ledger.assess.schema.json +2823 -0
  65. package/schemas/harness-ledger.suggest.schema.json +326 -0
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
228
228
  .mtx th:first-child, .mtx td:first-child { text-align: left; }
229
229
  .mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
230
230
  .kpi.wide { grid-column: span 2; cursor: pointer; }
231
+ .kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
232
+ .kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
233
+ .kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
231
234
  .kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
232
235
  .legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
233
236
  .legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
@@ -431,6 +434,11 @@ button, select, input { font: inherit; color: inherit; }
431
434
 
432
435
  const A = (o) => Object.assign({ kind: 'gpu', tfFp4: 0 }, o);
433
436
  const ACCELERATORS = [
437
+ // Vera Rubin NVL72 (VR200; first called NVL144 for its 144 dies): per Rubin package, 288 GB HBM4 at 22 TB/s; dense
438
+ // NVFP4 35 PF (the 50 PF inference figure uses adaptive compression), FP8 17.5 PF, BF16 4 PF; NVLink 6 3.6 TB/s
439
+ // bidirectional; ConnectX-9 1.6 Tb/s. NVIDIA publishes no board power: 2.3 kW is the reported Max-P TGP.
440
+ A({ id: 'VR200-NVL72', short: 'VR200', label: 'NVIDIA Vera Rubin NVL72 (72-GPU rack)', vendor: 'NVIDIA', vendorKey: 'nvidia', hbmGB: 288, hbmTBs: 22, tfBf16: 4000, tfFp8: 17500, tfFp4: 35000, scaleUpGBs: 1800, domain: 72, nicGbps: 1600, tdpW: 2300, price: 11.0, onprem: 6.5, match: 'Rubin(?!.*CPX)|VR200|\\bR200\\b',
441
+ source: 'https://developer.nvidia.com/blog/inside-the-NVIDIA-rubin-platform-six-new-chips-one-ai-supercomputer' }),
434
442
  A({ id: 'GB300-NVL72', short: 'GB300', label: 'NVIDIA GB300 NVL72 (72-GPU rack)', vendor: 'NVIDIA', vendorKey: 'nvidia', hbmGB: 278, hbmTBs: 8, tfBf16: 2500, tfFp8: 5000, tfFp4: 15000, scaleUpGBs: 900, domain: 72, nicGbps: 800, tdpW: 1400, price: 7.5, onprem: 4.4, match: 'GB300',
435
443
  // rack figures ÷ 72: 20 TB HBM, 576 TB/s, 360/720/1080 PFLOPS BF16 (sparse)/FP8 (sparse)/FP4 (dense); board power from InferenceX's chip page
436
444
  source: 'https://www.nvidia.com/en-us/data-center/gb300-nvl72/' }),
@@ -446,8 +454,17 @@ button, select, input { font: inherit; color: inherit; }
446
454
  source: 'https://www.nvidia.com/en-us/data-center/h100/' }),
447
455
  A({ id: 'A100', label: 'NVIDIA A100 80GB SXM (8-GPU)', vendor: 'NVIDIA', vendorKey: 'nvidia', hbmGB: 80, hbmTBs: 2.0, tfBf16: 312, tfFp8: 0, scaleUpGBs: 300, domain: 8, nicGbps: 200, nodeKW: 6.5, tdpW: 400, price: 1.6, onprem: 0.9, match: 'A100(?!.*PCIe)|A800',
448
456
  source: 'https://www.nvidia.com/en-us/data-center/a100/' }),
457
+ // RTX PRO 6000 Blackwell Server Edition: 96 GB GDDR7 at 1.6 TB/s; 4 / 2 / 1 PF FP4 / FP8 / BF16 with sparsity
458
+ // (halved here); PCIe 5.0 x16 between cards; up to 600 W
459
+ A({ id: 'RTX-PRO-6000', short: 'RTXPRO6000', label: 'NVIDIA RTX PRO 6000 Blackwell Server (PCIe, 8 per server)', vendor: 'NVIDIA', vendorKey: 'nvidia', hbmGB: 96, hbmTBs: 1.6, tfBf16: 500, tfFp8: 1000, tfFp4: 2000, scaleUpGBs: 64, domain: 8, nicGbps: 400, tdpW: 600, price: 1.8, onprem: 1.0, match: 'RTX ?PRO ?6000|RTX-PRO-6000',
460
+ source: 'https://www.nvidia.com/en-us/data-center/rtx-pro-6000-blackwell-server-edition/' }),
449
461
  A({ id: 'L40S', label: 'NVIDIA L40S (PCIe, 8 per server)', vendor: 'NVIDIA', vendorKey: 'nvidia', hbmGB: 48, hbmTBs: 0.864, tfBf16: 362, tfFp8: 733, scaleUpGBs: 32, domain: 8, nicGbps: 200, nodeKW: 5, tdpW: 350, price: 1.1, onprem: 0.7, match: 'L40S',
450
462
  source: 'https://www.nvidia.com/en-us/data-center/l40s/' }),
463
+ // Helios rack: 72 MI455X, 432 GB HBM4 at 23.3 TB/s, 40 / 20 / 5 PF MXFP4 / MXFP8 / BF16, 3.6 TB/s scale-up
464
+ // (UALink over Ethernet, bidirectional), 43 TB/s scale-out per rack (2.4 Tb/s per GPU per direction), 246 kW per
465
+ // rack (AMD's validated reference design). AMD publishes no board power: ~1.7 kW is the reported projection.
466
+ A({ id: 'MI455X-Helios', short: 'MI455X', label: 'AMD Instinct MI455X Helios (72-GPU rack)', vendor: 'AMD', vendorKey: 'amd', hbmGB: 432, hbmTBs: 23.3, tfBf16: 5000, tfFp8: 20000, tfFp4: 40000, scaleUpGBs: 1800, domain: 72, nicGbps: 2400, nodeKW: 246, tdpW: 1700, price: 8.0, onprem: 4.8, match: 'MI455',
467
+ source: 'https://www.amd.com/en/products/accelerators/instinct/mi400.html' }),
451
468
  A({ id: 'MI355X', label: 'AMD Instinct MI355X (8-GPU)', vendor: 'AMD', vendorKey: 'amd', hbmGB: 288, hbmTBs: 8, tfBf16: 2516.6, tfFp8: 5033.2, tfFp4: 10066.3, scaleUpGBs: 504, domain: 8, nicGbps: 400, tdpW: 1400, price: 4.5, onprem: 2.6, match: 'MI355',
452
469
  // Infinity Fabric: 7 links × 144 GB/s (bidirectional) = 504 GB/s per direction
453
470
  source: 'https://www.amd.com/en/products/accelerators/instinct/mi350/mi355x.html' }),
@@ -486,7 +503,7 @@ button, select, input { font: inherit; color: inherit; }
486
503
  // ---------- cloud instance types ----------
487
504
  // AWS: docs.aws.amazon.com/AWSEC2/latest/UserGuide/accelerated-computing-instances.html and aws.amazon.com/ec2/instance-types/p6/
488
505
  const INSTANCES = {};
489
- const add = (cloud, chip, list) => { for (const [type, gpus] of list) INSTANCES[type] = { cloud, chip, gpus }; };
506
+ const add = (cloud, chip, list) => { for (const [type, gpus] of list) INSTANCES[type.toLowerCase()] = { cloud, chip, gpus }; };
490
507
  const sizes = (fam, one, more) => one.map(s => [`${fam}.${s}`, 1]).concat(more.map(([s, n]) => [`${fam}.${s}`, n]));
491
508
  add('aws', 'A100-40GB', [['p4d.24xlarge', 8]]);
492
509
  add('aws', 'A100', [['p4de.24xlarge', 8]]);
@@ -512,6 +529,14 @@ button, select, input { font: inherit; color: inherit; }
512
529
  add('gcp', 'TPU-v5p', [['ct5p-hightpu-4t', 4]]);
513
530
  add('gcp', 'TPU7x', [['tpu7x-standard-4t', 4]]);
514
531
  add('gcp', 'TPU-v5e', [['ct5lp-hightpu-1t', 1], ['ct5lp-hightpu-4t', 4], ['ct5lp-hightpu-8t', 8]]);
532
+ // Azure: learn.microsoft.com/azure/virtual-machines/sizes/gpu-accelerated (ND H100/H200/MI300X v5, ND GB200 v6, ND A100 v4);
533
+ // AKS puts the size in node.kubernetes.io/instance-type with this capitalisation (matched case-insensitively)
534
+ add('azure', 'H100', [['Standard_ND96isr_H100_v5', 8]]);
535
+ add('azure', 'H200', [['Standard_ND96isr_H200_v5', 8]]);
536
+ add('azure', 'MI300X', [['Standard_ND96isr_MI300X_v5', 8]]);
537
+ add('azure', 'GB200-NVL72', [['Standard_ND128isr_NDR_GB200_v6', 4]]); // 18 VMs per NVL72 rack
538
+ add('azure', 'A100-40GB', [['Standard_ND96asr_v4', 8]]);
539
+ add('azure', 'A100', [['Standard_ND96amsr_A100_v4', 8]]);
515
540
  const instanceOf = type => INSTANCES[String(type || '').toLowerCase()] || null;
516
541
  // TPU slice topology for a chip count: 2D (v5e, v6e) or 3D torus (v4, v5p, 7x), as GKE's node selector wants it
517
542
  const TOPO2 = { 1: '1x1', 4: '2x2', 8: '2x4', 16: '4x4', 32: '4x8', 64: '8x8', 128: '8x16', 256: '16x16' };
@@ -558,6 +583,759 @@ button, select, input { font: inherit; color: inherit; }
558
583
  else root.AIInfraAccelerators = api;
559
584
  })(typeof globalThis !== 'undefined' ? globalThis : this);
560
585
 
586
+ </script>
587
+ <script>
588
+ /* Inference Sizer catalog: GPUs and models, spec-sheet import/export, and Hugging Face config.json parsing.
589
+ Plain data plus validation, so the browser page, the CLI and FleetScope can share it. */
590
+ (function (root) {
591
+ 'use strict';
592
+
593
+ // ---------- schemas ----------
594
+ // Every field a GPU or model entry may carry, with its unit, range and a one-line meaning.
595
+ // The UI builds its edit forms from these, and imports are checked against them.
596
+ const GPU_FIELDS = [
597
+ { k: 'label', type: 'text', label: 'Name', required: true },
598
+ { k: 'vendor', type: 'text', label: 'Vendor' },
599
+ { k: 'hbmGB', label: 'HBM per GPU', unit: 'GB', min: 1, max: 4096, required: true, hint: 'Memory the GPU exposes (e.g. 180 for HGX B200).' },
600
+ { k: 'hbmTBs', label: 'HBM bandwidth', unit: 'TB/s', min: 0.1, max: 100, required: true },
601
+ { k: 'tfBf16', label: 'BF16 dense', unit: 'TFLOPS', min: 1, max: 1e6, required: true, hint: 'Dense, not the "with sparsity" figure.' },
602
+ { k: 'tfFp8', label: 'FP8 dense', unit: 'TFLOPS', min: 0, max: 1e6, hint: '0 if the GPU has no FP8 tensor cores.' },
603
+ { k: 'tfFp4', label: 'FP4 dense', unit: 'TFLOPS', min: 0, max: 1e6, hint: '0 if the GPU has no FP4 tensor cores.' },
604
+ { k: 'scaleUpGBs', label: 'GPU-to-GPU link, per direction', unit: 'GB/s', min: 1, max: 1e5, required: true, hint: 'NVLink / Infinity Fabric. Half the bidirectional figure.' },
605
+ { k: 'domain', label: 'GPUs per scale-up domain', unit: 'GPUs', min: 1, max: 576, required: true, hint: '8 for an HGX server, 72 for an NVL72 rack.' },
606
+ { k: 'nicGbps', label: 'Scale-out NIC per GPU', unit: 'Gb/s', min: 1, max: 1e4, required: true },
607
+ { k: 'nodeKW', label: 'Power per domain (max)', unit: 'kW', min: 0, max: 2000 },
608
+ { k: 'price', label: 'Price', unit: '$/GPU-hr', min: 0, max: 1000, hint: 'Placeholder unless you set your own.' },
609
+ { k: 'source', type: 'text', label: 'Spec sheet URL' },
610
+ ];
611
+ const MODEL_FIELDS = [
612
+ { k: 'name', type: 'text', label: 'Name', required: true },
613
+ { k: 'total', label: 'Total params', unit: 'B', min: 0.01, max: 1e5, required: true },
614
+ { k: 'active', label: 'Active params per token', unit: 'B', min: 0.01, max: 1e5, required: true },
615
+ { k: 'layers', label: 'Layers', min: 1, max: 1000, int: true, required: true },
616
+ { k: 'hidden', label: 'Hidden size', min: 64, max: 1e6, int: true, required: true },
617
+ { k: 'qHeads', label: 'Query heads', min: 1, max: 4096, int: true, required: true },
618
+ { k: 'kvHeads', label: 'KV heads', min: 1, max: 4096, int: true, required: true },
619
+ { k: 'headDim', label: 'Head dim', min: 8, max: 4096, int: true, required: true },
620
+ { k: 'attn', type: 'enum', opts: ['gqa', 'mla'], label: 'Attention', required: true },
621
+ { k: 'mlaLatent', label: 'MLA KV latent (kv_lora_rank)', min: 1, max: 1e5, int: true },
622
+ { k: 'mlaRope', label: 'MLA RoPE dim', min: 0, max: 1e4, int: true },
623
+ { k: 'mlaNope', label: 'MLA QK no-PE dim', min: 0, max: 1e4, int: true },
624
+ { k: 'mlaV', label: 'MLA V head dim', min: 1, max: 1e4, int: true },
625
+ { k: 'experts', label: 'Routed experts (0 = dense)', min: 0, max: 1e5, int: true },
626
+ { k: 'topk', label: 'Experts per token', min: 0, max: 1e4, int: true },
627
+ { k: 'swaFrac', label: 'Share of sliding-window layers', min: 0, max: 1 },
628
+ { k: 'swaWindow', label: 'Sliding window', unit: 'tokens', min: 0, max: 1e8, int: true },
629
+ { k: 'linFrac', label: 'Share of linear-attention layers', min: 0, max: 1, hint: 'Kimi Delta Attention, Gated DeltaNet: a fixed state per sequence instead of KV per token.' },
630
+ { k: 'linStateMB', label: 'Linear-attention state per layer', unit: 'MB', min: 0, max: 1e4, hint: 'Per sequence: value heads × key dim × value dim × 4 bytes (fp32).' },
631
+ { k: 'kvKeep', label: 'Share of tokens whose KV is kept', min: 0.0001, max: 1, hint: 'Compressed attention (DeepSeek V4): average over layers. 1 for ordinary attention.' },
632
+ { k: 'sparseTopK', label: 'Tokens attended per query (sparse attention)', unit: 'tokens', min: 0, max: 1e8, int: true, hint: 'DSA / CSA / MSA index top-k. 0 = attends every kept token.' },
633
+ { k: 'maxCtx', label: 'Max context', unit: 'tokens', min: 256, max: 1e8, int: true, required: true },
634
+ { k: 'wprec', type: 'enum', opts: ['bf16', 'fp8', 'fp4'], label: 'Default weight precision' },
635
+ { k: 'source', type: 'text', label: 'Model card URL' },
636
+ ];
637
+
638
+ // ---------- built-in GPUs ----------
639
+ // From the shared accelerator registry (accelerators.js): per-GPU dense figures, HGX/DGX system totals divided by 8
640
+ // (or 72 for NVL72), "with sparsity" figures halved. Prices are placeholder on-demand rents, not quotes.
641
+ const REG = (typeof module !== 'undefined' && module.exports) ? require('./accelerators.js') : root.AIInfraAccelerators;
642
+ const ORDER = ['B200', 'B300', 'GB200-NVL72', 'GB300-NVL72', 'VR200-NVL72', 'H200', 'H100', 'A100', 'L40S', 'RTX-PRO-6000', 'MI300X', 'MI325X', 'MI355X', 'MI455X-Helios', 'TPU7x', 'TPU-v6e', 'TPU-v5p'];
643
+ const KEEP = ['id', 'kind', 'vendorKey', 'gkeAccelerator', 'tdpW'].concat(GPU_FIELDS.map(f => f.k)); // tdpW: board power, for tokens per MW
644
+ const GPUS = REG.ACCELERATORS.slice().sort((a, b) => (ORDER.indexOf(a.id) + 1 || 99) - (ORDER.indexOf(b.id) + 1 || 99))
645
+ .map(g => Object.fromEntries(KEEP.filter(k => g[k] !== undefined).map(k => [k, g[k]])));
646
+
647
+ // ---------- built-in models ----------
648
+ const MLA = { attn: 'mla', kvHeads: 1, headDim: 128, mlaLatent: 512, mlaRope: 64, mlaNope: 128, mlaV: 128 };
649
+ const G = { attn: 'gqa', experts: 0, topk: 0, swaFrac: 0, swaWindow: 0 };
650
+ const MODELS = [
651
+ Object.assign({ id: 'llama31-8b', name: 'Llama 3.1 8B', total: 8.03, active: 8.03, layers: 32, hidden: 4096, qHeads: 32, kvHeads: 8, headDim: 128, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct' }, G),
652
+ Object.assign({ id: 'qwen3-32b', name: 'Qwen3 32B', total: 32.8, active: 32.8, layers: 64, hidden: 5120, qHeads: 64, kvHeads: 8, headDim: 128, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3-32B' }, G),
653
+ Object.assign({ id: 'llama33-70b', name: 'Llama 3.3 70B', total: 70.6, active: 70.6, layers: 80, hidden: 8192, qHeads: 64, kvHeads: 8, headDim: 128, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct' }, G),
654
+ Object.assign({ id: 'qwen25-72b', name: 'Qwen2.5 72B', total: 72.7, active: 72.7, layers: 80, hidden: 8192, qHeads: 64, kvHeads: 8, headDim: 128, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen2.5-72B-Instruct' }, G),
655
+ Object.assign({ id: 'llama31-405b', name: 'Llama 3.1 405B', total: 405.9, active: 405.9, layers: 126, hidden: 16384, qHeads: 128, kvHeads: 8, headDim: 128, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/meta-llama/Llama-3.1-405B-Instruct' }, G),
656
+ Object.assign({}, G, { id: 'gpt-oss-120b', name: 'gpt-oss-120b (MoE)', total: 116.8, active: 5.1, layers: 36, hidden: 2880, qHeads: 64, kvHeads: 8, headDim: 64, experts: 128, topk: 4, swaFrac: 0.5, swaWindow: 128, maxCtx: 131072, wprec: 'fp4', source: 'https://huggingface.co/openai/gpt-oss-120b' }),
657
+ Object.assign({}, G, { id: 'mixtral-8x22b', name: 'Mixtral 8x22B (MoE)', total: 141, active: 39, layers: 56, hidden: 6144, qHeads: 48, kvHeads: 8, headDim: 128, experts: 8, topk: 2, maxCtx: 65536, wprec: 'fp8', source: 'https://huggingface.co/mistralai/Mixtral-8x22B-Instruct-v0.1' }),
658
+ Object.assign({}, G, { id: 'qwen3-235b', name: 'Qwen3 235B-A22B (MoE)', total: 235, active: 22, layers: 94, hidden: 4096, qHeads: 64, kvHeads: 4, headDim: 128, experts: 128, topk: 8, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3-235B-A22B' }),
659
+ Object.assign({}, G, { id: 'llama4-maverick', name: 'Llama 4 Maverick 400B (MoE)', total: 400, active: 17, layers: 48, hidden: 5120, qHeads: 40, kvHeads: 8, headDim: 128, experts: 128, topk: 1, swaFrac: 0.75, swaWindow: 8192, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/meta-llama/Llama-4-Maverick-17B-128E-Instruct' }),
660
+ Object.assign({}, G, { id: 'qwen3-coder-480b', name: 'Qwen3-Coder 480B-A35B (MoE)', total: 480, active: 35, layers: 62, hidden: 6144, qHeads: 96, kvHeads: 8, headDim: 128, experts: 160, topk: 8, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3-Coder-480B-A35B-Instruct' }),
661
+ Object.assign({}, G, MLA, { id: 'deepseek-v3', name: 'DeepSeek-V3 / R1 671B (MoE, MLA)', total: 671, active: 37, layers: 61, hidden: 7168, qHeads: 128, experts: 256, topk: 8, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/deepseek-ai/DeepSeek-V3' }),
662
+ Object.assign({}, G, MLA, { id: 'kimi-k2', name: 'Kimi K2 1T (MoE, MLA)', total: 1040, active: 32, layers: 61, hidden: 7168, qHeads: 64, experts: 384, topk: 8, maxCtx: 131072, wprec: 'fp8', source: 'https://huggingface.co/moonshotai/Kimi-K2-Instruct' }),
663
+ // ---- 2026 open-weight models (config.json values; see docs/CATALOG.md for where each figure comes from) ----
664
+ // Kimi K3 (K3.1 Pro shares the architecture): 69 Kimi Delta Attention layers (96 heads × 128 × 128 fp32 state) and
665
+ // 24 gated MLA layers; MXFP4 weights from quantization-aware training.
666
+ Object.assign({}, G, MLA, { id: 'kimi-k3', name: 'Kimi K3 / K3.1 Pro 2.8T-A104B (MoE, KDA + MLA)', total: 2800, active: 104, layers: 93, hidden: 7168, qHeads: 96, experts: 896, topk: 16, linFrac: 69 / 93, linStateMB: 6.29, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/moonshotai/Kimi-K3' }),
667
+ // Kimi K2.5 / K2.6: K2's shape with 256K context and native INT4 weights (sized as 4-bit)
668
+ Object.assign({}, G, MLA, { id: 'kimi-k26', name: 'Kimi K2.6 1T-A32B (MoE, MLA, INT4)', total: 1000, active: 32, layers: 61, hidden: 7168, qHeads: 64, experts: 384, topk: 8, maxCtx: 262144, wprec: 'fp4', source: 'https://huggingface.co/moonshotai/Kimi-K2.6' }),
669
+ // DeepSeek V4: one 512-wide latent per token, kept at 1/4 (CSA) or 1/128 (HCA) on alternating layers (≈ 0.129 on
670
+ // average); CSA attends its index top-1024, HCA all compressed blocks: modelled as 2048 attended tokens per query.
671
+ // Experts in FP4, the rest FP8.
672
+ Object.assign({}, G, MLA, { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro 1.6T-A49B (MoE, compressed sparse attention)', total: 1600, active: 49, layers: 61, hidden: 7168, qHeads: 128, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK: 2048, experts: 384, topk: 6, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro' }),
673
+ Object.assign({}, G, MLA, { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash 284B-A13B (MoE, compressed sparse attention)', total: 284, active: 13, layers: 43, hidden: 4096, qHeads: 64, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK: 2048, experts: 256, topk: 6, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash' }),
674
+ // GLM-5.1 and GLM-5.3: MLA with DeepSeek-style sparse attention (index top-2048); GLM-5.3 extends the context to 1M.
675
+ // GLM-5.3's active parameters are not published: the GLM-5 lineage's 40B is assumed.
676
+ Object.assign({}, G, MLA, { id: 'glm-5.1', name: 'GLM-5.1 744B-A40B (MoE, MLA, sparse)', total: 744, active: 40, layers: 78, hidden: 6144, qHeads: 64, mlaNope: 192, mlaV: 256, sparseTopK: 2048, experts: 256, topk: 8, maxCtx: 202752, wprec: 'fp8', source: 'https://huggingface.co/zai-org/GLM-5.1' }),
677
+ Object.assign({}, G, MLA, { id: 'glm-5.3', name: 'GLM-5.3 753B (MoE, MLA, sparse, 1M)', total: 753, active: 40, layers: 78, hidden: 6144, qHeads: 64, mlaNope: 192, mlaV: 256, sparseTopK: 2048, experts: 256, topk: 8, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/zai-org/GLM-5.3' }),
678
+ // Mistral Large 4: MLA with sparse token selection (top-2048); nope/v head dims not published (DeepSeek's 128 assumed)
679
+ Object.assign({}, G, MLA, { id: 'mistral-large-4', name: 'Mistral Large 4 1.05T-A52B (MoE, MLA, sparse)', total: 1050, active: 52, layers: 72, hidden: 6144, qHeads: 64, sparseTopK: 2048, experts: 128, topk: 4, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/mistralai/Mistral-Large-4-1T-A52B' }),
680
+ // Qwen3.5-397B and Qwen3.8 27B: three Gated DeltaNet layers per gated-attention layer (64 / 48 value heads × 128 × 128 fp32 state)
681
+ Object.assign({}, G, { id: 'qwen35-397b', name: 'Qwen3.5 397B-A17B (MoE, Gated DeltaNet hybrid)', total: 397, active: 17, layers: 60, hidden: 4096, qHeads: 32, kvHeads: 2, headDim: 256, linFrac: 0.75, linStateMB: 4.19, experts: 512, topk: 10, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3.5-397B-A17B' }),
682
+ Object.assign({}, G, { id: 'qwen38-27b', name: 'Qwen3.8 27B (Gated DeltaNet hybrid)', total: 27, active: 27, layers: 64, hidden: 5120, qHeads: 24, kvHeads: 4, headDim: 256, linFrac: 0.75, linStateMB: 3.15, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3.8-27B' }),
683
+ // MiniMax M3: sparse attention (16 blocks of 128 tokens) in 57 of 60 layers, modelled on all of them
684
+ Object.assign({}, G, { id: 'minimax-m3', name: 'MiniMax M3 428B-A23B (MoE, sparse)', total: 428, active: 23, layers: 60, hidden: 6144, qHeads: 64, kvHeads: 4, headDim: 128, sparseTopK: 2048, experts: 128, topk: 4, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/MiniMaxAI/MiniMax-M3' }),
685
+ Object.assign({}, G, { id: 'minimax-m27', name: 'MiniMax M2.7 229B-A10B (MoE)', total: 229, active: 10, layers: 62, hidden: 3072, qHeads: 48, kvHeads: 8, headDim: 128, experts: 256, topk: 8, maxCtx: 204800, wprec: 'fp8', source: 'https://huggingface.co/MiniMaxAI/MiniMax-M2.7' }),
686
+ // Muse Spark Open: 46 sliding-window layers (2048 tokens) and 16 full-attention layers
687
+ Object.assign({}, G, { id: 'muse-spark-open', name: 'Muse Spark Open 816B-A42B (MoE)', total: 816, active: 42, layers: 62, hidden: 8192, qHeads: 128, kvHeads: 16, headDim: 64, swaFrac: 46 / 62, swaWindow: 2048, experts: 256, topk: 8, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B' }),
688
+ // Gemma 4 31B: 50 sliding-window layers (1024 tokens) and 10 global layers with 4 KV heads of 512 and keys reused as
689
+ // values (the KV of 4 × 256 K+V pairs). The sliding layers' 16 heads are sized as 4: their KV is capped at 1024 tokens.
690
+ Object.assign({}, G, { id: 'gemma4-31b', name: 'Gemma 4 31B', total: 30.7, active: 30.7, layers: 60, hidden: 5376, qHeads: 32, kvHeads: 4, headDim: 256, swaFrac: 50 / 60, swaWindow: 1024, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/google/gemma-4-31B' }),
691
+ ];
692
+ const MODEL_DEFAULTS = { attn: 'gqa', experts: 0, topk: 0, swaFrac: 0, swaWindow: 0, linFrac: 0, linStateMB: 0, kvKeep: 1, sparseTopK: 0, mlaLatent: 512, mlaRope: 64, mlaNope: 128, mlaV: 128, wprec: 'fp8' };
693
+ const GPU_DEFAULTS = { tfFp8: 0, tfFp4: 0, nodeKW: 0, price: 0, vendor: '' };
694
+
695
+ // ---------- validation ----------
696
+ const slug = s => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'item';
697
+ function check(entry, fields, defaults, kind) {
698
+ const errors = [];
699
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return { ok: false, errors: [kind + ' entry must be an object.'] };
700
+ const out = Object.assign({}, defaults);
701
+ const nameKey = kind === 'GPU' ? 'label' : 'name';
702
+ out.id = entry.id ? String(entry.id).replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 60) : slug(entry[nameKey]);
703
+ for (const f of fields) {
704
+ let v = entry[f.k];
705
+ if (v === undefined || v === null || v === '') {
706
+ if (f.required) errors.push(`${kind} "${entry[nameKey] || entry.id || '?'}": missing ${f.label} (${f.k}).`);
707
+ continue;
708
+ }
709
+ if (f.type === 'text') { out[f.k] = String(v).slice(0, 300); continue; }
710
+ if (f.type === 'enum') {
711
+ v = String(v).toLowerCase();
712
+ if (!f.opts.includes(v)) { errors.push(`${kind} "${entry[nameKey] || out.id}": ${f.k} must be one of ${f.opts.join(', ')}.`); continue; }
713
+ out[f.k] = v; continue;
714
+ }
715
+ v = Number(v);
716
+ if (!isFinite(v)) { errors.push(`${kind} "${entry[nameKey] || out.id}": ${f.k} must be a number.`); continue; }
717
+ if (f.int) v = Math.round(v);
718
+ if (v < f.min || v > f.max) { errors.push(`${kind} "${entry[nameKey] || out.id}": ${f.k} = ${v} is outside ${f.min}–${f.max}${f.unit ? ' ' + f.unit : ''}.`); continue; }
719
+ out[f.k] = v;
720
+ }
721
+ if (kind === 'Model' && out.active > out.total) errors.push(`Model "${out.name}": active params (${out.active}B) exceed total (${out.total}B).`);
722
+ if (kind === 'Model' && (out.swaFrac || 0) + (out.linFrac || 0) > 1) errors.push(`Model "${out.name}": sliding-window and linear-attention shares add up to more than all layers.`);
723
+ if (kind === 'Model' && out.experts > 0 && !(out.topk > 0 && out.topk < out.experts)) errors.push(`Model "${out.name}": experts per token must be between 1 and ${out.experts - 1}.`);
724
+ if (kind === 'Model' && out.experts > 0 && out.active >= out.total) errors.push(`Model "${out.name}": an MoE model needs active params below total params.`);
725
+ return { ok: errors.length === 0, errors, value: out };
726
+ }
727
+ const validateGPU = g => check(g, GPU_FIELDS, GPU_DEFAULTS, 'GPU');
728
+ const validateModel = m => check(m, MODEL_FIELDS, MODEL_DEFAULTS, 'Model');
729
+
730
+ // ---------- spec sheets ----------
731
+ // A spec sheet is JSON: { "kind": "inference-sizer/catalog", "version": 1, "gpus": [...], "models": [...] }.
732
+ // An entry whose id matches a built-in one replaces it ("update via spec sheet"); new ids are added.
733
+ // A single GPU or model object, or a Hugging Face config.json, is also accepted.
734
+ const SHEET_KIND = 'inference-sizer/catalog';
735
+ function parseSheet(text) {
736
+ let j;
737
+ try { j = typeof text === 'string' ? JSON.parse(text) : text; } catch (e) { return { ok: false, errors: ['Not valid JSON: ' + e.message], gpus: [], models: [] }; }
738
+ const res = { ok: true, errors: [], gpus: [], models: [], notes: [] };
739
+ if (!j || typeof j !== 'object') return { ok: false, errors: ['Expected a JSON object.'], gpus: [], models: [] };
740
+ let gpus = [], models = [];
741
+ if (Array.isArray(j.gpus) || Array.isArray(j.models)) { gpus = j.gpus || []; models = j.models || []; }
742
+ else if (isHFConfig(j)) { const m = fromHFConfig(j); models = [m.model]; res.notes.push(...m.notes); }
743
+ else if ('hbmGB' in j || 'tfBf16' in j) gpus = [j];
744
+ else if ('layers' in j || 'qHeads' in j) models = [j];
745
+ else return { ok: false, errors: ['Could not recognise this file. Use a spec sheet with "gpus" and/or "models" arrays, a single GPU or model entry, or a Hugging Face config.json.'], gpus: [], models: [] };
746
+ for (const g of gpus) { const r = validateGPU(g); if (r.ok) res.gpus.push(r.value); else res.errors.push(...r.errors); }
747
+ for (const m of models) { const r = validateModel(m); if (r.ok) res.models.push(r.value); else res.errors.push(...r.errors); }
748
+ res.ok = res.errors.length === 0 && (res.gpus.length + res.models.length) > 0;
749
+ if (!res.gpus.length && !res.models.length && !res.errors.length) { res.ok = false; res.errors.push('The file holds no GPUs or models.'); }
750
+ return res;
751
+ }
752
+ function makeSheet(gpus, models) {
753
+ const strip = o => { const c = Object.assign({}, o); delete c.builtin; delete c.custom; return c; };
754
+ return { kind: SHEET_KIND, version: 1, gpus: (gpus || []).map(strip), models: (models || []).map(strip) };
755
+ }
756
+ // Built-ins overlaid with user entries (same id replaces).
757
+ function merge(builtin, custom) {
758
+ const out = builtin.map(x => Object.assign({ builtin: true }, x));
759
+ for (const c of custom || []) {
760
+ const i = out.findIndex(x => x.id === c.id);
761
+ const e = Object.assign({ custom: true }, c);
762
+ if (i >= 0) out[i] = Object.assign(e, { overrides: true }); else out.push(e);
763
+ }
764
+ return out;
765
+ }
766
+
767
+ // ---------- Hugging Face config.json ----------
768
+ function isHFConfig(j) {
769
+ const c = j.text_config || j;
770
+ return ('num_hidden_layers' in c || 'n_layer' in c) && ('hidden_size' in c || 'n_embd' in c || 'd_model' in c);
771
+ }
772
+ const first = (o, keys, d) => { for (const k of keys) if (o[k] !== undefined && o[k] !== null) return o[k]; return d; };
773
+ // Reads architecture fields and estimates parameter counts from the layer shapes (embeddings, attention, MLP/experts).
774
+ function fromHFConfig(j) {
775
+ const notes = [];
776
+ const c = j.text_config ? Object.assign({}, j.text_config) : j;
777
+ if (j.text_config) notes.push('Read the text model from text_config.');
778
+ const layers = +first(c, ['num_hidden_layers', 'n_layer', 'num_layers']);
779
+ const hidden = +first(c, ['hidden_size', 'n_embd', 'd_model']);
780
+ const qHeads = +first(c, ['num_attention_heads', 'n_head', 'num_heads']);
781
+ let kvHeads = +first(c, ['num_key_value_heads', 'num_kv_heads', 'n_head_kv'], c.multi_query ? 1 : qHeads);
782
+ const headDim = +first(c, ['head_dim'], Math.round(hidden / qHeads));
783
+ const V = +first(c, ['vocab_size', 'padded_vocab_size'], 32000);
784
+ const inter = +first(c, ['intermediate_size', 'ffn_hidden_size', 'n_inner'], 4 * hidden);
785
+ const experts = +first(c, ['num_local_experts', 'n_routed_experts', 'num_experts', 'moe_num_experts'], 0) || 0;
786
+ const topk = experts ? +first(c, ['num_experts_per_tok', 'experts_per_token', 'moe_top_k', 'num_experts_per_token', 'top_k'], 2) : 0;
787
+ const moeInter = +first(c, ['moe_intermediate_size', 'expert_intermediate_size'], inter);
788
+ const denseInter = +first(c, ['intermediate_size_mlp'], inter);
789
+ const mla = c.kv_lora_rank != null;
790
+ const mlaLatent = mla ? +c.kv_lora_rank : 512, mlaRope = mla ? +first(c, ['qk_rope_head_dim'], 64) : 64;
791
+ const mlaNope = mla ? +first(c, ['qk_nope_head_dim'], 128) : 128, mlaV = mla ? +first(c, ['v_head_dim'], 128) : 128;
792
+ if (mla) kvHeads = 1;
793
+ // sliding window
794
+ let swaFrac = 0, swaWindow = 0;
795
+ if (Array.isArray(c.layer_types) && c.sliding_window) {
796
+ const n = c.layer_types.filter(t => /slid/i.test(String(t))).length;
797
+ swaFrac = +(n / c.layer_types.length).toFixed(3); swaWindow = +c.sliding_window;
798
+ } else if (c.sliding_window && c.use_sliding_window === true) { swaFrac = 1; swaWindow = +c.sliding_window; }
799
+ else if (c.attention_chunk_size && c.no_rope_layers) {
800
+ const n = c.no_rope_layers.filter(x => x).length;
801
+ swaFrac = +(n / c.no_rope_layers.length).toFixed(3); swaWindow = +c.attention_chunk_size;
802
+ notes.push('Chunked-attention layers modelled as sliding-window layers.');
803
+ }
804
+ if (c.sliding_window && !swaFrac) notes.push('sliding_window is set but not enabled for these layers; KV is sized for full attention.');
805
+ // linear-attention layers (Qwen3-Next / Qwen3.5 Gated DeltaNet: layer_types "linear_attention" or full_attention_interval)
806
+ let linFrac = 0, linStateMB = 0;
807
+ const linN = Array.isArray(c.layer_types) ? c.layer_types.filter(t => /linear/i.test(String(t))).length
808
+ : c.full_attention_interval > 1 ? layers - Math.floor(layers / c.full_attention_interval) : 0;
809
+ if (linN) {
810
+ linFrac = +(linN / layers).toFixed(4);
811
+ const vh = +first(c, ['linear_num_value_heads'], qHeads), kd = +first(c, ['linear_key_head_dim'], 128), vd = +first(c, ['linear_value_head_dim'], 128);
812
+ linStateMB = +(vh * kd * vd * 4 / 1e6).toFixed(3);
813
+ notes.push(`${linN} linear-attention layers: a ${linStateMB} MB state per layer per sequence (fp32), no KV per token.`);
814
+ }
815
+ // sparse attention: an index picks the tokens each query attends (DeepSeek Sparse Attention and its descendants)
816
+ const sparseTopK = c.index_topk ? +c.index_topk : 0;
817
+ if (sparseTopK) notes.push(`Sparse attention: each query attends ${sparseTopK} selected tokens.`);
818
+ // context
819
+ let maxCtx = +first(c, ['max_position_embeddings', 'n_positions', 'seq_length', 'max_sequence_length'], 4096);
820
+ const rs = c.rope_scaling;
821
+ if (rs && rs.factor && rs.original_max_position_embeddings) maxCtx = Math.max(maxCtx, Math.round(rs.factor * rs.original_max_position_embeddings));
822
+ // which layers are MoE
823
+ let moeLayers = experts ? layers : 0;
824
+ if (experts && c.first_k_dense_replace != null) moeLayers = layers - c.first_k_dense_replace;
825
+ if (experts && c.interleave_moe_layer_step > 1) moeLayers = Math.floor(layers / c.interleave_moe_layer_step);
826
+ if (experts && c.decoder_sparse_step > 1) moeLayers = Math.floor(layers / c.decoder_sparse_step);
827
+ if (experts && Array.isArray(c.mlp_only_layers)) moeLayers -= c.mlp_only_layers.length;
828
+ if (experts && Array.isArray(c.moe_layers)) moeLayers = c.moe_layers.length;
829
+ const denseLayers = layers - moeLayers;
830
+ // attention params per layer
831
+ let attnP;
832
+ if (mla) {
833
+ const qk = mlaNope + mlaRope;
834
+ const qP = c.q_lora_rank ? hidden * c.q_lora_rank + c.q_lora_rank * qHeads * qk : hidden * qHeads * qk;
835
+ attnP = qP + hidden * (mlaLatent + mlaRope) + mlaLatent * qHeads * (mlaNope + mlaV) + qHeads * mlaV * hidden;
836
+ } else attnP = hidden * qHeads * headDim * 2 + hidden * kvHeads * headDim * 2;
837
+ const gated = !(c.hidden_act === 'gelu' && /gpt2|bloom|opt/.test(c.model_type || ''));
838
+ const mlp = n => (gated ? 3 : 2) * hidden * n;
839
+ const sharedN = +first(c, ['n_shared_experts', 'num_shared_experts'], 0) || 0;
840
+ const sharedInter = c.shared_expert_intermediate_size ? +c.shared_expert_intermediate_size : sharedN * moeInter;
841
+ const llama4Shared = /llama4/.test(c.model_type || '') && experts ? mlp(moeInter) : 0;
842
+ const expertP = mlp(moeInter);
843
+ const tied = j.tie_word_embeddings === true || c.tie_word_embeddings === true;
844
+ const emb = V * hidden * (tied ? 1 : 2);
845
+ const perMoE = experts * expertP + (sharedInter ? mlp(sharedInter) : 0) + llama4Shared + hidden * experts;
846
+ const total = emb + layers * attnP + denseLayers * mlp(denseInter) + moeLayers * perMoE;
847
+ const active = total - moeLayers * (experts - topk) * expertP;
848
+ notes.push('Parameter counts are estimated from layer shapes; check them against the model card.');
849
+ const name = String(first(j, ['_name_or_path', 'name_or_path'], '') || '').split('/').pop() || (c.model_type ? c.model_type + ' ' + (total / 1e9).toFixed(0) + 'B' : 'Imported model');
850
+ const model = {
851
+ name, total: +(total / 1e9).toFixed(2), active: +(active / 1e9).toFixed(2), layers, hidden, qHeads, kvHeads, headDim,
852
+ attn: mla ? 'mla' : 'gqa', mlaLatent, mlaRope, mlaNope, mlaV, experts, topk, swaFrac, swaWindow, linFrac, linStateMB, sparseTopK, maxCtx,
853
+ wprec: /fp8|float8/i.test(JSON.stringify(j.quantization_config || '')) ? 'fp8' : /mxfp4|nvfp4|fp4/i.test(JSON.stringify(j.quantization_config || '')) ? 'fp4' : 'fp8',
854
+ };
855
+ return { model, notes };
856
+ }
857
+
858
+ const api = { GPU_FIELDS, MODEL_FIELDS, GPUS, MODELS, MODEL_DEFAULTS, GPU_DEFAULTS, SHEET_KIND, validateGPU, validateModel, parseSheet, makeSheet, merge, fromHFConfig, isHFConfig, slug };
859
+ if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerCatalog = api;
860
+ })(this);
861
+
862
+ </script>
863
+ <script>
864
+ /* Inference Sizer model: how many GPUs, in what layout, serve a model at TTFT/TPOT targets.
865
+ First-order roofline per layout, M/D/1 queueing for prefill, disaggregated vs aggregated serving.
866
+ Pure functions over one flat input object `s` (model + GPU + traffic + targets + assumptions). See docs/METHOD.md. */
867
+ (function (root) {
868
+ 'use strict';
869
+
870
+ // Engine and traffic defaults. Model and GPU fields come from the catalog entry the user picks.
871
+ const SETTINGS = {
872
+ kvprec: 'fp8', ctx: 32768,
873
+ conc: 500, dau: 50000, rpu: 20, peakFactor: 3, concSource: 'max',
874
+ avgIn: 2000, peakIn: 16000, avgOut: 400, peakOut: 2000,
875
+ ttft: 1000, tpot: 30,
876
+ mode: 'auto', kvPolicy: 'paged', prefixHit: 0,
877
+ memUtil: 0.9, reserveGB: 8,
878
+ effPrefill: 0.40, effDecodeBW: 0.65, effDecodeComp: 0.30, stepMs: 1.5,
879
+ maxSeqPerGPU: 256, headroom: 15, nPlus1: true, kvMaxUtil: 0.9, sloMargin: 10,
880
+ };
881
+
882
+ function derive(s) {
883
+ const bpp = { bf16: 2, fp8: 1.0, fp4: 0.5625 }[s.wprec] || 1;
884
+ const kvb = { bf16: 2, fp8: 1 }[s.kvprec] || 1;
885
+ const isMoE = s.experts > 0 && s.topk > 0 && s.topk < s.experts && s.active < s.total;
886
+ let Eall = 0, dense = s.total;
887
+ if (isMoE) { Eall = Math.min((s.total - s.active) / (1 - s.topk / s.experts), s.total * 0.98); dense = s.total - Eall; }
888
+ const mla = s.attn === 'mla';
889
+ const lat = s.mlaLatent || 512, rope = s.mlaRope == null ? 64 : s.mlaRope, nope = s.mlaNope == null ? 128 : s.mlaNope, vh = s.mlaV || 128;
890
+ const swaLayers = s.swaWindow > 0 ? Math.round(s.layers * (s.swaFrac || 0)) : 0;
891
+ // linear-attention layers (Kimi Delta Attention, Gated DeltaNet): a fixed recurrent state per sequence, no KV per token
892
+ const linLayers = s.linFrac > 0 ? Math.min(s.layers - swaLayers, Math.round(s.layers * s.linFrac)) : 0;
893
+ const linState = linLayers * (s.linStateMB || 0) * 1e6;
894
+ // compressed attention keeps the KV of a share of the tokens (DeepSeek V4: 1/4 or 1/128 per layer); sparse attention
895
+ // (DSA, CSA, MSA) attends a fixed number of selected tokens per query instead of all of them
896
+ const keep = s.kvKeep > 0 && s.kvKeep < 1 ? s.kvKeep : 1, topK = s.sparseTopK > 0 ? s.sparseTopK : 0;
897
+ // tensor-core rate for the weight precision; fall back when the GPU lacks that precision
898
+ const tf = { bf16: s.tfBf16, fp8: s.tfFp8 || s.tfBf16, fp4: s.tfFp4 || s.tfFp8 || s.tfBf16 }[s.wprec] || s.tfBf16;
899
+ const computeFallback = (s.wprec === 'fp4' && !s.tfFp4) ? (s.tfFp8 ? 'fp8' : 'bf16') : (s.wprec === 'fp8' && !s.tfFp8) ? 'bf16' : null;
900
+ return {
901
+ bpp, kvb, isMoE, mla, computeFallback,
902
+ Wd: dense * 1e9 * bpp, We: Eall * 1e9 * bpp,
903
+ denseP: dense * 1e9, activeP: (isMoE ? s.active : s.total) * 1e9,
904
+ kvTokLayer: mla ? (lat + rope) * kvb : 2 * s.kvHeads * s.headDim * kvb,
905
+ swaLayers, linLayers, fullLayers: s.layers - swaLayers - linLayers, win: s.swaWindow || 0, keep, topK, linState,
906
+ // FLOPs per token per linear-attention layer: read and update the state (fp32, 4 bytes an element), ~4 FLOPs an element
907
+ Alin: (s.linStateMB || 0) * 1e6,
908
+ // attention FLOPs per (query token, context token) per layer
909
+ Apre: mla ? s.qHeads * (2 * (nope + rope) + 2 * vh) : 4 * s.qHeads * s.headDim,
910
+ Adec: mla ? s.qHeads * (2 * (lat + rope) + 2 * lat) : 4 * s.qHeads * s.headDim,
911
+ Fw: tf * 1e12, Fa: s.tfBf16 * 1e12,
912
+ BW: s.hbmTBs * 1e12, nvl: s.scaleUpGBs * 1e9 * 0.8, nic: s.nicGbps / 8 * 1e9 * 0.8,
913
+ hbm: s.hbmGB * 1e9 * s.memUtil, reserve: s.reserveGB * 1e9,
914
+ D: Math.max(1, Math.round(s.domain || 8)),
915
+ };
916
+ }
917
+
918
+ // KV bytes one sequence of L tokens holds: full-attention layers keep (a share of) every token, sliding-window layers
919
+ // the last W, linear-attention layers a fixed state
920
+ function kvBytes(md, L) {
921
+ const w = md.win || L, keep = md.keep || 1;
922
+ return md.kvTokLayer * (md.fullLayers * L * keep + md.swaLayers * Math.min(L, w)) + (md.linState || 0);
923
+ }
924
+ // context tokens one query attends in a full-attention layer, and its integral over query positions 0..x
925
+ const attended = (md, L) => { const n = L * (md.keep || 1); return md.topK ? Math.min(n, md.topK) : n; };
926
+ function attendedSum(md, x) {
927
+ const k = md.keep || 1;
928
+ if (!md.topK) return k * x * x / 2;
929
+ const t = md.topK / k;
930
+ return x <= t ? k * x * x / 2 : k * t * t / 2 + md.topK * (x - t);
931
+ }
932
+ function attnPre(md, Lc, L) {
933
+ const W = md.win;
934
+ const g = x => x <= W ? x * x / 2 : W * W / 2 + W * (x - W);
935
+ return md.Apre * (md.fullLayers * (attendedSum(md, L) - attendedSum(md, Lc)) + md.swaLayers * (g(L) - g(Lc))) + (md.linLayers || 0) * (md.Alin || 0) * (L - Lc);
936
+ }
937
+ function attnDec(md, L) { return md.Adec * (md.fullLayers * attended(md, L) + md.swaLayers * Math.min(L, md.win || L)) + (md.linLayers || 0) * (md.Alin || 0); }
938
+
939
+ // ---------- parallel layouts ----------
940
+ // Instances of g GPUs. Inside one scale-up domain (D GPUs): TP, or TP+EP for MoE, or DP-attention+EP for MLA.
941
+ // Larger than a domain: dense models pipeline across domains (TP=D × PP), MoE models use wide EP.
942
+ function configs(s, md) {
943
+ const out = [], D = md.D;
944
+ for (const g of [1, 2, 4, 8, 16, 32, 64]) {
945
+ const inDomain = g <= D;
946
+ if (!inDomain && g % D !== 0) continue;
947
+ let kind;
948
+ if (!md.isMoE) { if (g > 32 && !inDomain) continue; kind = inDomain ? 'TP' : 'TPPP'; }
949
+ else if (md.mla) kind = 'DPEP';
950
+ else kind = inDomain ? 'TPEP' : 'DPEP';
951
+ out.push({ g, kind, pp: kind === 'TPPP' ? g / D : 1, tpl: kind === 'TPPP' ? D : g });
952
+ }
953
+ return out;
954
+ }
955
+ function decodeLabel(c) {
956
+ if (c.g === 1) return '1 GPU';
957
+ if (c.kind === 'TP') return 'TP' + c.g;
958
+ if (c.kind === 'TPPP') return 'TP' + c.tpl + ' × PP' + c.pp;
959
+ if (c.kind === 'TPEP') return 'TP' + c.g + ' · EP' + c.g;
960
+ return 'DP' + c.g + ' attn · EP' + c.g;
961
+ }
962
+
963
+ // ---------- memory (decode-side layout) ----------
964
+ function memInfo(s, md, c) {
965
+ let wGPU, rep, cap, single;
966
+ if (c.kind === 'DPEP') { wGPU = md.Wd + md.We / c.g; rep = 1; }
967
+ else { wGPU = (md.Wd + md.We) / c.g; rep = md.mla ? c.tpl : Math.max(1, c.tpl / s.kvHeads); }
968
+ const avail = md.hbm - md.reserve - wGPU;
969
+ if (c.kind === 'DPEP') { cap = avail * c.g; single = avail; }
970
+ else { cap = avail * c.g / rep; single = cap; }
971
+ const ctxBytes = kvBytes(md, s.ctx);
972
+ const perSeq = s.kvPolicy === 'reserve' ? ctxBytes : kvBytes(md, Math.min(s.ctx, s.avgIn + s.avgOut)) * 1.1;
973
+ const fitsW = avail > 2e9;
974
+ const fitsCtx = fitsW && single >= ctxBytes;
975
+ const Bmem = fitsW ? Math.floor(cap * (s.kvMaxUtil || 1) / perSeq) : 0;
976
+ return { wGPU, rep, avail, cap, single, ctxBytes, perSeq, fitsW, fitsCtx, Bmem };
977
+ }
978
+
979
+ function allreduce(s, md, tp, tokens) {
980
+ if (tp <= 1) return 0;
981
+ const bw = tp <= md.D ? md.nvl : md.nic;
982
+ return 2 * s.layers * (8e-6 + 2 * (tp - 1) / tp * tokens * s.hidden * 2 / bw);
983
+ }
984
+
985
+ // One decode step with B sequences (per micro-batch when pipelined).
986
+ function decodeStep(s, md, c, B) {
987
+ const L = Math.min(s.ctx, s.avgIn + s.avgOut / 2);
988
+ const kvL = kvBytes(md, L);
989
+ const frac = md.isMoE ? 1 - Math.pow(1 - s.topk / s.experts, B) : 1;
990
+ const linF = 2 * md.activeP * B, atF = B * attnDec(md, L);
991
+ let bytes, gl = c.g, comm = 0;
992
+ if (c.kind === 'DPEP') {
993
+ const imb = c.g > 1 ? 1.15 : 1;
994
+ bytes = md.Wd + md.We * frac / c.g * imb + (B / c.g) * kvL;
995
+ const tok = (B / c.g) * s.topk * s.hidden * 1.5;
996
+ if (c.g > 1) comm = c.g <= md.D ? 2 * s.layers * (10e-6 + tok / md.nvl) : 2 * s.layers * (25e-6 + tok / md.nic) * 0.6;
997
+ } else {
998
+ const rep = md.mla ? c.tpl : Math.max(1, c.tpl / s.kvHeads);
999
+ gl = c.tpl;
1000
+ bytes = (md.Wd + md.We * frac) / gl + B * kvL * rep / gl;
1001
+ comm = allreduce(s, md, gl, B) * (c.kind === 'TPEP' ? 1.3 : 1);
1002
+ if (c.kind === 'TPPP') comm += (c.pp - 1) * (15e-6 + B * s.hidden * 2 / md.nic);
1003
+ }
1004
+ const tm = bytes / (md.BW * s.effDecodeBW);
1005
+ const tc = linF / gl / (md.Fw * s.effDecodeComp) + atF / gl / (md.Fa * s.effDecodeComp);
1006
+ const ovh = s.stepMs / 1000;
1007
+ return { t: Math.max(tm, tc) + comm + ovh, tm, tc, comm, ovh, bytes, bound: tm >= tc ? 'memory' : 'compute' };
1008
+ }
1009
+
1010
+ function decodeCap(s, md, c, mi) {
1011
+ return Math.max(0, Math.min(Math.floor(mi.Bmem / c.pp), s.maxSeqPerGPU * c.tpl));
1012
+ }
1013
+ // Largest per-micro-batch B whose step time stays within the TPOT target.
1014
+ function bmax(s, md, c, mi, tpotS) {
1015
+ const cap = decodeCap(s, md, c, mi);
1016
+ if (cap < 1) return { B: 0, limit: 'memory' };
1017
+ if (decodeStep(s, md, c, 1).t > tpotS) return { B: 0, limit: 'latency' };
1018
+ if (decodeStep(s, md, c, cap).t <= tpotS) return { B: cap, limit: cap === Math.floor(mi.Bmem / c.pp) ? 'kv-memory' : 'seq-cap' };
1019
+ let lo = 1, hi = cap;
1020
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (decodeStep(s, md, c, mid).t <= tpotS) lo = mid; else hi = mid; }
1021
+ return { B: lo, limit: 'tpot' };
1022
+ }
1023
+
1024
+ // ---------- prefill: TP inside a domain, context parallel (CP) across domains, EP for MoE ----------
1025
+ function preCfg(md, c) { const tp = Math.min(c.g, md.D); return { g: c.g, tp, cp: Math.max(1, Math.round(c.g / tp)) }; }
1026
+ function prefillLabel(c, md) {
1027
+ const p = preCfg(md, c);
1028
+ let l = p.g === 1 ? '1 GPU' : 'TP' + p.tp + (p.cp > 1 ? ' × CP' + p.cp : '');
1029
+ if (md.isMoE && p.g > 1) l += ' · EP' + p.g;
1030
+ return l;
1031
+ }
1032
+ function prefillTime(s, md, c, Lnew, Lc, n) {
1033
+ const p = preCfg(md, c);
1034
+ const lin = 2 * md.activeP * Lnew * n;
1035
+ const at = n * attnPre(md, Lc, Lc + Lnew);
1036
+ const par = p.cp > 1 ? 0.85 : 1;
1037
+ const tc = lin / p.g / (md.Fw * s.effPrefill * par) + at / p.g / (md.Fa * s.effPrefill * par);
1038
+ const tm = (md.Wd / p.tp + md.We / p.g) / (md.BW * s.effDecodeBW);
1039
+ const tokens = Lnew * n;
1040
+ let comm = allreduce(s, md, p.tp, tokens / p.cp) * 0.5;
1041
+ if (md.isMoE && p.g > 1) comm += 2 * s.layers * (10e-6 + tokens / p.g * s.topk * s.hidden * 1.5 / (p.g > md.D ? md.nic : md.nvl)) * 0.5;
1042
+ if (p.cp > 1) comm += (kvBytes(md, Lc + Lnew) * n * (p.cp - 1) / p.cp / (p.tp * md.nic) + s.layers * 20e-6) * 0.5;
1043
+ return Math.max(tc, tm) + comm + 0.004;
1044
+ }
1045
+ function prefillStats(s, md, c) {
1046
+ const hit = s.prefixHit / 100;
1047
+ const aIn = Math.min(s.avgIn, s.ctx), pIn = Math.min(s.peakIn, s.ctx);
1048
+ const Lavg = Math.max(1, aIn * (1 - hit)), LcA = aIn * hit;
1049
+ const Lpk = Math.max(1, pIn * (1 - hit)), LcP = pIn * hit;
1050
+ const budget = Math.max(Lavg, 8192);
1051
+ const n = budget / Lavg;
1052
+ const tBatch = prefillTime(s, md, c, Lavg, LcA, n);
1053
+ const cap = n * Lavg / tBatch; // new prompt tokens / s
1054
+ const Speak = prefillTime(s, md, c, Lpk, LcP, 1);
1055
+ const p = preCfg(md, c);
1056
+ const wGPU = md.Wd / p.tp + md.We / p.g;
1057
+ const rep = md.mla ? p.tp : Math.max(1, p.tp / s.kvHeads);
1058
+ const avail = md.hbm - md.reserve - wGPU;
1059
+ const fits = avail > 2e9 && kvBytes(md, pIn) * rep / p.g * 2 <= avail;
1060
+ return { cap, Sbatch: tBatch, Speak, Lavg, Lpk, fits, wGPU, avail };
1061
+ }
1062
+ function kvXfer(s, md, gP, L) { return kvBytes(md, L) / (Math.min(md.D, gP) * md.nic) + 0.002; }
1063
+ const mdWait = (rho, S) => rho * S / (2 * (1 - rho));
1064
+
1065
+ // ---------- load ----------
1066
+ // Cs concurrent decode streams to hold at the TPOT target (from "concurrent sessions")
1067
+ // Dtok output tokens/s to deliver (from DAU traffic)
1068
+ // lam request arrivals/s driving prefill
1069
+ function computeLoad(s) {
1070
+ const dur = s.avgOut * s.tpot / 1000 + s.ttft / 1000;
1071
+ const lamDau = s.dau * s.rpu / 86400 * s.peakFactor;
1072
+ const lamConc = s.conc / dur;
1073
+ const useC = s.concSource !== 'dau', useD = s.concSource !== 'conc';
1074
+ const h = 1 + s.headroom / 100;
1075
+ const lam0 = Math.max(useC ? lamConc : 0, useD ? lamDau : 0);
1076
+ const binding = !useD ? 'concurrency' : !useC ? 'DAU' : (lamDau * dur > s.conc ? 'DAU' : 'concurrency');
1077
+ return { dur, lamDau, lamConc, h, binding, Cs: useC ? s.conc * h : 0, Dtok: useD ? lamDau * s.avgOut * h : 0, lam: lam0 * h, lam0 };
1078
+ }
1079
+ // Smallest per-micro-batch B whose throughput pp*B/t(B) reaches `rate`.
1080
+ function minBforRate(c, tfun, rate, capBm) {
1081
+ if (rate <= 0) return 1;
1082
+ const thr = B => c.pp * B / tfun(B);
1083
+ if (thr(capBm) < rate) return Infinity;
1084
+ let lo = 0, hi = capBm;
1085
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (thr(mid) >= rate) hi = mid; else lo = mid; }
1086
+ return hi;
1087
+ }
1088
+
1089
+ // ---------- sizing ----------
1090
+ const fmtMs = t => { const ms = t * 1000; return ms >= 100 ? Math.round(ms) + ' ms' : ms.toFixed(1) + ' ms'; };
1091
+
1092
+ function sizeDisagg(s, md, load, cfgs) {
1093
+ const m = 1 - (s.sloMargin || 0) / 100, T = s.ttft / 1000 * m, P = s.tpot / 1000 * m; // size to targets less the safety margin
1094
+ const pre = cfgs.map(c => {
1095
+ const ps = prefillStats(s, md, c);
1096
+ const xa = kvXfer(s, md, c.g, Math.min(s.avgIn, s.ctx)), xp = kvXfer(s, md, c.g, Math.min(s.peakIn, s.ctx));
1097
+ const r = { c, label: prefillLabel(c, md), ps, xferAvg: xa, xferPeak: xp, feasible: false, why: '' };
1098
+ if (!ps.fits) { r.why = 'weights + prompt KV do not fit'; return r; }
1099
+ if (ps.Speak + xp > T) { r.why = 'peak prompt TTFT ' + fmtMs(ps.Speak + xp) + ' > target'; return r; }
1100
+ const budget = T - xa, S = ps.Sbatch;
1101
+ if (S >= budget) { r.why = 'avg prompt service time exceeds TTFT budget'; return r; }
1102
+ const x = (budget - S) / S, rhoMax = Math.min(0.85, 2 * x / (1 + 2 * x));
1103
+ const need = load.lam * ps.Lavg;
1104
+ const N = Math.max(1, Math.ceil(need / (ps.cap * rhoMax)));
1105
+ const rho = need / (N * ps.cap);
1106
+ Object.assign(r, { feasible: true, N, gpus: N * c.g, rho, rhoMax, ttftAvg: S + mdWait(rho, S) + xa, ttftPeak: ps.Speak + xp });
1107
+ return r;
1108
+ });
1109
+ const dec = cfgs.map(c => {
1110
+ const mi = memInfo(s, md, c);
1111
+ const r = { c, label: decodeLabel(c), mi, feasible: false, why: '' };
1112
+ if (!mi.fitsW) { r.why = 'weights do not fit'; return r; }
1113
+ if (!mi.fitsCtx) { r.why = 'one full-context sequence does not fit'; return r; }
1114
+ const bm = bmax(s, md, c, mi, P);
1115
+ r.bm = bm;
1116
+ if (bm.B < 1) { r.why = bm.limit === 'latency' ? 'TPOT floor ' + fmtMs(decodeStep(s, md, c, 1).t) + ' > target' : 'no KV room'; return r; }
1117
+ const Binst = bm.B * c.pp;
1118
+ const tfun = B => decodeStep(s, md, c, B).t;
1119
+ const thrInst = Binst / tfun(bm.B);
1120
+ const N = Math.max(1, Math.ceil(load.Cs / Binst), Math.ceil(load.Dtok / thrInst));
1121
+ const Bm = Math.max(1, Math.ceil(load.Cs / N / c.pp), minBforRate(c, tfun, load.Dtok / N, bm.B));
1122
+ const st = decodeStep(s, md, c, Bm), Bop = Bm * c.pp;
1123
+ Object.assign(r, { feasible: true, N, gpus: N * c.g, Binst, Bop, st, tpotOp: st.t, thrInst, kvUse: Bop * mi.perSeq / 1.1 / mi.cap });
1124
+ return r;
1125
+ });
1126
+ const best = arr => arr.filter(r => r.feasible).sort((a, b) => a.gpus - b.gpus || a.c.g - b.c.g)[0] || null;
1127
+ return { pre, dec, P: best(pre), D: best(dec) };
1128
+ }
1129
+
1130
+ // Aggregated: each step carries the decode batch plus a prefill chunk sized to keep the step within TPOT.
1131
+ function sizeAgg(s, md, load, cfgs) {
1132
+ const m = 1 - (s.sloMargin || 0) / 100, T = s.ttft / 1000 * m, P = s.tpot / 1000 * m; // size to targets less the safety margin
1133
+ const rows = cfgs.map(c => {
1134
+ const mi = memInfo(s, md, c);
1135
+ const r = { c, label: decodeLabel(c), mi, feasible: false, why: '' };
1136
+ if (!mi.fitsW) { r.why = 'weights do not fit'; return r; }
1137
+ if (!mi.fitsCtx) { r.why = 'one full-context sequence does not fit'; return r; }
1138
+ const capBm = decodeCap(s, md, c, mi), capB = capBm * c.pp;
1139
+ if (capB < 1) { r.why = 'no KV room'; return r; }
1140
+ const ps = prefillStats(s, md, c);
1141
+ if (!ps.fits) { r.why = 'weights + prompt KV do not fit'; return r; }
1142
+ if (ps.Speak + s.stepMs / 1000 > T) { r.why = 'peak prompt TTFT ' + fmtMs(ps.Speak) + ' > target'; return r; }
1143
+ if (decodeStep(s, md, c, 1).t > P) { r.why = 'TPOT floor ' + fmtMs(decodeStep(s, md, c, 1).t) + ' > target'; return r; }
1144
+ const Nmin = Math.max(1, Math.ceil(load.Cs / capB));
1145
+ const Nmax = Math.max(Nmin * 64, 4096);
1146
+ for (let N = Nmin; N <= Nmax; N++) {
1147
+ const fp0 = load.lam * ps.Lavg / N / ps.cap;
1148
+ if (fp0 >= 0.85) continue;
1149
+ const tAvgF = B => { const q = decodeStep(s, md, c, B); return Math.max(q.tm, q.tc / (1 - fp0)) * 1.1 + q.comm + q.ovh; };
1150
+ const Bm = Math.max(1, Math.ceil(load.Cs / N / c.pp), minBforRate(c, tAvgF, load.Dtok / N, capBm));
1151
+ if (!isFinite(Bm) || Bm > capBm) continue;
1152
+ const st = decodeStep(s, md, c, Bm);
1153
+ const Pcore = (P - st.comm - st.ovh) / 1.1;
1154
+ if (Math.max(st.tm, st.tc) >= Pcore) continue;
1155
+ const chunk = (Pcore - st.tc) * ps.cap;
1156
+ const mu = chunk / P;
1157
+ const rArr = load.lam * ps.Lavg / N;
1158
+ const rho = rArr / mu;
1159
+ if (rho >= 0.85) continue;
1160
+ const S = ps.Lavg / mu;
1161
+ const ttftAvg = S + mdWait(rho, S) + P, ttftPeak = ps.Lpk / mu + P;
1162
+ if (ttftAvg > T || ttftPeak > T) continue;
1163
+ const tAvg = Math.min(P, tAvgF(Bm)), Bop = Bm * c.pp;
1164
+ Object.assign(r, { feasible: true, N, gpus: N * c.g, Bop, st, tpotOp: tAvg, ttftAvg, ttftPeak, fp: fp0, rho, chunk, ps, kvUse: Bop * mi.perSeq / 1.1 / mi.cap, thrInst: Bop / tAvg });
1165
+ return r;
1166
+ }
1167
+ r.why = 'no instance count meets both targets';
1168
+ return r;
1169
+ });
1170
+ const best = rows.filter(r => r.feasible).sort((a, b) => a.gpus - b.gpus || a.c.g - b.c.g)[0] || null;
1171
+ return { rows, best };
1172
+ }
1173
+
1174
+ // The operating point of one fixed layout at a fixed concurrency: what an engine running config c with B sequences
1175
+ // in flight delivers, by the same physics sizeAgg uses (each step carries the decode batch plus prefill chunks; the
1176
+ // prefill share fp slows the compute part). For checking the model against measured runs (e.g. InferenceX):
1177
+ // returns TPOT, TTFT, and output tokens/s per GPU.
1178
+ function operatingPoint(s, md, c, B) {
1179
+ const st = decodeStep(s, md, c, B), ps = prefillStats(s, md, c), osl = s.avgOut, isl = Math.min(s.avgIn, s.ctx);
1180
+ // a prefix-cache hit skips that part of the prompt: only the new tokens are prefilled, attending to the cached ones
1181
+ // (as sizeAgg and prefillStats count them; ps.cap is in new tokens per second)
1182
+ const hit = Math.min(0.99, Math.max(0, (s.prefixHit || 0) / 100)), Lnew = Math.max(1, isl * (1 - hit)), Lc = isl - Lnew;
1183
+ let tpot = st.t, ttft = ps.Sbatch, fp = 0;
1184
+ for (let i = 0; i < 50; i++) {
1185
+ const lam = B / (osl * tpot + ttft); // requests/s through this instance
1186
+ fp = Math.min(0.95, lam * Lnew / ps.cap); // share of compute spent on prefill
1187
+ const t = Math.max(st.tm, st.tc / (1 - fp)) * 1.1 + st.comm + st.ovh;
1188
+ // a new prompt is prefilled in chunks between decode steps: its share of each step is what decode leaves
1189
+ const free = Math.max(0.05, 1 - Math.max(st.tm, st.tc) / t);
1190
+ const tt = prefillTime(s, md, c, Lnew, Lc, 1) / free + mdWait(Math.min(0.85, fp), Lnew / ps.cap) + t;
1191
+ if (Math.abs(t - tpot) < 1e-7 && Math.abs(tt - ttft) < 1e-6) { tpot = t; ttft = tt; break; }
1192
+ tpot = t; ttft = tt;
1193
+ }
1194
+ const outPerGpu = B * osl / (osl * tpot + ttft) / c.g;
1195
+ return { tpot, ttft, outPerGpu, prefillShare: fp, bound: st.bound, step: st };
1196
+ }
1197
+
1198
+ // Nodes (scale-up domains) needed: instances that span domains take whole domains; smaller ones pack first-fit-decreasing.
1199
+ function packNodes(pools, D) {
1200
+ const items = [];
1201
+ let whole = 0;
1202
+ for (const p of pools) for (let i = 0; i < p.N; i++) { if (p.g >= D) whole += Math.ceil(p.g / D); else items.push(p.g); }
1203
+ items.sort((a, b) => b - a);
1204
+ const bins = [];
1205
+ for (const g of items) { const b = bins.findIndex(x => x + g <= D); if (b >= 0) bins[b] += g; else bins.push(g); }
1206
+ return whole + bins.length;
1207
+ }
1208
+
1209
+ function plan(s, opts) {
1210
+ opts = opts || {};
1211
+ const md = derive(s);
1212
+ const load = computeLoad(s);
1213
+ const cfgs = configs(s, md);
1214
+ const dis = sizeDisagg(s, md, load, cfgs);
1215
+ const agg = sizeAgg(s, md, load, cfgs);
1216
+ const D = md.D;
1217
+ // N+1: room for one more instance of the largest layout, using free GPUs in existing nodes first
1218
+ const spareFor = pools => s.nPlus1 ? packNodes(pools.concat([{ N: 1, g: Math.max(...pools.map(p => p.g)) }]), D) - packNodes(pools, D) : 0;
1219
+ let disOpt = null, aggOpt = null;
1220
+ if (dis.P && dis.D) {
1221
+ const pools = [{ N: dis.P.N, g: dis.P.c.g }, { N: dis.D.N, g: dis.D.c.g }];
1222
+ const nodes = packNodes(pools, D), sp = spareFor(pools);
1223
+ disOpt = { mode: 'disagg', gpus: dis.P.gpus + dis.D.gpus, nodes, spareNodes: sp, totalNodes: nodes + sp };
1224
+ }
1225
+ if (agg.best) {
1226
+ const pools = [{ N: agg.best.N, g: agg.best.c.g }];
1227
+ const nodes = packNodes(pools, D), sp = spareFor(pools);
1228
+ aggOpt = { mode: 'agg', gpus: agg.best.gpus, nodes, spareNodes: sp, totalNodes: nodes + sp };
1229
+ }
1230
+ const plural = n => n === 1 ? '' : 's', U = D > 8 ? 'rack' : 'node';
1231
+ let chosen = null, reason = '';
1232
+ if (s.mode === 'disagg') { chosen = disOpt; reason = 'Disaggregated serving selected.'; }
1233
+ else if (s.mode === 'agg') { chosen = aggOpt; reason = 'Aggregated serving selected.'; }
1234
+ else if (disOpt && (!aggOpt || disOpt.totalNodes < aggOpt.totalNodes * 0.9)) {
1235
+ chosen = disOpt;
1236
+ reason = aggOpt ? `Disaggregated prefill/decode needs ${aggOpt.totalNodes - disOpt.totalNodes} fewer ${U}${plural(aggOpt.totalNodes - disOpt.totalNodes)} than aggregated (${disOpt.totalNodes} vs ${aggOpt.totalNodes}).` : 'Aggregated serving cannot meet both targets on any layout; splitting prefill and decode can.';
1237
+ } else if (aggOpt) {
1238
+ chosen = aggOpt;
1239
+ reason = disOpt ? (aggOpt.totalNodes <= disOpt.totalNodes ? `Aggregated serving with chunked prefill fits in ${aggOpt.totalNodes} ${U}${plural(aggOpt.totalNodes)} (disaggregated: ${disOpt.totalNodes}), with fewer moving parts.` : `Disaggregation would save under 10% (${disOpt.totalNodes} vs ${aggOpt.totalNodes} ${U}s); aggregated is simpler to run.`) : 'Only aggregated serving meets both targets.';
1240
+ } else if (disOpt) { chosen = disOpt; reason = 'Only disaggregated serving meets both targets.'; }
1241
+ const res = { s, md, load, cfgs, dis, agg, disOpt, aggOpt, chosen, reason };
1242
+ if (chosen) { chosen.nodeGPUs = D; chosen.provGPUs = chosen.totalNodes * D; chosen.kw = chosen.totalNodes * (s.nodeKW || 0); }
1243
+ res.tpotFloor = Math.min(...cfgs.map(c => memInfo(s, md, c).fitsW ? decodeStep(s, md, c, 1).t : Infinity));
1244
+ res.ttftFloor = Math.min(...cfgs.map(c => { const p = prefillStats(s, md, c); return p.fits ? p.Speak : Infinity; }));
1245
+ const reqDay = s.dau * s.rpu;
1246
+ res.econ = { reqDay, inDay: reqDay * s.avgIn, outDay: reqDay * s.avgOut };
1247
+ if (chosen) {
1248
+ const costDay = chosen.provGPUs * 24 * (s.price || 0);
1249
+ res.econ.costDay = costDay;
1250
+ res.econ.perMOut = res.econ.outDay > 0 ? costDay / (res.econ.outDay / 1e6) : NaN;
1251
+ res.econ.avgVsPeak = load.lam > 0 ? (reqDay / 86400) / load.lam : NaN;
1252
+ }
1253
+ if (!opts.noSens) {
1254
+ res.sens = [10, 15, 20, 25, 30, 40, 50, 60, 80, 100].map(tp => {
1255
+ const r = plan(Object.assign({}, s, { tpot: tp }), { noSens: true });
1256
+ return { tpot: tp, gpus: r.chosen ? r.chosen.provGPUs : null };
1257
+ });
1258
+ }
1259
+ return res;
1260
+ }
1261
+
1262
+ const api = { SETTINGS, plan, derive, kvBytes, attnPre, attnDec, decodeStep, memInfo, prefillStats, prefillTime, configs, computeLoad, decodeLabel, prefillLabel, decodeCap, packNodes, operatingPoint };
1263
+ if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerModel = api;
1264
+ })(this);
1265
+
1266
+ </script>
1267
+ <script>
1268
+ /* Suggestions for the Inference Sizer and FleetScope pages: the changes that would change the answer, shown next to it.
1269
+ forSizer re-plans the same request with one change at a time (weight and KV precision, speculative decoding, prefix
1270
+ caching, a shorter context) and keeps the ones that need fewer GPUs. forFleet reads a FleetScope run's first
1271
+ bottleneck and cache numbers and proposes what-ifs the page's Ask box can run in one click.
1272
+ Both are models: `aiinfra assess` on real traces, then fleetops shadow, check them. */
1273
+ (function (root) {
1274
+ 'use strict';
1275
+ // speculative decoding: k drafted tokens verified in one step, E accepted per step at acceptance a. A memory-bound
1276
+ // step barely grows with k+1 tokens; a compute-bound one grows with them (same model as harness-ledger advise).
1277
+ function specFactor(st, opt) {
1278
+ const a = (opt && opt.accept) || 0.7, k = (opt && opt.tokens) || 3;
1279
+ const E = (1 - Math.pow(a, k + 1)) / (1 - a), base = Math.max(st.tm, st.tc) + st.comm + st.ovh;
1280
+ const t = Math.max(st.tm * 1.05, st.tc * (k + 1)) + st.comm + st.ovh + 0.05 * Math.max(st.tm, st.tc);
1281
+ return { E: E, factor: t / E / base };
1282
+ }
1283
+ const HOURS = 730;
1284
+ const gpusOf = r => (r && r.chosen ? r.chosen.provGPUs : null);
1285
+
1286
+ function forSizer(s, r, M) {
1287
+ const base = gpusOf(r), out = [];
1288
+ const tryIt = (id, title, patch, extra) => {
1289
+ let r2; try { r2 = M.plan(Object.assign({}, s, patch), { noSens: true }); } catch (e) { return; }
1290
+ const g = gpusOf(r2);
1291
+ if (g == null || (base != null && g >= base)) return;
1292
+ out.push(Object.assign({ id: id, title: title, before: base, after: g, saved: base != null ? base - g : null,
1293
+ costBefore: base != null && s.price ? base * s.price * HOURS : null, costAfter: s.price ? g * s.price * HOURS : null }, extra));
1294
+ };
1295
+ const wprec = s.wprec || 'bf16';
1296
+ if (wprec === 'bf16' && s.tfFp8) tryIt('fp8-weights', 'FP8 weights', { wprec: 'fp8' }, { risk: 'quality', how: 'vLLM --quantization fp8, or an FP8 checkpoint' });
1297
+ if (wprec !== 'fp4' && s.tfFp4) tryIt('fp4-weights', 'FP4 weights (NVFP4/MXFP4)', { wprec: 'fp4' }, { risk: 'quality', how: 'an NVFP4 or MXFP4 checkpoint' });
1298
+ if (s.kvprec === 'bf16') tryIt('fp8-kv', 'FP8 KV cache', { kvprec: 'fp8' }, { risk: 'quality', how: 'vLLM --kv-cache-dtype fp8' });
1299
+ // speculative decoding on the layout the plan chose, at its operating batch
1300
+ const best = r && r.agg && r.agg.best;
1301
+ if (best && best.c && best.Bop) {
1302
+ try {
1303
+ const md = M.derive(s), st = M.decodeStep(s, md, best.c, Math.max(1, Math.round(best.Bop / (best.c.pp || 1)))), sf = specFactor(st);
1304
+ if (sf.factor < 0.95) tryIt('spec-decode', 'Speculative decoding (3 drafted tokens, 70% acceptance assumed)', { tpot: s.tpot / sf.factor },
1305
+ { risk: 'none', how: 'vLLM --speculative-config (MTP heads where the model has them, else a draft model)', note: `about ${Math.round(100 * (1 - sf.factor))}% faster tokens at this batch` });
1306
+ } catch (e) { /* layout without a decode step: skip */ }
1307
+ }
1308
+ if ((s.prefixHit || 0) < 50 && s.avgIn >= 2000) tryIt('prefix-cache', 'Half of each prompt served from the prefix cache (shared system prompts, agent sessions)', { prefixHit: 50 },
1309
+ { risk: 'none', how: 'stable prompt prefixes, prefix caching on, prefix-aware routing', note: 'measure your real hit rate: aiinfra assess traces/' });
1310
+ const need = (s.peakIn || 0) + (s.peakOut || 0);
1311
+ if (need > 0 && s.ctx > 2 * need) { let c = 4096; while (c < need * 1.25) c *= 2; if (c < s.ctx) tryIt('context', `Serve a ${c >= 1024 ? Math.round(c / 1024) + 'K' : c} context instead of ${Math.round(s.ctx / 1024)}K (your peak request is ${Math.round(need / 1024)}K)`, { ctx: c }, { risk: 'none', how: 'vLLM --max-model-len' }); }
1312
+ return out.sort((a, b) => (b.saved || 0) - (a.saved || 0));
1313
+ }
1314
+
1315
+ // FleetScope: from a run's summary (first bottleneck, cache locality, speculative decoding) to what-ifs for its Ask box.
1316
+ // Titles are short (the tile sits next to the bottleneck, which names the pool); the Ask phrase names it.
1317
+ function forFleet(sum) {
1318
+ const out = [], bf = sum && sum.bottleneck && sum.bottleneck.first, add = (id, title, why, ask) => out.push({ id: id, title: title, why: why, ask: ask || null });
1319
+ if (bf) {
1320
+ const nm = bf.name;
1321
+ if (bf.kind === 'kv') { add('kv-routing', 'Route sessions to the replica that holds their prefix', `${nm}: KV cache full; reuse cuts what each session holds`, 'Turn on KV-aware routing'); add('kv-more', 'Add 2 instances', 'more KV memory in total', `Add 2 instances to ${nm}`); }
1322
+ if (bf.kind === 'compute') { add('compute-more', 'Add 2 instances', `${nm}: compute saturated`, `Add 2 instances to ${nm}`); add('compute-gpu', 'Move to B200', 'more FLOPS per instance', `What if ${nm} moves to B200?`); }
1323
+ if (bf.kind === 'tpot') { add('tpot-spec', 'Speculative decoding', `${nm}: decode batches too large for the TPOT target`, 'Turn on speculative decoding'); add('tpot-more', 'Add 2 instances', 'smaller decode batches each', `Add 2 instances to ${nm}`); }
1324
+ if (bf.kind === 'queue') add('queue-more', 'Add 2 instances', `${nm}: requests queue`, `Add 2 instances to ${nm}`);
1325
+ if (bf.kind === 'cold') add('cold-warm', 'Keep warm capacity', 'requests wait on cold starts: a higher minimum, or weights cached on local NVMe', null);
1326
+ if (bf.kind === 'link' || bf.kind === 'linkdown') add('link', 'Relieve the link', 'link saturated: send less traffic across it, or raise its bandwidth', null);
1327
+ if (bf.kind === 'down') add('down', 'Capacity for the outage', `${nm} lost instances: spare instances elsewhere carry it`, null);
1328
+ }
1329
+ const loc = sum && sum.locality;
1330
+ if (loc && (loc.misses || loc.hits) && loc.cachedShare < 0.5 && !out.some(x => x.id === 'kv-routing')) add('cache-routing', 'Route sessions to the replica that holds their prefix', `only ${Math.round(100 * loc.cachedShare)}% of prompt tokens came from cache`, 'Turn on KV-aware routing');
1331
+ if (!sum || !sum.spec) { if (bf && bf.kind !== 'tpot' && sum && sum.tpotP99 && !out.some(x => x.id === 'tpot-spec')) add('spec', 'Speculative decoding', 'faster tokens at the same GPUs', 'Turn on speculative decoding'); }
1332
+ return out.slice(0, 4);
1333
+ }
1334
+
1335
+ const api = { forSizer: forSizer, forFleet: forFleet, specFactor: specFactor };
1336
+ if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerSuggest = api;
1337
+ })(this);
1338
+
561
1339
  </script>
562
1340
  <script>
563
1341
  /* FleetScope engine: time-stepped fleet simulation for LLM serving and training.
@@ -604,14 +1382,31 @@ button, select, input { font: inherit; color: inherit; }
604
1382
  'llama-405b': { label: 'Llama 3.1 405B', params: 405, active: 405, layers: 126, kvHeads: 8, headDim: 128, mla: 0 },
605
1383
  'moe-671b': { label: 'MoE 671B, 37B active (MLA)', params: 671, active: 37, layers: 61, kvHeads: 0, headDim: 0, mla: 576 }
606
1384
  };
1385
+ // Every other model in the Inference Sizer's catalog (one list for both tools, kept current there). kvScale: the KV a
1386
+ // token holds, averaged over a 32K context, against the plain kvDim × layers figure, so sliding-window, linear-attention
1387
+ // and compressed layers count; it scales with the layers and heads if they are edited.
1388
+ const node = typeof module !== 'undefined' && module.exports;
1389
+ const CAT = node ? require('../../inference-sizer/src/catalog.js') : root.SizerCatalog, SZ = node ? require('../../inference-sizer/src/model.js') : root.SizerModel;
1390
+ const kvDimTotal = m => (m.mla ? m.layers * m.mla : 2 * m.layers * m.kvHeads * m.headDim);
1391
+ for (const k of Object.keys(MODELS)) MODELS[k].kvScale = 1;
1392
+ const IN_LIST = { 'llama31-8b': 'llama-8b', 'llama33-70b': 'llama-70b', 'llama31-405b': 'llama-405b', 'deepseek-v3': 'moe-671b' };
1393
+ if (CAT && SZ) {
1394
+ for (const c of CAT.MODELS) {
1395
+ if (IN_LIST[c.id] || MODELS[c.id]) continue;
1396
+ const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : c.kvHeads, headDim: c.attn === 'mla' ? 0 : c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
1397
+ const md = SZ.derive(Object.assign({}, SZ.SETTINGS, CAT.MODEL_DEFAULTS, c, { kvprec: 'fp8', tfBf16: 1, hbmTBs: 1, scaleUpGBs: 1, nicGbps: 1, hbmGB: 1 }));
1398
+ m.kvScale = +(SZ.kvBytes(md, 32768) / 32768 / kvDimTotal(m)).toFixed(4);
1399
+ MODELS[c.id] = m;
1400
+ }
1401
+ }
607
1402
 
608
1403
  // ---------- performance profile ----------
609
1404
  // tpFixed: GPUs per instance set on the pool (0 or absent = smallest power of two whose share of the weights fits).
610
1405
  function profile(gpuKey, m, tpFixed) {
611
1406
  const G = GPUS[gpuKey];
612
- const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : 1);
1407
+ const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : m.wPrec === 'fp4' ? 0.5625 : 1);
613
1408
  const kvElem = m.kvPrec === 'bf16' ? 2 : 1;
614
- const kvBytesPerToken = m.mla ? m.layers * m.mla * kvElem : 2 * m.layers * m.kvHeads * m.headDim * kvElem;
1409
+ const kvBytesPerToken = kvDimTotal(m) * kvElem * (m.kvScale > 0 ? m.kvScale : 1);
615
1410
  let tp = 1;
616
1411
  if (tpFixed > 0) tp = Math.round(tpFixed);
617
1412
  else while (tp < 16 && wBytes / tp > 0.65 * G.hbm * 1e9) tp *= 2;
@@ -4205,9 +5000,19 @@ function renderKpis() {
4205
5000
  t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
4206
5001
  t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
4207
5002
  }
5003
+ // what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
5004
+ if (s.requests && window.SizerSuggest) {
5005
+ const tries = SizerSuggest.forFleet(s);
5006
+ if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
5007
+ ? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
5008
+ : '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
5009
+ }
4208
5010
  $('#kpis').innerHTML = tiles.join('');
4209
5011
  }
4210
- $('#kpis').addEventListener('click', e => { const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek); });
5012
+ $('#kpis').addEventListener('click', e => {
5013
+ const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
5014
+ const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
5015
+ });
4211
5016
 
4212
5017
  // ---------- charts ----------
4213
5018
  const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };