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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
#!/usr/bin/env python3
"""
TRACE study workload driver.

Runs one labelled workload window on this node: distributed training, or one
of the deliberately similar non-training workloads used as negatives for the
likelihood-ratio calibration.

  - Dependencies: Python 3 standard library plus PyTorch. Nothing else.
  - Network: torch.distributed traffic between the study nodes listed in
    nodes.conf only (rendezvous on MASTER_ADDR:MASTER_PORT, then NCCL or
    Gloo). No other connections. Single-node workloads open no sockets.
  - Reads: nothing outside this bundle. Training data is generated
    synthetically on the GPU; no dataset is required on the node.
  - Writes: checkpoints and generated files under --scratch (rotated, capped),
    and one ground-truth JSON per run under --out/ground_truth/.

Invoked by orchestrator.py; can also be run by hand for testing:
  python3 workloads.py --kind burn --duration 30 --out ./out --scratch ./scratch
"""
import argparse
import hashlib
import json
import math
import os
import random
import shutil
import signal
import socket
import struct
import sys
import time
from datetime import datetime, timezone, timedelta

import torch
import torch.nn as nn
import torch.nn.functional as F

STOP = False

# workload kinds that use torch.distributed across nodes
DIST_KINDS = {"train", "grad_eval", "fabric_bench", "tp_infer", "hpc"}


def log(msg):
    sys.stderr.write(f"{datetime.now(timezone.utc).isoformat()} workload {msg}\n")
    sys.stderr.flush()


def on_term(sig, frm):
    global STOP
    STOP = True


class Deadline:
    def __init__(self, seconds):
        self.t_end = time.time() + seconds

    def expired(self):
        return STOP or time.time() >= self.t_end

    def remaining(self):
        return max(0.0, self.t_end - time.time())


# ---------------------------------------------------------------- distributed
def dist_env():
    return int(os.environ.get("WORLD_SIZE", "1")), int(os.environ.get("RANK", "0"))


def init_dist():
    world, rank = dist_env()
    if world <= 1:
        return world, rank
    import torch.distributed as dist

    backend = "nccl" if torch.cuda.is_available() else "gloo"
    dist.init_process_group(
        backend=backend, world_size=world, rank=rank,
        timeout=timedelta(seconds=1800),
    )
    log(f"dist ready: backend={backend} rank={rank} world={world}")
    return world, rank


def cleanup_dist():
    import torch.distributed as dist

    if dist.is_available() and dist.is_initialized():
        dist.destroy_process_group()


def pick_device():
    if torch.cuda.is_available():
        return torch.device("cuda:0")
    return torch.device("cpu")


def autocast_ctx(device):
    if device.type == "cuda" and torch.cuda.is_bf16_supported():
        return torch.autocast("cuda", dtype=torch.bfloat16)
    import contextlib

    return contextlib.nullcontext()


def sync(device):
    if device.type == "cuda":
        torch.cuda.synchronize()


def coll_flags(device, world, stop, gap=False):
    """Agree on loop decisions across ranks so no rank ever exits a loop
    while a peer is still waiting in a collective. MAX-reduce of two flags:
    stop fires if ANY rank wants to stop; gap carries rank 0's decision."""
    if world <= 1:
        return stop, gap
    import torch.distributed as dist

    t = torch.tensor(
        [1.0 if stop else 0.0, 1.0 if gap else 0.0],
        device=device if device.type == "cuda" else "cpu",
    )
    dist.all_reduce(t, op=dist.ReduceOp.MAX)
    return bool(t[0] > 0), bool(t[1] > 0)


# ---------------------------------------------------------------- model
class Attention(nn.Module):
    def __init__(self, dim, heads):
        super().__init__()
        self.heads = heads
        self.qkv = nn.Linear(dim, 3 * dim, bias=False)
        self.proj = nn.Linear(dim, dim, bias=False)

    def forward(self, x):
        b, t, d = x.shape
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        q = q.view(b, t, self.heads, -1).transpose(1, 2)
        k = k.view(b, t, self.heads, -1).transpose(1, 2)
        v = v.view(b, t, self.heads, -1).transpose(1, 2)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        y = y.transpose(1, 2).reshape(b, t, d)
        return self.proj(y)


class Block(nn.Module):
    def __init__(self, dim, heads):
        super().__init__()
        self.ln1 = nn.LayerNorm(dim)
        self.attn = Attention(dim, heads)
        self.ln2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(
            nn.Linear(dim, 4 * dim, bias=False),
            nn.GELU(),
            nn.Linear(4 * dim, dim, bias=False),
        )

    def forward(self, x):
        x = x + self.attn(self.ln1(x))
        x = x + self.mlp(self.ln2(x))
        return x


class GPT(nn.Module):
    def __init__(self, vocab, dim, layers, heads, seq):
        super().__init__()
        self.seq = seq
        self.tok = nn.Embedding(vocab, dim)
        self.pos = nn.Embedding(seq, dim)
        self.blocks = nn.ModuleList(Block(dim, heads) for _ in range(layers))
        self.ln_f = nn.LayerNorm(dim)
        self.head = nn.Linear(dim, vocab, bias=False)

    def forward(self, idx, targets=None):
        b, t = idx.shape
        pos = torch.arange(t, device=idx.device)
        x = self.tok(idx) + self.pos(pos)
        for blk in self.blocks:
            x = blk(x)
        logits = self.head(self.ln_f(x))
        loss = None
        if targets is not None:
            loss = F.cross_entropy(
                logits.view(-1, logits.size(-1)), targets.reshape(-1)
            )
        return logits, loss


def build_model(p, device):
    torch.manual_seed(p["seed"])
    m = GPT(p["vocab"], p["dim"], p["layers"], p["heads"], p["seq"]).to(device)
    n = sum(q.numel() for q in m.parameters())
    log(f"model built: {n/1e6:.1f}M params")
    return m, n


def synth_batch(p, batch, device):
    # synthetic token stream; the study measures compute/communication
    # structure, not model quality, so random tokens are sufficient
    x = torch.randint(0, p["vocab"], (batch, p["seq"]), device=device)
    y = torch.roll(x, -1, dims=1)
    return x, y


# ---------------------------------------------------------------- checkpoint
class Checkpointer:
    """Writes checkpoints under scratch, keeps the newest `keep`, logs sizes.

    mode "normal":       one torch.save file, the standard pattern.
    mode "small_writes": the E1 evasion — the same state split into many
                         small files with a generic directory name.
    """

    def __init__(self, scratch, run_id, mode, keep, rank):
        self.dir = os.path.join(scratch, f"ckpt_{run_id}_rank{rank}")
        os.makedirs(self.dir, exist_ok=True)
        self.mode = mode
        self.keep = keep
        self.events = []

    def save(self, model, opt, step):
        t0 = time.time()
        state = {
            "step": step,
            "model": model.state_dict(),
            "opt": opt.state_dict() if opt is not None else None,
        }
        if self.mode == "small_writes":
            d = os.path.join(self.dir, f"data_export_{step:08d}")
            os.makedirs(d, exist_ok=True)
            i, buf, bufsz = 0, {}, 0
            for k, v in state["model"].items():
                buf[k] = v
                bufsz += v.numel() * v.element_size()
                if bufsz >= 8 * 2**20:
                    self._save_part(d, i, buf)
                    i, buf, bufsz = i + 1, {}, 0
            if buf:
                self._save_part(d, i, buf)
            path = d
        else:
            path = os.path.join(self.dir, f"step_{step:08d}.pt")
            with open(path, "wb") as f:
                torch.save(state, f)
                f.flush()
                os.fsync(f.fileno())
        nbytes = self._du(path)
        self._rotate()
        ev = {"t": time.time(), "step": step, "bytes": nbytes,
              "secs": round(time.time() - t0, 3)}
        self.events.append(ev)
        log(f"checkpoint step={step} {nbytes/2**20:.0f} MiB in {ev['secs']}s")
        return path

    def latest(self):
        entries = sorted(os.listdir(self.dir))
        return os.path.join(self.dir, entries[-1]) if entries else None

    def _save_part(self, d, i, buf):
        p = os.path.join(d, f"part_{i:05d}.bin")
        with open(p, "wb") as f:
            torch.save(buf, f)
            f.flush()
            os.fsync(f.fileno())

    def _du(self, path):
        if os.path.isfile(path):
            return os.path.getsize(path)
        return sum(
            os.path.getsize(os.path.join(r, f))
            for r, _, fs in os.walk(path) for f in fs
        )

    def _rotate(self):
        entries = sorted(os.listdir(self.dir))
        for e in entries[: max(0, len(entries) - self.keep)]:
            p = os.path.join(self.dir, e)
            shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)


# ---------------------------------------------------------------- train
TRAIN_DEFAULTS = {
    "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16,
    "seq": 1024, "micro_batch": 8, "accum": 8, "lr": 3e-4,
    "strategy": "ddp",           # ddp | fsdp | paced
    "ckpt_interval_s": 900, "ckpt_mode": "normal", "ckpt_keep": 2,
    "ckpt_include_optimizer": True,
    "preallocate_optimizer_state": False,
    "update_weights": True,
    "fragment_run_s": 0, "fragment_gap_s": 0,   # E3: run/gap chunking
    "pace_gap_ms": 40, "pace_chunk_mb": 24,     # E2: paced fabric traffic
}

GRAD_EVAL_DEFAULTS = dict(
    TRAIN_DEFAULTS,
    strategy="ddp",
    update_weights=False,
    ckpt_include_optimizer=False,
)


def parameter_probe(model, max_values=4096):
    """Hash a fixed, non-reversible sample of parameters for ground truth.

    The positional embedding is preferred because every training step touches
    it. The probe establishes whether this controlled fixture changed weights;
    it is direct runner ground truth, not an infrastructure observable.
    """
    named = list(model.named_parameters())
    chosen = next(
        ((name, value) for name, value in named if name.endswith("pos.weight")),
        named[0] if named else (None, None),
    )
    name, value = chosen
    if value is None:
        return None
    sample = value.detach().reshape(-1)[:max_values].float().cpu().tolist()
    digest = hashlib.sha256()
    for item in sample:
        digest.update(struct.pack("<f", float(item)))
    return {"parameter": name, "sample_values": len(sample),
            "sha256": digest.hexdigest()}


def flat_chunks(params, chunk_mb):
    """Group parameters into roughly chunk_mb-sized lists for allreduce."""
    groups, cur, sz = [], [], 0
    limit = chunk_mb * 2**20
    for p in params:
        cur.append(p)
        sz += p.numel() * p.element_size()
        if sz >= limit:
            groups.append(cur)
            cur, sz = [], 0
    if cur:
        groups.append(cur)
    return groups


def preallocate_adam_state(opt):
    """Materialize Adam state without changing a parameter.

    AdamW normally allocates its two moment tensors on the first optimizer
    step. The paired identifiability experiment uses this on both arms so the
    update and no-update workloads have the same steady-state GPU allocation.
    """
    saved = []
    for group in opt.param_groups:
        saved.append((group, group["lr"], group.get("weight_decay", 0.0)))
        group["lr"] = 0.0
        group["weight_decay"] = 0.0
        for parameter in group["params"]:
            parameter.grad = torch.zeros_like(parameter)
    opt.step()
    for state in opt.state.values():
        step = state.get("step")
        if torch.is_tensor(step):
            step.zero_()
        elif step is not None:
            state["step"] = 0
    for group, lr, weight_decay in saved:
        group["lr"] = lr
        group["weight_decay"] = weight_decay
    opt.zero_grad(set_to_none=True)


def run_train(args, p, dl):
    import torch.distributed as dist

    world, rank = init_dist()
    device = pick_device()
    model, nparams = build_model(p, device)
    strategy = p["strategy"]
    update_weights = bool(p["update_weights"])
    probe_before = parameter_probe(model) if strategy != "fsdp" else None
    # The model seed is shared so every DDP rank starts from identical
    # weights; the data seed is rank-specific, as in real data parallelism.
    data_seed = int(p["seed"]) + 100003 * rank
    torch.manual_seed(data_seed)

    if strategy == "fsdp" and world > 1 and device.type == "cuda":
        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
        from torch.distributed.fsdp.wrap import ModuleWrapPolicy

        model = FSDP(model, auto_wrap_policy=ModuleWrapPolicy({Block}))
    elif strategy == "fsdp":
        log("fsdp needs cuda+multi-rank; falling back to ddp")
        strategy = "ddp"
    if strategy == "ddp" and world > 1:
        model = nn.parallel.DistributedDataParallel(
            model, device_ids=[0] if device.type == "cuda" else None
        )

    opt = torch.optim.AdamW(model.parameters(), lr=p["lr"])
    if p["preallocate_optimizer_state"]:
        preallocate_adam_state(opt)
        log("preallocated AdamW state without changing parameters")
    ck = Checkpointer(args.scratch, args.run_id, p["ckpt_mode"],
                      p["ckpt_keep"], rank)
    write_ckpt = (strategy == "fsdp") or rank == 0  # fsdp saves shards per rank
    # save the unwrapped module so a resume can load with matching keys
    ckpt_model = model.module if (strategy == "ddp" and world > 1) else model
    ckpt_opt = opt if p["ckpt_include_optimizer"] else None
    acc = None
    if strategy == "paced":
        chunk_groups = flat_chunks(list(model.parameters()), p["pace_chunk_mb"])

    def microbatch(sync_grads):
        x, y = synth_batch(p, p["micro_batch"], device)
        ctx = None
        if strategy == "ddp" and world > 1 and not sync_grads:
            ctx = model.no_sync()
            ctx.__enter__()
        with autocast_ctx(device):
            _, loss = model(x, y)
        (loss / p["accum"]).backward()
        if ctx is not None:
            ctx.__exit__(None, None, None)
        return loss

    def paced_reduce():
        # E2: spread gradient traffic into jittered, chunked allreduces so the
        # fabric shows no clean step-boundary burst
        for grp in chunk_groups:
            flat = torch.cat([q.grad.reshape(-1) for q in grp])
            dist.all_reduce(flat)
            flat /= world
            off = 0
            for q in grp:
                q.grad.copy_(flat[off:off + q.numel()].view_as(q.grad))
                off += q.numel()
            time.sleep(random.expovariate(1000.0 / max(1, p["pace_gap_ms"])))

    # comms fraction probe: a few compute-only steps vs full steps
    comm_frac = None
    if strategy == "ddp" and world > 1:
        sync(device); t0 = time.time()
        for _ in range(2):
            for _ in range(p["accum"]):
                microbatch(sync_grads=False)
            opt.zero_grad(set_to_none=True)
        sync(device); t_compute = (time.time() - t0) / 2

    steps, optimizer_steps, t_step_sum, last_ckpt = 0, 0, 0.0, time.time()
    step_events = []
    losses = []
    frag_next_gap = (time.time() + p["fragment_run_s"]
                     if p["fragment_run_s"] > 0 else None)
    loop_start = time.time()
    while True:
        # loop decisions must be identical on every rank (see coll_flags)
        gap_due = (rank == 0 and frag_next_gap is not None
                   and time.time() >= frag_next_gap)
        stop, gap = coll_flags(device, world, dl.expired(), gap_due)
        if stop:
            break
        if gap:
            # E3: pause, then resume from checkpoint, as a fragmented run would
            if write_ckpt:
                ck.save(ckpt_model, ckpt_opt, steps)
            if world > 1:
                dist.barrier()
            log(f"fragment gap {p['fragment_gap_s']}s")
            time.sleep(min(p["fragment_gap_s"], dl.remaining()))
            latest = ck.latest()
            if latest and os.path.isfile(latest):
                state = torch.load(latest, map_location=device,
                                   weights_only=False)
                ckpt_model.load_state_dict(state["model"])
                if state.get("opt") is not None:
                    opt.load_state_dict(state["opt"])
                log("resumed from checkpoint")
            frag_next_gap = time.time() + p["fragment_run_s"]
            if world > 1:
                dist.barrier()
        t0 = time.time()
        for i in range(p["accum"]):
            last = i == p["accum"] - 1
            loss = microbatch(sync_grads=last)
            if strategy == "paced" and world > 1:
                # re-reducing the accumulated grad each microbatch is
                # mathematically a no-op on already-averaged terms, so the
                # result stays correct while the traffic loses its step burst
                paced_reduce()
        if update_weights:
            opt.step()
            optimizer_steps += 1
        opt.zero_grad(set_to_none=True)
        sync(device)
        steps += 1
        step_duration = time.time() - t0
        t_step_sum += step_duration
        step_events.append([
            round(time.time(), 6), round(step_duration, 6)
        ])
        losses.append(float(loss.detach()))
        if steps % 10 == 0:
            log(f"step {steps} loss {losses[-1]:.3f} "
                f"({t_step_sum/steps:.2f}s/step)")
        if (p["ckpt_mode"] != "off" and write_ckpt
                and time.time() - last_ckpt >= p["ckpt_interval_s"]):
            ck.save(ckpt_model, ckpt_opt, steps)
            last_ckpt = time.time()
    loop_end = time.time()
    if strategy == "ddp" and world > 1 and steps > 0:
        t_full = t_step_sum / steps
        comm_frac = max(0.0, round(1.0 - t_compute / t_full, 3))

    tokens = steps * world * p["accum"] * p["micro_batch"] * p["seq"]
    equivalent_6nd = 6.0 * nparams * tokens
    probe_model = model.module if (strategy == "ddp" and world > 1) else model
    probe_after = parameter_probe(probe_model) if strategy != "fsdp" else None
    weights_changed = (
        probe_before is not None and probe_after is not None
        and probe_before["sha256"] != probe_after["sha256"]
    )
    return {
        "param_count": nparams, "steps": steps, "tokens_global": tokens,
        "model_seed": int(p["seed"]), "data_seed": data_seed,
        "loop_start_epoch_s": loop_start,
        "loop_end_epoch_s": loop_end,
        "step_events_end_epoch_s_duration_s": step_events,
        "ddp_gradient_syncs": (
            steps if strategy == "ddp" and world > 1 else None
        ),
        "optimizer_steps": optimizer_steps,
        "purpose_ground_truth": (
            "parameter_update" if update_weights else "gradient_evaluation_no_update"
        ),
        "flop_6nd_estimate": equivalent_6nd if update_weights else None,
        "work_6nd_equivalent": equivalent_6nd,
        "step_time_s_mean": round(t_step_sum / max(1, steps), 3),
        "comm_fraction_est": comm_frac,
        "checkpoint_includes_optimizer": bool(p["ckpt_include_optimizer"]),
        "optimizer_state_preallocated": bool(p["preallocate_optimizer_state"]),
        "parameter_probe_before": probe_before,
        "parameter_probe_after": probe_after,
        "parameter_probe_changed": weights_changed,
        "loss_first": losses[0] if losses else None,
        "loss_last": losses[-1] if losses else None,
        "checkpoints": ck.events,
    }


# ---------------------------------------------------------------- negatives
FB_DEFAULTS = {"sizes_mb": [1, 4, 16, 64, 256], "iters_per_size": 20}


def run_fabric_bench(args, p, dl):
    """N1: nccl-tests-style collective sweep. Regular, training-free fabric."""
    import torch.distributed as dist

    world, rank = init_dist()
    device = pick_device()
    if world <= 1:
        log("fabric_bench needs >=2 ranks; nothing to benchmark on one node")
        while not dl.expired():
            time.sleep(min(5, dl.remaining()))
        return {"skipped": "needs >=2 ranks"}
    stats = {"rounds": 0, "bytes_allreduce": 0, "bytes_allgather": 0}
    stop = False
    while not stop:
        for mb in p["sizes_mb"]:
            n = mb * 2**20 // 4
            t = torch.ones(n, device=device)
            for _ in range(p["iters_per_size"]):
                dist.all_reduce(t)
                stats["bytes_allreduce"] += n * 4
            gather = [torch.empty_like(t) for _ in range(world)]
            for _ in range(max(1, p["iters_per_size"] // 4)):
                dist.all_gather(gather, t)
                stats["bytes_allgather"] += n * 4 * world
            sync(device)
            stop, _ = coll_flags(device, world, dl.expired())
            if stop:
                break
        stats["rounds"] += 1
    return stats


TP_DEFAULTS = {
    "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16,
    "seq": 512, "rate_hz": 4.0, "max_batch": 16,
}


class TPMlp(nn.Module):
    """Megatron-style MLP shard: column-parallel then row-parallel + allreduce."""

    def __init__(self, dim, world):
        super().__init__()
        self.fc1 = nn.Linear(dim, 4 * dim // world, bias=False)
        self.fc2 = nn.Linear(4 * dim // world, dim, bias=False)

    def forward(self, x):
        import torch.distributed as dist

        y = self.fc2(F.gelu(self.fc1(x)))
        if dist.is_initialized() and dist.get_world_size() > 1:
            dist.all_reduce(y)
        return y


def run_tp_infer(args, p, dl):
    """N2: tensor-parallel inference. Heavy per-layer collectives, no updates."""
    world, rank = init_dist()
    device = pick_device()
    model, _ = build_model(p, device)
    for blk in model.blocks:
        blk.mlp = TPMlp(p["dim"], max(1, world)).to(device)
    model.eval()
    # every rank must draw the same batch size or the allreduce shapes differ,
    # so the request stream comes from a shared-seed rng (a TP group serves
    # the same request on all ranks anyway)
    rng = random.Random(p["seed"])
    stats = {"requests": 0, "tokens": 0}
    with torch.no_grad():
        while True:
            stop, _ = coll_flags(device, world, dl.expired())
            if stop:
                break
            batch = rng.randint(1, p["max_batch"])
            x, _ = synth_batch(p, batch, device)
            with autocast_ctx(device):
                model(x)
            sync(device)
            stats["requests"] += batch
            stats["tokens"] += batch * p["seq"]
            time.sleep(rng.expovariate(p["rate_hz"]))
    return stats


HPC_DEFAULTS = {"grid": 8192, "halo_every": 1, "residual_every": 200}


def run_hpc(args, p, dl):
    """N5: Jacobi stencil with halo exchange, the classic HPC/MPI pattern."""
    import torch.distributed as dist

    world, rank = init_dist()
    device = pick_device()
    n = p["grid"]
    rows = max(4, n // max(1, world))
    grid = torch.rand(rows + 2, n, device=device)
    stats = {"iters": 0, "halo_exchanges": 0, "residual_allreduces": 0}
    stop = False
    while not stop:
        # a fixed block of iterations between collective stop checks keeps
        # every rank's collective sequence identical
        for _ in range(p["residual_every"]):
            if world > 1:
                reqs = []
                if rank > 0:
                    reqs.append(dist.isend(grid[1].contiguous(), rank - 1))
                    reqs.append(dist.irecv(grid[0], rank - 1))
                if rank < world - 1:
                    reqs.append(dist.isend(grid[rows].contiguous(), rank + 1))
                    reqs.append(dist.irecv(grid[rows + 1], rank + 1))
                for r in reqs:
                    r.wait()
                stats["halo_exchanges"] += 1
            inner = grid[1:rows + 1]
            new = 0.25 * (
                grid[0:rows] + grid[2:rows + 2]
                + torch.roll(inner, 1, dims=1) + torch.roll(inner, -1, dims=1)
            )
            grid[1:rows + 1] = new
            stats["iters"] += 1
        res = (new - inner).abs().sum()
        if world > 1:
            dist.all_reduce(res)
            stats["residual_allreduces"] += 1
        sync(device)
        stop, _ = coll_flags(device, world, dl.expired())
    return stats


INFER_DEFAULTS = {
    "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16,
    "seq": 1024, "batch": 32,
}


def run_batch_infer(args, p, dl):
    """N3: continuous large-batch inference. High activity, no fabric."""
    device = pick_device()
    model, _ = build_model(p, device)
    model.eval()
    stats = {"batches": 0, "tokens": 0}
    with torch.no_grad():
        while not dl.expired():
            x, _ = synth_batch(p, p["batch"], device)
            with autocast_ctx(device):
                model(x)
            sync(device)
            stats["batches"] += 1
            stats["tokens"] += p["batch"] * p["seq"]
    return stats


SERVE_DEFAULTS = {
    "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16,
    "seq": 256, "base_rate_hz": 4.0, "rate_swing": 0.6, "max_batch": 4,
}


def run_serving(args, p, dl):
    """S1: request-driven serving. Poisson arrivals, slowly varying rate."""
    device = pick_device()
    model, _ = build_model(p, device)
    model.eval()
    t_start = time.time()
    total = dl.remaining() + 1
    stats = {"requests": 0, "tokens": 0}
    with torch.no_grad():
        while not dl.expired():
            phase = 2 * math.pi * (time.time() - t_start) / total
            rate = p["base_rate_hz"] * (1 + p["rate_swing"] * math.sin(phase))
            time.sleep(random.expovariate(max(0.2, rate)))
            batch = random.randint(1, p["max_batch"])
            seq = random.randint(p["seq"] // 4, p["seq"])
            x = torch.randint(0, p["vocab"], (batch, seq), device=device)
            with autocast_ctx(device):
                model(x)
            sync(device)
            stats["requests"] += batch
            stats["tokens"] += batch * seq
    return stats


GEN_DEFAULTS = {
    "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16,
    "seq": 512, "batch": 32, "gen_tokens": 128, "cap_gb": 20,
}


def run_datagen(args, p, dl):
    """N6: synthetic-data generation. High activity plus steady writes."""
    device = pick_device()
    model, _ = build_model(p, device)
    model.eval()
    outdir = os.path.join(args.scratch, f"gen_{args.run_id}")
    os.makedirs(outdir, exist_ok=True)
    stats = {"tokens_generated": 0, "bytes_written": 0, "files": 0}
    fileno = 0
    with torch.no_grad():
        while not dl.expired():
            x = torch.randint(0, p["vocab"], (p["batch"], 8), device=device)
            for _ in range(p["gen_tokens"]):
                with autocast_ctx(device):
                    logits, _ = model(x[:, -p["seq"]:])
                nxt = torch.multinomial(
                    F.softmax(logits[:, -1].float(), dim=-1), 1
                )
                x = torch.cat([x, nxt], dim=1)
                if dl.expired():
                    break
            path = os.path.join(outdir, f"gen_{fileno:06d}.pt")
            with open(path, "wb") as f:
                torch.save(x.to(torch.int16).cpu(), f)
                f.flush()
                os.fsync(f.fileno())
            fileno += 1
            stats["tokens_generated"] += x.numel()
            stats["bytes_written"] += os.path.getsize(path)
            stats["files"] += 1
            files = sorted(os.listdir(outdir))
            while sum(os.path.getsize(os.path.join(outdir, q)) for q in files) \
                    > p["cap_gb"] * 2**30:
                os.remove(os.path.join(outdir, files.pop(0)))
    return stats


IO_DEFAULTS = {
    "burst_gb": 4, "files_per_burst": 8, "interval_s": 300,
    "initial_delay_s": 0, "cap_gb": 40,
}


def run_io_burst(args, p, dl):
    """N7: checkpoint-shaped write bursts with idle GPUs."""
    outdir = os.path.join(args.scratch, f"io_{args.run_id}")
    os.makedirs(outdir, exist_ok=True)
    stats = {"bursts": 0, "bytes_written": 0}
    burst = 0
    block = os.urandom(4 * 2**20)
    if p["initial_delay_s"] > 0:
        time.sleep(min(p["initial_delay_s"], dl.remaining()))
    while not dl.expired():
        per_file = int(p["burst_gb"] * 2**30 / p["files_per_burst"])
        for i in range(p["files_per_burst"]):
            path = os.path.join(outdir, f"burst_{burst:04d}_{i:02d}.bin")
            written = 0
            with open(path, "wb") as f:
                while written < per_file:
                    f.write(block)
                    written += len(block)
                f.flush()
                os.fsync(f.fileno())
            stats["bytes_written"] += written
            if dl.expired():
                break
        stats["bursts"] += 1
        burst += 1
        dirs = sorted(set(q.split("_")[1] for q in os.listdir(outdir)))
        while len(dirs) * p["burst_gb"] > p["cap_gb"]:
            old = dirs.pop(0)
            for q in list(os.listdir(outdir)):
                if q.startswith(f"burst_{old}_"):
                    os.remove(os.path.join(outdir, q))
        time.sleep(min(p["interval_s"], dl.remaining()))
    return stats


BURN_DEFAULTS = {"size": 8192}


def run_burn(args, p, dl):
    """N8: gpu-burn equivalent. Max activity, no fabric, no writes."""
    device = pick_device()
    n = p["size"] if device.type == "cuda" else 512
    a = torch.randn(n, n, device=device)
    b = torch.randn(n, n, device=device)
    stats = {"matmuls": 0, "flop_estimate": 0.0}
    while not dl.expired():
        with autocast_ctx(device):
            c = a @ b
        sync(device)
        a.copy_(c / (c.norm() + 1e-6) * n)  # keep values bounded, reuse output
        stats["matmuls"] += 1
        stats["flop_estimate"] += 2.0 * n ** 3
    return stats


def run_idle(args, p, dl):
    """N4: allocated and idle. Baselines the site's own background chatter."""
    while not dl.expired():
        time.sleep(min(5, dl.remaining()))
    return {"idled": True}


KINDS = {
    "train": (run_train, TRAIN_DEFAULTS),
    "grad_eval": (run_train, GRAD_EVAL_DEFAULTS),
    "fabric_bench": (run_fabric_bench, FB_DEFAULTS),
    "tp_infer": (run_tp_infer, TP_DEFAULTS),
    "hpc": (run_hpc, HPC_DEFAULTS),
    "batch_infer": (run_batch_infer, INFER_DEFAULTS),
    "serving": (run_serving, SERVE_DEFAULTS),
    "datagen": (run_datagen, GEN_DEFAULTS),
    "io_burst": (run_io_burst, IO_DEFAULTS),
    "burn": (run_burn, BURN_DEFAULTS),
    "idle": (run_idle, {}),
}


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--kind", required=True, choices=sorted(KINDS))
    ap.add_argument("--duration", type=float, required=True)
    ap.add_argument("--out", required=True, help="ground-truth output dir")
    ap.add_argument("--scratch", required=True, help="checkpoint/data scratch")
    ap.add_argument("--run-id", default="manual")
    ap.add_argument("--params", default="{}", help="JSON overrides")
    args = ap.parse_args()

    signal.signal(signal.SIGTERM, on_term)
    fn, defaults = KINDS[args.kind]
    p = dict(defaults)
    p.update(json.loads(args.params))
    os.makedirs(args.scratch, exist_ok=True)
    gt_dir = os.path.join(args.out, "ground_truth")
    os.makedirs(gt_dir, exist_ok=True)

    world, rank = dist_env()
    log(f"start kind={args.kind} run={args.run_id} rank={rank}/{world} "
        f"duration={args.duration:.0f}s")
    t0 = time.time()
    err = None
    try:
        stats = fn(args, p, Deadline(args.duration))
    except Exception as e:
        err, stats = f"{type(e).__name__}: {e}", {}
        log(f"ERROR {err}")
    finally:
        try:
            cleanup_dist()
        except Exception:
            pass

    record = {
        "run_id": args.run_id, "kind": args.kind, "params": p,
        "rank": rank, "world": world, "node": socket.gethostname(),
        "t_start_utc": datetime.fromtimestamp(t0, timezone.utc).isoformat(),
        "t_end_utc": datetime.now(timezone.utc).isoformat(),
        "wall_s": round(time.time() - t0, 1),
        "device": (torch.cuda.get_device_name(0)
                   if torch.cuda.is_available() else "cpu"),
        "torch": torch.__version__,
        "error": err, "stats": stats,
    }
    path = os.path.join(gt_dir, f"{args.run_id}_rank{rank}.json")
    with open(path, "w") as f:
        json.dump(record, f, indent=2)
    log(f"done kind={args.kind}; ground truth -> {path}")
    sys.exit(1 if err else 0)


if __name__ == "__main__":
    main()