aiinfra-tools 0.2.0 → 0.4.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 (160) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/README.md +27 -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 +41 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +123 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +53 -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 +10 -3
  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 +32 -10
  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 +4 -0
  75. package/fleetscope/dist/index.html +1013 -28
  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 +29 -13
  84. package/fleetscope/src/index.src.html +15 -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 +299 -31
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/CATALOG.md +71 -0
  139. package/inference-sizer/docs/METHOD.md +1 -1
  140. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  141. package/inference-sizer/package.json +4 -3
  142. package/inference-sizer/src/accelerators.js +194 -0
  143. package/inference-sizer/src/catalog.js +55 -22
  144. package/inference-sizer/src/fit-ui.js +1 -1
  145. package/inference-sizer/src/index.src.html +3 -0
  146. package/inference-sizer/src/model.js +45 -7
  147. package/inference-sizer/src/ui.js +1 -1
  148. package/inference-sizer/tools/validate-agentx.mjs +116 -0
  149. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  150. package/mcp/README.md +6 -1
  151. package/mcp/server.mjs +34 -0
  152. package/package.json +10 -6
  153. package/schemas/README.md +3 -0
  154. package/schemas/aiinfra.report.schema.json +474 -0
  155. package/schemas/commands.mjs +14 -0
  156. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  157. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  158. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  159. package/schemas/harness-ledger.economics.schema.json +567 -0
  160. package/schemas/sizer.list.schema.json +15 -2
@@ -0,0 +1,89 @@
1
+ # Agentic workloads
2
+
3
+ Agent traffic doesn't fit the usual sizing input of "N requests per second at ISL×OSL". A session is a loop of model
4
+ calls. Each call's context is the previous one plus the reply and tool output, so the context grows turn by turn and
5
+ most of it is re-read from the prefix cache. Calls are separated by tool runs (seconds) and by people (minutes). The
6
+ context is occasionally compacted, and subagents add bursts.
7
+
8
+ Sizing from the average prompt gets agent traffic wrong in two opposite ways:
9
+ - it counts the whole prompt as prefill on every call, which overstates compute;
10
+ - it counts only requests in flight, which understates memory, because idle sessions hold their KV cache between
11
+ turns.
12
+
13
+ `tools/agentic.mjs` fits a profile of how sessions behave from a real trace, generates synthetic sessions from it at any
14
+ load, measures what a workload asks of a fleet, and sizes GPUs for it.
15
+
16
+ ```
17
+ node tools/agentic.mjs fit tracelab -o coding.json # profile from the public TraceLab trace
18
+ node tools/agentic.mjs fit my-agent.jsonl -o mine.json # or from your own sessions
19
+ node tools/agentic.mjs size coding.json --sessions-per-hour 2000 --model qwen3-coder-480b --gpu B200
20
+ node tools/agentic.mjs synth coding.json --sessions-per-hour 2000 --hours 2 -o load.csv # replay through `fleetscope run --trace`
21
+ node tools/agentic.mjs validate tracelab --hours 4 --markdown # how well a profile stands in for real sessions
22
+ ```
23
+
24
+ ## Inputs
25
+
26
+ | Trace | Where from | What it gives |
27
+ | --- | --- | --- |
28
+ | TraceLab | `tracelab` (fetched at a pinned release, SHA-256 checked) or `syfi_coding_trace.jsonl.gz` | 8,058 real Claude Code and Codex sessions: each provider's cache accounting, timing, tool calls |
29
+ | AgentX ("weka" traces) | SemiAnalysis, Hugging Face `semianalysisai/cc-traces-weka-*` | Claude Code sessions with subagents; prompts as 64-token chained block hashes; reuse within a session is computed from the hashes |
30
+ | Mooncake | Kimi's released traces | Requests with 512-token block hashes in one hash space (chat and API traffic, not agents) |
31
+ | Your own | FleetScope CSV or JSON lines with `session` (and `agent` for subagents), or harness-ledger's `llm_call` records | Whatever your harness logs |
32
+
33
+ `harness-ledger import` turns Claude Code, Codex, OpenTelemetry and Langfuse logs into `llm_call` records that this tool
34
+ reads. That is the way from your own agents to your own profile.
35
+
36
+ ## The profile
37
+
38
+ A profile is two levels, so each synthetic session behaves like a real one rather than like an average of all of them.
39
+
40
+ - **Per-stream parameters, sampled whole** (up to 4,000 streams): turns; first prompt; context growth and uncached
41
+ tokens per turn, as 13-point quantiles of that stream's own turns; pace of the tool loop; share and length of long
42
+ pauses; where it compacts and how much it keeps; output length; model time per call. A session that reads big files
43
+ stays a session that reads big files.
44
+ - **Pooled per-turn variation**, normalized by each stream's own means: gaps, output, model time; the cache hit of a
45
+ session's first call (system prompts are shared across sessions); the share of context still cached after a pause
46
+ longer than the cache lifetime; how often, and how far, smaller edits cut the context.
47
+ - **Long pauses come in runs.** Gaps follow a two-state chain (short: tool loop; long: a person or a slow tool).
48
+
49
+ Profiles hold numbers only: no prompts, no tool output, no session ids. You can share them.
50
+
51
+ ## What a workload asks of a fleet
52
+
53
+ `stats` and `validate` report per-minute windows:
54
+ - calls per second;
55
+ - prefill tokens per second (input not served from cache);
56
+ - output tokens per second;
57
+ - calls in flight;
58
+ - the **KV working set**: the tokens of contexts that must stay resident to be re-read. That is each stream's latest
59
+ context, held from its call until its next call or until the cache lifetime runs out, whichever comes first.
60
+
61
+ ## Sizing
62
+
63
+ `size` hands the Inference Sizer the workload's peak-minute call rate, mean and p99 prompt, output and cache hit (the
64
+ sizer's request-rate path, so prefill and decode come from the measured rate). It also checks the KV working set
65
+ against the HBM left after weights on the chosen layout. The answer is the larger of the two GPU counts, and it says
66
+ which one binds. A flat sizing of the same calls is shown beside it: the same rate and mean ISL/OSL, no reuse, no idle
67
+ sessions.
68
+
69
+ ## How well it works
70
+
71
+ On TraceLab, a profile fitted on 70% of the sessions was checked against replaying the other 30% on the same arrivals
72
+ ([VALIDATION-AGENTIC.md](VALIDATION-AGENTIC.md)):
73
+ - **Within 1–8%:** cache hit, calls per second, prefill and output tokens per second (mean and p95 minute).
74
+ - **Mean prompt:** 15% low.
75
+ - **KV working set:** 28% low.
76
+ - **GPUs:** 48 from the synthetic sessions against 40 from the held-out ones.
77
+ - **Flat ISL/OSL sizing:** no layout meets a 2 s TTFT at all; relaxed to 10 s, it asks for 440 GPUs.
78
+
79
+ Pooling all turns into one distribution per quantity, which is the obvious design, put prefill 2.5× too high: heavy
80
+ per-stream tails got multiplied across streams. That is why the profile keeps per-stream quantiles.
81
+
82
+ Limits:
83
+ - Timing comes from the providers that served the trace, not from your GPUs. The profile carries the shape of the work
84
+ (growth, reuse, gaps, tool time), not latency.
85
+ - The KV working set assumes contexts stay in GPU memory for the cache lifetime. `size --kv-offload` models offload to
86
+ host memory instead (LMCache-style: 375 GB per GPU by default, `--cpu-kv-gb`): fewer GPUs when the working set binds,
87
+ at the cost of a PCIe reload when a session comes back. It is used only when that reload fits the TTFT target and
88
+ PCIe stays under 80% busy at the peak minute; the what-if is reported either way. SSD tiers are not modelled.
89
+ - TraceLab is mostly coding agents. Fit your own profile for other kinds of agent.
@@ -21,12 +21,14 @@ On the Hybrid chat burst graph (57% SLO met today), a 95% target is met by movin
21
21
 
22
22
  ## Buy vs rent
23
23
 
24
- This costs three ways to supply growing peak GPU demand over a horizon (24 months by default):
24
+ This costs five ways to supply growing peak GPU demand over a horizon (24 months by default):
25
25
  - **Rent on demand:** pay for average use at on-demand prices.
26
26
  - **Reserve the base:** reserved prices for the base load, on demand for the peaks.
27
+ - **Reserve the base, capacity blocks for the peaks:** short-term blocks for the peaks, such as AWS EC2 Capacity Blocks for ML or GCP calendar-mode reservations. They are bought in whole days, so the peak hours are assumed to come as one run of days (a training run or a launch); `blockPerGpuH` sets the price. To see what is actually on offer, `fleetops procure aws-blocks --gpu H100 --gpus 64 --days 7` prints the read-only AWS command; `fleetops procure gcp-calendar --gpu H200 --gpus 64 --days 7 --region us-central1` (or `--gpu TPU-v6e --chips 64`) prints GCP's calendar-mode advice command.
28
+ - **Reserve the base, spot for the peaks:** the peak hours on spot (`spotPerGpuH`), plus the share redone after interruptions (`spotRework`, 10% by default).
27
29
  - **Buy the base, rent the peaks:** order on-prem GPUs so that, after the lead time, owned capacity covers the base load. Pay capex on delivery, plus power (kW per GPU × PUE × $/kWh) and operations, and rent the rest on demand. Hardware keeps its undepreciated value at the end.
28
30
 
29
- The result gives cumulative cost curves, the cheapest strategy, the month buying pays back against renting, and the order schedule. At the defaults (16 GPUs today, +4% a month): buying the base costs $751k net of residual value, against $826k reserved and $1.18M rented, and pays back by month 21. This is a rough model, not financial advice.
31
+ The result gives cumulative cost curves, the cheapest strategy, the month buying pays back against renting, and the order schedule. At the defaults (16 GPUs today, +4% a month): buying the base costs $751k net of residual value, against $826k reserved and $1.18M rented, and pays back by month 21. The block and spot prices are placeholders; set your own. This is a rough model, not financial advice.
30
32
 
31
33
  ## MIG
32
34
 
@@ -0,0 +1,37 @@
1
+ # Agentic workload profiles against held-out sessions
2
+
3
+ Generated by `node fleetscope/tools/agentic.mjs validate tracelab --hours 4 --markdown`. Data: [TraceLab](https://github.com/uw-syfi/TraceLab) v0.0.2 (CC BY 4.0; Zhu et al., TraceLab: Characterizing Coding Agent Workloads for LLM Serving, arXiv:2606.30560 (2026)), 8058 sessions (665.5k model calls). The profile is fitted on 5643 sessions and checked on the other 2415: both are started on the same Poisson arrivals (600 sessions/hour for 4 h, 5 seeds); the held-out sessions keep their own recorded timing, the synthetic ones are drawn from the profile.
4
+
5
+ ## What the workload asks of a fleet: synthetic vs replay
6
+
7
+ | Metric | Replay (held out) | Synthetic | Mean error over seeds |
8
+ | --- | --- | --- | --- |
9
+ | Prefix-cache hit rate | 95.8% | 95.6% | -0.7% (abs 0.7%) |
10
+ | Prompt tokens, mean | 101.1k | 94.8k | -15.0% (abs 15.0%) |
11
+ | Prompt tokens, p90 | 198.3k | 203.2k | -4.6% (abs 5.6%) |
12
+ | Output tokens, mean | 544 | 538 | +0.3% (abs 1.7%) |
13
+ | Calls/s, mean | 5.39 | 5.57 | -4.0% (abs 5.3%) |
14
+ | Calls/s, p95 minute | 7.48 | 9.48 | +8.1% (abs 10.9%) |
15
+ | Prefill tokens/s (uncached), mean | 22.6k | 23.1k | -5.2% (abs 6.1%) |
16
+ | Prefill tokens/s (uncached), p95 minute | 36.0k | 37.0k | -4.2% (abs 5.4%) |
17
+ | Output tokens/s, mean | 2.9k | 3.0k | -3.7% (abs 4.6%) |
18
+ | Output tokens/s, p95 minute | 4.4k | 4.3k | +1.5% (abs 4.2%) |
19
+ | KV working set (tokens), p95 | 25.66M | 18.92M | -28.4% (abs 28.4%) |
20
+
21
+ ## GPUs: qwen3-coder-480b on B200, TTFT 2000 ms, TPOT 30 ms
22
+
23
+ | Sized from | Compute GPUs | GPUs to hold the KV working set | GPUs | Bound by |
24
+ | --- | --- | --- | --- | --- |
25
+ | Held-out sessions, agentic (cache reuse and idle sessions counted) | 40 | 40 | **40** | compute |
26
+ | Synthetic sessions from the profile | 48 | 32 | **48** | compute |
27
+ | Held-out sessions, flat (same calls/s and mean ISL/OSL, no reuse, no idle sessions) | no layout meets the targets | 16 | **–** | prefilling the whole prompt every call misses the TTFT target |
28
+ | The same flat sizing with the TTFT target relaxed to 10 s | 440 | 16 | **440** | compute |
29
+
30
+ 2589 of 77603 replayed calls were longer than the model's 262.1k-token context and were capped to it.
31
+
32
+ ## Notes
33
+
34
+ - Timing comes from the providers that served the trace (model time per call), not from the GPUs being sized; the profile carries the shape of the work — context growth, reuse, gaps, tool time — not latency.
35
+ - The KV working set assumes contexts stay resident from one call to the next for up to the cache lifetime (300 s). Offloading to CPU memory or storage lowers the GPUs it needs and adds reload time.
36
+ - The flat row is how most sizing is done today: it overstates prefill (it re-prefills the whole prompt every call) and understates memory (it only counts in-flight requests).
37
+
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "fleetscope",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Node editor for replaying LLM traffic on a modelled hybrid (on-prem + neocloud) GPU fleet",
7
7
  "scripts": {
8
8
  "build": "node build.mjs",
9
- "test": "node --test tests/*.test.mjs"
9
+ "test": "node --test tests/*.test.mjs",
10
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude='tests/**' --test-coverage-exclude='../**' --test-coverage-lines=93 --test-coverage-branches=80 tests/*.test.mjs"
10
11
  },
11
12
  "engines": {
12
- "node": ">=20"
13
+ "node": ">=22"
13
14
  }
14
15
  }
@@ -0,0 +1,288 @@
1
+ /* FleetScope agentic workloads: fit a profile of how agent sessions behave from a real trace, generate synthetic sessions
2
+ from it at any load, measure what a workload asks of a fleet, and size GPUs for it.
3
+
4
+ Why: agent traffic is not "N requests/s of ISL×OSL". A session is a loop of model calls whose context grows turn by
5
+ turn and is mostly re-read from the prefix cache, separated by tool runs (seconds) and human pauses (minutes), with
6
+ occasional compactions and subagent bursts. Sizing from average ISL/OSL ignores the reuse (overstating prefill) and
7
+ ignores the KV cache that idle sessions hold between turns (understating memory).
8
+
9
+ Profile: per stream kind (a session's main loop, or a subagent), a table of per-stream parameters sampled whole
10
+ (turns, first prompt, context growth and prefill per turn as 13-point quantiles, tool-loop pace, share and length of long pauses, compaction point, output length, model time) and pooled per-turn
11
+ distributions as quantile tables (growth, gaps, output and model time normalized by the stream's own means; the share of context
12
+ still cached after a pause longer than the cache lifetime, the first call's cache hit, how much a compaction
13
+ keeps), plus subagents per session.
14
+
15
+ Rows are FleetScope trace rows: { t, isl, osl, cached?, session?, agent?, api? } (see ingest.js). */
16
+ (function (root) {
17
+ 'use strict';
18
+
19
+ // ---------- distributions ----------
20
+ // Quantile tables on a fixed probability grid, finer in the tail (agent traces are heavy-tailed: a uniform 101-point
21
+ // table interpolating from p99 to the maximum would inflate means several-fold). The top point is p99.99, not the max.
22
+ const GRID = (() => { const g = []; for (let i = 0; i <= 90; i++) g.push(i / 100); for (let i = 1; i <= 90; i++) g.push(0.9 + i / 1000); for (let i = 1; i <= 9; i++) g.push(0.99 + i / 1000); g.push(0.9995, 0.9999); return g; })();
23
+ function quantiles(xs) {
24
+ const s = xs.filter(Number.isFinite).sort((a, b) => a - b);
25
+ if (!s.length) return null;
26
+ return GRID.map(p => { const x = p * (s.length - 1), lo = Math.floor(x), hi = Math.min(s.length - 1, lo + 1); return +(s[lo] + (s[hi] - s[lo]) * (x - lo)).toFixed(4); });
27
+ }
28
+ // inverse CDF: u in [0,1) → value, interpolating between grid points
29
+ function draw(q, u) {
30
+ if (!q) return 0;
31
+ const p = u * GRID[GRID.length - 1];
32
+ let lo = 0, hi = GRID.length - 1;
33
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (GRID[mid] <= p) lo = mid; else hi = mid; }
34
+ const f = (p - GRID[lo]) / (GRID[hi] - GRID[lo] || 1);
35
+ return q[lo] + (q[hi] - q[lo]) * f;
36
+ }
37
+ const at = (q, p) => { if (!q) return NaN; const i = GRID.findIndex(x => x >= p - 1e-12); return q[i < 0 ? q.length - 1 : i]; };
38
+ function rng(seed) { let s = (seed >>> 0) || 1; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); }
39
+ function hashStr(x) { let h = 2166136261; for (const ch of String(x)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); return h >>> 0; }
40
+
41
+ // ---------- streams ----------
42
+ function streams(rows) {
43
+ const m = new Map();
44
+ for (const r of rows) {
45
+ const sess = r.session != null ? r.session : 'all', k = sess + '\u0000' + (r.agent || '');
46
+ if (!m.has(k)) m.set(k, { session: sess, agent: r.agent || null, rows: [] });
47
+ m.get(k).rows.push(r);
48
+ }
49
+ for (const s of m.values()) s.rows.sort((a, b) => a.t - b.t);
50
+ return [...m.values()];
51
+ }
52
+
53
+ // ---------- fit ----------
54
+ // Two levels, so sessions keep their character: a table of per-stream parameters (how many turns, how big the first
55
+ // prompt, how fast context grows, how quick the tool loop is, how often the stream waits on a person, where it
56
+ // compacts), sampled whole; and pooled per-turn distributions, normalized by those parameters, for the variation
57
+ // inside a stream (normalized by the stream's means, so a stream keeps its own averages). Gaps follow a two-state chain (short: tool loop; long: a person or a slow tool), because long
58
+ // pauses come in runs.
59
+ const mean = a => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : NaN);
60
+ // a stream's own growth and prefill per turn, as 13 points (p0, p10 … p90, p95, p99, max): they are the stream's
61
+ // character (a session reading big files vs one making small edits), and pooling them across streams blurs the tails.
62
+ // The fine top keeps a stream's one-off largest turn to about 1% of draws.
63
+ const SQ = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1];
64
+ function streamQ(a) { if (!a.length) return null; const s = [...a].sort((x, y) => x - y); return SQ.map(p => Math.round(s[Math.min(s.length - 1, Math.round(p * (s.length - 1)))])); }
65
+ function drawSQ(q, u) { const p = u; let i = 0; while (i < SQ.length - 2 && SQ[i + 1] <= p) i++; const f = (p - SQ[i]) / (SQ[i + 1] - SQ[i]); return q[i] + (q[i + 1] - q[i]) * Math.min(1, f); }
66
+ function fitStreams(ss, o) {
67
+ const params = [], appendQ = [], uncachedQ = [], appendN = [], shortN = [], longGap = [], longN = [], firstReuse = [], missTokens = [], shrinkRatio = [], shrinkMiss = [], osl = [], api = [], reuseShort = [], reuseLong = [], compactRatio = [], preCompact = [];
68
+ let ll = 0, lAny = 0, grows = 0;
69
+ for (const s of ss) {
70
+ const rs = s.rows, app = [], unc = [], sg = [], lg = [], states = [], so = [], sa = [];
71
+ if (rs[0].cached != null) firstReuse.push(Math.min(1, rs[0].cached / Math.max(1, rs[0].isl)));
72
+ const cAt = [], cR = [];
73
+ rs.forEach((r, i) => {
74
+ so.push(r.osl); if (Number.isFinite(r.api)) sa.push(r.api);
75
+ if (!i) return;
76
+ const p = rs[i - 1], g = Math.max(0, r.t - (p.t + (Number.isFinite(p.api) ? p.api : 0))), long = g > o.longGapS;
77
+ states.push(long); if (long) { longGap.push(g); lg.push(g); } else sg.push(g);
78
+ if (r.isl < p.isl * o.compaction) { compactRatio.push(r.isl / Math.max(1, p.isl)); preCompact.push(p.isl); cAt.push(p.isl); cR.push(r.isl / Math.max(1, p.isl)); return; }
79
+ // a smaller cut (old tool output cleared, history edited): the edited part is prefilled again
80
+ if (r.isl < p.isl) { shrinkRatio.push(r.isl / Math.max(1, p.isl)); if (r.cached != null) shrinkMiss.push(Math.min(1, (r.isl - r.cached) / Math.max(1, r.isl))); return; }
81
+ grows++;
82
+ const add = Math.max(0, r.isl - p.isl); app.push(add);
83
+ if (r.cached != null) {
84
+ if (g > o.cacheTtlS) reuseLong.push(Math.min(1, r.cached / Math.max(1, r.isl)));
85
+ else { reuseShort.push(Math.min(1, r.cached / Math.max(1, p.isl))); missTokens.push(r.isl - r.cached - add); unc.push(Math.max(0, r.isl - r.cached)); }
86
+ }
87
+ });
88
+ for (let i = 1; i < states.length; i++) if (states[i - 1]) { lAny++; if (states[i]) ll++; }
89
+ // scales are the stream's means, so the pooled normalized draws average 1 and the stream keeps its own mean
90
+ const am = Math.max(1, mean(app) || 1), gm = Math.max(0.05, mean(sg) || 0.05), lm = lg.length ? mean(lg) : 0;
91
+ const om = Math.max(1, mean(so)), pm = sa.length ? Math.max(0.01, mean(sa)) : 0;
92
+ for (const a of app) appendN.push(a / am); for (const g of sg) shortN.push(g / gm); if (lm) for (const g of lg) longN.push(g / lm);
93
+ for (const x of so) osl.push(x / om); if (pm) for (const x of sa) api.push(x / pm);
94
+ appendQ.push(streamQ(app)); uncachedQ.push(streamQ(unc));
95
+ params.push([rs.length, rs[0].isl, am, gm, states.length ? states.filter(Boolean).length / states.length : 0, cAt.length ? Math.max(...cAt) : 0, lm, om, pm, cR.length ? +mean(cR).toFixed(4) : 0, app.length ? Math.max(...app) : 0, Math.max(...rs.map(x => x.isl))]);
96
+ }
97
+ // keep at most 4000 streams' parameters (evenly spaced) to bound the profile's size
98
+ const step = Math.max(1, params.length / 4000), table = [], aq = [], uq = [];
99
+ for (let i = 0; i < params.length && table.length < 4000; i += step) { table.push(params[Math.floor(i)].map(x => +(+x).toFixed(3))); aq.push(appendQ[Math.floor(i)]); uq.push(uncachedQ[Math.floor(i)]); }
100
+ return { streams: ss.length, params: table, appendQ: aq, uncachedQ: uq, paramsCols: ['turns', 'firstIsl', 'appendMean', 'shortGapMean', 'longShare', 'compactAt', 'longGapMean', 'outputMean', 'modelTimeMean', 'compactKeeps', 'appendMax', 'islMax'],
101
+ appendNorm: quantiles(appendN), shortGapNorm: quantiles(shortN), longGap: quantiles(longGap), longGapNorm: quantiles(longN), firstReuse: quantiles(firstReuse), missTokens: quantiles(missTokens), pLongAfterLong: lAny ? ll / lAny : 0,
102
+ oslNorm: quantiles(osl), apiNorm: quantiles(api), reuseShort: quantiles(reuseShort), reuseLong: quantiles(reuseLong),
103
+ compactRatio: quantiles(compactRatio), preCompact: quantiles(preCompact), compactions: compactRatio.length,
104
+ pShrink: shrinkRatio.length / Math.max(1, shrinkRatio.length + grows), shrinkRatio: quantiles(shrinkRatio), shrinkMiss: quantiles(shrinkMiss) };
105
+ }
106
+ function fitProfile(rows, opt) {
107
+ const o = Object.assign({ cacheTtlS: 300, compaction: 0.5, longGapS: 30, source: '' }, opt || {});
108
+ const ss = streams(rows), main = ss.filter(s => !s.agent), sub = ss.filter(s => s.agent);
109
+ const subPer = new Map(main.map(s => [s.session, 0])); for (const s of sub) subPer.set(s.session, (subPer.get(s.session) || 0) + 1);
110
+ const cached = rows.filter(r => r.cached != null);
111
+ return { kind: 'fleetscope.agentic-profile', version: 11, source: o.source, cacheTtlS: o.cacheTtlS, compaction: o.compaction, longGapS: o.longGapS,
112
+ sessions: main.length, requests: rows.length, cacheHit: cached.length ? cached.reduce((a, r) => a + r.cached, 0) / cached.reduce((a, r) => a + r.isl, 0) : null,
113
+ main: fitStreams(main, o), sub: sub.length ? fitStreams(sub, o) : null, subPerSession: sub.length ? quantiles([...subPer.values()]) : null };
114
+ }
115
+
116
+ // ---------- synthesize ----------
117
+ // A session per arrival (Poisson at sessionsPerHour, or given start times): pick a stream's parameters, then draw each
118
+ // turn's growth, gap, output and model time around them.
119
+ function synthStream(P, r, t0, sess, agent, horizon, o, out) {
120
+ const pi0 = Math.floor(r() * P.params.length), pr = P.params[pi0], aq = P.appendQ && P.appendQ[pi0], uq = P.uncachedQ && P.uncachedQ[pi0], [turns, first, am, gm, longShare, compactAt, lm, om, pm, ck, aMax, iMax] = pr;
121
+ const pLL = P.pLongAfterLong, pi = Math.min(0.99, longShare), pLS = pi >= 1 ? 1 : Math.min(1, pi * (1 - pLL) / Math.max(1e-6, 1 - pi));
122
+ let isl = Math.max(1, Math.round(first)), t = t0, prev = null, long = false;
123
+ for (let i = 0; i < turns && t < horizon; i++) {
124
+ let uncached = isl;
125
+ if (prev) {
126
+ long = r() < (long ? pLL : pLS);
127
+ const g = long ? (lm > 0 && P.longGapNorm ? draw(P.longGapNorm, r()) * lm : draw(P.longGap, r())) : draw(P.shortGapNorm, r()) * gm;
128
+ t += g; if (t >= horizon) break;
129
+ let shrink = false;
130
+ if (compactAt > 0 && prev.isl >= compactAt) isl = Math.max(1, Math.round(prev.isl * (ck || draw(P.compactRatio, r()))));
131
+ else if (P.shrinkRatio && r() < P.pShrink) { shrink = true; isl = Math.max(1, Math.round(prev.isl * draw(P.shrinkRatio, r()))); }
132
+ // growth stays within what this stream was seen to do: no single turn adds more, and the context gets no longer
133
+ else isl = Math.min(o.maxIsl, iMax || Infinity, prev.isl + Math.round(aq ? drawSQ(aq, r()) : Math.min(aMax || Infinity, draw(P.appendNorm, r()) * am)));
134
+ // prefill this turn: within the cache lifetime, drawn from the stream's own uncached tokens per turn (mostly the
135
+ // tokens appended, sometimes a miss); after it, a drawn share of the whole context
136
+ if (shrink && P.shrinkMiss) uncached = Math.round(isl * draw(P.shrinkMiss, r()));
137
+ else if (g > o.cacheTtlS && P.reuseLong) uncached = Math.round(isl * (1 - draw(P.reuseLong, r())));
138
+ else if (uq) uncached = Math.min(isl, Math.round(drawSQ(uq, r())));
139
+ else if (P.missTokens) uncached = Math.max(0, Math.round(Math.max(0, isl - prev.isl) + Math.min(prev.isl, draw(P.missTokens, r()))));
140
+ else uncached = isl;
141
+ }
142
+ const osl = Math.max(1, Math.round(draw(P.oslNorm, r()) * om)), api = pm && P.apiNorm ? draw(P.apiNorm, r()) * pm : NaN;
143
+ const row = { t, isl, osl, session: sess, cached: prev ? Math.max(0, Math.min(isl - 1, isl - uncached)) : P.firstReuse ? Math.min(isl - 1, Math.round(draw(P.firstReuse, r()) * isl)) : 0 };
144
+ if (agent) row.agent = agent;
145
+ if (Number.isFinite(api)) row.api = api;
146
+ out.push(row); prev = row; t += Number.isFinite(api) ? api : 0;
147
+ }
148
+ return t;
149
+ }
150
+ function arrivals(n, perHour, horizon, r) {
151
+ const out = []; let t = 0;
152
+ if (perHour > 0) { while (true) { t += -Math.log(1 - r()) * 3600 / perHour; if (t >= horizon) break; out.push(t); } }
153
+ else for (let i = 0; i < n; i++) out.push(r() * horizon);
154
+ return out;
155
+ }
156
+ function synthesize(profile, opt) {
157
+ const o = Object.assign({ seed: 1, horizonS: 3600, sessionsPerHour: 0, sessions: 100, starts: null, maxIsl: 2e6, cacheTtlS: profile.cacheTtlS || 300 }, opt || {});
158
+ const r = rng(o.seed), starts = o.starts || arrivals(o.sessions, o.sessionsPerHour, o.horizonS, r), out = [];
159
+ starts.forEach((t0, i) => {
160
+ const sess = 'synth-' + i, end = synthStream(profile.main, r, t0, sess, null, o.horizonS, o, out);
161
+ if (profile.sub && profile.subPerSession) {
162
+ const k = Math.round(draw(profile.subPerSession, r()));
163
+ for (let j = 0; j < k; j++) synthStream(profile.sub, r, t0 + r() * Math.max(1, end - t0), sess, 'sub-' + j, o.horizonS, o, out);
164
+ }
165
+ });
166
+ return out.sort((a, b) => a.t - b.t);
167
+ }
168
+ // The same arrival process, filled with real sessions (each keeps its own internal timing): the replay to compare a
169
+ // synthetic workload against.
170
+ function replay(rows, opt) {
171
+ const o = Object.assign({ seed: 1, horizonS: 3600 }, opt || {});
172
+ const r = rng(o.seed), byS = new Map();
173
+ for (const x of rows) { const k = x.session != null ? x.session : 'all'; if (!byS.has(k)) byS.set(k, []); byS.get(k).push(x); }
174
+ const sess = [...byS.values()].map(rs => { const t0 = Math.min(...rs.map(x => x.t)); return rs.map(x => Object.assign({}, x, { t: x.t - t0 })); });
175
+ const starts = o.starts || arrivals(o.sessions || 100, o.sessionsPerHour || 0, o.horizonS, r), out = [];
176
+ starts.forEach((t0, i) => { const s = sess[Math.floor(r() * sess.length)]; for (const x of s) { const t = t0 + x.t; if (t < o.horizonS) out.push(Object.assign({}, x, { t, session: 'replay-' + i + ':' + x.session })); } });
177
+ return out.sort((a, b) => a.t - b.t);
178
+ }
179
+
180
+ // ---------- what a workload asks of a fleet ----------
181
+ // Per window: arrivals, prefill tokens (input not served from cache), decode tokens; in-flight calls; and the KV
182
+ // working set: tokens of contexts that must stay resident to be re-read, i.e. each stream's latest context from its
183
+ // call until its next call (or the cache lifetime, whichever comes first).
184
+ function workloadStats(rows, opt) {
185
+ const o = Object.assign({ windowS: 60, cacheTtlS: 300, ideal: false }, opt || {});
186
+ if (!rows.length) return null;
187
+ // windows span the arrivals (or the given horizon); a call still running past the end isn't stretched over more windows
188
+ let t0 = Infinity, t1 = -Infinity; for (const r of rows) { if (r.t < t0) t0 = r.t; if (r.t > t1) t1 = r.t; }
189
+ if (o.horizonS) { t0 = Math.min(t0, 0); t1 = t0 + o.horizonS; } else t1 += o.windowS;
190
+ const W = Math.max(1, Math.ceil((t1 - t0) / o.windowS));
191
+ const arr = new Float64Array(W), pre = new Float64Array(W), dec = new Float64Array(W), kv = new Float64Array(W + 1), fl = new Float64Array(W + 1);
192
+ const ix = t => Math.min(W - 1, Math.max(0, Math.floor((t - t0) / o.windowS)));
193
+ let cachedSum = 0, islSum = 0;
194
+ for (const s of streams(rows)) {
195
+ s.rows.forEach((r, i) => {
196
+ const next = s.rows[i + 1], cached = o.ideal ? (i ? Math.min(r.isl, s.rows[i - 1].isl) : 0) : (r.cached || 0);
197
+ cachedSum += cached; islSum += r.isl;
198
+ const w = ix(r.t); arr[w]++; pre[w] += r.isl - cached; dec[w] += r.osl;
199
+ // resident from the call until the next call or the TTL; sampled at window edges
200
+ const end = Math.min(next ? next.t : Infinity, r.t + (r.api || 0) + o.cacheTtlS);
201
+ for (let e = Math.ceil((r.t - t0) / o.windowS); e * o.windowS + t0 < end && e <= W; e++) kv[e] += r.isl + r.osl;
202
+ if (r.api > 0) for (let e = Math.ceil((r.t - t0) / o.windowS); e * o.windowS + t0 < r.t + r.api && e <= W; e++) fl[e]++;
203
+ });
204
+ }
205
+ const Q = (a, p) => { const s = Array.from(a).sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * (s.length - 1)))]; };
206
+ const per = a => ({ mean: Array.from(a).reduce((x, y) => x + y, 0) / a.length / o.windowS, p50: Q(a, 0.5) / o.windowS, p95: Q(a, 0.95) / o.windowS, max: Q(a, 1) / o.windowS });
207
+ const isl = rows.map(r => r.isl), osl = rows.map(r => r.osl);
208
+ return { requests: rows.length, sessions: new Set(rows.map(r => r.session)).size, seconds: t1 - t0, cacheHit: islSum ? cachedSum / islSum : 0,
209
+ isl: { mean: isl.reduce((a, b) => a + b, 0) / isl.length, p50: Q(isl, 0.5), p90: Q(isl, 0.9), p99: Q(isl, 0.99) },
210
+ osl: { mean: osl.reduce((a, b) => a + b, 0) / osl.length, p50: Q(osl, 0.5), p90: Q(osl, 0.9), p99: Q(osl, 0.99) },
211
+ rps: per(arr), prefillTps: per(pre), decodeTps: per(dec),
212
+ kvTokens: { p50: Q(kv, 0.5), p95: Q(kv, 0.95), max: Q(kv, 1) }, inflight: { p50: Q(fl, 0.5), p95: Q(fl, 0.95), max: Q(fl, 1) } };
213
+ }
214
+ const KEYS = ['cacheHit', 'isl.mean', 'isl.p90', 'osl.mean', 'rps.mean', 'rps.p95', 'prefillTps.mean', 'prefillTps.p95', 'decodeTps.mean', 'decodeTps.p95', 'kvTokens.p95'];
215
+ const getp = (o, k) => k.split('.').reduce((a, x) => (a == null ? a : a[x]), o);
216
+ function compare(real, synth, keys) {
217
+ const out = {};
218
+ for (const k of keys || KEYS) { const a = getp(real, k), b = getp(synth, k); out[k] = { real: a, synth: b, err: a ? (b - a) / a : null }; }
219
+ return out;
220
+ }
221
+
222
+ // ---------- GPUs for a workload ----------
223
+ // The sizer for compute (peak arrivals, mean and p99 prompts, cache hit from the workload), and the KV working set
224
+ // against what's left of HBM after weights for memory. Agentic fleets are often bound by the second.
225
+ // KV offload defaults: host memory for KV per GPU, the cap InferenceX AgentX allows (3 TB per server, in proportion to
226
+ // the GPUs used: 375 GB for an 8-GPU server), and reload over PCIe 5.0 x16 (64 GB/s per direction) at 70% of it.
227
+ const OFFLOAD = { cpuGBPerGpu: 375, pcieGBs: 64, eff: 0.7 };
228
+ function sizeFor(stats, s0, M, opt) {
229
+ const o = Object.assign({ kvBound: true, kvOffload: false }, opt || {});
230
+ // the arrival rate goes in directly (the sizer's "DAU" path: requests/s at peak, output tokens/s), so prefill and
231
+ // decode are sized from the workload's own peak-minute rate rather than from a concurrency guess
232
+ const s = Object.assign({}, s0, { avgIn: Math.round(stats.isl.mean), peakIn: Math.round(stats.isl.p99), avgOut: Math.round(stats.osl.mean), peakOut: Math.round(stats.osl.p99),
233
+ ctx: Math.max(s0.ctx || 0, Math.round(stats.isl.p99 + stats.osl.p99)), prefixHit: Math.round(100 * stats.cacheHit), concSource: 'dau', dau: Math.max(1, stats.rps.p95 * 86400), rpu: 1, peakFactor: 1 });
234
+ const r = M.plan(s, { noSens: true }), md = M.derive(s);
235
+ const perTok = M.kvBytes(md, 1e6) / 1e6;
236
+ // KV lives on the decode (or aggregated) instances: what's left per GPU after that layout's share of the weights
237
+ const g = r.chosen ? (r.chosen.mode === 'disagg' ? r.dis.D.c.g : r.agg.best.c.g) : md.D;
238
+ const freePerGpu = Math.max(1e9, (md.hbm - md.reserve) * (s.kvMaxUtil || 0.9) - (md.Wd + md.We) / g);
239
+ const kvGpus = Math.ceil(stats.kvTokens.p95 * perTok / freePerGpu / g) * g;
240
+ const compute = r.chosen ? r.chosen.provGPUs : null;
241
+ // KV offload: contexts that don't fit in HBM wait in host memory and are reloaded over PCIe when their session comes
242
+ // back. The GPUs then only need to hold the hot part; a reload slower than the TTFT target means offload can't be used.
243
+ const off = Object.assign({}, OFFLOAD, o.offload || {}), W = stats.kvTokens.p95 * perTok;
244
+ const kvGpusOff = Math.ceil(W / (freePerGpu + off.cpuGBPerGpu * 1e9) / g) * g;
245
+ const gOff = compute == null ? null : Math.max(compute, kvGpusOff), hbmAtOff = gOff ? gOff * freePerGpu : 0;
246
+ const reloadMs = 1000 * stats.isl.mean * (stats.cacheHit || 0) * perTok / (off.pcieGBs * 1e9 * off.eff * g); // a returning session's cached prefix, the instance's GPUs reloading in parallel
247
+ const offShare = W > 0 ? Math.max(0, 1 - hbmAtOff / W) : 0;
248
+ // and all of them together: the reload traffic at the peak minute against the PCIe the GPUs have
249
+ const pcieUtil = gOff ? stats.rps.p95 * offShare * stats.isl.mean * (stats.cacheHit || 0) * perTok / (gOff * off.pcieGBs * 1e9 * off.eff) : null;
250
+ const offload = { cpuGBPerGpu: off.cpuGBPerGpu, kvGpus: kvGpusOff, gpus: gOff, offloadedShare: offShare, reloadMs, fitsTtft: reloadMs < s.ttft, pcieUtil, pcieGBs: off.pcieGBs };
251
+ offload.usable = offload.fitsTtft && pcieUtil != null && pcieUtil < 0.8; // headroom: reloads compete with weights and activations for the bus
252
+ const useOff = o.kvOffload && offload.usable && gOff != null;
253
+ const kvNeed = useOff ? kvGpusOff : kvGpus, gpus = compute == null ? null : Math.max(compute, o.kvBound ? kvNeed : 0);
254
+ // tokens per megawatt (AgentX's headline metric): peak-minute output tokens/s over the provisioned power, from the
255
+ // published per-node power (the whole server) when there is one, else the GPU's board power alone
256
+ const perGpuKW = s.nodeKW ? s.nodeKW / (s.domain || 8) : s.tdpW ? s.tdpW / 1000 : null;
257
+ const powerKW = gpus != null && perGpuKW ? gpus * perGpuKW : null;
258
+ return { compute, kvGpus, gpus, bound: compute == null ? 'none' : kvNeed > compute ? (useOff ? 'KV working set (with offload)' : 'KV working set') : 'compute',
259
+ kvGB: W / 1e9, mode: r.chosen && r.chosen.mode, offload, kvOffloadUsed: useOff,
260
+ power: powerKW == null ? null : { kw: powerKW, basis: s.nodeKW ? 'published node power' : 'GPU board power only', tokensPerSecPerMW: stats.decodeTps && stats.decodeTps.p95 != null ? stats.decodeTps.p95 / (powerKW / 1000) : null },
261
+ inputs: { avgIn: s.avgIn, peakIn: s.peakIn, avgOut: s.avgOut, prefixHit: s.prefixHit, requestsPerS: stats.rps.p95 } };
262
+ }
263
+ // The traditional sizing input: the same request rate and mean ISL/OSL, no prefix reuse, no idle sessions.
264
+ function flatStats(stats) {
265
+ return Object.assign({}, stats, { cacheHit: 0, kvTokens: { p50: stats.inflight.p50 * (stats.isl.mean + stats.osl.mean), p95: stats.inflight.p95 * (stats.isl.mean + stats.osl.mean), max: stats.inflight.max * (stats.isl.mean + stats.osl.mean) } });
266
+ }
267
+
268
+ // ---------- validation: fit on some sessions, compare synthetic against replay of the others ----------
269
+ function validate(rows, opt) {
270
+ const o = Object.assign({ holdout: 0.3, seeds: [1, 2, 3], sessionsPerHour: 600, horizonS: 3600, cacheTtlS: 300 }, opt || {});
271
+ const isTest = r => (hashStr(r.session) % 1000) / 1000 < o.holdout;
272
+ const train = rows.filter(r => !isTest(r)), test = rows.filter(isTest);
273
+ const profile = fitProfile(train, { cacheTtlS: o.cacheTtlS, source: o.source });
274
+ const runs = o.seeds.map(seed => {
275
+ const starts = arrivals(0, o.sessionsPerHour, o.horizonS, rng(seed * 7919));
276
+ const real = workloadStats(replay(test, { seed, starts, horizonS: o.horizonS }), o), synth = workloadStats(synthesize(profile, { seed, starts, horizonS: o.horizonS }), o);
277
+ return { seed, real, synth, cmp: compare(real, synth) };
278
+ });
279
+ const agg = {};
280
+ for (const k of KEYS) { const e = runs.map(x => x.cmp[k].err).filter(Number.isFinite); agg[k] = { meanAbsErr: e.reduce((a, b) => a + Math.abs(b), 0) / Math.max(1, e.length), meanErr: e.reduce((a, b) => a + b, 0) / Math.max(1, e.length) }; }
281
+ const res = { profile, train: { rows: train.length, sessions: new Set(train.map(r => r.session)).size }, test: { rows: test.length, sessions: new Set(test.map(r => r.session)).size }, runs, agg, settings: o };
282
+ Object.defineProperty(res, 'testRows', { value: test, enumerable: false });
283
+ return res;
284
+ }
285
+
286
+ const api = { GRID, at, quantiles, draw, fitProfile, synthesize, replay, workloadStats, compare, sizeFor, flatStats, validate, streams, arrivals, rng, KEYS };
287
+ if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.FleetAgentic = api;
288
+ })(typeof window !== 'undefined' ? window : globalThis);
@@ -4,7 +4,6 @@
4
4
  'use strict';
5
5
  const node = typeof module !== 'undefined' && module.exports;
6
6
  const E = node ? require('./engine.js') : root.FleetEngine;
7
- const SC = node ? require('./scenario.js') : root.FleetScenarioLib;
8
7
 
9
8
  const EXAMPLES = [
10
9
  'What if coding agents move to H200 and the cloud link drops to 100 Gbps?',
@@ -1,3 +1,4 @@
1
+ /* global FleetScenario */ // set by scenario.js, loaded first on the page
1
2
  /* FleetScope cluster view: GPU allocation grid, scheduler policy what-ifs, workload timeline. Browser only. */
2
3
  (function () {
3
4
  'use strict';
@@ -24,17 +24,16 @@
24
24
  }
25
25
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
26
26
 
27
- // Approximate public spec-sheet figures (dense TFLOPS, HBM GB, HBM TB/s). Prices are placeholders, $/GPU-hour.
28
- const GPUS = {
29
- A100: { label: 'A100 80GB', hbm: 80, bw: 2.0, bf16: 312, fp8: 312, onprem: 0.9, rent: 1.6, tdpW: 400 },
30
- L40S: { label: 'L40S 48GB', hbm: 48, bw: 0.864, bf16: 362, fp8: 733, onprem: 0.7, rent: 1.1, tdpW: 350 },
31
- H100: { label: 'H100 80GB', hbm: 80, bw: 3.35, bf16: 989, fp8: 1979, onprem: 1.4, rent: 2.4, tdpW: 700 },
32
- H200: { label: 'H200 141GB', hbm: 141, bw: 4.8, bf16: 989, fp8: 1979, onprem: 2.0, rent: 3.5, tdpW: 700 },
33
- MI300X: { label: 'MI300X 192GB', hbm: 192, bw: 5.3, bf16: 1307, fp8: 2615, onprem: 1.5, rent: 2.6, tdpW: 750 },
34
- B200: { label: 'B200 180GB', hbm: 180, bw: 8.0, bf16: 2250, fp8: 4500, onprem: 3.2, rent: 5.5, tdpW: 1000 },
35
- B300: { label: 'B300 262GB', hbm: 262, bw: 8.0, bf16: 2250, fp8: 4500, onprem: 4.0, rent: 7.0, tdpW: 1100 },
36
- GB200: { label: 'GB200 186GB (NVL72)', hbm: 186, bw: 8.0, bf16: 2500, fp8: 5000, onprem: 3.6, rent: 6.0, tdpW: 1200 }
37
- };
27
+ // Spec-sheet figures (dense TFLOPS, HBM GB, HBM TB/s) from the shared accelerator registry
28
+ // (inference-sizer/src/accelerators.js). Prices are placeholders, $/GPU-hour.
29
+ const REG = (typeof module !== 'undefined' && module.exports) ? require('../../inference-sizer/src/accelerators.js') : root.AIInfraAccelerators;
30
+ const GPU_ORDER = ['A100', 'L40S', 'H100', 'H200', 'MI300X', 'B200', 'B300', 'GB200', 'GB300', 'MI325X', 'MI355X'];
31
+ const GPUS = {};
32
+ for (const k of GPU_ORDER.concat(REG.ACCELERATORS.map(a => a.short || a.id))) {
33
+ const a = REG.byId(k); if (!a || GPUS[k] || !a.tdpW) continue; // the power model needs board power (cloud TPUs don't publish it)
34
+ GPUS[k] = { label: `${k} ${a.hbmGB}GB${a.domain >= 72 ? ` (NVL${a.domain})` : ''}`, hbm: a.hbmGB, bw: a.hbmTBs, bf16: a.tfBf16, fp8: a.tfFp8 || a.tfBf16,
35
+ onprem: a.onprem, rent: a.price, tdpW: a.tdpW, vendor: a.vendorKey, kind: a.kind };
36
+ }
38
37
  // Approximate architecture figures. kvDim = per-token, per-layer K+V width (2 x kv_heads x head_dim, or MLA latent).
39
38
  const MODELS = {
40
39
  'llama-8b': { label: 'Llama 3.1 8B', params: 8, active: 8, layers: 32, kvHeads: 8, headDim: 128, mla: 0 },
@@ -43,14 +42,31 @@
43
42
  'llama-405b': { label: 'Llama 3.1 405B', params: 405, active: 405, layers: 126, kvHeads: 8, headDim: 128, mla: 0 },
44
43
  'moe-671b': { label: 'MoE 671B, 37B active (MLA)', params: 671, active: 37, layers: 61, kvHeads: 0, headDim: 0, mla: 576 }
45
44
  };
45
+ // Every other model in the Inference Sizer's catalog (one list for both tools, kept current there). kvScale: the KV a
46
+ // token holds, averaged over a 32K context, against the plain kvDim × layers figure, so sliding-window, linear-attention
47
+ // and compressed layers count; it scales with the layers and heads if they are edited.
48
+ const node = typeof module !== 'undefined' && module.exports;
49
+ const CAT = node ? require('../../inference-sizer/src/catalog.js') : root.SizerCatalog, SZ = node ? require('../../inference-sizer/src/model.js') : root.SizerModel;
50
+ const kvDimTotal = m => (m.mla ? m.layers * m.mla : 2 * m.layers * m.kvHeads * m.headDim);
51
+ for (const k of Object.keys(MODELS)) MODELS[k].kvScale = 1;
52
+ const IN_LIST = { 'llama31-8b': 'llama-8b', 'llama33-70b': 'llama-70b', 'llama31-405b': 'llama-405b', 'deepseek-v3': 'moe-671b' };
53
+ if (CAT && SZ) {
54
+ for (const c of CAT.MODELS) {
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 };
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
+ m.kvScale = +(SZ.kvBytes(md, 32768) / 32768 / kvDimTotal(m)).toFixed(4);
59
+ MODELS[c.id] = m;
60
+ }
61
+ }
46
62
 
47
63
  // ---------- performance profile ----------
48
64
  // tpFixed: GPUs per instance set on the pool (0 or absent = smallest power of two whose share of the weights fits).
49
65
  function profile(gpuKey, m, tpFixed) {
50
66
  const G = GPUS[gpuKey];
51
- const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : 1);
67
+ const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : m.wPrec === 'fp4' ? 0.5625 : 1);
52
68
  const kvElem = m.kvPrec === 'bf16' ? 2 : 1;
53
- const kvBytesPerToken = m.mla ? m.layers * m.mla * kvElem : 2 * m.layers * m.kvHeads * m.headDim * kvElem;
69
+ const kvBytesPerToken = kvDimTotal(m) * kvElem * (m.kvScale > 0 ? m.kvScale : 1);
54
70
  let tp = 1;
55
71
  if (tpFixed > 0) tp = Math.round(tpFixed);
56
72
  else while (tp < 16 && wBytes / tp > 0.65 * G.hbm * 1e9) tp *= 2;
@@ -385,6 +385,15 @@ button, select, input { font: inherit; color: inherit; }
385
385
  <div class="shell" id="trainingApp" hidden></div>
386
386
  <div class="shell" id="inferenceApp" hidden></div>
387
387
  <script>
388
+ /*ACCELERATORS*/
389
+ </script>
390
+ <script>
391
+ /*SIZERCATALOG*/
392
+ </script>
393
+ <script>
394
+ /*SIZERMODEL*/
395
+ </script>
396
+ <script>
388
397
  /*ENGINE*/
389
398
  </script>
390
399
  <script>
@@ -2266,10 +2275,10 @@ function renderPlanPanel() {
2266
2275
  num('target', 'SLO attainment target (%)', PL.target, 50, 99.9, 0.5) + num('n1', 'N-1 floor: SLO with the largest pool down (%, 0 = off)', PL.n1, 0, 99, 1) +
2267
2276
  '<div class="ctl check"><label><input type="checkbox" data-pl="gpuSwap"' + (PL.gpuSwap ? ' checked' : '') + '>Try other GPU types (H100, H200, B200)</label></div>' + num('evals', 'Simulation budget', PL.evals, 10, 200, 10) +
2268
2277
  '<div class="btnrow"><button class="btn primary" type="button" data-act="plOpt">Find the cheapest setup</button></div>';
2269
- else if (PL.tab === 'cap') { const c = PL.cap; h += '<div class="sub">Costs three ways to supply growing GPU demand over ' + c.months + ' months: rent on demand, reserve the base load, or buy on-prem for the base load (with a lead time) and rent the peaks.</div>' +
2278
+ else if (PL.tab === 'cap') { const c = PL.cap; h += '<div class="sub">Costs five ways to supply growing GPU demand over ' + c.months + ' months: rent on demand; reserve the base load and rent the peaks on demand, as capacity blocks (EC2 Capacity Blocks, GCP calendar-mode reservations) or on spot; or buy on-prem for the base load (with a lead time) and rent the peaks.</div>' +
2270
2279
  num('gpusNow', 'Peak GPUs needed today', c.gpusNow, 1, 100000, 1, 'cap') + num('growthPct', 'Growth per month (%)', c.growthPct, -10, 50, 0.5, 'cap') + num('baseShare', 'Base load as a share of peak', c.baseShare, 0.1, 1, 0.05, 'cap') + num('peakHoursShare', 'Share of hours above base', c.peakHoursShare, 0.05, 1, 0.05, 'cap') +
2271
2280
  num('gpuCapex', 'On-prem $ per GPU (with server share)', c.gpuCapex, 1000, 200000, 500, 'cap') + num('leadMonths', 'Lead time (months)', c.leadMonths, 0, 18, 1, 'cap') + num('amortMonths', 'Depreciation (months)', c.amortMonths, 12, 84, 6, 'cap') + num('kwhPrice', 'Power $/kWh', c.kwhPrice, 0.01, 1, 0.01, 'cap') +
2272
- num('reservedPerGpuH', 'Reserved $/GPU-hour', c.reservedPerGpuH, 0.1, 20, 0.05, 'cap') + num('onDemandPerGpuH', 'On-demand $/GPU-hour', c.onDemandPerGpuH, 0.1, 20, 0.05, 'cap') + num('months', 'Horizon (months)', c.months, 6, 60, 6, 'cap') +
2281
+ num('reservedPerGpuH', 'Reserved $/GPU-hour', c.reservedPerGpuH, 0.1, 20, 0.05, 'cap') + num('onDemandPerGpuH', 'On-demand $/GPU-hour', c.onDemandPerGpuH, 0.1, 20, 0.05, 'cap') + num('blockPerGpuH', 'Capacity block $/GPU-hour', c.blockPerGpuH, 0.1, 20, 0.05, 'cap') + num('spotPerGpuH', 'Spot $/GPU-hour', c.spotPerGpuH, 0.1, 20, 0.05, 'cap') + num('spotRework', 'Spot hours redone after interruptions', c.spotRework, 0, 1, 0.05, 'cap') + num('months', 'Horizon (months)', c.months, 6, 60, 6, 'cap') +
2273
2282
  '<div class="btnrow"><button class="btn primary" type="button" data-act="plCap">Compare</button></div>'; }
2274
2283
  else h += '<div class="sub">Packs small models onto MIG slices instead of whole GPUs. Each line: name, GPU memory in GB, replicas. Memory gets 30% headroom for KV cache.</div>' +
2275
2284
  '<div class="ctl"><textarea data-pl="migText" rows="6" style="width:100%;font-family:var(--font-mono);font-size:12px">' + esc(PL.migText) + '</textarea></div>' +
@@ -2312,9 +2321,10 @@ function optCard(A) {
2312
2321
  function capCard(A) {
2313
2322
  const r = A.res, M = r.months, W = 980, H = 190, L = 56, k = 1000;
2314
2323
  const cum = key => { let c = 0; return M.map(x => (c += x[key])); };
2315
- const series = { rent: cum('rent'), reserved: cum('reserved'), hybrid: cum('hybrid') };
2324
+ const series = { rent: cum('rent'), reserved: cum('reserved'), blocks: cum('blocks'), spot: cum('spot'), hybrid: cum('hybrid') };
2316
2325
  const vmax = Math.max(...Object.values(series).map(a => a[a.length - 1])) * 1.05, X = m => L + (W - L - 10) * m / (M.length - 1), Y = v => 8 + (H - 30) * (1 - v / vmax);
2317
- const col = { rent: 'var(--crit)', reserved: 'var(--warn)', hybrid: 'var(--accent)' }, lab = { rent: 'Rent on demand', reserved: 'Reserve the base', hybrid: 'Buy the base, rent the peaks' };
2326
+ const col = { rent: 'var(--crit)', reserved: 'var(--warn)', blocks: 'var(--neo)', spot: 'var(--muted)', hybrid: 'var(--accent)' },
2327
+ lab = { rent: 'Rent on demand', reserved: 'Reserve the base', blocks: 'Reserve the base, capacity blocks for the peaks', spot: 'Reserve the base, spot for the peaks', hybrid: 'Buy the base, rent the peaks' };
2318
2328
  let svg = '<svg viewBox="0 0 ' + W + ' ' + H + '" style="width:100%;height:auto" role="img" aria-label="Cumulative cost by strategy">';
2319
2329
  for (const key in series) svg += '<path d="' + series[key].map((v, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(v).toFixed(1)).join('') + '" fill="none" stroke="' + col[key] + '" stroke-width="2"/>';
2320
2330
  for (let m = 0; m < M.length; m += 6) svg += '<text x="' + X(m) + '" y="' + (H - 6) + '" font-size="10" fill="var(--muted)" text-anchor="middle">month ' + m + '</text>';
@@ -2324,7 +2334,7 @@ function capCard(A) {
2324
2334
  (r.best === 'hybrid' ? 'Buying pays back against renting by month ' + (r.breakEven == null ? '—' : r.breakEven) + ', and leaves ' + fInt(r.ownedEnd) + ' GPUs worth about ' + fUsd(r.residual) + ' after depreciation.' : 'At these prices and growth, owning does not pay back within the horizon.') + '</p>' + svg +
2325
2335
  '<div class="glegend">' + Object.keys(series).map(key => '<span><i style="background:' + col[key] + '"></i>' + lab[key] + ': ' + fUsd(r.totals[key] / 1) + (key === 'hybrid' ? ' net of residual value (' + fUsd(r.totals.hybridCash) + ' cash)' : '') + '</span>').join('') + '</div>' +
2326
2336
  (orders.length ? '<h3 class="sec">On-prem orders</h3><ul class="plain">' + orders.map(o => '<li>' + o + '</li>').join('') + '</ul>' : '') +
2327
- '<div class="sub">Rough model: average utilisation from base and peak shares, power at ' + r.opt.kwPerGpu + ' kW per GPU and PUE ' + r.opt.pue + ', operations ' + fUsd(r.opt.opsPerGpuMonth) + ' per GPU-month. Not financial advice.</div>';
2337
+ '<div class="sub">Rough model: average utilisation from base and peak shares; capacity blocks bought in whole days (' + M[0].blockDays + ' a month), spot hours plus ' + fPct(r.opt.spotRework) + ' redone after interruptions; power at ' + r.opt.kwPerGpu + ' kW per GPU and PUE ' + r.opt.pue + ', operations ' + fUsd(r.opt.opsPerGpuMonth) + ' per GPU-month. Not financial advice.</div>';
2328
2338
  }
2329
2339
  function migCard(A) {
2330
2340
  const r = A.res;
@@ -1,3 +1,4 @@
1
+ /* global FleetScenario */ // set by scenario.js, loaded first on the page
1
2
  /* FleetScope Inference view: serving deployments as pods — replicas wanted vs ready, start-up time,
2
3
  and contention with training and batch work for GPUs. Browser only. */
3
4
  (function () {