| |
| """ |
| 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 |
|
|
| |
| 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()) |
|
|
|
|
| |
| 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) |
|
|
|
|
| |
| 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): |
| |
| |
| x = torch.randint(0, p["vocab"], (batch, p["seq"]), device=device) |
| y = torch.roll(x, -1, dims=1) |
| return x, y |
|
|
|
|
| |
| 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_DEFAULTS = { |
| "seed": 1234, "vocab": 32768, "dim": 1024, "layers": 24, "heads": 16, |
| "seq": 1024, "micro_batch": 8, "accum": 8, "lr": 3e-4, |
| "strategy": "ddp", |
| "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, |
| "pace_gap_ms": 40, "pace_chunk_mb": 24, |
| } |
|
|
| 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 |
| |
| |
| 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 |
| |
| 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(): |
| |
| |
| 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"]))) |
|
|
| |
| 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: |
| |
| 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: |
| |
| 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: |
| |
| |
| |
| 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, |
| } |
|
|
|
|
| |
| 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() |
| |
| |
| |
| 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: |
| |
| |
| 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) |
| 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() |
|
|