aiinfra-tools 0.4.0 → 0.5.1
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/CHANGELOG.md +179 -0
- package/README.md +33 -1
- package/bin/aiinfra.mjs +12 -0
- package/fleetops/deploy/grafana-dashboard.json +71 -0
- package/fleetops/docs/SHADOW.md +25 -2
- package/fleetops/package.json +1 -1
- package/fleetops/src/adapters/nvsentinel.mjs +2 -1
- package/fleetops/src/api.mjs +8 -0
- package/fleetops/src/schema.mjs +3 -0
- package/fleetops/src/shadow-quality.mjs +107 -0
- package/fleetops/src/shadow.mjs +12 -6
- package/fleetops/tools/cmd/help.mjs +4 -1
- package/fleetops/tools/cmd/shadow.mjs +14 -2
- package/fleetscope/build.mjs +1 -0
- package/fleetscope/dist/index.html +134 -16
- package/fleetscope/package.json +1 -1
- package/fleetscope/src/engine.js +1 -1
- package/fleetscope/src/index.src.html +17 -1
- package/gpu-health/package.json +1 -1
- package/gpu-ledger/package.json +1 -1
- package/harness-ledger/README.md +48 -0
- package/harness-ledger/integrations/README.md +11 -0
- package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
- package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
- package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
- package/harness-ledger/package.json +1 -1
- package/harness-ledger/src/advise.mjs +410 -0
- package/harness-ledger/src/assess.mjs +66 -0
- package/harness-ledger/src/doctor.mjs +202 -0
- package/harness-ledger/src/engine-metrics.mjs +35 -0
- package/harness-ledger/src/importers.mjs +14 -3
- package/harness-ledger/src/lint.mjs +115 -0
- package/harness-ledger/src/mooncake.mjs +83 -0
- package/harness-ledger/src/prices.json +585 -0
- package/harness-ledger/src/prices.mjs +7 -17
- package/harness-ledger/src/profile.mjs +164 -0
- package/harness-ledger/src/record.mjs +2 -2
- package/harness-ledger/src/suggest.mjs +177 -0
- package/harness-ledger/src/trajectory.mjs +81 -0
- package/harness-ledger/src/workload-demo.mjs +100 -0
- package/harness-ledger/tools/harness-ledger.mjs +224 -5
- package/hybrid-tracing/package.json +1 -1
- package/inference-sizer/build.mjs +1 -0
- package/inference-sizer/dist/index.html +137 -18
- package/inference-sizer/docs/CATALOG.md +13 -4
- package/inference-sizer/package.json +1 -1
- package/inference-sizer/src/catalog.js +36 -10
- package/inference-sizer/src/fleetscope.js +1 -1
- package/inference-sizer/src/index.src.html +7 -0
- package/inference-sizer/src/model.js +10 -4
- package/inference-sizer/src/suggest.js +70 -0
- package/inference-sizer/src/ui.js +13 -3
- package/inference-sizer/tools/size.mjs +4 -0
- package/mcp/README.md +3 -0
- package/mcp/server.mjs +22 -0
- package/package.json +5 -2
- package/schemas/README.md +3 -0
- package/schemas/commands.mjs +7 -0
- package/schemas/harness-ledger.advise.schema.json +1106 -0
- package/schemas/harness-ledger.assess.schema.json +2839 -0
- package/schemas/harness-ledger.economics.schema.json +8 -2
- package/schemas/harness-ledger.suggest.schema.json +326 -0
|
@@ -7,6 +7,7 @@ import * as Replay from '../../src/shadow-replay.mjs';
|
|
|
7
7
|
import * as SProm from '../../src/shadow-prom.mjs';
|
|
8
8
|
import * as Gate from '../../src/shadow-gate.mjs';
|
|
9
9
|
import * as Canary from '../../src/shadow-canary.mjs';
|
|
10
|
+
import * as Quality from '../../src/shadow-quality.mjs';
|
|
10
11
|
import { J, OUT, say, read, time, fmt, pctS } from './common.mjs';
|
|
11
12
|
|
|
12
13
|
// ---------- shadow upgrades ----------
|
|
@@ -24,6 +25,7 @@ export function shadowText(r) {
|
|
|
24
25
|
if (r.metrics.tokPerGpuS) L.push(` tok/s per GPU ${r.metrics.tokPerGpuS.baseline.toFixed(0)} → ${r.metrics.tokPerGpuS.candidate.toFixed(0)} (${pctS(r.metrics.tokPerGpuS.effect)}; ${r.metrics.tokPerGpuS.note})`);
|
|
25
26
|
if (r.metrics.costPerMTok) L.push(` $ per M output tokens ${r.metrics.costPerMTok.baseline.toFixed(2)} → ${r.metrics.costPerMTok.candidate.toFixed(2)} (${pctS(r.metrics.costPerMTok.effect)}) ${r.metrics.costPerMTok.verdict}`);
|
|
26
27
|
if (r.answers) L.push(` answers ${r.answers.identical}/${r.answers.prompts} identical under greedy decoding; log-prob drift ${r.answers.meanAbsLogprobDiff != null ? r.answers.meanAbsLogprobDiff.toFixed(3) : '–'} ${r.answers.verdict}`);
|
|
28
|
+
if (r.quality) L.push(` quality ${r.quality.candidate.passed}/${r.quality.n} tasks vs ${r.quality.baseline.passed}/${r.quality.n} (${pctS(r.quality.diff).replace('%', ' pts')}; ${r.quality.lost} lost, ${r.quality.gained} gained)`.padEnd(52) + ` ${r.quality.verdict}`);
|
|
27
29
|
if (r.prediction) L.push('', ` prediction ${r.prediction.holds ? 'holds' : 'is off: recalibrate'}: ` + r.prediction.rows.map(x => `${x.metric} predicted ${pctS(x.predicted)}, measured ${pctS(x.measured)}`).join('; '));
|
|
28
30
|
if (r.infra) L.push('', ' infra: ' + Object.entries(r.infra).map(([k, v]) => v.effect != null ? `${k} ${pctS(v.effect)}` : `${k} ${v.baseline} → ${v.candidate}`).join(', '));
|
|
29
31
|
return L.join('\n');
|
|
@@ -95,13 +97,23 @@ export async function shadowCmd(store, cmd, rest, o) {
|
|
|
95
97
|
if (J) { OUT.answers = res; return; }
|
|
96
98
|
return say(res.dryRun ? `dry run: ${res.note}. Add --live to send them.` : `${res.identical}/${res.prompts} identical; first divergence at token ${res.meanFirstDivergence ?? '–'} on average; log-prob drift ${res.meanAbsLogprobDiff != null ? res.meanAbsLogprobDiff.toFixed(4) : '–'}${opt('out') ? ` → ${opt('out')}` : ''}`);
|
|
97
99
|
}
|
|
100
|
+
if (cmd === 'quality') {
|
|
101
|
+
if (!opt('tasks') || !opt('baseline') || !opt('candidate')) throw new Error('--tasks FILE.jsonl --baseline URL --candidate URL [--max-drop 2] [--live]');
|
|
102
|
+
const tasks = Quality.loadTasks(read(opt('tasks')));
|
|
103
|
+
const maxDrop = num('max-drop') != null ? num('max-drop') / 100 : Quality.DEFAULTS.maxDrop;
|
|
104
|
+
const res = await Quality.runQuality(tasks, [arm('baseline', opt('baseline')), arm('candidate', opt('candidate'))], { live: !!o.live, model: opt('model'), maxTokens: num('max-tokens'), completions: !!o.completions,
|
|
105
|
+
concurrency: num('concurrency') || Quality.DEFAULTS.concurrency, maxDrop, minTasks: num('min-tasks') ?? Quality.DEFAULTS.minTasks });
|
|
106
|
+
if (!res.dryRun) { const f = opt('out') || path.join(dir, 'quality.json'); fs.writeFileSync(f, JSON.stringify(res, null, 1) + '\n'); res.file = f; }
|
|
107
|
+
if (J) { OUT.quality = res; return; }
|
|
108
|
+
return say(Quality.qualityText(res) + (res.file ? `\nwrote ${res.file}; fleetops shadow compare … --quality ${res.file}` : ''));
|
|
109
|
+
}
|
|
98
110
|
if (cmd === 'compare') {
|
|
99
111
|
let base, cand;
|
|
100
112
|
if (opt('results')) { const rs = readJsonl(opt('results')); base = rs.filter(r => r.variant === 'baseline'); cand = rs.filter(r => r.variant === 'candidate'); }
|
|
101
113
|
else { if (!opt('baseline') || !opt('candidate')) throw new Error('--results FILE, or --baseline SEL --candidate SEL'); base = requests(opt('baseline')); cand = requests(opt('candidate')); }
|
|
102
114
|
if (!base.length || !cand.length) throw new Error(`no requests: ${base.length} baseline, ${cand.length} candidate`);
|
|
103
115
|
const plan = json('plan'), re = k => (opt(k) ? new RegExp(opt(k)) : null);
|
|
104
|
-
const r = Shadow.compare(base, cand, { gates: json('gates'), predicted: plan && plan.predicted, answers: json('answers'),
|
|
116
|
+
const r = Shadow.compare(base, cand, { gates: json('gates'), predicted: plan && plan.predicted, answers: json('answers'), quality: json('quality'),
|
|
105
117
|
baseline: { gpus: num('baseline-gpus'), rate: num('baseline-rate') }, candidate: { gpus: num('candidate-gpus'), rate: num('candidate-rate') },
|
|
106
118
|
infra: opt('baseline-nodes') ? Shadow.infraSignals(store, { baselineNodes: re('baseline-nodes'), candidateNodes: re('candidate-nodes'), from, to }) : null });
|
|
107
119
|
fs.appendFileSync(path.join(dir, 'verdicts.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), baseline: opt('baseline') || opt('results'), candidate: opt('candidate') || opt('results'), decision: r.decision, why: r.why, metrics: r.metrics, ...(r.prediction ? { prediction: r.prediction } : {}) }) + '\n');
|
|
@@ -200,5 +212,5 @@ export async function shadowCmd(store, cmd, rest, o) {
|
|
|
200
212
|
}
|
|
201
213
|
throw new Error('fleetops shadow canary start | advance | approve | status');
|
|
202
214
|
}
|
|
203
|
-
throw new Error('fleetops shadow demo | plan | replay | answers | compare | baseline save|list | watch | prom | serve | canary');
|
|
215
|
+
throw new Error('fleetops shadow demo | plan | replay | answers | quality | compare | baseline save|list | watch | prom | serve | canary');
|
|
204
216
|
}
|
package/fleetscope/build.mjs
CHANGED
|
@@ -13,6 +13,7 @@ const inlined = {
|
|
|
13
13
|
// the sizer's catalog and model: FleetScope's model list comes from the catalog, its KV per token from the model
|
|
14
14
|
'/*SIZERCATALOG*/': readFileSync(join(here, '../inference-sizer/src/catalog.js'), 'utf8'),
|
|
15
15
|
'/*SIZERMODEL*/': readFileSync(join(here, '../inference-sizer/src/model.js'), 'utf8'),
|
|
16
|
+
'/*SIZERSUGGEST*/': readFileSync(join(here, '../inference-sizer/src/suggest.js'), 'utf8'),
|
|
16
17
|
'/*ENGINE*/': read('src/engine.js'),
|
|
17
18
|
'/*TEMPLATES*/': read('src/templates.js'),
|
|
18
19
|
'/*INGEST*/': read('src/ingest.js'),
|
|
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
228
228
|
.mtx th:first-child, .mtx td:first-child { text-align: left; }
|
|
229
229
|
.mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
|
|
230
230
|
.kpi.wide { grid-column: span 2; cursor: pointer; }
|
|
231
|
+
.kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
|
232
|
+
.kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
|
233
|
+
.kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
|
|
231
234
|
.kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
232
235
|
.legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
|
|
233
236
|
.legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
|
|
@@ -614,6 +617,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
614
617
|
{ k: 'qHeads', label: 'Query heads', min: 1, max: 4096, int: true, required: true },
|
|
615
618
|
{ k: 'kvHeads', label: 'KV heads', min: 1, max: 4096, int: true, required: true },
|
|
616
619
|
{ k: 'headDim', label: 'Head dim', min: 8, max: 4096, int: true, required: true },
|
|
620
|
+
{ k: 'globalKvHeads', label: 'KV heads on full-attention layers', min: 0, max: 4096, int: true, hint: 'When full-attention layers differ from sliding-window ones (Gemma 4: num_global_key_value_heads). 0 = same as KV heads.' },
|
|
621
|
+
{ k: 'globalHeadDim', label: 'Head dim on full-attention layers', min: 0, max: 4096, int: true, hint: 'Gemma 4: global_head_dim. 0 = same as head dim.' },
|
|
622
|
+
{ k: 'kvShared', label: 'Keys and values share one tensor on full-attention layers (1 = yes)', min: 0, max: 1, int: true, hint: 'Gemma 4: attention_k_eq_v. Halves the KV those layers keep.' },
|
|
617
623
|
{ k: 'attn', type: 'enum', opts: ['gqa', 'mla'], label: 'Attention', required: true },
|
|
618
624
|
{ k: 'mlaLatent', label: 'MLA KV latent (kv_lora_rank)', min: 1, max: 1e5, int: true },
|
|
619
625
|
{ k: 'mlaRope', label: 'MLA RoPE dim', min: 0, max: 1e4, int: true },
|
|
@@ -660,14 +666,14 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
660
666
|
// ---- 2026 open-weight models (config.json values; see docs/CATALOG.md for where each figure comes from) ----
|
|
661
667
|
// Kimi K3 (K3.1 Pro shares the architecture): 69 Kimi Delta Attention layers (96 heads × 128 × 128 fp32 state) and
|
|
662
668
|
// 24 gated MLA layers; MXFP4 weights from quantization-aware training.
|
|
663
|
-
Object.assign({}, G, MLA, { id: 'kimi-k3', name: 'Kimi K3 / K3.1 Pro 2.8T-A104B (MoE, KDA + MLA)', total: 2800, active: 104, layers: 93, hidden: 7168, qHeads: 96, experts: 896, topk: 16, linFrac: 69 / 93, linStateMB: 6.29, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/moonshotai/Kimi-K3' }),
|
|
669
|
+
Object.assign({}, G, MLA, { id: 'kimi-k3', name: 'Kimi K3 / K3.1 Pro 2.8T-A104B (MoE, KDA + MLA)', total: 2800, active: 104, layers: 93, hidden: 7168, qHeads: 96, experts: 896, topk: 16, linFrac: 69 / 93, linStateMB: 6.29, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/moonshotai/Kimi-K3', alsoRepos: ['moonshotai/Kimi-K3.1-Pro'] }),
|
|
664
670
|
// Kimi K2.5 / K2.6: K2's shape with 256K context and native INT4 weights (sized as 4-bit)
|
|
665
671
|
Object.assign({}, G, MLA, { id: 'kimi-k26', name: 'Kimi K2.6 1T-A32B (MoE, MLA, INT4)', total: 1000, active: 32, layers: 61, hidden: 7168, qHeads: 64, experts: 384, topk: 8, maxCtx: 262144, wprec: 'fp4', source: 'https://huggingface.co/moonshotai/Kimi-K2.6' }),
|
|
666
672
|
// DeepSeek V4: one 512-wide latent per token, kept at 1/4 (CSA) or 1/128 (HCA) on alternating layers (≈ 0.129 on
|
|
667
673
|
// average); CSA attends its index top-1024, HCA all compressed blocks: modelled as 2048 attended tokens per query.
|
|
668
674
|
// Experts in FP4, the rest FP8.
|
|
669
|
-
Object.assign({}, G, MLA, { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro 1.6T-A49B (MoE, compressed sparse attention)', total: 1600, active: 49, layers: 61, hidden: 7168, qHeads: 128, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK:
|
|
670
|
-
Object.assign({}, G, MLA, { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash 284B-A13B (MoE, compressed sparse attention)', total: 284, active: 13, layers: 43, hidden: 4096, qHeads: 64, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK:
|
|
675
|
+
Object.assign({}, G, MLA, { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro 1.6T-A49B (MoE, compressed sparse attention)', total: 1600, active: 49, layers: 61, hidden: 7168, qHeads: 128, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK: 1024, experts: 384, topk: 6, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro' }),
|
|
676
|
+
Object.assign({}, G, MLA, { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash 284B-A13B (MoE, compressed sparse attention)', total: 284, active: 13, layers: 43, hidden: 4096, qHeads: 64, mlaLatent: 448, mlaRope: 64, mlaNope: 448, mlaV: 512, kvKeep: 0.129, sparseTopK: 512, experts: 256, topk: 6, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash' }),
|
|
671
677
|
// GLM-5.1 and GLM-5.3: MLA with DeepSeek-style sparse attention (index top-2048); GLM-5.3 extends the context to 1M.
|
|
672
678
|
// GLM-5.3's active parameters are not published: the GLM-5 lineage's 40B is assumed.
|
|
673
679
|
Object.assign({}, G, MLA, { id: 'glm-5.1', name: 'GLM-5.1 744B-A40B (MoE, MLA, sparse)', total: 744, active: 40, layers: 78, hidden: 6144, qHeads: 64, mlaNope: 192, mlaV: 256, sparseTopK: 2048, experts: 256, topk: 8, maxCtx: 202752, wprec: 'fp8', source: 'https://huggingface.co/zai-org/GLM-5.1' }),
|
|
@@ -678,15 +684,15 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
678
684
|
Object.assign({}, G, { id: 'qwen35-397b', name: 'Qwen3.5 397B-A17B (MoE, Gated DeltaNet hybrid)', total: 397, active: 17, layers: 60, hidden: 4096, qHeads: 32, kvHeads: 2, headDim: 256, linFrac: 0.75, linStateMB: 4.19, experts: 512, topk: 10, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3.5-397B-A17B' }),
|
|
679
685
|
Object.assign({}, G, { id: 'qwen38-27b', name: 'Qwen3.8 27B (Gated DeltaNet hybrid)', total: 27, active: 27, layers: 64, hidden: 5120, qHeads: 24, kvHeads: 4, headDim: 256, linFrac: 0.75, linStateMB: 3.15, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/Qwen/Qwen3.8-27B' }),
|
|
680
686
|
// MiniMax M3: sparse attention (16 blocks of 128 tokens) in 57 of 60 layers, modelled on all of them
|
|
681
|
-
Object.assign({}, G, { id: 'minimax-m3', name: 'MiniMax M3 428B-A23B (MoE, sparse)', total: 428, active: 23, layers: 60, hidden: 6144, qHeads: 64, kvHeads: 4, headDim: 128, sparseTopK: 2048, experts: 128, topk: 4, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/MiniMaxAI/MiniMax-M3' }),
|
|
687
|
+
Object.assign({}, G, { id: 'minimax-m3', name: 'MiniMax M3 428B-A23B (MoE, sparse)', total: 428, active: 23, layers: 60, hidden: 6144, qHeads: 64, kvHeads: 4, headDim: 128, sparseTopK: 2048, experts: 128, topk: 4, maxCtx: 1048576, wprec: 'fp8', source: 'https://huggingface.co/MiniMaxAI/MiniMax-M3', alsoRepos: ['MiniMaxAI/MiniMax-M3.1-Flash'] }),
|
|
682
688
|
Object.assign({}, G, { id: 'minimax-m27', name: 'MiniMax M2.7 229B-A10B (MoE)', total: 229, active: 10, layers: 62, hidden: 3072, qHeads: 48, kvHeads: 8, headDim: 128, experts: 256, topk: 8, maxCtx: 204800, wprec: 'fp8', source: 'https://huggingface.co/MiniMaxAI/MiniMax-M2.7' }),
|
|
683
689
|
// Muse Spark Open: 46 sliding-window layers (2048 tokens) and 16 full-attention layers
|
|
684
690
|
Object.assign({}, G, { id: 'muse-spark-open', name: 'Muse Spark Open 816B-A42B (MoE)', total: 816, active: 42, layers: 62, hidden: 8192, qHeads: 128, kvHeads: 16, headDim: 64, swaFrac: 46 / 62, swaWindow: 2048, experts: 256, topk: 8, maxCtx: 1048576, wprec: 'fp4', source: 'https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B' }),
|
|
685
691
|
// Gemma 4 31B: 50 sliding-window layers (1024 tokens) and 10 global layers with 4 KV heads of 512 and keys reused as
|
|
686
692
|
// values (the KV of 4 × 256 K+V pairs). The sliding layers' 16 heads are sized as 4: their KV is capped at 1024 tokens.
|
|
687
|
-
Object.assign({}, G, { id: 'gemma4-31b', name: 'Gemma 4 31B', total: 30.7, active: 30.7, layers: 60, hidden: 5376, qHeads: 32, kvHeads:
|
|
693
|
+
Object.assign({}, G, { id: 'gemma4-31b', name: 'Gemma 4 31B', total: 30.7, active: 30.7, layers: 60, hidden: 5376, qHeads: 32, kvHeads: 16, headDim: 256, globalKvHeads: 4, globalHeadDim: 512, kvShared: 1, swaFrac: 50 / 60, swaWindow: 1024, maxCtx: 262144, wprec: 'fp8', source: 'https://huggingface.co/google/gemma-4-31B' }),
|
|
688
694
|
];
|
|
689
|
-
const MODEL_DEFAULTS = { attn: 'gqa', experts: 0, topk: 0, swaFrac: 0, swaWindow: 0, linFrac: 0, linStateMB: 0, kvKeep: 1, sparseTopK: 0, mlaLatent: 512, mlaRope: 64, mlaNope: 128, mlaV: 128, wprec: 'fp8' };
|
|
695
|
+
const MODEL_DEFAULTS = { attn: 'gqa', globalKvHeads: 0, globalHeadDim: 0, kvShared: 0, experts: 0, topk: 0, swaFrac: 0, swaWindow: 0, linFrac: 0, linStateMB: 0, kvKeep: 1, sparseTopK: 0, mlaLatent: 512, mlaRope: 64, mlaNope: 128, mlaV: 128, wprec: 'fp8' };
|
|
690
696
|
const GPU_DEFAULTS = { tfFp8: 0, tfFp4: 0, nodeKW: 0, price: 0, vendor: '' };
|
|
691
697
|
|
|
692
698
|
// ---------- validation ----------
|
|
@@ -787,6 +793,22 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
787
793
|
const mlaLatent = mla ? +c.kv_lora_rank : 512, mlaRope = mla ? +first(c, ['qk_rope_head_dim'], 64) : 64;
|
|
788
794
|
const mlaNope = mla ? +first(c, ['qk_nope_head_dim'], 128) : 128, mlaV = mla ? +first(c, ['v_head_dim'], 128) : 128;
|
|
789
795
|
if (mla) kvHeads = 1;
|
|
796
|
+
// Gemma 4: full-attention layers have their own KV shape (num_global_key_value_heads, global_head_dim), and with
|
|
797
|
+
// attention_k_eq_v keys and values share one tensor there
|
|
798
|
+
const globalKvHeads = c.num_global_key_value_heads != null ? +c.num_global_key_value_heads : 0;
|
|
799
|
+
const globalHeadDim = globalKvHeads && c.global_head_dim != null ? +c.global_head_dim : 0;
|
|
800
|
+
const kvShared = globalKvHeads && c.attention_k_eq_v === true ? 1 : 0;
|
|
801
|
+
if (globalKvHeads) notes.push(`Full-attention layers: ${globalKvHeads} KV heads of ${globalHeadDim || headDim}${kvShared ? ', keys and values in one tensor' : ''}; sliding-window layers: ${kvHeads} of ${headDim}.`);
|
|
802
|
+
// DeepSeek V4 compressed attention: one shared KV head (head_dim, of which qk_rope_head_dim is RoPE) per layer, kept
|
|
803
|
+
// for 1 in compress_ratios[layer] tokens. Sized like MLA: a latent of head_dim − rope plus the rope part per kept token.
|
|
804
|
+
let csa = false, kvKeep = 1;
|
|
805
|
+
if (!mla && kvHeads === 1 && Array.isArray(c.compress_ratios) && /^deepseek_v4$/.test(String(c.model_type || ''))) {
|
|
806
|
+
csa = true;
|
|
807
|
+
const r = c.compress_ratios.map(Number);
|
|
808
|
+
kvKeep = +(r.reduce((a, x) => a + (x > 0 ? 1 / x : 1), 0) / r.length).toFixed(4);
|
|
809
|
+
notes.push(`Compressed attention: KV kept for ${(kvKeep * 100).toFixed(1)}% of tokens on average (layers with ratio 0 counted as uncompressed); the ${c.sliding_window || 0}-token window each layer also keeps is not added.`);
|
|
810
|
+
} else if (Array.isArray(c.compress_ratios)) notes.push(`compress_ratios is set but this importer reads it only for DeepSeek V4 (model_type ${c.model_type}); KV is sized without compression.`);
|
|
811
|
+
const ropeD = +first(c, ['qk_rope_head_dim'], 64);
|
|
790
812
|
// sliding window
|
|
791
813
|
let swaFrac = 0, swaWindow = 0;
|
|
792
814
|
if (Array.isArray(c.layer_types) && c.sliding_window) {
|
|
@@ -798,7 +820,7 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
798
820
|
swaFrac = +(n / c.no_rope_layers.length).toFixed(3); swaWindow = +c.attention_chunk_size;
|
|
799
821
|
notes.push('Chunked-attention layers modelled as sliding-window layers.');
|
|
800
822
|
}
|
|
801
|
-
if (c.sliding_window && !swaFrac) notes.push('sliding_window is set but not enabled for these layers; KV is sized for full attention.');
|
|
823
|
+
if (c.sliding_window && !swaFrac && !csa) notes.push('sliding_window is set but not enabled for these layers; KV is sized for full attention.');
|
|
802
824
|
// linear-attention layers (Qwen3-Next / Qwen3.5 Gated DeltaNet: layer_types "linear_attention" or full_attention_interval)
|
|
803
825
|
let linFrac = 0, linStateMB = 0;
|
|
804
826
|
const linN = Array.isArray(c.layer_types) ? c.layer_types.filter(t => /linear/i.test(String(t))).length
|
|
@@ -810,7 +832,8 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
810
832
|
notes.push(`${linN} linear-attention layers: a ${linStateMB} MB state per layer per sequence (fp32), no KV per token.`);
|
|
811
833
|
}
|
|
812
834
|
// sparse attention: an index picks the tokens each query attends (DeepSeek Sparse Attention and its descendants)
|
|
813
|
-
|
|
835
|
+
// MiniMax M3: block-sparse, sparse_topk_blocks blocks of sparse_block_size tokens
|
|
836
|
+
const sparseTopK = c.index_topk ? +c.index_topk : c.use_sparse_attention && c.sparse_topk_blocks ? +c.sparse_topk_blocks * +first(c, ['sparse_block_size'], 128) : 0;
|
|
814
837
|
if (sparseTopK) notes.push(`Sparse attention: each query attends ${sparseTopK} selected tokens.`);
|
|
815
838
|
// context
|
|
816
839
|
let maxCtx = +first(c, ['max_position_embeddings', 'n_positions', 'seq_length', 'max_sequence_length'], 4096);
|
|
@@ -826,7 +849,11 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
826
849
|
const denseLayers = layers - moeLayers;
|
|
827
850
|
// attention params per layer
|
|
828
851
|
let attnP;
|
|
829
|
-
if (
|
|
852
|
+
if (csa) {
|
|
853
|
+
const qP = c.q_lora_rank ? hidden * c.q_lora_rank + c.q_lora_rank * qHeads * headDim : hidden * qHeads * headDim;
|
|
854
|
+
const oP = c.o_lora_rank ? qHeads * headDim * c.o_lora_rank + c.o_lora_rank * hidden : qHeads * headDim * hidden;
|
|
855
|
+
attnP = qP + hidden * headDim + oP;
|
|
856
|
+
} else if (mla) {
|
|
830
857
|
const qk = mlaNope + mlaRope;
|
|
831
858
|
const qP = c.q_lora_rank ? hidden * c.q_lora_rank + c.q_lora_rank * qHeads * qk : hidden * qHeads * qk;
|
|
832
859
|
attnP = qP + hidden * (mlaLatent + mlaRope) + mlaLatent * qHeads * (mlaNope + mlaV) + qHeads * mlaV * hidden;
|
|
@@ -846,7 +873,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
846
873
|
const name = String(first(j, ['_name_or_path', 'name_or_path'], '') || '').split('/').pop() || (c.model_type ? c.model_type + ' ' + (total / 1e9).toFixed(0) + 'B' : 'Imported model');
|
|
847
874
|
const model = {
|
|
848
875
|
name, total: +(total / 1e9).toFixed(2), active: +(active / 1e9).toFixed(2), layers, hidden, qHeads, kvHeads, headDim,
|
|
849
|
-
attn: mla ? 'mla' : 'gqa',
|
|
876
|
+
attn: mla || csa ? 'mla' : 'gqa',
|
|
877
|
+
mlaLatent: csa ? headDim - ropeD : mlaLatent, mlaRope: csa ? ropeD : mlaRope, mlaNope: csa ? headDim - ropeD : mlaNope, mlaV: csa ? headDim : mlaV,
|
|
878
|
+
globalKvHeads, globalHeadDim, kvShared, kvKeep, experts, topk, swaFrac, swaWindow, linFrac, linStateMB, sparseTopK, maxCtx,
|
|
850
879
|
wprec: /fp8|float8/i.test(JSON.stringify(j.quantization_config || '')) ? 'fp8' : /mxfp4|nvfp4|fp4/i.test(JSON.stringify(j.quantization_config || '')) ? 'fp4' : 'fp8',
|
|
851
880
|
};
|
|
852
881
|
return { model, notes };
|
|
@@ -898,7 +927,10 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
898
927
|
bpp, kvb, isMoE, mla, computeFallback,
|
|
899
928
|
Wd: dense * 1e9 * bpp, We: Eall * 1e9 * bpp,
|
|
900
929
|
denseP: dense * 1e9, activeP: (isMoE ? s.active : s.total) * 1e9,
|
|
901
|
-
|
|
930
|
+
// KV elements per token per layer: full-attention layers may have their own shape (Gemma 4), sliding-window layers
|
|
931
|
+
// use kvHeads × headDim
|
|
932
|
+
kvTokLayer: mla ? (lat + rope) * kvb : (s.kvShared ? 1 : 2) * (s.globalKvHeads || s.kvHeads) * (s.globalHeadDim || s.headDim) * kvb,
|
|
933
|
+
kvTokSwa: mla ? (lat + rope) * kvb : 2 * s.kvHeads * s.headDim * kvb,
|
|
902
934
|
swaLayers, linLayers, fullLayers: s.layers - swaLayers - linLayers, win: s.swaWindow || 0, keep, topK, linState,
|
|
903
935
|
// FLOPs per token per linear-attention layer: read and update the state (fp32, 4 bytes an element), ~4 FLOPs an element
|
|
904
936
|
Alin: (s.linStateMB || 0) * 1e6,
|
|
@@ -916,7 +948,7 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
916
948
|
// the last W, linear-attention layers a fixed state
|
|
917
949
|
function kvBytes(md, L) {
|
|
918
950
|
const w = md.win || L, keep = md.keep || 1;
|
|
919
|
-
return md.kvTokLayer *
|
|
951
|
+
return md.kvTokLayer * md.fullLayers * L * keep + (md.kvTokSwa != null ? md.kvTokSwa : md.kvTokLayer) * md.swaLayers * Math.min(L, w) + (md.linState || 0);
|
|
920
952
|
}
|
|
921
953
|
// context tokens one query attends in a full-attention layer, and its integral over query positions 0..x
|
|
922
954
|
const attended = (md, L) => { const n = L * (md.keep || 1); return md.topK ? Math.min(n, md.topK) : n; };
|
|
@@ -1174,14 +1206,17 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
1174
1206
|
// returns TPOT, TTFT, and output tokens/s per GPU.
|
|
1175
1207
|
function operatingPoint(s, md, c, B) {
|
|
1176
1208
|
const st = decodeStep(s, md, c, B), ps = prefillStats(s, md, c), osl = s.avgOut, isl = Math.min(s.avgIn, s.ctx);
|
|
1209
|
+
// a prefix-cache hit skips that part of the prompt: only the new tokens are prefilled, attending to the cached ones
|
|
1210
|
+
// (as sizeAgg and prefillStats count them; ps.cap is in new tokens per second)
|
|
1211
|
+
const hit = Math.min(0.99, Math.max(0, (s.prefixHit || 0) / 100)), Lnew = Math.max(1, isl * (1 - hit)), Lc = isl - Lnew;
|
|
1177
1212
|
let tpot = st.t, ttft = ps.Sbatch, fp = 0;
|
|
1178
1213
|
for (let i = 0; i < 50; i++) {
|
|
1179
1214
|
const lam = B / (osl * tpot + ttft); // requests/s through this instance
|
|
1180
|
-
fp = Math.min(0.95, lam *
|
|
1215
|
+
fp = Math.min(0.95, lam * Lnew / ps.cap); // share of compute spent on prefill
|
|
1181
1216
|
const t = Math.max(st.tm, st.tc / (1 - fp)) * 1.1 + st.comm + st.ovh;
|
|
1182
1217
|
// a new prompt is prefilled in chunks between decode steps: its share of each step is what decode leaves
|
|
1183
1218
|
const free = Math.max(0.05, 1 - Math.max(st.tm, st.tc) / t);
|
|
1184
|
-
const tt = prefillTime(s, md, c,
|
|
1219
|
+
const tt = prefillTime(s, md, c, Lnew, Lc, 1) / free + mdWait(Math.min(0.85, fp), Lnew / ps.cap) + t;
|
|
1185
1220
|
if (Math.abs(t - tpot) < 1e-7 && Math.abs(tt - ttft) < 1e-6) { tpot = t; ttft = tt; break; }
|
|
1186
1221
|
tpot = t; ttft = tt;
|
|
1187
1222
|
}
|
|
@@ -1257,6 +1292,79 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
1257
1292
|
if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerModel = api;
|
|
1258
1293
|
})(this);
|
|
1259
1294
|
|
|
1295
|
+
</script>
|
|
1296
|
+
<script>
|
|
1297
|
+
/* Suggestions for the Inference Sizer and FleetScope pages: the changes that would change the answer, shown next to it.
|
|
1298
|
+
forSizer re-plans the same request with one change at a time (weight and KV precision, speculative decoding, prefix
|
|
1299
|
+
caching, a shorter context) and keeps the ones that need fewer GPUs. forFleet reads a FleetScope run's first
|
|
1300
|
+
bottleneck and cache numbers and proposes what-ifs the page's Ask box can run in one click.
|
|
1301
|
+
Both are models: `aiinfra assess` on real traces, then fleetops shadow, check them. */
|
|
1302
|
+
(function (root) {
|
|
1303
|
+
'use strict';
|
|
1304
|
+
// speculative decoding: k drafted tokens verified in one step, E accepted per step at acceptance a. A memory-bound
|
|
1305
|
+
// step barely grows with k+1 tokens; a compute-bound one grows with them (same model as harness-ledger advise).
|
|
1306
|
+
function specFactor(st, opt) {
|
|
1307
|
+
const a = (opt && opt.accept) || 0.7, k = (opt && opt.tokens) || 3;
|
|
1308
|
+
const E = (1 - Math.pow(a, k + 1)) / (1 - a), base = Math.max(st.tm, st.tc) + st.comm + st.ovh;
|
|
1309
|
+
const t = Math.max(st.tm * 1.05, st.tc * (k + 1)) + st.comm + st.ovh + 0.05 * Math.max(st.tm, st.tc);
|
|
1310
|
+
return { E: E, factor: t / E / base };
|
|
1311
|
+
}
|
|
1312
|
+
const HOURS = 730;
|
|
1313
|
+
const gpusOf = r => (r && r.chosen ? r.chosen.provGPUs : null);
|
|
1314
|
+
|
|
1315
|
+
function forSizer(s, r, M) {
|
|
1316
|
+
const base = gpusOf(r), out = [];
|
|
1317
|
+
const tryIt = (id, title, patch, extra) => {
|
|
1318
|
+
let r2; try { r2 = M.plan(Object.assign({}, s, patch), { noSens: true }); } catch (e) { return; }
|
|
1319
|
+
const g = gpusOf(r2);
|
|
1320
|
+
if (g == null || (base != null && g >= base)) return;
|
|
1321
|
+
out.push(Object.assign({ id: id, title: title, before: base, after: g, saved: base != null ? base - g : null,
|
|
1322
|
+
costBefore: base != null && s.price ? base * s.price * HOURS : null, costAfter: s.price ? g * s.price * HOURS : null }, extra));
|
|
1323
|
+
};
|
|
1324
|
+
const wprec = s.wprec || 'bf16';
|
|
1325
|
+
if (wprec === 'bf16' && s.tfFp8) tryIt('fp8-weights', 'FP8 weights', { wprec: 'fp8' }, { risk: 'quality', how: 'vLLM --quantization fp8, or an FP8 checkpoint' });
|
|
1326
|
+
if (wprec !== 'fp4' && s.tfFp4) tryIt('fp4-weights', 'FP4 weights (NVFP4/MXFP4)', { wprec: 'fp4' }, { risk: 'quality', how: 'an NVFP4 or MXFP4 checkpoint' });
|
|
1327
|
+
if (s.kvprec === 'bf16') tryIt('fp8-kv', 'FP8 KV cache', { kvprec: 'fp8' }, { risk: 'quality', how: 'vLLM --kv-cache-dtype fp8' });
|
|
1328
|
+
// speculative decoding on the layout the plan chose, at its operating batch
|
|
1329
|
+
const best = r && r.agg && r.agg.best;
|
|
1330
|
+
if (best && best.c && best.Bop) {
|
|
1331
|
+
try {
|
|
1332
|
+
const md = M.derive(s), st = M.decodeStep(s, md, best.c, Math.max(1, Math.round(best.Bop / (best.c.pp || 1)))), sf = specFactor(st);
|
|
1333
|
+
if (sf.factor < 0.95) tryIt('spec-decode', 'Speculative decoding (3 drafted tokens, 70% acceptance assumed)', { tpot: s.tpot / sf.factor },
|
|
1334
|
+
{ risk: 'none', how: 'vLLM --speculative-config (MTP heads where the model has them, else a draft model)', note: `about ${Math.round(100 * (1 - sf.factor))}% faster tokens at this batch` });
|
|
1335
|
+
} catch (e) { /* layout without a decode step: skip */ }
|
|
1336
|
+
}
|
|
1337
|
+
if ((s.prefixHit || 0) < 50 && s.avgIn >= 2000) tryIt('prefix-cache', 'Half of each prompt served from the prefix cache (shared system prompts, agent sessions)', { prefixHit: 50 },
|
|
1338
|
+
{ risk: 'none', how: 'stable prompt prefixes, prefix caching on, prefix-aware routing', note: 'measure your real hit rate: aiinfra assess traces/' });
|
|
1339
|
+
const need = (s.peakIn || 0) + (s.peakOut || 0);
|
|
1340
|
+
if (need > 0 && s.ctx > 2 * need) { let c = 4096; while (c < need * 1.25) c *= 2; if (c < s.ctx) tryIt('context', `Serve a ${c >= 1024 ? Math.round(c / 1024) + 'K' : c} context instead of ${Math.round(s.ctx / 1024)}K (your peak request is ${Math.round(need / 1024)}K)`, { ctx: c }, { risk: 'none', how: 'vLLM --max-model-len' }); }
|
|
1341
|
+
return out.sort((a, b) => (b.saved || 0) - (a.saved || 0));
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// FleetScope: from a run's summary (first bottleneck, cache locality, speculative decoding) to what-ifs for its Ask box.
|
|
1345
|
+
// Titles are short (the tile sits next to the bottleneck, which names the pool); the Ask phrase names it.
|
|
1346
|
+
function forFleet(sum) {
|
|
1347
|
+
const out = [], bf = sum && sum.bottleneck && sum.bottleneck.first, add = (id, title, why, ask) => out.push({ id: id, title: title, why: why, ask: ask || null });
|
|
1348
|
+
if (bf) {
|
|
1349
|
+
const nm = bf.name;
|
|
1350
|
+
if (bf.kind === 'kv') { add('kv-routing', 'Route sessions to the replica that holds their prefix', `${nm}: KV cache full; reuse cuts what each session holds`, 'Turn on KV-aware routing'); add('kv-more', 'Add 2 instances', 'more KV memory in total', `Add 2 instances to ${nm}`); }
|
|
1351
|
+
if (bf.kind === 'compute') { add('compute-more', 'Add 2 instances', `${nm}: compute saturated`, `Add 2 instances to ${nm}`); add('compute-gpu', 'Move to B200', 'more FLOPS per instance', `What if ${nm} moves to B200?`); }
|
|
1352
|
+
if (bf.kind === 'tpot') { add('tpot-spec', 'Speculative decoding', `${nm}: decode batches too large for the TPOT target`, 'Turn on speculative decoding'); add('tpot-more', 'Add 2 instances', 'smaller decode batches each', `Add 2 instances to ${nm}`); }
|
|
1353
|
+
if (bf.kind === 'queue') add('queue-more', 'Add 2 instances', `${nm}: requests queue`, `Add 2 instances to ${nm}`);
|
|
1354
|
+
if (bf.kind === 'cold') add('cold-warm', 'Keep warm capacity', 'requests wait on cold starts: a higher minimum, or weights cached on local NVMe', null);
|
|
1355
|
+
if (bf.kind === 'link' || bf.kind === 'linkdown') add('link', 'Relieve the link', 'link saturated: send less traffic across it, or raise its bandwidth', null);
|
|
1356
|
+
if (bf.kind === 'down') add('down', 'Capacity for the outage', `${nm} lost instances: spare instances elsewhere carry it`, null);
|
|
1357
|
+
}
|
|
1358
|
+
const loc = sum && sum.locality;
|
|
1359
|
+
if (loc && (loc.misses || loc.hits) && loc.cachedShare < 0.5 && !out.some(x => x.id === 'kv-routing')) add('cache-routing', 'Route sessions to the replica that holds their prefix', `only ${Math.round(100 * loc.cachedShare)}% of prompt tokens came from cache`, 'Turn on KV-aware routing');
|
|
1360
|
+
if (!sum || !sum.spec) { if (bf && bf.kind !== 'tpot' && sum && sum.tpotP99 && !out.some(x => x.id === 'tpot-spec')) add('spec', 'Speculative decoding', 'faster tokens at the same GPUs', 'Turn on speculative decoding'); }
|
|
1361
|
+
return out.slice(0, 4);
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
const api = { forSizer: forSizer, forFleet: forFleet, specFactor: specFactor };
|
|
1365
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerSuggest = api;
|
|
1366
|
+
})(this);
|
|
1367
|
+
|
|
1260
1368
|
</script>
|
|
1261
1369
|
<script>
|
|
1262
1370
|
/* FleetScope engine: time-stepped fleet simulation for LLM serving and training.
|
|
@@ -1314,7 +1422,7 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
1314
1422
|
if (CAT && SZ) {
|
|
1315
1423
|
for (const c of CAT.MODELS) {
|
|
1316
1424
|
if (IN_LIST[c.id] || MODELS[c.id]) continue;
|
|
1317
|
-
const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : c.kvHeads, headDim: c.attn === 'mla' ? 0 : c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
|
|
1425
|
+
const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : (c.globalKvHeads || c.kvHeads) * (c.kvShared ? 0.5 : 1), headDim: c.attn === 'mla' ? 0 : c.globalHeadDim || c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
|
|
1318
1426
|
const md = SZ.derive(Object.assign({}, SZ.SETTINGS, CAT.MODEL_DEFAULTS, c, { kvprec: 'fp8', tfBf16: 1, hbmTBs: 1, scaleUpGBs: 1, nicGbps: 1, hbmGB: 1 }));
|
|
1319
1427
|
m.kvScale = +(SZ.kvBytes(md, 32768) / 32768 / kvDimTotal(m)).toFixed(4);
|
|
1320
1428
|
MODELS[c.id] = m;
|
|
@@ -4921,9 +5029,19 @@ function renderKpis() {
|
|
|
4921
5029
|
t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
|
|
4922
5030
|
t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
|
|
4923
5031
|
}
|
|
5032
|
+
// what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
|
|
5033
|
+
if (s.requests && window.SizerSuggest) {
|
|
5034
|
+
const tries = SizerSuggest.forFleet(s);
|
|
5035
|
+
if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
|
|
5036
|
+
? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
|
|
5037
|
+
: '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
|
|
5038
|
+
}
|
|
4924
5039
|
$('#kpis').innerHTML = tiles.join('');
|
|
4925
5040
|
}
|
|
4926
|
-
$('#kpis').addEventListener('click', e => {
|
|
5041
|
+
$('#kpis').addEventListener('click', e => {
|
|
5042
|
+
const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
|
|
5043
|
+
const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
|
|
5044
|
+
});
|
|
4927
5045
|
|
|
4928
5046
|
// ---------- charts ----------
|
|
4929
5047
|
const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };
|
package/fleetscope/package.json
CHANGED
package/fleetscope/src/engine.js
CHANGED
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
if (CAT && SZ) {
|
|
54
54
|
for (const c of CAT.MODELS) {
|
|
55
55
|
if (IN_LIST[c.id] || MODELS[c.id]) continue;
|
|
56
|
-
const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : c.kvHeads, headDim: c.attn === 'mla' ? 0 : c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
|
|
56
|
+
const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : (c.globalKvHeads || c.kvHeads) * (c.kvShared ? 0.5 : 1), headDim: c.attn === 'mla' ? 0 : c.globalHeadDim || c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
|
|
57
57
|
const md = SZ.derive(Object.assign({}, SZ.SETTINGS, CAT.MODEL_DEFAULTS, c, { kvprec: 'fp8', tfBf16: 1, hbmTBs: 1, scaleUpGBs: 1, nicGbps: 1, hbmGB: 1 }));
|
|
58
58
|
m.kvScale = +(SZ.kvBytes(md, 32768) / 32768 / kvDimTotal(m)).toFixed(4);
|
|
59
59
|
MODELS[c.id] = m;
|
|
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
228
228
|
.mtx th:first-child, .mtx td:first-child { text-align: left; }
|
|
229
229
|
.mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
|
|
230
230
|
.kpi.wide { grid-column: span 2; cursor: pointer; }
|
|
231
|
+
.kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
|
232
|
+
.kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
|
233
|
+
.kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
|
|
231
234
|
.kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
232
235
|
.legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
|
|
233
236
|
.legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
|
|
@@ -394,6 +397,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
394
397
|
/*SIZERMODEL*/
|
|
395
398
|
</script>
|
|
396
399
|
<script>
|
|
400
|
+
/*SIZERSUGGEST*/
|
|
401
|
+
</script>
|
|
402
|
+
<script>
|
|
397
403
|
/*ENGINE*/
|
|
398
404
|
</script>
|
|
399
405
|
<script>
|
|
@@ -1684,9 +1690,19 @@ function renderKpis() {
|
|
|
1684
1690
|
t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
|
|
1685
1691
|
t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
|
|
1686
1692
|
}
|
|
1693
|
+
// what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
|
|
1694
|
+
if (s.requests && window.SizerSuggest) {
|
|
1695
|
+
const tries = SizerSuggest.forFleet(s);
|
|
1696
|
+
if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
|
|
1697
|
+
? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
|
|
1698
|
+
: '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
|
|
1699
|
+
}
|
|
1687
1700
|
$('#kpis').innerHTML = tiles.join('');
|
|
1688
1701
|
}
|
|
1689
|
-
$('#kpis').addEventListener('click', e => {
|
|
1702
|
+
$('#kpis').addEventListener('click', e => {
|
|
1703
|
+
const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
|
|
1704
|
+
const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
|
|
1705
|
+
});
|
|
1690
1706
|
|
|
1691
1707
|
// ---------- charts ----------
|
|
1692
1708
|
const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };
|
package/gpu-health/package.json
CHANGED
package/gpu-ledger/package.json
CHANGED
package/harness-ledger/README.md
CHANGED
|
@@ -120,6 +120,54 @@ On TraceLab's workload, with SWE-bench success rates ([VALIDATION-ECONOMICS.md](
|
|
|
120
120
|
- **Pooled teams:** at $3 a GPU-hour on B200 it wins from about 8–16× that volume.
|
|
121
121
|
- **Context:** half the calls exceed those models' 128k context.
|
|
122
122
|
|
|
123
|
+
## Assess, doctor, optimize
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
harness-ledger assess traces/ [--requests gateway.jsonl] [--engine-metrics http://vllm:8000] # all three below, one report
|
|
127
|
+
harness-ledger profile traces/ --critical 'harness:payments-*' # classes, token ratios, what bounds each
|
|
128
|
+
harness-ledger doctor traces/ --requests gateway.jsonl # why the prefix cache misses, and what to change
|
|
129
|
+
harness-ledger advise traces/ --goal ttft [--model deepseek-v3 --gpu H200 --gpus 64] [--apply IDS] [--fail-if 'ttft>+5%']
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- **The profile** puts each session in one of five classes: critical, realtime, agentic, reasoning or batch. For each
|
|
133
|
+
class it reports input:output tokens, the share read from cache, fresh tokens per output token, context and output
|
|
134
|
+
percentiles and pauses past the cache lifetime, and from those, whether prefill, decode or the KV cache bounds it.
|
|
135
|
+
- **The doctor** compares the hit rate now with what the same calls could reach. With request bodies, it names the
|
|
136
|
+
first point where each request stops matching the previous one and why (a timestamp in the system prompt, reordered
|
|
137
|
+
tools, JSON key order and so on), keeping only hashes and positions. With the engine's metrics, it gives the
|
|
138
|
+
server-side hit rate against what the traces could reuse.
|
|
139
|
+
- **The optimizer** prices every change across the stack that moves the goal. On an API, each change is measured on
|
|
140
|
+
the recorded calls changed as the change would change them. Self-hosted, it also uses the Inference Sizer's operating
|
|
141
|
+
point. It gives the best combination, the best at no extra cost and the best with no quality risk, then a dry run of
|
|
142
|
+
the ones you pick.
|
|
143
|
+
|
|
144
|
+
See [docs/OPTIMIZE.md](../docs/OPTIMIZE.md).
|
|
145
|
+
|
|
146
|
+
## Suggestions, prompt lint, and where they show up
|
|
147
|
+
|
|
148
|
+
```
|
|
149
|
+
harness-ledger suggest traces/ [--watch 3600 --since 24h] [--store DIR] [--slack URL|--lark URL] [--langfuse] [--live]
|
|
150
|
+
harness-ledger suggest list | accept ID | dismiss ID | snooze ID --for 2w | reopen ID
|
|
151
|
+
harness-ledger lint prompts/ [--md] [--fail] # a per-call value before static text, in a template
|
|
152
|
+
harness-ledger mooncake trace.jsonl --sim-replicas 8 # prefix reuse by cache size; random vs prefix routing
|
|
153
|
+
harness-ledger mooncake --requests gateway.jsonl --out trace.jsonl # your traffic as a Mooncake trace, no text
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`suggest` raises each change once, again only if it grows by half, and remembers what people decided. It also feeds:
|
|
157
|
+
|
|
158
|
+
- the Claude Code hook and status line (`integrations/claude-code/`);
|
|
159
|
+
- the LiteLLM prefix linter (`integrations/litellm/`);
|
|
160
|
+
- the Grafana panel, through a fleetops store;
|
|
161
|
+
- Slack and Lark/Feishu cards;
|
|
162
|
+
- comments on Langfuse sessions.
|
|
163
|
+
|
|
164
|
+
Two more input formats are detected:
|
|
165
|
+
|
|
166
|
+
- **`trajectory`:** agent runs with full message lists, such as SWE-agent or OpenHands datasets exported to JSON lines.
|
|
167
|
+
- **`mooncake`:** serving traces with chained block hashes.
|
|
168
|
+
|
|
169
|
+
See [docs/SUGGEST.md](../docs/SUGGEST.md).
|
|
170
|
+
|
|
123
171
|
## On real data
|
|
124
172
|
|
|
125
173
|
- **Real coding-agent use** ([VALIDATION-TRACELAB.md](docs/VALIDATION-TRACELAB.md)). On TraceLab (8,058 Claude Code
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Integrations
|
|
2
|
+
|
|
3
|
+
Where harness-ledger's findings show up without anyone running a report. See [docs/SUGGEST.md](../../docs/SUGGEST.md).
|
|
4
|
+
|
|
5
|
+
| Folder | What | Set up |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| [claude-code/](claude-code/) | Hooks that show cache misses and tool-output waste in Claude Code (last session at start, live warnings after a response), and a status line with the live cache hit rate | `aiinfra claude-code-hook --print-settings` → `~/.claude/settings.json` |
|
|
8
|
+
| [litellm/](litellm/) | A LiteLLM proxy callback that reports each request that breaks its session's prompt prefix, and why (Prometheus counters, one log line per template and cause) | `callbacks: aiinfra_prefix_lint.proxy_handler_instance` in the proxy's `litellm_settings` |
|
|
9
|
+
|
|
10
|
+
Both read only what passes through them, keep counts and hashes (no prompt text), and never block or change a session
|
|
11
|
+
or a request.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A Claude Code hook: tells you, in Claude Code, when a session wasted tokens on the prompt cache or on oversized tool
|
|
3
|
+
// output, at the moment you can still do something about it. It reads only the session's own transcript, on your
|
|
4
|
+
// machine, and keeps counts (no prompt or tool text) in ~/.aiinfra/claude-code/ (or $AIINFRA_STATE/claude-code/).
|
|
5
|
+
//
|
|
6
|
+
// SessionEnd analyzes the finished session and keeps a one-line summary
|
|
7
|
+
// SessionStart shows the previous session's summary once, if it found something worth changing
|
|
8
|
+
// Stop (optional; run it async) after each response, warns once per session per problem as it happens:
|
|
9
|
+
// a cache miss that re-sent a large context, a pause that let the cache expire, a huge tool result
|
|
10
|
+
// The message is a hook systemMessage, shown to you, not added to Claude's context.
|
|
11
|
+
//
|
|
12
|
+
// Settings (~/.claude/settings.json or .claude/settings.json): node aiinfra-hook.mjs --print-settings
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
import { claudeCode } from '../../src/importers.mjs';
|
|
18
|
+
import { ledger } from '../../src/ledger.mjs';
|
|
19
|
+
|
|
20
|
+
const HERE = fileURLToPath(import.meta.url);
|
|
21
|
+
export const THRESHOLDS = { missTokens: 50000, bigResult: 20000, minWasteShare: 0.15, minTokens: 100000 };
|
|
22
|
+
export const stateDir = () => path.join(process.env.AIINFRA_STATE || path.join(os.homedir(), '.aiinfra'), 'claude-code');
|
|
23
|
+
const n = v => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
|
|
24
|
+
|
|
25
|
+
// one transcript (and its subagents' transcripts beside it) → what went to waste
|
|
26
|
+
export function analyze(transcriptPath, { cacheTtlS = 300 } = {}) {
|
|
27
|
+
const files = [transcriptPath], sub = path.join(path.dirname(transcriptPath), path.basename(transcriptPath, '.jsonl'), 'subagents');
|
|
28
|
+
if (fs.existsSync(sub)) for (const f of fs.readdirSync(sub)) if (f.endsWith('.jsonl')) files.push(path.join(sub, f));
|
|
29
|
+
const calls = files.flatMap(f => { try { return claudeCode(fs.readFileSync(f, 'utf8'), { file: f }); } catch { return []; } });
|
|
30
|
+
if (!calls.length) return null;
|
|
31
|
+
const r = ledger(calls, { cacheTtlS }), T = r.report.totals;
|
|
32
|
+
const by = c => r.findings.filter(f => f.cause === c);
|
|
33
|
+
const sum = (xs, k) => xs.reduce((a, x) => a + (x[k] || 0), 0);
|
|
34
|
+
const miss = by('cache-miss'), exp = by('cache-expired'), bloat = by('tool-output-bloat');
|
|
35
|
+
const tools = {}; for (const f of bloat) tools[f.tool] = (tools[f.tool] || 0) + f.tokens;
|
|
36
|
+
return { session: calls[0].session, calls: calls.length, input: T.input, cacheRead: T.cacheRead, hit: T.input ? T.cacheRead / T.input : null, cost: T.cost,
|
|
37
|
+
missed: { count: miss.length, tokens: sum(miss, 'tokens'), cost: sum(miss, 'cost') }, expired: { count: exp.length, tokens: sum(exp, 'tokens'), cost: sum(exp, 'cost') },
|
|
38
|
+
bloat: { count: bloat.length, tokens: sum(bloat, 'tokens'), cost: sum(bloat, 'cost'), tools }, avoidable: T.avoidableTokens || 0, avoidableCost: T.avoidableCost || 0,
|
|
39
|
+
lastCallT: calls.reduce((a, c) => Math.max(a, c.t || 0), 0), findings: r.findings.map(f => ({ cause: f.cause, at: f.at, tokens: f.tokens, tool: f.tool })) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// the summary worth showing, or null when the session was fine
|
|
43
|
+
export function message(A, { thresholds = THRESHOLDS, prefix = 'aiinfra', transcript = null } = {}) {
|
|
44
|
+
if (!A || A.input < thresholds.minTokens) return null;
|
|
45
|
+
const parts = [];
|
|
46
|
+
if (A.missed.tokens >= thresholds.missTokens) parts.push(`${n(A.missed.tokens)} tokens re-sent after ${A.missed.count} cache miss${A.missed.count === 1 ? '' : 'es'} (the prompt prefix changed)`);
|
|
47
|
+
if (A.expired.tokens >= thresholds.missTokens) parts.push(`${n(A.expired.tokens)} re-sent after ${A.expired.count} pause${A.expired.count === 1 ? '' : 's'} past the cache lifetime`);
|
|
48
|
+
const top = Object.entries(A.bloat.tools).sort((a, b) => b[1] - a[1])[0];
|
|
49
|
+
if (top && A.bloat.tokens >= thresholds.bigResult) parts.push(`${n(A.bloat.tokens)} from oversized tool output (mostly ${top[0]})`);
|
|
50
|
+
if (!parts.length || A.avoidable / A.input < thresholds.minWasteShare && A.missed.tokens < thresholds.missTokens * 4) return null;
|
|
51
|
+
return `${prefix}: ${Math.round(100 * (A.hit ?? 0))}% of input came from cache; ${parts.join('; ')}.` + (A.avoidableCost ? ` About $${A.avoidableCost.toFixed(2)} avoidable.` : '') + ` Details: aiinfra harness-ledger doctor ${transcript ? JSON.stringify(transcript) : '<transcript>'}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Stop: problems that appeared since the last check of this session, each kind raised once per session
|
|
55
|
+
export function live(A, seen, { thresholds = THRESHOLDS } = {}) {
|
|
56
|
+
const out = [];
|
|
57
|
+
const add = (key, text) => { if (!seen.includes(key)) { seen.push(key); out.push(text); } };
|
|
58
|
+
const big = A.findings.filter(f => (f.cause === 'cache-miss' || f.cause === 'cache-expired') && f.tokens >= thresholds.missTokens);
|
|
59
|
+
if (big.some(f => f.cause === 'cache-miss')) add('miss', `a cache miss re-sent ${n(Math.max(...big.filter(f => f.cause === 'cache-miss').map(f => f.tokens)))} tokens: something early in the prompt changed (a file re-read into the system prompt, tools changing, a /model switch)`);
|
|
60
|
+
if (big.some(f => f.cause === 'cache-expired')) add('expired', 'a pause past the cache lifetime made the next turn re-read the whole context: after a long pause, /compact first (the cache is gone anyway, so the summary is the cheapest thing to re-read)');
|
|
61
|
+
const huge = A.findings.filter(f => f.cause === 'tool-output-bloat' && f.tokens >= thresholds.bigResult);
|
|
62
|
+
if (huge.length) add(`bloat:${huge[0].tool}`, `${huge[0].tool} returned more than ${n(thresholds.bigResult)} tokens, which every later turn re-sends: narrow it (a line range, a head, a grep)`);
|
|
63
|
+
return out.length ? `aiinfra: ${out.join('; ')}.` : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const readJson = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
|
|
67
|
+
const writeJson = (f, v) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify(v, null, 1) + '\n'); };
|
|
68
|
+
|
|
69
|
+
export function handle(input, { dir = stateDir(), thresholds = THRESHOLDS } = {}) {
|
|
70
|
+
const ev = input.hook_event_name, tp = input.transcript_path && input.transcript_path.replace(/^~(?=\/)/, os.homedir());
|
|
71
|
+
if (ev === 'SessionEnd') {
|
|
72
|
+
if (!tp || !fs.existsSync(tp)) return null;
|
|
73
|
+
const A = analyze(tp); if (!A) return null;
|
|
74
|
+
const msg = message(A, { thresholds, transcript: tp });
|
|
75
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
76
|
+
fs.appendFileSync(path.join(dir, 'sessions.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), session: input.session_id || A.session, cwd: input.cwd || null, calls: A.calls, input: A.input, hit: A.hit, missed: A.missed.tokens, expired: A.expired.tokens, bloat: A.bloat.tokens, avoidable: A.avoidable, avoidableCost: A.avoidableCost }) + '\n');
|
|
77
|
+
writeJson(path.join(dir, 'last.json'), { session: input.session_id || A.session, message: msg, shown: false, t: Math.floor(Date.now() / 1000) });
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (ev === 'SessionStart') {
|
|
81
|
+
const f = path.join(dir, 'last.json'), last = readJson(f);
|
|
82
|
+
if (!last || last.shown || !last.message || last.session === input.session_id) return null;
|
|
83
|
+
last.shown = true; writeJson(f, last);
|
|
84
|
+
return { systemMessage: `${last.message.replace(/^aiinfra:/, 'aiinfra (last session):')}` };
|
|
85
|
+
}
|
|
86
|
+
if (ev === 'Stop' || ev === 'SubagentStop') {
|
|
87
|
+
if (!tp || !fs.existsSync(tp)) return null;
|
|
88
|
+
const A = analyze(tp); if (!A) return null;
|
|
89
|
+
const f = path.join(dir, 'live', `${String(input.session_id || A.session).replace(/[^\w.-]/g, '_')}.json`), st = readJson(f) || { seen: [] };
|
|
90
|
+
const msg = live(A, st.seen, { thresholds }); writeJson(f, st);
|
|
91
|
+
return msg ? { systemMessage: msg } : null;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function settingsSnippet(script = HERE) {
|
|
97
|
+
const cmd = `node "${script}"`;
|
|
98
|
+
return { hooks: {
|
|
99
|
+
SessionEnd: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
|
|
100
|
+
SessionStart: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
|
|
101
|
+
Stop: [{ hooks: [{ type: 'command', command: cmd, async: true, timeout: 30 }] }],
|
|
102
|
+
}, statusLine: { type: 'command', command: `node "${path.join(path.dirname(script), 'aiinfra-statusline.mjs')}"` } };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === HERE) {
|
|
106
|
+
if (process.argv.includes('--print-settings')) { process.stdout.write(JSON.stringify(settingsSnippet(), null, 2) + '\n'); process.exit(0); }
|
|
107
|
+
let raw = ''; process.stdin.setEncoding('utf8');
|
|
108
|
+
process.stdin.on('data', c => { raw += c; if (raw.length > 1 << 20) process.stdin.destroy(); });
|
|
109
|
+
process.stdin.on('end', () => {
|
|
110
|
+
// a hook must never get in the way of the session: any failure is silent (exit 0, nothing printed)
|
|
111
|
+
try { const out = handle(JSON.parse(raw || '{}')); if (out) process.stdout.write(JSON.stringify(out) + '\n'); } catch (e) { if (process.env.AIINFRA_DEBUG) process.stderr.write(`aiinfra-hook: ${e.message}\n`); }
|
|
112
|
+
});
|
|
113
|
+
}
|