github-actions[bot] commited on
Commit
9f8e391
·
1 Parent(s): b087c23

deploy: sync from GitHub 2026-10-07T03:30:20Z

Browse files
examples/model_insights/common.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared building blocks for the model-insights experiments.
2
+
3
+ `SPECS` is the model catalog. `load_shared_data` hydrates inference data,
4
+ training trace, and logistic fits. `build_scenario` wraps a list of
5
+ `(ModelDeployment, ReplicaSchedule)` pairs into a scenario dict that mirrors
6
+ the IEEE 13 preset (training overlay, replica ramp, tap schedule, OFO
7
+ config); pass `ScenarioOverrides` to deviate. `run_scenario` runs one
8
+ controller mode and returns voltage + performance stats.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import logging
15
+ import math
16
+ from dataclasses import dataclass, field
17
+ from fractions import Fraction
18
+ from pathlib import Path
19
+ from typing import Any, Literal
20
+
21
+ import numpy as np
22
+
23
+ from openg2g.controller.ofo import (
24
+ LogisticModelStore,
25
+ OFOBatchSizeController,
26
+ OFOConfig,
27
+ )
28
+ from openg2g.controller.tap_schedule import TapScheduleController
29
+ from openg2g.coordinator import Coordinator, SimulationLog
30
+ from openg2g.datacenter.config import (
31
+ DatacenterConfig,
32
+ InferenceModelSpec,
33
+ ModelDeployment,
34
+ PowerAugmentationConfig,
35
+ ReplicaSchedule,
36
+ TrainingRun,
37
+ )
38
+ from openg2g.datacenter.offline import OfflineDatacenter, OfflineWorkload
39
+ from openg2g.datacenter.workloads.inference import InferenceData
40
+ from openg2g.datacenter.workloads.training import TrainingTrace
41
+ from openg2g.grid.config import TapPosition, TapSchedule
42
+ from openg2g.grid.opendss import OpenDSSGrid
43
+ from openg2g.metrics.performance import PerformanceStats, compute_performance_stats
44
+ from openg2g.metrics.voltage import VoltageStats, compute_allbus_voltage_stats
45
+
46
+ from systems import SYSTEMS, tap
47
+
48
+ logger = logging.getLogger("model_insights")
49
+
50
+ # IEEE 13 scenario preset. Do not tweak per experiment.
51
+
52
+ DT_DC = Fraction(1, 10)
53
+ DT_GRID = Fraction(1, 10)
54
+ DT_CTRL = Fraction(1)
55
+ V_MIN = 0.95
56
+ V_MAX = 1.05
57
+ TOTAL_DURATION_S = 3600
58
+ POWER_AUG = PowerAugmentationConfig(amplitude_scale_range=(0.98, 1.02), noise_fraction=0.005)
59
+
60
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
61
+
62
+
63
+ # Model specifications catalog. Each entry binds a simulation label to an
64
+ # `InferenceModelSpec`. The HuggingFace `model_id` is matched against
65
+ # ML.ENERGY benchmark runs; `feasible_batch_sizes` is the OFO-allowed subset
66
+ # of `batch_sizes`.
67
+
68
+
69
+ def _spec(
70
+ label: str,
71
+ model_id: str,
72
+ *,
73
+ gpu_model: str,
74
+ task: str,
75
+ precision: str = "bfloat16",
76
+ gpus_per_replica: int = 1,
77
+ tensor_parallel: int | None = None,
78
+ expert_parallel: int = 1,
79
+ itl_deadline_s: float,
80
+ batch_sizes: tuple[int, ...],
81
+ feasible_batch_sizes: tuple[int, ...] | None = None,
82
+ ) -> InferenceModelSpec:
83
+ return InferenceModelSpec(
84
+ model_label=label,
85
+ model_id=model_id,
86
+ gpu_model=gpu_model,
87
+ task=task,
88
+ precision=precision,
89
+ gpus_per_replica=gpus_per_replica,
90
+ tensor_parallel=tensor_parallel if tensor_parallel is not None else gpus_per_replica,
91
+ expert_parallel=expert_parallel,
92
+ itl_deadline_s=itl_deadline_s,
93
+ batch_sizes=batch_sizes,
94
+ feasible_batch_sizes=feasible_batch_sizes,
95
+ )
96
+
97
+
98
+ SPECS: dict[str, InferenceModelSpec] = {
99
+ # Llama 3.1
100
+ "Llama-3.1-70B": _spec(
101
+ "Llama-3.1-70B",
102
+ "meta-llama/Llama-3.1-70B-Instruct",
103
+ gpu_model="H100",
104
+ task="lm-arena-chat",
105
+ gpus_per_replica=4,
106
+ itl_deadline_s=0.10,
107
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256, 384, 512, 768, 1024),
108
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024),
109
+ ),
110
+ "Llama-3.1-405B": _spec(
111
+ "Llama-3.1-405B",
112
+ "meta-llama/Llama-3.1-405B-Instruct-FP8",
113
+ gpu_model="H100",
114
+ task="lm-arena-chat",
115
+ precision="fp8",
116
+ gpus_per_replica=8,
117
+ itl_deadline_s=0.12,
118
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256),
119
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256),
120
+ ),
121
+ # Qwen 3 dense
122
+ "Qwen3-8B": _spec(
123
+ "Qwen3-8B",
124
+ "Qwen/Qwen3-8B",
125
+ gpu_model="H100",
126
+ task="lm-arena-chat",
127
+ gpus_per_replica=1,
128
+ itl_deadline_s=0.08,
129
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256, 384, 512),
130
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512),
131
+ ),
132
+ "Qwen3-8B-B200": _spec(
133
+ "Qwen3-8B-B200",
134
+ "Qwen/Qwen3-8B",
135
+ gpu_model="B200",
136
+ task="lm-arena-chat",
137
+ gpus_per_replica=1,
138
+ itl_deadline_s=0.08,
139
+ batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 1536),
140
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 1536),
141
+ ),
142
+ "Qwen3-32B-1GPU-H100": _spec(
143
+ "Qwen3-32B-1GPU-H100",
144
+ "Qwen/Qwen3-32B",
145
+ gpu_model="H100",
146
+ task="lm-arena-chat",
147
+ gpus_per_replica=1,
148
+ itl_deadline_s=0.10,
149
+ batch_sizes=(8, 16, 32),
150
+ feasible_batch_sizes=(8, 16, 32),
151
+ ),
152
+ "Qwen3-32B-1GPU-B200": _spec(
153
+ "Qwen3-32B-1GPU-B200",
154
+ "Qwen/Qwen3-32B",
155
+ gpu_model="B200",
156
+ task="lm-arena-chat",
157
+ gpus_per_replica=1,
158
+ itl_deadline_s=0.10,
159
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256, 384, 512),
160
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512),
161
+ ),
162
+ # Qwen 3 30B A3B Instruct (MoE)
163
+ "Qwen3-30B-A3B-Instruct-1GPU": _spec(
164
+ "Qwen3-30B-A3B-Instruct-1GPU",
165
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
166
+ gpu_model="H100",
167
+ task="lm-arena-chat",
168
+ gpus_per_replica=1,
169
+ itl_deadline_s=0.10,
170
+ batch_sizes=(8, 16, 32, 64, 96),
171
+ feasible_batch_sizes=(8, 16, 32, 64, 96),
172
+ ),
173
+ "Qwen3-30B-A3B-Instruct-2GPU": _spec(
174
+ "Qwen3-30B-A3B-Instruct-2GPU",
175
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
176
+ gpu_model="H100",
177
+ task="lm-arena-chat",
178
+ gpus_per_replica=2,
179
+ itl_deadline_s=0.10,
180
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256, 384, 512, 768, 1024),
181
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024),
182
+ ),
183
+ "Qwen3-30B-A3B-Instruct-1GPU-B200": _spec(
184
+ "Qwen3-30B-A3B-Instruct-1GPU-B200",
185
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
186
+ gpu_model="B200",
187
+ task="lm-arena-chat",
188
+ gpus_per_replica=1,
189
+ itl_deadline_s=0.10,
190
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256),
191
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256),
192
+ ),
193
+ # Qwen 3 235B A22B Instruct (MoE)
194
+ "Qwen3-235B-A22B-Instruct-FP8-8GPU": _spec(
195
+ "Qwen3-235B-A22B-Instruct-FP8-8GPU",
196
+ "Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
197
+ gpu_model="H100",
198
+ task="lm-arena-chat",
199
+ precision="fp8",
200
+ gpus_per_replica=8,
201
+ itl_deadline_s=0.14,
202
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256, 384, 512),
203
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512),
204
+ ),
205
+ "Qwen3-235B-A22B-Instruct-8GPU": _spec(
206
+ "Qwen3-235B-A22B-Instruct-8GPU",
207
+ "Qwen/Qwen3-235B-A22B-Instruct-2507",
208
+ gpu_model="H100",
209
+ task="lm-arena-chat",
210
+ gpus_per_replica=8,
211
+ itl_deadline_s=0.14,
212
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256),
213
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256),
214
+ ),
215
+ "Qwen3-235B-A22B-Instruct-8GPU-B200": _spec(
216
+ "Qwen3-235B-A22B-Instruct-8GPU-B200",
217
+ "Qwen/Qwen3-235B-A22B-Instruct-2507",
218
+ gpu_model="B200",
219
+ task="lm-arena-chat",
220
+ gpus_per_replica=8,
221
+ itl_deadline_s=0.14,
222
+ batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 1536, 2048, 4096),
223
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 1536, 2048),
224
+ ),
225
+ # Qwen 3 235B A22B Thinking (MoE, reasoning)
226
+ "Qwen3-235B-A22B-Thinking-8GPU": _spec(
227
+ "Qwen3-235B-A22B-Thinking-8GPU",
228
+ "Qwen/Qwen3-235B-A22B-Thinking-2507",
229
+ gpu_model="H100",
230
+ task="gpqa",
231
+ gpus_per_replica=8,
232
+ itl_deadline_s=0.14,
233
+ batch_sizes=(8, 16, 32),
234
+ feasible_batch_sizes=(8, 16, 32),
235
+ ),
236
+ "Qwen3-235B-A22B-Thinking-FP8-8GPU": _spec(
237
+ "Qwen3-235B-A22B-Thinking-FP8-8GPU",
238
+ "Qwen/Qwen3-235B-A22B-Thinking-2507-FP8",
239
+ gpu_model="H100",
240
+ task="gpqa",
241
+ precision="fp8",
242
+ gpus_per_replica=8,
243
+ itl_deadline_s=0.14,
244
+ batch_sizes=(8, 16, 32, 64, 96, 128),
245
+ feasible_batch_sizes=(8, 16, 32, 64, 96, 128),
246
+ ),
247
+ "Qwen3-235B-A22B-Thinking-4GPU-B200": _spec(
248
+ "Qwen3-235B-A22B-Thinking-4GPU-B200",
249
+ "Qwen/Qwen3-235B-A22B-Thinking-2507",
250
+ gpu_model="B200",
251
+ task="gpqa",
252
+ gpus_per_replica=4,
253
+ itl_deadline_s=0.20,
254
+ batch_sizes=(8, 16, 32, 64, 128, 256),
255
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256),
256
+ ),
257
+ "Qwen3-235B-A22B-Thinking-8GPU-B200": _spec(
258
+ "Qwen3-235B-A22B-Thinking-8GPU-B200",
259
+ "Qwen/Qwen3-235B-A22B-Thinking-2507",
260
+ gpu_model="B200",
261
+ task="gpqa",
262
+ gpus_per_replica=8,
263
+ itl_deadline_s=0.20,
264
+ batch_sizes=(8, 16, 32, 64, 128, 256, 384, 512, 768),
265
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 384, 512, 768),
266
+ ),
267
+ "Qwen3-235B-A22B-Thinking-FP8-4GPU-B200": _spec(
268
+ "Qwen3-235B-A22B-Thinking-FP8-4GPU-B200",
269
+ "Qwen/Qwen3-235B-A22B-Thinking-2507-FP8",
270
+ gpu_model="B200",
271
+ task="gpqa",
272
+ precision="fp8",
273
+ gpus_per_replica=4,
274
+ itl_deadline_s=0.14,
275
+ batch_sizes=(8, 16, 32, 64, 128, 256, 384, 512),
276
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 384, 512),
277
+ ),
278
+ # GPT-OSS 120B (MoE, mxfp4)
279
+ "GPT-OSS-120B-H100-2GPU": _spec(
280
+ "GPT-OSS-120B-H100-2GPU",
281
+ "openai/gpt-oss-120b",
282
+ gpu_model="H100",
283
+ task="gpqa",
284
+ precision="mxfp4",
285
+ gpus_per_replica=2,
286
+ itl_deadline_s=0.10,
287
+ batch_sizes=(8, 16, 32, 64, 96, 128, 192, 256),
288
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256),
289
+ ),
290
+ "GPT-OSS-120B-B200-1GPU": _spec(
291
+ "GPT-OSS-120B-B200-1GPU",
292
+ "openai/gpt-oss-120b",
293
+ gpu_model="B200",
294
+ task="gpqa",
295
+ precision="mxfp4",
296
+ gpus_per_replica=1,
297
+ itl_deadline_s=0.10,
298
+ batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072),
299
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024),
300
+ ),
301
+ "GPT-OSS-120B-B200-2GPU": _spec(
302
+ "GPT-OSS-120B-B200-2GPU",
303
+ "openai/gpt-oss-120b",
304
+ gpu_model="B200",
305
+ task="gpqa",
306
+ precision="mxfp4",
307
+ gpus_per_replica=2,
308
+ itl_deadline_s=0.10,
309
+ batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072, 4096),
310
+ feasible_batch_sizes=(8, 16, 32, 64, 128, 256, 512, 1024),
311
+ ),
312
+ }
313
+
314
+
315
+ # Data pipeline: per-spec content-addressed cache (see InferenceModelSpec.cache_hash)
316
+
317
+ SPECS_CACHE_DIR = _PROJECT_ROOT / "data" / "specs"
318
+ TRAINING_TRACE_PATH = _PROJECT_ROOT / "data" / "training_trace.csv"
319
+
320
+
321
+ @dataclass
322
+ class SharedData:
323
+ inference_data: InferenceData
324
+ logistic_models: LogisticModelStore
325
+ training_trace: TrainingTrace | None
326
+ data_dir: Path
327
+
328
+
329
+ def load_shared_data(*, specs_used: tuple[InferenceModelSpec, ...] | None = None) -> SharedData:
330
+ """Load / generate the data backing all model-insights experiments.
331
+
332
+ Triggers the ML.ENERGY download the first time it runs; subsequent calls
333
+ hit the per-spec content-addressed cache.
334
+
335
+ Args:
336
+ specs_used: Subset of specs to materialize. When `None`, loads the
337
+ full SPECS catalog.
338
+ """
339
+ if specs_used is None:
340
+ specs_used = tuple(SPECS.values())
341
+ SPECS_CACHE_DIR.mkdir(parents=True, exist_ok=True)
342
+
343
+ logger.info("Model-insights specs cache: %s (%d specs)", SPECS_CACHE_DIR, len(specs_used))
344
+ inference_data = InferenceData.ensure(SPECS_CACHE_DIR, specs_used, plot=False, dt_s=float(DT_DC))
345
+ training_trace = TrainingTrace.ensure(TRAINING_TRACE_PATH)
346
+ logistic_models = LogisticModelStore.ensure(SPECS_CACHE_DIR, specs_used, plot=False)
347
+ return SharedData(inference_data, logistic_models, training_trace, SPECS_CACHE_DIR)
348
+
349
+
350
+ # Scenario factory
351
+
352
+
353
+ _IEEE13_OFO_CONFIG = OFOConfig(
354
+ primal_step_size=0.1,
355
+ w_throughput=0.001,
356
+ w_switch=1.0,
357
+ voltage_gradient_scale=1e6,
358
+ v_min=V_MIN,
359
+ v_max=V_MAX,
360
+ voltage_dual_step_size=1.0,
361
+ latency_dual_step_size=1.0,
362
+ sensitivity_update_interval=3600,
363
+ sensitivity_perturbation_kw=100.0,
364
+ )
365
+
366
+ _IEEE13_TAP_SCHEDULE = TapSchedule(
367
+ (
368
+ (1500, TapPosition(regulators={"creg1a": tap(16), "creg1b": tap(6), "creg1c": tap(17)})),
369
+ (3300, TapPosition(regulators={"creg1a": tap(10), "creg1b": tap(6), "creg1c": tap(10)})),
370
+ )
371
+ )
372
+
373
+
374
+ @dataclass
375
+ class ScenarioOverrides:
376
+ """Per-experiment deviations from the IEEE 13 preset.
377
+
378
+ Each `None` field inherits the preset; set a field to deviate.
379
+ """
380
+
381
+ ofo_config: OFOConfig | None = None
382
+ training_n_gpus: int | None = None # None = 2400, 0 = disable training overlay
383
+ ramp_factor: float | None = None # None = 0.5 (ramp to 50% of initial replicas)
384
+ enable_tap_schedule: bool = True
385
+ total_gpu_capacity: int | None = None # None = 7200
386
+ base_kw_per_phase: float | None = None # None = 500.0
387
+ seed: int = 0
388
+
389
+
390
+ def build_scenario(
391
+ deployments: list[tuple[ModelDeployment, ReplicaSchedule]],
392
+ *,
393
+ shared: SharedData,
394
+ overrides: ScenarioOverrides | None = None,
395
+ ) -> dict:
396
+ """Build the IEEE 13 scenario around a custom model deployment."""
397
+ overrides = overrides or ScenarioOverrides()
398
+ sys = SYSTEMS["ieee13"]()
399
+
400
+ models = tuple(m for m, _ in deployments)
401
+ specs = tuple(m.spec for m in models)
402
+ raw_schedules = {m.spec.model_label: s for m, s in deployments}
403
+
404
+ ramp_factor = 0.5 if overrides.ramp_factor is None else overrides.ramp_factor
405
+ replica_schedules: dict[str, ReplicaSchedule] = {}
406
+ for label, sched in raw_schedules.items():
407
+ if len(sched) > 0: # caller already set a ramp; take it as-is
408
+ replica_schedules[label] = sched
409
+ else:
410
+ target = max(1, int(round(sched.initial * ramp_factor)))
411
+ replica_schedules[label] = sched.ramp_to(target, t_start=2500.0, t_end=3000.0)
412
+
413
+ training_n_gpus = 2400 if overrides.training_n_gpus is None else overrides.training_n_gpus
414
+ training = (
415
+ TrainingRun(n_gpus=training_n_gpus, trace=shared.training_trace, target_peak_W_per_gpu=400.0).at(
416
+ t_start=1000.0, t_end=2000.0
417
+ )
418
+ if (shared.training_trace is not None and training_n_gpus > 0)
419
+ else None
420
+ )
421
+
422
+ site_inference = shared.inference_data.filter_models(specs)
423
+ workload_kwargs: dict[str, Any] = {
424
+ "inference_data": site_inference,
425
+ "replica_schedules": replica_schedules,
426
+ "initial_batch_sizes": {m.spec.model_label: m.initial_batch_size for m in models},
427
+ }
428
+ if training is not None:
429
+ workload_kwargs["training"] = training
430
+
431
+ total_gpu_capacity = 7200 if overrides.total_gpu_capacity is None else overrides.total_gpu_capacity
432
+ base_kw_per_phase = 500.0 if overrides.base_kw_per_phase is None else overrides.base_kw_per_phase
433
+
434
+ dc = OfflineDatacenter(
435
+ DatacenterConfig(gpus_per_server=8, base_kw_per_phase=base_kw_per_phase),
436
+ OfflineWorkload(**workload_kwargs),
437
+ name="default",
438
+ dt_s=DT_DC,
439
+ seed=overrides.seed,
440
+ power_augmentation=POWER_AUG,
441
+ total_gpu_capacity=total_gpu_capacity,
442
+ )
443
+
444
+ grid = OpenDSSGrid(
445
+ dss_case_dir=sys["dss_case_dir"],
446
+ dss_master_file=sys["dss_master_file"],
447
+ source_pu=sys["source_pu"],
448
+ dt_s=DT_GRID,
449
+ initial_tap_position=sys["initial_taps"],
450
+ exclude_buses=sys["exclude_buses"],
451
+ )
452
+ grid.attach_dc(dc, bus="671")
453
+
454
+ return dict(
455
+ datacenters=[dc],
456
+ dc_info={
457
+ dc: {"specs": specs, "initial_batch_sizes": {m.spec.model_label: m.initial_batch_size for m in models}}
458
+ },
459
+ grid=grid,
460
+ ofo_config=overrides.ofo_config or _IEEE13_OFO_CONFIG,
461
+ tap_schedule=_IEEE13_TAP_SCHEDULE if overrides.enable_tap_schedule else None,
462
+ generators=[],
463
+ time_varying_loads=[],
464
+ zones=None,
465
+ exclude_buses=tuple(sys["exclude_buses"]),
466
+ )
467
+
468
+
469
+ # Runner
470
+
471
+
472
+ Mode = Literal["baseline-no-tap", "baseline-tap-change", "ofo-no-tap", "ofo-tap-change"]
473
+
474
+
475
+ @dataclass
476
+ class VariantResult:
477
+ mode: Mode
478
+ voltage: VoltageStats
479
+ performance: PerformanceStats
480
+ log: SimulationLog | None = field(default=None, repr=False)
481
+
482
+
483
+ def run_scenario(
484
+ scenario: dict,
485
+ logistic_models: LogisticModelStore,
486
+ *,
487
+ mode: Mode,
488
+ total_duration_s: int = TOTAL_DURATION_S,
489
+ ) -> VariantResult:
490
+ """Run one mode against a built scenario. Returns voltage + performance stats."""
491
+ datacenters = scenario["datacenters"]
492
+ dc_info = scenario["dc_info"]
493
+ grid = scenario["grid"]
494
+ ofo_config = scenario["ofo_config"]
495
+ tap_schedule = scenario["tap_schedule"] if "tap_change" in mode else None
496
+ exclude_buses = scenario["exclude_buses"]
497
+
498
+ controllers: list[Any] = [
499
+ TapScheduleController(
500
+ schedule=tap_schedule if tap_schedule is not None else TapSchedule(()),
501
+ dt_s=DT_CTRL,
502
+ ),
503
+ ]
504
+ if mode.startswith("ofo") and ofo_config is not None:
505
+ for dc, info in dc_info.items():
506
+ controllers.append(
507
+ OFOBatchSizeController(
508
+ info["specs"],
509
+ datacenter=dc,
510
+ models=logistic_models,
511
+ config=ofo_config,
512
+ dt_s=DT_CTRL,
513
+ initial_batch_sizes=info["initial_batch_sizes"],
514
+ grid=grid,
515
+ )
516
+ )
517
+
518
+ coord = Coordinator(
519
+ datacenters=datacenters,
520
+ grid=grid,
521
+ controllers=controllers,
522
+ total_duration_s=total_duration_s,
523
+ )
524
+ log = coord.run()
525
+
526
+ vstats = compute_allbus_voltage_stats(log.grid_states, v_min=V_MIN, v_max=V_MAX, exclude_buses=exclude_buses)
527
+ itl_deadlines: dict[str, float] = {}
528
+ for info in dc_info.values():
529
+ for ms in info["specs"]:
530
+ itl_deadlines[ms.model_label] = ms.itl_deadline_s
531
+ pstats = compute_performance_stats(log.dc_states, itl_deadline_s_by_model=itl_deadlines)
532
+
533
+ return VariantResult(
534
+ mode=mode,
535
+ voltage=vstats,
536
+ performance=pstats,
537
+ log=log,
538
+ )
539
+
540
+
541
+ # Achievable power range
542
+
543
+
544
+ def compute_achievable_power_range(
545
+ *,
546
+ deployments: list[tuple[ModelDeployment, ReplicaSchedule]],
547
+ logistic_models: LogisticModelStore,
548
+ at_t_s: float = 0.0,
549
+ ) -> float:
550
+ """Per-variant controller-free power-flexibility metric (MW).
551
+
552
+ For each deployment, evaluates the per-replica power fit at the min and
553
+ max feasible batch sizes, scales by the active replica count at
554
+ `at_t_s` (defaults to the initial replica count), and sums across
555
+ models. Returns the difference between the resulting max and min total
556
+ DC power.
557
+
558
+ The logistic is fit to `avg_power_watts`, the per-run average power for
559
+ the full `num_gpus` bench configuration: `model.eval(batch)` already
560
+ covers the whole replica, so do NOT multiply by `gpus_per_replica`.
561
+ """
562
+ total_max_w = 0.0
563
+ total_min_w = 0.0
564
+ for deployment, schedule in deployments:
565
+ spec = deployment.spec
566
+ fit = logistic_models.power(spec.model_label)
567
+ feasible = sorted(spec.feasible_batch_sizes)
568
+ b_lo, b_hi = feasible[0], feasible[-1]
569
+ p_lo = float(fit.eval(b_lo))
570
+ p_hi = float(fit.eval(b_hi))
571
+ n = schedule.count_at(at_t_s)
572
+ total_min_w += p_lo * n
573
+ total_max_w += p_hi * n
574
+ return (total_max_w - total_min_w) / 1e6
575
+
576
+
577
+ def compute_matched_peak_replicas(
578
+ spec: InferenceModelSpec,
579
+ target_peak_kw: float,
580
+ logistic_models: LogisticModelStore,
581
+ ) -> int:
582
+ """Replica count whose peak inference power matches `target_peak_kw`.
583
+
584
+ Peak is evaluated at `max(spec.feasible_batch_sizes)` using the logistic
585
+ power fit. Returns `ceil(target_peak_kw * 1e3 / per-replica-peak-w)`,
586
+ floored at 1. Use this to compare variants on a fixed peak DC-footprint
587
+ budget when GPU counts per replica differ.
588
+
589
+ Args:
590
+ spec: The model spec: `feasible_batch_sizes` must already be capped
591
+ to batches that meet the SLO; pass the output of
592
+ `restrict_spec_by_deadline` if an SLO is in play.
593
+ target_peak_kw: Target peak inference power in kW.
594
+ logistic_models: Populated `LogisticModelStore` covering
595
+ `spec.model_label`.
596
+ """
597
+ per_rep_w = float(logistic_models.power(spec.model_label).eval(max(spec.feasible_batch_sizes)))
598
+ if per_rep_w <= 0:
599
+ raise ValueError(f"non-positive peak power for {spec.model_label}: {per_rep_w}")
600
+ return max(1, math.ceil(target_peak_kw * 1e3 / per_rep_w))
601
+
602
+
603
+ def compute_pareto_curve(
604
+ deployment: tuple[ModelDeployment, ReplicaSchedule],
605
+ logistic_models: LogisticModelStore,
606
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
607
+ """Return `(batches, power_MW, throughput_Mtps)` for one deployment.
608
+
609
+ Power and throughput come from the logistic fits, evaluated at every
610
+ `spec.feasible_batch_sizes` and scaled by the schedule's initial replica
611
+ count.
612
+ """
613
+ spec = deployment[0].spec
614
+ n = deployment[1].initial
615
+ batches = np.array(sorted(spec.feasible_batch_sizes), dtype=int)
616
+ p_fit = logistic_models.power(spec.model_label)
617
+ t_fit = logistic_models.throughput(spec.model_label)
618
+ p_mw = np.array([float(p_fit.eval(int(b))) * n / 1e6 for b in batches])
619
+ t_mtps = np.array([float(t_fit.eval(int(b))) * n / 1e6 for b in batches])
620
+ return batches, p_mw, t_mtps
621
+
622
+
623
+ # Convenience
624
+
625
+
626
+ def deploy(
627
+ label: str,
628
+ num_replicas: int,
629
+ *,
630
+ initial_batch_size: int | None = None,
631
+ ) -> tuple[ModelDeployment, ReplicaSchedule]:
632
+ """Shorthand for `(ModelDeployment, ReplicaSchedule(initial=...))`.
633
+
634
+ `initial_batch_size=None` (the default) starts the scenario at the
635
+ largest feasible batch: i.e., maximum DC power stress, leaving the
636
+ controller full downward range.
637
+
638
+ Args:
639
+ label: Key into `SPECS`.
640
+ num_replicas: Initial replica count for the schedule.
641
+ initial_batch_size: Starting batch.
642
+ """
643
+ spec = SPECS[label]
644
+ feasible_batch_sizes = spec.feasible_batch_sizes
645
+ if feasible_batch_sizes is None:
646
+ raise ValueError(f"{label} has no feasible_batch_sizes")
647
+ feasible = sorted(feasible_batch_sizes)
648
+ if initial_batch_size is None:
649
+ initial_batch_size = feasible[-1]
650
+ elif initial_batch_size not in feasible_batch_sizes:
651
+ initial_batch_size = (
652
+ max(b for b in feasible if b <= initial_batch_size) if feasible[0] <= initial_batch_size else feasible[0]
653
+ )
654
+ return (
655
+ ModelDeployment(spec=spec, initial_batch_size=initial_batch_size),
656
+ ReplicaSchedule(initial=num_replicas),
657
+ )
658
+
659
+
660
+ def max_feasible_batch_under_deadline(
661
+ spec: InferenceModelSpec,
662
+ logistic_models: LogisticModelStore,
663
+ deadline_s: float,
664
+ ) -> int:
665
+ """Largest element of `spec.feasible_batch_sizes` whose predicted ITL
666
+ (from the logistic latency fit) stays at or under `deadline_s`.
667
+
668
+ Returns the smallest feasible batch if no batch meets the deadline.
669
+ """
670
+ lat_fit = logistic_models.latency(spec.model_label)
671
+ feasible = sorted(spec.feasible_batch_sizes)
672
+ for b in reversed(feasible):
673
+ if float(lat_fit.eval(b)) <= deadline_s:
674
+ return b
675
+ return feasible[0]
676
+
677
+
678
+ def restrict_spec_by_deadline(
679
+ spec: InferenceModelSpec,
680
+ logistic_models: LogisticModelStore,
681
+ deadline_s: float,
682
+ ) -> InferenceModelSpec:
683
+ """Return a copy of `spec` with `feasible_batch_sizes` capped so every
684
+ remaining batch yields predicted ITL ≤ `deadline_s`, and with
685
+ `itl_deadline_s` set to `deadline_s`.
686
+ """
687
+ lat_fit = logistic_models.latency(spec.model_label)
688
+ capped = tuple(b for b in sorted(spec.feasible_batch_sizes) if float(lat_fit.eval(b)) <= deadline_s)
689
+ if not capped:
690
+ capped = (min(spec.feasible_batch_sizes),)
691
+ return spec.model_copy(update={"feasible_batch_sizes": capped, "itl_deadline_s": deadline_s})
692
+
693
+
694
+ def write_csv(rows: list[Any], path: Path) -> None:
695
+ """Write a list of dataclass instances to CSV; columns come from the first row's fields."""
696
+ fields = list(rows[0].__dataclass_fields__.keys())
697
+ with open(path, "w", newline="") as f:
698
+ writer = csv.DictWriter(f, fieldnames=fields)
699
+ writer.writeheader()
700
+ for r in rows:
701
+ writer.writerow({k: getattr(r, k) for k in fields})
examples/model_insights/hardware.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """H100 → B200 hardware-upgrade sweep on the IEEE 13 scenario.
2
+
3
+ Paired (model, parallelism) variants measured on both H100 and B200 at
4
+ the same DC footprint. The simulator only tracks an active-GPU count;
5
+ per-replica power and ITL come from hardware-specific logistic fits in
6
+ `LogisticModelStore`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ import common as aic
17
+ import tyro
18
+
19
+ from openg2g.datacenter.config import ModelDeployment, ReplicaSchedule
20
+
21
+ logger = logging.getLogger("model_insights.hardware")
22
+
23
+
24
+ # (pair_label, spec_label, hardware_label, role).
25
+ # `role="anchor"` runs at `ANCHOR_REPLICAS` active GPUs. `role="match-peak"`
26
+ # sizes replicas so peak inference power at the variant's max-feasible-
27
+ # under-SLO batch matches the anchor's peak.
28
+ PAIRS: list[tuple[str, str, str, str]] = [
29
+ ("qwen-8b-1gpu", "Qwen3-8B", "H100", "anchor"),
30
+ ("qwen-8b-1gpu", "Qwen3-8B-B200", "B200", "match-peak"),
31
+ ("qwen-32b-1gpu", "Qwen3-32B-1GPU-H100", "H100", "anchor"),
32
+ ("qwen-32b-1gpu", "Qwen3-32B-1GPU-B200", "B200", "match-peak"),
33
+ ("qwen-30b-a3b-instruct-1gpu", "Qwen3-30B-A3B-Instruct-1GPU", "H100", "anchor"),
34
+ ("qwen-30b-a3b-instruct-1gpu", "Qwen3-30B-A3B-Instruct-1GPU-B200", "B200", "match-peak"),
35
+ ]
36
+
37
+
38
+ ANCHOR_REPLICAS: int = 4800
39
+ COMMON_DEADLINE_MS: int = 50
40
+ DEFAULT_MODES: tuple[aic.Mode, ...] = ("baseline-no-tap", "ofo-no-tap")
41
+ DEFAULT_OUT = Path(__file__).resolve().parent / "outputs" / "hardware_b200.csv"
42
+
43
+
44
+ @dataclass
45
+ class Row:
46
+ experiment: str
47
+ variant: str
48
+ pair: str
49
+ hardware: str
50
+ role: str
51
+ mode: str
52
+ seed: int
53
+ num_replicas: int
54
+ gpus_per_replica: int
55
+ feasible_batch_min: int
56
+ feasible_batch_max: int
57
+ initial_batch: int
58
+ peak_inference_kw: float
59
+ violation_time_s: float
60
+ integral_violation_pu_s: float
61
+ worst_vmin: float
62
+ worst_vmax: float
63
+ mean_throughput_tps: float
64
+ integrated_throughput_tokens: float
65
+ itl_deadline_fraction: float
66
+ achievable_power_range_mw: float
67
+
68
+
69
+ def _peak_inference_kw(spec, n_replicas, logistic_models) -> float:
70
+ fit = logistic_models.power(spec.model_label)
71
+ return float(fit.eval(max(spec.feasible_batch_sizes))) * n_replicas / 1e3
72
+
73
+
74
+ def _resolve_replicas(spec, role: str, anchor_peak_kw: float | None, logistic_models) -> int:
75
+ if role == "anchor":
76
+ return ANCHOR_REPLICAS
77
+ if role == "match-peak":
78
+ if anchor_peak_kw is None:
79
+ raise ValueError("match-peak role requires an anchor peak first")
80
+ return aic.compute_matched_peak_replicas(spec, anchor_peak_kw, logistic_models)
81
+ raise ValueError(f"unknown role: {role}")
82
+
83
+
84
+ def run_variant(
85
+ pair: str,
86
+ spec_label: str,
87
+ hardware: str,
88
+ role: str,
89
+ *,
90
+ anchor_peak_kw: float | None,
91
+ seed: int,
92
+ shared: aic.SharedData,
93
+ modes: tuple[aic.Mode, ...],
94
+ total_duration_s: int,
95
+ deadline_ms: int,
96
+ ) -> tuple[list[Row], float]:
97
+ base = aic.SPECS[spec_label]
98
+ spec = aic.restrict_spec_by_deadline(base, shared.logistic_models, deadline_ms / 1000.0)
99
+ num_replicas = _resolve_replicas(spec, role, anchor_peak_kw, shared.logistic_models)
100
+ deployments = [
101
+ (
102
+ ModelDeployment(spec=spec, initial_batch_size=max(spec.feasible_batch_sizes)),
103
+ ReplicaSchedule(initial=num_replicas),
104
+ )
105
+ ]
106
+ peak_kw = _peak_inference_kw(spec, num_replicas, shared.logistic_models)
107
+
108
+ apr_mw = aic.compute_achievable_power_range(deployments=deployments, logistic_models=shared.logistic_models)
109
+
110
+ scenario = aic.build_scenario(deployments, shared=shared, overrides=aic.ScenarioOverrides(seed=seed))
111
+
112
+ rows: list[Row] = []
113
+ for mode in modes:
114
+ result = aic.run_scenario(scenario, shared.logistic_models, mode=mode, total_duration_s=total_duration_s)
115
+ rows.append(
116
+ Row(
117
+ experiment="hardware",
118
+ variant=spec_label,
119
+ pair=pair,
120
+ hardware=hardware,
121
+ role=role,
122
+ mode=mode,
123
+ seed=seed,
124
+ num_replicas=num_replicas,
125
+ gpus_per_replica=spec.gpus_per_replica,
126
+ feasible_batch_min=min(spec.feasible_batch_sizes),
127
+ feasible_batch_max=max(spec.feasible_batch_sizes),
128
+ initial_batch=deployments[0][0].initial_batch_size,
129
+ peak_inference_kw=peak_kw,
130
+ violation_time_s=result.voltage.violation_time_s,
131
+ integral_violation_pu_s=result.voltage.integral_violation_pu_s,
132
+ worst_vmin=result.voltage.worst_vmin,
133
+ worst_vmax=result.voltage.worst_vmax,
134
+ mean_throughput_tps=result.performance.mean_throughput_tps,
135
+ integrated_throughput_tokens=result.performance.integrated_throughput_tokens,
136
+ itl_deadline_fraction=result.performance.itl_deadline_fraction,
137
+ achievable_power_range_mw=apr_mw,
138
+ )
139
+ )
140
+ logger.info(
141
+ " [%s %s seed=%d mode=%s] n_rep=%d peak=%.0fkW viol=%.2fs "
142
+ "integral=%.4f vmin=%.4f thpt=%.1fk tok/s itl_miss=%.2f%% APR=%.2f MW",
143
+ pair,
144
+ hardware,
145
+ seed,
146
+ mode,
147
+ num_replicas,
148
+ peak_kw,
149
+ result.voltage.violation_time_s,
150
+ result.voltage.integral_violation_pu_s,
151
+ result.voltage.worst_vmin,
152
+ result.performance.mean_throughput_tps / 1e3,
153
+ result.performance.itl_deadline_fraction * 100.0,
154
+ apr_mw,
155
+ )
156
+ return rows, peak_kw
157
+
158
+
159
+ def main(
160
+ seeds: tuple[int, ...] = (0, 1, 2, 3, 4),
161
+ total_duration_s: int = aic.TOTAL_DURATION_S,
162
+ modes: tuple[
163
+ Literal["baseline-no-tap", "baseline-tap-change", "ofo-no-tap", "ofo-tap-change"], ...
164
+ ] = DEFAULT_MODES,
165
+ deadline_ms: int = COMMON_DEADLINE_MS,
166
+ only_pair: str | None = None,
167
+ out: Path = DEFAULT_OUT,
168
+ ) -> None:
169
+ logging.basicConfig(
170
+ level=logging.INFO, format="%(asctime)s %(levelname)s [%(name)s] %(message)s", datefmt="%H:%M:%S"
171
+ )
172
+ logging.getLogger("httpx").setLevel(logging.WARNING)
173
+
174
+ shared = aic.load_shared_data()
175
+ out.parent.mkdir(parents=True, exist_ok=True)
176
+
177
+ pairs = [p for p in PAIRS if (only_pair is None or p[0] == only_pair)]
178
+ if not pairs:
179
+ raise ValueError(f"No pairs match filter: only_pair={only_pair}")
180
+
181
+ all_rows: list[Row] = []
182
+ anchor_peak_by_pair: dict[str, float] = {}
183
+ for pair, spec_label, hardware, role in pairs:
184
+ logger.info("=== pair=%s variant=%s (%s, role=%s) ===", pair, spec_label, hardware, role)
185
+ for seed in seeds:
186
+ anchor_peak = anchor_peak_by_pair.get(pair) if role == "match-peak" else None
187
+ rows, peak_kw = run_variant(
188
+ pair,
189
+ spec_label,
190
+ hardware,
191
+ role,
192
+ anchor_peak_kw=anchor_peak,
193
+ seed=seed,
194
+ shared=shared,
195
+ modes=modes,
196
+ total_duration_s=total_duration_s,
197
+ deadline_ms=deadline_ms,
198
+ )
199
+ if role == "anchor" and pair not in anchor_peak_by_pair:
200
+ anchor_peak_by_pair[pair] = peak_kw
201
+ all_rows.extend(rows)
202
+
203
+ aic.write_csv(all_rows, out)
204
+ logger.info("Wrote %d rows to %s", len(all_rows), out)
205
+
206
+
207
+ if __name__ == "__main__":
208
+ tyro.cli(main)
examples/model_insights/model_size.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model size and architecture sweep on the IEEE 13 scenario.
2
+
3
+ Runs a model ladder on both B200 and H100 (selectable via `--gpu`) and
4
+ writes one CSV per GPU (`model_size_b200.csv`, `model_size_h100.csv`).
5
+
6
+ Both `lm-arena-chat` and `gpqa` tasks are represented to cover chat and
7
+ reasoning workloads. Each variant uses a per-variant ITL deadline and a
8
+ pre-computed match-peak replica count so peak inference power at the
9
+ variant's largest feasible batch equals a shared 3.12 MW anchor (Qwen 3
10
+ 8B at 4,800 replicas on H100).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Literal
19
+
20
+ import common as aic
21
+ import tyro
22
+
23
+ from openg2g.datacenter.config import ModelDeployment, ReplicaSchedule
24
+
25
+ logger = logging.getLogger("model_insights.model_size")
26
+
27
+
28
+ # Variant catalogs, indexed by GPU. Each entry is
29
+ # (spec_label, num_replicas, deadline_ms); replica counts are match-peak
30
+ # sized to a 3.12 MW anchor (Qwen 3 8B at 4,800 replicas on H100).
31
+ VARIANTS_B200: list[tuple[str, int, int]] = [
32
+ ("Qwen3-8B-B200", 4326, 50), # 1 GPU, B200 BF16, lm-arena-chat
33
+ ("Qwen3-32B-1GPU-B200", 3361, 50), # 1 GPU, B200 BF16, lm-arena-chat
34
+ ("Qwen3-30B-A3B-Instruct-1GPU-B200", 3483, 50), # 1 GPU MoE, B200 BF16, lm-arena-chat
35
+ ("GPT-OSS-120B-B200-2GPU", 2092, 50), # 2 GPU, B200 MXFP4, gpqa (reasoning)
36
+ ("Qwen3-235B-A22B-Instruct-8GPU-B200", 632, 100), # 8 GPU MoE, B200 BF16, lm-arena-chat
37
+ ]
38
+
39
+ VARIANTS_H100: list[tuple[str, int, int]] = [
40
+ ("Qwen3-8B", 4800, 50), # 1 GPU, H100 BF16, lm-arena-chat (anchor)
41
+ ("Qwen3-32B-1GPU-H100", 5206, 50), # 1 GPU, H100 BF16, lm-arena-chat
42
+ ("GPT-OSS-120B-H100-2GPU", 2489, 50), # 2 GPU, H100 MXFP4, gpqa (reasoning)
43
+ ("Qwen3-235B-A22B-Instruct-8GPU", 773, 100), # 8 GPU MoE, H100 BF16, lm-arena-chat
44
+ ("Llama-3.1-70B", 1264, 100), # 4 GPU, H100 BF16, lm-arena-chat (H100-only)
45
+ ("Llama-3.1-405B", 637, 120), # 8 GPU, H100 FP8, lm-arena-chat (H100-only)
46
+ ]
47
+
48
+ VARIANTS_BY_GPU: dict[str, list[tuple[str, int, int]]] = {
49
+ "b200": VARIANTS_B200,
50
+ "h100": VARIANTS_H100,
51
+ }
52
+
53
+ DEFAULT_MODES: tuple[aic.Mode, ...] = ("baseline-no-tap", "ofo-no-tap")
54
+ DEFAULT_OUTDIR = Path(__file__).resolve().parent / "outputs"
55
+
56
+
57
+ @dataclass
58
+ class Row:
59
+ experiment: str
60
+ variant: str
61
+ mode: str
62
+ seed: int
63
+ num_replicas: int
64
+ gpus_per_replica: int
65
+ deadline_ms: int
66
+ feasible_batch_min: int
67
+ feasible_batch_max: int
68
+ initial_batch: int
69
+ violation_time_s: float
70
+ integral_violation_pu_s: float
71
+ worst_vmin: float
72
+ worst_vmax: float
73
+ mean_throughput_tps: float
74
+ integrated_throughput_tokens: float
75
+ itl_deadline_fraction: float
76
+ achievable_power_range_mw: float
77
+
78
+
79
+ def run_variant(
80
+ spec_label: str,
81
+ num_replicas: int,
82
+ *,
83
+ seed: int,
84
+ shared: aic.SharedData,
85
+ modes: tuple[aic.Mode, ...],
86
+ total_duration_s: int,
87
+ deadline_ms: int,
88
+ ) -> list[Row]:
89
+ base = aic.SPECS[spec_label]
90
+ spec = aic.restrict_spec_by_deadline(base, shared.logistic_models, deadline_ms / 1000.0)
91
+ deployments = [
92
+ (
93
+ ModelDeployment(spec=spec, initial_batch_size=max(spec.feasible_batch_sizes)),
94
+ ReplicaSchedule(initial=num_replicas),
95
+ )
96
+ ]
97
+
98
+ apr_mw = aic.compute_achievable_power_range(deployments=deployments, logistic_models=shared.logistic_models)
99
+
100
+ scenario = aic.build_scenario(deployments, shared=shared, overrides=aic.ScenarioOverrides(seed=seed))
101
+ rows: list[Row] = []
102
+ for mode in modes:
103
+ result = aic.run_scenario(scenario, shared.logistic_models, mode=mode, total_duration_s=total_duration_s)
104
+ rows.append(
105
+ Row(
106
+ experiment="model_size",
107
+ variant=spec_label,
108
+ mode=mode,
109
+ seed=seed,
110
+ num_replicas=num_replicas,
111
+ gpus_per_replica=spec.gpus_per_replica,
112
+ deadline_ms=deadline_ms,
113
+ feasible_batch_min=min(spec.feasible_batch_sizes),
114
+ feasible_batch_max=max(spec.feasible_batch_sizes),
115
+ initial_batch=deployments[0][0].initial_batch_size,
116
+ violation_time_s=result.voltage.violation_time_s,
117
+ integral_violation_pu_s=result.voltage.integral_violation_pu_s,
118
+ worst_vmin=result.voltage.worst_vmin,
119
+ worst_vmax=result.voltage.worst_vmax,
120
+ mean_throughput_tps=result.performance.mean_throughput_tps,
121
+ integrated_throughput_tokens=result.performance.integrated_throughput_tokens,
122
+ itl_deadline_fraction=result.performance.itl_deadline_fraction,
123
+ achievable_power_range_mw=apr_mw,
124
+ )
125
+ )
126
+ logger.info(
127
+ " [%s dl=%dms seed=%d mode=%s] viol=%.2fs integral=%.4f "
128
+ "vmin=%.4f thpt=%.1fk tok/s itl_miss=%.2f%% APR=%.2f MW",
129
+ spec_label,
130
+ deadline_ms,
131
+ seed,
132
+ mode,
133
+ result.voltage.violation_time_s,
134
+ result.voltage.integral_violation_pu_s,
135
+ result.voltage.worst_vmin,
136
+ result.performance.mean_throughput_tps / 1e3,
137
+ result.performance.itl_deadline_fraction * 100.0,
138
+ apr_mw,
139
+ )
140
+ return rows
141
+
142
+
143
+ def main(
144
+ seeds: tuple[int, ...] = (0, 1, 2, 3, 4),
145
+ total_duration_s: int = aic.TOTAL_DURATION_S,
146
+ modes: tuple[
147
+ Literal["baseline-no-tap", "baseline-tap-change", "ofo-no-tap", "ofo-tap-change"], ...
148
+ ] = DEFAULT_MODES,
149
+ gpu: Literal["both", "b200", "h100"] = "both",
150
+ override_deadline_ms: int | None = None,
151
+ only: tuple[str, ...] | None = None,
152
+ outdir: Path = DEFAULT_OUTDIR,
153
+ ) -> None:
154
+ """Run the model-size sweep on one or both GPU ladders.
155
+
156
+ Args:
157
+ seeds: seeds to run per variant.
158
+ total_duration_s: scenario duration; default is the master preset.
159
+ modes: which controller modes to evaluate per seed.
160
+ gpu: which GPU ladder(s) to run. Default runs both and writes one
161
+ CSV per GPU.
162
+ override_deadline_ms: when set, applies this deadline to every
163
+ variant (for ablation studies). When None, each variant uses
164
+ its VARIANTS-declared deadline.
165
+ only: subset of spec labels to run (default: all variants in the
166
+ selected ladders).
167
+ outdir: directory for per-GPU CSV outputs (`model_size_<gpu>.csv`).
168
+ """
169
+ logging.basicConfig(
170
+ level=logging.INFO, format="%(asctime)s %(levelname)s [%(name)s] %(message)s", datefmt="%H:%M:%S"
171
+ )
172
+ logging.getLogger("httpx").setLevel(logging.WARNING)
173
+ wanted_labels = {
174
+ "Llama-3.1-70B",
175
+ "Llama-3.1-405B",
176
+ "Qwen3-8B",
177
+ "Qwen3-8B-B200",
178
+ }
179
+ wanted_specs = tuple(aic.SPECS[label] for label in wanted_labels)
180
+ shared = aic.load_shared_data(specs_used=wanted_specs)
181
+ outdir.mkdir(parents=True, exist_ok=True)
182
+
183
+ #shared = aic.load_shared_data()
184
+
185
+
186
+
187
+ targets = ["b200", "h100"] if gpu == "both" else [gpu]
188
+ for gpu_tag in targets:
189
+ variants = [(label, n, d) for label, n, d in VARIANTS_BY_GPU[gpu_tag] if (only is None or label in only)]
190
+ if not variants:
191
+ logger.warning("No variants match filter for gpu=%s only=%s; skipping", gpu_tag, only)
192
+ continue
193
+ if override_deadline_ms is not None:
194
+ variants = [(label, n, override_deadline_ms) for label, n, _ in variants]
195
+ logger.info("override_deadline_ms=%d applied to every variant", override_deadline_ms)
196
+ logger.info(
197
+ "=== GPU=%s %d variants × %d seeds × %d modes on IEEE 13 ===",
198
+ gpu_tag.upper(),
199
+ len(variants),
200
+ len(seeds),
201
+ len(modes),
202
+ )
203
+
204
+ rows: list[Row] = []
205
+ for spec_label, n_replicas, deadline_ms in variants:
206
+ logger.info(" variant: %s × %d replicas @ %d ms", spec_label, n_replicas, deadline_ms)
207
+ for seed in seeds:
208
+ rows.extend(
209
+ run_variant(
210
+ spec_label,
211
+ n_replicas,
212
+ seed=seed,
213
+ shared=shared,
214
+ modes=modes,
215
+ total_duration_s=total_duration_s,
216
+ deadline_ms=deadline_ms,
217
+ )
218
+ )
219
+
220
+ out_path = outdir / f"model_size_{gpu_tag}.csv"
221
+ aic.write_csv(rows, out_path)
222
+ logger.info("Wrote %d rows to %s", len(rows), out_path)
223
+
224
+
225
+ if __name__ == "__main__":
226
+ tyro.cli(main)
examples/model_insights/paper_plots.mplstyle ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ### Fonts
3
+ font.size : 9
4
+ axes.labelsize : 10
5
+ axes.titlesize : 10
6
+ xtick.labelsize : 8.5
7
+ ytick.labelsize : 8.5
8
+ legend.fontsize : 8
9
+
10
+ # San-serif font use Arial
11
+ font.family: sans-serif
12
+ #font.sans-serif: Helvetica
13
+ font.sans-serif: Arial
14
+
15
+ ### Axes / grid defaults
16
+ axes.grid : False
17
+ grid.alpha : 0.25
18
+ grid.linewidth : 0.5
19
+ axes.spines.top : False
20
+ axes.spines.right : False
21
+
22
+ # Serif font use TMR
23
+ #font.family: serif
24
+ #font.serif: Times New Roman
25
+ #mathtext.fontset : stix
26
+
27
+
28
+ ### Plotting
29
+ # lines.linewidth : 2
30
+
31
+ ### Saving figures
32
+ path.simplify : True
33
+
34
+ # SVG export now don't render font as path, but save font as text object.
35
+ # This allows for easy integration with MS Office
36
+ svg.fonttype : none
37
+ # Make SVG generation deterministic
38
+ svg.hashsalt : 42
39
+
40
+ # Enforce Type 1 font usage
41
+ pdf.fonttype : 42
42
+ ps.fonttype : 42
examples/model_insights/parallelism.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parallelism sweep on the IEEE 13 scenario.
2
+
3
+ Runs parallelism-pair sweeps on both B200 and H100 (selectable via
4
+ `--gpu`) and writes one CSV per GPU (`parallelism_b200.csv`,
5
+ `parallelism_h100.csv`).
6
+
7
+ B200 pairs:
8
+ GPT-OSS 120B on gpqa, 50 ms ITL: 1 GPU vs 2 GPU
9
+ Qwen 3 235B A22B Thinking on gpqa, 100 ms ITL: 4 GPU vs 8 GPU
10
+
11
+ H100 pair:
12
+ Qwen 3 30B A3B Instruct on lm-arena-chat, 100 ms ITL: 1 GPU vs 2 GPU
13
+
14
+ Each variant is match-peak sized to the shared 3.12 MW anchor at the
15
+ largest batch meeting its ITL target.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Literal
24
+
25
+ import common as aic
26
+ import tyro
27
+
28
+ from openg2g.datacenter.config import ModelDeployment, ReplicaSchedule
29
+
30
+ logger = logging.getLogger("model_insights.parallelism")
31
+
32
+
33
+ # (pair_label, spec_label, parallelism_degree_label, deadline_ms)
34
+ PAIRS_B200: list[tuple[str, str, str, int]] = [
35
+ ("gpt-oss-120b", "GPT-OSS-120B-B200-1GPU", "1 GPU", 50),
36
+ ("gpt-oss-120b", "GPT-OSS-120B-B200-2GPU", "2 GPU", 50),
37
+ ("qwen-235b-a22b-thinking", "Qwen3-235B-A22B-Thinking-4GPU-B200", "4 GPU", 100),
38
+ ("qwen-235b-a22b-thinking", "Qwen3-235B-A22B-Thinking-8GPU-B200", "8 GPU", 100),
39
+ ]
40
+
41
+ PAIRS_H100: list[tuple[str, str, str, int]] = [
42
+ ("qwen-30b-a3b-instruct", "Qwen3-30B-A3B-Instruct-1GPU", "1 GPU", 100),
43
+ ("qwen-30b-a3b-instruct", "Qwen3-30B-A3B-Instruct-2GPU", "2 GPU", 100),
44
+ ]
45
+
46
+ PAIRS_BY_GPU: dict[str, list[tuple[str, str, str, int]]] = {
47
+ "b200": PAIRS_B200,
48
+ "h100": PAIRS_H100,
49
+ }
50
+
51
+
52
+ ANCHOR_PEAK_KW: float = 3_120.0
53
+
54
+ DEFAULT_MODES: tuple[aic.Mode, ...] = ("baseline-no-tap", "ofo-no-tap")
55
+ DEFAULT_OUTDIR = Path(__file__).resolve().parent / "outputs"
56
+
57
+
58
+ @dataclass
59
+ class Row:
60
+ experiment: str
61
+ variant: str
62
+ pair: str
63
+ parallelism_label: str
64
+ mode: str
65
+ seed: int
66
+ num_replicas: int
67
+ gpus_per_replica: int
68
+ deadline_ms: int
69
+ feasible_batch_min: int
70
+ feasible_batch_max: int
71
+ initial_batch: int
72
+ violation_time_s: float
73
+ integral_violation_pu_s: float
74
+ worst_vmin: float
75
+ worst_vmax: float
76
+ mean_throughput_tps: float
77
+ integrated_throughput_tokens: float
78
+ itl_deadline_fraction: float
79
+ achievable_power_range_mw: float
80
+
81
+
82
+ def run_variant(
83
+ pair: str,
84
+ spec_label: str,
85
+ num_replicas: int,
86
+ parallelism_label: str,
87
+ *,
88
+ seed: int,
89
+ shared: aic.SharedData,
90
+ modes: tuple[aic.Mode, ...],
91
+ total_duration_s: int,
92
+ deadline_ms: int,
93
+ ) -> list[Row]:
94
+ base = aic.SPECS[spec_label]
95
+ spec = aic.restrict_spec_by_deadline(base, shared.logistic_models, deadline_ms / 1000.0)
96
+ deployments = [
97
+ (
98
+ ModelDeployment(spec=spec, initial_batch_size=max(spec.feasible_batch_sizes)),
99
+ ReplicaSchedule(initial=num_replicas),
100
+ )
101
+ ]
102
+
103
+ apr_mw = aic.compute_achievable_power_range(deployments=deployments, logistic_models=shared.logistic_models)
104
+
105
+ scenario = aic.build_scenario(deployments, shared=shared, overrides=aic.ScenarioOverrides(seed=seed))
106
+
107
+ rows: list[Row] = []
108
+ for mode in modes:
109
+ result = aic.run_scenario(scenario, shared.logistic_models, mode=mode, total_duration_s=total_duration_s)
110
+ rows.append(
111
+ Row(
112
+ experiment="parallelism",
113
+ variant=spec_label,
114
+ pair=pair,
115
+ parallelism_label=parallelism_label,
116
+ mode=mode,
117
+ seed=seed,
118
+ num_replicas=num_replicas,
119
+ gpus_per_replica=spec.gpus_per_replica,
120
+ deadline_ms=deadline_ms,
121
+ feasible_batch_min=min(spec.feasible_batch_sizes),
122
+ feasible_batch_max=max(spec.feasible_batch_sizes),
123
+ initial_batch=deployments[0][0].initial_batch_size,
124
+ violation_time_s=result.voltage.violation_time_s,
125
+ integral_violation_pu_s=result.voltage.integral_violation_pu_s,
126
+ worst_vmin=result.voltage.worst_vmin,
127
+ worst_vmax=result.voltage.worst_vmax,
128
+ mean_throughput_tps=result.performance.mean_throughput_tps,
129
+ integrated_throughput_tokens=result.performance.integrated_throughput_tokens,
130
+ itl_deadline_fraction=result.performance.itl_deadline_fraction,
131
+ achievable_power_range_mw=apr_mw,
132
+ )
133
+ )
134
+ logger.info(
135
+ " [%s %s n_rep=%d dl=%dms seed=%d mode=%s] viol=%.2fs integral=%.4f "
136
+ "vmin=%.4f thpt=%.1fk tok/s itl_miss=%.2f%% APR=%.2f MW",
137
+ pair,
138
+ parallelism_label,
139
+ num_replicas,
140
+ deadline_ms,
141
+ seed,
142
+ mode,
143
+ result.voltage.violation_time_s,
144
+ result.voltage.integral_violation_pu_s,
145
+ result.voltage.worst_vmin,
146
+ result.performance.mean_throughput_tps / 1e3,
147
+ result.performance.itl_deadline_fraction * 100.0,
148
+ apr_mw,
149
+ )
150
+ return rows
151
+
152
+
153
+ def main(
154
+ seeds: tuple[int, ...] = (0, 1, 2, 3, 4),
155
+ total_duration_s: int = aic.TOTAL_DURATION_S,
156
+ modes: tuple[
157
+ Literal["baseline-no-tap", "baseline-tap-change", "ofo-no-tap", "ofo-tap-change"], ...
158
+ ] = DEFAULT_MODES,
159
+ gpu: Literal["both", "b200", "h100"] = "both",
160
+ only_pair: str | None = None,
161
+ outdir: Path = DEFAULT_OUTDIR,
162
+ ) -> None:
163
+ logging.basicConfig(
164
+ level=logging.INFO, format="%(asctime)s %(levelname)s [%(name)s] %(message)s", datefmt="%H:%M:%S"
165
+ )
166
+ logging.getLogger("httpx").setLevel(logging.WARNING)
167
+
168
+ shared = aic.load_shared_data()
169
+ outdir.mkdir(parents=True, exist_ok=True)
170
+
171
+ targets = ["b200", "h100"] if gpu == "both" else [gpu]
172
+ for gpu_tag in targets:
173
+ pairs = [p for p in PAIRS_BY_GPU[gpu_tag] if (only_pair is None or p[0] == only_pair)]
174
+ if not pairs:
175
+ logger.warning("No pairs match filter for gpu=%s only_pair=%s; skipping", gpu_tag, only_pair)
176
+ continue
177
+
178
+ rows: list[Row] = []
179
+ for pair, spec_label, parallelism_label, deadline_ms in pairs:
180
+ base = aic.SPECS[spec_label]
181
+ spec = aic.restrict_spec_by_deadline(base, shared.logistic_models, deadline_ms / 1000.0)
182
+ num_replicas = aic.compute_matched_peak_replicas(spec, ANCHOR_PEAK_KW, shared.logistic_models)
183
+ logger.info(
184
+ "=== gpu=%s pair=%s variant=%s (%s) n_replicas=%d (match-peak @ %.0f kW, dl=%d ms) ===",
185
+ gpu_tag.upper(),
186
+ pair,
187
+ spec_label,
188
+ parallelism_label,
189
+ num_replicas,
190
+ ANCHOR_PEAK_KW,
191
+ deadline_ms,
192
+ )
193
+ for seed in seeds:
194
+ rows.extend(
195
+ run_variant(
196
+ pair,
197
+ spec_label,
198
+ num_replicas,
199
+ parallelism_label,
200
+ seed=seed,
201
+ shared=shared,
202
+ modes=modes,
203
+ total_duration_s=total_duration_s,
204
+ deadline_ms=deadline_ms,
205
+ )
206
+ )
207
+
208
+ out_path = outdir / f"parallelism_{gpu_tag}.csv"
209
+ aic.write_csv(rows, out_path)
210
+ logger.info("Wrote %d rows to %s", len(rows), out_path)
211
+
212
+
213
+ if __name__ == "__main__":
214
+ tyro.cli(main)
examples/model_insights/plots.py ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-variant plots for the model-insights experiments.
2
+
3
+ Each panel saves as its own PDF, SVG, and PNG; the paper composes subfloats
4
+ from these. Style comes from the local `paper_plots.mplstyle`. Legends are
5
+ color-only and horizontal; display labels drop precision / parallelism
6
+ decorations: those live in captions.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import math
13
+ from pathlib import Path
14
+
15
+ import matplotlib
16
+ import numpy as np
17
+ import pandas as pd
18
+ import tyro
19
+ from matplotlib.lines import Line2D
20
+ from matplotlib.patches import Patch
21
+
22
+ matplotlib.use("Agg")
23
+ import common as mi
24
+ import matplotlib.pyplot as plt
25
+
26
+ _MPLSTYLE_PATH = Path(__file__).resolve().parent / "paper_plots.mplstyle"
27
+ if not _MPLSTYLE_PATH.exists():
28
+ raise FileNotFoundError(
29
+ f"Paper mplstyle not found at {_MPLSTYLE_PATH}. "
30
+ "This file is the paper-wide plot style and is load-bearing; "
31
+ "do not regenerate figures without it."
32
+ )
33
+ plt.style.use(str(_MPLSTYLE_PATH))
34
+
35
+ logger = logging.getLogger("model_insights.plots")
36
+
37
+ OUTDIR = Path(__file__).resolve().parent / "outputs"
38
+
39
+ OFO_MODE = "ofo-no-tap"
40
+ BASELINE_MODE = "baseline-no-tap"
41
+
42
+ COLORS = {
43
+ "baseline": "#9A9A9A",
44
+ "ofo": "#1F77B4", # tab10 blue
45
+ "h100": "#1F77B4", # tab10 blue
46
+ "b200": "#D62728", # tab10 red
47
+ "hardware": "#D62728", # tab10 red
48
+ }
49
+
50
+ _TAB10 = plt.get_cmap("tab10").colors
51
+
52
+ # Stable per-model colors used wherever a model is identified by color
53
+ # (model-size figure, hardware figure, etc.). The hardware figure uses
54
+ # blue for Qwen 3 32B and red for Qwen 3 8B; that pair is canonical and
55
+ # the rest of the palette is filled in around it.
56
+ MODEL_COLORS: dict[str, str] = {
57
+ "Qwen 3 32B": _TAB10[0], # blue
58
+ "Qwen 3 30B A3B": _TAB10[1], # orange
59
+ "GPT-OSS 120B": _TAB10[2], # green
60
+ "Qwen 3 8B": _TAB10[3], # red
61
+ "Qwen 3 235B A22B": _TAB10[4], # purple
62
+ "Qwen 3 235B A22B Thinking": _TAB10[4], # same as 235B A22B
63
+ "Llama 3.1 70B": _TAB10[5], # brown
64
+ "Llama 3.1 405B": _TAB10[6], # pink
65
+ }
66
+
67
+ # Distinct color pairs for the two parallelism panels so (a) and (b) read as
68
+ # separate experiments rather than the same one twice. The first pair reuses
69
+ # the default h100/b200 hues (blue, red); the second pair picks two of the
70
+ # remaining tab10 colors used by the model-size figure that are not in (a).
71
+ PARALLELISM_PAIR_COLORS = {
72
+ "gpt-oss-120b": (COLORS["h100"], COLORS["b200"]),
73
+ "qwen-235b-a22b-thinking": (_TAB10[1], _TAB10[2]),
74
+ }
75
+
76
+ DISPLAY_LABELS = {
77
+ "Qwen3-8B": "Qwen 3 8B",
78
+ "Qwen3-30B-A3B-Instruct-1GPU": "Qwen 3 30B A3B",
79
+ "Qwen3-30B-A3B-Instruct-2GPU": "Qwen 3 30B A3B",
80
+ "Llama-3.1-70B": "Llama 3.1 70B",
81
+ "Llama-3.1-405B": "Llama 3.1 405B",
82
+ "GPT-OSS-120B-H100-2GPU": "GPT-OSS 120B",
83
+ "GPT-OSS-120B-B200-1GPU": "GPT-OSS 120B",
84
+ "GPT-OSS-120B-B200-2GPU": "GPT-OSS 120B",
85
+ "Qwen3-8B-B200": "Qwen 3 8B",
86
+ "Qwen3-32B-1GPU-H100": "Qwen 3 32B",
87
+ "Qwen3-32B-1GPU-B200": "Qwen 3 32B",
88
+ "Qwen3-30B-A3B-Instruct-1GPU-B200": "Qwen 3 30B A3B",
89
+ "Qwen3-235B-A22B-Instruct-FP8-8GPU": "Qwen 3 235B A22B",
90
+ "Qwen3-235B-A22B-Instruct-8GPU": "Qwen 3 235B A22B",
91
+ "Qwen3-235B-A22B-Instruct-8GPU-B200": "Qwen 3 235B A22B",
92
+ "Qwen3-235B-A22B-Thinking-8GPU": "Qwen 3 235B A22B Thinking",
93
+ "Qwen3-235B-A22B-Thinking-4GPU-B200": "Qwen 3 235B A22B Thinking",
94
+ "Qwen3-235B-A22B-Thinking-8GPU-B200": "Qwen 3 235B A22B Thinking",
95
+ "Qwen3-235B-A22B-Thinking-FP8-8GPU": "Qwen 3 235B A22B Thinking",
96
+ "Qwen3-235B-A22B-Thinking-FP8-4GPU-B200": "Qwen 3 235B A22B Thinking",
97
+ "qwen-8b-1gpu": "Qwen 3 8B",
98
+ "qwen-32b-1gpu": "Qwen 3 32B",
99
+ "qwen-30b-a3b-instruct-1gpu": "Qwen 3 30B A3B",
100
+ "qwen-30b-a3b-instruct": "Qwen 3 30B A3B",
101
+ "qwen-235b-a22b-thinking": "Qwen 3 235B A22B Thinking",
102
+ "gpt-oss-120b": "GPT-OSS 120B",
103
+ }
104
+
105
+
106
+ def _pretty(label: str) -> str:
107
+ return DISPLAY_LABELS.get(label, label)
108
+
109
+
110
+ def _line_handle(color: str, label: str) -> Line2D:
111
+ """Legend handle for a line-marker plot (Pareto curves)."""
112
+ return Line2D(
113
+ [0],
114
+ [0],
115
+ color=color,
116
+ marker="o",
117
+ markersize=5.5,
118
+ markeredgecolor="black",
119
+ markeredgewidth=0.4,
120
+ lw=1.6,
121
+ label=label,
122
+ )
123
+
124
+
125
+ def _combo_handle(color: str, label: str):
126
+ """Composite legend handle: a bar swatch + a line marker, both in
127
+ `color`, rendered side-by-side under one label. Use with
128
+ `HandlerTuple` so one legend entry covers both the (a) bars and the
129
+ (b) Pareto panels at once.
130
+ """
131
+ bar = Patch(facecolor=color, edgecolor="white")
132
+ line = Line2D(
133
+ [0], [0], color=color, marker="o", markersize=5.5, markeredgecolor="black", markeredgewidth=0.4, lw=1.6
134
+ )
135
+ return ((bar, line), label)
136
+
137
+
138
+ def _save_legend(handles, stem: Path, *, ncol: int, width: float, tight: bool = True) -> None:
139
+ """Save a standalone legend PDF.
140
+
141
+ Handles may be plain artists OR `(tuple_of_artists, label)` pairs
142
+ (produced by `_combo_handle`) that render as side-by-side glyphs
143
+ under one label via `HandlerTuple`. When `tight=False` the full
144
+ figsize is preserved (useful for padding a narrow legend so it
145
+ renders at larger physical font in LaTeX).
146
+ """
147
+ if not handles:
148
+ return
149
+ from matplotlib.legend_handler import HandlerTuple
150
+
151
+ plain_handles, tuple_handles, tuple_labels = [], [], []
152
+ for h in handles:
153
+ if isinstance(h, tuple) and len(h) == 2 and isinstance(h[0], tuple):
154
+ tuple_handles.append(h[0])
155
+ tuple_labels.append(h[1])
156
+ else:
157
+ plain_handles.append(h)
158
+
159
+ fig, ax = plt.subplots(figsize=(width, 0.35))
160
+ ax.axis("off")
161
+ legend_fontsize = 11
162
+ if tuple_handles:
163
+ ax.legend(
164
+ handles=tuple_handles + plain_handles,
165
+ labels=tuple_labels + [h.get_label() for h in plain_handles],
166
+ ncol=ncol,
167
+ loc="center",
168
+ frameon=False,
169
+ fontsize=legend_fontsize,
170
+ handlelength=2.6,
171
+ columnspacing=1.2,
172
+ handletextpad=0.5,
173
+ handler_map={tuple: HandlerTuple(ndivide=None, pad=0.2)},
174
+ )
175
+ else:
176
+ ax.legend(
177
+ handles=plain_handles,
178
+ ncol=ncol,
179
+ loc="center",
180
+ frameon=False,
181
+ fontsize=legend_fontsize,
182
+ handlelength=1.2,
183
+ columnspacing=1.2,
184
+ handletextpad=0.4,
185
+ )
186
+ stem.parent.mkdir(parents=True, exist_ok=True)
187
+ if tight:
188
+ kw = {"bbox_inches": "tight", "pad_inches": 0.02}
189
+ else:
190
+ kw = {"bbox_inches": None, "pad_inches": 0.0}
191
+ fig.savefig(stem.with_suffix(".pdf"), metadata={"CreationDate": None, "Creator": None, "Producer": None}, **kw)
192
+ fig.savefig(stem.with_suffix(".svg"), metadata={"Date": None}, **kw)
193
+ fig.savefig(stem.with_suffix(".png"), dpi=200, metadata={"Creation Time": None}, **kw)
194
+ plt.close(fig)
195
+
196
+
197
+ def _grouped_bars(
198
+ ax,
199
+ base_vals,
200
+ ofo_vals,
201
+ colors,
202
+ *,
203
+ base_errs=None,
204
+ ofo_errs=None,
205
+ ylog: bool = True,
206
+ ylabel: str = "Integral violation\n(pu·s)",
207
+ bar_width: float = 0.38,
208
+ ) -> None:
209
+ """Bars grouped by variant. Each variant has two bars: hatched
210
+ (uncoordinated) and solid (coordinated), both colored by variant.
211
+ No x tick labels: identity comes from the shared legend + caption."""
212
+ n = len(colors)
213
+ xs = np.arange(n)
214
+ offset = bar_width / 2 + 0.012
215
+ for i, color in enumerate(colors):
216
+ be = base_errs[i] if base_errs is not None else None
217
+ oe = ofo_errs[i] if ofo_errs is not None else None
218
+ ax.bar(
219
+ xs[i] - offset,
220
+ base_vals[i],
221
+ bar_width,
222
+ color=color,
223
+ hatch="///",
224
+ edgecolor="white",
225
+ linewidth=0.6,
226
+ yerr=be,
227
+ capsize=1.8,
228
+ error_kw={"lw": 0.7},
229
+ )
230
+ ax.bar(
231
+ xs[i] + offset,
232
+ ofo_vals[i],
233
+ bar_width,
234
+ color=color,
235
+ edgecolor="white",
236
+ linewidth=0.6,
237
+ yerr=oe,
238
+ capsize=1.8,
239
+ error_kw={"lw": 0.7},
240
+ )
241
+ ax.set_xticks([])
242
+ ax.set_xlim(-0.6, n - 0.4)
243
+ ax.set_ylabel(ylabel, fontsize=9)
244
+ if ylog:
245
+ ax.set_yscale("log")
246
+ lo, hi = ax.get_ylim()
247
+ ax.set_ylim(lo, hi * 1.2)
248
+ ax.grid(True, axis="y", alpha=0.25)
249
+
250
+
251
+ # Fixed axes rectangle so all (a)/(b) panel PDFs share dimensions and
252
+ # x-baselines line up when composed side-by-side in LaTeX.
253
+ _PANEL_FIGSIZE = (2.6, 1.8)
254
+ _PANEL_AXES = (0.23, 0.26, 0.74, 0.70) # (left, bottom, width, height)
255
+
256
+
257
+ def _make_panel():
258
+ fig, ax = plt.subplots(figsize=_PANEL_FIGSIZE)
259
+ ax.set_position(_PANEL_AXES)
260
+ return fig, ax
261
+
262
+
263
+ def _save(fig: plt.Figure, stem: Path) -> None:
264
+ stem.parent.mkdir(parents=True, exist_ok=True)
265
+ # No tight_layout: it overrides set_position. bbox_inches=None
266
+ # preserves the exact figsize, guaranteeing matched dimensions.
267
+ kwargs = {"bbox_inches": None, "pad_inches": 0.0}
268
+ fig.savefig(stem.with_suffix(".pdf"), metadata={"CreationDate": None, "Creator": None, "Producer": None}, **kwargs)
269
+ fig.savefig(stem.with_suffix(".svg"), metadata={"Date": None}, **kwargs)
270
+ fig.savefig(stem.with_suffix(".png"), dpi=200, metadata={"Creation Time": None}, **kwargs)
271
+ plt.close(fig)
272
+
273
+
274
+ def _aggregate(df: pd.DataFrame) -> pd.DataFrame:
275
+ return df.groupby(["variant", "mode"], as_index=False).agg(
276
+ n_seeds=("seed", "nunique"),
277
+ integral_mean=("integral_violation_pu_s", "mean"),
278
+ integral_std=("integral_violation_pu_s", "std"),
279
+ vmin_mean=("worst_vmin", "mean"),
280
+ thpt_mean=("mean_throughput_tps", "mean"),
281
+ itl_miss_mean=("itl_deadline_fraction", "mean"),
282
+ apr_mw=("achievable_power_range_mw", "mean"),
283
+ )
284
+
285
+
286
+ def _pareto_from_row(row, logistic_models) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
287
+ """Return (batches, power MW, throughput M tok/s) for one variant."""
288
+ variant = row["variant"]
289
+ base = variant.split("_dl")[0]
290
+ spec = mi.SPECS[base]
291
+ fmax = int(row["feasible_batch_max"])
292
+ fmin = int(row["feasible_batch_min"])
293
+ batches = np.array([b for b in sorted(spec.feasible_batch_sizes) if fmin <= b <= fmax], dtype=int)
294
+ p_fit = logistic_models.power(base)
295
+ t_fit = logistic_models.throughput(base)
296
+ n = int(row["num_replicas"])
297
+ p_mw = np.array([float(p_fit.eval(int(b))) * n / 1e6 for b in batches])
298
+ t_mtps = np.array([float(t_fit.eval(int(b))) * n / 1e6 for b in batches]) # tokens/s → M tokens/s
299
+ return batches, p_mw, t_mtps
300
+
301
+
302
+ def _apply_pareto_axes(ax, with_ylabel: bool = True) -> None:
303
+ ax.set_xlabel("Datacenter power (MW)", fontsize=9)
304
+ if with_ylabel:
305
+ ax.set_ylabel("Token throughput\n(M tok/s)", fontsize=9)
306
+ ax.set_ylim(bottom=0)
307
+ ax.set_xlim(left=max(0, ax.get_xlim()[0]))
308
+ ax.grid(True, alpha=0.3)
309
+
310
+
311
+ def _plot_pareto(
312
+ ax,
313
+ entries,
314
+ logistic_models,
315
+ color_map,
316
+ label_map,
317
+ *,
318
+ marker_size: float = 5.5,
319
+ ) -> None:
320
+ """Color-only Pareto curves. Each entry is a dict with variant,
321
+ num_replicas, feasible_batch_min, feasible_batch_max."""
322
+ for entry in entries:
323
+ batches, p_mw, t_m = _pareto_from_row(entry, logistic_models)
324
+ if len(batches) == 0:
325
+ continue
326
+ key = entry.get("color_key", entry["variant"])
327
+ color = color_map.get(key, COLORS["ofo"])
328
+ label = label_map.get(entry["variant"], _pretty(entry["variant"]))
329
+ ax.plot(
330
+ p_mw,
331
+ t_m,
332
+ "-o",
333
+ color=color,
334
+ markersize=marker_size,
335
+ markeredgecolor="black",
336
+ markeredgewidth=0.4,
337
+ label=label,
338
+ alpha=0.95,
339
+ lw=1.6,
340
+ )
341
+
342
+
343
+ def _pair_bars(
344
+ ax,
345
+ x,
346
+ base_vals,
347
+ ofo_vals,
348
+ *,
349
+ ylog: bool,
350
+ ylabel: str,
351
+ base_errs=None,
352
+ ofo_errs=None,
353
+ tick_labels=None,
354
+ rotation: float = 25.0,
355
+ ) -> None:
356
+ width = 0.38
357
+ ax.bar(x - width / 2, base_vals, width, yerr=base_errs, color=COLORS["baseline"], label="Baseline", capsize=2.5)
358
+ ax.bar(x + width / 2, ofo_vals, width, yerr=ofo_errs, color=COLORS["ofo"], label="OFO", capsize=2.5)
359
+ ax.set_xticks(x)
360
+ if tick_labels is not None:
361
+ ax.set_xticklabels(tick_labels, rotation=rotation, ha="right" if rotation else "center")
362
+ ax.set_ylabel(ylabel)
363
+ if ylog:
364
+ ax.set_yscale("log")
365
+ lo, hi = ax.get_ylim()
366
+ ax.set_ylim(lo, hi * 2.5)
367
+ ax.grid(True, axis="y", alpha=0.25)
368
+
369
+
370
+ # ──────────────────────────────────────────────────────────────────────
371
+ # Model size & architecture
372
+
373
+
374
+ def plot_model_size(
375
+ df,
376
+ out,
377
+ logistic_models,
378
+ *,
379
+ suffix: str = "",
380
+ pareto_xlim: tuple[float, float] | None = None,
381
+ ) -> tuple[float, float]:
382
+ agg = _aggregate(df)
383
+ all_variants = df["variant"].drop_duplicates().tolist()
384
+
385
+ # Compute power-swing range per variant.
386
+ def _swing(variant: str) -> float:
387
+ row = df[(df["variant"] == variant) & (df["mode"] == OFO_MODE)].iloc[0].to_dict()
388
+ _, p_mw, _ = _pareto_from_row(row, logistic_models)
389
+ return float(p_mw.max() - p_mw.min()) if len(p_mw) else 0.0
390
+
391
+ # Color is fixed per model identity (MODEL_COLORS), so the same model
392
+ # appears in the same color across model-size, hardware, and other
393
+ # figures.
394
+ color_map = {v: MODEL_COLORS[_pretty(v)] for v in all_variants}
395
+
396
+ # Plot order: widest → narrowest, so the reference model with the largest
397
+ # feasible power range anchors the leftmost position and other models
398
+ # trail as comparisons.
399
+ variants = sorted(all_variants, key=_swing, reverse=True)
400
+
401
+ def _val(v, mode, col):
402
+ row = agg[(agg.variant == v) & (agg["mode"] == mode)]
403
+ return float(row[col].iloc[0]) if not row.empty else math.nan
404
+
405
+ # (a) integral violation: colored bars, hatched (uncoord.) vs solid (coord.)
406
+ fig, ax = _make_panel()
407
+ _grouped_bars(
408
+ ax,
409
+ [_val(v, BASELINE_MODE, "integral_mean") for v in variants],
410
+ [_val(v, OFO_MODE, "integral_mean") for v in variants],
411
+ [color_map[v] for v in variants],
412
+ base_errs=[_val(v, BASELINE_MODE, "integral_std") for v in variants],
413
+ ofo_errs=[_val(v, OFO_MODE, "integral_std") for v in variants],
414
+ )
415
+ _save(fig, out / f"model_size_a{suffix}")
416
+
417
+ # (b) Pareto frontier: same color per variant
418
+ entries = [df[(df["variant"] == v) & (df["mode"] == OFO_MODE)].iloc[0].to_dict() for v in variants]
419
+ fig, ax = _make_panel()
420
+ _plot_pareto(ax, entries, logistic_models, color_map=color_map, label_map={v: _pretty(v) for v in variants})
421
+ _apply_pareto_axes(ax)
422
+ resolved_pareto_xlim = ax.get_xlim()
423
+ if pareto_xlim is not None:
424
+ ax.set_xlim(pareto_xlim)
425
+ resolved_pareto_xlim = pareto_xlim
426
+ _save(fig, out / f"model_size_b{suffix}")
427
+
428
+ # Shared legend: model colors only (hatch/solid explained in caption).
429
+ handles = [_combo_handle(color_map[v], _pretty(v)) for v in variants]
430
+ _save_legend(handles, out / f"model_size_legend{suffix}", ncol=len(variants), width=4.6)
431
+ return resolved_pareto_xlim
432
+
433
+
434
+ # ──────────────────────────────────────────────────────────────────────
435
+ # Parallelism
436
+
437
+
438
+ def plot_parallelism(df, out, logistic_models, *, suffix: str = "") -> None:
439
+ agg = _aggregate(df).merge(
440
+ df[["variant", "pair", "parallelism_label"]].drop_duplicates(),
441
+ on="variant",
442
+ how="left",
443
+ )
444
+ pairs = sorted(agg["pair"].unique())
445
+ for pair in pairs:
446
+ sub = agg[agg["pair"] == pair].copy()
447
+ variants = sub[["variant", "parallelism_label"]].drop_duplicates().sort_values("variant")["variant"].tolist()
448
+ labels = [sub[sub["variant"] == v]["parallelism_label"].iloc[0] for v in variants]
449
+ stem = "parallelism" if len(pairs) == 1 else f"parallelism_{pair}"
450
+
451
+ def _v(v, mode, col, sub=sub):
452
+ r = sub[(sub["variant"] == v) & (sub["mode"] == mode)]
453
+ return float(r[col].iloc[0]) if not r.empty else math.nan
454
+
455
+ pair_palette = PARALLELISM_PAIR_COLORS.get(pair, (COLORS["h100"], COLORS["b200"]))
456
+ color_map = {labels[i]: pair_palette[i] for i in range(len(variants))}
457
+
458
+ # (a) integral violation: colored bars, hatch = baseline vs OFO
459
+ fig, ax = _make_panel()
460
+ _grouped_bars(
461
+ ax,
462
+ [_v(v, BASELINE_MODE, "integral_mean") for v in variants],
463
+ [_v(v, OFO_MODE, "integral_mean") for v in variants],
464
+ [color_map[lbl] for lbl in labels],
465
+ base_errs=[_v(v, BASELINE_MODE, "integral_std") for v in variants],
466
+ ofo_errs=[_v(v, OFO_MODE, "integral_std") for v in variants],
467
+ )
468
+ _save(fig, out / f"{stem}_a{suffix}")
469
+
470
+ # (b) Pareto: same colors.
471
+ entries = []
472
+ for vv, lbl in zip(variants, labels, strict=True):
473
+ r = df[(df["variant"] == vv) & (df["mode"] == OFO_MODE)].iloc[0].to_dict()
474
+ r["color_key"] = lbl
475
+ entries.append(r)
476
+ fig, ax = _make_panel()
477
+ _plot_pareto(
478
+ ax,
479
+ entries,
480
+ logistic_models,
481
+ color_map=color_map,
482
+ label_map={vv: lbl for vv, lbl in zip(variants, labels, strict=True)},
483
+ )
484
+ _apply_pareto_axes(ax)
485
+ _save(fig, out / f"{stem}_b{suffix}")
486
+
487
+ # Pareto-only legend (line markers); width tuned to match the
488
+ # rendered font scale of the bar+line legends in other experiments.
489
+ handles = [_line_handle(color_map[lbl], lbl) for lbl in labels]
490
+ _save_legend(handles, out / f"{stem}_legend{suffix}", ncol=len(labels), width=2.3)
491
+
492
+
493
+ # ──────────────────────────────────────────────────────────────────────
494
+ # Hardware (per-pair + shared legend)
495
+
496
+
497
+ _HARDWARE_DROP_PAIRS = {"qwen-30b-a3b-instruct-1gpu"} # MoE finding redundant with model_size
498
+
499
+
500
+ def plot_hardware(df, out, logistic_models, *, suffix: str = "") -> None:
501
+ agg = _aggregate(df).merge(
502
+ df[["variant", "pair", "hardware"]].drop_duplicates(),
503
+ on="variant",
504
+ how="left",
505
+ )
506
+ pairs = [p for p in sorted(agg["pair"].unique()) if p not in _HARDWARE_DROP_PAIRS]
507
+ hardware_order = ["H100", "B200"]
508
+
509
+ variants_by_pair_hw: dict[tuple[str, str], str] = {}
510
+ for _, row in agg.drop_duplicates(["pair", "hardware", "variant"]).iterrows():
511
+ variants_by_pair_hw[(row["pair"], row["hardware"])] = row["variant"]
512
+
513
+ def _v(pair_, hw, mode, col):
514
+ v = variants_by_pair_hw.get((pair_, hw))
515
+ if v is None:
516
+ return math.nan
517
+ r = agg[(agg["variant"] == v) & (agg["mode"] == mode)]
518
+ return float(r[col].iloc[0]) if not r.empty else math.nan
519
+
520
+ # Color each pair by its canonical model color (MODEL_COLORS), so
521
+ # e.g. Qwen 3 8B is the same red here as in the model-size figure.
522
+ pair_colors = {
523
+ p: MODEL_COLORS[_pretty(next(v for (pp, _), v in variants_by_pair_hw.items() if pp == p))] for p in pairs
524
+ }
525
+
526
+ # (a): integral violation. X-axis = hardware. Within each hardware
527
+ # group, 4 bars: 2 models × (uncoord, coord). Color = model, hatch =
528
+ # uncoord (hatched) / coord (solid).
529
+ bar_width = 0.18
530
+ x = np.arange(len(hardware_order))
531
+ fig, ax = _make_panel()
532
+ n = len(pairs)
533
+ for pi, pair in enumerate(pairs):
534
+ color = pair_colors[pair]
535
+ for mode_idx, mode in enumerate([BASELINE_MODE, OFO_MODE]):
536
+ hatch = "///" if mode == BASELINE_MODE else ""
537
+ offset = (pi - (n - 1) / 2) * 2 * bar_width + (mode_idx - 0.5) * bar_width
538
+ vals = [_v(pair, hw, mode, "integral_mean") for hw in hardware_order]
539
+ ax.bar(x + offset, vals, bar_width, color=color, hatch=hatch, edgecolor="white", linewidth=0.6)
540
+ ax.set_xticks(x)
541
+ ax.set_xticklabels(hardware_order)
542
+ ax.set_yscale("log")
543
+ lo, hi = ax.get_ylim()
544
+ ax.set_ylim(lo, hi * 1.5)
545
+ ax.set_ylabel("Integral violation\n(pu·s)", fontsize=9)
546
+ ax.grid(True, axis="y", alpha=0.2)
547
+ _save(fig, out / f"hardware_a{suffix}")
548
+
549
+ # (b): Pareto for both models on BOTH hardware. Color = model
550
+ # (shared with (a) and the main legend). Marker fill = hardware:
551
+ # open = H100, filled = B200. An inline mini-legend inside the axes
552
+ # explains the marker encoding.
553
+ fig, ax = _make_panel()
554
+ for pair in pairs:
555
+ color = pair_colors[pair]
556
+ for hw in hardware_order:
557
+ variant = variants_by_pair_hw.get((pair, hw))
558
+ if variant is None:
559
+ continue
560
+ r = df[(df["variant"] == variant) & (df["mode"] == OFO_MODE)].iloc[0].to_dict()
561
+ batches, p_mw, t_m = _pareto_from_row(r, logistic_models)
562
+ if len(batches) == 0:
563
+ continue
564
+ if hw == "H100":
565
+ ax.plot(
566
+ p_mw,
567
+ t_m,
568
+ "-o",
569
+ color=color,
570
+ markersize=5.5,
571
+ markerfacecolor="white",
572
+ markeredgecolor=color,
573
+ markeredgewidth=1.3,
574
+ lw=1.6,
575
+ alpha=0.95,
576
+ )
577
+ else:
578
+ ax.plot(
579
+ p_mw,
580
+ t_m,
581
+ "-o",
582
+ color=color,
583
+ markersize=5.5,
584
+ markeredgecolor="black",
585
+ markeredgewidth=0.4,
586
+ lw=1.6,
587
+ alpha=0.95,
588
+ )
589
+ _apply_pareto_axes(ax)
590
+ # Inline hardware-marker key (small, inside the axes so it doesn't
591
+ # add to the shared top legend).
592
+ hw_key = [
593
+ Line2D(
594
+ [0],
595
+ [0],
596
+ marker="o",
597
+ color="#555",
598
+ markerfacecolor="white",
599
+ markeredgecolor="#555",
600
+ markeredgewidth=1.3,
601
+ lw=1.0,
602
+ label="H100",
603
+ ),
604
+ Line2D(
605
+ [0],
606
+ [0],
607
+ marker="o",
608
+ color="#555",
609
+ markerfacecolor="#555",
610
+ markeredgecolor="black",
611
+ markeredgewidth=0.4,
612
+ lw=1.0,
613
+ label="B200",
614
+ ),
615
+ ]
616
+ ax.legend(
617
+ handles=hw_key,
618
+ loc="upper left",
619
+ frameon=False,
620
+ fontsize=8,
621
+ handlelength=1.2,
622
+ handletextpad=0.4,
623
+ borderaxespad=0.2,
624
+ labelspacing=0.25,
625
+ )
626
+ _save(fig, out / f"hardware_b{suffix}")
627
+
628
+ # Shared legend: model colors only.
629
+ handles = [_combo_handle(pair_colors[p], _pretty(p)) for p in pairs]
630
+ _save_legend(handles, out / f"hardware_legend{suffix}", ncol=len(pairs), width=2.5)
631
+
632
+
633
+ # ──────────────────────────────────────────────────────────────────────
634
+ # Precision
635
+
636
+
637
+ MAIN_PRECISION_PAIR = "qwen-235b-a22b-instruct-h100-8gpu"
638
+
639
+
640
+ def plot_precision(df, out, logistic_models, *, suffix: str = "") -> None:
641
+ # Main paper figure uses only MAIN_PRECISION_PAIR; the other pairs
642
+ # appear in the appendix.
643
+ df = df[df["pair"] == MAIN_PRECISION_PAIR].copy()
644
+ agg = _aggregate(df).merge(
645
+ df[["variant", "precision_label"]].drop_duplicates(),
646
+ on="variant",
647
+ how="left",
648
+ )
649
+ variants = agg.drop_duplicates("variant").sort_values("variant")["variant"].tolist()
650
+ labels = [agg[agg["variant"] == v]["precision_label"].iloc[0] for v in variants]
651
+
652
+ def _v(v, mode, col):
653
+ r = agg[(agg["variant"] == v) & (agg["mode"] == mode)]
654
+ return float(r[col].iloc[0]) if not r.empty else math.nan
655
+
656
+ color_map = {"bf16": COLORS["ofo"], "FP8": COLORS["hardware"]}
657
+
658
+ # (a) violation: colored bars, hatch = uncoord., solid = coord.
659
+ fig, ax = _make_panel()
660
+ _grouped_bars(
661
+ ax,
662
+ [_v(v, BASELINE_MODE, "integral_mean") for v in variants],
663
+ [_v(v, OFO_MODE, "integral_mean") for v in variants],
664
+ [color_map[lbl] for lbl in labels],
665
+ base_errs=[_v(v, BASELINE_MODE, "integral_std") for v in variants],
666
+ ofo_errs=[_v(v, OFO_MODE, "integral_std") for v in variants],
667
+ )
668
+ _save(fig, out / f"precision_a{suffix}")
669
+
670
+ # (b) Pareto: same colors
671
+ entries = []
672
+ for v, lbl in zip(variants, labels, strict=True):
673
+ r = df[(df["variant"] == v) & (df["mode"] == OFO_MODE)].iloc[0].to_dict()
674
+ r["color_key"] = lbl
675
+ entries.append(r)
676
+ fig, ax = _make_panel()
677
+ _plot_pareto(
678
+ ax,
679
+ entries,
680
+ logistic_models,
681
+ color_map=color_map,
682
+ label_map={vv: lbl for vv, lbl in zip(variants, labels, strict=True)},
683
+ )
684
+ _apply_pareto_axes(ax)
685
+ _save(fig, out / f"precision_b{suffix}")
686
+
687
+ # Shared legend: colors only; hatch/solid explained in the caption.
688
+ # Display "BF16" (not "bf16") per paper style.
689
+ def _display_prec(label: str) -> str:
690
+ return "BF16" if label == "bf16" else label
691
+
692
+ # Order: BF16 first (blue), then FP8 (red), matching the blue-then-red
693
+ # order used in the model-size, hardware, and parallelism legends.
694
+ ordered_labels = [lbl for lbl in ("bf16", "FP8") if lbl in set(labels)]
695
+ handles = [_combo_handle(color_map[lbl], _display_prec(lbl)) for lbl in ordered_labels]
696
+ _save_legend(handles, out / f"precision_legend{suffix}", ncol=len(set(labels)), width=1.8)
697
+
698
+
699
+ # ──────────────────────────────────────────────────────────────────────
700
+
701
+
702
+ def main(
703
+ indir: Path = OUTDIR,
704
+ outdir: Path = OUTDIR / "figures",
705
+ ) -> None:
706
+ """Generate figures for every CSV present in `indir`.
707
+
708
+ `model_size` and `parallelism` each write one CSV per GPU
709
+ (`<name>_b200.csv`, `<name>_h100.csv`); one figure set per GPU is
710
+ emitted with a matching suffix. `hardware` and `precision` span both
711
+ GPUs in their PAIRS list and write a single CSV (kept under
712
+ `<name>_b200.csv` for filename consistency).
713
+
714
+ Args:
715
+ indir: Directory holding per-experiment CSVs.
716
+ outdir: Where to write PDF/SVG/PNG per panel.
717
+ """
718
+ logging.basicConfig(
719
+ level=logging.INFO, format="%(asctime)s %(levelname)s [%(name)s] %(message)s", datefmt="%H:%M:%S"
720
+ )
721
+ outdir.mkdir(parents=True, exist_ok=True)
722
+
723
+ wanted_models = {
724
+ "Llama-3.1-70B",
725
+ "Llama-3.1-405B",
726
+ "Qwen3-8B",
727
+ "Qwen3-8B-B200",
728
+ }
729
+
730
+ mi.SPECS = {
731
+ name: spec
732
+ for name, spec in mi.SPECS.items()
733
+ if name in wanted_models
734
+ }
735
+
736
+ shared = mi.load_shared_data()
737
+ lm = shared.logistic_models
738
+
739
+ #shared = mi.load_shared_data()
740
+ #lm = shared.logistic_models
741
+
742
+ dual_gpu = (
743
+ ("model_size", plot_model_size),
744
+ ("parallelism", plot_parallelism),
745
+ )
746
+ model_size_b200_xlim: tuple[float, float] | None = None
747
+ for gpu_tag in ("b200", "h100"):
748
+ suffix = f"_{gpu_tag}"
749
+ for name, plotter in dual_gpu:
750
+ path = indir / f"{name}{suffix}.csv"
751
+ if not path.exists():
752
+ logger.warning("Missing %s: skipping", path)
753
+ continue
754
+
755
+ df = pd.read_csv(path)
756
+ df = df[df["variant"].isin(wanted_models)].copy()
757
+ logger.info("Loaded %s: %d rows", path.name, len(df))
758
+ # df = pd.read_csv(path)
759
+ #logger.info("Loaded %s: %d rows", path.name, len(df))
760
+ if name == "model_size":
761
+ if gpu_tag == "h100" and model_size_b200_xlim is not None:
762
+ plot_model_size(df, outdir, lm, suffix=suffix, pareto_xlim=model_size_b200_xlim)
763
+ else:
764
+ resolved = plot_model_size(df, outdir, lm, suffix=suffix)
765
+ if gpu_tag == "b200":
766
+ model_size_b200_xlim = resolved
767
+ else:
768
+ plotter(df, outdir, lm, suffix=suffix)
769
+
770
+ cross_gpu = (("hardware", plot_hardware), ("precision", plot_precision))
771
+ for name, plotter in cross_gpu:
772
+ path = indir / f"{name}_b200.csv"
773
+ if not path.exists():
774
+ logger.warning("Missing %s: skipping", path)
775
+ continue
776
+ df = pd.read_csv(path)
777
+ logger.info("Loaded %s: %d rows", path.name, len(df))
778
+ plotter(df, outdir, lm, suffix="_b200")
779
+
780
+ logger.info("Wrote figures to %s", outdir)
781
+
782
+
783
+ if __name__ == "__main__":
784
+ tyro.cli(main)
examples/model_insights/precision.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Weight-precision sweep on the IEEE 13 scenario.
2
+
3
+ Sweeps bf16 vs FP8 on three matched-hardware pairs of the Qwen 3 235B
4
+ A22B family:
5
+
6
+ - Instruct, H100 8 GPU, `lm-arena-chat`.
7
+ - Thinking, H100 8 GPU, `gpqa`.
8
+ - Thinking, B200 4 GPU, `gpqa`.
9
+
10
+ Within each pair, replica count is match-peak sized so the bf16 variant's
11
+ peak inference power at its largest feasible batch matches the shared
12
+ 3.12 MW anchor; the FP8 sibling runs at the same replica count, so the
13
+ DC footprint is identical within the pair.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Literal
22
+
23
+ import common as aic
24
+ import tyro
25
+
26
+ from openg2g.datacenter.config import ModelDeployment, ReplicaSchedule
27
+
28
+ logger = logging.getLogger("model_insights.precision")
29
+
30
+
31
+ # (pair_label, bf16_spec_label, fp8_spec_label, hardware_description, deadline_ms)
32
+ PAIRS: list[tuple[str, str, str, str, int]] = [
33
+ (
34
+ "qwen-235b-a22b-instruct-h100-8gpu",
35
+ "Qwen3-235B-A22B-Instruct-8GPU",
36
+ "Qwen3-235B-A22B-Instruct-FP8-8GPU",
37
+ "H100 8 GPU (lm-arena-chat)",
38
+ 100,
39
+ ),
40
+ (
41
+ "qwen-235b-a22b-thinking-h100-8gpu",
42
+ "Qwen3-235B-A22B-Thinking-8GPU",
43
+ "Qwen3-235B-A22B-Thinking-FP8-8GPU",
44
+ "H100 8 GPU (gpqa)",
45
+ 100,
46
+ ),
47
+ (
48
+ "qwen-235b-a22b-thinking-b200-4gpu",
49
+ "Qwen3-235B-A22B-Thinking-4GPU-B200",
50
+ "Qwen3-235B-A22B-Thinking-FP8-4GPU-B200",
51
+ "B200 4 GPU (gpqa)",
52
+ 100,
53
+ ),
54
+ ]
55
+
56
+ ANCHOR_PEAK_KW: float = 3_120.0
57
+ DEFAULT_MODES: tuple[aic.Mode, ...] = ("baseline-no-tap", "ofo-no-tap")
58
+ DEFAULT_OUT = Path(__file__).resolve().parent / "outputs" / "precision_b200.csv"
59
+
60
+
61
+ @dataclass
62
+ class Row:
63
+ experiment: str
64
+ variant: str
65
+ pair: str
66
+ precision_label: str
67
+ hardware: str
68
+ mode: str
69
+ seed: int
70
+ num_replicas: int
71
+ gpus_per_replica: int
72
+ deadline_ms: int
73
+ feasible_batch_min: int
74
+ feasible_batch_max: int
75
+ initial_batch: int
76
+ violation_time_s: float
77
+ integral_violation_pu_s: float
78
+ worst_vmin: float
79
+ worst_vmax: float
80
+ mean_throughput_tps: float
81
+ integrated_throughput_tokens: float
82
+ itl_deadline_fraction: float
83
+ achievable_power_range_mw: float
84
+
85
+
86
+ def run_variant(
87
+ pair: str,
88
+ spec_label: str,
89
+ precision_label: str,
90
+ hardware: str,
91
+ num_replicas: int,
92
+ *,
93
+ seed: int,
94
+ shared: aic.SharedData,
95
+ modes: tuple[aic.Mode, ...],
96
+ total_duration_s: int,
97
+ deadline_ms: int,
98
+ ) -> list[Row]:
99
+ base = aic.SPECS[spec_label]
100
+ spec = aic.restrict_spec_by_deadline(base, shared.logistic_models, deadline_ms / 1000.0)
101
+ deployments = [
102
+ (
103
+ ModelDeployment(spec=spec, initial_batch_size=max(spec.feasible_batch_sizes)),
104
+ ReplicaSchedule(initial=num_replicas),
105
+ )
106
+ ]
107
+
108
+ apr_mw = aic.compute_achievable_power_range(deployments=deployments, logistic_models=shared.logistic_models)
109
+
110
+ # Match-peak sizing can push replica × GPU count past the preset's
111
+ # 7,200 GPU cap; provision the GPU budget for this deployment plus
112
+ # headroom.
113
+ gpu_budget = max(7200, num_replicas * spec.gpus_per_replica + 200)
114
+ scenario = aic.build_scenario(
115
+ deployments,
116
+ shared=shared,
117
+ overrides=aic.ScenarioOverrides(seed=seed, total_gpu_capacity=gpu_budget),
118
+ )
119
+ rows: list[Row] = []
120
+ for mode in modes:
121
+ result = aic.run_scenario(scenario, shared.logistic_models, mode=mode, total_duration_s=total_duration_s)
122
+ rows.append(
123
+ Row(
124
+ experiment="precision",
125
+ variant=spec_label,
126
+ pair=pair,
127
+ precision_label=precision_label,
128
+ hardware=hardware,
129
+ mode=mode,
130
+ seed=seed,
131
+ num_replicas=num_replicas,
132
+ gpus_per_replica=spec.gpus_per_replica,
133
+ deadline_ms=deadline_ms,
134
+ feasible_batch_min=min(spec.feasible_batch_sizes),
135
+ feasible_batch_max=max(spec.feasible_batch_sizes),
136
+ initial_batch=deployments[0][0].initial_batch_size,
137
+ violation_time_s=result.voltage.violation_time_s,
138
+ integral_violation_pu_s=result.voltage.integral_violation_pu_s,
139
+ worst_vmin=result.voltage.worst_vmin,
140
+ worst_vmax=result.voltage.worst_vmax,
141
+ mean_throughput_tps=result.performance.mean_throughput_tps,
142
+ integrated_throughput_tokens=result.performance.integrated_throughput_tokens,
143
+ itl_deadline_fraction=result.performance.itl_deadline_fraction,
144
+ achievable_power_range_mw=apr_mw,
145
+ )
146
+ )
147
+ logger.info(
148
+ " [%s (%s) n_rep=%d dl=%dms seed=%d mode=%s] viol=%.2fs integral=%.4f "
149
+ "vmin=%.4f thpt=%.1fk tok/s itl_miss=%.2f%% APR=%.2f MW",
150
+ spec_label,
151
+ precision_label,
152
+ num_replicas,
153
+ deadline_ms,
154
+ seed,
155
+ mode,
156
+ result.voltage.violation_time_s,
157
+ result.voltage.integral_violation_pu_s,
158
+ result.voltage.worst_vmin,
159
+ result.performance.mean_throughput_tps / 1e3,
160
+ result.performance.itl_deadline_fraction * 100.0,
161
+ apr_mw,
162
+ )
163
+ return rows
164
+
165
+
166
+ def main(
167
+ seeds: tuple[int, ...] = (0, 1, 2, 3, 4),
168
+ total_duration_s: int = aic.TOTAL_DURATION_S,
169
+ modes: tuple[
170
+ Literal["baseline-no-tap", "baseline-tap-change", "ofo-no-tap", "ofo-tap-change"], ...
171
+ ] = DEFAULT_MODES,
172
+ out: Path = DEFAULT_OUT,
173
+ ) -> None:
174
+ logging.basicConfig(
175
+ level=logging.INFO, format="%(asctime)s %(levelname)s [%(name)s] %(message)s", datefmt="%H:%M:%S"
176
+ )
177
+ logging.getLogger("httpx").setLevel(logging.WARNING)
178
+
179
+ shared = aic.load_shared_data()
180
+
181
+ out.parent.mkdir(parents=True, exist_ok=True)
182
+
183
+ logger.info(
184
+ "Running %d (bf16, FP8) pairs × %d seeds × %d modes on IEEE 13",
185
+ len(PAIRS),
186
+ len(seeds),
187
+ len(modes),
188
+ )
189
+
190
+ all_rows: list[Row] = []
191
+ for pair, bf16_label, fp8_label, hw, deadline_ms in PAIRS:
192
+ # Match-peak sizing uses the bf16 variant; FP8 runs at the same
193
+ # replica count so DC footprint is identical within the pair.
194
+ bf16_spec = aic.restrict_spec_by_deadline(aic.SPECS[bf16_label], shared.logistic_models, deadline_ms / 1000.0)
195
+ n_replicas = aic.compute_matched_peak_replicas(bf16_spec, ANCHOR_PEAK_KW, shared.logistic_models)
196
+ logger.info("=== pair=%s (%s) n_replicas=%d (match-peak @ %.0f kW) ===", pair, hw, n_replicas, ANCHOR_PEAK_KW)
197
+ for precision_label, spec_label in (("bf16", bf16_label), ("FP8", fp8_label)):
198
+ for seed in seeds:
199
+ all_rows.extend(
200
+ run_variant(
201
+ pair,
202
+ spec_label,
203
+ precision_label,
204
+ hw,
205
+ n_replicas,
206
+ seed=seed,
207
+ shared=shared,
208
+ modes=modes,
209
+ total_duration_s=total_duration_s,
210
+ deadline_ms=deadline_ms,
211
+ )
212
+ )
213
+
214
+ aic.write_csv(all_rows, out)
215
+ logger.info("Wrote %d rows to %s", len(all_rows), out)
216
+
217
+
218
+ if __name__ == "__main__":
219
+ tyro.cli(main)
examples/model_insights/systems.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IEEE test feeder constants.
2
+
3
+ Feeder-specific constants (DSS paths, regulator names, initial taps,
4
+ excluded buses, source voltage, bus voltage levels) are defined here.
5
+
6
+ Experiment-specific parameters (datacenter sizing, controller tuning,
7
+ workload scenarios, model specs, simulation defaults) belong in
8
+ `experiment.py` or inline in each example script.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ from openg2g.grid.config import TapPosition
16
+
17
+ GRID_DATA_DIR = Path(__file__).resolve().parent.parent.parent / "data" / "grid"
18
+
19
+ TAP_STEP = 0.00625 # Standard 32-step regulator: +-10% in 32 steps
20
+
21
+
22
+ def tap(steps: int) -> float:
23
+ """Convert integer tap step to per-unit ratio. E.g., `tap(14)` -> 1.0875."""
24
+ return 1.0 + steps * TAP_STEP
25
+
26
+
27
+ # IEEE test feeder constants
28
+
29
+
30
+ def ieee13() -> dict:
31
+ """IEEE 13-bus test feeder constants."""
32
+ return dict(
33
+ dss_case_dir=GRID_DATA_DIR / "ieee13",
34
+ dss_master_file="IEEE13Bus.dss",
35
+ bus_kv=4.16,
36
+ source_pu=1.0,
37
+ initial_taps=TapPosition(
38
+ regulators={
39
+ "creg1a": tap(14),
40
+ "creg1b": tap(6),
41
+ "creg1c": tap(15),
42
+ }
43
+ ),
44
+ exclude_buses=["sourcebus", "650", "rg60"],
45
+ )
46
+
47
+
48
+ def ieee34() -> dict:
49
+ """IEEE 34-bus (half-line variant) test feeder constants."""
50
+ # fmt: off
51
+ return dict(
52
+ dss_case_dir=GRID_DATA_DIR / "ieee34",
53
+ dss_master_file="IEEE34Bus.dss",
54
+ bus_kv=24.9,
55
+ source_pu=1.09,
56
+ initial_taps=TapPosition(
57
+ regulators={
58
+ "creg1a": tap(12),
59
+ "creg1b": tap(8),
60
+ "creg1c": tap(10),
61
+ "creg2a": tap(8),
62
+ "creg2b": tap(8),
63
+ "creg2c": tap(8),
64
+ }
65
+ ),
66
+ exclude_buses=[
67
+ "sourcebus", "800", "802", "806", "808", "810", "812", "814", "888", "890",
68
+ ],
69
+ regulator_zones={
70
+ "creg1": ["814r", "850", "816", "824", "828", "830", "854"],
71
+ "creg2": ["852r", "832", "858", "834", "860", "836", "840", "862", "842", "844", "846", "848"],
72
+ },
73
+ )
74
+ # fmt: on
75
+
76
+
77
+ def ieee123() -> dict:
78
+ """IEEE 123-bus test feeder constants."""
79
+ # fmt: off
80
+ return dict(
81
+ dss_case_dir=GRID_DATA_DIR / "ieee123",
82
+ dss_master_file="IEEE123Bus.dss",
83
+ bus_kv=4.16,
84
+ source_pu=1.0,
85
+ initial_taps=TapPosition(
86
+ regulators={
87
+ "creg1a": tap(9),
88
+ "creg2a": tap(5),
89
+ "creg3a": tap(5),
90
+ "creg3c": tap(5),
91
+ "creg4a": tap(14),
92
+ "creg4b": tap(1),
93
+ "creg4c": tap(4),
94
+ }
95
+ ),
96
+ exclude_buses=[
97
+ "sourcebus", "150", "150r", "149", "9r", "25r", "160r", "61s", "610", "300_open", "94_open",
98
+ ],
99
+ zones={
100
+ "z1_sw": [
101
+ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
102
+ "12", "13", "14", "15", "16", "17", "18", "19", "20", "34",
103
+ ],
104
+ "z2_nw": [
105
+ "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "35", "36",
106
+ "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51",
107
+ ],
108
+ "z3_se": [
109
+ "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66",
110
+ "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81",
111
+ "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96",
112
+ ],
113
+ "z4_ne": [
114
+ "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110",
115
+ "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123",
116
+ ],
117
+ },
118
+ )
119
+ # fmt: on
120
+
121
+
122
+ SYSTEMS = {"ieee13": ieee13, "ieee34": ieee34, "ieee123": ieee123}