neurarch 0.1.2 → 0.2.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.
package/engine.bundle.mjs CHANGED
@@ -4313,7 +4313,7 @@ var require_react_dom_production_min = __commonJS({
4313
4313
  null !== b && (b.selected = true);
4314
4314
  }
4315
4315
  }
4316
- function gb2(a, b) {
4316
+ function gb3(a, b) {
4317
4317
  if (null != b.dangerouslySetInnerHTML) throw Error(p(91));
4318
4318
  return A({}, b, { value: void 0, defaultValue: void 0, children: "" + a._wrapperState.initialValue });
4319
4319
  }
@@ -7885,8 +7885,8 @@ var require_react_dom_production_min = __commonJS({
7885
7885
  f = [];
7886
7886
  break;
7887
7887
  case "textarea":
7888
- e = gb2(a, e);
7889
- d = gb2(a, d);
7888
+ e = gb3(a, e);
7889
+ d = gb3(a, d);
7890
7890
  f = [];
7891
7891
  break;
7892
7892
  default:
@@ -8115,7 +8115,7 @@ var require_react_dom_production_min = __commonJS({
8115
8115
  break;
8116
8116
  case "textarea":
8117
8117
  hb(a, d);
8118
- e = gb2(a, d);
8118
+ e = gb3(a, d);
8119
8119
  D("invalid", a);
8120
8120
  break;
8121
8121
  default:
@@ -32679,15 +32679,15 @@ async function fetchDiffusersConfig(modelId) {
32679
32679
  const subResp = await fetch(`https://huggingface.co/${modelId}/resolve/main/${denoiser}/config.json`);
32680
32680
  if (!subResp.ok) return null;
32681
32681
  const raw = await subResp.json();
32682
- const num4 = (...keys) => {
32682
+ const num5 = (...keys) => {
32683
32683
  for (const k of keys) if (typeof raw[k] === "number") return raw[k];
32684
32684
  return void 0;
32685
32685
  };
32686
32686
  const className = raw._class_name || (Array.isArray(mi[denoiser]) ? mi[denoiser][1] : void 0) || (denoiser === "unet" ? "UNet2DConditionModel" : "Transformer2DModel");
32687
- const heads = num4("num_attention_heads");
32688
- const headDim = num4("attention_head_dim");
32689
- const hidden = (heads && headDim ? heads * headDim : void 0) ?? num4("inner_dim", "cross_attention_dim", "hidden_size", "caption_channels", "joint_attention_dim") ?? 1152;
32690
- const layers = denoiser === "transformer" ? num4("num_layers", "num_hidden_layers", "depth") ?? 12 : void 0;
32687
+ const heads = num5("num_attention_heads");
32688
+ const headDim = num5("attention_head_dim");
32689
+ const hidden = (heads && headDim ? heads * headDim : void 0) ?? num5("inner_dim", "cross_attention_dim", "hidden_size", "caption_channels", "joint_attention_dim") ?? 1152;
32690
+ const layers = denoiser === "transformer" ? num5("num_layers", "num_hidden_layers", "depth") ?? 12 : void 0;
32691
32691
  const config = normalizeAndAugmentConfig({
32692
32692
  model_type: denoiser === "unet" ? "unet" : "dit",
32693
32693
  architectures: [className],
@@ -32697,23 +32697,23 @@ async function fetchDiffusersConfig(modelId) {
32697
32697
  // Use the model's real FFN width when it ships one (Wan: ffn_dim 8960,
32698
32698
  // not hidden×4 = 6144 — the hardcoded ×4 undercounted the MLP by ~260M
32699
32699
  // across 30 layers). Falls back to ×4 only when no width is declared.
32700
- intermediate_size: num4("ffn_dim", "intermediate_size", "d_ff", "mlp_dim", "mlp_ratio") ?? hidden * 4
32700
+ intermediate_size: num5("ffn_dim", "intermediate_size", "d_ff", "mlp_dim", "mlp_ratio") ?? hidden * 4
32701
32701
  }, modelId);
32702
32702
  const c = config;
32703
32703
  c._diffusion = true;
32704
32704
  c._denoiser = denoiser;
32705
32705
  c._diffuser_class = className;
32706
- c.in_channels = num4("in_channels") ?? 4;
32707
- c.sample_size = num4("sample_size") ?? 64;
32708
- c.patch_size = num4("patch_size") ?? 2;
32709
- c.cross_attention_dim = num4("cross_attention_dim", "caption_channels", "joint_attention_dim", "text_dim", "text_embed_dim");
32706
+ c.in_channels = num5("in_channels") ?? 4;
32707
+ c.sample_size = num5("sample_size") ?? 64;
32708
+ c.patch_size = num5("patch_size") ?? 2;
32709
+ c.cross_attention_dim = num5("cross_attention_dim", "caption_channels", "joint_attention_dim", "text_dim", "text_embed_dim");
32710
32710
  if (Array.isArray(raw.block_out_channels)) c.block_out_channels = raw.block_out_channels;
32711
32711
  if (typeof raw.layers_per_block === "number") c.layers_per_block = raw.layers_per_block;
32712
32712
  const classLower = className.toLowerCase();
32713
32713
  if (/sd3|stablediffusion3|sd35|\bflux\b|mmdit/.test(classLower) || typeof raw.joint_attention_dim === "number") {
32714
32714
  c._mmdit = true;
32715
32715
  }
32716
- const singleLayers = num4("num_single_layers");
32716
+ const singleLayers = num5("num_single_layers");
32717
32717
  if (singleLayers != null) c._num_single_layers = singleLayers;
32718
32718
  if (mi.vae) {
32719
32719
  try {
@@ -38538,14 +38538,14 @@ var hugeLinearParams = (model) => {
38538
38538
  if (!Number.isFinite(inF) || !Number.isFinite(outF) || inF <= 0 || outF <= 0) continue;
38539
38539
  const count = inF * outF;
38540
38540
  if (count > LARGE_LINEAR_MAX_PARAMS) {
38541
- const gb2 = (count * 4 / 1073741824).toFixed(1);
38541
+ const gb3 = (count * 4 / 1073741824).toFixed(1);
38542
38542
  issues.push({
38543
38543
  id: `huge-linear-${c.id}`,
38544
38544
  ruleId: "huge-linear-params",
38545
38545
  severity: "warning",
38546
38546
  category: "performance",
38547
38547
  title: `Very large Linear: "${c.name}" (~${Math.round(count / 1e6)}M params)`,
38548
- message: `Linear "${c.name}" is ${inF} \xD7 ${outF} = ${Math.round(count / 1e6)}M parameters (~${gb2} GB float32). A single dense layer this large usually means a feature map was flattened without pooling first; embedding / vocab-projection heads are the expected exception.`,
38548
+ message: `Linear "${c.name}" is ${inF} \xD7 ${outF} = ${Math.round(count / 1e6)}M parameters (~${gb3} GB float32). A single dense layer this large usually means a feature map was flattened without pooling first; embedding / vocab-projection heads are the expected exception.`,
38549
38549
  affectedIds: [c.id],
38550
38550
  suggestion: "Add a Global Average Pool or more downsampling before the Linear, or factorize it (low-rank / bottleneck projection)."
38551
38551
  });
@@ -40281,7 +40281,7 @@ function buildPreflightReport(model, opts) {
40281
40281
  const outShape = shapes.get(c.id)?.out;
40282
40282
  flops += estimateLayerFlops(c.type, c.params, inShape ?? [], outShape ?? []) ?? 0;
40283
40283
  }
40284
- const weightBytes = params * 4;
40284
+ const weightBytes2 = params * 4;
40285
40285
  const trainFootprintBytes = params * 16;
40286
40286
  const footprintGb = trainFootprintBytes / 1e9;
40287
40287
  const gpu = PREFLIGHT_GPUS.find((g) => g.name === opts?.plan?.gpu) ?? PREFLIGHT_GPUS[2];
@@ -40359,7 +40359,7 @@ function buildPreflightReport(model, opts) {
40359
40359
  layers: realLayers.length,
40360
40360
  params,
40361
40361
  flops,
40362
- weightBytes,
40362
+ weightBytes: weightBytes2,
40363
40363
  trainFootprintBytes,
40364
40364
  fitsGpu: gpu.name,
40365
40365
  estTrainSec,
@@ -41460,7 +41460,7 @@ function evaluateChangeSpec(model, spec, problems, ctx) {
41460
41460
  }
41461
41461
  }
41462
41462
  const precision = spec.quant?.precision ?? "fp16";
41463
- const weightBytes = ctx.params > 0 ? computeQuantPreview(model).totalBytes[precision] : null;
41463
+ const weightBytes2 = ctx.params > 0 ? computeQuantPreview(model).totalBytes[precision] : null;
41464
41464
  let adapterMatch = null;
41465
41465
  if (spec.adapter && ctx.lora && (spec.adapter.pattern || spec.adapter.targets.length)) {
41466
41466
  adapterMatch = checkLoraTargets(model, spec.adapter.pattern ?? spec.adapter.targets, ctx.lora);
@@ -41497,14 +41497,14 @@ function evaluateChangeSpec(model, spec, problems, ctx) {
41497
41497
  });
41498
41498
  }
41499
41499
  let servingFits = null;
41500
- if (spec.serving && weightBytes != null) {
41500
+ if (spec.serving && weightBytes2 != null) {
41501
41501
  const gpu = resolveGpu(spec.serving.gpu);
41502
41502
  if (!gpu) warnings.push({ title: `change: unknown serving GPU (${spec.serving.gpu})`, detail: `Known: ${GPU_HARDWARE.map((g) => g.id).join(", ")}.`, stage: "change" });
41503
41503
  else {
41504
41504
  const kvBytesPerToken = kvBytesPerTokenForModel(model, 2, spec.serving.promptTokens + spec.serving.genTokens);
41505
41505
  const sp = planServing({
41506
41506
  gpu,
41507
- weightBytes,
41507
+ weightBytes: weightBytes2,
41508
41508
  kvBytesPerToken,
41509
41509
  stateBytesPerRequest: recurrentStateBytesForModel(model, 2),
41510
41510
  flopsPerToken: 2 * ctx.params,
@@ -41515,7 +41515,7 @@ function evaluateChangeSpec(model, spec, problems, ctx) {
41515
41515
  servingFits = sp.fits;
41516
41516
  if (!sp.fits) {
41517
41517
  blockers.push({
41518
- title: `change: serving target ${gpu.label} does not fit (${precision} weights ${(weightBytes / 1e9).toFixed(1)} GB plus KV for batch ${spec.serving.batchSize} at ${spec.serving.promptTokens + spec.serving.genTokens} tokens)`,
41518
+ title: `change: serving target ${gpu.label} does not fit (${precision} weights ${(weightBytes2 / 1e9).toFixed(1)} GB plus KV for batch ${spec.serving.batchSize} at ${spec.serving.promptTokens + spec.serving.genTokens} tokens)`,
41519
41519
  detail: `serving: ${spec.serving.gpu}`,
41520
41520
  stage: "change"
41521
41521
  });
@@ -41526,7 +41526,7 @@ function evaluateChangeSpec(model, spec, problems, ctx) {
41526
41526
  specId: changeSpecId(spec, ctx.baseFingerprint),
41527
41527
  baseFingerprint: ctx.baseFingerprint,
41528
41528
  spec,
41529
- estimates: { trainableParams, trainMemGb, weightBytes, servingFits },
41529
+ estimates: { trainableParams, trainMemGb, weightBytes: weightBytes2, servingFits },
41530
41530
  gate: { ok: blockers.length === 0, blockers, warnings },
41531
41531
  adapterMatch,
41532
41532
  problems
@@ -41593,7 +41593,7 @@ function readPolicy(input) {
41593
41593
  const raw = input;
41594
41594
  const policy = {};
41595
41595
  const problems = [];
41596
- const num4 = (k) => {
41596
+ const num5 = (k) => {
41597
41597
  const v = raw[k];
41598
41598
  if (v == null) return void 0;
41599
41599
  const n2 = typeof v === "string" ? Number(v) : v;
@@ -41621,11 +41621,11 @@ function readPolicy(input) {
41621
41621
  if (typeof raw.must_fit !== "string") problems.push("must_fit: expected a GPU name like A100-40GB");
41622
41622
  else policy.must_fit = raw.must_fit;
41623
41623
  }
41624
- const mm = num4("max_memory_gb");
41624
+ const mm = num5("max_memory_gb");
41625
41625
  if (mm != null) policy.max_memory_gb = mm;
41626
- const ml = num4("max_layers");
41626
+ const ml = num5("max_layers");
41627
41627
  if (ml != null) policy.max_layers = ml;
41628
- const mc = num4("max_cost_usd");
41628
+ const mc = num5("max_cost_usd");
41629
41629
  if (mc != null) policy.max_cost_usd = mc;
41630
41630
  const ft = list2("forbid_types");
41631
41631
  if (ft) policy.forbid_types = ft;
@@ -41738,10 +41738,10 @@ function upperPeakGb(peakGb) {
41738
41738
  if (!(peakGb > 0)) return 0;
41739
41739
  return Math.max(peakGb * UPPER_K, UPPER_FLOOR_GB);
41740
41740
  }
41741
- function fitVerdict(peakGb, params, gb2) {
41741
+ function fitVerdict(peakGb, params, gb3) {
41742
41742
  if (params <= 0) return null;
41743
- if (upperPeakGb(peakGb) * FIT_HEADROOM <= gb2) return "fits";
41744
- return peakGb <= gb2 ? "borderline" : "does_not_fit";
41743
+ if (upperPeakGb(peakGb) * FIT_HEADROOM <= gb3) return "fits";
41744
+ return peakGb <= gb3 ? "borderline" : "does_not_fit";
41745
41745
  }
41746
41746
  var MIG_PROFILES = {
41747
41747
  A100_40: [{ name: "1g.5gb", gb: 5 }, { name: "1g.10gb", gb: 10 }, { name: "2g.10gb", gb: 10 }, { name: "3g.20gb", gb: 20 }, { name: "4g.20gb", gb: 20 }, { name: "7g.40gb", gb: 40 }],
@@ -41848,12 +41848,12 @@ function attentionElemsFor(model, shapes) {
41848
41848
  return eager == null || sdpa == null ? 0 : Math.max(0, eager - sdpa);
41849
41849
  }
41850
41850
  var FIT_HEADROOM = 1.15;
41851
- function maxBatchFor(f, gb2) {
41851
+ function maxBatchFor(f, gb3) {
41852
41852
  const per = f.activationPerSampleGb;
41853
- if (per == null || !(per > 0) || !(gb2 > 0)) return null;
41854
- const fits = (b2) => (f.footprintGb + (f.activationGbAt ? f.activationGbAt(b2) : per * b2)) * FIT_HEADROOM <= gb2;
41853
+ if (per == null || !(per > 0) || !(gb3 > 0)) return null;
41854
+ const fits = (b2) => (f.footprintGb + (f.activationGbAt ? f.activationGbAt(b2) : per * b2)) * FIT_HEADROOM <= gb3;
41855
41855
  if (!fits(1)) return null;
41856
- let b = Math.max(1, Math.floor((gb2 / FIT_HEADROOM - f.footprintGb) / per));
41856
+ let b = Math.max(1, Math.floor((gb3 / FIT_HEADROOM - f.footprintGb) / per));
41857
41857
  while (b > 1 && !fits(b)) b--;
41858
41858
  while (fits(b + 1)) b++;
41859
41859
  return b;
@@ -41925,13 +41925,13 @@ function deviceMapFor(model, gpus, opts = {}) {
41925
41925
  function twoCardSplitFor(model, peakGb, params, batchSize, attention) {
41926
41926
  if (params <= 0) return null;
41927
41927
  const sizes = [...new Set(PREFLIGHT_GPUS.map((g) => g.gb))].sort((a, b) => a - b);
41928
- for (const gb2 of sizes) {
41929
- if (peakGb * FIT_HEADROOM <= gb2) return null;
41930
- if (peakGb * FIT_HEADROOM > 2 * gb2) continue;
41931
- const map = deviceMapFor(model, [gb2, gb2], { batchSize, attention });
41928
+ for (const gb3 of sizes) {
41929
+ if (peakGb * FIT_HEADROOM <= gb3) return null;
41930
+ if (peakGb * FIT_HEADROOM > 2 * gb3) continue;
41931
+ const map = deviceMapFor(model, [gb3, gb3], { batchSize, attention });
41932
41932
  if (map.fits) {
41933
- const gpu = PREFLIGHT_GPUS.find((g) => g.gb === gb2).name;
41934
- return { gpu, gbPerCard: gb2, ...map };
41933
+ const gpu = PREFLIGHT_GPUS.find((g) => g.gb === gb3).name;
41934
+ return { gpu, gbPerCard: gb3, ...map };
41935
41935
  }
41936
41936
  }
41937
41937
  return null;
@@ -41976,9 +41976,9 @@ function factsFor(model, workload, run, attention = DEFAULT_ATTENTION) {
41976
41976
  seqLen: tokenSeqLenOf(model)
41977
41977
  };
41978
41978
  }
41979
- function fitsCard(peakGb, params, gb2) {
41979
+ function fitsCard(peakGb, params, gb3) {
41980
41980
  if (params <= 0) return null;
41981
- return peakGb * FIT_HEADROOM <= gb2;
41981
+ return peakGb * FIT_HEADROOM <= gb3;
41982
41982
  }
41983
41983
  function smallestSafeCardFor(peakGb, params) {
41984
41984
  return PREFLIGHT_GPUS.find((g) => fitVerdict(peakGb, params, g.gb) === "fits")?.name ?? null;
@@ -42435,21 +42435,21 @@ function loraTargetsFor(model, shapesIn) {
42435
42435
  const ms = modules.filter(pick);
42436
42436
  const r8 = ms.reduce((a, m) => a + m.lora.r8, 0);
42437
42437
  const r16 = ms.reduce((a, m) => a + m.lora.r16, 0);
42438
- const pct = (x) => baseParams > 0 ? x / baseParams * 100 : 0;
42438
+ const pct2 = (x) => baseParams > 0 ? x / baseParams * 100 : 0;
42439
42439
  return {
42440
42440
  targetModules: [...new Set(ms.map((m) => m.module))],
42441
42441
  modules: ms.length,
42442
42442
  loraParams: { r8, r16 },
42443
- pctOfBase: { r8: pct(r8), r16: pct(r16) }
42443
+ pctOfBase: { r8: pct2(r8), r16: pct2(r16) }
42444
42444
  };
42445
42445
  };
42446
- const ATTN = /* @__PURE__ */ new Set(["q_proj", "k_proj", "v_proj", "o_proj"]);
42446
+ const ATTN2 = /* @__PURE__ */ new Set(["q_proj", "k_proj", "v_proj", "o_proj"]);
42447
42447
  return {
42448
42448
  baseParams,
42449
42449
  modules,
42450
42450
  byRole,
42451
42451
  presets: {
42452
- attention: preset((m) => ATTN.has(m.role)),
42452
+ attention: preset((m) => ATTN2.has(m.role)),
42453
42453
  allLinear: preset((m) => m.role !== "head")
42454
42454
  },
42455
42455
  uncovered
@@ -42476,11 +42476,11 @@ function trainingPeakFor(p, adapter) {
42476
42476
  return { trainableParams: Math.round(adapterParams), peakGb };
42477
42477
  }
42478
42478
  function renderLoraText(lora) {
42479
- const pct = (x) => x < 0.01 ? "<0.01%" : `${x.toFixed(2)}%`;
42479
+ const pct2 = (x) => x < 0.01 ? "<0.01%" : `${x.toFixed(2)}%`;
42480
42480
  const L = [];
42481
42481
  L.push(`LoRA targets base ${fmtParamCount(lora.baseParams)} params, ${lora.modules.length} linear module${lora.modules.length === 1 ? "" : "s"}`);
42482
42482
  const row = (label, pr) => {
42483
- L.push(` ${label.padEnd(11)} r=8 +${fmtParamCount(pr.loraParams.r8)} (${pct(pr.pctOfBase.r8)}) r=16 +${fmtParamCount(pr.loraParams.r16)} (${pct(pr.pctOfBase.r16)}) over ${pr.modules} module${pr.modules === 1 ? "" : "s"}`);
42483
+ L.push(` ${label.padEnd(11)} r=8 +${fmtParamCount(pr.loraParams.r8)} (${pct2(pr.pctOfBase.r8)}) r=16 +${fmtParamCount(pr.loraParams.r16)} (${pct2(pr.pctOfBase.r16)}) over ${pr.modules} module${pr.modules === 1 ? "" : "s"}`);
42484
42484
  L.push(` ${"".padEnd(11)} target_modules=${JSON.stringify(pr.targetModules)}`);
42485
42485
  };
42486
42486
  row("attention", lora.presets.attention);
@@ -43752,34 +43752,34 @@ function sizingFor(model, plan) {
43752
43752
  const serveTokens = Math.min(SERVE_TOKENS, ctx ?? SERVE_TOKENS);
43753
43753
  const inf = ctx == null ? null : inferencePeakFor(model, { batch: 1, promptTokens: serveTokens, genTokens: 0, precision: "bf16" });
43754
43754
  const serve = inf ? { tokens: serveTokens, weightsGb: inf.weightsGb, kvPerSequenceGb: inf.kvPerSequenceGb, statePerSequenceGb: inf.stateBytesPerSequence / 1e9 } : null;
43755
- const train = (fixed, gb2) => {
43755
+ const train = (fixed, gb3) => {
43756
43756
  if (fixed == null || perSample == null) return { kind: "unknown" };
43757
- const b = maxBatchFor({ footprintGb: fixed, activationPerSampleGb: perSample }, gb2);
43758
- const upper = maxBatchFor({ footprintGb: fixed * UPPER_K, activationPerSampleGb: perSample * UPPER_K }, gb2);
43757
+ const b = maxBatchFor({ footprintGb: fixed, activationPerSampleGb: perSample }, gb3);
43758
+ const upper = maxBatchFor({ footprintGb: fixed * UPPER_K, activationPerSampleGb: perSample * UPPER_K }, gb3);
43759
43759
  return b == null ? { kind: "none" } : { kind: "batch", batch: b, upperBatch: upper };
43760
43760
  };
43761
- const cards = SIZING_CARDS.map(({ label, gb: gb2 }) => {
43762
- let full = train(fullFixedGb, gb2);
43763
- if (full.kind === "none" && perSample != null && (fullFixedGb + perSample) * FIT_HEADROOM <= 2 * gb2) {
43764
- const map = deviceMapFor(withSeqLen(model, c.seqLen).model, [gb2, gb2], { batchSize: 1, attention: c.attention });
43761
+ const cards = SIZING_CARDS.map(({ label, gb: gb3 }) => {
43762
+ let full = train(fullFixedGb, gb3);
43763
+ if (full.kind === "none" && perSample != null && (fullFixedGb + perSample) * FIT_HEADROOM <= 2 * gb3) {
43764
+ const map = deviceMapFor(withSeqLen(model, c.seqLen).model, [gb3, gb3], { batchSize: 1, attention: c.attention });
43765
43765
  if (map.fits && map.splits.length === 2) full = { kind: "split", first: map.splits[0].layers, second: map.splits[1].layers };
43766
43766
  }
43767
43767
  let srv = { kind: "unknown" };
43768
43768
  if (serve) {
43769
43769
  const per = serve.kvPerSequenceGb + serve.statePerSequenceGb;
43770
- if ((serve.weightsGb + per) * FIT_HEADROOM > gb2) srv = { kind: "none" };
43770
+ if ((serve.weightsGb + per) * FIT_HEADROOM > gb3) srv = { kind: "none" };
43771
43771
  else if (per > 0) {
43772
- let b = Math.max(1, Math.floor((gb2 / FIT_HEADROOM - serve.weightsGb) / per));
43773
- while (b > 1 && (serve.weightsGb + per * b) * FIT_HEADROOM > gb2) b--;
43772
+ let b = Math.max(1, Math.floor((gb3 / FIT_HEADROOM - serve.weightsGb) / per));
43773
+ while (b > 1 && (serve.weightsGb + per * b) * FIT_HEADROOM > gb3) b--;
43774
43774
  srv = { kind: "batch", batch: b };
43775
43775
  }
43776
43776
  }
43777
- return { label, gb: gb2, full, lora: train(loraFixedGb, gb2), serve: srv };
43777
+ return { label, gb: gb3, full, lora: train(loraFixedGb, gb3), serve: srv };
43778
43778
  });
43779
43779
  const fullBatch1Gb = perSample == null ? null : fullFixedGb + perSample;
43780
43780
  const loraBatch1Gb = loraFixedGb == null || perSample == null ? null : loraFixedGb + perSample;
43781
43781
  const serveBatch1Gb = serve ? serve.weightsGb + serve.kvPerSequenceGb + serve.statePerSequenceGb : null;
43782
- const floor = (job, gb2) => gb2 == null || cards.some((x) => x[job].kind === "batch" || x[job].kind === "split") ? null : { h200: Math.ceil(gb2 * FIT_HEADROOM / 141), gb80: Math.ceil(gb2 * FIT_HEADROOM / 80) };
43782
+ const floor = (job, gb3) => gb3 == null || cards.some((x) => x[job].kind === "batch" || x[job].kind === "split") ? null : { h200: Math.ceil(gb3 * FIT_HEADROOM / 141), gb80: Math.ceil(gb3 * FIT_HEADROOM / 80) };
43783
43783
  return {
43784
43784
  trainSeqLen: c.seqLen,
43785
43785
  fullBatch1Gb,
@@ -43903,10 +43903,11 @@ function inputContractOf(model, config) {
43903
43903
  const first = (t) => comps.find((c) => c.type === t);
43904
43904
  const source = {};
43905
43905
  const emb = first("embedding");
43906
- const vocabSize = posInt2(emb?.params?.vocabSize);
43906
+ const vocabSize = posInt2(emb?.params?.vocabSize) ?? posInt2(emb?.params?.numEmbeddings);
43907
43907
  if (vocabSize != null) source.vocabSize = "the token embedding";
43908
43908
  const patch = first("patchEmbed");
43909
43909
  const learned = first("learnedPositionalEmbedding");
43910
+ const sinusoidal = first("positionalEncoding");
43910
43911
  let maxPositions = null;
43911
43912
  let positionKind = null;
43912
43913
  if (!patch) {
@@ -43914,6 +43915,10 @@ function inputContractOf(model, config) {
43914
43915
  maxPositions = posInt2(learned.params?.maxLen);
43915
43916
  positionKind = "learned";
43916
43917
  source.maxPositions = "the learned position table";
43918
+ } else if (sinusoidal && posInt2(sinusoidal.params?.maxLen) != null) {
43919
+ maxPositions = posInt2(sinusoidal.params?.maxLen);
43920
+ positionKind = "buffer";
43921
+ source.maxPositions = "the positional encoding buffer";
43917
43922
  } else if (posInt2(emb?.params?.maxSeqLen) != null) {
43918
43923
  maxPositions = posInt2(emb?.params?.maxSeqLen);
43919
43924
  positionKind = comps.some((c) => c.type === "rope") ? "rotary" : "declared";
@@ -43960,12 +43965,12 @@ function checkDataFit(contract, data) {
43960
43965
  } else {
43961
43966
  checked.push("sequence length");
43962
43967
  if (data.seqLen > c.maxPositions) {
43963
- if (c.positionKind === "learned") {
43968
+ if (c.positionKind === "learned" || c.positionKind === "buffer") {
43964
43969
  findings.push({
43965
43970
  rule: "seq-over-positions",
43966
43971
  severity: "block",
43967
- title: `Sequences of ${data.seqLen} tokens are longer than the ${c.maxPositions}-row position table`,
43968
- detail: `Position ids past ${c.maxPositions - 1} index outside a learned table, so the first batch that long raises an IndexError (a device-side assert on GPU) after the reservation is taken.`,
43972
+ title: `Sequences of ${data.seqLen} tokens are longer than the ${c.maxPositions}-row position ${c.positionKind === "learned" ? "table" : "buffer"}`,
43973
+ detail: c.positionKind === "learned" ? `Position ids past ${c.maxPositions - 1} index outside a learned table, so the first batch that long raises an IndexError (a device-side assert on GPU) after the reservation is taken.` : `The encoding is a precomputed ${c.maxPositions}-row buffer, so adding it to a longer sequence fails on shape at the first batch that long, after the reservation is taken.`,
43969
43974
  fix: `Truncate or chunk to ${c.maxPositions} tokens, or pick a model whose context covers ${data.seqLen}.`
43970
43975
  });
43971
43976
  } else {
@@ -44051,6 +44056,1039 @@ function checkDataFit(contract, data) {
44051
44056
  return { checked, skipped, findings, contract };
44052
44057
  }
44053
44058
 
44059
+ // src/utils/parallelLayout.ts
44060
+ init_paramEstimator();
44061
+
44062
+ // src/utils/parallelismPlanner.ts
44063
+ var NODE_SIZE = 8;
44064
+ var COMPUTE_BOUND_MFU = 0.4;
44065
+ function tpCeilingFor(gpu, ffDim) {
44066
+ const c = gpu.bf16TFLOPS * 1e12;
44067
+ const linkGBs = gpu.nvlinkGBs > 0 ? gpu.nvlinkGBs : 32;
44068
+ const cw = c / (linkGBs * 1e9);
44069
+ return Math.max(1, Math.min(NODE_SIZE, Math.floor((ffDim > 0 ? ffDim : 4096) / cw)));
44070
+ }
44071
+
44072
+ // src/utils/parallelLayout.ts
44073
+ var BUBBLE_WARN = 0.15;
44074
+ var STRAGGLE_THRESHOLD = 0.1;
44075
+ var SEQ_IMBALANCE_WARN = 0.05;
44076
+ var LOSS_FLOPS_PER_LOGIT = 10;
44077
+ var W_BYTES = 4;
44078
+ var G_BYTES = 4;
44079
+ var O_BYTES = 8;
44080
+ var ACT_BYTES = 2;
44081
+ var MEM_BW_EFFICIENCY = 0.8;
44082
+ var MEM_BYTES_PER_ELEM = {
44083
+ /**
44084
+ * transformers' LlamaRMSNorm / Qwen3RMSNorm: fwd to(fp32) 6, pow 8, mean 4,
44085
+ * x*rsqrt 8, to(bf16) 6, *weight 4 = 36; bwd mirrors it with two gradient
44086
+ * paths summed (weight grad 8, cast 6, mul 16, mean 4, pow 12, sum 12, cast 6) = 64.
44087
+ */
44088
+ rmsNorm: 100,
44089
+ /** torch.nn.LayerNorm is one fused kernel each way: fwd read + write 4, bwd grad + input + write + weight-grad read 12. */
44090
+ layerNorm: 16,
44091
+ /** Residual add: fwd two reads + one write 6; bwd the gradient is summed where the residual stream forks, 6. */
44092
+ add: 12,
44093
+ /** SwiGLU per intermediate element: fwd silu 4 + mul 6; bwd mul (two grads) 12 + silu 6. */
44094
+ swiglu: 28,
44095
+ /** GELU MLP per intermediate element: fwd 4, bwd 6. */
44096
+ gelu: 10,
44097
+ /** RoPE per q / k element (transformers' rotate_half): fwd mul, neg, cat, mul, add = 26; bwd the same. */
44098
+ rope: 52,
44099
+ /**
44100
+ * Cross-entropy per logit on the stock path, `cross_entropy(logits.float())`:
44101
+ * fwd fp32 cast 6, log_softmax 12; bwd nll grad 4, log_softmax backward 12,
44102
+ * cast back to bf16 6 = 40.
44103
+ */
44104
+ crossEntropy: 40,
44105
+ /** Fused / chunked linear + cross-entropy: bf16 logits written and read once each way, never upcast whole. An assumption, not a count. */
44106
+ crossEntropyFused: 8
44107
+ };
44108
+ var LAYOUT_BASIS = "Derived from the graph, not measured. A stage's time is the sum of its layers: matmul FLOPs at 40% of the card's peak, plus memory-bound bytes (norms, elementwise ops, RoPE, the fp32 loss) at 80% of its memory bandwidth. Step time uses the pipeline formula m x slowest + (sum - slowest) / v at this layout's microbatch count. On 2 and 4 L4 GPUs the predicted speedup of a split landed within 5.1 points of measured; on H100 this overprices the LM head. Memory uses the same per-layer terms and calibrated upper bound as the training-peak estimate, plus the fp32 logits on the stage with the loss. Nothing here was timed on a GPU.";
44109
+ var DEFAULT_GPU = "h100-sxm";
44110
+ var posInt3 = (v) => {
44111
+ const n2 = typeof v === "string" && v.trim() !== "" ? Number(v) : typeof v === "number" ? v : NaN;
44112
+ return Number.isInteger(n2) && n2 > 0 ? n2 : null;
44113
+ };
44114
+ function readLayout(raw) {
44115
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return { error: "`layout` must be an object." };
44116
+ const r = raw;
44117
+ const pick = (...names) => {
44118
+ const n2 = names.find((k) => r[k] != null);
44119
+ return n2 == null ? null : { name: n2, v: r[n2] };
44120
+ };
44121
+ const int = (required, ...names) => {
44122
+ const p = pick(...names);
44123
+ if (!p) return required ? { error: `\`layout.${names[0]}\` is required.` } : void 0;
44124
+ const v = posInt3(p.v);
44125
+ return v == null ? { error: `\`layout.${p.name}\` must be a positive integer.` } : v;
44126
+ };
44127
+ const out = {};
44128
+ const spec = [
44129
+ ["tp", false, ["tp", "tensor_parallel"]],
44130
+ ["pp", false, ["pp", "pipeline_parallel"]],
44131
+ ["dp", false, ["dp", "data_parallel"]],
44132
+ ["cp", false, ["cp", "context_parallel"]],
44133
+ ["ep", false, ["ep", "expert_parallel"]],
44134
+ ["numGpus", false, ["num_gpus", "numGpus", "gpus"]],
44135
+ ["microBatch", true, ["micro_batch", "microBatch", "micro_batch_size"]],
44136
+ ["globalBatch", false, ["global_batch", "globalBatch", "global_batch_size"]],
44137
+ ["gradAccum", false, ["grad_accum", "gradAccum", "gradient_accumulation_steps"]],
44138
+ ["seqLen", true, ["seq_len", "seqLen"]],
44139
+ ["virtualStages", false, ["virtual_stages", "virtualStages", "virtual_pipeline_stages"]]
44140
+ ];
44141
+ for (const [key, req, names] of spec) {
44142
+ const v = int(req, ...names);
44143
+ if (v && typeof v === "object") return v;
44144
+ if (v != null) out[key] = v;
44145
+ }
44146
+ out.tp = out.tp ?? 1;
44147
+ out.pp = out.pp ?? 1;
44148
+ out.dp = out.dp ?? 1;
44149
+ const gpu = pick("gpu");
44150
+ if (gpu) {
44151
+ if (typeof gpu.v !== "string") return { error: "`layout.gpu` must be a string." };
44152
+ out.gpu = gpu.v;
44153
+ }
44154
+ const sch = pick("schedule");
44155
+ if (sch) {
44156
+ const s = String(sch.v).toLowerCase();
44157
+ if (s !== "1f1b" && s !== "interleaved") return { error: '`layout.schedule` must be "1f1b" or "interleaved".' };
44158
+ out.schedule = s;
44159
+ }
44160
+ const lps = pick("layers_per_stage", "layersPerStage");
44161
+ if (lps) {
44162
+ const arr = typeof lps.v === "string" ? lps.v.split(",") : lps.v;
44163
+ if (!Array.isArray(arr) || !arr.length) return { error: `\`layout.${lps.name}\` must be a list of positive integers.` };
44164
+ const nums = arr.map(posInt3);
44165
+ if (nums.some((n2) => n2 == null)) return { error: `\`layout.${lps.name}\` must be a list of positive integers.` };
44166
+ out.layersPerStage = nums;
44167
+ }
44168
+ for (const [key, names] of [["embeddingOnFirst", ["embedding_on_first", "embeddingOnFirst"]], ["headOnLast", ["head_on_last", "headOnLast"]], ["fsdp", ["fsdp"]], ["activationCheckpointing", ["activation_checkpointing", "activationCheckpointing", "recompute"]], ["fusedCrossEntropy", ["fused_cross_entropy", "fusedCrossEntropy", "fused_ce"]]]) {
44169
+ const p = pick(...names);
44170
+ if (!p) continue;
44171
+ if (typeof p.v !== "boolean") return { error: `\`layout.${p.name}\` must be true or false.` };
44172
+ out[key] = p.v;
44173
+ }
44174
+ const z = pick("zero_stage", "zeroStage", "zero");
44175
+ if (z) {
44176
+ const v = Number(z.v);
44177
+ if (![0, 1, 2, 3].includes(v)) return { error: `\`layout.${z.name}\` must be 0, 1, 2 or 3.` };
44178
+ out.zeroStage = v;
44179
+ }
44180
+ const h = pick("seq_len_histogram", "seqLenHistogram");
44181
+ if (h) {
44182
+ const hist = readHistogram(h.v);
44183
+ if ("error" in hist) return { error: `\`layout.${h.name}\`: ${hist.error}` };
44184
+ out.seqLenHistogram = hist.histogram;
44185
+ }
44186
+ return out;
44187
+ }
44188
+ function readHistogram(raw) {
44189
+ let rows = [];
44190
+ if (typeof raw === "string") {
44191
+ rows = raw.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((l) => l.split(/[,\t ]+/)).filter(([a]) => !/^[a-z_]/i.test(String(a)));
44192
+ } else if (Array.isArray(raw)) {
44193
+ rows = raw.map((e) => Array.isArray(e) ? [e[0], e[1]] : e && typeof e === "object" ? [e.len ?? e.length, e.count] : [null, null]);
44194
+ } else return { error: "must be a list of {len, count} or two-column CSV text." };
44195
+ const out = [];
44196
+ for (const [a, b] of rows) {
44197
+ const len = posInt3(a), count = Number(b);
44198
+ if (len == null || !(Number.isFinite(count) && count >= 0)) return { error: `unreadable row ${JSON.stringify([a, b])}; each row is a positive length and a non-negative count.` };
44199
+ if (count > 0) out.push({ len, count });
44200
+ }
44201
+ if (!out.length) return { error: "no rows with a positive count." };
44202
+ return { histogram: out };
44203
+ }
44204
+ function resolveLayoutGpu(id) {
44205
+ const want = String(id ?? DEFAULT_GPU).toLowerCase().replace(/[^a-z0-9]/g, "");
44206
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
44207
+ const exact = GPU_HARDWARE.find((g) => norm(g.id) === want) ?? gpuById(String(id ?? DEFAULT_GPU));
44208
+ if (exact) return exact;
44209
+ const hits = GPU_HARDWARE.filter((g) => norm(g.id).startsWith(want));
44210
+ return hits.length === 1 ? hits[0] : null;
44211
+ }
44212
+ function topoOrder2(model) {
44213
+ const idx = new Map(model.components.map((c, i) => [c.id, i]));
44214
+ const indeg = new Map(model.components.map((c) => [c.id, 0]));
44215
+ const next = new Map(model.components.map((c) => [c.id, []]));
44216
+ for (const e of model.connections ?? []) {
44217
+ if (!idx.has(e.from) || !idx.has(e.to)) continue;
44218
+ next.get(e.from).push(e.to);
44219
+ indeg.set(e.to, (indeg.get(e.to) ?? 0) + 1);
44220
+ }
44221
+ const ready = model.components.filter((c) => indeg.get(c.id) === 0).map((c) => c.id);
44222
+ const seen = /* @__PURE__ */ new Set();
44223
+ const out = [];
44224
+ while (ready.length) {
44225
+ ready.sort((a, b) => idx.get(a) - idx.get(b));
44226
+ const id = ready.shift();
44227
+ if (seen.has(id)) continue;
44228
+ seen.add(id);
44229
+ out.push(model.components[idx.get(id)]);
44230
+ for (const n2 of next.get(id) ?? []) {
44231
+ const d = indeg.get(n2) - 1;
44232
+ indeg.set(n2, d);
44233
+ if (d === 0) ready.push(n2);
44234
+ }
44235
+ }
44236
+ for (const c of model.components) if (!seen.has(c.id)) out.push(c);
44237
+ return out;
44238
+ }
44239
+ var SKIP_TYPES2 = /* @__PURE__ */ new Set(["input", "output", "stickyNote"]);
44240
+ var BLOCK_TYPES = /^(transformerBlock|transformerEncoder|transformerDecoder|transformerEncoderLayer|transformerDecoderLayer|ditBlock|llamaBlock|decoderBlock|encoderBlock)$/;
44241
+ function blocksOf(model) {
44242
+ const order = topoOrder2(model).filter((c) => !SKIP_TYPES2.has(c.type));
44243
+ const numOf = (c) => {
44244
+ const m = /_(\d+)(?=_|$)/.exec(c.name ?? "");
44245
+ return m ? Number(m[1]) : null;
44246
+ };
44247
+ const numbered = order.map(numOf);
44248
+ const firstIdx = numbered.findIndex((n2) => n2 != null);
44249
+ let lastIdx = -1;
44250
+ for (let i = numbered.length - 1; i >= 0; i--) if (numbered[i] != null) {
44251
+ lastIdx = i;
44252
+ break;
44253
+ }
44254
+ if (firstIdx >= 0) {
44255
+ const blocks = [];
44256
+ let cur = null;
44257
+ let monotone = true;
44258
+ for (let i = firstIdx; i <= lastIdx; i++) {
44259
+ const n2 = numbered[i];
44260
+ if (n2 != null && n2 !== cur) {
44261
+ if (cur != null && n2 < cur) monotone = false;
44262
+ cur = n2;
44263
+ blocks.push([]);
44264
+ }
44265
+ blocks[blocks.length - 1].push(order[i]);
44266
+ }
44267
+ if (monotone && blocks.length >= 2) {
44268
+ return { pre: order.slice(0, firstIdx), blocks, post: order.slice(lastIdx + 1), method: "numbered-names" };
44269
+ }
44270
+ }
44271
+ const bIdx = order.map((c, i) => BLOCK_TYPES.test(c.type) ? i : -1).filter((i) => i >= 0);
44272
+ if (bIdx.length >= 2) {
44273
+ const blocks = [];
44274
+ for (let k = 0; k < bIdx.length; k++) {
44275
+ const end = k + 1 < bIdx.length ? bIdx[k + 1] : bIdx[k] + 1;
44276
+ blocks.push(order.slice(bIdx[k], end));
44277
+ }
44278
+ return { pre: order.slice(0, bIdx[0]), blocks, post: order.slice(bIdx[bIdx.length - 1] + 1), method: "block-components" };
44279
+ }
44280
+ return null;
44281
+ }
44282
+ var ATTN = /attention|^mla$/i;
44283
+ function geometryOf(model) {
44284
+ const g = { numHeads: null, numKVHeads: null, hidden: null, ffn: null, numExperts: null, vocab: null };
44285
+ const num5 = (v) => typeof v === "number" && v > 0 ? v : null;
44286
+ for (const c of model.components) {
44287
+ const p = c.params ?? {};
44288
+ if (g.numHeads == null && ATTN.test(c.type)) {
44289
+ g.numHeads = num5(p.numHeads);
44290
+ g.numKVHeads = num5(p.numKVHeads) ?? g.numHeads;
44291
+ g.hidden = g.hidden ?? num5(p.embedDim);
44292
+ }
44293
+ if (g.ffn == null && /^(swiglu|feedForward|geglu|mlp)$/i.test(c.type)) g.ffn = num5(p.intermediateSize) ?? num5(p.ffDim) ?? num5(p.hiddenFeatures);
44294
+ if (/moe/i.test(c.type)) {
44295
+ g.numExperts = g.numExperts ?? num5(p.numExperts);
44296
+ g.ffn = g.ffn ?? num5(p.expertDim) ?? num5(p.ffDim);
44297
+ }
44298
+ if (c.type === "embedding" && g.vocab == null) {
44299
+ g.vocab = num5(p.vocabSize);
44300
+ g.hidden = g.hidden ?? num5(p.embeddingDim);
44301
+ }
44302
+ }
44303
+ return g;
44304
+ }
44305
+ function weightedNoTransient(l) {
44306
+ return l.outputs * OUTPUT_K + l.scores * ATTENTION_K + l.internal * INTERNAL_K + l.recurrent * RECURRENT_K;
44307
+ }
44308
+ function memBoundBytes(c, shapes, hasRope) {
44309
+ const sh = shapes.get(c.id);
44310
+ const outS = sh?.out ?? [];
44311
+ if (!outS.length) return 0;
44312
+ const elems = outS.reduce((a, b) => a * b, 1);
44313
+ const width = outS[outS.length - 1] || 1;
44314
+ const tokens = elems / width;
44315
+ const p = c.params ?? {};
44316
+ const num5 = (v) => typeof v === "number" && v > 0 ? v : null;
44317
+ const B = MEM_BYTES_PER_ELEM;
44318
+ switch (c.type) {
44319
+ case "rmsNorm":
44320
+ return elems * B.rmsNorm;
44321
+ case "layerNorm":
44322
+ return elems * B.layerNorm;
44323
+ case "add":
44324
+ return elems * B.add;
44325
+ case "swiglu":
44326
+ case "geglu": {
44327
+ const I = num5(p.intermediateSize) ?? num5(p.ffDim) ?? num5(p.hiddenFeatures);
44328
+ return I ? tokens * I * B.swiglu : 0;
44329
+ }
44330
+ case "feedForward": {
44331
+ const I = num5(p.intermediateSize) ?? num5(p.ffDim) ?? num5(p.hiddenFeatures);
44332
+ return I ? tokens * I * B.gelu : 0;
44333
+ }
44334
+ case "embedding": {
44335
+ const V = num5(p.vocabSize), D = num5(p.embeddingDim) ?? width;
44336
+ return (V ? V * D * ACT_BYTES : 0) + tokens * D * 10;
44337
+ }
44338
+ default:
44339
+ if (hasRope && ATTN.test(c.type)) {
44340
+ const H = num5(p.numHeads), E = num5(p.embedDim) ?? width;
44341
+ if (!H) return 0;
44342
+ const hd = num5(p.headDim) ?? E / H;
44343
+ const kv = num5(p.numKVHeads) ?? H;
44344
+ return tokens * (H + kv) * hd * B.rope;
44345
+ }
44346
+ return 0;
44347
+ }
44348
+ }
44349
+ function unitCost(comps, shapes, isPost, hasRope) {
44350
+ const stores = storesScoresUnder("sdpa");
44351
+ const u = { params: 0, expertParams: 0, macs: 0, actElems: 0, largest: 0, boundaryElems: 0, logits: 0, memBytes: 0 };
44352
+ for (const c of comps) {
44353
+ const sh = shapes.get(c.id);
44354
+ const inS = sh?.in ?? [];
44355
+ const outS = sh?.out ?? [];
44356
+ const p = estimateLayerParams(c.type, c.params, inS.length ? inS : void 0) ?? 0;
44357
+ u.params += p;
44358
+ if (/moe/i.test(c.type)) u.expertParams += p;
44359
+ u.macs += estimateLayerFlops(c.type, c.params ?? {}, inS, outS) || 0;
44360
+ u.memBytes += memBoundBytes(c, shapes, hasRope);
44361
+ const l = layerMemoryTerms(c, shapes, stores);
44362
+ if (l) {
44363
+ u.actElems += weightedNoTransient(l);
44364
+ u.largest = Math.max(u.largest, l.outputs, l.scores);
44365
+ }
44366
+ if (outS.length) u.boundaryElems = outS.reduce((a, b) => a * b, 1);
44367
+ }
44368
+ if (isPost) {
44369
+ const head2 = [...comps].reverse().find((c) => c.type === "linear");
44370
+ const o = head2 ? shapes.get(head2.id)?.out ?? [] : [];
44371
+ if (o.length) u.logits = o.reduce((a, b) => a * b, 1);
44372
+ }
44373
+ return u;
44374
+ }
44375
+ function optimalPartition(w, k, head0 = 0, tailK = 0) {
44376
+ const n2 = w.length;
44377
+ if (k < 1 || k > n2) return null;
44378
+ const pre = [0];
44379
+ for (const x of w) pre.push(pre[pre.length - 1] + x);
44380
+ const sum = (i, j2) => pre[j2] - pre[i];
44381
+ const f = Array.from({ length: k + 1 }, () => new Array(n2 + 1).fill(Infinity));
44382
+ f[0][0] = 0;
44383
+ for (let s = 1; s <= k; s++) {
44384
+ for (let j2 = s; j2 <= n2 - (k - s); j2++) {
44385
+ for (let i = s - 1; i < j2; i++) {
44386
+ if (f[s - 1][i] === Infinity) continue;
44387
+ const part = sum(i, j2) + (s === 1 ? head0 : 0) + (s === k ? tailK : 0);
44388
+ const v = Math.max(f[s - 1][i], part);
44389
+ if (v < f[s][j2]) f[s][j2] = v;
44390
+ }
44391
+ }
44392
+ }
44393
+ if (f[k][n2] === Infinity) return null;
44394
+ const cap = f[k][n2] * (1 + 1e-9);
44395
+ const g = Array.from({ length: k + 1 }, () => new Array(n2 + 1).fill(Infinity));
44396
+ const arg2 = Array.from({ length: k + 1 }, () => new Array(n2 + 1).fill(-1));
44397
+ g[0][0] = 0;
44398
+ for (let s = 1; s <= k; s++) {
44399
+ for (let j2 = s; j2 <= n2 - (k - s); j2++) {
44400
+ for (let i = s - 1; i < j2; i++) {
44401
+ if (g[s - 1][i] === Infinity) continue;
44402
+ const part = sum(i, j2) + (s === 1 ? head0 : 0) + (s === k ? tailK : 0);
44403
+ if (part > cap) continue;
44404
+ const val = g[s - 1][i] + part * part;
44405
+ if (val < g[s][j2]) {
44406
+ g[s][j2] = val;
44407
+ arg2[s][j2] = i;
44408
+ }
44409
+ }
44410
+ }
44411
+ }
44412
+ const sizes = [];
44413
+ let j = n2;
44414
+ for (let s = k; s >= 1; s--) {
44415
+ const i = arg2[s][j];
44416
+ sizes.unshift(j - i);
44417
+ j = i;
44418
+ }
44419
+ return sizes;
44420
+ }
44421
+ function evenSplit(blocks, pp) {
44422
+ const base = Math.floor(blocks / pp), rem = blocks % pp;
44423
+ return Array.from({ length: pp }, (_, i) => base + (i < rem ? 1 : 0));
44424
+ }
44425
+ function bubbleFraction(pp, microbatches, virtualStages = 1) {
44426
+ if (pp <= 1 || microbatches <= 0) return 0;
44427
+ const x = (pp - 1) / Math.max(1, virtualStages);
44428
+ return x / (microbatches + x);
44429
+ }
44430
+ function pipelineStepTime(stageTimes, microbatches, virtualStages = 1) {
44431
+ if (!stageTimes.length) return 0;
44432
+ const max = Math.max(...stageTimes);
44433
+ const sum = stageTimes.reduce((a, b) => a + b, 0);
44434
+ return Math.max(1, microbatches) * max + (sum - max) / Math.max(1, virtualStages);
44435
+ }
44436
+ function microbatchesForBubble(pp, target, virtualStages = 1) {
44437
+ const x = (pp - 1) / Math.max(1, virtualStages);
44438
+ return Math.max(1, Math.ceil(x * (1 - target) / target - 1e-9));
44439
+ }
44440
+ function mulberry32(seed) {
44441
+ let a = seed >>> 0;
44442
+ return () => {
44443
+ a = a + 1831565813 >>> 0;
44444
+ let t = a;
44445
+ t = Math.imul(t ^ t >>> 15, t | 1);
44446
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
44447
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
44448
+ };
44449
+ }
44450
+ function invNorm(p) {
44451
+ const a = [-39.69683028665376, 220.9460984245205, -275.9285104469687, 138.357751867269, -30.66479806614716, 2.506628277459239];
44452
+ const b = [-54.47609879822406, 161.5858368580409, -155.6989798598866, 66.80131188771972, -13.28068155288572];
44453
+ const c = [-0.007784894002430293, -0.3223964580411365, -2.400758277161838, -2.549732539343734, 4.374664141464968, 2.938163982698783];
44454
+ const d = [0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416];
44455
+ const pl = 0.02425;
44456
+ if (p < pl) {
44457
+ const q2 = Math.sqrt(-2 * Math.log(p));
44458
+ return (((((c[0] * q2 + c[1]) * q2 + c[2]) * q2 + c[3]) * q2 + c[4]) * q2 + c[5]) / ((((d[0] * q2 + d[1]) * q2 + d[2]) * q2 + d[3]) * q2 + 1);
44459
+ }
44460
+ if (p > 1 - pl) {
44461
+ const q2 = Math.sqrt(-2 * Math.log(1 - p));
44462
+ return -(((((c[0] * q2 + c[1]) * q2 + c[2]) * q2 + c[3]) * q2 + c[4]) * q2 + c[5]) / ((((d[0] * q2 + d[1]) * q2 + d[2]) * q2 + d[3]) * q2 + 1);
44463
+ }
44464
+ const q = p - 0.5, r = q * q;
44465
+ return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
44466
+ }
44467
+ function seqImbalance(hist, ranks, perRank, a, b, seed = 7) {
44468
+ const total = hist.reduce((s, h) => s + h.count, 0);
44469
+ const lens = hist.map((h) => h.len);
44470
+ const cdf = [];
44471
+ let acc = 0;
44472
+ for (const h of hist) {
44473
+ acc += h.count / total;
44474
+ cdf.push(acc);
44475
+ }
44476
+ const work = (L) => a * L + b * L * L;
44477
+ const meanLen = hist.reduce((s, h) => s + h.len * h.count, 0) / total;
44478
+ const meanW = hist.reduce((s, h) => s + work(h.len) * h.count, 0) / total;
44479
+ const varW = hist.reduce((s, h) => s + (work(h.len) - meanW) ** 2 * h.count, 0) / total;
44480
+ const budget = perRank * meanLen;
44481
+ if (ranks <= 1) return { expectedMaxOverMean: 1, packedEstimate: 1, method: "monte-carlo" };
44482
+ const draws = ranks * perRank;
44483
+ if (draws <= 4e4) {
44484
+ const rnd = mulberry32(seed);
44485
+ const sample = () => {
44486
+ const u = rnd();
44487
+ let i = 0;
44488
+ while (i < cdf.length - 1 && u > cdf[i]) i++;
44489
+ return lens[i];
44490
+ };
44491
+ const trials = Math.max(50, Math.min(2e3, Math.floor(2e6 / draws)));
44492
+ let sumRatio = 0, sumPacked = 0;
44493
+ for (let t = 0; t < trials; t++) {
44494
+ let mx = 0, sm = 0, pmx = 0, psm = 0;
44495
+ for (let r = 0; r < ranks; r++) {
44496
+ let w = 0;
44497
+ for (let k = 0; k < perRank; k++) w += work(sample());
44498
+ mx = Math.max(mx, w);
44499
+ sm += w;
44500
+ let left = budget, q = 0;
44501
+ while (left > 0) {
44502
+ const L = Math.min(sample(), left);
44503
+ q += L * L;
44504
+ left -= L;
44505
+ }
44506
+ const pw = a * budget + b * q;
44507
+ pmx = Math.max(pmx, pw);
44508
+ psm += pw;
44509
+ }
44510
+ sumRatio += mx / (sm / ranks);
44511
+ sumPacked += pmx / (psm / ranks);
44512
+ }
44513
+ return { expectedMaxOverMean: sumRatio / trials, packedEstimate: sumPacked / trials, method: "monte-carlo" };
44514
+ }
44515
+ const z = invNorm((ranks - 0.375) / (ranks + 0.25));
44516
+ const mean = perRank * meanW;
44517
+ const ratio = 1 + z * Math.sqrt(perRank * varW) / mean;
44518
+ const meanL2 = hist.reduce((s, h) => s + h.len * h.len * h.count, 0) / total;
44519
+ const varL2 = hist.reduce((s, h) => s + (h.len * h.len - meanL2) ** 2 * h.count, 0) / total;
44520
+ const docs = budget / meanLen;
44521
+ const pMean = a * budget + b * docs * meanL2;
44522
+ const packed = 1 + z * b * Math.sqrt(docs * varL2) / pMean;
44523
+ return { expectedMaxOverMean: ratio, packedEstimate: packed, method: "normal-approximation" };
44524
+ }
44525
+ var pct = (x) => `${(x * 100).toFixed(1)}%`;
44526
+ var gb = (x) => `${x.toFixed(1)} GB`;
44527
+ function checkParallelLayout(model, layout) {
44528
+ const checked = [];
44529
+ const skipped = [];
44530
+ const findings = [];
44531
+ const recommendations = [];
44532
+ const add = (f) => findings.push(f);
44533
+ const tp = Math.max(1, Math.floor(layout.tp || 1));
44534
+ const pp = Math.max(1, Math.floor(layout.pp || 1));
44535
+ const dp = Math.max(1, Math.floor(layout.dp || 1));
44536
+ const cp = Math.max(1, Math.floor(layout.cp ?? 1));
44537
+ const ep = Math.max(1, Math.floor(layout.ep ?? 1));
44538
+ const micro = Math.max(1, Math.floor(layout.microBatch || 1));
44539
+ const seqLen = Math.max(1, Math.floor(layout.seqLen || 1));
44540
+ const schedule = layout.schedule ?? "1f1b";
44541
+ const v = schedule === "interleaved" ? Math.max(1, Math.floor(layout.virtualStages ?? 2)) : 1;
44542
+ const zero = layout.fsdp ? 3 : layout.zeroStage ?? 0;
44543
+ const embFirst = layout.embeddingOnFirst !== false;
44544
+ const headLast = layout.headOnLast !== false;
44545
+ const world = tp * pp * dp * cp;
44546
+ const gpu = resolveLayoutGpu(layout.gpu);
44547
+ const geo = geometryOf(model);
44548
+ if (layout.numGpus != null) {
44549
+ checked.push("world-size");
44550
+ if (world !== layout.numGpus) {
44551
+ add({
44552
+ rule: "world-size",
44553
+ severity: "block",
44554
+ title: `tp x pp x dp x cp = ${world}, but the job has ${layout.numGpus} GPUs`,
44555
+ detail: `${tp} x ${pp} x ${dp} x ${cp} = ${world}. The launcher refuses a world size that does not match the process count${world < layout.numGpus ? `, or ${layout.numGpus - world} GPUs sit idle` : ""}.`,
44556
+ fix: layout.numGpus % (tp * pp * cp) === 0 ? `Set dp = ${layout.numGpus / (tp * pp * cp)}.` : `Choose tp x pp x cp dividing ${layout.numGpus}.`
44557
+ });
44558
+ }
44559
+ } else skipped.push({ check: "world-size", reason: "numGpus not given; the product tp x pp x dp x cp is taken as the world size." });
44560
+ if (geo.numHeads != null) {
44561
+ checked.push("tp-heads");
44562
+ if (geo.numHeads % tp !== 0) {
44563
+ add({
44564
+ rule: "tp-heads",
44565
+ severity: "block",
44566
+ title: `TP ${tp} does not divide ${geo.numHeads} attention heads`,
44567
+ detail: "Megatron-style TP gives each rank whole heads; a remainder fails at model construction.",
44568
+ fix: `Use a TP degree dividing ${geo.numHeads}: ${divisors(geo.numHeads).filter((d) => d <= NODE_SIZE).join(", ")}.`
44569
+ });
44570
+ }
44571
+ if (geo.numKVHeads != null && geo.numKVHeads !== geo.numHeads) {
44572
+ checked.push("tp-kv-heads");
44573
+ if (geo.numKVHeads % tp !== 0) {
44574
+ if (tp % geo.numKVHeads === 0) {
44575
+ add({
44576
+ rule: "tp-kv-replicated",
44577
+ severity: "warn",
44578
+ title: `TP ${tp} exceeds ${geo.numKVHeads} KV heads: each KV head is replicated ${tp / geo.numKVHeads}x`,
44579
+ detail: "It runs, but every replica stores and computes the same K and V projections, so the KV weights and KV activations do not shrink past TP = KV heads.",
44580
+ fix: `Keep TP at or under ${geo.numKVHeads}, or accept the replication knowingly.`
44581
+ });
44582
+ } else {
44583
+ add({
44584
+ rule: "tp-kv-heads",
44585
+ severity: "block",
44586
+ title: `TP ${tp} neither divides nor is a multiple of ${geo.numKVHeads} KV heads`,
44587
+ detail: "Grouped-query attention needs whole KV heads per rank or an exact replication factor.",
44588
+ fix: `Use a TP degree that divides ${geo.numKVHeads} or is a multiple of it.`
44589
+ });
44590
+ }
44591
+ }
44592
+ }
44593
+ } else skipped.push({ check: "tp-heads", reason: "no attention layer with a head count in the graph." });
44594
+ if (geo.hidden != null) {
44595
+ checked.push("tp-hidden");
44596
+ if (geo.hidden % tp !== 0) add({ rule: "tp-hidden", severity: "block", title: `TP ${tp} does not divide hidden size ${geo.hidden}`, detail: "Column- and row-parallel linears split the hidden dimension evenly across ranks.", fix: `Use a TP degree dividing ${geo.hidden}.` });
44597
+ }
44598
+ if (geo.ffn != null) {
44599
+ checked.push("tp-ffn");
44600
+ if (geo.ffn % tp !== 0) add({ rule: "tp-ffn", severity: "block", title: `TP ${tp} does not divide FFN width ${geo.ffn}`, detail: "The MLP up and down projections are split along the intermediate dimension.", fix: `Use a TP degree dividing ${geo.ffn}.` });
44601
+ }
44602
+ checked.push("tp-node");
44603
+ if (tp > NODE_SIZE) {
44604
+ add({
44605
+ rule: "tp-crosses-node",
44606
+ severity: "warn",
44607
+ title: `TP ${tp} spans more than one ${NODE_SIZE}-GPU node`,
44608
+ detail: "Every layer does TP all-reduces; past the NVLink domain they run on the node fabric, an order of magnitude slower (the planner caps TP at one node for this reason).",
44609
+ fix: `Keep TP at ${NODE_SIZE} or under and move the rest of the split to PP or DP.`
44610
+ });
44611
+ } else if (gpu && tp > 1 && geo.ffn != null) {
44612
+ const ceiling = tpCeilingFor(gpu, geo.ffn);
44613
+ if (tp > ceiling) {
44614
+ add({
44615
+ rule: "tp-past-link-ceiling",
44616
+ severity: "info",
44617
+ title: `TP ${tp} is past the ~${ceiling}-way ceiling for FFN width ${geo.ffn} on ${gpu.label}`,
44618
+ detail: "Roofline estimate (scaling-book): past about ffDim x link bandwidth / peak FLOPs ways, the TP collectives cost more than the matmuls they split.",
44619
+ fix: `Consider TP ${ceiling} with more PP or DP.`
44620
+ });
44621
+ }
44622
+ }
44623
+ if (geo.numExperts != null) {
44624
+ checked.push("ep-experts");
44625
+ if (geo.numExperts % ep !== 0) add({ rule: "ep-experts", severity: "block", title: `EP ${ep} does not divide ${geo.numExperts} experts`, detail: "Expert parallelism places whole experts on each rank.", fix: `Use an EP degree dividing ${geo.numExperts}.` });
44626
+ if (dp * cp % ep !== 0) add({ rule: "ep-ranks", severity: "block", title: `EP ${ep} does not divide dp x cp = ${dp * cp}`, detail: "Expert-parallel groups are carved out of the data- and context-parallel ranks (Megatron-Core).", fix: `Use an EP degree dividing ${dp * cp}.` });
44627
+ } else if (ep > 1) {
44628
+ add({ rule: "ep-experts", severity: "block", title: `EP ${ep} on a graph with no MoE layer`, detail: "There are no experts to distribute.", fix: "Set ep = 1." });
44629
+ }
44630
+ checked.push("cp-seq");
44631
+ if (cp > 1) {
44632
+ if (seqLen % cp !== 0) add({ rule: "cp-seq", severity: "block", title: `CP ${cp} does not divide sequence length ${seqLen}`, detail: "Context parallelism gives each rank an equal slice of every sequence.", fix: `Use a sequence length divisible by ${2 * cp}, or a CP degree dividing ${seqLen}.` });
44633
+ else if (seqLen % (2 * cp) !== 0) add({ rule: "cp-causal-balance", severity: "warn", title: `Sequence length ${seqLen} is not divisible by 2 x CP = ${2 * cp}`, detail: "Load-balanced causal CP splits each sequence into 2 x CP chunks so every rank gets an early and a late chunk; without it the last rank does most of the attention.", fix: `Pad or choose a sequence length divisible by ${2 * cp}.` });
44634
+ }
44635
+ let m = null;
44636
+ let globalBatch = null;
44637
+ checked.push("batch-arithmetic");
44638
+ if (layout.gradAccum != null) {
44639
+ m = layout.gradAccum;
44640
+ globalBatch = micro * m * dp;
44641
+ if (layout.globalBatch != null && layout.globalBatch !== globalBatch) {
44642
+ add({
44643
+ rule: "batch-arithmetic",
44644
+ severity: "block",
44645
+ title: `global batch ${layout.globalBatch} != micro ${micro} x grad-accum ${m} x dp ${dp} = ${globalBatch}`,
44646
+ detail: "Megatron and DeepSpeed both assert this identity at startup.",
44647
+ fix: `Set grad-accum to ${layout.globalBatch / (micro * dp)} if that is an integer, or change the global batch to ${globalBatch}.`
44648
+ });
44649
+ }
44650
+ } else if (layout.globalBatch != null) {
44651
+ globalBatch = layout.globalBatch;
44652
+ const q = layout.globalBatch / (micro * dp);
44653
+ if (!Number.isInteger(q)) {
44654
+ add({
44655
+ rule: "batch-arithmetic",
44656
+ severity: "block",
44657
+ title: `global batch ${layout.globalBatch} is not a multiple of micro ${micro} x dp ${dp} = ${micro * dp}`,
44658
+ detail: "The microbatches per step must be a whole number on every DP rank.",
44659
+ fix: `Use a global batch that is a multiple of ${micro * dp} (e.g. ${Math.max(1, Math.round(q)) * micro * dp}).`
44660
+ });
44661
+ } else m = q;
44662
+ } else skipped.push({ check: "batch-arithmetic", reason: "neither globalBatch nor gradAccum given." });
44663
+ const split = blocksOf(model);
44664
+ const resolvedBase = {
44665
+ gpu: gpu?.id ?? null,
44666
+ gpuMemoryGb: gpu?.memoryGB ?? null,
44667
+ worldSize: world,
44668
+ microbatchesPerStep: m,
44669
+ globalBatch,
44670
+ blocks: split?.blocks.length ?? 0,
44671
+ layersPerStage: null,
44672
+ schedule,
44673
+ virtualStages: v,
44674
+ zeroStage: zero
44675
+ };
44676
+ if (!gpu) skipped.push({ check: "stage-memory", reason: `unknown or ambiguous GPU "${layout.gpu}"; one of ${GPU_HARDWARE.map((g) => g.id).join(", ")}.` });
44677
+ if (!split) {
44678
+ skipped.push({ check: "stage-balance", reason: "no repeated blocks found in the graph (numbered layer names or block components), so there is nothing to cut into stages." });
44679
+ if (gpu) skipped.push({ check: "stage-memory", reason: "needs the stage split." });
44680
+ return finish(null, [], null);
44681
+ }
44682
+ const nBlocks = split.blocks.length;
44683
+ const units = nBlocks + (embFirst ? 0 : 1) + (headLast ? 0 : 1);
44684
+ checked.push("pp-over-blocks");
44685
+ if (pp > units) {
44686
+ add({ rule: "pp-over-blocks", severity: "block", title: `PP ${pp} is more than the ${nBlocks} blocks`, detail: "Every stage needs at least one block.", fix: `Use PP ${Math.min(units, 8)} or fewer.` });
44687
+ }
44688
+ let lps;
44689
+ if (layout.layersPerStage) {
44690
+ checked.push("layers-per-stage");
44691
+ lps = layout.layersPerStage;
44692
+ const sum = lps.reduce((a, b) => a + b, 0);
44693
+ if (lps.length !== pp || sum !== units) {
44694
+ add({
44695
+ rule: "layers-per-stage",
44696
+ severity: "block",
44697
+ title: `layersPerStage [${lps.join(", ")}] does not describe ${pp} stages of ${units} layers`,
44698
+ detail: `It has ${lps.length} entries summing to ${sum}; the graph has ${nBlocks} blocks${units !== nBlocks ? ` plus ${units - nBlocks} counted end layer${units - nBlocks > 1 ? "s" : ""}` : ""}, cut into PP ${pp}.`,
44699
+ fix: `Give ${pp} positive counts summing to ${units}.`
44700
+ });
44701
+ }
44702
+ } else {
44703
+ lps = evenSplit(units, Math.min(pp, units));
44704
+ if (units % pp !== 0 && pp <= units) {
44705
+ add({
44706
+ rule: "uneven-default-split",
44707
+ severity: "warn",
44708
+ title: `${units} layers do not divide evenly into PP ${pp}`,
44709
+ detail: `Megatron-LM's default split asserts num_layers % pp == 0. The report assumes [${lps.join(", ")}].`,
44710
+ fix: "Set the first and last stage layer counts explicitly (decoder_first/last_pipeline_num_layers) or choose a PP degree dividing the layer count."
44711
+ });
44712
+ }
44713
+ }
44714
+ if (schedule === "interleaved") {
44715
+ checked.push("interleaved-chunks");
44716
+ if (nBlocks % (pp * v) !== 0) {
44717
+ add({ rule: "interleaved-chunks", severity: "block", title: `${nBlocks} blocks do not split into PP ${pp} x ${v} virtual stages`, detail: "The interleaved schedule gives each rank v equal model chunks.", fix: `Choose v with ${nBlocks} divisible by ${pp} x v.` });
44718
+ }
44719
+ if (m != null && pp > 1 && m % pp !== 0) {
44720
+ add({ rule: "interleaved-microbatches", severity: "warn", title: `${m} microbatches per step is not a multiple of PP ${pp}`, detail: "Megatron-LM's interleaved schedule has required the microbatch count to be divisible by the pipeline size; check your version.", fix: `Use a microbatch count that is a multiple of ${pp}.` });
44721
+ }
44722
+ }
44723
+ if (findings.some((f) => f.severity === "block" && (f.rule === "pp-over-blocks" || f.rule === "layers-per-stage"))) {
44724
+ return finish(null, [], null);
44725
+ }
44726
+ const sized = withSeqLen(model, seqLen).model;
44727
+ const shapes = propagateShapes(sized).shapes;
44728
+ const hasRope = model.components.some((c) => c.type === "rope");
44729
+ const preC = unitCost(split.pre, shapes, false, hasRope);
44730
+ const postC = unitCost(split.post, shapes, true, hasRope);
44731
+ if (postC.logits === 0 && geo.vocab != null && geo.hidden != null) {
44732
+ postC.macs += seqLen * geo.hidden * geo.vocab;
44733
+ postC.logits = seqLen * geo.vocab;
44734
+ postC.params += geo.hidden * geo.vocab;
44735
+ postC.boundaryElems = Math.max(postC.boundaryElems, seqLen * geo.vocab);
44736
+ postC.largest = Math.max(postC.largest, seqLen * geo.vocab);
44737
+ if (!split.post.some((c) => /norm/i.test(c.type))) {
44738
+ const normType = split.blocks[0].find((c) => /norm/i.test(c.type))?.type;
44739
+ postC.memBytes += seqLen * geo.hidden * (normType === "layerNorm" ? MEM_BYTES_PER_ELEM.layerNorm : normType ? MEM_BYTES_PER_ELEM.rmsNorm : 0);
44740
+ }
44741
+ if (headLast && pp > 1) add({
44742
+ rule: "tied-head",
44743
+ severity: "info",
44744
+ title: "Tied LM head costed on the last stage",
44745
+ detail: `The checkpoint ties the output head to the embedding (${geo.vocab} x ${geo.hidden}). The weight is shared; the matmul and the loss are not, and under PP the last stage keeps its own copy of the matrix.`,
44746
+ fix: "Nothing to change; this says why the last stage is heavier than its block count suggests."
44747
+ });
44748
+ }
44749
+ const fusedCe = layout.fusedCrossEntropy === true;
44750
+ postC.memBytes += postC.logits * (fusedCe ? MEM_BYTES_PER_ELEM.crossEntropyFused : MEM_BYTES_PER_ELEM.crossEntropy);
44751
+ const blockC = split.blocks.map((b) => unitCost(b, shapes, false, hasRope));
44752
+ const recompute = layout.activationCheckpointing ? 4 / 3 : 1;
44753
+ const flopsPerTok = (u, isBlock) => 6 * u.macs / seqLen * (isBlock ? recompute : 1);
44754
+ const lossPerTok = postC.logits / seqLen * LOSS_FLOPS_PER_LOGIT;
44755
+ const perGpu = micro / (tp * cp);
44756
+ const mmMs = (u, isBlock) => gpu ? flopsPerTok(u, isBlock) * seqLen * perGpu / (gpu.bf16TFLOPS * 1e12 * COMPUTE_BOUND_MFU) * 1e3 : 0;
44757
+ const memMs = (u, isBlock) => gpu ? u.memBytes * (isBlock ? recompute : 1) * perGpu / (gpu.memBandwidthGBs * 1e9 * MEM_BW_EFFICIENCY) * 1e3 : 0;
44758
+ const costBasis = gpu ? "time" : "flops";
44759
+ const unitCostOf = (u, kind) => {
44760
+ const isBlock = kind === "block";
44761
+ if (costBasis === "time") return mmMs(u, isBlock) + memMs(u, isBlock);
44762
+ return flopsPerTok(u, isBlock) + (kind === "post" ? lossPerTok : 0);
44763
+ };
44764
+ const preF = flopsPerTok(preC, false);
44765
+ const postF = flopsPerTok(postC, false) + lossPerTok;
44766
+ const unitF = [];
44767
+ const unitW = [];
44768
+ const unitList = [];
44769
+ if (!embFirst) {
44770
+ unitF.push(preF);
44771
+ unitW.push(unitCostOf(preC, "pre"));
44772
+ unitList.push({ kind: "pre", c: preC });
44773
+ }
44774
+ blockC.forEach((c, i) => {
44775
+ unitF.push(flopsPerTok(c, true));
44776
+ unitW.push(unitCostOf(c, "block"));
44777
+ unitList.push({ kind: "block", c, i });
44778
+ });
44779
+ if (!headLast) {
44780
+ unitF.push(postF);
44781
+ unitW.push(unitCostOf(postC, "post"));
44782
+ unitList.push({ kind: "post", c: postC });
44783
+ }
44784
+ const head0F = embFirst ? preF : 0, tailF = headLast ? postF : 0;
44785
+ const head0W = embFirst ? unitCostOf(preC, "pre") : 0, tailW = headLast ? unitCostOf(postC, "post") : 0;
44786
+ const stageRanges = [];
44787
+ {
44788
+ let s = 0;
44789
+ for (const n2 of lps) {
44790
+ stageRanges.push([s, s + n2]);
44791
+ s += n2;
44792
+ }
44793
+ }
44794
+ const stageSum = (sizes, per, h0, tk) => {
44795
+ const out = [];
44796
+ let s = 0;
44797
+ sizes.forEach((n2, k) => {
44798
+ let f = 0;
44799
+ for (let j = s; j < s + n2; j++) f += per[j];
44800
+ if (k === 0) f += h0;
44801
+ if (k === sizes.length - 1) f += tk;
44802
+ out.push(f);
44803
+ s += n2;
44804
+ });
44805
+ return out;
44806
+ };
44807
+ const sf = stageSum(lps, unitF, head0F, tailF);
44808
+ const sw = stageSum(lps, unitW, head0W, tailW);
44809
+ const mean = sw.reduce((a, b) => a + b, 0) / sw.length;
44810
+ const maxW = Math.max(...sw);
44811
+ const slowest = sw.indexOf(maxW);
44812
+ const best = pp > 1 ? optimalPartition(unitW, pp, head0W, tailW) : null;
44813
+ const bestW = best ? stageSum(best, unitW, head0W, tailW) : sw;
44814
+ const bestMax = Math.max(...bestW);
44815
+ const stepOf = (stages2) => m != null ? pipelineStepTime(stages2, m, v) : null;
44816
+ const balanced = sw.map(() => mean);
44817
+ const curStep = stepOf(sw), balStep = stepOf(balanced), bestStep = stepOf(bestW);
44818
+ const asymptoticSlowdown = maxW / mean - 1;
44819
+ const imbalance = {
44820
+ costBasis,
44821
+ maxOverMean: maxW / mean,
44822
+ slowestStage: slowest,
44823
+ estStepSlowdown: curStep != null && balStep != null ? curStep / balStep - 1 : asymptoticSlowdown,
44824
+ asymptoticSlowdown,
44825
+ step: {
44826
+ microbatches: m,
44827
+ formula: m != null ? v > 1 ? `t = m x max + (sum - max) / v, m = ${m}, v = ${v} (interleaved)` : `t = m x max + (sum - max), m = ${m} (1F1B)` : "max / mean (microbatches per step unknown, so fill and drain are left out and this overstates the gap)",
44828
+ currentMs: costBasis === "time" ? curStep : null,
44829
+ balancedMs: costBasis === "time" ? balStep : null
44830
+ },
44831
+ rebalanced: best && bestMax < maxW * (1 - 1e-9) ? {
44832
+ layersPerStage: best,
44833
+ maxOverMean: bestMax / mean,
44834
+ estStepSpeedup: curStep != null && bestStep != null ? curStep / bestStep - 1 : maxW / bestMax - 1,
44835
+ asymptoticSpeedup: maxW / bestMax - 1,
44836
+ stepMs: costBasis === "time" ? bestStep : null
44837
+ } : null
44838
+ };
44839
+ const costWord = costBasis === "time" ? "predicted time" : "FLOPs";
44840
+ if (pp > 1) {
44841
+ checked.push("stage-balance");
44842
+ const what = slowest === pp - 1 && headLast ? " (it also carries the LM head and the loss)" : slowest === 0 && embFirst ? " (it also carries the embedding)" : "";
44843
+ if (imbalance.estStepSlowdown > 0.03) {
44844
+ const reb = imbalance.rebalanced;
44845
+ const per = costBasis === "time" ? `Per-stage predicted ms per microbatch: ${sw.map((x) => x.toFixed(1)).join(" | ")}.` : `Per-stage FLOPs/token: ${sf.map((x) => fmtFlops2(x)).join(" | ")} (unknown card, so FLOPs stand in for time and the memory-bound loss is understated).`;
44846
+ add({
44847
+ rule: "stage-imbalance",
44848
+ severity: imbalance.estStepSlowdown >= STRAGGLE_THRESHOLD && reb && reb.estStepSpeedup > 0.03 ? "warn" : "info",
44849
+ title: `Stage ${slowest} has ${pct(asymptoticSlowdown)} more ${costWord} than the mean stage${what}`,
44850
+ detail: `${per} Every microbatch waits on the slowest stage, so ${m != null ? `at ${m} microbatches per step the predicted step is ${pct(imbalance.estStepSlowdown)} longer than a perfectly balanced split (${imbalance.step.formula})` : `the step is up to ${pct(imbalance.estStepSlowdown)} longer than a perfectly balanced split (microbatches per step unknown; the fill and drain that shrink this are left out)`}. Predicted from the graph, not measured.`,
44851
+ fix: reb ? `layersPerStage ${reb.layersPerStage.join(",")}: predicted ${pct(reb.estStepSpeedup)} faster steps${m != null ? ` at ${m} microbatches` : ""} (${pct(reb.asymptoticSpeedup)} as microbatches grow).` : "No contiguous split of whole blocks does better; consider moving the loss onto its own layer (account_for_loss_in_pipeline_split)."
44852
+ });
44853
+ }
44854
+ if (imbalance.rebalanced) {
44855
+ recommendations.push(`Rebalance: layersPerStage ${imbalance.rebalanced.layersPerStage.join(",")} (now ${lps.join(",")}); slowest stage drops from ${imbalance.maxOverMean.toFixed(2)}x to ${imbalance.rebalanced.maxOverMean.toFixed(2)}x the mean, predicted ${pct(imbalance.rebalanced.estStepSpeedup)} faster per step${m != null ? ` at ${m} microbatches` : ""}.`);
44856
+ }
44857
+ } else skipped.push({ check: "stage-balance", reason: "PP 1: one stage, nothing to balance." });
44858
+ let bubble = null;
44859
+ if (pp > 1 && m == null) {
44860
+ skipped.push({ check: "pipeline-bubble", reason: "the microbatches per step are unknown (no readable globalBatch or gradAccum); per-stage memory assumes at least PP microbatches in flight." });
44861
+ } else if (pp > 1 && m != null) {
44862
+ const mb = m;
44863
+ const frac = bubbleFraction(pp, mb, v);
44864
+ const need = microbatchesForBubble(pp, BUBBLE_WARN, v);
44865
+ bubble = { fraction: frac, microbatches: mb, microbatchesForTarget: frac > BUBBLE_WARN ? need : null };
44866
+ checked.push("pipeline-bubble");
44867
+ if (frac > BUBBLE_WARN) {
44868
+ add({
44869
+ rule: "pipeline-bubble",
44870
+ severity: "warn",
44871
+ title: `Pipeline bubble is ${pct(frac)} of each step`,
44872
+ detail: `${schedule === "interleaved" ? `Interleaved (v=${v})` : "1F1B"} with PP ${pp} and ${mb} microbatch${mb === 1 ? "" : "es"} per step: (p-1)${v > 1 ? "/v" : ""} / (m + (p-1)${v > 1 ? "/v" : ""}). Every GPU idles this share of the step.`,
44873
+ fix: `Use at least ${need} microbatches per step (raise grad-accum, lower micro-batch, or lower DP) to bring it under ${pct(BUBBLE_WARN)}${schedule === "1f1b" && pp > 2 ? "; the interleaved schedule also divides it by its virtual stages" : ""}.`
44874
+ });
44875
+ recommendations.push(`Bubble: ${need}+ microbatches per step brings it from ${pct(frac)} to under ${pct(BUBBLE_WARN)}.`);
44876
+ }
44877
+ }
44878
+ const shardDp = dp * cp;
44879
+ const stateBytesPerParam = W_BYTES / (zero >= 3 ? shardDp : 1) + G_BYTES / (zero >= 2 ? shardDp : 1) + O_BYTES / (zero >= 1 ? shardDp : 1);
44880
+ const actFactor = micro * ACT_BYTES / (tp * cp) / 1e9;
44881
+ const stages = [];
44882
+ for (let k = 0; k < lps.length; k++) {
44883
+ const [s, e] = stageRanges[k];
44884
+ const parts = unitList.slice(s, e);
44885
+ if (k === 0 && embFirst) parts.unshift({ kind: "pre", c: preC });
44886
+ if (k === lps.length - 1 && headLast) parts.push({ kind: "post", c: postC });
44887
+ const blocksHere = parts.filter((p) => p.kind === "block").map((p) => p.i + 1);
44888
+ const extras = parts.filter((p) => p.kind !== "block").map((p) => p.kind === "pre" ? "embedding" : "head+loss");
44889
+ const params = parts.reduce((a, p) => a + p.c.params, 0);
44890
+ const expert = parts.reduce((a, p) => a + p.c.expertParams, 0);
44891
+ const paramsPerGpu = (params - expert) / tp + expert / (tp * ep);
44892
+ const stateGb = paramsPerGpu * stateBytesPerParam * OPTIMIZER_K / 1e9;
44893
+ let actElems = 0, largest = 0, maxBlock = 0;
44894
+ for (const p of parts) {
44895
+ largest = Math.max(largest, p.c.largest);
44896
+ if (layout.activationCheckpointing && p.kind === "block") {
44897
+ actElems += p.c.boundaryElems * OUTPUT_K;
44898
+ maxBlock = Math.max(maxBlock, p.c.actElems);
44899
+ } else actElems += p.c.actElems;
44900
+ }
44901
+ actElems += maxBlock;
44902
+ const actPerMb = actElems * actFactor;
44903
+ const transientGb = largest * TRANSIENT_K * actFactor;
44904
+ const mb = m ?? pp;
44905
+ const inflightBase = schedule === "interleaved" ? (pp - k) * (1 + (pp - 1) / (pp * v)) : pp - k;
44906
+ const inflight = Math.min(mb * v, Math.max(1, inflightBase));
44907
+ const hasLoss = parts.some((p) => p.kind === "post");
44908
+ const lossLogitsGb = hasLoss && !fusedCe ? 2 * postC.logits * 4 * micro / (tp * cp) / 1e9 : 0;
44909
+ const peak = stateGb + actPerMb * inflight + transientGb + lossLogitsGb;
44910
+ const flopsHere = sf[k];
44911
+ const mm = gpu ? parts.reduce((a, p) => a + mmMs(p.c, p.kind === "block"), 0) : null;
44912
+ const mem = gpu ? parts.reduce((a, p) => a + memMs(p.c, p.kind === "block"), 0) : null;
44913
+ const memBytes = parts.reduce((a, p) => a + p.c.memBytes * (p.kind === "block" ? recompute : 1), 0) * perGpu;
44914
+ stages.push({
44915
+ index: k,
44916
+ layers: { first: blocksHere.length ? blocksHere[0] : null, last: blocksHere.length ? blocksHere[blocksHere.length - 1] : null, count: blocksHere.length, extras },
44917
+ params,
44918
+ flopsPerToken: flopsHere,
44919
+ estMsPerMicrobatch: mm != null && mem != null ? mm + mem : null,
44920
+ msBreakdown: mm != null && mem != null ? { matmul: mm, memoryBound: mem } : null,
44921
+ memBoundGbPerMicrobatch: memBytes / 1e9,
44922
+ activationGbPerMicrobatch: actPerMb,
44923
+ lossLogitsGb,
44924
+ inFlightMicrobatches: Math.round(inflight * 100) / 100,
44925
+ stateGbPerGpu: stateGb,
44926
+ peakGbPerGpu: peak,
44927
+ peakGbUpperPerGpu: upperPeakGb(peak),
44928
+ fitsGpu: gpu ? fitVerdict(peak, params, gpu.memoryGB) : null
44929
+ });
44930
+ }
44931
+ if (gpu) {
44932
+ checked.push("stage-memory");
44933
+ const over = stages.filter((s) => s.fitsGpu === "does_not_fit");
44934
+ const border = stages.filter((s) => s.fitsGpu === "borderline");
44935
+ if (over.length) {
44936
+ const w = over.reduce((a, b) => b.peakGbPerGpu > a.peakGbPerGpu ? b : a);
44937
+ add({
44938
+ rule: "stage-memory",
44939
+ severity: "block",
44940
+ title: `Stage ${over.map((s) => s.index).join(", ")} does not fit ${gpu.label}: ${gb(w.peakGbPerGpu)} per GPU on stage ${w.index}`,
44941
+ detail: `Weights, gradients and Adam state ${gb(w.stateGbPerGpu)} (ZeRO ${zero}, TP ${tp}${ep > 1 ? `, EP ${ep}` : ""}) plus activations for ${w.inFlightMicrobatches} in-flight microbatch${w.inFlightMicrobatches === 1 ? "" : "es"} at ${gb(w.activationGbPerMicrobatch)} each. Derived, with the same per-layer terms as the training-peak estimate.`,
44942
+ fix: memoryFix(zero, layout.activationCheckpointing, micro, tp, pp)
44943
+ });
44944
+ } else if (border.length) {
44945
+ add({
44946
+ rule: "stage-memory-borderline",
44947
+ severity: "warn",
44948
+ title: `Stage ${border.map((s) => s.index).join(", ")} is borderline on ${gpu.label}`,
44949
+ detail: "The point estimate fits, the calibrated upper bound (x1.43, 95% of held-out runs) with 1.15x headroom does not. Measure once before reserving the full job.",
44950
+ fix: memoryFix(zero, layout.activationCheckpointing, micro, tp, pp)
44951
+ });
44952
+ }
44953
+ }
44954
+ let dpSeq;
44955
+ if (!layout.seqLenHistogram?.length) {
44956
+ skipped.push({ check: "dp-seq-imbalance", reason: "no sequence-length histogram given (seqLenHistogram / --seq-hist); padded or packed fixed-length batches are assumed." });
44957
+ } else if (dp <= 1) {
44958
+ skipped.push({ check: "dp-seq-imbalance", reason: "DP 1: no ranks to wait on each other." });
44959
+ } else {
44960
+ checked.push("dp-seq-imbalance");
44961
+ const fAt = (L) => {
44962
+ const sh = propagateShapes(withSeqLen(model, L).model).shapes;
44963
+ let s = 0;
44964
+ for (const c of model.components) {
44965
+ const x = sh.get(c.id);
44966
+ s += estimateLayerFlops(c.type, c.params ?? {}, x?.in ?? [], x?.out ?? []) || 0;
44967
+ }
44968
+ return s;
44969
+ };
44970
+ const T = Math.max(2, seqLen - seqLen % 2);
44971
+ const f1 = fAt(T), f22 = fAt(T / 2);
44972
+ const b = Math.max(0, 2 * (f1 - 2 * f22) / (T * T));
44973
+ const a = Math.max(0, (f1 - b * T * T) / T);
44974
+ const r = seqImbalance(layout.seqLenHistogram, dp, micro * (m ?? 1), a, b);
44975
+ dpSeq = { expectedMaxOverMean: r.expectedMaxOverMean, estSlowdown: r.expectedMaxOverMean - 1, packedEstimate: r.packedEstimate, method: r.method };
44976
+ if (dpSeq.estSlowdown > SEQ_IMBALANCE_WARN) {
44977
+ add({
44978
+ rule: "dp-seq-imbalance",
44979
+ severity: "warn",
44980
+ title: `Uneven sequence lengths make the slowest of ${dp} DP ranks ~${pct(dpSeq.estSlowdown)} slower than the mean`,
44981
+ detail: `Each rank draws ${micro * (m ?? 1)} sequences per step from your histogram; work per sequence is modelled as a*len + b*len^2 from this graph's FLOPs (attention is the len^2 term). Every rank waits for the slowest at the gradient all-reduce. ${r.method === "monte-carlo" ? "Monte Carlo, fixed seed" : "Normal approximation"}; derived, not measured.`,
44982
+ fix: `Pack sequences to a fixed token budget per rank (with per-document attention masking), predicted ${pct(dpSeq.packedEstimate - 1)}; or bucket by length so ranks in a step draw similar lengths.`
44983
+ });
44984
+ recommendations.push(`Sequence packing: slowest-rank overhead ${pct(dpSeq.estSlowdown)} -> ${pct(dpSeq.packedEstimate - 1)} (predicted).`);
44985
+ }
44986
+ }
44987
+ return finish(imbalance, stages, bubble, dpSeq);
44988
+ function finish(imb, st, bub, seq) {
44989
+ const order = { block: 0, warn: 1, info: 2 };
44990
+ findings.sort((x, y) => order[x.severity] - order[y.severity]);
44991
+ return {
44992
+ checked,
44993
+ skipped,
44994
+ findings,
44995
+ resolved: { ...resolvedBase, layersPerStage: st.length ? lps : null },
44996
+ stages: st,
44997
+ imbalance: imb,
44998
+ bubble: bub,
44999
+ ...seq ? { dpSeqImbalance: seq } : {},
45000
+ recommendations,
45001
+ basis: LAYOUT_BASIS
45002
+ };
45003
+ }
45004
+ }
45005
+ function memoryFix(zero, ac, micro, tp, pp) {
45006
+ const opts = [];
45007
+ if (zero < 1) opts.push("ZeRO-1 / distributed optimizer (shards the 8 bytes/param of Adam state across DP)");
45008
+ if (!ac) opts.push("activation checkpointing");
45009
+ if (micro > 1) opts.push("a smaller micro-batch");
45010
+ if (tp < NODE_SIZE) opts.push(`TP ${tp * 2}`);
45011
+ opts.push(`PP ${pp * 2}`);
45012
+ return `Options, cheapest first: ${opts.join("; ")}.`;
45013
+ }
45014
+ function divisors(n2) {
45015
+ const out = [];
45016
+ for (let d = 1; d <= n2; d++) if (n2 % d === 0) out.push(d);
45017
+ return out;
45018
+ }
45019
+ function fmtFlops2(f) {
45020
+ if (f >= 1e12) return `${(f / 1e12).toFixed(2)} TFLOP`;
45021
+ if (f >= 1e9) return `${(f / 1e9).toFixed(2)} GFLOP`;
45022
+ if (f >= 1e6) return `${(f / 1e6).toFixed(1)} MFLOP`;
45023
+ return `${Math.round(f)} FLOP`;
45024
+ }
45025
+ function renderLayoutText(r, name = "model") {
45026
+ const L = [];
45027
+ const res = r.resolved;
45028
+ L.push(`Parallel layout check: ${name}`);
45029
+ L.push(` ${res.worldSize} GPUs${res.gpu ? ` (${res.gpu}, ${res.gpuMemoryGb} GB)` : ""}, ${res.blocks} blocks, schedule ${res.schedule}${res.virtualStages > 1 ? ` v=${res.virtualStages}` : ""}, ZeRO ${res.zeroStage}${res.microbatchesPerStep != null ? `, ${res.microbatchesPerStep} microbatches/step` : ""}${res.globalBatch != null ? `, global batch ${res.globalBatch}` : ""}`);
45030
+ if (r.stages.length) {
45031
+ L.push("");
45032
+ const head2 = ["stage", "blocks", "extra", "params", "FLOPs/tok", "ms/mb*", "mem-bound", "vs mean", "act/mb", "in-flight", "peak/GPU", "upper", "fits"];
45033
+ const byTime = r.stages.every((s) => s.estMsPerMicrobatch != null);
45034
+ const cost = (s) => byTime ? s.estMsPerMicrobatch : s.flopsPerToken;
45035
+ const mean = r.stages.reduce((a, s) => a + cost(s), 0) / r.stages.length;
45036
+ const rows = r.stages.map((s) => [
45037
+ String(s.index),
45038
+ s.layers.count ? `${s.layers.first}-${s.layers.last} (${s.layers.count})` : "-",
45039
+ s.layers.extras.join("+") || "-",
45040
+ s.params >= 1e9 ? `${(s.params / 1e9).toFixed(2)}B` : `${(s.params / 1e6).toFixed(0)}M`,
45041
+ fmtFlops2(s.flopsPerToken),
45042
+ s.estMsPerMicrobatch != null ? s.estMsPerMicrobatch.toFixed(0) : "-",
45043
+ s.msBreakdown && s.estMsPerMicrobatch ? `${Math.round(s.msBreakdown.memoryBound / s.estMsPerMicrobatch * 100)}%` : "-",
45044
+ `${(cost(s) / mean).toFixed(2)}x`,
45045
+ gb(s.activationGbPerMicrobatch),
45046
+ String(s.inFlightMicrobatches),
45047
+ gb(s.peakGbPerGpu),
45048
+ gb(s.peakGbUpperPerGpu),
45049
+ s.fitsGpu == null ? "n/a" : s.fitsGpu === "does_not_fit" ? "NO" : s.fitsGpu
45050
+ ]);
45051
+ const w = head2.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
45052
+ const line = (cells) => " " + cells.map((c, i) => i <= 2 ? c.padEnd(w[i]) : c.padStart(w[i])).join(" ");
45053
+ L.push(line(head2));
45054
+ for (const row of rows) L.push(line(row));
45055
+ L.push(` * predicted fwd+bwd ms per microbatch per GPU: matmuls at ${Math.round(COMPUTE_BOUND_MFU * 100)}% of peak FLOPs plus memory-bound bytes (the mem-bound share) at ${Math.round(MEM_BW_EFFICIENCY * 100)}% of memory bandwidth. Not measured.`);
45056
+ const loss = r.stages.find((s) => s.lossLogitsGb > 0);
45057
+ if (loss) L.push(` Stage ${loss.index}'s peak includes ${gb(loss.lossLogitsGb)} of fp32 logits and their gradient for the loss (--fused-ce if the loss is fused or chunked).`);
45058
+ }
45059
+ if (r.imbalance) {
45060
+ const im = r.imbalance;
45061
+ const unit = im.costBasis === "time" ? "predicted time" : "FLOPs (unknown card)";
45062
+ L.push("");
45063
+ L.push(` Balance: slowest stage ${im.slowestStage} at ${im.maxOverMean.toFixed(2)}x the mean stage's ${unit}.`);
45064
+ if (im.step.microbatches != null) {
45065
+ const ms = im.step.currentMs != null && im.step.balancedMs != null ? `: ${im.step.currentMs.toFixed(0)} ms vs ${im.step.balancedMs.toFixed(0)} ms balanced` : "";
45066
+ L.push(` Predicted step at ${im.step.microbatches} microbatches (${im.step.formula.replace(/, m = \d+.*$/, "")})${ms}, ${pct(im.estStepSlowdown)} slower than a perfect split (${pct(im.asymptoticSlowdown)} as microbatches grow).`);
45067
+ } else {
45068
+ L.push(` Microbatches per step unknown: up to ${pct(im.estStepSlowdown)} slower than a perfect split, the asymptotic ratio, which overstates the gap at small microbatch counts.`);
45069
+ }
45070
+ if (im.rebalanced) {
45071
+ const rb = im.rebalanced;
45072
+ L.push(` Rebalanced split ${rb.layersPerStage.join(",")}: ${rb.maxOverMean.toFixed(2)}x, predicted ${pct(rb.estStepSpeedup)} faster per step${im.step.microbatches != null ? ` at ${im.step.microbatches} microbatches${rb.stepMs != null ? ` (${rb.stepMs.toFixed(0)} ms)` : ""}; ${pct(rb.asymptoticSpeedup)} as microbatches grow` : ""}.`);
45073
+ }
45074
+ }
45075
+ if (r.bubble) L.push(` Bubble: ${pct(r.bubble.fraction)} at ${r.bubble.microbatches} microbatch${r.bubble.microbatches === 1 ? "" : "es"}/step${r.bubble.microbatchesForTarget ? ` (${r.bubble.microbatchesForTarget}+ for under ${pct(BUBBLE_WARN)})` : ""}.`);
45076
+ if (r.dpSeqImbalance) L.push(` DP sequence imbalance: slowest rank ${r.dpSeqImbalance.expectedMaxOverMean.toFixed(3)}x the mean; packed ${r.dpSeqImbalance.packedEstimate.toFixed(3)}x (${r.dpSeqImbalance.method}).`);
45077
+ L.push("");
45078
+ if (!r.findings.length) L.push(" No findings on the checks that ran.");
45079
+ for (const f of r.findings) {
45080
+ L.push(` ${f.severity.padEnd(5)} ${f.title}`);
45081
+ L.push(` ${f.detail}`);
45082
+ L.push(` fix: ${f.fix}`);
45083
+ }
45084
+ L.push("");
45085
+ L.push(` checked: ${r.checked.join(", ") || "none"}`);
45086
+ for (const s of r.skipped) L.push(` skipped ${s.check}: ${s.reason}`);
45087
+ L.push("");
45088
+ L.push(` ${r.basis}`);
45089
+ return L.join("\n") + "\n";
45090
+ }
45091
+
44054
45092
  // src/utils/trainCost.ts
44055
45093
  init_paramEstimator();
44056
45094
  var GPU_CATALOG = {
@@ -44381,7 +45419,7 @@ var DOES_NOT_KNOW = [
44381
45419
  "Output logits upcast to fp32, and per-token entropy or log-probabilities over a large vocabulary (as TRL computes them): batch x tokens x vocabulary x 4 bytes, which on a 150k-token vocabulary can be several GB on its own."
44382
45420
  ];
44383
45421
  var usd = (n2) => Math.abs(n2) >= 1e3 ? `$${Math.round(n2).toLocaleString("en-US")}` : `$${n2.toFixed(2)}`;
44384
- var gb = (n2) => n2 == null ? "" : n2 >= 10 ? n2.toFixed(0) : n2.toFixed(1);
45422
+ var gb2 = (n2) => n2 == null ? "" : n2 >= 10 ? n2.toFixed(0) : n2.toFixed(1);
44385
45423
  var md = (s) => s.replace(/\|/g, "\\|");
44386
45424
  function headline(r) {
44387
45425
  const t = r.totals;
@@ -44403,7 +45441,7 @@ function renderMarkdown(r) {
44403
45441
  j.attention === "eager" ? "eager attention" : ""
44404
45442
  ].filter(Boolean).join(", ");
44405
45443
  const note = [extras, j.reason ?? ""].filter(Boolean).join("; ");
44406
- L.push(`| ${md(j.jobId)} | ${md(j.model)} | ${j.requested?.label ?? ""} | ${j.batch ?? ""} | ${j.hours ?? ""} | ${gb(j.needGb)} | ${j.smallestCard ?? (j.needGb != null ? "none single" : "")} | ${j.verdict}${j.fit === "borderline" ? " (borderline)" : ""} | ${j.verdict === "over" ? j.rightSized?.label ?? "" : j.verdict === "right-sized" ? "as requested" : ""} | ${usd(j.spentUsd)} | ${j.savedUsd > 0 ? usd(j.savedUsd) : "-"} | ${md(note)} |`);
45444
+ L.push(`| ${md(j.jobId)} | ${md(j.model)} | ${j.requested?.label ?? ""} | ${j.batch ?? ""} | ${j.hours ?? ""} | ${gb2(j.needGb)} | ${j.smallestCard ?? (j.needGb != null ? "none single" : "")} | ${j.verdict}${j.fit === "borderline" ? " (borderline)" : ""} | ${j.verdict === "over" ? j.rightSized?.label ?? "" : j.verdict === "right-sized" ? "as requested" : ""} | ${usd(j.spentUsd)} | ${j.savedUsd > 0 ? usd(j.savedUsd) : "-"} | ${md(note)} |`);
44407
45445
  }
44408
45446
  L.push("", "## Method", "", METHOD, "");
44409
45447
  L.push("## Prices", "", `Default: ${r.prices.source}.` + (r.prices.overridden.length ? ` Overridden by --prices: ${r.prices.overridden.join(", ")}.` : " Pass --prices to use your own rates."), "");
@@ -44415,14 +45453,1274 @@ function renderMarkdown(r) {
44415
45453
  return L.join("\n");
44416
45454
  }
44417
45455
 
45456
+ // src/utils/serveConfigCheck.ts
45457
+ init_paramEstimator();
45458
+ var SERVE_ENGINES = ["vllm", "sglang", "llamacpp"];
45459
+ var SERVE_BASIS = "Derived from config.json, the engine flags and the card, not measured. Card memory is the nominal GB; the engine's own reserve (activation profiling, CUDA graphs, communication buffers) is not counted, so every KV capacity and concurrency here is an upper bound. Template checks read files and do not render a conversation, so they cannot prove two stacks produce the same prompt.";
45460
+ var CARD_SM = {
45461
+ "b200": 100,
45462
+ "h200": 90,
45463
+ "h100-sxm": 90,
45464
+ "a100-80g": 80,
45465
+ "a100-40g": 80,
45466
+ "l40s": 89,
45467
+ "l4": 89,
45468
+ "a10g": 86,
45469
+ "t4": 75,
45470
+ "v100": 70,
45471
+ "rtx-4090": 89,
45472
+ "rtx-3090": 86
45473
+ };
45474
+ var VLLM_QUANT_TABLE = 'vLLM docs, "Supported Hardware" quantization table (docs.vllm.ai/en/latest/features/quantization/)';
45475
+ var QUANT_SUPPORT = [
45476
+ {
45477
+ method: "fp8",
45478
+ nativeSm: 89,
45479
+ fallbackSm: 75,
45480
+ fallbackNote: "runs as weight-only W8A16 through the FP8 Marlin kernel: weights are stored in fp8, the matmuls run in 16 bits, so the memory saving is there and the FP8 compute speedup is not",
45481
+ source: 'vLLM docs, FP8 W8A8: "FP8 computation is supported on NVIDIA GPUs with compute capability >= 8.9"; "FP8 models will run on compute capability >= 7.5 (Turing) as weight-only W8A16, utilizing FP8 Marlin" (docs.vllm.ai/en/latest/features/quantization/llm_compressor/fp8/)'
45482
+ },
45483
+ {
45484
+ method: "mxfp4",
45485
+ nativeSm: 90,
45486
+ fallbackSm: 80,
45487
+ fallbackNote: "runs on Ampere and Ada through the Marlin MXFP4 MoE kernel (weight-only), not the Hopper / Blackwell MXFP4 path",
45488
+ source: 'vLLM gpt-oss recipe: "GPT-OSS works on Ampere devices by default, using the TRITON_ATTN attention backend and Marlin MXFP4 MoE"; the quantization table footnote: "Turing does not support Marlin MXFP4" (docs.vllm.ai/projects/recipes/en/latest/OpenAI/GPT-OSS.html)'
45489
+ },
45490
+ {
45491
+ method: "nvfp4",
45492
+ nativeSm: 100,
45493
+ fallbackSm: 75,
45494
+ fallbackNote: "FP4 tensor cores are Blackwell (sm100) only; elsewhere the weights run weight-only through the Marlin FP4 kernel",
45495
+ source: `${VLLM_QUANT_TABLE}: Marlin (GPTQ/AWQ/FP8/FP4) supported from Turing`
45496
+ },
45497
+ { method: "awq", nativeSm: 75, fallbackSm: 75, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: AWQ not on Volta (sm70)` },
45498
+ { method: "gptq", nativeSm: 70, fallbackSm: 70, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: GPTQ Volta and later` },
45499
+ { method: "marlin", nativeSm: 75, fallbackSm: 75, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: Marlin (GPTQ/AWQ/FP8/FP4) not on Volta` },
45500
+ { method: "int8", nativeSm: 75, fallbackSm: 75, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: llm-compressor INT8 (W8A8) not on Volta` },
45501
+ { method: "bitsandbytes", nativeSm: 70, fallbackSm: 70, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: bitsandbytes Volta and later` },
45502
+ { method: "gguf", nativeSm: 70, fallbackSm: 70, fallbackNote: null, source: `${VLLM_QUANT_TABLE}: GGUF Volta and later` }
45503
+ ];
45504
+ var BF16_MIN_SM = 80;
45505
+ var BF16_SOURCE = 'bf16 tensor cores start at Ampere (sm80); vLLM refuses an explicit --dtype bfloat16 below it ("Bfloat16 is only supported on GPUs with compute capability of at least 8.0")';
45506
+ var GGUF_BPW = {
45507
+ IQ1_S: 2.0042,
45508
+ IQ1_M: 2.146,
45509
+ IQ2_XXS: 2.3824,
45510
+ IQ2_XS: 2.5882,
45511
+ IQ2_S: 2.7403,
45512
+ IQ2_M: 2.9294,
45513
+ IQ3_XXS: 3.2548,
45514
+ IQ3_XS: 3.4977,
45515
+ IQ3_S: 3.6606,
45516
+ IQ3_M: 3.7628,
45517
+ IQ4_XS: 4.4597,
45518
+ IQ4_NL: 4.6818,
45519
+ Q2_K_S: 2.9697,
45520
+ Q2_K: 3.1593,
45521
+ Q3_K_S: 3.6429,
45522
+ Q3_K_M: 3.996,
45523
+ Q3_K_L: 4.2979,
45524
+ Q4_K_S: 4.6672,
45525
+ Q4_K_M: 4.8944,
45526
+ Q5_K_S: 5.5704,
45527
+ Q5_K_M: 5.7036,
45528
+ Q6_K: 6.5633,
45529
+ Q8_0: 8.5008,
45530
+ F16: 16.0005,
45531
+ BF16: 16,
45532
+ F32: 32,
45533
+ MXFP4: 4.25
45534
+ };
45535
+ var GGUF_BPW_SOURCE = "llama.cpp tools/quantize/README.md, bits/weight measured on meta-llama/Llama-3.1-8B";
45536
+ var GGUF_KV_BYTES = {
45537
+ f32: 4,
45538
+ f16: 2,
45539
+ bf16: 2,
45540
+ q8_0: 34 / 32,
45541
+ q4_0: 18 / 32,
45542
+ q4_1: 20 / 32,
45543
+ iq4_nl: 18 / 32,
45544
+ q5_0: 22 / 32,
45545
+ q5_1: 24 / 32
45546
+ };
45547
+ var ENGINE_SAMPLER_DEFAULTS = {
45548
+ // OpenAI-compatible defaults used when --generation-config vllm turns the model's file off.
45549
+ vllm: { temperature: 1, top_p: 1, top_k: 0, repetition_penalty: 1, source: "vLLM SamplingParams defaults (temperature 1.0, top_p 1.0, top_k off, repetition_penalty 1.0)" },
45550
+ sglang: { temperature: 1, top_p: 1, top_k: 0, repetition_penalty: 1, source: "SGLang sampling defaults when not taken from the model (temperature 1.0, top_p 1.0, top_k off)" },
45551
+ llamacpp: { temperature: 0.8, top_p: 0.95, top_k: 40, repetition_penalty: 1, source: "llama.cpp tools/server/README.md: --temp 0.80, --top-k 40, --top-p 0.95, --repeat-penalty 1.00 (and --min-p 0.05)" }
45552
+ };
45553
+ var KNOWN_SERVE_ISSUES = [
45554
+ {
45555
+ id: "gpt-oss-jinja-vs-harmony",
45556
+ match: /gpt[_-]?oss/i,
45557
+ engines: ["sglang", "llamacpp"],
45558
+ severity: "warn",
45559
+ title: "gpt-oss: the Jinja chat template in the repo was reported to diverge from the harmony training format",
45560
+ detail: "Same weights, same payload, same harness: 0.400 on vllm-mlx against 0.650 on Ollama on a 20-task agentic benchmark. The bundled template differs from harmony in developer-block order, tool-call header placement and tool-result wrapping. An engine that renders the Jinja template inherits that; vLLM renders gpt-oss through openai-harmony instead.",
45561
+ fix: "Render through openai-harmony, or diff a rendered 5-message conversation with tool calls against harmony's output before serving.",
45562
+ source: "github.com/waybarrios/vllm-mlx/issues/568; vLLM gpt-oss recipe (openai-harmony rendering)"
45563
+ },
45564
+ {
45565
+ id: "kimi-k2-tool-calls",
45566
+ match: /kimi[_-]?k2/i,
45567
+ engines: ["vllm", "sglang", "llamacpp"],
45568
+ severity: "warn",
45569
+ title: "Kimi K2: tool-call accuracy and decoding parameters vary by host",
45570
+ detail: "Moonshot's K2 Vendor Verifier measured tool-call schema accuracy from 100% (Moonshot) down to 87.22% (a vLLM deployment) for kimi-k2-thinking, and says a significant share of discrepancies came from decoding-parameter misuse.",
45571
+ fix: "Set the K2 tool-call parser (--tool-call-parser kimi_k2), keep the model card's temperature, and run the vendor verifier before taking traffic.",
45572
+ source: "github.com/MoonshotAI/K2-Vendor-Verifier; kimi.com/blog/kimi-vendor-verifier"
45573
+ },
45574
+ {
45575
+ id: "qwen3-greedy",
45576
+ match: /^qwen3/i,
45577
+ engines: ["vllm", "sglang", "llamacpp"],
45578
+ severity: "warn",
45579
+ title: "Qwen3 is served with temperature 0 (greedy)",
45580
+ detail: "The Qwen3 model card says not to use greedy decoding in thinking mode: it can cause performance degradation and endless repetition.",
45581
+ fix: "Use the model card's values (thinking: temperature 0.6, top_p 0.95, top_k 20).",
45582
+ source: 'Qwen3 model card, "Best Practices" (huggingface.co/Qwen/Qwen3-8B)',
45583
+ when: ({ sampler }) => sampler.temperature === 0
45584
+ }
45585
+ ];
45586
+ function tokenizeCommand(cmd) {
45587
+ const out = [];
45588
+ let cur = "";
45589
+ let has = false;
45590
+ let q = null;
45591
+ const s = cmd.replace(/\\\r?\n/g, " ");
45592
+ for (let i = 0; i < s.length; i++) {
45593
+ const ch = s[i];
45594
+ if (q) {
45595
+ if (ch === q) {
45596
+ q = null;
45597
+ continue;
45598
+ }
45599
+ if (ch === "\\" && q === '"' && i + 1 < s.length && /["\\$`]/.test(s[i + 1])) {
45600
+ cur += s[++i];
45601
+ continue;
45602
+ }
45603
+ cur += ch;
45604
+ continue;
45605
+ }
45606
+ if (ch === '"' || ch === "'") {
45607
+ q = ch;
45608
+ has = true;
45609
+ continue;
45610
+ }
45611
+ if (ch === "\\" && i + 1 < s.length) {
45612
+ cur += s[++i];
45613
+ has = true;
45614
+ continue;
45615
+ }
45616
+ if (/\s/.test(ch)) {
45617
+ if (has || cur) {
45618
+ out.push(cur);
45619
+ cur = "";
45620
+ has = false;
45621
+ }
45622
+ continue;
45623
+ }
45624
+ cur += ch;
45625
+ has = true;
45626
+ }
45627
+ if (has || cur) out.push(cur);
45628
+ return out;
45629
+ }
45630
+ function detectEngine(tokens) {
45631
+ const joined = tokens.join(" ");
45632
+ if (/\bsglang(\.launch_server|\s+serve)\b|sglang\.launch_server/.test(joined)) return "sglang";
45633
+ if (/(^|\s|\/)vllm\s+serve\b|vllm\.entrypoints/.test(joined)) return "vllm";
45634
+ if (/(^|\s|\/)(llama-server|llama-cli|llama-run|server)(\s|$)/.test(joined) && /(^|\s)(-m|--model|-hf|-hfr|--hf-repo)(\s|=)/.test(joined)) return "llamacpp";
45635
+ if (/(^|\s|\/)llama-(server|cli)(\s|$)/.test(joined)) return "llamacpp";
45636
+ return null;
45637
+ }
45638
+ function readTokenCount(v) {
45639
+ if (typeof v === "number") return Number.isInteger(v) && v > 0 ? v : null;
45640
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([kKmM]?)\s*$/.exec(String(v ?? ""));
45641
+ if (!m) return null;
45642
+ const mult = m[2] === "" ? 1 : /k/i.test(m[2]) ? 1024 : 1024 * 1024;
45643
+ const n2 = Math.round(Number(m[1]) * mult);
45644
+ return n2 > 0 ? n2 : null;
45645
+ }
45646
+ var num3 = (v) => {
45647
+ const n2 = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
45648
+ return Number.isFinite(n2) ? n2 : null;
45649
+ };
45650
+ var posInt4 = (v) => {
45651
+ const n2 = num3(v);
45652
+ return n2 != null && Number.isInteger(n2) && n2 > 0 ? n2 : null;
45653
+ };
45654
+ function parseJsonObject(v) {
45655
+ if (v == null) return null;
45656
+ try {
45657
+ const o = JSON.parse(v);
45658
+ return o && typeof o === "object" && !Array.isArray(o) ? o : null;
45659
+ } catch {
45660
+ return null;
45661
+ }
45662
+ }
45663
+ var BOOL_FLAGS = /* @__PURE__ */ new Set([
45664
+ "--enable-expert-parallel",
45665
+ "--enable-auto-tool-choice",
45666
+ "--trust-remote-code",
45667
+ "--enforce-eager",
45668
+ "--enable-prefix-caching",
45669
+ "--no-enable-prefix-caching",
45670
+ "--enable-chunked-prefill",
45671
+ "--disable-log-requests",
45672
+ "--disable-log-stats",
45673
+ "--enable-reasoning",
45674
+ "--enable-ep-moe",
45675
+ "--enable-dp-attention",
45676
+ "--disable-radix-cache",
45677
+ "--disable-cuda-graph",
45678
+ "--enable-torch-compile",
45679
+ "--enable-lora",
45680
+ "--jinja",
45681
+ "--no-jinja",
45682
+ "-cb",
45683
+ "--cont-batching",
45684
+ "-nocb",
45685
+ "--no-cont-batching",
45686
+ "-kvu",
45687
+ "--kv-unified",
45688
+ "-no-kvu",
45689
+ "--no-kv-unified",
45690
+ "--mlock",
45691
+ "--no-mmap",
45692
+ "--verbose",
45693
+ "-v",
45694
+ "--metrics",
45695
+ "--embedding",
45696
+ "--embeddings",
45697
+ "--async-scheduling"
45698
+ ]);
45699
+ function parseServeCommand(cmd, engineHint) {
45700
+ const tokens = Array.isArray(cmd) ? cmd : tokenizeCommand(cmd);
45701
+ const engine = engineHint ?? detectEngine(tokens);
45702
+ const flags = /* @__PURE__ */ new Map();
45703
+ const positional = [];
45704
+ for (let i = 0; i < tokens.length; i++) {
45705
+ const t = tokens[i];
45706
+ if (t === "-m" && i > 0 && /(^|\/)python[\d.]*$/.test(tokens[i - 1])) {
45707
+ positional.push(tokens[++i] ?? "");
45708
+ continue;
45709
+ }
45710
+ if (/^--?[A-Za-z]/.test(t)) {
45711
+ const eq = t.indexOf("=");
45712
+ if (eq > 0) {
45713
+ flags.set(t.slice(0, eq), t.slice(eq + 1));
45714
+ continue;
45715
+ }
45716
+ const next = tokens[i + 1];
45717
+ if (BOOL_FLAGS.has(t) || next == null || /^--?[A-Za-z]/.test(next)) {
45718
+ flags.set(t, true);
45719
+ continue;
45720
+ }
45721
+ flags.set(t, next);
45722
+ i++;
45723
+ continue;
45724
+ }
45725
+ positional.push(t);
45726
+ }
45727
+ const used = /* @__PURE__ */ new Set();
45728
+ const get = (...names) => {
45729
+ for (const n2 of names) {
45730
+ if (flags.has(n2)) {
45731
+ used.add(n2);
45732
+ const v = flags.get(n2);
45733
+ return v === true ? "true" : v;
45734
+ }
45735
+ }
45736
+ return void 0;
45737
+ };
45738
+ const has = (...names) => names.some((n2) => {
45739
+ if (flags.has(n2)) {
45740
+ used.add(n2);
45741
+ return true;
45742
+ }
45743
+ return false;
45744
+ });
45745
+ const args = {};
45746
+ const setNum = (k, v, reader = posInt4) => {
45747
+ if (v == null) return;
45748
+ const n2 = reader(v);
45749
+ if (n2 != null) args[k] = n2;
45750
+ };
45751
+ if (engine === "vllm" || engine === "sglang") {
45752
+ if (engine === "vllm") {
45753
+ const si = positional.findIndex((p) => p === "serve");
45754
+ const pm = si >= 0 ? positional[si + 1] : void 0;
45755
+ args.model = get("--model") ?? pm;
45756
+ setNum("tp", get("--tensor-parallel-size", "-tp"));
45757
+ setNum("pp", get("--pipeline-parallel-size", "-pp"));
45758
+ setNum("dp", get("--data-parallel-size", "-dp"));
45759
+ if (has("--enable-expert-parallel")) args.expertParallel = true;
45760
+ setNum("maxModelLen", get("--max-model-len"), readTokenCount);
45761
+ setNum("maxNumSeqs", get("--max-num-seqs"));
45762
+ setNum("gpuMemoryUtilization", get("--gpu-memory-utilization"), num3);
45763
+ const rope = parseJsonObject(get("--rope-scaling"));
45764
+ const hfo = parseJsonObject(get("--hf-overrides"));
45765
+ if (rope) args.ropeScaling = rope;
45766
+ if (hfo?.rope_scaling && typeof hfo.rope_scaling === "object") args.ropeScaling = hfo.rope_scaling;
45767
+ if (hfo && posInt4(hfo.max_position_embeddings) != null) args.maxPositionOverride = posInt4(hfo.max_position_embeddings);
45768
+ args.generationConfigMode = get("--generation-config");
45769
+ const ogc = parseJsonObject(get("--override-generation-config"));
45770
+ if (ogc) args.samplerFlags = readSampler(ogc);
45771
+ if (has("--enable-auto-tool-choice")) args.enableAutoToolChoice = true;
45772
+ } else {
45773
+ args.model = get("--model-path", "--model");
45774
+ setNum("tp", get("--tp-size", "--tp", "--tensor-parallel-size"));
45775
+ setNum("pp", get("--pp-size", "--pipeline-parallel-size"));
45776
+ setNum("dp", get("--dp-size", "--dp", "--data-parallel-size"));
45777
+ setNum("epSize", get("--ep-size", "--ep", "--expert-parallel-size"));
45778
+ if (has("--enable-ep-moe") || args.epSize != null && args.epSize > 1) args.expertParallel = true;
45779
+ setNum("maxModelLen", get("--context-length"), readTokenCount);
45780
+ setNum("maxNumSeqs", get("--max-running-requests"));
45781
+ setNum("memFractionStatic", get("--mem-fraction-static"), num3);
45782
+ const over = parseJsonObject(get("--json-model-override-args"));
45783
+ if (over?.rope_scaling && typeof over.rope_scaling === "object") args.ropeScaling = over.rope_scaling;
45784
+ if (over && posInt4(over.max_position_embeddings) != null) args.maxPositionOverride = posInt4(over.max_position_embeddings);
45785
+ args.generationConfigMode = get("--sampling-defaults");
45786
+ }
45787
+ args.dtype = get("--dtype");
45788
+ args.quantization = get("--quantization", "-q");
45789
+ args.kvCacheDtype = get("--kv-cache-dtype");
45790
+ args.chatTemplate = get("--chat-template");
45791
+ args.toolCallParser = get("--tool-call-parser");
45792
+ args.reasoningParser = get("--reasoning-parser");
45793
+ } else if (engine === "llamacpp") {
45794
+ const m = get("-m", "--model");
45795
+ const hf = get("-hf", "-hfr", "--hf-repo");
45796
+ const hff = get("-hff", "--hf-file");
45797
+ args.model = m ?? hf;
45798
+ args.ggufFile = hff ?? m ?? (hf ? hf.includes(":") ? hf : `${hf}:Q4_K_M` : void 0);
45799
+ const c = get("-c", "--ctx-size");
45800
+ if (c != null) {
45801
+ const n2 = num3(c);
45802
+ if (n2 != null && n2 >= 0) args.ctxSize = n2;
45803
+ }
45804
+ const ngl = get("-ngl", "--gpu-layers", "--n-gpu-layers");
45805
+ if (ngl != null) args.nGpuLayers = ngl === "all" || ngl === "auto" ? ngl : posInt4(ngl) ?? (num3(ngl) === 0 ? 0 : "auto");
45806
+ const np = get("-np", "--parallel", "--n-parallel");
45807
+ if (np != null) {
45808
+ const n2 = num3(np);
45809
+ if (n2 != null && n2 > 0) args.nParallel = n2;
45810
+ }
45811
+ if (has("-kvu", "--kv-unified")) args.kvUnified = true;
45812
+ if (has("-no-kvu", "--no-kv-unified")) args.kvUnified = false;
45813
+ args.cacheTypeK = get("-ctk", "--cache-type-k");
45814
+ args.cacheTypeV = get("-ctv", "--cache-type-v");
45815
+ args.ropeScalingType = get("--rope-scaling");
45816
+ setNum("ropeScale", get("--rope-scale"), num3);
45817
+ setNum("yarnOrigCtx", get("--yarn-orig-ctx"));
45818
+ args.chatTemplate = get("--chat-template", "--chat-template-file");
45819
+ const s = {};
45820
+ const t = num3(get("--temp", "--temperature"));
45821
+ if (t != null) s.temperature = t;
45822
+ const tp = num3(get("--top-p"));
45823
+ if (tp != null) s.top_p = tp;
45824
+ const tk = num3(get("--top-k"));
45825
+ if (tk != null) s.top_k = tk;
45826
+ const rp = num3(get("--repeat-penalty"));
45827
+ if (rp != null) s.repetition_penalty = rp;
45828
+ if (Object.keys(s).length) args.samplerFlags = s;
45829
+ }
45830
+ for (const k of Object.keys(args)) if (args[k] == null) delete args[k];
45831
+ const ignored = [...flags.keys()].filter((f) => !used.has(f));
45832
+ return { engine, args, ignored };
45833
+ }
45834
+ function readSampler(raw) {
45835
+ const r = raw && typeof raw === "object" ? raw : {};
45836
+ const out = {};
45837
+ const pick = (k, ...names) => {
45838
+ for (const n2 of names) {
45839
+ const v = num3(r[n2]);
45840
+ if (v != null) {
45841
+ out[k] = v;
45842
+ return;
45843
+ }
45844
+ }
45845
+ };
45846
+ pick("temperature", "temperature", "temp");
45847
+ pick("top_p", "top_p", "topP");
45848
+ pick("top_k", "top_k", "topK");
45849
+ pick("repetition_penalty", "repetition_penalty", "repetitionPenalty", "repeat_penalty");
45850
+ return out;
45851
+ }
45852
+ function normalizeQuant(q) {
45853
+ if (q == null) return null;
45854
+ const s = String(q).toLowerCase().replace(/-/g, "_");
45855
+ if (!s || s === "none" || s === "null") return null;
45856
+ if (/^fp8|fbgemm_fp8|^ptpc_fp8|^modelopt$/.test(s)) return "fp8";
45857
+ if (/mxfp4/.test(s)) return "mxfp4";
45858
+ if (/nvfp4|modelopt_fp4|fp4/.test(s)) return "nvfp4";
45859
+ if (/^awq_marlin|^gptq_marlin|^marlin|machete/.test(s)) return "marlin";
45860
+ if (/^awq/.test(s)) return "awq";
45861
+ if (/^gptq/.test(s)) return "gptq";
45862
+ if (/bitsandbytes|bnb/.test(s)) return "bitsandbytes";
45863
+ if (/gguf/.test(s)) return "gguf";
45864
+ if (/int8|w8a8|smoothquant/.test(s)) return "int8";
45865
+ return s;
45866
+ }
45867
+ function checkpointQuant(config) {
45868
+ const qc = config?.quantization_config ?? null;
45869
+ if (!qc || typeof qc !== "object") return { method: null, raw: null, bits: null, blockN: null };
45870
+ let raw = qc.quant_method != null ? String(qc.quant_method) : null;
45871
+ let bits = posInt4(qc.bits) ?? posInt4(qc.w_bit);
45872
+ if (raw === "compressed-tensors") {
45873
+ const groups = qc.config_groups ?? {};
45874
+ const w = Object.values(groups)[0]?.weights;
45875
+ if (w?.num_bits === 8 && w.type === "float") raw = "fp8";
45876
+ else if (w?.num_bits === 4 && w.type === "float") raw = "nvfp4";
45877
+ else if (w?.num_bits === 8) raw = "int8";
45878
+ else if (w?.num_bits === 4) {
45879
+ raw = "gptq";
45880
+ bits = 4;
45881
+ }
45882
+ }
45883
+ if (raw === "bitsandbytes") bits = qc.load_in_8bit === true ? 8 : 4;
45884
+ const wbs = Array.isArray(qc.weight_block_size) ? qc.weight_block_size.map(posInt4) : null;
45885
+ return { method: normalizeQuant(raw), raw, bits, blockN: wbs?.[0] ?? null };
45886
+ }
45887
+ var isMoe = (c) => /moe/i.test(c.type);
45888
+ var isLmHead = (c, comps) => c.type === "linear" && comps.filter((x) => x.type === "linear").pop() === c;
45889
+ function paramSplit(model) {
45890
+ let total = 0, expert = 0, edge = 0;
45891
+ const comps = model.components ?? [];
45892
+ for (const c of comps) {
45893
+ const p = estimateLayerParams(c.type, c.params, c.inputShape);
45894
+ total += p;
45895
+ if (isMoe(c)) expert += p;
45896
+ if (c.type === "embedding" || isLmHead(c, comps)) edge += p;
45897
+ }
45898
+ return { total, expert, edge };
45899
+ }
45900
+ var DTYPE_BYTES = { bf16: 2, fp16: 2, fp32: 4 };
45901
+ function normDtype(d) {
45902
+ if (d == null) return null;
45903
+ const s = String(d).toLowerCase();
45904
+ if (s === "auto") return "auto";
45905
+ if (/bfloat16|bf16/.test(s)) return "bf16";
45906
+ if (/float16|half|fp16/.test(s)) return "fp16";
45907
+ if (/float32|fp32|float$/.test(s)) return "fp32";
45908
+ return null;
45909
+ }
45910
+ function ggufQuantOf(file) {
45911
+ if (!file) return null;
45912
+ const s = file.toUpperCase();
45913
+ const keys = Object.keys(GGUF_BPW).sort((a, b) => b.length - a.length);
45914
+ for (const k of keys) {
45915
+ const re = new RegExp(`(^|[^A-Z0-9])${k.replace(/_/g, "[_-]")}([^A-Z0-9]|$)`);
45916
+ if (re.test(s)) return k;
45917
+ }
45918
+ return null;
45919
+ }
45920
+ function derivedMaxLen(config, ropeOverride, maxPosOverride, graphMax) {
45921
+ const c = config ?? {};
45922
+ const native = maxPosOverride ?? posInt4(c.max_position_embeddings) ?? posInt4(c.n_positions) ?? posInt4(c.max_seq_len) ?? posInt4(c.seq_length) ?? graphMax ?? null;
45923
+ const rope = ropeOverride ?? (c.rope_scaling && typeof c.rope_scaling === "object" ? c.rope_scaling : null);
45924
+ if (native == null) return { len: null, native: null, rope };
45925
+ if (!rope) return { len: native, native, rope: null };
45926
+ const type = String(rope.rope_type ?? rope.type ?? "").toLowerCase();
45927
+ const factor = num3(rope.factor);
45928
+ if (!factor || ["llama3", "longrope", "su", "mrope", "default"].includes(type)) return { len: native, native, rope };
45929
+ const base = type === "yarn" ? posInt4(rope.original_max_position_embeddings) ?? native : native;
45930
+ return { len: Math.floor(base * factor), native, rope };
45931
+ }
45932
+ function chatTemplateOf(side) {
45933
+ if (typeof side.chatTemplateFile === "string" && side.chatTemplateFile.trim()) return side.chatTemplateFile;
45934
+ const t = side.tokenizerConfig?.chat_template;
45935
+ if (typeof t === "string") return t;
45936
+ if (Array.isArray(t)) {
45937
+ const d = t.find((x) => x.name === "default") ?? t[0];
45938
+ return typeof d?.template === "string" ? d.template : null;
45939
+ }
45940
+ return null;
45941
+ }
45942
+ function templateHash(s) {
45943
+ let h = 2166136261;
45944
+ for (let i = 0; i < s.length; i++) {
45945
+ h ^= s.charCodeAt(i);
45946
+ h = Math.imul(h, 16777619);
45947
+ }
45948
+ return (h >>> 0).toString(16).padStart(8, "0");
45949
+ }
45950
+ var gbs = (x) => `${x.toFixed(x < 10 ? 2 : 1)} GB`;
45951
+ var divisors2 = (n2) => {
45952
+ const d = [];
45953
+ for (let i = 1; i <= n2; i++) if (n2 % i === 0) d.push(i);
45954
+ return d;
45955
+ };
45956
+ function weightBytes(split, dtypeBytes, quant, bits, engine, ggufType) {
45957
+ const { total, expert, edge } = split;
45958
+ if (engine === "llamacpp") {
45959
+ if (!ggufType) return null;
45960
+ const bpw = GGUF_BPW[ggufType];
45961
+ return { bytes: total * bpw / 8, basis: `${ggufType} at ${bpw} bits per weight (${GGUF_BPW_SOURCE}); mixed per-tensor types make this approximate` };
45962
+ }
45963
+ const body = total - edge;
45964
+ switch (quant) {
45965
+ case null:
45966
+ return { bytes: total * dtypeBytes, basis: `${dtypeBytes} bytes per parameter (${dtypeBytes === 4 ? "fp32" : "16-bit"})` };
45967
+ case "fp8":
45968
+ return { bytes: body * 1 + edge * 2, basis: "fp8 weights (1 byte) with the embedding and LM head kept 16-bit" };
45969
+ case "int8":
45970
+ return { bytes: body * 1 + edge * 2, basis: "int8 weights (1 byte) with the embedding and LM head kept 16-bit" };
45971
+ case "mxfp4": {
45972
+ const ex = expert > 0 ? expert : body;
45973
+ return { bytes: ex * 4.25 / 8 + (total - ex) * dtypeBytes, basis: "MXFP4 experts at 4.25 bits (4-bit values plus a shared 8-bit scale per 32) and everything else 16-bit, as gpt-oss's modules_to_not_convert lists" };
45974
+ }
45975
+ case "nvfp4":
45976
+ return { bytes: body * 4.5 / 8 + edge * 2, basis: "NVFP4 weights at 4.5 bits (4-bit values plus an fp8 scale per 16), embedding and LM head 16-bit" };
45977
+ case "bitsandbytes": {
45978
+ const b = bits === 8 ? 8 : 4.5;
45979
+ return { bytes: body * b / 8 + edge * 2, basis: `bitsandbytes ${bits === 8 ? "int8" : "nf4"} at ${b} bits, embedding and LM head 16-bit` };
45980
+ }
45981
+ case "awq":
45982
+ case "gptq":
45983
+ case "marlin":
45984
+ default: {
45985
+ const b = (bits ?? 4) + 0.25;
45986
+ return { bytes: body * b / 8 + edge * 2, basis: `${bits ?? 4}-bit weights plus group scales (~${b} bits at group size 128), embedding and LM head 16-bit` };
45987
+ }
45988
+ }
45989
+ }
45990
+ function checkServeConfig(input) {
45991
+ const { engine, args, model } = input;
45992
+ const config = input.config ?? null;
45993
+ const checked = [];
45994
+ const skipped = [];
45995
+ const findings = [];
45996
+ const add = (f) => findings.push(f);
45997
+ const geo = geometryOf(model);
45998
+ const comps = model.components ?? [];
45999
+ const hasMla = comps.some((c) => c.type === "mla");
46000
+ const learned = comps.some((c) => c.type === "learnedPositionalEmbedding" || c.type === "positionalEncoding");
46001
+ const card = input.gpu ? resolveLayoutGpu(input.gpu) : null;
46002
+ const sm = card ? CARD_SM[card.id] ?? null : null;
46003
+ const lc = engine === "llamacpp";
46004
+ const tp = lc ? 1 : Math.max(1, args.tp ?? 1);
46005
+ const pp = lc ? 1 : Math.max(1, args.pp ?? 1);
46006
+ const dp = lc ? 1 : Math.max(1, args.dp ?? 1);
46007
+ const ep = !lc && args.expertParallel === true;
46008
+ const world = tp * pp * dp;
46009
+ const gpus = input.gpus ?? (lc ? 1 : world);
46010
+ const modelType = String(config?.model_type ?? "");
46011
+ const ident = `${modelType} ${input.modelId ?? ""} ${model.name ?? ""}`;
46012
+ const ckpt = checkpointQuant(config);
46013
+ if (lc) {
46014
+ skipped.push({ check: "parallel", reason: "llama.cpp splits whole layers (and their KV) across GPUs by default (--split-mode layer), so no head or width divisibility applies." });
46015
+ } else {
46016
+ checked.push("gpu-count");
46017
+ if (input.gpus != null && world > input.gpus) {
46018
+ add({
46019
+ rule: "world-over-gpus",
46020
+ area: "parallel",
46021
+ severity: "block",
46022
+ title: `TP ${tp} x PP ${pp} x DP ${dp} = ${world} GPUs, but ${input.gpus} are available`,
46023
+ detail: `The engine needs one GPU per rank; with ${input.gpus} it fails to place the workers (or waits for them).`,
46024
+ fix: `Make TP x PP x DP at most ${input.gpus}${input.gpus % (tp * pp) === 0 ? ` (e.g. DP ${input.gpus / (tp * pp)})` : ""}.`
46025
+ });
46026
+ } else if (input.gpus != null && world < input.gpus) {
46027
+ add({
46028
+ rule: "gpus-idle",
46029
+ area: "parallel",
46030
+ severity: "info",
46031
+ title: `${input.gpus - world} of ${input.gpus} GPUs are not used by TP x PP x DP = ${world}`,
46032
+ detail: "The engine only starts as many ranks as the product of the parallel sizes.",
46033
+ fix: input.gpus % (tp * pp) === 0 ? `Add DP ${input.gpus / (tp * pp)} to use them as replicas.` : "Change the parallel sizes to use every GPU, or launch on fewer."
46034
+ });
46035
+ }
46036
+ if (geo.numHeads != null) {
46037
+ checked.push("tp-heads");
46038
+ if (geo.numHeads % tp !== 0) {
46039
+ add({
46040
+ rule: "tp-heads",
46041
+ area: "parallel",
46042
+ severity: "block",
46043
+ title: `TP ${tp} does not divide ${geo.numHeads} attention heads`,
46044
+ detail: `${engine === "vllm" ? "vLLM" : "SGLang"} gives each TP rank whole heads and asserts the division at load ("Total number of attention heads (${geo.numHeads}) must be divisible by tensor parallel size (${tp})").`,
46045
+ fix: `Use a TP size dividing ${geo.numHeads}: ${divisors2(geo.numHeads).filter((d) => d <= 8).join(", ")}.`
46046
+ });
46047
+ }
46048
+ if (!hasMla && geo.numKVHeads != null) {
46049
+ checked.push("tp-kv-heads");
46050
+ if (geo.numKVHeads % tp !== 0) {
46051
+ if (tp % geo.numKVHeads === 0) {
46052
+ add({
46053
+ rule: "tp-kv-replicated",
46054
+ area: "parallel",
46055
+ severity: "warn",
46056
+ title: `TP ${tp} is past ${geo.numKVHeads} KV heads: each KV head is replicated ${tp / geo.numKVHeads}x`,
46057
+ detail: `It starts, but every GPU stores a full KV head, so the KV cache per GPU stops shrinking at TP ${geo.numKVHeads}: the extra ranks hold copies, not more sequences.`,
46058
+ fix: `TP ${geo.numKVHeads} with DP ${tp / geo.numKVHeads} serves more sequences on the same GPUs, if the weights fit at TP ${geo.numKVHeads}.`
46059
+ });
46060
+ } else {
46061
+ add({
46062
+ rule: "tp-kv-heads",
46063
+ area: "parallel",
46064
+ severity: "block",
46065
+ title: `TP ${tp} neither divides nor is a multiple of ${geo.numKVHeads} KV heads`,
46066
+ detail: "Grouped-query attention needs whole KV heads per rank or an exact replication factor; the engine asserts this at load.",
46067
+ fix: `Use a TP size dividing ${geo.numKVHeads} or a multiple of it.`
46068
+ });
46069
+ }
46070
+ }
46071
+ }
46072
+ } else skipped.push({ check: "tp-heads", reason: "no attention layer with a head count in the graph." });
46073
+ if (geo.ffn != null && tp > 1) {
46074
+ checked.push("tp-ffn");
46075
+ const moeNoEp = geo.numExperts != null && !ep;
46076
+ const what = geo.numExperts != null ? "expert FFN width" : "FFN width";
46077
+ const splitFfn = geo.numExperts == null || moeNoEp;
46078
+ if (splitFfn && geo.ffn % tp !== 0) {
46079
+ add({
46080
+ rule: "tp-ffn",
46081
+ area: "parallel",
46082
+ severity: "block",
46083
+ title: `TP ${tp} does not divide the ${what} ${geo.ffn}`,
46084
+ detail: "Column-parallel linears split the intermediate dimension evenly across ranks and assert the division.",
46085
+ fix: `Use a TP size dividing ${geo.ffn}${geo.numExperts != null ? ", or enable expert parallelism so experts stay whole" : ""}.`
46086
+ });
46087
+ } else if (splitFfn && ckpt.blockN != null && geo.ffn / tp % ckpt.blockN !== 0) {
46088
+ add({
46089
+ rule: "tp-quant-block",
46090
+ area: "parallel",
46091
+ severity: "block",
46092
+ title: `TP ${tp} leaves ${geo.ffn / tp} columns of the ${what} per rank, not a multiple of the checkpoint's ${ckpt.blockN}-wide quant block`,
46093
+ detail: `The checkpoint is block-quantized (weight_block_size [${ckpt.blockN}, ...]); each rank's slice must hold whole blocks, and vLLM refuses at load ("... is not divisible by weight quantization block_n = ${ckpt.blockN}").`,
46094
+ fix: `Use a TP size where ${geo.ffn} / TP is a multiple of ${ckpt.blockN} (${divisors2(geo.ffn).filter((d) => d <= 8 && geo.ffn / d % ckpt.blockN === 0 && (geo.numHeads == null || geo.numHeads % d === 0)).join(", ") || "none up to 8"})${geo.numExperts != null ? ", or enable expert parallelism so experts stay whole" : ""}.`,
46095
+ source: "Qwen deployment docs, vLLM FP8 troubleshooting: the same block_n = 128 error, fixed by lower TP or expert parallelism (qwen.readthedocs.io/en/latest/deployment/vllm.html)"
46096
+ });
46097
+ }
46098
+ }
46099
+ if (geo.numExperts != null) {
46100
+ checked.push("expert-parallel");
46101
+ if (ep) {
46102
+ const epSize = engine === "vllm" ? tp * dp : args.epSize ?? tp;
46103
+ if (geo.numExperts % epSize !== 0) {
46104
+ add({
46105
+ rule: "ep-uneven",
46106
+ area: "parallel",
46107
+ severity: "warn",
46108
+ title: `${geo.numExperts} experts over EP ${epSize} is not even`,
46109
+ detail: `${engine === "vllm" ? "vLLM sets EP = TP x DP and" : "The engine"} gives some ranks one more expert than others, so the busiest rank sets the pace and holds the most weights.`,
46110
+ fix: `Choose TP x DP dividing ${geo.numExperts}.`
46111
+ });
46112
+ }
46113
+ if (engine === "sglang" && args.epSize != null && tp % args.epSize !== 0) {
46114
+ add({
46115
+ rule: "ep-tp",
46116
+ area: "parallel",
46117
+ severity: "block",
46118
+ title: `SGLang EP ${args.epSize} does not divide TP ${tp}`,
46119
+ detail: "SGLang carves the expert-parallel group out of the tensor-parallel ranks.",
46120
+ fix: `Use an EP size dividing ${tp}.`
46121
+ });
46122
+ }
46123
+ } else if (tp >= 4) {
46124
+ add({
46125
+ rule: "moe-no-ep",
46126
+ area: "parallel",
46127
+ severity: "info",
46128
+ title: `MoE with ${geo.numExperts} experts at TP ${tp} without expert parallelism`,
46129
+ detail: `Every expert is split ${tp} ways, so each rank multiplies ${geo.ffn != null ? `${geo.ffn / tp}-wide` : "thin"} expert slices and all-reduces after every MoE layer. Expert parallelism keeps experts whole and sends tokens to them instead.`,
46130
+ fix: engine === "vllm" ? "Try --enable-expert-parallel (EP = TP x DP) and compare throughput." : "Try --ep-size equal to TP and compare throughput."
46131
+ });
46132
+ }
46133
+ } else if (ep) {
46134
+ add({
46135
+ rule: "ep-dense",
46136
+ area: "parallel",
46137
+ severity: "warn",
46138
+ title: "Expert parallelism on a model with no MoE layer",
46139
+ detail: "There are no experts to distribute; the flag does nothing here.",
46140
+ fix: "Drop the expert-parallel flag."
46141
+ });
46142
+ }
46143
+ }
46144
+ const graphMax = (() => {
46145
+ const lp = comps.find((c) => c.type === "learnedPositionalEmbedding" || c.type === "positionalEncoding");
46146
+ const e = comps.find((c) => c.type === "embedding");
46147
+ return posInt4(lp?.params?.maxLen) ?? posInt4(e?.params?.maxSeqLen);
46148
+ })();
46149
+ let ropeOverride = args.ropeScaling;
46150
+ if (lc && (args.ropeScale != null || args.ropeScalingType != null) && String(args.ropeScalingType ?? "linear") !== "none") {
46151
+ ropeOverride = { rope_type: args.ropeScalingType ?? "linear", factor: args.ropeScale ?? 1, ...args.yarnOrigCtx ? { original_max_position_embeddings: args.yarnOrigCtx } : {} };
46152
+ }
46153
+ const derived = derivedMaxLen(config, ropeOverride, args.maxPositionOverride, graphMax);
46154
+ let servedLen = null;
46155
+ let servedLenSource = "";
46156
+ let kvTokensAllocated = null;
46157
+ if (lc) {
46158
+ const total = args.ctxSize && args.ctxSize > 0 ? args.ctxSize : derived.native;
46159
+ const slots = args.nParallel ?? 1;
46160
+ const unified = args.kvUnified ?? args.nParallel == null;
46161
+ kvTokensAllocated = total;
46162
+ servedLen = total == null ? null : unified ? total : Math.floor(total / slots);
46163
+ servedLenSource = args.ctxSize && args.ctxSize > 0 ? unified ? `-c ${args.ctxSize} (one unified KV buffer, so one sequence may use all of it)` : `-c ${args.ctxSize} split over --parallel ${slots} slots = ${servedLen} per sequence` : `-c 0: the model's training context${unified ? "" : `, split over ${slots} slots`}`;
46164
+ } else if (args.maxModelLen != null) {
46165
+ servedLen = args.maxModelLen;
46166
+ servedLenSource = engine === "vllm" ? `--max-model-len ${args.maxModelLen}` : `--context-length ${args.maxModelLen}`;
46167
+ } else {
46168
+ servedLen = derived.len;
46169
+ servedLenSource = "not set: the engine derives it from the config";
46170
+ }
46171
+ if (servedLen != null && derived.native != null) {
46172
+ checked.push("context");
46173
+ const limitName = engine === "vllm" ? "VLLM_ALLOW_LONG_MAX_MODEL_LEN=1" : "SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1";
46174
+ if (learned && servedLen > derived.native) {
46175
+ add({
46176
+ rule: "context-over-learned",
46177
+ area: "context",
46178
+ severity: "block",
46179
+ title: `Serving ${servedLen} tokens on a ${derived.native}-row learned position table`,
46180
+ detail: `Positions past ${derived.native - 1} index outside the table: the first long request crashes (or, if the engine clamps, attends with wrong positions). Rope scaling does not apply to learned positions.`,
46181
+ fix: `Serve at most ${derived.native} tokens.`
46182
+ });
46183
+ } else if (derived.len != null && servedLen > derived.len) {
46184
+ const ropeSet = derived.rope != null;
46185
+ add({
46186
+ rule: "context-over-derived",
46187
+ area: "context",
46188
+ severity: lc ? "warn" : "block",
46189
+ title: `Served length ${servedLen} is past the model's ${ropeSet ? `rope-scaled ${derived.len}` : `${derived.len}-token`} context`,
46190
+ detail: lc ? `llama.cpp runs past n_ctx_train with a warning; rotary positions keep computing, and quality past the trained length is not something the config vouches for.` : `The engine refuses to start ("User-specified ${engine === "vllm" ? "max_model_len" : "context_length"} (${servedLen}) is greater than the derived ${engine === "vllm" ? "max_model_len" : "context_length"} (${derived.len})") unless ${limitName} is set, and with it set, positions past the trained length are extrapolated.`,
46191
+ fix: ropeSet ? `Raise the rope factor to at least ${Math.ceil(servedLen / (posInt4(derived.rope?.original_max_position_embeddings) ?? derived.native))}, or serve at most ${derived.len}.` : `Serve at most ${derived.len}, or add rope scaling where the model card supports it, with the card's own original length (e.g. ${engine === "vllm" ? `--hf-overrides '{"rope_scaling":{"rope_type":"yarn","factor":F,"original_max_position_embeddings":N}}'` : engine === "sglang" ? `--json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":F,"original_max_position_embeddings":N}}'` : "--rope-scaling yarn --rope-scale F --yarn-orig-ctx N"}, with N x F >= ${servedLen}; N is the native length the card states, which can be below max_position_embeddings).`
46192
+ });
46193
+ }
46194
+ if (ropeOverride && !config?.rope_scaling) {
46195
+ const type = String(ropeOverride.rope_type ?? ropeOverride.type ?? "");
46196
+ if (/yarn|linear|dynamic/.test(type)) {
46197
+ add({
46198
+ rule: "rope-static",
46199
+ area: "context",
46200
+ severity: servedLen <= derived.native ? "warn" : "info",
46201
+ title: servedLen <= derived.native ? `Rope scaling (${type}) is set but the served length ${servedLen} is within the native ${derived.native}` : `Rope scaling (${type}, factor ${ropeOverride.factor}) applies to every request, short ones included`,
46202
+ detail: "The scaling is static in these engines: the factor applies regardless of input length, which the Qwen model cards say can hurt quality on shorter texts.",
46203
+ fix: servedLen <= derived.native ? "Drop the rope scaling; it buys nothing at this length." : "Keep it only on the deployment that needs the long context.",
46204
+ source: 'Qwen3 model card, "Processing Long Texts" (static YaRN note)'
46205
+ });
46206
+ }
46207
+ }
46208
+ } else skipped.push({ check: "context", reason: derived.native == null ? "the config states no maximum length (max_position_embeddings)." : "no served length." });
46209
+ const cfgDtype = normDtype(String(config?.torch_dtype ?? config?.dtype ?? "")) ?? null;
46210
+ const flagDtype = normDtype(args.dtype);
46211
+ let dtype = flagDtype && flagDtype !== "auto" ? flagDtype : cfgDtype && cfgDtype !== "auto" ? cfgDtype : "bf16";
46212
+ if (flagDtype === "fp32" && cfgDtype && cfgDtype !== "fp32") {
46213
+ }
46214
+ const flagQuant = normalizeQuant(args.quantization);
46215
+ const quant = lc ? "gguf" : flagQuant ?? ckpt.method;
46216
+ const ggufType = lc ? ggufQuantOf(args.ggufFile) : null;
46217
+ if (!lc && flagQuant && ckpt.method && flagQuant !== ckpt.method) {
46218
+ const compatible = flagQuant === "marlin" && (ckpt.method === "gptq" || ckpt.method === "awq");
46219
+ if (!compatible) {
46220
+ add({
46221
+ rule: "quant-mismatch",
46222
+ area: "quant",
46223
+ severity: "block",
46224
+ title: `--quantization ${args.quantization} does not match the checkpoint's ${ckpt.raw}`,
46225
+ detail: `The weights are stored as ${ckpt.raw}; the engine refuses a different method ("Quantization method specified in the model config (${ckpt.raw}) does not match the quantization method specified in the \`quantization\` argument").`,
46226
+ fix: "Drop --quantization and let the engine read quantization_config, or point at an unquantized checkpoint."
46227
+ });
46228
+ }
46229
+ }
46230
+ if (sm == null) {
46231
+ skipped.push({ check: "quant-support", reason: card ? `${card.label} is not a CUDA card with a compute capability in the table.` : "no --gpu given." });
46232
+ } else if (lc) {
46233
+ skipped.push({ check: "quant-support", reason: "llama.cpp's CUDA backend runs every GGUF type on these cards; support is not a per-architecture table." });
46234
+ } else {
46235
+ checked.push("quant-support");
46236
+ if (sm < BF16_MIN_SM && (flagDtype === "bf16" || flagDtype !== "fp16" && flagDtype !== "fp32" && cfgDtype === "bf16")) {
46237
+ if (flagDtype === "bf16") {
46238
+ add({
46239
+ rule: "bf16-unsupported",
46240
+ area: "quant",
46241
+ severity: "block",
46242
+ title: `--dtype bfloat16 on ${card.label} (sm${sm})`,
46243
+ detail: "The card has no bf16 tensor cores and the engine refuses the explicit dtype.",
46244
+ fix: "Use --dtype float16 (and check the model does not overflow in fp16), or a card at sm80 or newer.",
46245
+ source: BF16_SOURCE
46246
+ });
46247
+ } else {
46248
+ add({
46249
+ rule: "bf16-auto-cast",
46250
+ area: "quant",
46251
+ severity: "warn",
46252
+ title: `The checkpoint is bf16 and ${card.label} (sm${sm}) has no bf16`,
46253
+ detail: "With --dtype auto the engine casts to fp16 (older versions refuse). fp16 has a narrower range than bf16, and some models trained in bf16 overflow in it.",
46254
+ fix: "Pass --dtype float16 knowingly and spot-check outputs, or use an sm80+ card.",
46255
+ source: BF16_SOURCE
46256
+ });
46257
+ dtype = "fp16";
46258
+ }
46259
+ }
46260
+ if (quant != null) {
46261
+ const row = QUANT_SUPPORT.find((r) => r.method === quant);
46262
+ if (!row) skipped.push({ check: "quant-support", reason: `no support row for quant method "${quant}".` });
46263
+ else if (sm < row.fallbackSm) {
46264
+ add({
46265
+ rule: "quant-unsupported",
46266
+ area: "quant",
46267
+ severity: "block",
46268
+ title: `${quant} weights on ${card.label} (sm${sm}): not supported`,
46269
+ detail: `${quant} needs sm${row.fallbackSm} or newer${row.nativeSm !== row.fallbackSm ? ` (sm${row.nativeSm} for the native kernels)` : ""}; the engine refuses at load.`,
46270
+ fix: `Use a ${quant === "mxfp4" ? "bf16 build of the model" : "different quantization"} on this card, or an sm${row.fallbackSm}+ card.`,
46271
+ source: row.source
46272
+ });
46273
+ } else if (sm < row.nativeSm) {
46274
+ add({
46275
+ rule: "quant-fallback",
46276
+ area: "quant",
46277
+ severity: "warn",
46278
+ title: `${quant} on ${card.label} (sm${sm}) is not native: it runs on a fallback kernel`,
46279
+ detail: `Native ${quant} kernels need sm${row.nativeSm}+. On this card it ${row.fallbackNote ?? "runs on a slower path"}.`,
46280
+ fix: `Expect the memory saving and not the speedup; for native ${quant} use an sm${row.nativeSm}+ card.`,
46281
+ source: row.source
46282
+ });
46283
+ }
46284
+ }
46285
+ }
46286
+ let memory = null;
46287
+ if (!card) skipped.push({ check: "memory", reason: "no --gpu given." });
46288
+ else if (servedLen == null) skipped.push({ check: "memory", reason: "no served length (set the max length, or give a config with max_position_embeddings)." });
46289
+ else {
46290
+ const peak = inferencePeakFor(model, { promptTokens: servedLen, genTokens: 0, batch: 1, precision: "bf16" });
46291
+ const split = paramSplit(model);
46292
+ const w = weightBytes(split, DTYPE_BYTES[dtype], quant, ckpt.bits, engine, ggufType);
46293
+ if (!peak || !w || !(split.total > 0)) {
46294
+ skipped.push({ check: "memory", reason: !w && lc ? `the GGUF quant type is not readable from "${args.ggufFile ?? "(no -m)"}"; name the file with its type (e.g. model-Q4_K_M.gguf).` : "the graph has no parameter count to size." });
46295
+ } else {
46296
+ checked.push("memory");
46297
+ let kvBytes = dtype === "fp32" ? 4 : 2;
46298
+ let kvName = dtype === "fp32" ? "fp32" : "16-bit";
46299
+ if (lc) {
46300
+ const k = GGUF_KV_BYTES[String(args.cacheTypeK ?? "f16").toLowerCase()] ?? 2;
46301
+ const v = GGUF_KV_BYTES[String(args.cacheTypeV ?? "f16").toLowerCase()] ?? 2;
46302
+ kvBytes = (k + v) / 2;
46303
+ kvName = `K ${args.cacheTypeK ?? "f16"} / V ${args.cacheTypeV ?? "f16"}`;
46304
+ } else if (args.kvCacheDtype && /fp8/i.test(args.kvCacheDtype)) {
46305
+ kvBytes = 1;
46306
+ kvName = args.kvCacheDtype;
46307
+ }
46308
+ let weightsPerGpu;
46309
+ let kvShare;
46310
+ let budgetGb;
46311
+ let fraction = null;
46312
+ if (lc) {
46313
+ const layers = posInt4(config?.num_hidden_layers) ?? Math.max(1, comps.filter((c) => /attention|mla/i.test(c.type)).length);
46314
+ const ngl = args.nGpuLayers;
46315
+ const onGpu = ngl === "all" || ngl === "auto" || ngl == null ? 1 : Math.min(1, ngl / (layers + 1));
46316
+ weightsPerGpu = w.bytes * onGpu / gpus;
46317
+ kvShare = onGpu / gpus;
46318
+ budgetGb = card.memoryGB;
46319
+ } else {
46320
+ const expertBytesShare = split.expert > 0 ? w.bytes * split.expert / split.total : 0;
46321
+ const denseBytes = w.bytes - expertBytesShare;
46322
+ const expertWays = ep && engine === "vllm" ? tp * dp * pp : tp * pp;
46323
+ weightsPerGpu = denseBytes / (tp * pp) + expertBytesShare / expertWays;
46324
+ kvShare = (hasMla ? 1 : geo.numKVHeads ? Math.max(1 / tp, 1 / geo.numKVHeads) : 1 / tp) / pp;
46325
+ fraction = engine === "vllm" ? args.gpuMemoryUtilization ?? 0.9 : args.memFractionStatic ?? 0.88;
46326
+ budgetGb = card.memoryGB * fraction;
46327
+ }
46328
+ const kvPerTokGpu = peak.kvBytesPerToken * kvBytes / 2 * kvShare;
46329
+ const statePerSeqGpu = peak.stateBytesPerSequence * kvShare;
46330
+ const weightsGb = weightsPerGpu / 1e9;
46331
+ const kvSeqGb = (kvPerTokGpu * servedLen + statePerSeqGpu) / 1e9;
46332
+ const lcTokens = kvTokensAllocated ?? servedLen;
46333
+ const capGb = lc ? kvPerTokGpu * lcTokens / 1e9 : budgetGb - weightsGb;
46334
+ const tokenCapacity = lc ? lcTokens : capGb > 0 && kvPerTokGpu > 0 ? Math.floor(capGb * 1e9 / kvPerTokGpu) : 0;
46335
+ const conc = lc ? args.kvUnified ?? args.nParallel == null ? Math.max(1, Math.floor(lcTokens / servedLen)) : args.nParallel ?? 1 : capGb > 0 && kvSeqGb > 0 ? capGb / kvSeqGb : 0;
46336
+ memory = {
46337
+ weightsBasis: w.basis,
46338
+ weightsGbTotal: w.bytes / 1e9,
46339
+ weightsGbPerGpu: weightsGb,
46340
+ budgetGbPerGpu: budgetGb,
46341
+ kvBytesPerTokenPerGpu: kvPerTokGpu,
46342
+ stateBytesPerSequencePerGpu: statePerSeqGpu,
46343
+ kvGbPerSequencePerGpu: kvSeqGb,
46344
+ kvCapacityGbPerGpu: Math.max(0, capGb),
46345
+ tokenCapacity,
46346
+ maxConcurrentFullLength: Math.floor(conc * 100) / 100,
46347
+ notCounted: [
46348
+ "the engine's activation reserve from its profiling run, CUDA graphs and communication buffers (they come out of the same budget, so capacity here is an upper bound)",
46349
+ "the card's real usable memory, which is below the nominal figure",
46350
+ ...lc ? ["host RAM for layers left on the CPU"] : []
46351
+ ]
46352
+ };
46353
+ const budgetWord = lc ? `${card.memoryGB} GB on the card` : `${card.memoryGB} GB x ${fraction} = ${gbs(budgetGb)}`;
46354
+ const shareWord = lc ? gpus > 1 ? ` (layers split over ${gpus} GPUs)` : "" : ` after TP ${tp}${pp > 1 ? ` x PP ${pp}` : ""}${ep && split.expert > 0 ? " with experts spread by EP" : ""}`;
46355
+ if (lc) {
46356
+ const need = weightsGb + kvPerTokGpu * (kvTokensAllocated ?? servedLen) / 1e9;
46357
+ const ngl = args.nGpuLayers;
46358
+ if (need > budgetGb) {
46359
+ const explicitAll = ngl === "all" || typeof ngl === "number" && ngl > 0;
46360
+ add({
46361
+ rule: "memory-over-card",
46362
+ area: "memory",
46363
+ severity: explicitAll ? "block" : "warn",
46364
+ title: `Weights ${gbs(weightsGb)} + KV for ${kvTokensAllocated ?? servedLen} tokens ${gbs(need - weightsGb)} = ${gbs(need)} per GPU, over the ${card.label}`,
46365
+ detail: explicitAll ? "llama.cpp allocates the whole -c context up front; with these layers forced onto the GPU the allocation fails at load." : "With -ngl auto llama.cpp keeps the layers that do not fit on the CPU, which runs, at CPU memory bandwidth for those layers.",
46366
+ fix: `Lower -c, quantize the cache (-ctk q8_0 -ctv q8_0 halves it), pick a smaller quant, or offload fewer layers.`
46367
+ });
46368
+ } else {
46369
+ checked.push("memory-fit");
46370
+ }
46371
+ } else if (weightsGb >= budgetGb) {
46372
+ add({
46373
+ rule: "weights-over-budget",
46374
+ area: "memory",
46375
+ severity: "block",
46376
+ title: `Weights alone are ${gbs(weightsGb)} per GPU${shareWord}, over the ${gbs(budgetGb)} budget`,
46377
+ detail: `Budget = ${budgetWord}. Weights: ${w.basis}. Nothing is left for the KV cache, so the engine fails at load.`,
46378
+ fix: `Raise TP (or PP), quantize the weights, or use a larger card.`
46379
+ });
46380
+ } else if (conc < 1) {
46381
+ add({
46382
+ rule: "kv-under-one-sequence",
46383
+ area: "memory",
46384
+ severity: engine === "vllm" ? "block" : "warn",
46385
+ title: `One ${servedLen}-token sequence needs ${gbs(kvSeqGb)} of KV per GPU; at most ${gbs(capGb)} is left`,
46386
+ detail: `Budget = ${budgetWord}; weights ${gbs(weightsGb)} per GPU${shareWord}. ${engine === "vllm" ? 'vLLM checks at startup that one request at the full length fits the KV cache and refuses otherwise ("larger than the maximum number of tokens that can be stored in KV cache").' : "The KV pool cannot hold one request at the full length, so the server starts and the longest requests it advertises cannot be scheduled."} Capacity here is an upper bound: the engine's reserve comes out of it too.`,
46387
+ fix: `Serve at most ~${Math.floor(tokenCapacity / 1024) * 1024} tokens, raise ${engine === "vllm" ? "--gpu-memory-utilization" : "--mem-fraction-static"}, use an fp8 KV cache (--kv-cache-dtype fp8), or raise TP.`
46388
+ });
46389
+ } else {
46390
+ checked.push("memory-fit");
46391
+ if (conc < 1.5) {
46392
+ add({
46393
+ rule: "kv-borderline",
46394
+ area: "memory",
46395
+ severity: "warn",
46396
+ title: `Only ~${conc.toFixed(1)} full-length sequences fit, before the engine's own reserve`,
46397
+ detail: `${gbs(capGb)} per GPU for KV against ${gbs(kvSeqGb)} per ${servedLen}-token sequence. The activation profile and CUDA graphs come out of the same budget, so this can fail the startup check that one full sequence fits.`,
46398
+ fix: `Leave more room: lower the max length, use an fp8 KV cache, or raise TP.`
46399
+ });
46400
+ }
46401
+ if (args.maxNumSeqs != null && args.maxNumSeqs > Math.floor(conc)) {
46402
+ add({
46403
+ rule: "seqs-over-capacity",
46404
+ area: "memory",
46405
+ severity: "warn",
46406
+ title: `${engine === "vllm" ? "--max-num-seqs" : "--max-running-requests"} ${args.maxNumSeqs}, but at most ${Math.floor(conc)} sequences fit at the full ${servedLen} tokens`,
46407
+ detail: `KV capacity is at most ${tokenCapacity.toLocaleString("en-US")} tokens per replica (each GPU holds its share of every token; ${gbs(capGb)} at ${Math.round(kvPerTokGpu).toLocaleString("en-US")} bytes per token, ${kvName}). Shorter requests pack more, but once long ones arrive the engine preempts or queues past ~${Math.floor(conc)}; the batch size the flag promises is not there.`,
46408
+ fix: `Set the flag to what fits (${Math.max(1, Math.floor(conc))}), shorten the max length, use an fp8 KV cache, or add GPUs as DP replicas.`
46409
+ });
46410
+ }
46411
+ if (!findings.some((f) => f.rule === "seqs-over-capacity")) add({
46412
+ rule: "kv-capacity",
46413
+ area: "memory",
46414
+ severity: "info",
46415
+ title: `At most ${Math.floor(conc)} concurrent ${servedLen}-token sequences per replica (${tokenCapacity.toLocaleString("en-US")} KV tokens)`,
46416
+ detail: `Per GPU: budget ${budgetWord}; weights ${gbs(weightsGb)}${shareWord} (${w.basis}); KV ${Math.round(kvPerTokGpu).toLocaleString("en-US")} bytes per token (${kvName}${!hasMla && geo.numKVHeads && tp > geo.numKVHeads ? `, KV heads replicated past TP ${geo.numKVHeads}` : ""}${hasMla ? ", MLA latent cache is not split by TP" : ""}). Upper bound: the engine's reserve is not counted.`,
46417
+ fix: ""
46418
+ });
46419
+ }
46420
+ }
46421
+ }
46422
+ const template = chatTemplateOf(input);
46423
+ const haveTokenizerSide = input.tokenizerConfig != null || input.chatTemplateFile != null;
46424
+ if (!haveTokenizerSide && !args.chatTemplate) {
46425
+ skipped.push({ check: "chat-template", reason: "no tokenizer_config.json or chat_template.jinja was given (they are fetched for a Hugging Face id)." });
46426
+ } else {
46427
+ checked.push("chat-template");
46428
+ if (args.chatTemplate) {
46429
+ add({
46430
+ rule: "template-overridden",
46431
+ area: "template",
46432
+ severity: "info",
46433
+ title: `The chat template is replaced by ${args.chatTemplate}`,
46434
+ detail: `${template ? `The model ships its own template (hash ${templateHash(template)}); ` : ""}the override wins for every chat request. Nothing here renders the two, so whether they produce the same prompt is not checked.`,
46435
+ fix: "Render one multi-turn conversation with tool calls through both and diff the prompts before serving."
46436
+ });
46437
+ } else if (!template) {
46438
+ add({
46439
+ rule: "template-missing",
46440
+ area: "template",
46441
+ severity: "warn",
46442
+ title: "The model ships no chat template",
46443
+ detail: "Chat completions have nothing to render with: transformers 4.44+ no longer supplies a default, so vLLM and SGLang refuse /v1/chat/completions, and llama.cpp falls back to a generic format. Fine for a base model served on /v1/completions only.",
46444
+ fix: `Pass ${lc ? "--chat-template-file" : "--chat-template"} with the template the model was trained on, or serve completions only.`
46445
+ });
46446
+ }
46447
+ const effTemplate = args.chatTemplate ? null : template;
46448
+ if (effTemplate) {
46449
+ const addBos = input.tokenizerConfig?.add_bos_token === true;
46450
+ if (addBos && /bos_token/.test(effTemplate)) {
46451
+ add({
46452
+ rule: "bos-duplication",
46453
+ area: "template",
46454
+ severity: "info",
46455
+ title: "The template inserts the BOS token and the tokenizer also adds one (add_bos_token: true)",
46456
+ detail: lc ? "llama.cpp prints a warning and keeps both when a rendered prompt already starts with BOS; two BOS tokens shift every position the model saw in training." : "The chat path tokenizes the rendered template without special tokens, so chat is safe; a client that renders the template itself and posts to /v1/completions gets two BOS tokens.",
46457
+ fix: "Render with the engine's chat endpoint, or tokenize client-rendered prompts with add_special_tokens=False."
46458
+ });
46459
+ }
46460
+ const thinking = /<think>|enable_thinking|reasoning_content/.test(effTemplate);
46461
+ if (thinking && !lc && !args.reasoningParser) {
46462
+ add({
46463
+ rule: "reasoning-parser-missing",
46464
+ area: "template",
46465
+ severity: "info",
46466
+ title: "The template has a thinking block and no --reasoning-parser is set",
46467
+ detail: "The reasoning text comes back inside message.content instead of reasoning_content, which breaks clients that hide or strip it.",
46468
+ fix: `Add --reasoning-parser ${/qwen3/i.test(ident) ? "qwen3" : /deepseek/i.test(ident) ? "deepseek_r1" : "<family>"}.`
46469
+ });
46470
+ }
46471
+ }
46472
+ }
46473
+ if (!lc && args.enableAutoToolChoice && !args.toolCallParser) {
46474
+ checked.push("tool-parser");
46475
+ add({
46476
+ rule: "tool-parser-missing",
46477
+ area: "template",
46478
+ severity: "block",
46479
+ title: "--enable-auto-tool-choice without --tool-call-parser",
46480
+ detail: "vLLM refuses to start: automatic tool choice needs a parser to turn the model's tool-call text into tool_calls.",
46481
+ fix: "Add --tool-call-parser for this family (e.g. hermes for Qwen, llama3_json for Llama 3, kimi_k2, openai for gpt-oss)."
46482
+ });
46483
+ }
46484
+ const effSampler = effectiveSampler(input);
46485
+ for (const k of KNOWN_SERVE_ISSUES) {
46486
+ if (!k.match.test(modelType) && !k.match.test(input.modelId ?? "") && !k.match.test(model.name ?? "")) continue;
46487
+ if (k.when && !k.when({ args, sampler: effSampler.values })) continue;
46488
+ checked.push(`known:${k.id}`);
46489
+ if (k.engines.includes(engine)) add({ rule: k.id, area: k.id === "qwen3-greedy" ? "sampler" : "template", severity: k.severity, title: k.title, detail: k.detail, fix: k.fix, source: k.source });
46490
+ else add({ rule: k.id, area: "template", severity: "info", title: `${k.title} (not ${engine === "vllm" ? "vLLM" : engine})`, detail: k.detail, fix: "No change needed on this engine; keep it in mind if the deployment moves.", source: k.source });
46491
+ }
46492
+ const gen = input.generationConfig ?? null;
46493
+ if (!gen) skipped.push({ check: "sampler", reason: "no generation_config.json (fetched for a Hugging Face id)." });
46494
+ else {
46495
+ checked.push("sampler");
46496
+ const rec = readSampler(gen);
46497
+ const diffs = [];
46498
+ for (const k of ["temperature", "top_p", "top_k", "repetition_penalty"]) {
46499
+ const want = rec[k];
46500
+ const got = effSampler.values[k];
46501
+ if (want == null || got == null) continue;
46502
+ const norm = (x) => k === "top_k" && x < 0 ? 0 : x;
46503
+ if (Math.abs(norm(want) - norm(got)) > 1e-9) diffs.push(`${k} ${got} (recommended ${want}, from ${effSampler.origin[k]})`);
46504
+ }
46505
+ if (diffs.length) {
46506
+ add({
46507
+ rule: "sampler-differs",
46508
+ area: "sampler",
46509
+ severity: "warn",
46510
+ title: `Sampling defaults differ from the model's generation_config.json: ${diffs.map((d) => d.split(" (")[0]).join(", ")}`,
46511
+ detail: `${diffs.join("; ")}. Applies to every request that does not send its own value. Model makers have traced host-to-host quality gaps to exactly this (Moonshot: "a significant portion" of discrepancies came from decoding-parameter misuse).`,
46512
+ fix: lc ? `Pass ${Object.entries(rec).map(([k, v]) => `--${k === "temperature" ? "temp" : k === "repetition_penalty" ? "repeat-penalty" : k.replace("_", "-")} ${v}`).join(" ")} (llama.cpp does not read generation_config.json).` : engine === "vllm" ? "Leave --generation-config at auto (the default reads generation_config.json), and do not override it in the gateway." : "Let the engine read the model's sampling defaults, and do not override them in the gateway.",
46513
+ source: "kimi.com/blog/kimi-vendor-verifier"
46514
+ });
46515
+ }
46516
+ const eos = gen.eos_token_id ?? config?.eos_token_id;
46517
+ const pad = gen.pad_token_id ?? config?.pad_token_id;
46518
+ const eosList = Array.isArray(eos) ? eos : eos != null ? [eos] : [];
46519
+ if (pad != null && eosList.some((e) => e === pad)) {
46520
+ add({
46521
+ rule: "pad-is-eos",
46522
+ area: "template",
46523
+ severity: "info",
46524
+ title: `pad_token_id ${pad} is also an EOS id`,
46525
+ detail: "Serving engines do not pad, so generation is unaffected; a fine-tune on this tokenizer that masks pad tokens out of the loss also masks every EOS, and the tuned model stops learning to stop.",
46526
+ fix: "For fine-tuning, set a distinct pad token."
46527
+ });
46528
+ }
46529
+ }
46530
+ let change = null;
46531
+ if (input.against) {
46532
+ checked.push("change");
46533
+ change = diffAgainst(input, memory, derived.len, template);
46534
+ for (const c of change.changed) {
46535
+ add({ rule: "changed", area: "change", severity: "info", title: `${c.key}: ${fmt(c.from)} -> ${fmt(c.to)}`, detail: c.effect, fix: "" });
46536
+ }
46537
+ for (const n2 of change.numbers) {
46538
+ add({ rule: "changed-number", area: "change", severity: "info", title: `${n2.what}: ${n2.from} -> ${n2.to}`, detail: "Same engine flags and card, computed for both models.", fix: "" });
46539
+ }
46540
+ }
46541
+ return {
46542
+ engine,
46543
+ resolved: {
46544
+ gpu: card?.id ?? null,
46545
+ gpuMemoryGb: card?.memoryGB ?? null,
46546
+ sm,
46547
+ gpus,
46548
+ tp,
46549
+ pp,
46550
+ dp,
46551
+ expertParallel: ep,
46552
+ dtype,
46553
+ quant: lc ? ggufType ?? "gguf" : quant,
46554
+ kvCacheDtype: lc ? `${args.cacheTypeK ?? "f16"}/${args.cacheTypeV ?? "f16"}` : args.kvCacheDtype ?? "auto",
46555
+ servedLen,
46556
+ servedLenSource,
46557
+ derivedMaxLen: derived.len,
46558
+ memFraction: lc ? null : engine === "vllm" ? args.gpuMemoryUtilization ?? 0.9 : args.memFractionStatic ?? 0.88,
46559
+ maxNumSeqs: args.maxNumSeqs ?? null
46560
+ },
46561
+ checked,
46562
+ skipped,
46563
+ findings,
46564
+ memory,
46565
+ change,
46566
+ basis: SERVE_BASIS
46567
+ };
46568
+ }
46569
+ function effectiveSampler(input) {
46570
+ const { engine, args } = input;
46571
+ const def = ENGINE_SAMPLER_DEFAULTS[engine];
46572
+ const values = { temperature: def.temperature, top_p: def.top_p, top_k: def.top_k, repetition_penalty: def.repetition_penalty };
46573
+ const origin = { temperature: "engine default", top_p: "engine default", top_k: "engine default", repetition_penalty: "engine default" };
46574
+ const readsModel = engine === "vllm" ? !/^vllm$/i.test(args.generationConfigMode ?? "auto") : engine === "sglang" ? !/^openai$/i.test(args.generationConfigMode ?? "model") : false;
46575
+ if (readsModel && input.generationConfig) {
46576
+ const m = readSampler(input.generationConfig);
46577
+ for (const k of Object.keys(m)) {
46578
+ values[k] = m[k];
46579
+ origin[k] = "generation_config.json";
46580
+ }
46581
+ }
46582
+ if (engine !== "vllm" && engine !== "sglang" && !input.generationConfig) {
46583
+ }
46584
+ if (!readsModel && engine !== "llamacpp") {
46585
+ for (const k of Object.keys(origin)) origin[k] = engine === "vllm" ? "vLLM default (--generation-config vllm)" : "SGLang default (--sampling-defaults openai)";
46586
+ }
46587
+ if (engine === "llamacpp") for (const k of Object.keys(origin)) origin[k] = "llama.cpp default";
46588
+ for (const [src, s] of [[engine === "llamacpp" ? "llama.cpp flag" : "--override-generation-config", args.samplerFlags], ["request / gateway override", input.sampler]]) {
46589
+ if (!s) continue;
46590
+ for (const k of Object.keys(s)) {
46591
+ values[k] = s[k];
46592
+ origin[k] = src;
46593
+ }
46594
+ }
46595
+ return { values, origin };
46596
+ }
46597
+ var fmt = (v) => v === void 0 ? "(absent)" : typeof v === "object" ? JSON.stringify(v) : String(v);
46598
+ var DIFF_KEYS = [
46599
+ ["model_type", "A different architecture family: the engine loads a different model class, and every family-specific flag (tool-call parser, reasoning parser, chat template) must be re-chosen."],
46600
+ ["num_hidden_layers", "Layer count changes weights and KV per token; PP stage splits must be redone."],
46601
+ ["hidden_size", "Width changes weights, the TP divisibility of every linear, and activation memory."],
46602
+ ["num_attention_heads", "Head count changes which TP sizes are legal."],
46603
+ ["num_key_value_heads", "KV heads change KV bytes per token and where TP starts replicating KV."],
46604
+ ["head_dim", "Head dimension changes KV bytes per token and the attention kernels that apply."],
46605
+ ["intermediate_size", "FFN width changes weights and which TP sizes divide it."],
46606
+ ["moe_intermediate_size", "Expert width changes which TP sizes divide it (and block-quant alignment)."],
46607
+ ["num_experts", "Expert count changes legal EP sizes and expert weight memory."],
46608
+ ["num_local_experts", "Expert count changes legal EP sizes and expert weight memory."],
46609
+ ["vocab_size", "Vocabulary changes the embedding and LM head; the tokenizer changes with it, so token budgets and stop ids measured on the old model no longer apply."],
46610
+ ["max_position_embeddings", "The longest servable length changes; --max-model-len / --context-length may now be past it or leave length unused."],
46611
+ ["rope_scaling", "Rope scaling changes the derived maximum length and short-context quality."],
46612
+ ["rope_theta", "Rope base changes how positions are encoded; any rope override written for the old model is wrong for this one."],
46613
+ ["sliding_window", "Sliding window changes KV per token at long lengths and which attention backends apply."],
46614
+ ["torch_dtype", "Stored dtype changes weight memory and which cards run it natively."],
46615
+ ["quantization_config", "Quantization changes weight memory, which cards run it, and --quantization must match it."],
46616
+ ["tie_word_embeddings", "Tied embeddings change weight memory by one vocab x hidden matrix."],
46617
+ ["bos_token_id", "BOS id changes: prompt templates and BOS handling must follow."],
46618
+ ["eos_token_id", "Stop ids change: a gateway or client that hard-codes stop token ids stops at the wrong place or never stops."],
46619
+ ["pad_token_id", "Pad id changes (matters for batched fine-tuning, not for serving engines)."]
46620
+ ];
46621
+ function diffAgainst(input, mem, derivedLen, template) {
46622
+ const old = input.against;
46623
+ const a = old.config ?? {};
46624
+ const b = input.config ?? {};
46625
+ const changed = [];
46626
+ const same = (x, y) => JSON.stringify(x ?? null) === JSON.stringify(y ?? null);
46627
+ for (const [k, effect] of DIFF_KEYS) {
46628
+ const ka = k === "torch_dtype" ? a.torch_dtype ?? a.dtype : a[k];
46629
+ const kb = k === "torch_dtype" ? b.torch_dtype ?? b.dtype : b[k];
46630
+ if (ka === void 0 && kb === void 0) continue;
46631
+ if (!same(ka, kb)) changed.push({ key: k, from: ka, to: kb, effect });
46632
+ }
46633
+ const tOld = chatTemplateOf(old);
46634
+ if ((tOld ?? "") !== (template ?? "")) {
46635
+ changed.push({
46636
+ key: "chat_template",
46637
+ from: tOld ? `hash ${templateHash(tOld)}` : void 0,
46638
+ to: template ? `hash ${templateHash(template)}` : void 0,
46639
+ effect: input.args.chatTemplate ? "The model's own template changed, but --chat-template overrides both: the override was written for one of them at most." : "Every chat request renders differently: re-render a reference conversation (with tool calls) and re-run the evals that depend on format."
46640
+ });
46641
+ }
46642
+ const ga = readSampler(old.generationConfig ?? {});
46643
+ const gb3 = readSampler(input.generationConfig ?? {});
46644
+ for (const k of ["temperature", "top_p", "top_k", "repetition_penalty"]) {
46645
+ if (ga[k] != null || gb3[k] != null) {
46646
+ if (ga[k] !== gb3[k]) changed.push({ key: `generation_config.${k}`, from: ga[k], to: gb3[k], effect: "The recommended sampling changes; a gateway that pins the old value now overrides the new model's recommendation." });
46647
+ }
46648
+ }
46649
+ const numbers = [];
46650
+ const oldReport = checkServeConfig({
46651
+ engine: input.engine,
46652
+ args: input.args,
46653
+ gpu: input.gpu,
46654
+ gpus: input.gpus,
46655
+ sampler: input.sampler,
46656
+ model: old.model,
46657
+ config: old.config ?? null,
46658
+ tokenizerConfig: old.tokenizerConfig ?? null,
46659
+ chatTemplateFile: old.chatTemplateFile ?? null,
46660
+ generationConfig: old.generationConfig ?? null,
46661
+ modelId: old.modelId
46662
+ });
46663
+ const om = oldReport.memory;
46664
+ if (om && mem) {
46665
+ numbers.push({ what: "weights per GPU", from: gbs(om.weightsGbPerGpu), to: gbs(mem.weightsGbPerGpu) });
46666
+ numbers.push({ what: "KV bytes per token per GPU", from: Math.round(om.kvBytesPerTokenPerGpu).toLocaleString("en-US"), to: Math.round(mem.kvBytesPerTokenPerGpu).toLocaleString("en-US") });
46667
+ numbers.push({ what: "concurrent full-length sequences (upper bound)", from: String(Math.floor(om.maxConcurrentFullLength)), to: String(Math.floor(mem.maxConcurrentFullLength)) });
46668
+ }
46669
+ if (oldReport.resolved.derivedMaxLen !== derivedLen) {
46670
+ numbers.push({ what: "derived maximum length", from: String(oldReport.resolved.derivedMaxLen ?? "n/a"), to: String(derivedLen ?? "n/a") });
46671
+ }
46672
+ return { against: old.modelId ?? old.model.name ?? "previous model", changed, numbers };
46673
+ }
46674
+ var ENGINE_NAME = { vllm: "vLLM", sglang: "SGLang", llamacpp: "llama.cpp" };
46675
+ function renderServeText(r, name = "model") {
46676
+ const L = [];
46677
+ const R = r.resolved;
46678
+ L.push("");
46679
+ L.push(` ${name} on ${ENGINE_NAME[r.engine]}`);
46680
+ const par = r.engine === "llamacpp" ? "" : `TP ${R.tp} x PP ${R.pp} x DP ${R.dp}${R.expertParallel ? " + EP" : ""}, `;
46681
+ L.push(` ${par}${R.gpus} x ${R.gpu ?? "(no card given)"}${R.sm ? ` (sm${R.sm})` : ""}${r.engine === "llamacpp" ? "" : `, dtype ${R.dtype}`}, weights ${R.quant ?? "unquantized"}, KV cache ${R.kvCacheDtype}`);
46682
+ L.push(` served length ${R.servedLen ?? "n/a"} (${R.servedLenSource}); the model's derived maximum ${R.derivedMaxLen ?? "n/a"}`);
46683
+ if (r.memory) {
46684
+ const m = r.memory;
46685
+ L.push("");
46686
+ if (r.engine === "llamacpp") {
46687
+ L.push(` memory per GPU card ${m.budgetGbPerGpu.toFixed(1)} GB, weights ${m.weightsGbPerGpu.toFixed(2)} GB, KV for ${m.tokenCapacity.toLocaleString("en-US")} tokens ${m.kvCapacityGbPerGpu.toFixed(2)} GB (allocated up front), total ${(m.weightsGbPerGpu + m.kvCapacityGbPerGpu).toFixed(2)} GB`);
46688
+ L.push(` ${Math.round(m.kvBytesPerTokenPerGpu).toLocaleString("en-US")} KV bytes per token; one full-length sequence ${m.kvGbPerSequencePerGpu.toFixed(2)} GB`);
46689
+ } else {
46690
+ L.push(` memory per GPU budget ${m.budgetGbPerGpu.toFixed(1)} GB, weights ${m.weightsGbPerGpu.toFixed(2)} GB, KV room ${m.kvCapacityGbPerGpu.toFixed(2)} GB`);
46691
+ L.push(` ${Math.round(m.kvBytesPerTokenPerGpu).toLocaleString("en-US")} KV bytes per token; one full-length sequence ${m.kvGbPerSequencePerGpu.toFixed(2)} GB`);
46692
+ L.push(` at most ${Math.floor(m.maxConcurrentFullLength)} concurrent full-length sequences (${m.tokenCapacity.toLocaleString("en-US")} tokens)`);
46693
+ }
46694
+ L.push(` weights: ${m.weightsBasis}`);
46695
+ }
46696
+ const order = { block: 0, warn: 1, info: 2 };
46697
+ const fs = [...r.findings].sort((a, b) => order[a.severity] - order[b.severity]);
46698
+ L.push("");
46699
+ if (!fs.length) L.push(" no findings in the checks that ran");
46700
+ for (const f of fs) {
46701
+ const tag = f.severity === "block" ? "block" : f.severity === "warn" ? "warn " : "info ";
46702
+ L.push(` ${tag} ${f.title}`);
46703
+ if (f.detail) L.push(` ${f.detail}`);
46704
+ if (f.fix) L.push(` fix: ${f.fix}`);
46705
+ if (f.source) L.push(` source: ${f.source}`);
46706
+ }
46707
+ L.push("");
46708
+ L.push(` checked: ${r.checked.join(", ") || "nothing"}`);
46709
+ for (const s of r.skipped) L.push(` not checked: ${s.check}: ${s.reason}`);
46710
+ L.push("");
46711
+ L.push(` ${r.basis}`);
46712
+ L.push("");
46713
+ return L.join("\n");
46714
+ }
46715
+
44418
46716
  // src/utils/oomDiagnosis.ts
44419
46717
  var UNIT = { b: 1e-9, kib: 1024 / 1e9, kb: 1e-6, mib: 1024 ** 2 / 1e9, mb: 1e-3, gib: 1024 ** 3 / 1e9, gb: 1, tib: 1024 ** 4 / 1e9 };
44420
- var num3 = (v, unit) => Number(v.replace(/,/g, "")) * (UNIT[unit.toLowerCase()] ?? NaN);
46718
+ var num4 = (v, unit) => Number(v.replace(/,/g, "")) * (UNIT[unit.toLowerCase()] ?? NaN);
44421
46719
  var SIZE = String.raw`([\d.,]+)\s*(B|KiB|KB|MiB|MB|GiB|GB|TiB)`;
44422
46720
  function grab(text, re) {
44423
46721
  const m = re.exec(text);
44424
46722
  if (!m) return null;
44425
- const v = num3(m[1], m[2]);
46723
+ const v = num4(m[1], m[2]);
44426
46724
  return Number.isFinite(v) ? v : null;
44427
46725
  }
44428
46726
  function parseOomMessage(text) {
@@ -44435,7 +46733,7 @@ function parseOomMessage(text) {
44435
46733
  const reservedUnallocatedGb = grab(t, new RegExp(String.raw`${SIZE} is reserved by PyTorch but unallocated`, "i"));
44436
46734
  let other = 0;
44437
46735
  for (const m of t.matchAll(new RegExp(String.raw`Process \d+ has ${SIZE} memory in use`, "gi"))) {
44438
- const v = num3(m[1], m[2]);
46736
+ const v = num4(m[1], m[2]);
44439
46737
  if (Number.isFinite(v)) other += v;
44440
46738
  }
44441
46739
  const processInUseGb = grab(t, new RegExp(String.raw`this process has ${SIZE} memory in use`, "i"));
@@ -44849,6 +47147,66 @@ async function inspectHFModel(modelId, fetchImpl = fetch) {
44849
47147
  if ("skipped" in facts) return { ok: false, hub, reason: facts.skipped };
44850
47148
  return { ok: true, hub, facts };
44851
47149
  }
47150
+ async function layoutHFModel(ref, layout) {
47151
+ let model;
47152
+ if (isGraphPath(ref)) {
47153
+ const r = await defaultLoader(ref);
47154
+ if ("error" in r) return { error: r.error };
47155
+ model = r.model;
47156
+ } else {
47157
+ const config = await fetchHFModelConfig(ref);
47158
+ if (!config) return { error: `Hugging Face has no readable config.json for "${ref}" (check the id, or set HF_TOKEN for a gated repo)` };
47159
+ model = graphOfFacts({ key: keyFor(ref), snap: { modelId: ref, name: ref, config } });
47160
+ }
47161
+ return { name: model.name || ref, report: checkParallelLayout(model, layout) };
47162
+ }
47163
+ async function fetchServeSide(ref, fetchImpl = fetch) {
47164
+ if (isGraphPath(ref)) {
47165
+ const r = await defaultLoader(ref);
47166
+ if ("error" in r) return { error: r.error };
47167
+ return { model: r.model, config: null, modelId: ref };
47168
+ }
47169
+ const headers = {};
47170
+ const token = typeof process !== "undefined" ? process.env?.HF_TOKEN?.trim() : void 0;
47171
+ if (token) headers.Authorization = `Bearer ${token}`;
47172
+ const get = async (file, json) => {
47173
+ try {
47174
+ const res = await fetchImpl(`https://huggingface.co/${ref}/resolve/main/${file}`, { headers });
47175
+ if (!res.ok) return null;
47176
+ return json ? await res.json() : await res.text();
47177
+ } catch {
47178
+ return null;
47179
+ }
47180
+ };
47181
+ const [config, tok, tmpl, gen] = await Promise.all([
47182
+ get("config.json", true),
47183
+ get("tokenizer_config.json", true),
47184
+ get("chat_template.jinja", false),
47185
+ get("generation_config.json", true)
47186
+ ]);
47187
+ if (!config || typeof config !== "object") return { error: `Hugging Face has no readable config.json for "${ref}" (check the id, or set HF_TOKEN for a gated repo)` };
47188
+ const cfg = config;
47189
+ const model = graphOfFacts({ key: keyFor(ref), snap: { modelId: ref, name: ref, config: cfg } });
47190
+ return {
47191
+ model,
47192
+ config: cfg,
47193
+ modelId: ref,
47194
+ tokenizerConfig: tok && typeof tok === "object" ? tok : null,
47195
+ chatTemplateFile: typeof tmpl === "string" && tmpl.trim() ? tmpl : null,
47196
+ generationConfig: gen && typeof gen === "object" ? gen : null
47197
+ };
47198
+ }
47199
+ async function serveCheckHFModel(ref, opts, fetchImpl = fetch) {
47200
+ const side = await fetchServeSide(ref, fetchImpl);
47201
+ if ("error" in side) return side;
47202
+ let against;
47203
+ if (opts.against) {
47204
+ const a = await fetchServeSide(opts.against, fetchImpl);
47205
+ if ("error" in a) return { error: `--against ${opts.against}: ${a.error}` };
47206
+ against = a;
47207
+ }
47208
+ return { name: ref, report: checkServeConfig({ ...side, engine: opts.engine, args: opts.args, gpu: opts.gpu, gpus: opts.gpus, sampler: opts.sampler, against }) };
47209
+ }
44852
47210
  export {
44853
47211
  AGREE_TOLERANCE,
44854
47212
  CHANGE_HEADROOM,
@@ -44857,29 +47215,47 @@ export {
44857
47215
  DEFAULT_INFERENCE_BATCH,
44858
47216
  DEFAULT_INFERENCE_PRECISION,
44859
47217
  DEFAULT_SEQ_LEN,
47218
+ GGUF_BPW,
44860
47219
  INFERENCE_PRECISIONS,
47220
+ LAYOUT_BASIS,
44861
47221
  PREFLIGHT_GPUS,
44862
47222
  PRICE_SOURCE,
47223
+ QUANT_SUPPORT,
47224
+ SERVE_BASIS,
47225
+ SERVE_ENGINES,
44863
47226
  applyPrices,
44864
47227
  attentionPhrase,
47228
+ checkServeConfig,
44865
47229
  dataFitHFModel,
47230
+ detectEngine,
47231
+ fetchServeSide,
44866
47232
  graphOfFacts,
44867
47233
  headline,
44868
47234
  inferHFModel,
44869
47235
  inspectHFModel,
44870
47236
  keyFor,
47237
+ layoutHFModel,
44871
47238
  oomReport,
44872
47239
  parseHumanSize,
47240
+ parseServeCommand,
44873
47241
  priceHFModel,
44874
47242
  readAttention,
47243
+ readHistogram,
44875
47244
  readInferencePrecision,
47245
+ readLayout,
47246
+ readSampler,
44876
47247
  readSeqLen,
47248
+ renderLayoutText,
44877
47249
  renderLoraText,
44878
47250
  renderMarkdown,
44879
47251
  renderOomText,
47252
+ renderServeText,
47253
+ resolveLayoutGpu,
44880
47254
  rightsize,
47255
+ serveCheckHFModel,
44881
47256
  specFromFlags,
44882
- storedTwiceSentence
47257
+ storedTwiceSentence,
47258
+ tokenizeCommand
44883
47259
  };
44884
47260
  /*! Bundled license information:
44885
47261