aiinfra-tools 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +14 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +33 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +121 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +48 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +1 -1
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +21 -9
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +1 -0
  75. package/fleetscope/dist/index.html +295 -26
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +10 -11
  84. package/fleetscope/src/index.src.html +9 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +205 -22
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  139. package/inference-sizer/package.json +4 -3
  140. package/inference-sizer/src/accelerators.js +172 -0
  141. package/inference-sizer/src/catalog.js +7 -20
  142. package/inference-sizer/src/fit-ui.js +1 -1
  143. package/inference-sizer/src/index.src.html +3 -0
  144. package/inference-sizer/src/model.js +22 -1
  145. package/inference-sizer/tools/validate-agentx.mjs +110 -0
  146. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  147. package/mcp/README.md +6 -1
  148. package/mcp/server.mjs +34 -0
  149. package/package.json +9 -4
  150. package/schemas/README.md +3 -0
  151. package/schemas/aiinfra.report.schema.json +474 -0
  152. package/schemas/commands.mjs +14 -0
  153. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  154. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  155. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  156. package/schemas/harness-ledger.economics.schema.json +567 -0
  157. package/schemas/sizer.list.schema.json +15 -2
@@ -0,0 +1,291 @@
1
+ // Shadow upgrades: measure an infra change (GPUs, engine or its config, network, topology, serving layout) against the
2
+ // baseline before it ships, and keep measuring the baseline so drift is caught. See docs/SHADOW.md.
3
+ //
4
+ // plan predict what the change should do (the Inference Sizer at the workload's load) and how many requests a test
5
+ // needs to see an effect of a given size
6
+ // compare baseline vs candidate on request records at matched load: per metric an effect with a confidence interval,
7
+ // a verdict against gates, the naive comparison beside it, prediction vs measurement, cost
8
+ // baseline / watch keep a sample of a service's requests as its baseline; compare later windows with it
9
+ //
10
+ // Request records are the store's `request` kind: { t, isl, osl, cached?, ttft?, e2e?, tpot?, error?, variant?, pair? }.
11
+ // They come from engine traces (fleetops data import otlp-traces FILE --derive), from shadow replay (shadow-replay.mjs), or files.
12
+ import { createRequire } from 'node:module';
13
+ import { median, pctl, rng } from './stats.mjs';
14
+
15
+ const require = createRequire(import.meta.url);
16
+ const C = require('../../inference-sizer/src/catalog.js'), M = require('../../inference-sizer/src/model.js');
17
+
18
+ // An effect inside ±gate is "the same"; a confidence interval wholly past it is "worse" or "better". Latency effects
19
+ // are ratios (candidate ÷ baseline − 1); errors are a difference in rate; answers are a match rate.
20
+ export const GATES = { ttft: 0.05, tpot: 0.05, e2e: 0.05, errorRate: 0.005, tokPerGpuS: 0.05, costPerMTok: 0.05, answers: { match: 0.98, logprob: 0.05 }, prediction: 0.15 };
21
+ const METRICS = ['ttft', 'tpot', 'e2e'];
22
+
23
+ // ---------- small statistics ----------
24
+ const normCdf = z => { const t = 1 / (1 + 0.2316419 * Math.abs(z)), d = 0.3989423 * Math.exp(-z * z / 2), p = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274)))); return z > 0 ? 1 - p : p; };
25
+
26
+ // ---------- load context ----------
27
+ export function withMetrics(r) {
28
+ const o = Object.assign({}, r);
29
+ if (o.tpot == null && Number.isFinite(o.e2e) && Number.isFinite(o.ttft) && o.osl > 1) o.tpot = (o.e2e - o.ttft) / (o.osl - 1);
30
+ return o;
31
+ }
32
+ // calls in flight at each request's start, within its own arm (itself included)
33
+ export function annotateLoad(rs) {
34
+ const out = rs.map(withMetrics).sort((a, b) => a.t - b.t), ends = [];
35
+ for (const r of out) {
36
+ while (ends.length && ends[0] <= r.t) ends.shift();
37
+ r.conc = ends.length + 1;
38
+ const e = r.t + (Number.isFinite(r.e2e) ? r.e2e : 0); let i = ends.length; while (i > 0 && ends[i - 1] > e) i--; ends.splice(i, 0, e);
39
+ }
40
+ return out;
41
+ }
42
+ // the load a request met: calls in flight (half powers of two: 1, 2, 3, 4, 6, 8, 11, 16…), prompt length (powers of two), cache hit (none/part/most)
43
+ export function stratum(r, m) {
44
+ const c = Math.floor(2 * Math.log2(Math.max(1, r.conc || 1))), l = Math.floor(Math.log2(Math.max(1, r.isl || 1)));
45
+ const h = r.cached == null ? 'n' : r.cached / Math.max(1, r.isl) >= 0.9 ? 'h' : r.cached / Math.max(1, r.isl) >= 0.5 ? 'p' : 'z';
46
+ // end-to-end time scales with output length, so its strata also split by output length (powers of two)
47
+ return m === 'e2e' ? `${c}|${l}|${h}|${Math.floor(Math.log2(Math.max(1, r.osl || 1)))}` : `${c}|${l}|${h}`;
48
+ }
49
+
50
+ // ---------- matched-load effect of one metric ----------
51
+ // Stratified: in each load stratum both arms reach, log(median candidate) − log(median baseline), weighted by how much
52
+ // traffic the stratum carries in both arms. Paired (replay sends each request to both): the median per-request log ratio.
53
+ // Confidence interval by bootstrap (resampling requests within strata, or pairs).
54
+ function strataOf(rs, m) { const S = new Map(); for (const r of rs) { const v = r[m]; if (!(v > 0)) continue; const k = stratum(r, m); if (!S.has(k)) S.set(k, []); S.get(k).push(Math.log(v)); } return S; }
55
+ function stratEffect(Sb, Sc, minN) {
56
+ let w = 0, sum = 0;
57
+ for (const [k, b] of Sb) { const c = Sc.get(k); if (!c || b.length < minN || c.length < minN) continue; const wt = b.length + c.length; sum += wt * (median(c) - median(b)); w += wt; }
58
+ return w ? sum / w : NaN;
59
+ }
60
+ const resample = (a, u) => { const o = new Array(a.length); for (let i = 0; i < a.length; i++) o[i] = a[Math.floor(u() * a.length)]; return o; };
61
+ export function effect(base, cand, m, { minN = 5, boot = 400, seed = 7, paired = false } = {}) {
62
+ const u = rng(seed + m.length);
63
+ if (paired) {
64
+ const byPair = new Map(); for (const r of base) if (r.pair != null && r[m] > 0) byPair.set(r.pair, r[m]);
65
+ const d = []; for (const r of cand) { const b = byPair.get(r.pair); if (b > 0 && r[m] > 0) d.push(Math.log(r[m] / b)); }
66
+ if (d.length < minN) return null;
67
+ const est = median(d), bs = []; for (let i = 0; i < boot; i++) bs.push(median(resample(d, u)));
68
+ return { n: d.length, est, lo: pctl(bs, 0.025), hi: pctl(bs, 0.975), mode: 'paired', coverage: 1 };
69
+ }
70
+ const Sb = strataOf(base, m), Sc = strataOf(cand, m), est = stratEffect(Sb, Sc, minN);
71
+ if (!Number.isFinite(est)) return null;
72
+ let matched = 0, all = 0; for (const [k, b] of Sb) { const c = Sc.get(k) || []; all += b.length; if (b.length >= minN && c.length >= minN) matched += b.length; }
73
+ const bs = [];
74
+ for (let i = 0; i < boot; i++) {
75
+ const rb = new Map([...Sb].map(([k, v]) => [k, resample(v, u)])), rc = new Map([...Sc].map(([k, v]) => [k, resample(v, u)]));
76
+ const e = stratEffect(rb, rc, minN); if (Number.isFinite(e)) bs.push(e);
77
+ }
78
+ const nb = [...Sb.values()].reduce((a, v) => a + v.length, 0), nc = [...Sc.values()].reduce((a, v) => a + v.length, 0);
79
+ return { n: Math.min(nb, nc), est, lo: pctl(bs, 0.025), hi: pctl(bs, 0.975), mode: 'matched load', coverage: all ? matched / all : 0 };
80
+ }
81
+ // the comparison most dashboards make: all requests, medians, no load matching
82
+ export function naive(base, cand, m) { const b = base.map(r => r[m]).filter(v => v > 0), c = cand.map(r => r[m]).filter(v => v > 0); return b.length && c.length ? Math.log(median(c) / median(b)) : NaN; }
83
+
84
+ const ratio = x => Math.expm1(x);
85
+ // worse / better / same / inconclusive, and for inconclusive about how many more requests per arm would settle it
86
+ export function judge(e, gate, n) {
87
+ if (!e) return { verdict: 'no data' };
88
+ const lo = ratio(e.lo), hi = ratio(e.hi), est = ratio(e.est);
89
+ let verdict = lo > gate ? 'worse' : hi < -gate ? 'better' : lo > -gate && hi < gate ? 'same' : 'inconclusive', more = null;
90
+ if (verdict === 'inconclusive') { const half = (hi - lo) / 2, target = Math.max(Math.abs(gate - Math.abs(est)), gate / 20); more = Math.max(0, Math.ceil(n * ((half / target) ** 2 - 1))); }
91
+ return { verdict, effect: est, lo, hi, more };
92
+ }
93
+
94
+ // ---------- compare ----------
95
+ // arms: { baseline: [requests], candidate: [requests] } with optional { gpus, rate ($/GPU-h) } per arm, predicted ratios
96
+ // from plan(), answers from shadow-replay's equivalence check, infra signals from infraSignals().
97
+ export function compare(base0, cand0, opt = {}) {
98
+ const G = Object.assign({}, GATES, opt.gates || {});
99
+ const base = annotateLoad(base0), cand = annotateLoad(cand0);
100
+ const pairIds = new Set(base.filter(r => r.pair != null).map(r => r.pair)), shared = cand.filter(r => pairIds.has(r.pair)).length;
101
+ const paired = opt.paired ?? (shared >= Math.min(base.length, cand.length) * 0.5 && shared >= 5);
102
+ const metrics = {};
103
+ for (const m of METRICS) {
104
+ const e = effect(base, cand, m, { paired, boot: opt.boot, minN: opt.minN });
105
+ const j = judge(e, G[m], e ? e.n : 0);
106
+ metrics[m] = Object.assign(j, e ? { n: e.n, mode: e.mode, coverage: e.coverage } : {}, { naive: ratio(naive(base, cand, m)) });
107
+ }
108
+ // errors: difference in rate, two-proportion test
109
+ const er = rs => ({ n: rs.length, k: rs.filter(r => r.error).length }), eb = er(base), ec = er(cand);
110
+ if (eb.n && ec.n) metrics.errorRate = errorTest(eb, ec, G.errorRate);
111
+ // tokens/s per GPU and cost per million output tokens: meaningful when both arms served the same requests (paired)
112
+ const span = rs => (rs.length ? Math.max(...rs.map(r => r.t + (r.e2e || 0))) - Math.min(...rs.map(r => r.t)) : 0);
113
+ const outTok = rs => rs.filter(r => !r.error).reduce((a, r) => a + (r.osl || 0), 0);
114
+ const B = opt.baseline || {}, Cc = opt.candidate || {};
115
+ if (B.gpus && Cc.gpus) {
116
+ const tb = outTok(base) / Math.max(1, span(base)) / B.gpus, tc = outTok(cand) / Math.max(1, span(cand)) / Cc.gpus;
117
+ metrics.tokPerGpuS = { baseline: tb, candidate: tc, effect: tc / tb - 1, note: paired ? 'same requests on both arms' : 'arms served different traffic: read with care' };
118
+ if (B.rate && Cc.rate) {
119
+ const cb = B.gpus * B.rate * span(base) / 3600 / Math.max(1e-9, outTok(base) / 1e6), cc = Cc.gpus * Cc.rate * span(cand) / 3600 / Math.max(1e-9, outTok(cand) / 1e6);
120
+ metrics.costPerMTok = { baseline: cb, candidate: cc, effect: cc / cb - 1, verdict: cc / cb - 1 > G.costPerMTok ? 'worse' : cc / cb - 1 < -G.costPerMTok ? 'better' : 'same' };
121
+ }
122
+ }
123
+ // the same answers: greedy decoding should give the same tokens on both arms
124
+ let answers = null;
125
+ if (opt.answers) {
126
+ const a = opt.answers;
127
+ answers = Object.assign({}, a, { verdict: a.matchRate >= G.answers.match && (a.meanAbsLogprobDiff ?? 0) <= G.answers.logprob ? 'same' : 'different' });
128
+ }
129
+ // prediction vs measurement: is the model of the change right?
130
+ let prediction = null;
131
+ if (opt.predicted) {
132
+ const rows = [];
133
+ for (const [k, p] of Object.entries(opt.predicted)) { const m = metrics[k]; const meas = m ? (m.effect ?? null) : null; if (meas == null || !Number.isFinite(p)) continue; rows.push({ metric: k, predicted: p, measured: meas, off: (1 + meas) / (1 + p) - 1 }); }
134
+ prediction = { rows, holds: rows.every(r => Math.abs(r.off) <= G.prediction) };
135
+ }
136
+ const d = decide(metrics, answers, prediction);
137
+ // answers, prediction and infra appear only when given: absent rather than null, so their shape is part of the --json contract
138
+ return Object.assign({ decision: d.decision, why: d.why, paired, requests: { baseline: base.length, candidate: cand.length }, metrics, gates: G }, answers ? { answers } : {}, prediction ? { prediction } : {}, opt.infra ? { infra: opt.infra } : {});
139
+ }
140
+
141
+ // errors: a difference in rate past the gate, by a one-sided two-proportion test. eb, ec: { n, k } (requests, errors)
142
+ export function errorTest(eb, ec, gate = GATES.errorRate) {
143
+ const pb = eb.k / eb.n, pc = ec.k / ec.n, pp = (eb.k + ec.k) / (eb.n + ec.n), se = Math.sqrt(Math.max(1e-12, pp * (1 - pp) * (1 / eb.n + 1 / ec.n))), z = (pc - pb) / se;
144
+ return { baseline: pb, candidate: pc, diff: pc - pb, p: 1 - normCdf(z), verdict: pc - pb > gate && 1 - normCdf(z) < 0.05 ? 'worse' : pb - pc > gate && normCdf(z) < 0.05 ? 'better' : 'same' };
145
+ }
146
+
147
+ // promote / roll back / extend the test, from the metric verdicts (and answers and the prediction when there are any)
148
+ export function decide(metrics, answers = null, prediction = null, { unit = 'requests per arm' } = {}) {
149
+ const vs = Object.entries(metrics).filter(([, m]) => m && m.verdict);
150
+ const worse = vs.filter(([, m]) => m.verdict === 'worse').map(([k]) => k), open = vs.filter(([, m]) => m.verdict === 'inconclusive').map(([k]) => k);
151
+ let decision, why;
152
+ if (answers && answers.verdict === 'different') { decision = 'roll back'; why = `answers differ (${(100 * answers.matchRate).toFixed(1)}% identical under greedy decoding)`; }
153
+ else if (worse.length) { decision = 'roll back'; why = `worse on ${worse.join(', ')}`; }
154
+ else if (open.length) { decision = 'extend the test'; why = `not settled on ${open.join(', ')}: about ${Math.max(...open.map(k => metrics[k].more || 0))} more ${unit}`; }
155
+ else if (['ttft', 'tpot', 'e2e'].every(k => !metrics[k] || metrics[k].verdict === 'no data')) { decision = 'extend the test'; why = 'no latency data to judge yet'; }
156
+ else { decision = 'promote'; why = `no metric worse${vs.some(([, m]) => m.verdict === 'better') ? `; better on ${vs.filter(([, m]) => m.verdict === 'better').map(([k]) => k).join(', ')}` : ''}`; }
157
+ if (prediction && !prediction.holds) why += '; the prediction was off: recalibrate the sizer for this change';
158
+ return { decision, why };
159
+ }
160
+
161
+ // ---------- infra signals per arm (from the store's collectors) ----------
162
+ export function infraSignals(store, { baselineNodes, candidateNodes, from, to }) {
163
+ const inArm = (re, n) => re && n && re.test(n), out = {};
164
+ const bw = { b: [], c: [] }; for (const x of store.query('collective', { from, to })) { if (!Number.isFinite(x.busbw)) continue; if (inArm(baselineNodes, x.node)) bw.b.push(x.busbw); else if (inArm(candidateNodes, x.node)) bw.c.push(x.busbw); }
165
+ if (bw.b.length && bw.c.length) out.ncclBusBw = { baseline: median(bw.b), candidate: median(bw.c), effect: median(bw.c) / median(bw.b) - 1 };
166
+ const pw = { b: [], c: [] }, ecc = { b: 0, c: 0 };
167
+ for (const d of store.query('device', { from, to })) { const k = inArm(baselineNodes, d.node) ? 'b' : inArm(candidateNodes, d.node) ? 'c' : null; if (!k) continue; if (Number.isFinite(d.powerW)) pw[k].push(d.powerW); if ((d.faults || []).length) ecc[k] += d.faults.length; }
168
+ if (pw.b.length && pw.c.length) out.powerW = { baseline: median(pw.b), candidate: median(pw.c), effect: median(pw.c) / median(pw.b) - 1 };
169
+ const hard = { b: 0, c: 0 }; for (const l of store.query('log', { from, to, where: l => l.severity === 'hard' })) { if (inArm(baselineNodes, l.node)) hard.b++; else if (inArm(candidateNodes, l.node)) hard.c++; }
170
+ out.hardFaults = { baseline: hard.b + ecc.b, candidate: hard.c + ecc.c };
171
+ return out;
172
+ }
173
+
174
+ // ---------- plan: predict the change, size the test ----------
175
+ // config: { model, gpu, tp, wprec?, kvprec?, gpus?, effs? } (sizer ids). workload: { isl, osl, prefixHit (0–100), inflight }.
176
+ export function predict(config, w) {
177
+ const m = C.MODELS.find(x => x.id === config.model), g = C.GPUS.find(x => x.id === config.gpu);
178
+ if (!m) throw new Error(`unknown model ${config.model}`); if (!g) throw new Error(`unknown GPU ${config.gpu}`);
179
+ const tp = config.tp || g.domain || 8, s = Object.assign({}, M.SETTINGS, m, g, { wprec: config.wprec || m.wprec, kvprec: config.kvprec || 'fp8', avgIn: w.isl, peakIn: w.isl, avgOut: w.osl, peakOut: w.osl, ctx: Math.max(w.isl + w.osl, m.maxCtx || 0), prefixHit: w.prefixHit || 0 }, config.effs || {});
180
+ const inst = Math.max(1, Math.round((config.gpus || tp) / tp));
181
+ return M.operatingPoint(s, M.derive(s), { g: tp, kind: config.layout || 'TPEP', pp: 1, tpl: tp }, Math.max(1, Math.round(w.inflight / inst)));
182
+ }
183
+ export function workloadOf(requests) {
184
+ const rs = annotateLoad(requests);
185
+ const isl = median(rs.map(r => r.isl)), osl = median(rs.map(r => r.osl)), cachedKnown = rs.filter(r => r.cached != null);
186
+ return { isl, osl, prefixHit: cachedKnown.length ? 100 * cachedKnown.reduce((a, r) => a + r.cached, 0) / Math.max(1, cachedKnown.reduce((a, r) => a + r.isl, 0)) : 0, inflight: median(rs.map(r => r.conc)),
187
+ sigma: (() => { const l = rs.map(r => r.ttft).filter(v => v > 0).map(Math.log); if (l.length < 10) return null; const mu = l.reduce((a, b) => a + b, 0) / l.length; return Math.sqrt(l.reduce((a, b) => a + (b - mu) ** 2, 0) / (l.length - 1)); })() };
188
+ }
189
+ // requests per arm to see a relative effect `delta` (two-sided α = 0.05, power 0.8) on a log-normal latency of spread σ;
190
+ // pairing removes most of the request-to-request spread (σ of a paired log ratio ≈ pairedShare × σ)
191
+ export function testSize({ sigma = 0.6, delta = 0.03, paired = true, pairedShare = 0.35, rps = null } = {}) {
192
+ const s = paired ? sigma * pairedShare : sigma, d = Math.log(1 + delta), k = (1.96 + 0.8416) ** 2;
193
+ const n = Math.ceil((paired ? 1 : 2) * k * s * s / (d * d));
194
+ return { requestsPerArm: n, sigma, delta, paired, seconds: rps ? n / rps : null };
195
+ }
196
+ // ---------- calibration: what measurements taught the sizer ----------
197
+ // A profile is the one fleetops calibrate writes and the Inference Sizer reads (--calibration):
198
+ // { version, sizer: { "<gpu>|<model>": { effPrefill, effDecodeBW, effDecodeComp, fitOn, source } } }
199
+ export const EFF_KEYS = ['effPrefill', 'effDecodeBW', 'effDecodeComp'];
200
+ const EFF_CAP = { effPrefill: 0.9, effDecodeBW: 0.95, effDecodeComp: 0.9 }; // as calibrate.mjs: past these it is a model gap
201
+ export function calibrationFor(profile, config) {
202
+ const p = profile && profile.sizer && (profile.sizer[`${config.gpu}|${config.model}`] || profile.sizer[`${config.gpu}|*`]);
203
+ return p ? Object.fromEntries(EFF_KEYS.filter(k => typeof p[k] === 'number').map(k => [k, p[k]])) : null;
204
+ }
205
+ // a config with the profile's efficiencies for its GPU and model (its own effs still win)
206
+ export function applyCalibration(config, profile) { const c = calibrationFor(profile, config); return c ? Object.assign({}, config, { effs: Object.assign({}, c, config.effs || {}), calibrated: true }) : config; }
207
+
208
+ // When the measured effect of a change is off the prediction by more than the gate, fit the candidate's efficiencies
209
+ // so the sizer predicts what was measured: TPOT through the decode efficiencies, then TTFT through prefill, each by a
210
+ // one-dimensional search on a multiplier (capped as calibrate.mjs caps them). The baseline is taken as calibrated:
211
+ // measurements are relative, candidate against baseline. Only metrics with a settled verdict are used.
212
+ export function recalibrate(planObj, metrics, { gate = GATES.prediction } = {}) {
213
+ if (!planObj || !planObj.configs || !planObj.workload) return null;
214
+ const { baseline, candidate } = planObj.configs, w = planObj.workload, settled = m => m && ['worse', 'better', 'same'].includes(m.verdict) && Number.isFinite(m.effect);
215
+ const pb = predict(baseline, w), base = Object.assign({}, M.SETTINGS, candidate.effs || {});
216
+ const eff0 = Object.fromEntries(EFF_KEYS.map(k => [k, base[k]])), eff = Object.assign({}, eff0), rows = [];
217
+ const ratio = (k, e) => { const pc = predict(Object.assign({}, candidate, { effs: e }), w); return pc[k] / pb[k]; };
218
+ const fit = (k, keys) => {
219
+ if (!settled(metrics[k])) return;
220
+ const want = 1 + metrics[k].effect, now = ratio(k, eff), off = want / now - 1;
221
+ if (Math.abs(off) <= gate) { rows.push({ metric: k, predicted: now - 1, measured: metrics[k].effect, off, changed: false }); return; }
222
+ const at = m => { const e = Object.assign({}, eff); for (const x of keys) e[x] = Math.min(EFF_CAP[x], eff0[x] * m); return e; };
223
+ // latency falls as efficiency rises: find the multiplier whose predicted ratio meets the measured one
224
+ let lo = 0.05, hi = Math.max(...keys.map(x => EFF_CAP[x] / eff0[x]));
225
+ if (ratio(k, at(hi)) > want || ratio(k, at(lo)) < want) { rows.push({ metric: k, predicted: now - 1, measured: metrics[k].effect, off, changed: false, note: 'outside what efficiencies can explain: a model gap, not a calibration' }); return; }
226
+ for (let i = 0; i < 40; i++) { const mid = Math.sqrt(lo * hi); if (ratio(k, at(mid)) > want) lo = mid; else hi = mid; }
227
+ Object.assign(eff, at(hi));
228
+ rows.push({ metric: k, predicted: now - 1, measured: metrics[k].effect, off, changed: true, after: ratio(k, eff) - 1 });
229
+ };
230
+ fit('tpot', ['effDecodeBW', 'effDecodeComp']);
231
+ fit('ttft', ['effPrefill']);
232
+ const changed = rows.some(r => r.changed);
233
+ return { key: `${candidate.gpu}|${candidate.model}`, changed, rows, before: eff0, eff: Object.fromEntries(EFF_KEYS.map(k => [k, +eff[k].toFixed(4)])) };
234
+ }
235
+ export function mergeProfile(profile, rc, { fitOn, t = Math.floor(Date.now() / 1000) } = {}) {
236
+ const p = profile && typeof profile === 'object' ? JSON.parse(JSON.stringify(profile)) : { version: 1, sizer: {} };
237
+ p.sizer = p.sizer || {}; p.sizer[rc.key] = Object.assign({}, p.sizer[rc.key] || {}, rc.eff, { fitOn, source: 'fleetops-shadow', at: t });
238
+ p.generatedAt = t; return p;
239
+ }
240
+
241
+ export function plan({ baseline, candidate, workload, delta = 0.03, rps = null, paired = true }) {
242
+ const pb = predict(baseline, workload), pc = predict(candidate, workload);
243
+ const tokB = pb.outPerGpu, tokC = pc.outPerGpu;
244
+ const predicted = { ttft: pc.ttft / pb.ttft - 1, tpot: pc.tpot / pb.tpot - 1, tokPerGpuS: tokC / tokB - 1 };
245
+ if (baseline.rate && candidate.rate) predicted.costPerMTok = (candidate.rate / tokC) / (baseline.rate / tokB) - 1;
246
+ return { workload, configs: { baseline, candidate }, baseline: { ttft: pb.ttft, tpot: pb.tpot, tokPerGpuS: tokB }, candidate: { ttft: pc.ttft, tpot: pc.tpot, tokPerGpuS: tokC }, predicted,
247
+ test: testSize({ sigma: workload.sigma || 0.6, delta, paired, rps }),
248
+ note: 'Predictions are the Inference Sizer at the workload\'s median prompt, output, cache hit and calls in flight; calibrate it (fleetops calibrate) for numbers to trust.' };
249
+ }
250
+
251
+ // ---------- baselines and drift ----------
252
+ // A baseline is a sample of a service's requests (load context and latencies only), kept to compare later windows with.
253
+ export function makeBaseline(name, requests, { max = 5000, t = Math.floor(Date.now() / 1000), meta = {} } = {}) {
254
+ const rs = annotateLoad(requests), step = Math.max(1, rs.length / max), sample = [];
255
+ for (let i = 0; i < rs.length && sample.length < max; i += step) { const r = rs[Math.floor(i)]; sample.push({ t: r.t, isl: r.isl, osl: r.osl, cached: r.cached, conc: r.conc, ttft: r.ttft, tpot: r.tpot, e2e: r.e2e, error: r.error ? 1 : undefined }); }
256
+ return { kind: 'shadow-baseline', name, t, requests: rs.length, sample, meta };
257
+ }
258
+ // keep the arms' own load context: a baseline sample already has conc
259
+ const keepConc = rs => rs.map(r => Object.assign({}, r));
260
+ export function drift(baseline, current, opt = {}) {
261
+ const base = keepConc(baseline.sample), cur = annotateLoad(current);
262
+ const res = {};
263
+ for (const m of METRICS) { const e = effect(base, cur, m, { boot: opt.boot, minN: opt.minN }); res[m] = Object.assign(judge(e, (opt.gates || GATES)[m], e ? e.n : 0), e ? { coverage: e.coverage, n: e.n } : {}); }
264
+ const drifted = Object.entries(res).filter(([, v]) => v.verdict === 'worse' || v.verdict === 'better').map(([k, v]) => `${k} ${v.effect >= 0 ? '+' : ''}${(100 * v.effect).toFixed(1)}%`);
265
+ return { baseline: { name: baseline.name, t: baseline.t, requests: baseline.requests }, current: cur.length, metrics: res, drifted: drifted.length > 0, note: drifted.length ? `drifted from the baseline: ${drifted.join(', ')}` : 'within the baseline at matched load' };
266
+ }
267
+
268
+ // ---------- demo ----------
269
+ // A candidate 8% slower than the baseline at any load, that happened to get less than half the traffic during the test:
270
+ // the naive comparison says it's faster, the matched-load comparison says it's worse.
271
+ export function synth({ seed = 3, n = 3000, t0 = Date.UTC(2026, 10, 20, 12) / 1000 } = {}) {
272
+ const u = rng(seed), lognorm = s => Math.exp(s * Math.sqrt(-2 * Math.log(1 - u() + 1e-12)) * Math.cos(2 * Math.PI * u()));
273
+ const arm = (variant, rate, speed, loadPenalty) => {
274
+ const out = []; let t = t0;
275
+ // traffic: Poisson with bursts; the arm's offered rate sets how loaded it runs
276
+ while (out.length < n) {
277
+ t += -Math.log(1 - u()) / (rate * (1 + 0.8 * Math.sin((t - t0) / 600)));
278
+ const isl = Math.round(2000 * lognorm(0.9)), osl = Math.max(16, Math.round(250 * lognorm(0.6))), cached = Math.round(isl * (u() < 0.6 ? 0.92 : 0.1));
279
+ out.push({ t, isl, osl, cached, variant, source: 'shadow-demo' });
280
+ }
281
+ // latencies depend on load and load on latencies: settle both in a few passes
282
+ const noise = out.map(() => [lognorm(0.25), lognorm(0.15)]);
283
+ const set = (r, i, conc) => { const load = 1 + loadPenalty * Math.max(0, conc - 8) / 8, fresh = r.isl - r.cached;
284
+ r.ttft = (0.05 + fresh / 20000) * load * speed * noise[i][0]; r.tpot = 0.02 * load * speed * noise[i][1]; r.e2e = r.ttft + r.tpot * (r.osl - 1); };
285
+ out.forEach((r, i) => set(r, i, 1));
286
+ for (let pass = 0; pass < 3; pass++) { const byT = new Map(annotateLoad(out).map(x => [x.t, x.conc])); out.forEach((r, i) => set(r, i, byT.get(r.t))); }
287
+ for (const r of out) r.error = u() < 0.002 ? true : undefined;
288
+ return out;
289
+ };
290
+ return { baseline: arm('baseline', 1.0, 1.0, 0.5), candidate: arm('candidate', 0.55, 1.08, 0.5) };
291
+ }
@@ -0,0 +1,14 @@
1
+ // Small statistics shared across fleetops. Each keeps the exact behaviour of the copies it replaced, so results don't move.
2
+
3
+ // the true median of the finite values (mean of the middle two when even); NaN when there are none
4
+ export function median(a) {
5
+ const s = a.filter(Number.isFinite).sort((x, y) => x - y), m = s.length >> 1;
6
+ return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : NaN;
7
+ }
8
+ // the upper median of the finite values (the middle element, the higher of the two when even): what the detectors and
9
+ // root-cause rules were fitted with; `empty` when there are none
10
+ export function medianUpper(a, empty = NaN) { const s = a.filter(Number.isFinite).sort((x, y) => x - y); return s.length ? s[Math.floor(s.length / 2)] : empty; }
11
+ // the p-quantile by nearest rank (p in 0–1)
12
+ export function pctl(a, p) { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.max(0, Math.round(p * (s.length - 1))))] : NaN; }
13
+ // a seeded uniform generator in [0, 1) (an LCG: fast, reproducible, not for anything secret)
14
+ export function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); }
@@ -42,11 +42,6 @@ export function requestsFromSpans(spans, { poolAttr = 'gen_ai.request.model' } =
42
42
  return out.sort((x, y) => x.t - y.t);
43
43
  }
44
44
 
45
- // The slowest requests of a pool in a window: exemplars for a latency incident.
46
- export function slowRequests(store, { pool, from, to, by = 'ttft', top = 10 } = {}) {
47
- return store.query('request', { from, to, where: r => (!pool || r.pool === pool) && Number.isFinite(r[by]) }).sort((a, b) => b[by] - a[by]).slice(0, top);
48
- }
49
-
50
45
  // PyTorch profiler trace (Chrome trace JSON from torch.profiler / Kineto) → step records for one rank.
51
46
  // t0: epoch seconds of the trace's time zero when its timestamps are relative (default: baseTimeNanoseconds, else 0)
52
47
  export function kineto(json, { job, node, rank, t0 } = {}) {
@@ -15,5 +15,10 @@ that uses them says what it checks.
15
15
  | `llm-d/pd-disaggregation.disaggregatedset.yaml`, `llm-d/pd-disaggregation.router.values.yaml`, `llm-d/router.base.values.yaml` | llm-d's P/D guide for NVIDIA GPUs and vLLM: the DisaggregatedSet, and the router values it layers on the base | [llm-d/llm-d](https://github.com/llm-d/llm-d) `guides/` at a3ae49a | Apache-2.0 |
16
16
  | `llm-d/disaggregatedset.crd-v1.schema.json.gz` | The v1 `openAPIV3Schema` of the DisaggregatedSet CRD, as JSON | [kubernetes-sigs/lws](https://github.com/kubernetes-sigs/lws) v1.0.0 `config/crd/bases` | Apache-2.0 |
17
17
  | `llm-d/inferencepool.crd-v1.schema.json.gz` | The v1 schema of the InferencePool CRD | [kubernetes-sigs/gateway-api-inference-extension](https://github.com/kubernetes-sigs/gateway-api-inference-extension) `config/crd/bases` (main, Nov 2026) | Apache-2.0 |
18
+ | `llm-d/llminferenceservice.crd-v1alpha2.schema.json.gz` | The v1alpha2 (storage) schema of KServe's LLMInferenceService CRD, with `spec.router.route.group` / `weight` for canary traffic splitting | [kserve/kserve](https://github.com/kserve/kserve) `config/crd/full/llmisvc` at 1cee2db | Apache-2.0 |
19
+ | `rollouts/argo-rollouts-analysistemplate.crd-v1alpha1.schema.json.gz`, `rollouts/argo-rollouts-rollout.crd-v1alpha1.schema.json.gz` | The `openAPIV3Schema` of the AnalysisTemplate and Rollout CRDs, as JSON | [argoproj/argo-rollouts](https://github.com/argoproj/argo-rollouts) v1.10.2 `manifests/crds` | Apache-2.0 |
20
+ | `rollouts/flagger-canary.crd-v1beta1.schema.json.gz` | The v1beta1 schema of Flagger's Canary CRD | [fluxcd/flagger](https://github.com/fluxcd/flagger) v1.45.0 `artifacts/flagger/crd.yaml` | Apache-2.0 |
21
+ | `rollouts/prometheus-operator-podmonitor.crd-v1.schema.json.gz` | The v1 schema of the PodMonitor CRD | [prometheus-operator/prometheus-operator](https://github.com/prometheus-operator/prometheus-operator) v0.95.2 `example/prometheus-operator-crd` | Apache-2.0 |
22
+ | `vllm/metric-names.txt` | vLLM's Prometheus metric names (v1 engine) with the suffixes the client library adds, and the `finished_reason` values | [vllm-project/vllm](https://github.com/vllm-project/vllm) `vllm/v1/metrics/loggers.py` at 43108ff | Apache-2.0 (names only) |
18
23
 
19
24
  `tools/fetch-public-data.sh` downloads the full Philly traces for larger runs.
@@ -1,45 +1,79 @@
1
1
  #!/usr/bin/env bash
2
- # Admission checks for one GPU node, run on the node before it joins the training pool or returns from repair.
2
+ # Admission checks for one GPU node (NVIDIA or AMD), run on the node before it joins the training pool or returns from repair.
3
3
  # Writes JSON lines ({"record": kind, …}) for `fleetops data import admission FILE`, then `fleetops admit check NODE` gives the verdict.
4
4
  #
5
5
  # tools/admit-node.sh > admit-$(hostname).jsonl # versions, topology, DCGM diag, NCCL, SDC canary
6
6
  # tools/admit-node.sh --burn-in 6h --out admit.jsonl # plus a burn-in under load (dcgmproftester)
7
7
  #
8
8
  # What it runs (each skipped with a note when its tool is missing):
9
- # versions driver, VBIOS, CUDA, kernel, NCCL (via PyTorch), GPU model and count → an inventory record
10
- # topology PCIe generation and width per GPU, active NVLink links per GPU → check + topology records
11
- # dcgm-diag dcgmi diag -r 3 (about 10–20 minutes) → check record
12
- # nccl all_reduce_perf from nccl-tests on every GPU of the node → check record (bus bandwidth)
13
- # sdc-canary tools/sdc-canary.py (needs PyTorch) → sdc_check records
14
- # burn-in with --burn-in: dcgmproftester on every GPU, max temperature and new XIDs → check record
9
+ # versions driver, VBIOS/IFWI, CUDA or ROCm, kernel, NCCL or RCCL (via PyTorch), GPU model and count → inventory
10
+ # topology PCIe generation and width, active NVLink (nvidia-smi) or XGMI (amd-smi topology) links → check + topology
11
+ # diag NVIDIA: dcgmi diag -r 3 (10–20 minutes) → dcgm-diag; AMD: ROCm Validation Suite (rvs -c CONF) → rvs-diag
12
+ # nccl all_reduce_perf from nccl-tests (NVIDIA) or rccl-tests (AMD) on every GPU of the node → check record
13
+ # sdc-canary tools/sdc-canary.py (needs PyTorch, CUDA or ROCm) → sdc_check records
14
+ # burn-in with --burn-in, NVIDIA: dcgmproftester on every GPU, max temperature and new XIDs → check record
15
+ # (AMD: run your own load; admission counts hours under load from the exporter's samples)
15
16
  #
16
17
  # It loads every GPU, so it refuses to run while compute processes are on them (--force to override). It changes
17
18
  # nothing on the node.
18
19
  #
19
20
  # Options: --out FILE --burn-in DURATION (e.g. 6h, 90m) --diag-level 1|2|3|4 (3) --skip dcgm,nccl,sdc,burn-in
20
- # --nccl-bin PATH (all_reduce_perf) --node NAME (hostname) --force
21
+ # --nccl-bin PATH (all_reduce_perf) --rvs-conf FILE (AMD) --node NAME (hostname) --force
21
22
  set -euo pipefail
22
23
  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
23
- OUT=/dev/stdout; BURN=""; LEVEL=3; SKIP=""; NCCL_BIN="${ALL_REDUCE_PERF:-all_reduce_perf}"; NODE="$(hostname)"; FORCE=0
24
+ OUT=/dev/stdout; BURN=""; LEVEL=3; SKIP=""; RVS_CONF=""; NCCL_BIN="${ALL_REDUCE_PERF:-all_reduce_perf}"; NODE="$(hostname)"; FORCE=0
24
25
  while [ $# -gt 0 ]; do case "$1" in
25
26
  --out) OUT="$2"; shift 2;; --burn-in) BURN="$2"; shift 2;; --diag-level) LEVEL="$2"; shift 2;; --skip) SKIP="$2"; shift 2;;
26
- --nccl-bin) NCCL_BIN="$2"; shift 2;; --node) NODE="$2"; shift 2;; --force) FORCE=1; shift;;
27
- -h|--help) sed -n '2,23p' "$0"; exit 0;; *) echo "unknown option: $1" >&2; exit 2;; esac; done
27
+ --nccl-bin) NCCL_BIN="$2"; shift 2;; --rvs-conf) RVS_CONF="$2"; shift 2;; --node) NODE="$2"; shift 2;; --force) FORCE=1; shift;;
28
+ -h|--help) sed -n '2,26p' "$0"; exit 0;; *) echo "unknown option: $1" >&2; exit 2;; esac; done
28
29
  die() { printf 'admit-node: %s\n' "$*" >&2; exit 1; }
29
30
  note() { printf 'admit-node: %s\n' "$*" >&2; }
30
31
  skip() { [[ ",$SKIP," == *",$1,"* ]]; }
31
32
  [[ "$NODE" =~ ^[A-Za-z0-9._-]+$ ]] || die "--node must be a plain host name"
32
33
  [[ "$LEVEL" =~ ^[1-4]$ ]] || die "--diag-level 1-4"
33
- command -v nvidia-smi >/dev/null || die "nvidia-smi not found (NVIDIA GPUs only for now)"
34
+ if command -v nvidia-smi >/dev/null; then VENDOR=nvidia; elif command -v amd-smi >/dev/null; then VENDOR=amd
35
+ else die "neither nvidia-smi nor amd-smi found"; fi
34
36
  command -v python3 >/dev/null || die "python3 is needed to write the results"
35
- if [ "$FORCE" != 1 ] && [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null | tr -d '[:space:]')" ]; then
36
- die "compute processes are running on the GPUs; drain the node first (or --force)"
37
+ TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
38
+ if [ "$FORCE" != 1 ]; then
39
+ if [ "$VENDOR" = nvidia ] && [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null | tr -d '[:space:]')" ]; then
40
+ die "compute processes are running on the GPUs; drain the node first (or --force)"
41
+ fi
42
+ if [ "$VENDOR" = amd ]; then
43
+ amd-smi process --json > "$TMP/procs.json" 2>/dev/null || echo '[]' > "$TMP/procs.json"
44
+ python3 "$HERE/amd-admit.py" --node "$NODE" --processes "$TMP/procs.json" --busy-only || die "compute processes are running on the GPUs; drain the node first (or --force)"
45
+ fi
37
46
  fi
38
47
  secs() { local v="$1"; case "$v" in *h) echo $(( ${v%h} * 3600 ));; *m) echo $(( ${v%m} * 60 ));; *s) echo "${v%s}";; *) echo "$v";; esac; }
39
- TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
40
48
  emit() { python3 -c 'import json,sys,time; r=json.loads(sys.argv[1]); r.setdefault("t", int(time.time())); r.setdefault("source","admit-node"); print(json.dumps(r))' "$1" >> "$TMP/out.jsonl"; }
41
49
  J() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"; }
42
50
 
51
+ if [ "$VENDOR" = amd ]; then
52
+ # versions, inventory, PCIe and XGMI from amd-smi
53
+ amd-smi static --json > "$TMP/static.json" 2>/dev/null || die "amd-smi static --json failed"
54
+ amd-smi metric --pcie --json > "$TMP/metric.json" 2>/dev/null || true
55
+ amd-smi topology --json > "$TMP/topo.json" 2>/dev/null || true
56
+ ROCM=$(cat /opt/rocm/.info/version 2>/dev/null | sed -n 1p || true)
57
+ RCCLV=$(python3 -c 'import torch; print(".".join(map(str, torch.cuda.nccl.version())))' 2>/dev/null || true)
58
+ python3 "$HERE/amd-admit.py" --node "$NODE" --static "$TMP/static.json" $([ -s "$TMP/metric.json" ] && echo --metric "$TMP/metric.json") \
59
+ $([ -s "$TMP/topo.json" ] && echo --topology "$TMP/topo.json") ${ROCM:+--rocm "$ROCM"} ${RCCLV:+--rccl "$RCCLV"} --kernel "$(uname -r)" >> "$TMP/out.jsonl"
60
+ COUNT=$(python3 -c 'import json,sys; o=json.load(open(sys.argv[1])); print(len(o if isinstance(o,list) else o.get("gpu_data",[])))' "$TMP/static.json")
61
+ # ROCm Validation Suite: GPU stress and health checks from a config file
62
+ if ! skip dcgm && ! skip diag; then
63
+ RVS=$(command -v rvs || ls /opt/rocm/bin/rvs 2>/dev/null || true)
64
+ CONF="${RVS_CONF:-$(ls /opt/rocm/share/rocm-validation-suite/conf/gst_single.conf 2>/dev/null || true)}"
65
+ if [ -n "$RVS" ] && [ -n "$CONF" ]; then
66
+ note "rvs -c $CONF (this takes a while)"
67
+ set +e; "$RVS" -c "$CONF" > "$TMP/rvs.txt" 2>&1; RC=$?; set -e
68
+ BAD=$(grep -ciE '(pass|met)[[:space:]]*:[[:space:]]*FALSE|\bFAIL' "$TMP/rvs.txt" || true)
69
+ emit "{\"record\":\"check\",\"node\":$(J "$NODE"),\"check\":\"rvs-diag\",\"ok\":$([ "$RC" -eq 0 ] && [ "${BAD:-0}" -eq 0 ] && echo true || echo false),\"detail\":$(J "$(basename "$CONF"): exit $RC, $BAD failing line(s)")}"
70
+ else note "rvs (ROCm Validation Suite) or its config not found: no GPU diagnostic (--rvs-conf FILE)"; fi
71
+ fi
72
+ [ -n "$BURN" ] && note "burn-in on AMD: run your own load; admission counts hours under load from the exporter's samples"
73
+ BURN=""
74
+ fi
75
+
76
+ if [ "$VENDOR" = nvidia ]; then
43
77
  # versions and inventory
44
78
  NAME=$(nvidia-smi --query-gpu=name --format=csv,noheader | sed -n 1p | sed 's/ *$//')
45
79
  COUNT=$(nvidia-smi --query-gpu=index --format=csv,noheader | wc -l | tr -d ' ')
@@ -94,6 +128,7 @@ print(json.dumps({"record": "check", "t": int(time.time()), "source": "admit-nod
94
128
  PY
95
129
  else note "dcgmi not found: no DCGM diagnostic"; fi
96
130
  fi
131
+ fi
97
132
 
98
133
  # NCCL all-reduce across the node's GPUs
99
134
  if ! skip nccl; then
@@ -132,7 +167,7 @@ if ! skip sdc; then
132
167
  python3 "$HERE/sdc-canary.py" --node "$NODE" | python3 -c 'import json,sys
133
168
  for l in sys.stdin:
134
169
  if l.strip(): r = json.loads(l); r["record"] = "sdc_check"; print(json.dumps(r))' >> "$TMP/out.jsonl" || note "the canary failed to run"
135
- else note "PyTorch with CUDA not found: no SDC canary"; fi
170
+ else note "PyTorch with CUDA or ROCm not found: no SDC canary"; fi
136
171
  fi
137
172
 
138
173
  cat "$TMP/out.jsonl" > "$OUT"
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env python3
2
+ """AMD side of admit-node.sh: amd-smi JSON → admission records (JSON lines), the same shapes the NVIDIA path writes.
3
+
4
+ amd-admit.py --node N --static static.json [--metric metric.json] [--topology topo.json] [--processes procs.json]
5
+ [--rocm VERSION] [--rccl VERSION] [--busy-only]
6
+
7
+ static `amd-smi static --json` → inventory record (market name, driver, IFWI, ROCm, RCCL) + gpu-count check
8
+ metric `amd-smi metric --pcie --json` → pcie check: the slowest GPU's max generation × current width
9
+ topology `amd-smi topology --json` → topology records, one per XGMI link (kind xgmi)
10
+ processes `amd-smi process --json` → with --busy-only: exit 3 when compute processes are running, else 0
11
+
12
+ amd-smi prints a list of per-GPU objects, or {"gpu_data": [...]} in newer releases, and values as plain numbers or
13
+ {"value": …, "unit": …}; both are read.
14
+ """
15
+ import argparse, json, sys, time
16
+
17
+ GEN = {2.5: 1, 5: 2, 8: 3, 16: 4, 32: 5, 64: 6, 128: 7}
18
+
19
+
20
+ def gpus(path):
21
+ with open(path) as f:
22
+ o = json.load(f)
23
+ a = o if isinstance(o, list) else (o.get("gpu_data") or o.get("gpus") or [])
24
+ return [g for g in a if isinstance(g, dict) and "gpu" in g]
25
+
26
+
27
+ def val(v):
28
+ if isinstance(v, dict) and "value" in v:
29
+ v = v["value"]
30
+ return None if v in (None, "N/A", "") else v
31
+
32
+
33
+ def num(v):
34
+ v = val(v)
35
+ try:
36
+ return float(v)
37
+ except (TypeError, ValueError):
38
+ try:
39
+ return float(str(v).split()[0])
40
+ except (TypeError, ValueError, IndexError):
41
+ return None
42
+
43
+
44
+ def busy(path):
45
+ """True when any GPU lists a process with a pid."""
46
+ def walk(o):
47
+ if isinstance(o, dict):
48
+ if num(o.get("pid")):
49
+ return True
50
+ return any(walk(v) for v in o.values())
51
+ if isinstance(o, list):
52
+ return any(walk(v) for v in o)
53
+ return False
54
+ with open(path) as f:
55
+ return walk(json.load(f))
56
+
57
+
58
+ def main():
59
+ ap = argparse.ArgumentParser()
60
+ ap.add_argument("--node", required=True)
61
+ ap.add_argument("--static"); ap.add_argument("--metric"); ap.add_argument("--topology"); ap.add_argument("--processes")
62
+ ap.add_argument("--rocm"); ap.add_argument("--rccl"); ap.add_argument("--kernel")
63
+ ap.add_argument("--busy-only", action="store_true")
64
+ ap.add_argument("--t", type=int, default=int(time.time()))
65
+ a = ap.parse_args()
66
+ if a.busy_only:
67
+ sys.exit(3 if a.processes and busy(a.processes) else 0)
68
+ out = []
69
+ rec = lambda **r: out.append(dict(r, t=a.t, source="admit-node", node=a.node))
70
+ if a.static:
71
+ gs = gpus(a.static)
72
+ names = [val((g.get("asic") or {}).get("market_name")) or val((g.get("board") or {}).get("product_name")) for g in gs]
73
+ fw = sorted({val((g.get("ifwi") if isinstance(g.get("ifwi"), dict) else g.get("vbios") or {}).get("version")) or "" for g in gs} - {""})
74
+ drv = [val((g.get("driver") or {}).get("version")) for g in gs]
75
+ versions = {k: v for k, v in {"driver": next((d for d in drv if d), None), "vbios": "|".join(fw) or None, "rocm": a.rocm, "rccl": a.rccl, "kernel": a.kernel}.items() if v}
76
+ sku = max(set(n for n in names if n), key=names.count) if any(names) else ""
77
+ rec(record="inventory", vendor="amd", kind="gpu", sku=sku, devices=len(gs), versions=versions)
78
+ rec(record="check", check="gpu-count", value=len(gs))
79
+ if a.metric:
80
+ width = {str(g["gpu"]): num((g.get("pcie") or {}).get("width")) for g in gpus(a.metric)}
81
+ pairs = []
82
+ for g in gs:
83
+ sp, w = num((g.get("bus") or {}).get("max_pcie_speed")), width.get(str(g["gpu"]))
84
+ if sp in GEN and w:
85
+ pairs.append((GEN[sp], int(w)))
86
+ if pairs:
87
+ gen, w = sorted(pairs)[0]
88
+ rec(record="check", check="pcie", value=f"gen{gen}x{w}")
89
+ if a.topology:
90
+ seen = set()
91
+ for g in gpus(a.topology):
92
+ links = g.get("links")
93
+ if isinstance(links, list):
94
+ items = [(l.get("gpu"), l.get("link_type"), l.get("link_status"), l.get("num_hops")) for l in links]
95
+ else:
96
+ lt = g.get("link_type") or {}
97
+ items = [(k.replace("gpu_", ""), v, (g.get("link_accessibility") or {}).get(k), (g.get("hops") or {}).get(k)) for k, v in lt.items()]
98
+ for peer, typ, status, hops in items:
99
+ if str(typ).upper() != "XGMI" or str(peer) == str(g["gpu"]) or (status and str(status).upper() != "ENABLED"):
100
+ continue
101
+ key = tuple(sorted((str(g["gpu"]), str(peer))))
102
+ if key in seen:
103
+ continue
104
+ seen.add(key)
105
+ rec(record="topology", kind="xgmi", **{"from": f"{a.node}/gpu{key[0]}", "to": f"{a.node}/gpu{key[1]}"}, hops=num(hops))
106
+ for r in out:
107
+ print(json.dumps({k: v for k, v in r.items() if v is not None}))
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
@@ -0,0 +1,61 @@
1
+ // fleetops CLI: calibrate (see ../fleetops.mjs for the entry point and dispatch)
2
+ import fs from 'node:fs';
3
+ import * as Calib from '../../src/calibrate.mjs';
4
+ import { J, OUT, say, read, time, pc, errs } from './common.mjs';
5
+ import { HELP } from './help.mjs';
6
+
7
+ export async function calibrate(store, cmd, o) {
8
+ const now = o.now ? +o.now : Math.floor(Date.now() / 1000);
9
+ const writeProfile = p => { if (o.profile && o.profile !== true) { fs.writeFileSync(o.profile, JSON.stringify(p, null, 1)); say(`profile written to ${o.profile}`); } };
10
+ if (cmd === 'benchmarks') {
11
+ const r = Calib.calibrateBenchmarks(store, { islMean: o.isl ? +o.isl : 300, fleetscope: !o['no-fleetscope'], now });
12
+ store.append('calibration', r.records);
13
+ writeProfile(r.profile);
14
+ if (J) { Object.assign(OUT, r); return; }
15
+ say(`Inference Sizer: GPUs predicted for each benchmark's measured load, before and after calibration (mean input ${r.profile.assumptions.islMean} tokens assumed)`);
16
+ for (const x of r.runs) say(x.sizer.error ? ` ${x.system}: ${x.sizer.error}` : ` ${x.system}: used ${x.sizer.measuredGpus}; spec-sheet model ${x.sizer.before} (${pc(x.sizer.errBefore)}) → calibrated ${x.sizer.after} (${pc(x.sizer.errAfter)})${x.sizer.capped.length ? `; at the ceiling: ${x.sizer.capped.join(', ')}` : ''}`);
17
+ if (!o['no-fleetscope']) {
18
+ say('FleetScope: one pool at the benchmark\'s load');
19
+ for (const x of r.runs) if (x.fleetscope) say(x.fleetscope.error ? ` ${x.system}: ${x.fleetscope.error}` : ` ${x.system}: before ${errs(x.fleetscope.before)}\n fitted prefill ×${x.fleetscope.calib.prefill}, decode ×${x.fleetscope.calib.decode}: ${x.fleetscope.pass ? 'within the bar' : `not within the bar (${x.fleetscope.diagnosis})`}; after ${errs(x.fleetscope.after)}`);
20
+ }
21
+ if (r.heldOut.length) say('Held out (low-latency runs, checked against the profile fitted on the same system):');
22
+ for (const h of r.heldOut) {
23
+ if (h.sizerCalibrated) say(` ${h.system} ${h.model}: sizer spec-sheet ${h.sizerSpecSheet.predicted} GPUs (${pc(h.sizerSpecSheet.err)}), calibrated ${h.sizerCalibrated.predicted} (${pc(h.sizerCalibrated.err)}) vs ${h.sizerCalibrated.measuredGpus} used`);
24
+ if (h.fleetscopeCalibrated) say(` FleetScope spec-sheet ${errs(h.fleetscopeSpecSheet.rows)}\n FleetScope calibrated ${errs(h.fleetscopeCalibrated.rows)}`);
25
+ }
26
+ return;
27
+ }
28
+ const graphFile = o.graph && o.graph !== true ? o.graph : null;
29
+ if (!graphFile) throw new Error('--graph FILE (a FleetScope graph: "Copy graph JSON" in the editor)');
30
+ const graph = JSON.parse(read(graphFile));
31
+ if (cmd === 'serving') {
32
+ const run = () => {
33
+ const t = Math.floor(Date.now() / 1000), to = time(o.to) ?? (o.every ? t : undefined), from = time(o.from) ?? (o.every ? t - 86400 : undefined);
34
+ const r = Calib.calibrateServing(store, graph, { from, to, holdout: o.holdout ? +o.holdout : 0, now: o.now ? +o.now : t });
35
+ store.append('calibration', r.records);
36
+ writeProfile(r.profile);
37
+ if (o['graph-out'] && o['graph-out'] !== true) fs.writeFileSync(o['graph-out'], JSON.stringify(Calib.applyToGraph(graph, r.profile).graph, null, 1));
38
+ if (J) { Object.assign(OUT, r); return; }
39
+ for (const p of r.pools) say(p.skipped ? ` ${p.name}: ${p.skipped}` : ` ${p.name}: prefill ×${p.calib.prefill}, decode ×${p.calib.decode} — ${p.pass ? 'within the bar' : `not within the bar (${p.diagnosis})`}\n fit: ${errs(p.after)}${p.heldOut ? `\n held out: ${errs(p.heldOut.rows)} — ${p.heldOut.pass ? 'pass' : 'fail'}` : ''}`);
40
+ };
41
+ run();
42
+ if (o.every) { const every = +o.every * 1000; say(`re-fitting every ${o.every} s`); setInterval(() => { try { run(); } catch (e) { console.error(e.message); } }, every); }
43
+ return;
44
+ }
45
+ if (cmd === 'drift') {
46
+ if (!o.profile || o.profile === true) throw new Error('--profile FILE');
47
+ const d = Calib.driftCheck(store, graph, JSON.parse(read(o.profile)), { from: time(o.from), to: time(o.to), now });
48
+ store.append('drift', d);
49
+ if (J) OUT.drift = d; else for (const x of d) say(` ${x.pool}: ${x.drifted ? 'DRIFT' : 'ok'} — ${x.why}`);
50
+ if (o['fail-on-drift'] && d.some(x => x.drifted)) process.exitCode = 3;
51
+ return;
52
+ }
53
+ if (cmd === 'apply') {
54
+ if (!o.profile || !o.out) throw new Error('--profile FILE --out FILE');
55
+ const r = Calib.applyToGraph(graph, JSON.parse(read(o.profile)));
56
+ fs.writeFileSync(o.out, JSON.stringify(r.graph, null, 1));
57
+ if (J) OUT.applied = r.applied; else say(`multipliers written for ${r.applied.join(', ') || 'no pools (no profile entries match the graph)'} → ${o.out}`);
58
+ return;
59
+ }
60
+ throw new Error(`unknown: calibrate ${cmd}\n\n${HELP}`);
61
+ }