Complete runtime support
labs/bridge_experiments.py
"""Small real Megatron Bridge training with explicit communication controls."""
from __future__ import annotations
import argparse
import hashlib
import math
import os
import statistics
import time
from pathlib import Path
from common import (
add_common_args,
require_course_gpu,
validate_common_args,
write_result,
)
def make_config(args, folder, kind):
from megatron.bridge.models import GPTModelProvider
from megatron.bridge.recipes.utils.optimizer_utils import (
distributed_fused_adam_with_cosine_annealing,
)
from megatron.bridge.training.comm_overlap import CommOverlapConfig
from megatron.bridge.training.config import (
CheckpointConfig,
ConfigContainer,
DistributedDataParallelConfig,
DistributedInitConfig,
GPTDatasetConfig,
LoggerConfig,
RNGConfig,
TokenizerConfig,
TrainingConfig,
ValidationConfig,
)
length = 2048 if args.workload == "small" else 16384
steps = args.warmup + args.iterations
overlap = kind == "overlap" and args.overlap == "on"
optimizer, scheduler = distributed_fused_adam_with_cosine_annealing(
lr_warmup_iters=2, lr_decay_iters=steps, max_lr=1e-4, min_lr=1e-5
)
model = GPTModelProvider(
num_layers=4,
hidden_size=512,
ffn_hidden_size=2048,
num_attention_heads=8,
num_query_groups=8,
vocab_size=8192,
seq_length=length,
tensor_model_parallel_size=1,
pipeline_model_parallel_size=1,
context_parallel_size=16 if kind == "context" else 1,
hidden_dropout=0.0,
attention_dropout=0.0,
position_embedding_type="rope",
cross_entropy_loss_fusion=False,
)
if kind == "context":
model.cp_comm_type = "a2a+p2p" if args.layout == "hierarchical" else "p2p"
model.hierarchical_context_parallel_sizes = (
[8, 2] if args.layout == "hierarchical" else None
)
return ConfigContainer(
model=model,
train=TrainingConfig(
train_iters=steps, global_batch_size=16, micro_batch_size=1
),
validation=ValidationConfig(eval_interval=steps + 1, eval_iters=0),
optimizer=optimizer,
scheduler=scheduler,
ddp=DistributedDataParallelConfig(
use_distributed_optimizer=True,
grad_reduce_in_fp32=True,
check_for_nan_in_grad=True,
overlap_grad_reduce=overlap,
overlap_param_gather=False,
),
comm_overlap=CommOverlapConfig(
tp_comm_overlap=False,
overlap_grad_reduce=overlap,
overlap_param_gather=False,
),
dataset=GPTDatasetConfig(
dataloader_type="single",
seq_length=length,
random_seed=args.seed,
reset_attention_mask=False,
reset_position_ids=False,
eod_mask_loss=False,
blend=None,
blend_per_split=None,
split="9999,8,2",
num_dataset_builder_threads=1,
create_attention_mask=False,
skip_getting_attention_mask_from_dataset=True,
),
tokenizer=TokenizerConfig(
tokenizer_type="NullTokenizer",
vocab_size=8192,
use_tokenizer_vocab_size=True,
),
logger=LoggerConfig(
log_interval=1,
tensorboard_log_interval=1,
tensorboard_dir=str(folder / "tensorboard"),
log_timers_to_tensorboard=True,
),
checkpoint=CheckpointConfig(
save=str(folder / "checkpoints"),
load=None,
save_interval=steps,
ckpt_format="torch_dist",
async_save=False,
fully_parallel_save=True,
),
rng=RNGConfig(seed=args.seed),
dist=DistributedInitConfig(use_decentralized_pg=False),
mixed_precision="bf16_mixed",
)
def compare_weights(torch, actual, reference, *, atol, rtol):
if actual.keys() != reference.keys():
raise ValueError("Reference parameter names differ")
maximum = 0.0
for name, value in actual.items():
expected = reference[name]
if (
value.shape != expected.shape
or not torch.isfinite(value).all()
or not torch.isfinite(expected).all()
):
raise ValueError("Reference shape or finite-value check failed")
maximum = max(maximum, float((value.float() - expected.float()).abs().max()))
if not torch.allclose(value.float(), expected.float(), atol=atol, rtol=rtol):
raise ValueError(
"Full final parameters exceed the declared BF16 comparison tolerance"
)
return maximum
def run(kind):
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.set_defaults(warmup=5, iterations=20)
parser.add_argument("--overlap", choices=("off", "on"), default="off")
parser.add_argument("--layout", choices=("flat", "hierarchical"), default="flat")
parser.add_argument("--reference-only", action="store_true")
parser.add_argument("--reference", type=Path)
parser.add_argument("--atol", type=float, default=0.005)
parser.add_argument("--rtol", type=float, default=0.05)
args = parser.parse_args()
if not args.reference_only and (
args.reference is None or not args.reference.is_file()
):
parser.error(
"Create a same-workload --reference-only run first, then pass its final-weights.pt via --reference"
)
if args.reference_only and (args.overlap != "off" or args.layout != "flat"):
parser.error("Reference must use the unchanged baseline controls")
if args.warmup < 2 or any(
not math.isfinite(x) or x < 0 for x in (args.atol, args.rtol)
):
parser.error("Use at least two warm-up steps and finite nonnegative tolerances")
if (kind == "overlap" and args.layout != "flat") or (
kind == "context" and args.overlap != "off"
):
parser.error("Change only the control belonging to this experiment")
if (
int(os.environ.get("WORLD_SIZE", "0")) != 16
or os.environ.get("LOCAL_WORLD_SIZE") != "8"
):
parser.error(
"Use fabric.sbatch with the prepared Bridge Python and torchrun on two eight-H100 workers"
)
validate_common_args(args)
import torch
from megatron.bridge.training.callbacks import Callback
from megatron.bridge.training.gpt_step import forward_step
from megatron.bridge.training.pretrain import pretrain
local = int(os.environ["LOCAL_RANK"])
rank = int(os.environ["RANK"])
torch.cuda.set_device(local)
env = {**require_course_gpu(torch), "bridge_candidate": "0.6.0", "rank_count": 16}
lab = "30_megatron_overlap" if kind == "overlap" else "31_context_parallel"
folder = (args.output_dir / lab / ("vendor-" + args.run_id)).resolve()
if rank == 0:
folder.mkdir(parents=True, mode=0o700, exist_ok=False)
states = []
weights = {}
trace_enabled = os.environ.get("COURSE_PROFILE_TOOL", "none") == "nsys"
class Evidence(Callback):
def on_train_step_start(self, context):
if trace_enabled:
torch.cuda.nvtx.range_push("bridge_training_step")
def on_train_step_end(self, context):
if trace_enabled:
torch.cuda.nvtx.range_pop()
states.append((context.loss_dict, context.grad_norm, context.skipped_iter))
def on_train_end(self, context):
if rank == 0:
weights.update(
{
name: value.detach().cpu()
for name, value in context.model[0].named_parameters()
}
)
torch.save(
{
"weights": weights,
"profile": args.workload,
"seed": args.seed,
"steps": args.warmup + args.iterations,
"kind": kind,
},
folder / "final-weights.pt",
)
pretrain(make_config(args, folder, kind), forward_step, callbacks=[Evidence()])
if rank != 0:
return
losses = [float(loss["lm loss"].detach().cpu()) for loss, _, _ in states]
norms = [float(norm) for _, norm, _ in states]
if (
len(losses) != args.warmup + args.iterations
or any(skipped for _, _, skipped in states)
or not all(math.isfinite(x) for x in losses + norms)
):
raise ValueError("Training has missing, skipped or nonfinite steps")
if args.reference_only:
print("Reference weights:", folder / "final-weights.pt")
return
reference = torch.load(args.reference, map_location="cpu", weights_only=True)
if any(
reference[key] != value
for key, value in {
"profile": args.workload,
"seed": args.seed,
"steps": args.warmup + args.iterations,
"kind": kind,
}.items()
):
raise ValueError("Reference was trained with a different workload")
maximum = compare_weights(
torch, weights, reference["weights"], atol=args.atol, rtol=args.rtol
)
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
events = EventAccumulator(str(folder / "tensorboard"), size_guidance={"scalars": 0})
deadline = time.monotonic() + 30
samples = []
while time.monotonic() < deadline:
events.Reload()
if "iteration-time" in events.Tags().get("scalars", []):
samples = [
entry.value
for entry in events.Scalars("iteration-time")
if entry.step > args.warmup
]
if len(samples) >= args.iterations:
break
time.sleep(0.5)
if len(samples) != args.iterations or not all(
math.isfinite(x) and x > 0 for x in samples
):
raise ValueError(
"Missing complete vendor iteration-time scalars; do not substitute console submission time"
)
length = 2048 if args.workload == "small" else 16384
print(
write_result(
args,
lab_id=lab,
environment=env,
measurements={
"step_seconds": statistics.median(samples),
"tokens_per_second": 16 * length / statistics.mean(samples),
"step_samples_seconds": samples,
"losses": losses,
"parameter_max_abs_error": maximum,
"tokens_per_step": 16 * length,
"reference_sha256": hashlib.sha256(
args.reference.read_bytes()
).hexdigest(),
},
correctness={
"no_skipped_nonfinite_steps": True,
"all_parameters_match_reference": True,
},
)
)
if __name__ == "__main__":
raise SystemExit("Use the numbered Megatron or context-parallel lab entry")
labs/collective_common.py
"""Shared, dependency-light helpers for the GPU Fundamentals labs."""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import secrets
import statistics
from collections.abc import Callable
from pathlib import Path
from typing import IO, Any
from course_evidence import (
annotated_operation,
atomic_result,
begin_experiment,
enrich_result,
gpu_family,
)
def add_common_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--workload",
choices=("small", "large"),
default=os.environ.get("COURSE_WORKLOAD", "small"),
help="Use small correctness sizes or larger benchmark sizes.",
)
parser.add_argument("--seed", type=int, default=17, help="Random seed.")
parser.add_argument("--warmup", type=int, default=5, help="Untimed warmup steps.")
parser.add_argument("--iterations", type=int, default=20, help="Timed steps.")
parser.add_argument(
"--output-dir",
type=Path,
default=Path(os.environ.get("COURSE_RESULTS_DIR", "results")),
help="Directory for sanitized JSON results.",
)
def validate_common_args(args: argparse.Namespace) -> None:
begin_experiment(args)
if args.warmup < 0:
raise SystemExit("--warmup must be non-negative")
if args.iterations < 1:
raise SystemExit("--iterations must be positive")
os.umask(0o077)
args.run_id = resolve_run_id(getattr(args, "run_id", None))
def resolve_run_id(value: str | None = None) -> str:
run_id = value if value is not None else os.environ.get("COURSE_RUN_ID")
if run_id is None:
run_id = secrets.token_hex(6)
if re.fullmatch(r"[0-9a-f]{12}", run_id) is None:
raise SystemExit("COURSE_RUN_ID must be exactly 12 lowercase hex characters")
return run_id
def resolve_int_override(
value: int | None,
default: int,
*,
option: str,
minimum: int = 1,
) -> int:
resolved = default if value is None else value
if resolved < minimum:
raise SystemExit(f"{option} must be at least {minimum}")
return resolved
def load_torch() -> Any:
try:
import torch
except ImportError as exc:
raise SystemExit(
"PyTorch is required. Follow the course environment setup before running this lab."
) from exc
return torch
def seed_everything(torch: Any, seed: int) -> None:
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def require_course_gpu(torch: Any) -> dict[str, Any]:
if not torch.cuda.is_available():
raise SystemExit("CUDA is unavailable; allocate a full course GPU.")
props = torch.cuda.get_device_properties(torch.cuda.current_device())
try:
family = gpu_family(props.name)
if (props.major, props.minor) != (9, 0):
raise ValueError("Expected compute capability 9.0")
except ValueError as exc:
raise SystemExit(str(exc)) from exc
return {
"gpu_family": family,
"compute_capability": "9.0",
"memory_gib": round(props.total_memory / 2**30, 1),
"torch_version": torch.__version__,
"cuda_version": torch.version.cuda,
}
def cuda_times_ms(
torch: Any,
operation: Callable[[], Any],
*,
warmup: int,
iterations: int,
) -> list[float]:
warmup_operation = annotated_operation(operation, "course_warmup")
operation = annotated_operation(operation, "course_measure")
for _ in range(warmup):
warmup_operation()
torch.cuda.synchronize()
samples: list[float] = []
for _ in range(iterations):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
operation()
end.record()
end.synchronize()
samples.append(float(start.elapsed_time(end)))
return samples
def summarize_ms(samples: list[float]) -> dict[str, float]:
ordered = sorted(samples)
p90_index = max(0, min(len(ordered) - 1, math.ceil(0.9 * len(ordered)) - 1))
return {
"median_ms": round(statistics.median(ordered), 4),
"min_ms": round(ordered[0], 4),
"p90_ms": round(ordered[p90_index], 4),
}
def write_result(
args: argparse.Namespace,
*,
lab_id: str,
environment: dict[str, Any],
measurements: dict[str, Any],
correctness: dict[str, Any],
) -> Path:
failed_checks = sorted(key for key, value in correctness.items() if value is False)
if failed_checks:
raise SystemExit("Failed correctness checks: " + ", ".join(failed_checks))
run_id = resolve_run_id(getattr(args, "run_id", None))
target = args.output_dir / f"{lab_id}-run-{run_id}.json"
payload = {
"schema": "gpu-course-result/v1",
"lab_id": lab_id,
"profile": args.workload,
"run_id": run_id,
"seed": args.seed,
"environment": environment,
"measurements": measurements,
"correctness": correctness,
}
write_json_exclusive(target, payload)
return target
def open_private_exclusive(target: Path, *, binary: bool = False) -> IO[Any]:
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
try:
descriptor = os.open(target, flags, 0o600)
except FileExistsError as exc:
raise SystemExit(
f"Refusing to overwrite an existing artifact: {target}"
) from exc
if binary:
return os.fdopen(descriptor, "wb")
return os.fdopen(descriptor, "w", encoding="utf-8")
def write_json_exclusive(target: Path, payload: dict[str, Any]) -> Path:
document = json.dumps(enrich_result(payload), indent=2, sort_keys=True) + "\n"
atomic_result(target, document)
return target
def configure_slurm_distributed_env() -> tuple[int, int, int]:
rank = int(os.environ.get("RANK", os.environ.get("SLURM_PROCID", "0")))
world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("SLURM_STEP_NUM_TASKS", os.environ.get("SLURM_NTASKS", "1"))))
local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("SLURM_LOCALID", "0")))
os.environ.setdefault("RANK", str(rank))
os.environ.setdefault("WORLD_SIZE", str(world_size))
os.environ.setdefault("LOCAL_RANK", str(local_rank))
return rank, world_size, local_rank
def init_nccl(torch: Any, *, expected_world_size: int = 2) -> tuple[int, int, int]:
rank, world_size, local_rank = configure_slurm_distributed_env()
if world_size != expected_world_size:
raise SystemExit(
f"Expected {expected_world_size} distributed ranks; received {world_size}. "
"Use slurm/two_node.sbatch."
)
for required in ("MASTER_ADDR", "MASTER_PORT"):
if not os.environ.get(required):
raise SystemExit(f"{required} is missing; use the supplied Slurm launcher.")
torch.cuda.set_device(local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://", device_id=torch.device("cuda", local_rank)
)
return rank, world_size, local_rank
def close_distributed(torch: Any) -> None:
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
labs/common.py
"""Shared, dependency-light helpers for the GPU Optimization labs."""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import secrets
import statistics
from collections.abc import Callable
from pathlib import Path
from typing import IO, Any
from course_evidence import (
annotated_operation,
atomic_result,
begin_experiment,
enrich_result,
gpu_family,
)
def add_common_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--workload", choices=("small", "large"), default=os.environ.get("COURSE_WORKLOAD", "small"))
parser.add_argument("--seed", type=int, default=17)
parser.add_argument("--warmup", type=int, default=5)
parser.add_argument("--iterations", type=int, default=20)
parser.add_argument("--output-dir", type=Path, default=Path(os.environ.get("COURSE_RESULTS_DIR", "results")))
def validate_common_args(args: argparse.Namespace) -> None:
begin_experiment(args)
if args.warmup < 0 or args.iterations < 1:
raise SystemExit(
"--warmup must be non-negative and --iterations must be positive"
)
os.umask(0o077)
args.run_id = resolve_run_id(getattr(args, "run_id", None))
def resolve_run_id(value: str | None = None) -> str:
run_id = value if value is not None else os.environ.get("COURSE_RUN_ID")
if run_id is None:
run_id = secrets.token_hex(6)
if re.fullmatch(r"[0-9a-f]{12}", run_id) is None:
raise SystemExit("COURSE_RUN_ID must be exactly 12 lowercase hex characters")
return run_id
def resolve_int_override(
value: int | None,
default: int,
*,
option: str,
minimum: int = 1,
) -> int:
resolved = default if value is None else value
if resolved < minimum:
raise SystemExit(f"{option} must be at least {minimum}")
return resolved
def load_torch() -> Any:
try:
import torch
except ImportError as exc:
raise SystemExit(
"PyTorch is required; follow the course environment setup."
) from exc
return torch
def seed_everything(torch: Any, seed: int) -> None:
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def require_course_gpu(torch: Any) -> dict[str, Any]:
if not torch.cuda.is_available():
raise SystemExit("CUDA is unavailable; allocate a full course GPU.")
props = torch.cuda.get_device_properties(torch.cuda.current_device())
try:
family = gpu_family(props.name)
if (props.major, props.minor) != (9, 0):
raise ValueError("Expected compute capability 9.0")
except ValueError as exc:
raise SystemExit(str(exc)) from exc
return {
"gpu_family": family,
"compute_capability": "9.0",
"memory_gib": round(props.total_memory / 2**30, 1),
"torch_version": torch.__version__,
"cuda_version": torch.version.cuda,
}
def cuda_times_ms(
torch: Any,
operation: Callable[[], Any],
*,
warmup: int,
iterations: int,
) -> list[float]:
warmup_operation = annotated_operation(operation, "course_warmup")
operation = annotated_operation(operation, "course_measure")
for _ in range(warmup):
warmup_operation()
torch.cuda.synchronize()
samples: list[float] = []
for _ in range(iterations):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
operation()
end.record()
end.synchronize()
samples.append(float(start.elapsed_time(end)))
return samples
def summarize_ms(samples: list[float]) -> dict[str, float]:
ordered = sorted(samples)
p90_index = max(0, min(len(ordered) - 1, math.ceil(0.9 * len(ordered)) - 1))
return {
"median_ms": round(statistics.median(ordered), 4),
"min_ms": round(ordered[0], 4),
"p90_ms": round(ordered[p90_index], 4),
}
def write_result(
args: argparse.Namespace,
*,
lab_id: str,
environment: dict[str, Any],
measurements: dict[str, Any],
correctness: dict[str, Any],
) -> Path:
failed_checks = sorted(key for key, value in correctness.items() if value is False)
if failed_checks:
raise SystemExit("Failed correctness checks: " + ", ".join(failed_checks))
run_id = resolve_run_id(getattr(args, "run_id", None))
target = args.output_dir / f"{lab_id}-run-{run_id}.json"
payload = {
"schema": "gpu-course-result/v1",
"lab_id": lab_id,
"profile": args.workload,
"run_id": run_id,
"seed": args.seed,
"environment": environment,
"measurements": measurements,
"correctness": correctness,
}
write_json_exclusive(target, payload)
return target
def open_private_exclusive(target: Path, *, binary: bool = False) -> IO[Any]:
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
try:
descriptor = os.open(target, flags, 0o600)
except FileExistsError as exc:
raise SystemExit(f"Refusing to overwrite an existing result: {target}") from exc
if binary:
return os.fdopen(descriptor, "wb")
return os.fdopen(descriptor, "w", encoding="utf-8")
def write_json_exclusive(target: Path, payload: dict[str, Any]) -> Path:
document = json.dumps(enrich_result(payload), indent=2, sort_keys=True) + "\n"
atomic_result(target, document)
return target
def configure_slurm_distributed_env() -> tuple[int, int, int]:
rank = int(os.environ.get("RANK", os.environ.get("SLURM_PROCID", "0")))
world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("SLURM_STEP_NUM_TASKS", os.environ.get("SLURM_NTASKS", "1"))))
local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("SLURM_LOCALID", "0")))
os.environ.setdefault("RANK", str(rank))
os.environ.setdefault("WORLD_SIZE", str(world_size))
os.environ.setdefault("LOCAL_RANK", str(local_rank))
return rank, world_size, local_rank
def init_nccl(torch: Any, *, expected_world_size: int = 2) -> tuple[int, int, int]:
rank, world_size, local_rank = configure_slurm_distributed_env()
if world_size != expected_world_size:
raise SystemExit(
f"Expected {expected_world_size} ranks; use slurm/two_node.sbatch."
)
for required in ("MASTER_ADDR", "MASTER_PORT"):
if not os.environ.get(required):
raise SystemExit(f"{required} is missing; use the supplied Slurm launcher.")
torch.cuda.set_device(local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://", device_id=torch.device("cuda", local_rank)
)
return rank, world_size, local_rank
def close_distributed(torch: Any) -> None:
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
labs/course_evidence.py
"""Private experiment provenance and opt-in NVTX; copied into each course's labs."""
from __future__ import annotations
import hashlib
import os
import re
import subprocess
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Any
STARTED = time.time()
PARAMETERS: dict[str, Any] = {}
def gpu_family(name: str) -> str:
"""Record the observed full Hopper device, independently of teaching titles."""
match = re.search(r"\b(H100|H200)\b", name)
if "MIG" in name.upper() or not match:
raise ValueError(f"Expected a full H100 or H200; detected {name!r}")
return "NVIDIA " + match[1]
def allocation_gpu_family() -> str:
"""Observe every full GPU in a one- or two-worker fabric allocation."""
nodes = int(os.environ.get("SLURM_JOB_NUM_NODES", "0"))
if not os.environ.get("SLURM_JOB_ID") or nodes not in (1, 2):
raise ValueError("Require a one- or two-worker fabric allocation")
output = subprocess.check_output(
[
"srun",
f"--nodes={nodes}",
f"--ntasks={nodes}",
"--ntasks-per-node=1",
"--gpus-per-task=8",
"nvidia-smi",
"--query-gpu=name,compute_cap",
"--format=csv,noheader,nounits",
],
text=True,
timeout=60,
)
rows = [line.split(",") for line in output.splitlines() if line.strip()]
if len(rows) != nodes * 8 or any(
len(row) != 2 or row[1].strip() != "9.0" for row in rows
):
raise ValueError("Require observed SM90 identity for every allocated GPU")
families = {gpu_family(row[0].strip()) for row in rows}
if len(families) != 1:
raise ValueError("Mixed GPU families are unsupported")
return families.pop()
def annotated_operation(operation: Any, name: str) -> Any:
"""The clean path returns the original callable, without a timed wrapper."""
if os.environ.get("COURSE_CAPTURE", "0") != "1":
return operation
def captured(*args: Any, **kwargs: Any) -> Any:
with evidence_phase(name):
return operation(*args, **kwargs)
return captured
def begin_experiment(args: Any) -> None:
"""Keep only scalar experiment controls, never paths, credentials or URLs."""
global STARTED, PARAMETERS
STARTED = time.time()
private = {
"token",
"api_key",
"secret",
"password",
"base_url",
"endpoint",
"output",
"output_dir",
"run_id",
}
PARAMETERS = {}
for key, value in vars(args).items():
if key in private or key.endswith(
("_path", "_dir", "_url", "_secret", "_password")
):
continue
if (
isinstance(value, list)
and len(value) <= 128
and all(type(v) in (int, float, bool) for v in value)
):
PARAMETERS[key] = value.copy()
continue
if type(value) not in (int, float, bool, str, type(None)):
continue
if key in {"model", "revision", "checkpoint"} or (
isinstance(value, str) and (len(value) > 64 or "/" in value or ":" in value)
):
PARAMETERS[key + "_sha256"] = hashlib.sha256(
str(value).encode()
).hexdigest()
else:
stored_key = (
"profile"
if key == "workload" and value in ("small", "large")
else key
)
PARAMETERS[stored_key] = value
def enrich_result(payload: dict[str, Any]) -> dict[str, Any]:
if payload.get("schema") != "gpu-course-result/v1":
return payload
result = dict(payload)
result.setdefault("profile", os.environ.get("COURSE_WORKLOAD", "small"))
result.setdefault("seed", None)
result.setdefault(
"environment",
{"runtime_identity": os.environ.get("COURSE_RUNTIME_ID", "unqualified")},
)
code = Path(__file__).parent
source = code / (str(result.get("lab_id", "")) + ".py")
parameters = dict(PARAMETERS)
if source.is_file():
helpers = sorted(p for p in code.glob("*.py") if not p.name[0].isdigit())
digest = hashlib.sha256()
for path in [source, *helpers]:
digest.update(path.name.encode())
digest.update(path.read_bytes())
parameters["implementation_sha256"] = digest.hexdigest()
layout = os.environ.get("COURSE_SERVER_LAYOUT")
if layout is not None:
if layout not in {"tp8-pp2", "tp16-pp1", "ep16"}:
raise ValueError("Unknown qualified server layout")
parameters["server_layout"] = layout
parameters["server_world_size"] = 16
result["experiment"] = {
"started_unix_seconds": STARTED,
"ended_unix_seconds": time.time(),
"instrumented": os.environ.get("COURSE_CAPTURE", "0") == "1"
or os.environ.get("COURSE_PROFILE_TOOL", "none") != "none",
"parameters": {
**parameters,
"world_size": int(os.environ.get("WORLD_SIZE", "1")),
},
"slurm_job_id": int(os.environ.get("SLURM_JOB_ID", "0")),
"rank": int(os.environ.get("RANK", os.environ.get("SLURM_PROCID", "0"))),
}
trial = os.environ.get("COURSE_TRIAL_INDEX")
if trial is not None:
if trial not in {"1", "2", "3"}:
raise ValueError("COURSE_TRIAL_INDEX must be 1, 2 or 3")
result["experiment"]["trial_index"] = int(trial)
return result
@contextmanager
def evidence_phase(name: str):
"""Host submission region; it does not synchronize or measure GPU execution."""
if os.environ.get("COURSE_CAPTURE", "0") != "1":
yield
return
import torch
if not torch.cuda.is_available():
raise RuntimeError("NVTX capture requires a CUDA workload")
torch.cuda.nvtx.range_push(name)
try:
yield
finally:
torch.cuda.nvtx.range_pop()
def atomic_result(path: Path, document: str) -> None:
"""Publish a complete immutable file; never expose a half-written JSON result."""
import secrets
job = os.environ.get("COURSE_JOB_DIR")
if job and (not path.resolve().is_relative_to(Path(job).resolve()) or any(p.is_symlink() for p in (path, *path.parents))):
raise ValueError("Job evidence must stay inside its own regular output tree")
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
temporary = path.parent / ("." + path.name + "." + secrets.token_hex(6))
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
stream.write(document)
stream.flush()
os.fsync(stream.fileno())
try:
os.link(temporary, path)
except FileExistsError as exc:
raise SystemExit(
f"Refusing to overwrite an existing artifact: {path}"
) from exc
finally:
temporary.unlink(missing_ok=True)
labs/dynamo_experiments.py
"""Own a private two-node Dynamo deployment for one bounded Slurm experiment."""
from __future__ import annotations
import argparse
import contextlib
import ipaddress
import json
import os
import shutil
import socket
import time
import urllib.request
from pathlib import Path
from common import add_common_args, validate_common_args, write_result
from course_evidence import allocation_gpu_family
from job_processes import (
Processes,
allocated_nodes,
private_folder,
start_etcd,
step,
wait_http,
)
from serving_client import benchmark, request
from vendor_capture import (
add_worker_prefix,
native_systems_prefix,
validate_worker_prefix,
)
MODEL_REVISION = "b968826d9c46dd6066d109eabc6255188de91218"
def wait_frontend_model(url, processes, timeout=600):
"""Wait for asynchronous discovery, retaining the exact model identity gate."""
deadline = time.monotonic() + timeout
empty_polls = 0
while (remaining := deadline - time.monotonic()) > 0:
models = wait_http(url + "/v1/models", processes, timeout=remaining)
rows = models.get("data") if isinstance(models, dict) else None
if not isinstance(rows, list) or any(
not isinstance(row, dict) or not isinstance(row.get("id"), str)
for row in rows
):
raise ValueError("Frontend discovery returned malformed model data")
identities = {row["id"] for row in rows}
if identities == {"course-model"}:
print(
json.dumps(
{
"frontend_discovery": {
"model": "course-model",
"empty_polls": empty_polls,
}
}
),
flush=True,
)
return
if identities:
raise ValueError("Frontend discovery differs from the expected model")
empty_polls += 1
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
raise RuntimeError("Frontend model discovery did not complete within its deadline")
def profile_control(address, action):
"""Require the allocated worker to acknowledge its CUDA profiler control."""
url = f"http://{address}:8081/engine/control/{action}_profile"
request = urllib.request.Request(
url, data=b"{}", headers={"Content-Type": "application/json"}, method="POST"
)
timeout = 600 if action == "stop" else 90
with urllib.request.urlopen(request, timeout=timeout) as response:
body = response.read(65537)
if response.status != 200 or len(body) > 65536:
raise RuntimeError("Worker did not acknowledge profiler control")
document = json.loads(body)
if not isinstance(document, dict) or document.get("status") != "ok":
raise RuntimeError("Worker did not acknowledge profiler control")
def wait_server_reports(folder, count, processes, timeout=180):
"""Retain reports before engine shutdown can terminate GPU worker processes."""
reports = [folder / f"server-rank{rank}.nsys-rep" for rank in range(count)]
deadline = time.monotonic() + timeout
while not all(report.is_file() and report.stat().st_size for report in reports):
processes.healthy()
if time.monotonic() >= deadline:
raise RuntimeError("Server profiling did not produce both reports")
time.sleep(1)
@contextlib.contextmanager
def server_capture(addresses, folder, processes):
"""End collection while every owned engine is still alive, including on failure."""
with (folder / "capture-control.jsonl").open("x") as evidence:
def control(rank, action):
profile_control(addresses[rank], action)
evidence.write(
json.dumps(
{"rank": rank, "action": action, "unix_seconds": time.time()}
)
+ "\n"
)
evidence.flush()
with contextlib.ExitStack() as cleanup:
for rank in range(len(addresses)):
cleanup.callback(control, rank, "stop")
control(rank, "start")
yield
wait_server_reports(folder, len(addresses), processes)
def worker_command(python, model, role):
command = [
python,
"-m",
"dynamo.vllm",
"--model",
str(model),
"--served-model-name",
"course-model",
"--tensor-parallel-size",
"8",
"--dtype",
"bfloat16",
"--max-model-len",
"8192",
"--block-size",
"64",
"--enable-prefix-caching",
"--attention-config",
json.dumps({"flash_attn_version": 2}),
"--compilation-config",
json.dumps(
{
"custom_ops": ["+rms_norm"],
"pass_config": {"fuse_allreduce_rms": False},
}
),
"--disaggregation-mode",
role,
]
command += [
"--kv-events-config",
json.dumps(
{
"publisher": "zmq",
"topic": "kv-events",
"endpoint": "tcp://*:20080",
"enable_kv_cache_events": True,
}
),
]
if role != "agg":
command += [
"--kv-transfer-config",
json.dumps({"kv_connector": "NixlConnector", "kv_role": "kv_both"}),
]
return command
@contextlib.contextmanager
def service(args, folder):
if os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
raise ValueError("Use --capture systems to profile the owned GPU servers")
nodes = allocated_nodes()
addresses = [socket.gethostbyname(node) for node in nodes]
if any(
not ipaddress.ip_address(ip).is_private or ipaddress.ip_address(ip).is_loopback
for ip in addresses
):
raise ValueError(
"Allocated worker names must resolve to reachable private addresses"
)
python = os.environ.get("COURSE_DYNAMO_PYTHON")
if not python or not Path(python).is_file():
raise ValueError(
"Run the one-time course setup and submit through the native launcher"
)
libraries = os.environ.get("COURSE_DYNAMO_LIBRARY_PATH")
if not libraries:
raise ValueError("The prepared Dynamo library path is missing; rerun course setup")
if (
args.model_dir.resolve().name != MODEL_REVISION
or not (args.model_dir / "config.json").is_file()
):
raise ValueError(
"Use the shared README setup's pinned Qwen3-8B snapshot directory"
)
with Processes(folder) as processes:
endpoint = start_etcd(processes, nodes[0])
shared = {
"LD_LIBRARY_PATH": libraries,
"PATH": str(Path(python).absolute().parent)
+ os.pathsep
+ os.environ.get("PATH", os.defpath),
"ETCD_ENDPOINTS": endpoint,
"DYN_DISCOVERY_BACKEND": "etcd",
"DYN_REQUEST_PLANE": "tcp",
"DYN_EVENT_PLANE": "zmq",
"DYN_NAMESPACE": "course-" + args.run_id,
"PYTHONHASHSEED": "0",
"VLLM_BATCH_INVARIANT": "1",
"HF_HUB_OFFLINE": "1",
"TRANSFORMERS_OFFLINE": "1",
}
for rank, node in enumerate(nodes):
role = "agg" if args.layout == "aggregated" else ("prefill", "decode")[rank]
environment = {
**shared,
"DYN_TCP_RPC_HOST": addresses[rank],
"DYN_TCP_RPC_PORT": "8090",
"DYN_SYSTEM_HOST": addresses[rank],
"DYN_SYSTEM_PORT": "8081",
"VLLM_NIXL_SIDE_CHANNEL_PORT": "5600",
}
command = worker_command(python, args.model_dir, role)
if args.capture == "systems":
command += ["--profiler-config", json.dumps({"profiler": "cuda"})]
binary = shutil.which("nsys")
if not binary:
raise ValueError("Source the shared profiler environment first")
if getattr(args, "worker_prefix", None) is not None:
command = [*native_systems_prefix(args.worker_prefix, folder / f"server-rank{rank}", server=True), *command]
else:
raise ValueError("Systems capture requires the job's explicit --worker-prefix")
processes.start(
f"worker{rank}",
step(
node,
[
"env",
"-u",
"NATS_SERVER",
*(key + "=" + value for key, value in environment.items()),
*command,
],
forward_interrupt=args.capture == "systems",
),
persistent=True,
interrupt_on_exit=args.capture == "systems",
shutdown_timeout=180 if args.capture == "systems" else 10,
)
frontend = [
python,
"-m",
"dynamo.frontend",
"--http-host",
"127.0.0.1",
"--http-port",
"8000",
"--namespace",
shared["DYN_NAMESPACE"],
"--router-mode",
args.router,
]
processes.start(
"frontend",
[
"env",
"-u",
"NATS_SERVER",
*(key + "=" + value for key, value in shared.items()),
*frontend,
],
persistent=True,
)
for ip in addresses:
ready = wait_http(f"http://{ip}:8081/health", processes)
if ready.get("status") != "ready":
raise ValueError("Worker health does not declare ready")
url = "http://127.0.0.1:8000"
wait_frontend_model(url, processes)
request(url, "Write a short greeting. /no_think", 8)
capture = (
server_capture(addresses, folder, processes)
if args.capture == "systems"
else contextlib.nullcontext()
)
with capture:
yield url, processes
if args.capture == "systems":
for rank in range(len(nodes)):
report = folder / f"server-rank{rank}.nsys-rep"
if not report.is_file() or report.stat().st_size == 0:
raise RuntimeError(
"Server profiling did not produce both reports; inspect worker logs"
)
def run(kind):
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.set_defaults(warmup=4, iterations=64)
parser.add_argument("--model-dir", type=Path, default=os.environ.get("COURSE_MODEL_DIR"),
required=not bool(os.environ.get("COURSE_MODEL_DIR")))
parser.add_argument(
"--layout", choices=("aggregated", "disaggregated"), default="aggregated"
)
parser.add_argument(
"--router", choices=("round-robin", "kv"), default="round-robin"
)
parser.add_argument("--concurrency", type=int, default=8)
parser.add_argument("--capture", choices=("none", "systems"), default="none")
add_worker_prefix(parser)
args = parser.parse_args()
validate_worker_prefix(args, server=True)
if (
not 1 <= args.concurrency <= 64
or not 8 <= args.iterations <= 4096
or not 0 <= args.warmup <= args.iterations
):
parser.error("Use concurrency 1..64, requests 8..4096 and bounded warm-up")
if (kind == "routing" and args.layout != "aggregated") or (
kind == "disaggregation" and args.router != "round-robin"
):
parser.error("Keep other serving controls fixed for this experiment")
validate_common_args(args)
lab = (
"32_dynamo_disaggregation" if kind == "disaggregation" else "33_dynamo_routing"
)
folder = private_folder(args, lab)
with service(args, folder) as (url, processes):
measured = benchmark(
url,
count=args.iterations,
words=16 if args.workload == "small" else 256,
output_tokens=32 if args.workload == "small" else 128,
concurrency=args.concurrency,
warmup=args.warmup,
folder=folder,
)
processes.healthy()
if args.capture != "none":
print("Diagnostic server reports and client measurements:", folder)
return
print(
write_result(
args,
lab_id=lab,
environment={
"gpu_family": allocation_gpu_family(),
"allocated_gpus": 16,
"dynamo_candidate": "1.4.2",
"model_revision": MODEL_REVISION,
},
measurements=measured,
correctness={
"all_streams_complete": True,
"fixed_output_token_count": True,
},
)
)
labs/fabric_common.py
"""Eight-/sixteen-rank experiments; all timing uses the slowest participating rank."""
from __future__ import annotations
import os
import statistics
import time
from common import init_nccl, load_torch, require_course_gpu, seed_everything
from course_evidence import annotated_operation
def initialize(seed):
torch = load_torch()
world = int(os.environ.get("WORLD_SIZE", "0"))
if world not in (8, 16) or int(os.environ.get("LOCAL_WORLD_SIZE", "0")) != 8:
raise SystemExit("Use fabric.sbatch: eight GPUs per node, one or two nodes.")
rank, world, local = init_nccl(torch, expected_world_size=world)
environment = {**require_course_gpu(torch), "rank_count": world, "gpus_per_node": 8}
seed_everything(torch, seed)
return torch, rank, world, local, environment
def all_correct(torch, value, message):
flag = torch.tensor(int(bool(value)), device="cuda", dtype=torch.int32)
torch.distributed.all_reduce(flag, op=torch.distributed.ReduceOp.MIN)
if not flag.item():
raise SystemExit(message)
def measure(torch, operation, warmup, iterations):
warming = annotated_operation(operation, "course_warmup")
measured = annotated_operation(operation, "course_measure")
for _ in range(warmup):
warming()
torch.cuda.synchronize()
samples = []
for _ in range(iterations):
torch.distributed.barrier()
torch.cuda.synchronize()
start = time.perf_counter()
measured()
torch.cuda.synchronize()
elapsed = torch.tensor(
(time.perf_counter() - start) * 1000, dtype=torch.float64, device="cuda"
)
torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
samples.append(elapsed.item())
return {
"median_ms": statistics.median(samples),
"min_ms": min(samples),
"max_ms": max(samples),
"samples_ms": samples,
}
labs/fabric_tools.py
"""Strict vendor output contracts and private, owned RDMA endpoint execution."""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import re
import signal
import subprocess
import time
from pathlib import Path
PINS = {
"nvbandwidth": "82fc4e8c6afa0babb8687793678f615b3b8d793e",
"perftest": "b513a77278c8061ca6c4dcd1a95d08801c6e7623",
"perftest_read_lat": "b513a77278c8061ca6c4dcd1a95d08801c6e7623",
}
def qualified_binary(name):
prefix = Path(os.environ.get("COURSE_TOOLS", "")) / "fabric"
manifest = json.loads((prefix / "builds.json").read_text())
record = manifest[name]
binary = prefix / record["binary"]
if (
record["revision"] != PINS[name]
or hashlib.sha256(binary.read_bytes()).hexdigest() != record["sha256"]
):
raise ValueError(
"Vendor build differs from the shared README setup's pinned build receipt"
)
return binary
def nvbandwidth_result(document, testcase, buffer_mib, samples):
root = document["nvbandwidth"]
if root.get("error") or buffer_mib <= 0 or samples <= 0:
raise ValueError("Failed or mismatched nvbandwidth experiment")
tests = root["testcases"]
if (
len(tests) != 1
or tests[0]["name"] != testcase
or tests[0]["status"] != "Passed"
or tests[0].get("error")
):
raise ValueError("Expected exactly one passing peer-bandwidth test")
matrix = tests[0]["bandwidth_matrix"]
if len(matrix) != 8 or any(len(row) != 8 for row in matrix):
raise ValueError("Expected a complete eight-GPU peer matrix")
pairs = {}
for source, row in enumerate(matrix):
for destination, value in enumerate(row):
if source == destination:
continue
number = float(value)
if not math.isfinite(number) or number <= 0:
raise ValueError(
"Every directed GPU pair must have finite positive bandwidth"
)
pairs[f"gpu{source}_to_gpu{destination}"] = number
return {
"pairs_GBps": pairs,
"pairs": [
{
"source": source,
"destination": destination,
"GBps": pairs[f"gpu{source}_to_gpu{destination}"],
}
for source in range(8)
for destination in range(8)
if source != destination
],
"minimum_GBps": min(pairs.values()),
"mean_GBps": sum(pairs.values()) / len(pairs),
"pair_count": len(pairs),
}
def rdma_result(document, log, size, iterations, depth, memory):
info, result = document["test_info"], document["results"]
if (
info["Connection_type"] != "RC"
or info["Link_type"] != "IB"
or info["TX_depth"] != depth
or result["MsgSize"] != size
or result["n_iterations"] != iterations
):
raise ValueError(
"RDMA report does not match the requested workload or transport"
)
if memory != "host" and info.get("cuda_device") != 0:
raise ValueError("CUDA memory registration was not reported")
if memory == "host" and "cuda_device" in info:
raise ValueError("Host baseline unexpectedly used CUDA memory")
passed = re.findall(
r"VALIDATION: PASSED(?: \([^)]*\))? - ([0-9]+) chunks, ([0-9]+) bytes", log
)
if (
len(passed) != 1
or any(int(n) <= 0 for n in passed[0])
or re.search(r"VALIDATION: (?:FAILED|ERROR|WARNING)", log)
):
raise ValueError(
"Endpoint must validate actual transferred bytes without errors"
)
bandwidth = float(result["BW_average"])
if not math.isfinite(bandwidth) or bandwidth <= 0:
raise ValueError("Invalid RDMA bandwidth")
return {"bidirectional_Gbps": bandwidth, "validated_bytes": int(passed[0][1])}
def owns_listener(pid, port):
"""Inspect only this child process's socket inodes; never connect to the test port."""
try:
inodes = {
p.readlink().name.removeprefix("socket:[").removesuffix("]")
for p in Path(f"/proc/{pid}/fd").iterdir()
if p.is_symlink()
}
for family in ("tcp", "tcp6"):
for line in Path(f"/proc/{pid}/net/{family}").read_text().splitlines()[1:]:
fields = line.split()
if (
fields[3] == "0A"
and int(fields[1].rsplit(":", 1)[1], 16) == port
and fields[9] in inodes
):
return True
except (FileNotFoundError, ProcessLookupError):
pass
return False
def endpoint():
parser = argparse.ArgumentParser(
description="Owned endpoint for the RDMA labs; invoked by their Slurm jobs."
)
parser.add_argument("--role", choices=("server", "client"), required=True)
parser.add_argument("--folder", type=Path, required=True)
parser.add_argument("--port", type=int, required=True)
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args()
command = args.command[1:] if args.command[:1] == ["--"] else args.command
if not command or not os.environ.get("SLURM_JOB_ID"):
parser.error("An allocated job and vendor command are required")
os.umask(0o077)
with (args.folder / (args.role + ".log")).open("x") as log:
child = subprocess.Popen(
command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True
)
def terminate(signum, frame):
if child.poll() is None:
os.killpg(child.pid, signum)
previous = {
s: signal.signal(s, terminate) for s in (signal.SIGINT, signal.SIGTERM)
}
try:
if args.role == "server":
deadline = time.monotonic() + 30
while not owns_listener(child.pid, args.port):
if child.poll() is not None or time.monotonic() >= deadline:
raise RuntimeError(
"Owned server did not open its test listener"
)
time.sleep(0.1)
(args.folder / "ready").touch(exist_ok=False)
status = child.wait(timeout=180)
if status:
raise RuntimeError(
f"{args.role} vendor process failed with status {status}"
)
finally:
terminate(signal.SIGTERM, None)
try:
child.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait()
for sig, handler in previous.items():
signal.signal(sig, handler)
if __name__ == "__main__":
endpoint()
labs/gradient_overlap_common.py
"""BF16 bucket arithmetic and scale-aware checks for Lab 19 and its diagnostic."""
from __future__ import annotations
from typing import Any
GRADIENT_RTOL = 1e-2
GRADIENT_ATOL_FRACTION = 1e-2
def bucket_sizes(profile: str, override: list[int] | None) -> list[int]:
sizes = (
override
if override is not None
else ([8, 24] if profile == "small" else [64, 192])
)
if len(sizes) < 2 or any(size < 1 for size in sizes):
raise SystemExit("--bucket-mib requires at least two positive sizes")
return sizes
def make_bucket_seeds(
torch: Any, sizes: list[int], *, device: str
) -> list[tuple[Any, Any]]:
pairs = []
for size_mib in sizes:
elements = size_mib * 2**20 // 2
parameter = torch.randn(elements, device=device, dtype=torch.bfloat16)
values = torch.linspace(0.5, 1.5, elements, device=device, dtype=torch.bfloat16)
pairs.append((parameter, values))
return pairs
def bucket_loss(parameters: list[Any], seeds: list[tuple[Any, Any]]) -> Any:
return sum(
(parameter * values).float().square().mean()
for parameter, (_seed, values) in zip(parameters, seeds, strict=True)
)
def local_gradient_reference(torch: Any, seeds: list[tuple[Any, Any]]) -> list[Any]:
"""Differentiate the actual BF16 product and backward casts without autograd."""
references = []
with torch.no_grad():
for parameter, values in seeds:
product = (parameter * values).float()
mean_gradient = (
torch.ones((), device=product.device, dtype=torch.float32)
/ product.numel()
)
product_gradient = (2 * product * mean_gradient).to(torch.bfloat16)
references.append(product_gradient * values)
return references
def gradient_checks(torch: Any, reference: Any, observed: Any) -> dict[str, Any]:
"""Return local failure, never raise for malformed gradient bucket structure."""
checks: dict[str, Any] = {
"passed": False,
"all_finite": False,
"rtol": GRADIENT_RTOL,
"atol_fraction_of_reference_max": GRADIENT_ATOL_FRACTION,
"buckets": [],
}
if (
not isinstance(reference, (list, tuple))
or not isinstance(observed, (list, tuple))
or not reference
or len(reference) != len(observed)
):
checks["reason"] = "nonempty matching bucket lists required"
return checks
all_finite = True
for expected, actual in zip(reference, observed, strict=True):
row: dict[str, Any] = {"passed": False}
checks["buckets"].append(row)
if (
not torch.is_tensor(expected)
or not torch.is_tensor(actual)
or expected.shape != actual.shape
or expected.device != actual.device
or expected.dtype != torch.bfloat16
or actual.dtype != torch.bfloat16
or expected.numel() == 0
):
row["reason"] = "matching nonempty BF16 tensors required"
all_finite = False
continue
row["elements"] = expected.numel()
if not bool(torch.isfinite(expected).all() and torch.isfinite(actual).all()):
row["reason"] = "nonfinite gradient"
all_finite = False
continue
expected_fp32, actual_fp32 = expected.float(), actual.float()
scale = float(expected_fp32.abs().max().item())
error = float((actual_fp32 - expected_fp32).abs().max().item())
row.update(
reference_max_abs=scale,
max_abs_error=error,
max_normalized_abs_error=error / scale if scale else None,
passed=(
bool(torch.equal(actual_fp32, expected_fp32))
if scale == 0
else bool(
torch.allclose(
actual_fp32,
expected_fp32,
rtol=GRADIENT_RTOL,
atol=GRADIENT_ATOL_FRACTION * scale,
)
)
),
)
checks["all_finite"] = all_finite
checks["passed"] = all(row["passed"] for row in checks["buckets"])
return checks
def require_gradient_consensus(
torch: Any, checks: dict[str, Any], *, device: str
) -> None:
verdict = torch.tensor(int(checks["passed"]), device=device, dtype=torch.int32)
torch.distributed.all_reduce(verdict, op=torch.distributed.ReduceOp.MIN)
if not bool(verdict.item()):
raise SystemExit(
"Gradient buckets failed equivalence or finite checks on a rank."
)
labs/gradient_overlap_compute.py
"""Diagnose one local Lab 19 backward kernel; never emit acceptance timing."""
from __future__ import annotations
import argparse
import json
import os
from gradient_overlap_common import (
bucket_loss,
bucket_sizes,
gradient_checks,
local_gradient_reference,
make_bucket_seeds,
)
from training_common import load_torch, require_course_gpu, seed_everything
def require_single_process() -> None:
for name, expected in (
("WORLD_SIZE", 1),
("LOCAL_WORLD_SIZE", 1),
("SLURM_STEP_NUM_TASKS", 1),
("SLURM_STEP_NUM_NODES", 1),
("RANK", 0),
("LOCAL_RANK", 0),
("SLURM_PROCID", 0),
("SLURM_LOCALID", 0),
):
value = os.environ.get(name, str(expected))
if not value.isdecimal() or int(value) != expected:
raise SystemExit(
f"Compute companion requires one local process: invalid {name}"
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workload", choices=("small", "large"), default="small")
parser.add_argument("--seed", type=int, default=17)
parser.add_argument("--bucket-mib", type=int, nargs="+", default=None)
parser.add_argument("--warmup", type=int, default=3)
args = parser.parse_args()
if args.warmup < 0:
parser.error("--warmup must be non-negative")
sizes = bucket_sizes(args.workload, args.bucket_mib)
require_single_process()
torch = load_torch()
require_course_gpu(torch)
if torch.cuda.device_count() != 1:
raise SystemExit("Compute companion requires exactly one visible H100 GPU")
seed_everything(torch, args.seed)
seeds = make_bucket_seeds(torch, sizes, device="cuda:0")
def prepare():
parameters = [seed.detach().clone().requires_grad_(True) for seed, _ in seeds]
return parameters, bucket_loss(parameters, seeds)
for _ in range(args.warmup):
parameters, loss = prepare()
loss.backward()
parameters, loss = prepare()
torch.cuda.synchronize()
with torch.cuda.nvtx.range("gradient_backward"):
loss.backward()
torch.cuda.synchronize()
checks = gradient_checks(
torch,
local_gradient_reference(torch, seeds),
[parameter.grad for parameter in parameters],
)
print(
json.dumps(
{"acceptance_timing": False, "gradient_validation": checks}, allow_nan=False
)
)
if not checks["passed"]:
raise SystemExit(
"Local BF16 backward failed its independent gradient reference"
)
if __name__ == "__main__":
main()
labs/inference_common.py
"""Shared, dependency-light helpers for the LLM inference labs."""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import secrets
import statistics
from collections.abc import Callable
from pathlib import Path
from typing import IO, Any
from course_evidence import (
annotated_operation,
atomic_result,
begin_experiment,
enrich_result,
gpu_family,
)
DEFAULT_MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
DEFAULT_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
def add_common_args(
parser: argparse.ArgumentParser, *, include_measurement: bool = True
) -> None:
parser.add_argument("--workload", choices=("small", "large"), default=os.environ.get("COURSE_WORKLOAD", "small"))
parser.add_argument("--seed", type=int, default=17)
if include_measurement:
parser.add_argument("--warmup", type=int, default=3)
parser.add_argument("--iterations", type=int, default=10)
parser.add_argument("--output-dir", type=Path, default=Path(os.environ.get("COURSE_RESULTS_DIR", "results")))
def validate_common_args(args: argparse.Namespace) -> None:
begin_experiment(args)
if getattr(args, "warmup", 0) < 0 or getattr(args, "iterations", 1) < 1:
raise SystemExit(
"--warmup must be non-negative and --iterations must be positive"
)
os.umask(0o077)
args.run_id = resolve_run_id(getattr(args, "run_id", None))
def resolve_run_id(value: str | None = None) -> str:
run_id = value if value is not None else os.environ.get("COURSE_RUN_ID")
if run_id is None:
run_id = secrets.token_hex(6)
if re.fullmatch(r"[0-9a-f]{12}", run_id) is None:
raise SystemExit("COURSE_RUN_ID must be exactly 12 lowercase hex characters")
return run_id
def resolve_int_override(
value: int | None,
default: int,
*,
option: str,
minimum: int = 1,
) -> int:
resolved = default if value is None else value
if resolved < minimum:
raise SystemExit(f"{option} must be at least {minimum}")
return resolved
def require_hf_commit_revision(value: str, *, option: str = "--revision") -> None:
"""Reject mutable branches and tags in reproducibility-critical labs."""
if re.fullmatch(r"[0-9a-f]{40}", value) is None:
raise SystemExit(
f"{option} must be an immutable 40-character Hugging Face commit ID"
)
def load_torch() -> Any:
try:
import torch
except ImportError as exc:
raise SystemExit(
"PyTorch is required; activate the inference mechanics environment."
) from exc
return torch
def seed_everything(torch: Any, seed: int) -> None:
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def require_course_gpu(torch: Any) -> dict[str, Any]:
if not torch.cuda.is_available():
raise SystemExit("CUDA is unavailable; allocate a full course GPU.")
props = torch.cuda.get_device_properties(torch.cuda.current_device())
try:
family = gpu_family(props.name)
if (props.major, props.minor) != (9, 0):
raise ValueError("Expected compute capability 9.0")
except ValueError as exc:
raise SystemExit(str(exc)) from exc
return {
"gpu_family": family,
"compute_capability": "9.0",
"memory_gib": round(props.total_memory / 2**30, 1),
"torch_version": torch.__version__,
"cuda_version": torch.version.cuda,
}
def cuda_times_ms(
torch: Any,
operation: Callable[[], Any],
*,
warmup: int,
iterations: int,
) -> list[float]:
warmup_operation = annotated_operation(operation, "course_warmup")
operation = annotated_operation(operation, "course_measure")
for _ in range(warmup):
warmup_operation()
torch.cuda.synchronize()
samples: list[float] = []
for _ in range(iterations):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
operation()
end.record()
end.synchronize()
samples.append(float(start.elapsed_time(end)))
return samples
def summarize_ms(samples: list[float]) -> dict[str, float]:
ordered = sorted(samples)
p90_index = max(0, min(len(ordered) - 1, math.ceil(0.9 * len(ordered)) - 1))
return {
"median_ms": round(statistics.median(ordered), 4),
"min_ms": round(ordered[0], 4),
"p90_ms": round(ordered[p90_index], 4),
}
def write_result(
args: argparse.Namespace,
*,
lab_id: str,
environment: dict[str, Any],
measurements: dict[str, Any],
correctness: dict[str, Any],
) -> Path:
failed_checks = sorted(key for key, value in correctness.items() if value is False)
if failed_checks:
raise SystemExit("Failed correctness checks: " + ", ".join(failed_checks))
run_id = resolve_run_id(getattr(args, "run_id", None))
target = args.output_dir / f"{lab_id}-run-{run_id}.json"
payload = {
"schema": "gpu-course-result/v1",
"lab_id": lab_id,
"profile": args.workload,
"run_id": run_id,
"seed": args.seed,
"environment": environment,
"measurements": measurements,
"correctness": correctness,
}
write_json_exclusive(target, payload)
return target
def open_private_exclusive(target: Path, *, binary: bool = False) -> IO[Any]:
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
try:
descriptor = os.open(target, flags, 0o600)
except FileExistsError as exc:
raise SystemExit(
f"Refusing to overwrite an existing artifact: {target}"
) from exc
if binary:
return os.fdopen(descriptor, "wb")
return os.fdopen(descriptor, "w", encoding="utf-8")
def write_json_exclusive(target: Path, payload: dict[str, Any]) -> Path:
document = json.dumps(enrich_result(payload), indent=2, sort_keys=True) + "\n"
atomic_result(target, document)
return target
def configure_slurm_distributed_env() -> tuple[int, int, int]:
rank = int(os.environ.get("RANK", os.environ.get("SLURM_PROCID", "0")))
world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("SLURM_STEP_NUM_TASKS", os.environ.get("SLURM_NTASKS", "1"))))
local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("SLURM_LOCALID", "0")))
os.environ.setdefault("RANK", str(rank))
os.environ.setdefault("WORLD_SIZE", str(world_size))
os.environ.setdefault("LOCAL_RANK", str(local_rank))
return rank, world_size, local_rank
def init_nccl(torch: Any, *, expected_world_size: int = 2) -> tuple[int, int, int]:
rank, world_size, local_rank = configure_slurm_distributed_env()
if world_size != expected_world_size:
raise SystemExit(
f"Expected {expected_world_size} ranks; use slurm/two_node.sbatch."
)
for required in ("MASTER_ADDR", "MASTER_PORT"):
if not os.environ.get(required):
raise SystemExit(f"{required} is missing; use the supplied Slurm launcher.")
torch.cuda.set_device(local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://", device_id=torch.device("cuda", local_rank)
)
return rank, world_size, local_rank
def close_distributed(torch: Any) -> None:
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
labs/job_processes.py
"""Private, bounded, job-owned subprocesses for communication experiments."""
from __future__ import annotations
import contextlib
import json
import os
import signal
import socket
import subprocess
import time
import urllib.request
from pathlib import Path
def allocated_nodes():
if (
not os.environ.get("SLURM_JOB_ID")
or os.environ.get("SLURM_JOB_NUM_NODES") != "2"
):
raise ValueError("Use the exclusive two-node vendor_job.sbatch launcher")
nodes = subprocess.check_output(
["scontrol", "show", "hostnames", os.environ["SLURM_JOB_NODELIST"]], text=True
).split()
if len(nodes) != 2 or len(set(nodes)) != 2:
raise ValueError("Expected exactly two distinct allocated nodes")
return nodes
def step(node, command, *, gpus=8, forward_interrupt=False):
return [
"srun",
"--overlap",
"--nodes=1",
"--ntasks=1",
"--nodelist=" + node,
"--gpus-per-task=" + str(gpus),
"--kill-on-bad-exit=1",
*(["--disable-status"] if forward_interrupt else []),
*command,
]
def private_folder(args, lab):
folder = (args.output_dir / lab / ("vendor-" + args.run_id)).resolve()
folder.mkdir(parents=True, mode=0o700, exist_ok=False)
return folder
class Processes:
def __init__(self, folder):
self.folder, self.children, self.files, self.signals = folder, [], [], {}
self.persistent = []
self.shutdown_options = {}
def __enter__(self):
def interrupted(signum, frame):
raise KeyboardInterrupt("Job interrupted")
self.signals = {
sig: signal.signal(sig, interrupted)
for sig in (signal.SIGTERM, signal.SIGINT)
}
return self
def start(
self,
name,
command,
env=None,
*,
persistent=False,
interrupt_on_exit=False,
shutdown_timeout=10,
):
output = (self.folder / (name + ".log")).open("x")
self.files.append(output)
child = subprocess.Popen(
command,
stdout=output,
stderr=subprocess.STDOUT,
env=env,
start_new_session=True,
)
self.children.append(child)
self.shutdown_options[child.pid] = (
signal.SIGINT if interrupt_on_exit else signal.SIGTERM,
shutdown_timeout,
)
if persistent:
self.persistent.append(child)
return child
def wait(self, child, timeout=900):
status = child.wait(timeout=timeout)
if status:
raise RuntimeError(
f"Vendor process exited with status {status}; inspect the private job log"
)
def healthy(self):
if any(child.poll() is not None for child in self.persistent) or any(
child.poll() not in (None, 0) for child in self.children
):
raise RuntimeError("An owned process failed before readiness")
def __exit__(self, *_):
for child in reversed(self.children):
if child.poll() is None:
stop_signal, timeout = self.shutdown_options[child.pid]
with contextlib.suppress(ProcessLookupError):
os.killpg(child.pid, stop_signal)
try:
child.wait(timeout=timeout)
except subprocess.TimeoutExpired:
with contextlib.suppress(ProcessLookupError):
os.killpg(child.pid, signal.SIGKILL)
child.wait()
for output in self.files:
output.close()
for sig, handler in self.signals.items():
signal.signal(sig, handler)
def wait_http(url, processes, timeout=600):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
processes.healthy()
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return json.load(response)
except (OSError, ValueError):
pass
time.sleep(0.5)
raise RuntimeError("Owned service did not become ready within its deadline")
def start_etcd(processes, node):
port = 25000 + int(os.environ["SLURM_JOB_ID"]) % 10000
endpoint = f"http://{node}:{port}"
listen_endpoint = f"http://{socket.gethostbyname(node)}:{port}"
peer = f"http://127.0.0.1:{port + 1}"
binary = os.environ.get("COURSE_ETCD")
if not binary or not Path(binary).is_file():
raise ValueError(
"Complete the shared README setup: COURSE_ETCD must identify the prepared etcd executable"
)
command = [
binary,
"--name",
"course",
"--data-dir",
str(processes.folder / "etcd"),
"--listen-client-urls",
listen_endpoint,
"--advertise-client-urls",
endpoint,
"--listen-peer-urls",
peer,
"--initial-advertise-peer-urls",
peer,
"--initial-cluster",
"course=" + peer,
"--initial-cluster-state",
"new",
]
processes.start("etcd", step(node, command, gpus=0), persistent=True)
wait_http(endpoint + "/health", processes, timeout=30)
return endpoint
labs/network_experiments.py
"""Controlled NCCL latency and NIC-selection experiments, with lazy GPU imports."""
from __future__ import annotations
import argparse
import os
import re
from common import (
add_common_args,
close_distributed,
validate_common_args,
write_result,
)
from course_evidence import evidence_phase
from fabric_common import all_correct, initialize, measure
def configure_transport(algorithm, policy, server_hca, client_hca):
if any(
name in os.environ
for name in ("NCCL_ALGO", "NCCL_PROTO", "NCCL_IB_HCA", "NCCL_IB_DISABLE")
):
raise ValueError(
"Start from a clean job environment: remove previous NCCL tuning overrides"
)
if algorithm != "auto":
os.environ["NCCL_ALGO"] = algorithm
if policy == "single":
if not all(
re.fullmatch(r"mlx5_[0-9]+", value or "")
for value in (server_hca, client_hca)
):
raise ValueError("Supply the observed mlx5 device on each allocated node")
node = int(os.environ["RANK"]) // 8
os.environ["NCCL_IB_HCA"] = "=" + (server_hca, client_hca)[node] + ":1"
os.environ["NCCL_DEBUG"] = "INFO"
os.environ["NCCL_DEBUG_SUBSYS"] = "INIT,NET,GRAPH"
def run(kind):
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--algorithm", choices=("auto", "Ring", "Tree"), default="auto")
parser.add_argument("--hca-policy", choices=("all", "single"), default="all")
parser.add_argument("--server-hca")
parser.add_argument("--client-hca")
args = parser.parse_args()
validate_common_args(args)
if kind == "latency" and args.hca_policy != "all":
parser.error("The latency experiment changes algorithm only")
if kind == "rails" and args.algorithm != "auto":
parser.error("The NIC experiment retains NCCL automatic algorithms")
configure_transport(
args.algorithm, args.hca_policy, args.server_hca, args.client_hca
)
torch, rank, world, _, env = initialize(args.seed)
try:
if world != 16:
raise ValueError(
"These network experiments require two nodes and sixteen ranks"
)
sizes = (
(4, 4096, 1048576)
if kind == "latency"
else ((4 if args.workload == "small" else 64) * 2**20,)
)
rows = []
for size in sizes:
tensor = torch.full((size // 4,), float(rank + 1), device="cuda")
def operation(tensor=tensor):
with evidence_phase("network_all_reduce"):
torch.distributed.all_reduce(
tensor, op=torch.distributed.ReduceOp.MAX
)
times = measure(torch, operation, args.warmup, args.iterations)
all_correct(
torch,
bool((tensor == world).all().item()),
"Collective payload differs from MAX reference",
)
rows.append(
{
"payload_bytes": size,
"median_ms": times["median_ms"],
"max_ms": times["max_ms"],
"useful_GBps": size / times["median_ms"] / 1e6,
"samples_ms": times["samples_ms"],
}
)
if rank == 0:
print(
write_result(
args,
lab_id="26_collective_latency"
if kind == "latency"
else "28_nic_selection",
environment=env,
measurements={"cases": rows},
correctness={"max_reference_exact": True},
)
)
finally:
close_distributed(torch)
labs/networking.py
"""Pure, bounded job-local NCCL experiment settings; no cluster configuration."""
from __future__ import annotations
from collections.abc import Mapping
PROFILES = {
"default": {},
"socket": {"NCCL_NET": "Socket"},
"gdr-off": {"NCCL_NET_GDR_LEVEL": "LOC"},
"ring": {"NCCL_ALGO": "Ring"},
"tree": {"NCCL_ALGO": "Tree"},
"qp1": {"NCCL_IB_QPS_PER_CONNECTION": "1"},
"qp4": {"NCCL_IB_QPS_PER_CONNECTION": "4"},
}
EXPERIMENT_KEYS = (
"NCCL_NET",
"NCCL_IB_DISABLE",
"NCCL_NET_GDR_LEVEL",
"NCCL_ALGO",
"NCCL_PROTO",
"NCCL_IB_QPS_PER_CONNECTION",
"NCCL_IB_SPLIT_DATA_ON_QPS",
"NCCL_IB_GID_INDEX",
"NCCL_TESTS_SPLIT",
"NCCL_TESTS_SPLIT_MASK",
"NCCL_TESTS_DEVICE",
)
def profile_settings(name: str, environment: Mapping[str, str]) -> dict[str, str]:
if name not in PROFILES:
raise ValueError("Unknown experiment profile")
conflicts = [key for key in EXPERIMENT_KEYS if key in environment]
if conflicts:
raise ValueError(
"Conflicting inherited NCCL experiment settings: "
+ ", ".join(conflicts)
+ ". Start a clean job shell; ask the owner before changing required site settings."
)
return PROFILES[name].copy()
def message_sizes(minimum: int, maximum: int) -> list[int]:
if not (8 <= minimum <= maximum <= 256 * 2**20):
raise ValueError("Message range must be between 8 bytes and 256 MiB")
if minimum & (minimum - 1) or maximum & (maximum - 1):
raise ValueError("Message bounds must be powers of two")
sizes = []
size = minimum
while size <= maximum:
sizes.append(size)
size *= 2
return sizes
labs/serving_client.py
"""A fixed public prompt workload with explicit client-visible streaming boundaries."""
from __future__ import annotations
import concurrent.futures
import hashlib
import json
import math
import statistics
import time
import urllib.request
from itertools import pairwise
def percentile(values, fraction):
if not values:
raise ValueError("No samples")
return sorted(values)[
min(len(values) - 1, max(0, math.ceil(len(values) * fraction) - 1))
]
def prompts(count, words):
base = "Describe how a packet moves through a network. "
return [
(base * words)
+ f"\nGive a concise numbered explanation for request {n % 4}. /no_think"
for n in range(count)
]
def request(url, prompt, output_tokens):
body = {
"model": "course-model",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0,
"max_tokens": output_tokens,
"min_tokens": output_tokens,
"ignore_eos": True,
"stream": True,
"stream_options": {"include_usage": True},
}
req = urllib.request.Request(
url + "/v1/chat/completions",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
)
started_unix_ns = time.time_ns()
started = time.perf_counter()
arrivals, content, usage = [], [], None
complete = False
with urllib.request.urlopen(req, timeout=180) as response:
for raw in response:
if not raw.startswith(b"data: "):
continue
payload = raw[6:].strip()
if payload == b"[DONE]":
complete = True
break
item = json.loads(payload)
if item.get("error"):
raise ValueError("Serving returned an error event")
if item.get("usage"):
usage = item["usage"]
for choice in item.get("choices", []):
delta = choice.get("delta", {})
text = (
delta.get("reasoning_content") or delta.get("reasoning") or ""
) + (delta.get("content") or "")
if text:
arrivals.append(time.perf_counter())
content.append(text)
if (
not complete
or not arrivals
or not usage
or usage.get("completion_tokens") != output_tokens
):
raise ValueError(
"Incomplete stream or changed output-token count; inspect min_tokens/ignore_eos support before comparison"
)
gaps = [(b - a) * 1000 for a, b in pairwise(arrivals)]
request_ms = (time.perf_counter() - started) * 1000
ended_unix_ns = time.time_ns()
return {
"request_start_unix_ns": started_unix_ns,
"request_end_unix_ns": ended_unix_ns,
"ttft_ms": (arrivals[0] - started) * 1000,
"request_ms": request_ms,
"mean_token_spacing_ms": (arrivals[-1] - arrivals[0])
* 1000
/ (output_tokens - 1)
if output_tokens > 1
else 0,
"chunk_gaps_ms": gaps,
"completion_tokens": output_tokens,
"prompt_tokens": usage["prompt_tokens"],
"output_sha256": hashlib.sha256("".join(content).encode()).hexdigest(),
}
def benchmark(url, *, count, words, output_tokens, concurrency, warmup, folder):
corpus = prompts(count, words)
for prompt in corpus[:warmup]:
request(url, prompt, output_tokens)
started_unix_ns = time.time_ns()
started = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
rows = list(
pool.map(lambda prompt: request(url, prompt, output_tokens), corpus)
)
elapsed = time.perf_counter() - started
ended_unix_ns = time.time_ns()
(folder / "requests.json").write_text(json.dumps(rows, indent=2) + "\n")
(folder / "measurement-window.json").write_text(
json.dumps(
{
"started_unix_ns": started_unix_ns,
"ended_unix_ns": ended_unix_ns,
"request_count": count,
"warmup_count": warmup,
"elapsed_seconds": elapsed,
"latency_clock": "time.perf_counter",
},
indent=2,
)
+ "\n"
)
gaps = [value for row in rows for value in row["chunk_gaps_ms"]]
return {
"request_count": count,
"prompt_tokens_total": sum(row["prompt_tokens"] for row in rows),
"output_tokens_total": count * output_tokens,
"ttft_p50_ms": statistics.median(row["ttft_ms"] for row in rows),
"ttft_p99_ms": percentile([row["ttft_ms"] for row in rows], 0.99),
"mean_token_spacing_ms": statistics.mean(
row["mean_token_spacing_ms"] for row in rows
),
"chunk_gap_p99_ms": percentile(gaps, 0.99) if gaps else 0,
"requests_per_second": count / elapsed,
"tokens_per_second": count * output_tokens / elapsed,
"elapsed_seconds": elapsed,
"prompt_corpus_sha256": hashlib.sha256(json.dumps(corpus).encode()).hexdigest(),
"output_signature": hashlib.sha256(
json.dumps([row["output_sha256"] for row in rows]).encode()
).hexdigest(),
}
labs/tiny_lm.py
"""Small decoder-only transformer used by the distributed training labs."""
from __future__ import annotations
from typing import Any
def build_tiny_lm(
torch: Any,
*,
vocab_size: int,
hidden_size: int,
layers: int,
heads: int,
max_sequence: int,
) -> Any:
class CausalSelfAttention(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.heads = heads
self.head_dim = hidden_size // heads
self.qkv = torch.nn.Linear(hidden_size, 3 * hidden_size, bias=False)
self.output = torch.nn.Linear(hidden_size, hidden_size, bias=False)
def forward(self, values: Any) -> Any:
batch, sequence, _ = values.shape
qkv = self.qkv(values).view(batch, sequence, 3, self.heads, self.head_dim)
query, key, value = qkv.unbind(dim=2)
query = query.transpose(1, 2)
key = key.transpose(1, 2)
value = value.transpose(1, 2)
attended = torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=True
)
attended = (
attended.transpose(1, 2).contiguous().view(batch, sequence, hidden_size)
)
return self.output(attended)
class Block(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.attention_norm = torch.nn.LayerNorm(hidden_size)
self.attention = CausalSelfAttention()
self.mlp_norm = torch.nn.LayerNorm(hidden_size)
self.mlp = torch.nn.Sequential(
torch.nn.Linear(hidden_size, 4 * hidden_size, bias=False),
torch.nn.GELU(),
torch.nn.Linear(4 * hidden_size, hidden_size, bias=False),
)
def forward(self, values: Any) -> Any:
values = values + self.attention(self.attention_norm(values))
return values + self.mlp(self.mlp_norm(values))
class TinyCausalLM(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.token_embedding = torch.nn.Embedding(vocab_size, hidden_size)
self.position_embedding = torch.nn.Embedding(max_sequence, hidden_size)
self.blocks = torch.nn.ModuleList([Block() for _ in range(layers)])
self.final_norm = torch.nn.LayerNorm(hidden_size)
self.lm_head = torch.nn.Linear(hidden_size, vocab_size, bias=False)
def forward(self, token_ids: Any) -> Any:
positions = torch.arange(token_ids.shape[1], device=token_ids.device)
hidden = self.token_embedding(token_ids) + self.position_embedding(
positions
)
for block in self.blocks:
hidden = block(hidden)
return self.lm_head(self.final_norm(hidden))
return TinyCausalLM()
def make_language_batch(
torch: Any,
*,
batch_size: int,
sequence: int,
vocab_size: int,
device: str,
offset: int = 0,
) -> tuple[Any, Any]:
"""Create deterministic next-token data without downloading a dataset."""
starts = torch.arange(batch_size, device=device).unsqueeze(1) + offset
steps = torch.arange(sequence + 1, device=device).unsqueeze(0)
tokens = (starts * 7 + steps * 3 + 11) % vocab_size
return tokens[:, :-1].long(), tokens[:, 1:].long()
labs/training_common.py
"""Shared, dependency-light helpers for the LLM training and inference labs."""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import secrets
import statistics
from collections.abc import Callable
from pathlib import Path
from typing import IO, Any
from course_evidence import (
annotated_operation,
atomic_result,
begin_experiment,
enrich_result,
gpu_family,
)
DEFAULT_MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
DEFAULT_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
def add_common_args(
parser: argparse.ArgumentParser, *, include_measurement: bool = True
) -> None:
parser.add_argument("--workload", choices=("small", "large"), default=os.environ.get("COURSE_WORKLOAD", "small"))
parser.add_argument("--seed", type=int, default=17)
if include_measurement:
parser.add_argument("--warmup", type=int, default=3)
parser.add_argument("--iterations", type=int, default=10)
parser.add_argument("--output-dir", type=Path, default=Path(os.environ.get("COURSE_RESULTS_DIR", "results")))
def validate_common_args(args: argparse.Namespace) -> None:
begin_experiment(args)
if getattr(args, "warmup", 0) < 0 or getattr(args, "iterations", 1) < 1:
raise SystemExit(
"--warmup must be non-negative and --iterations must be positive"
)
os.umask(0o077)
args.run_id = resolve_run_id(getattr(args, "run_id", None))
def resolve_run_id(value: str | None = None) -> str:
run_id = value if value is not None else os.environ.get("COURSE_RUN_ID")
if run_id is None:
run_id = secrets.token_hex(6)
if re.fullmatch(r"[0-9a-f]{12}", run_id) is None:
raise SystemExit("COURSE_RUN_ID must be exactly 12 lowercase hex characters")
return run_id
def resolve_int_override(
value: int | None,
default: int,
*,
option: str,
minimum: int = 1,
) -> int:
resolved = default if value is None else value
if resolved < minimum:
raise SystemExit(f"{option} must be at least {minimum}")
return resolved
def require_hf_commit_revision(value: str, *, option: str = "--revision") -> None:
"""Reject mutable branches and tags in reproducibility-critical labs."""
if re.fullmatch(r"[0-9a-f]{40}", value) is None:
raise SystemExit(
f"{option} must be an immutable 40-character Hugging Face commit ID"
)
def load_torch() -> Any:
try:
import torch
except ImportError as exc:
raise SystemExit(
"PyTorch is required; activate the training environment."
) from exc
return torch
def seed_everything(torch: Any, seed: int) -> None:
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def require_course_gpu(torch: Any) -> dict[str, Any]:
if not torch.cuda.is_available():
raise SystemExit("CUDA is unavailable; allocate a full course GPU.")
props = torch.cuda.get_device_properties(torch.cuda.current_device())
try:
family = gpu_family(props.name)
if (props.major, props.minor) != (9, 0):
raise ValueError("Expected compute capability 9.0")
except ValueError as exc:
raise SystemExit(str(exc)) from exc
return {
"gpu_family": family,
"compute_capability": "9.0",
"memory_gib": round(props.total_memory / 2**30, 1),
"torch_version": torch.__version__,
"cuda_version": torch.version.cuda,
}
def cuda_times_ms(
torch: Any,
operation: Callable[[], Any],
*,
warmup: int,
iterations: int,
) -> list[float]:
warmup_operation = annotated_operation(operation, "course_warmup")
operation = annotated_operation(operation, "course_measure")
for _ in range(warmup):
warmup_operation()
torch.cuda.synchronize()
samples: list[float] = []
for _ in range(iterations):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
operation()
end.record()
end.synchronize()
samples.append(float(start.elapsed_time(end)))
return samples
def summarize_ms(samples: list[float]) -> dict[str, float]:
ordered = sorted(samples)
p90_index = max(0, min(len(ordered) - 1, math.ceil(0.9 * len(ordered)) - 1))
return {
"median_ms": round(statistics.median(ordered), 4),
"min_ms": round(ordered[0], 4),
"p90_ms": round(ordered[p90_index], 4),
}
def sgd_updates_match(
torch: Any,
initial: tuple[Any, ...],
baseline: tuple[Any, ...],
candidate: tuple[Any, ...],
*,
learning_rate: float,
) -> bool:
"""Check gradient agreement and each plain-SGD update at its actual scale."""
changed = False
with torch.no_grad():
for before, reference, observed in zip(
initial, baseline, candidate, strict=True
):
if reference.grad is None or observed.grad is None:
return False
if not all(
bool(torch.isfinite(value).all())
for value in (
before,
reference,
observed,
reference.grad,
observed.grad,
)
):
return False
scale = float(reference.grad.abs().max())
if scale == 0:
if not torch.equal(reference.grad, observed.grad):
return False
elif not torch.allclose(
observed.grad.float() / scale,
reference.grad.float() / scale,
rtol=1e-2,
atol=1e-2,
):
return False
for parameter in (reference, observed):
expected = before.clone().add_(parameter.grad, alpha=-learning_rate)
if not torch.equal(parameter, expected):
return False
changed = changed or not torch.equal(before, reference)
return changed
def write_result(
args: argparse.Namespace,
*,
lab_id: str,
environment: dict[str, Any],
measurements: dict[str, Any],
correctness: dict[str, Any],
) -> Path:
failed_checks = sorted(key for key, value in correctness.items() if value is False)
if failed_checks:
raise SystemExit("Failed correctness checks: " + ", ".join(failed_checks))
run_id = resolve_run_id(getattr(args, "run_id", None))
target = args.output_dir / f"{lab_id}-run-{run_id}.json"
payload = {
"schema": "gpu-course-result/v1",
"lab_id": lab_id,
"profile": args.workload,
"run_id": run_id,
"seed": args.seed,
"environment": environment,
"measurements": measurements,
"correctness": correctness,
}
write_json_exclusive(target, payload)
return target
def open_private_exclusive(target: Path, *, binary: bool = False) -> IO[Any]:
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
try:
descriptor = os.open(target, flags, 0o600)
except FileExistsError as exc:
raise SystemExit(
f"Refusing to overwrite an existing artifact: {target}"
) from exc
if binary:
return os.fdopen(descriptor, "wb")
return os.fdopen(descriptor, "w", encoding="utf-8")
def write_json_exclusive(target: Path, payload: dict[str, Any]) -> Path:
document = json.dumps(enrich_result(payload), indent=2, sort_keys=True) + "\n"
atomic_result(target, document)
return target
def configure_slurm_distributed_env() -> tuple[int, int, int]:
rank = int(os.environ.get("RANK", os.environ.get("SLURM_PROCID", "0")))
world_size = int(os.environ.get("WORLD_SIZE", os.environ.get("SLURM_STEP_NUM_TASKS", os.environ.get("SLURM_NTASKS", "1"))))
local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("SLURM_LOCALID", "0")))
os.environ.setdefault("RANK", str(rank))
os.environ.setdefault("WORLD_SIZE", str(world_size))
os.environ.setdefault("LOCAL_RANK", str(local_rank))
return rank, world_size, local_rank
def init_nccl(torch: Any, *, expected_world_size: int = 2) -> tuple[int, int, int]:
rank, world_size, local_rank = configure_slurm_distributed_env()
if world_size != expected_world_size:
raise SystemExit(
f"Expected {expected_world_size} ranks; use slurm/two_node.sbatch."
)
for required in ("MASTER_ADDR", "MASTER_PORT"):
if not os.environ.get(required):
raise SystemExit(f"{required} is missing; use the supplied Slurm launcher.")
torch.cuda.set_device(local_rank)
torch.distributed.init_process_group(
backend="nccl", init_method="env://", device_id=torch.device("cuda", local_rank)
)
return rank, world_size, local_rank
def close_distributed(torch: Any) -> None:
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
labs/vendor_capture.py
"""Profile worker-side vendor executables without contaminating their raw output."""
from __future__ import annotations
import argparse
import os
from pathlib import Path
def native_systems_prefix(prefix: list[str], report: Path, *, server=False, ucx=False):
"""Validate visible native argv before a coordinator launches its GPU workers."""
if prefix[:5] != ["env", "-u", "DEBUGINFOD_URLS", "nsys", "profile"]:
raise ValueError(
"Worker prefix must start with env -u DEBUGINFOD_URLS nsys profile"
)
expected = {
"--trace": "cuda,nvtx,osrt,nccl"
if server
else "cuda,nvtx,osrt,ucx"
if ucx
else "cuda,nvtx,osrt",
"--cuda-trace-scope": "process-tree",
"--sample": "none",
"--discard-environment": "true",
"--force-overwrite": "false",
"--kill": "none",
"--output": "{report}",
}
if server:
expected.update(
{
"--trace-fork-before-exec": "true",
"--cuda-graph-trace": "node",
"--capture-range": "cudaProfilerApi",
"--capture-range-end": "stop",
"--flush-on-cudaprofilerstop": "false",
"--wait": "primary",
}
)
else:
expected.update({"--cpuctxsw": "none", "--duration": "300", "--wait": "all"})
options = {}
for token in prefix[5:]:
key, separator, value = token.partition("=")
if not separator or key in options:
raise ValueError("Use each native worker option once, as --name=value")
options[key] = value
if options != expected:
raise ValueError(
"Native worker options must preserve the documented capture scope and private report"
)
return [
str(report)
if token == "{report}"
else token.replace("={report}", "=" + str(report))
for token in prefix
]
def add_worker_prefix(parser):
parser.add_argument(
"--worker-prefix",
nargs=argparse.REMAINDER,
help="Visible native Systems argv; put this option last. {report} is a private per-rank path.",
)
def validate_worker_prefix(args, *, server=False, ucx=True):
prefix = args.worker_prefix
if prefix is None:
return
if os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
raise ValueError(
"Clear COURSE_PROFILE_TOOL before supplying native worker argv"
)
if server and args.capture != "systems":
raise ValueError("Native server prefix requires --capture systems")
native_systems_prefix(prefix, Path("report"), server=server, ucx=ucx and not server)
os.environ["COURSE_CAPTURE"] = "1"
if not server:
os.environ["COURSE_PROFILE_TOOL"] = "nsys"
def worker_command(
command: list[str], output: Path, *, ucx: bool = False, prefix=None
) -> list[str]:
"""Call inside srun; keep the vendor stdout separate from profiler diagnostics."""
tool = os.environ.get("COURSE_PROFILE_TOOL", "none")
if tool not in ("none", "nsys"):
raise ValueError("Vendor communication captures support Nsight Systems only")
native = ["bash", "-c", 'set -euo pipefail; umask 077; set -o noclobber; output=$1; shift; exec "$@" >"$output"',
"vendor-stdout", str(output.resolve()), *command]
if prefix is not None:
return [
"timeout", "--signal=TERM", "--kill-after=15s", "900s",
*native_systems_prefix(prefix, output.resolve().with_suffix(""), ucx=ucx),
*native,
]
if tool == "none":
return native
raise ValueError("Supply the native --worker-prefix from the lab's Systems job")