Advanced Labs: Multi-GPUs Multi-Nodes communication optimization

Estimated guided hours: 64

Course overview

Advanced Labs develops the ability to diagnose communication across GPUs, network adapters, collectives and complete training or inference workloads. Through guided comparisons and independent investigations, learn to quantify exposed communication costs and justify a change using correctness, measurements and traces.

Read GPU Performance Tools before practical work. For the full lab route, complete GPU Fundamentals, GPU Performance Optimization and the relevant training or inference foundations, or bring equivalent readiness to launch Slurm jobs, produce a correct unprofiled result and interpret its GPU timeline. For Fundamentals Lesson 12, enter at Lab 02, then run Lab 08 after Lab 02 passes; reading Fundamentals through that lesson supplies this assignment's concepts. This is a labs-only course: each guide contains its own explanation and practice.

Practice requires two eight-H100 workers, sixteen GPUs in total, with local NVLink/NVSwitch and inter-worker InfiniBand. Follow the shared Lab Preparation and read its completion summary. The single command prepares software; these labs qualify the fabric and workload. The full route begins with Lab 01 and qualifies placement and fabric in Labs 01–07. The Fundamentals assignment uses Lab 02's readiness checks before Lab 08. Bounded experiments support scoped decisions; they do not establish production convergence or large-model scaling.

For a tensor-reading refresher, use PyTorch for GPU Performance Engineering, a concise visual course with commented examples and no labs.

Practical labs

Download results

Download all lab results:
Grafana dashboards, Small and Large results

Setup the lab environment:
Lab setup guide

Lab 01: Verify the GPU fabric and rank placement

A rank is one participating process, and its local rank chooses a GPU on its own node. This readiness check verifies rank placement, GPU links and a tiny all-reduce with a known sum.

Complete source: labs/01_fabric_topology.py
"""Qualify rank placement and collective correctness on one or two eight-H100 nodes."""

import argparse
import json
import socket
import subprocess
import sys

from common import (
    add_common_args,
    close_distributed,
    validate_common_args,
    write_result,
)
from fabric_common import all_correct, initialize, measure


def validate_placement(rows, world):
    if len(rows) != world or {r[0] for r in rows} != set(range(world)):
        raise ValueError("Missing or duplicate global ranks")
    hosts = {r[2] for r in rows}
    if len(hosts) != world // 8:
        raise ValueError("Expected one host per group of eight ranks")
    for host in hosts:
        local = [r for r in rows if r[2] == host]
        if {r[1] for r in local} != set(range(8)) or len({r[3] for r in local}) != 8:
            raise ValueError("Ranks do not own eight distinct local GPUs")
    return True


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch, rank, world, local, env = initialize(args.seed)
    try:
        props = torch.cuda.get_device_properties(local)
        rows = [None] * world
        torch.distributed.all_gather_object(
            rows, (rank, local, socket.gethostname(), str(props.uuid))
        )
        validate_placement(rows, world)
        guard = None
        if local == 0:
            guard = json.loads(
                subprocess.check_output(
                    [sys.executable, "tools/fabric_guard.py"], text=True
                )
            )
        guards = [None] * world
        torch.distributed.all_gather_object(guards, guard)
        counts = [g for g in guards if g is not None]
        value = torch.zeros(1, device="cuda")

        def collective():
            value.fill_(rank + 1)
            torch.distributed.all_reduce(value)

        times = measure(torch, collective, args.warmup, args.iterations)
        expected = world * (world + 1) // 2
        all_correct(torch, value.item() == expected, "Collective sum is incorrect")
        if rank == 0:
            print(
                write_result(
                    args,
                    lab_id="01_fabric_topology",
                    environment=env,
                    measurements={
                        "ranks": world,
                        "nodes": world // 8,
                        "gpus_per_node": 8,
                        "nvlink_peers_per_gpu": min(
                            g["nvlink_peers_per_gpu"] for g in counts
                        ),
                        "active_ib_ports_per_node_min": min(
                            g["active_ib_ports"] for g in counts
                        ),
                        "collective_sum": expected,
                        "all_reduce": times,
                    },
                    correctness={
                        "distinct_gpu_per_rank": True,
                        "all_reduce_exact": True,
                        "hardware_guard_passed": True,
                    },
                )
            )
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    main()
Teaching diagram
Two communication domainsWithin each worker, eight GPUs share the NVLink and NVSwitch domain. InfiniBand connects the workers through their adapters. The arrows identify paths to qualify, not measured bandwidth.Worker A: GPUs 0–7NVLink / NVSwitchWorker B: GPUs 8–15NVLink / NVSwitchHCA ↔ InfiniBand ↔ HCA
Two communication domains

Within each worker, eight GPUs share the NVLink and NVSwitch domain. InfiniBand connects the workers through their adapters. The arrows identify paths to qualify, not measured bandwidth.

# Normal execution
sbatch slurm/01_fabric_topology.sbatch --workload small

# Optional profiling
sbatch slurm/01_fabric_topology.sbatch --workload small --profiler all

Lab 02: Verify the two-node H100 platform

Before interpreting GPU timings, establish that the program is running on the platform you think it is. This lab checks process placement, device visibility, and communication using one rank on each of the two eight-GPU workers. For the Fundamentals assignment, read through Lesson 12 and complete shared preparation and fabric qualification; Optimization, a specialization, Lab 01 and Labs 03–07 are not prerequisites. The supplied launcher still checks the sixteen-H100 fabric. Verify this lab's placement and correctness results before continuing to Lab 08.

Complete source: labs/02_collective_readiness.py
"""Verify the two-node, two participating ranks on a sixteen-H100 course platform."""

from __future__ import annotations

import argparse
import socket

from collective_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    return parser.parse_args()


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    names: list[str | None] = [None] * world_size
    torch.distributed.all_gather_object(names, socket.gethostname())
    unique_nodes = len(set(names))
    if unique_nodes != 2:
        raise SystemExit(f"Expected two distinct nodes, observed {unique_nodes}.")
    # Create explicit input values on the selected device.
    probe = torch.tensor([float(rank + 1)], device="cuda")
    torch.distributed.all_reduce(probe)
    collective_ok = float(probe.item()) == 3.0
    if not collective_ok:
        raise SystemExit("NCCL all-reduce returned an unexpected value.")
    if rank == 0:
        environment["node_count"] = unique_nodes
        environment["rank_count"] = world_size
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="02_collective_readiness",
            environment=environment,
            measurements={"nccl_backend": torch.distributed.get_backend()},
            correctness={"two_distinct_nodes": True, "all_reduce": True},
        )
        print(f"Preflight passed; sanitized result: {target}")
    close_distributed(torch)


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/02_collective_readiness.sbatch --workload small

# Optional profiling
sbatch slurm/02_collective_readiness.sbatch --workload small --profiler all

Lab 03: Verify the distributed training allocation

Training correctness depends on each process owning the intended device and participating in the same communication group. This lab checks one participating GPU rank on each of two eight-H100 workers, using one participating rank per worker before DDP, FSDP2, or parallelism experiments.

Complete source: labs/03_training_readiness.py
"""Verify the two-node, one-full-H100-per-node Slurm learning environment."""

from __future__ import annotations

import argparse
import socket

from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    try:
        # Create explicit input values on the selected device.
        value = torch.tensor(float(rank + 1), device="cuda")
        torch.distributed.all_reduce(value)
        hosts: list[str | None] = [None] * world_size
        torch.distributed.all_gather_object(hosts, socket.gethostname())
        if rank == 0:
            if len(set(hosts)) != 2 or float(value) != 3.0:
                raise SystemExit(
                    "Expected two distinct hosts and an all-reduce result of 3.0."
                )
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="03_training_readiness",
                environment=environment,
                measurements={
                    "world_size": world_size,
                    "distinct_host_count": len(set(hosts)),
                },
                correctness={"two_nodes": True, "nccl_all_reduce": True},
            )
            print(f"Two-node H100 preflight passed: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/03_training_readiness.sbatch --workload small

# Optional profiling
sbatch slurm/03_training_readiness.sbatch --workload small --profiler all

Lab 04: Verify the two-node inference mechanics platform

Distributed inference requires correctly placed workers before model partitioning or serving behavior can be evaluated. This lab checks the two-node H100 allocation and a known NCCL collective without starting an inference engine.

Complete source: labs/04_inference_readiness.py
"""Verify the two-node, one-full-H100-per-node Slurm learning environment."""

from __future__ import annotations

import argparse
import socket

from inference_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    try:
        # Create explicit input values on the selected device.
        value = torch.tensor(float(rank + 1), device="cuda")
        torch.distributed.all_reduce(value)
        hosts: list[str | None] = [None] * world_size
        torch.distributed.all_gather_object(hosts, socket.gethostname())
        if rank == 0:
            if len(set(hosts)) != 2 or float(value) != 3.0:
                raise SystemExit(
                    "Expected two distinct hosts and an all-reduce result of 3.0."
                )
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="04_inference_readiness",
                environment=environment,
                measurements={
                    "world_size": world_size,
                    "distinct_host_count": len(set(hosts)),
                },
                correctness={"two_nodes": True, "nccl_all_reduce": True},
            )
            print(f"Two-node H100 preflight passed: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/04_inference_readiness.sbatch --workload small

# Optional profiling
sbatch slurm/04_inference_readiness.sbatch --workload small --profiler all

Lab 05: Establish the optimization platform contract

An optimization comparison is interpretable only when the execution platform is known and functioning. This lab verifies the advanced two-node H100 fabric used by the distributed exercises, including rank placement and a known collective result.

Complete source: labs/05_transport_readiness.py
"""Verify the two-node H100 optimization lab platform."""

from __future__ import annotations

import argparse
import socket

from common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    nodes: list[str | None] = [None] * world_size
    torch.distributed.all_gather_object(nodes, socket.gethostname())
    if len(set(nodes)) != 2:
        raise SystemExit("The full lab suite requires two distinct nodes.")
    # Create explicit input values on the selected device.
    probe = torch.tensor([rank + 1.0], device="cuda")
    torch.distributed.all_reduce(probe)
    if float(probe.item()) != 3.0:
        raise SystemExit("NCCL all-reduce validation failed.")
    if rank == 0:
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="05_transport_readiness",
            environment={**environment, "node_count": 2, "rank_count": world_size},
            measurements={"nccl_backend": torch.distributed.get_backend()},
            correctness={"topology": True, "all_reduce": True},
        )
        print(f"Preflight passed: {target}")
    close_distributed(torch)


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/05_transport_readiness.sbatch --workload small

# Optional profiling
sbatch slurm/05_transport_readiness.sbatch --workload small --profiler all

Lab 07: Validate host and GPU memory over InfiniBand

RDMA lets the NIC access registered memory without the CPU copying each payload. In this experiment you will measure a baseline, inspect the evidence, and change one control while keeping useful work fixed.

Complete source: labs/07_rdma_bandwidth.py
"""Compare host and CUDA buffers with validated, bidirectional InfiniBand RDMA writes."""

import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time

from course_evidence import allocation_gpu_family
from common import add_common_args, validate_common_args, write_result
from fabric_tools import PINS, qualified_binary, rdma_result


def vendor_command(binary, device, memory, size, iterations, depth, port, output):
    command = [
        str(binary),
        "-d",
        device,
        "-s",
        str(size),
        "-n",
        str(iterations),
        "-t",
        str(depth),
        "-p",
        str(port),
        "-b",
        "--report_gbits",
        "--data_validation",
        "--out_json",
        "--out_json_file=" + str(output),
    ]
    if memory != "host":
        command += ["--use_cuda=0"]
    if memory == "cuda-dmabuf":
        command += ["--use_cuda_dmabuf"]
    return command


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.set_defaults(iterations=1000, warmup=0)
    parser.add_argument(
        "--memory", choices=("host", "cuda-peermem", "cuda-dmabuf"), default="host"
    )
    parser.add_argument("--tx-depth", type=int, choices=(32, 64, 128, 256), default=128)
    parser.add_argument("--server-device", required=True)
    parser.add_argument("--client-device", required=True)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.iterations < 32 or args.warmup != 0:
        parser.error("Validated vendor runs require --iterations >=32 and --warmup 0")
    if (
        not os.environ.get("SLURM_JOB_ID")
        or os.environ.get("SLURM_JOB_NUM_NODES") != "2"
    ):
        parser.error("Use the two-node fabric_tools.sbatch allocation")
    if os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
        parser.error(
            "RDMA evidence comes from validated vendor reports, not CUDA kernel replay"
        )
    if any(
        not re.fullmatch(r"mlx5_[0-9]+", d)
        for d in (args.server_device, args.client_device)
    ):
        parser.error("Select the topology-qualified mlx5 device on each node")
    binary = qualified_binary("perftest")
    nodes = subprocess.check_output(
        ["scontrol", "show", "hostnames", os.environ["SLURM_JOB_NODELIST"]], text=True
    ).split()
    if len(nodes) != 2 or len(set(nodes)) != 2:
        parser.error("Expected two distinct allocated nodes")
    port = 24000 + int(os.environ["SLURM_JOB_ID"]) % 20000
    size = 65536 if args.workload == "small" else 4 * 2**20
    folder = (
        args.output_dir / "07_rdma_bandwidth" / ("vendor-" + args.run_id)
    ).resolve()
    folder.mkdir(mode=0o700, parents=True, exist_ok=False)
    processes = []
    try:
        for index, role in enumerate(("server", "client")):
            command = vendor_command(
                binary,
                (args.server_device, args.client_device)[index],
                args.memory,
                size,
                args.iterations,
                args.tx_depth,
                port,
                folder / (role + ".json"),
            )
            if role == "client":
                command.append(nodes[0])
            step = [
                "srun",
                "--exclusive",
                "--nodes=1",
                "--ntasks=1",
                "--gpus-per-task=8",
                "--nodelist=" + nodes[index],
                sys.executable,
                "labs/fabric_tools.py",
                "--role",
                role,
                "--folder",
                str(folder),
                "--port",
                str(port),
                "--",
                *command,
            ]
            process = subprocess.Popen(step, start_new_session=True)
            processes.append(process)
            if role == "server":
                deadline = time.monotonic() + 60
                while not (folder / "ready").is_file():
                    if process.poll() is not None or time.monotonic() >= deadline:
                        raise RuntimeError(
                            "Server readiness failed; inspect private endpoint log"
                        )
                    time.sleep(0.1)
        for process in processes:
            if process.wait(timeout=240):
                raise RuntimeError(
                    "RDMA endpoint failed; no comparison artifact was accepted"
                )
        reports = [
            rdma_result(
                json.loads((folder / (role + ".json")).read_text()),
                (folder / (role + ".log")).read_text(),
                size,
                args.iterations,
                args.tx_depth,
                args.memory,
            )
            for role in ("server", "client")
        ]
        print(
            write_result(
                args,
                lab_id="07_rdma_bandwidth",
                environment={
                    "gpu_family": allocation_gpu_family(),
                    "nodes": 2,
                    "gpus_per_node": 8,
                    "vendor_revision": PINS["perftest"],
                },
                measurements={
                    "payload_bytes": size,
                    "iterations": args.iterations,
                    "bidirectional_Gbps": min(r["bidirectional_Gbps"] for r in reports),
                    "validated_bytes_min": min(r["validated_bytes"] for r in reports),
                },
                correctness={
                    "both_endpoints_validated_bytes": True,
                    "infiniBand_rc_confirmed": True,
                },
            )
        )
    finally:
        for process in processes:
            if process.poll() is None:
                os.killpg(process.pid, signal.SIGTERM)
                try:
                    process.wait(timeout=15)
                except subprocess.TimeoutExpired:
                    os.killpg(process.pid, signal.SIGKILL)
                    process.wait()


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/07_rdma_bandwidth.sbatch --workload small --memory host --server-device "${SERVER_HCA:?qualified mlx5 device}" --client-device "${CLIENT_HCA:?qualified mlx5 device}"

# Optional profiling
sbatch slurm/07_rdma_bandwidth.sbatch --workload small --memory host --server-device "${SERVER_HCA:?qualified mlx5 device}" --client-device "${CLIENT_HCA:?qualified mlx5 device}" --profiler all

Lab 08: Measure a two-node NCCL all-reduce

Distributed work cannot progress faster than its required data exchanges allow. This lab reduces a known tensor across two nodes and measures how message size affects completion time. For the Fundamentals assignment, read through Lesson 12 and complete Lab 02's placement and correctness checks on the prepared, qualified sixteen-H100 fabric before running this lab. Optimization, a specialization, Lab 01 and Labs 03–07 are not prerequisites. The supplied launcher reserves the fabric while two ranks participate; afterward, return to Fundamentals to complete Lesson 12.

Complete source: labs/08_distributed_collectives.py
"""Measure and verify a two-node NCCL all-reduce."""

from __future__ import annotations

import argparse
import statistics
import time

from collective_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    resolve_int_override,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--payload-mib", type=int, default=None)
    return parser.parse_args()


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    payload_mib = resolve_int_override(
        args.payload_mib,
        8 if args.workload == "small" else 256,
        option="--payload-mib",
    )
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    elements = payload_mib * 2**20 // 4
    tensor = torch.empty(elements, device="cuda", dtype=torch.float32)
    for _ in range(args.warmup):
        tensor.fill_(rank + 1)
        torch.distributed.all_reduce(tensor)
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    samples = []
    for _ in range(args.iterations):
        tensor.fill_(rank + 1)
        torch.distributed.barrier()
        start = time.perf_counter()
        torch.distributed.all_reduce(tensor)
        torch.cuda.synchronize()
        samples.append((time.perf_counter() - start) * 1_000)
    correct = bool(torch.all(tensor == 3.0).item())
    if not correct:
        raise SystemExit("All-reduce result was not the sum of both ranks.")
    if rank == 0:
        median_ms = statistics.median(samples)
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="08_distributed_collectives",
            environment={**environment, "rank_count": world_size, "node_count": 2},
            measurements={
                "payload_mib": payload_mib,
                "median_ms": round(median_ms, 4),
                "effective_payload_gib_per_s": round(
                    (payload_mib / 1024) / (median_ms / 1_000), 2
                ),
            },
            correctness={"all_reduce_sum": True},
        )
        print(f"Completed collective benchmark: {target}")
    close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/08_distributed_collectives.sbatch --workload small --payload-mib 4

# Optional profiling
sbatch slurm/08_distributed_collectives.sbatch --workload small --payload-mib 4 --profiler all

Lab 09: Measure a two-node NCCL message-size curve

A communication problem can affect tiny synchronization messages differently from large tensors. This lab gives you a controlled way to see that difference before investigating a full training step.

Complete source: labs/09_nccl_transport_sweep.py
"""Measure a correct two-node FP32 all-reduce curve under one NCCL setting."""

from __future__ import annotations

import argparse
import os
import statistics
import time

from common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation
from networking import PROFILES, message_sizes, profile_settings


def summarize_curve(
    size: int, world: int, samples: list[float], wall_samples: list[float]
) -> dict:
    median_seconds = statistics.median(samples) / 1000
    if median_seconds <= 0:
        raise ValueError("Non-positive measured duration")
    algbw = size / median_seconds / 1e9
    return {
        "bytes": size,
        "slowest_rank_samples_ms": samples,
        **summarize_ms(samples),
        "slowest_rank_wall_samples_ms": wall_samples,
        "wall_summary": summarize_ms(wall_samples),
        "algbw_GBps_at_median": algbw,
        "normalized_busbw_GBps_at_median": algbw * 2 * (world - 1) / world,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--variant", choices=tuple(PROFILES), default="default")
    parser.add_argument("--min-bytes", type=int, default=8)
    parser.add_argument("--max-bytes", type=int, default=64 * 2**20)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if not 1 <= args.warmup <= 100 or not 3 <= args.iterations <= 1000:
        parser.error("Use 1–100 warmups and 3–1000 measured iterations")
    try:
        sizes = message_sizes(args.min_bytes, args.max_bytes)
        overrides = profile_settings(args.variant, os.environ)
    except ValueError as exc:
        parser.error(str(exc))
    # NCCL reads settings when the communicator is created, never mid-experiment.
    os.environ.update(overrides)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world, local_rank = init_nccl(torch)
    expected = world * (world + 1) // 2
    records = []
    try:
        for size in sizes:
            values = torch.empty(
                size // 4, dtype=torch.float32, device=f"cuda:{local_rank}"
            )
            start = torch.cuda.Event(enable_timing=True)
            stop = torch.cuda.Event(enable_timing=True)
            samples = []
            wall_samples = []
            correct = True
            for iteration in range(args.warmup + args.iterations):
                values.fill_(rank + 1)
                # Wait for queued GPU work to finish at this measurement boundary.
                torch.cuda.synchronize()
                torch.distributed.barrier()
                torch.cuda.synchronize()
                wall_start = time.perf_counter()
                start.record()
                work = torch.distributed.all_reduce(values, async_op=True)
                work.wait()  # Join NCCL's stream before recording the stop event.
                stop.record()
                stop.synchronize()
                wall_ms = (time.perf_counter() - wall_start) * 1000
                if iteration >= args.warmup:
                    samples.append(float(start.elapsed_time(stop)))
                    wall_samples.append(wall_ms)
                correct = correct and bool(torch.all(values == expected).item())
            # Create explicit input values on the selected device.
            sample_tensor = torch.tensor(
                samples, dtype=torch.float64, device=values.device
            )
            torch.distributed.all_reduce(
                sample_tensor, op=torch.distributed.ReduceOp.MAX
            )
            wall_tensor = torch.tensor(
                wall_samples, dtype=torch.float64, device=values.device
            )
            torch.distributed.all_reduce(wall_tensor, op=torch.distributed.ReduceOp.MAX)
            check = torch.tensor(int(correct), device=values.device)
            torch.distributed.all_reduce(check, op=torch.distributed.ReduceOp.MIN)
            if not bool(check.item()):
                raise SystemExit("All-reduce correctness failed on at least one rank")
            records.append(
                summarize_curve(
                    size, world, sample_tensor.tolist(), wall_tensor.tolist()
                )
            )
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="09_nccl_transport_sweep",
                environment={
                    **environment,
                    "rank_count": world,
                    "nccl_version": list(torch.cuda.nccl.version()),
                },
                measurements={
                    "variant": args.variant,
                    "job_local_overrides": overrides,
                    "acceptance_timing": os.environ.get("NCCL_DEBUG", "WARN")
                    in ("WARN", "VERSION"),
                    "dtype": "float32",
                    "collective": "all_reduce_sum",
                    "timing_scope": "maximum rank CUDA-event time per synchronized iteration",
                    "warmup": args.warmup,
                    "iterations": args.iterations,
                    "curve": records,
                    "transport_and_gdr": "not inferred; correlate separate diagnostic evidence",
                },
                correctness={"all_sizes_exact_on_all_ranks": True},
            )
            print(f"Communication sweep completed: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Reading an illustrative all-reduce result An illustrative two-rank result has a 64 MiB logical payload and 4000 microseconds duration. It yields about 16.78 decimal GB per second. All-reduce's normalized bus bandwidth factor equals one for two ranks. Each out-of-place and in-place result also needs a zero incorrect-element count. Illustration only — not a measured H100 result Payload: 64 MiB 67,108,864 bytes Duration: 4,000 μs 0.004 seconds Rank count: 2 Sum all-reduce algbw = bytes / seconds / 10⁹ ≈ 16.78 GB/s busbw factor: 2(N−1)/N N = 2 → factor = 1Read both buffer modes; require enabled checks and #wrong = 0 for each.Normalized bus bandwidth is not a NIC wire counter or proof of link saturation.
Reading an illustrative all-reduce result

An illustrative two-rank result has a 64 MiB logical payload and 4000 microseconds duration. It yields about 16.78 decimal GB per second. All-reduce's normalized bus bandwidth factor equals one for two ranks. Each out-of-place and in-place result also needs a zero incorrect-element count.

# Normal execution
sbatch slurm/09_nccl_transport_sweep.sbatch --max-bytes 1048576 --workload small

# Optional profiling
sbatch slurm/09_nccl_transport_sweep.sbatch --max-bytes 1048576 --workload small --profiler all

Lab 10: Run and interpret NVIDIA NCCL Tests on Slurm

NVIDIA NCCL Tests separates collective performance from model computation. In this lab you will launch its all-reduce benchmark on two H100 nodes, inspect the rank and version records, interpret both buffer-placement results, and compare a baseline with one justified candidate.

Complete source: labs/10_nccl_tests_report.py
"""Run or inspect a bounded MPI all_reduce_perf sweep without exporting secrets."""

from __future__ import annotations

import argparse
import hashlib
import math
import os
import re
import shutil
import subprocess
from pathlib import Path

from common import (
    add_common_args,
    open_private_exclusive,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation, gpu_family
from networking import PROFILES, message_sizes, profile_settings

SOURCE_COMMIT = "b4d5beebca8a76cf01335f724d154b9b9d394d96"
MAX_LOG_BYTES = 16 * 2**20


def acceptance_timing(mode: str, diagnostic: bool, document: str) -> bool:
    # Offline logs do not prove the launch or whether hidden instrumentation ran.
    verbose = re.search(r"\bNCCL (?:INFO|TRACE)\b", document) is not None
    return (
        mode == "run"
        and not diagnostic
        and not verbose
        and os.environ.get("COURSE_PROFILE_TOOL", "none") == "none"
    )


def parse_output(document: str, sizes: list[int], ranks: int) -> dict:
    """Accept only the pinned float/sum, uninstrumented two-mode table format."""
    lines = [" ".join(line.split()) for line in document.splitlines() if line.strip()]
    if re.search(r"\b(?:FAILED|ERROR)\b|NCCL WARN", document):
        raise ValueError(
            "Log contains a failed check or runtime warning/error; investigate first"
        )
    headers = [line for line in lines if line.startswith("# nccl-tests version ")]
    match = re.fullmatch(
        r"# nccl-tests version v?(2\.20\.0) \([^()]+\) nccl-headers=(\d+) nccl-library=(\d+)",
        headers[0] if len(headers) == 1 else "",
    )
    if not match:
        raise ValueError("Expected one nccl-tests 2.20.0 version record")
    if min(int(match[2]), int(match[3])) < 20000:
        raise ValueError("Invalid NCCL version record")
    configs = [line for line in lines if line.startswith("# nThread ")]
    config = re.fullmatch(
        r"# nThread 1 nGpus 1 minBytes (\d+) maxBytes (\d+) step: 2\(factor\) "
        r"warmup iters: (\d+) iters: (\d+) agg iters: 1 validation: (\d+) graph: 0 unalign: 0",
        configs[0] if len(configs) == 1 else "",
    )
    if not config or (int(config[1]), int(config[2])) != (sizes[0], sizes[-1]):
        raise ValueError("Missing or incompatible sweep configuration")
    if (
        not 1 <= int(config[3]) <= 100
        or not 3 <= int(config[4]) <= 1000
        or int(config[5]) < 1
    ):
        raise ValueError("Warm-up, iterations and enabled validation must be recorded")
    rank_rows = [line for line in lines if line.startswith("# Rank ")]
    seen_ranks, hosts, placements = set(), set(), set()
    families = set()
    per_node = 8 if ranks in (8, 16) else 1
    for line in rank_rows:
        entry = re.fullmatch(
            r"# Rank (\d+) Group 0 Pid \d+ on (\S+) device 0 \[([^]]+)\] (.+)", line
        )
        if not entry:
            raise ValueError("Expected one full GPU, visible device zero, per rank")
        families.add(gpu_family(entry[4]))
        seen_ranks.add(int(entry[1]))
        hosts.add(entry[2])
        placements.add((entry[2], entry[3]))
    if (
        len(rank_rows) != ranks
        or seen_ranks != set(range(ranks))
        or len(hosts) != ranks // per_node
        or len(placements) != ranks
        or any(sum(host == h for host, _ in placements) != per_node for h in hosts)
    ):
        raise ValueError(
            "Rank inventory must show distinct GPUs and the requested ranks per node"
        )
    table = (
        "# size count type redop root time algbw busbw #wrong time algbw busbw #wrong"
    )
    units = "# (B) (elements) (us) (GB/s) (GB/s) (us) (GB/s) (GB/s)"
    if lines.count(table) != 1 or lines.count(units) != 1:
        raise ValueError(
            "Unsupported columns or time units; use the uninstrumented table"
        )
    starts = [
        i
        for i, line in enumerate(lines)
        if re.fullmatch(r"# Collective test starting: .*all_reduce_perf\w*", line)
    ]
    ends = [
        i
        for i, line in enumerate(lines)
        if re.fullmatch(r"# Collective test concluded: .*all_reduce_perf\w*", line)
    ]
    good = "# Out of bounds values : 0 OK"
    if len(starts) != 1 or len(ends) != 1 or lines.count(good) != 1:
        raise ValueError(
            "Incomplete or duplicate test start/completion/correctness footer"
        )
    if (
        not starts[0]
        < lines.index(table)
        < lines.index(units)
        < lines.index(good)
        < ends[0]
    ):
        raise ValueError("Invalid report ordering")
    averages = [line for line in lines if line.startswith("# Avg bus bandwidth : ")]
    if len(averages) != 1 or not re.fullmatch(
        r"# Avg bus bandwidth : [0-9.eE+\-]+(?: OK)?", averages[0]
    ):
        raise ValueError("Missing average bandwidth footer")
    rows = []
    for position, line in enumerate(lines):
        if not line[0].isdigit():
            continue
        fields = line.split()
        if len(fields) != 13 or not lines.index(units) < position < lines.index(good):
            raise ValueError("Malformed, unexpected or misplaced numeric row")
        try:
            size, count = int(fields[0]), int(fields[1])
            if fields[2:5] != ["float", "sum", "-1"] or count * 4 != size:
                raise ValueError("Expected aligned float/sum all-reduce")
            row = {"bytes": size}
            for name, offset in (("out_of_place", 5), ("in_place", 9)):
                latency, algbw, busbw = map(float, fields[offset : offset + 3])
                wrong = int(fields[offset + 3])
                if not all(math.isfinite(v) for v in (latency, algbw, busbw)):
                    raise ValueError("Non-finite metric")
                if latency <= 0 or min(algbw, busbw) < 0 or wrong != 0:
                    raise ValueError("Invalid metric or nonzero correctness count")
                row[name] = {
                    "time_us": latency,
                    "algbw_GBps": algbw,
                    "normalized_busbw_GBps": busbw,
                    "wrong": wrong,
                }
            rows.append(row)
        except (ValueError, OverflowError) as exc:
            raise ValueError(
                "Invalid result row; inspect the private source log"
            ) from exc
    if [row["bytes"] for row in rows] != sizes:
        raise ValueError("Missing, duplicate or unexpected message sizes")
    # Do not retain hostnames, PIDs, PCI addresses, arbitrary environment or raw lines.
    return {
        "gpu_family": one_family(families),
        "benchmark_version": match[1],
        "nccl_headers": int(match[2]),
        "nccl_library": int(match[3]),
        "ranks": ranks,
        "warmup": int(config[3]),
        "iterations": int(config[4]),
        "validation_iterations": int(config[5]),
        "rows": rows,
    }


def one_family(families):
    if len(families) != 1:
        raise ValueError("Require one observed GPU family across all ranks")
    return next(iter(families))


def launch_command(
    binary: Path,
    mpi: str,
    sizes: list[int],
    warmup: int,
    iterations: int,
    nodes: int = 2,
    worker_prefix: list[str] | None = None,
) -> list[str]:
    if not re.fullmatch(r"(?:pmix(?:_v[0-9]+)?|pmi2)", mpi):
        raise ValueError("Select a site-qualified pmix, pmix_vN or pmi2 mode")
    native = [str(binary)]
    if worker_prefix:
        if "nsys" not in worker_prefix or "profile" not in worker_prefix:
            raise ValueError("Supply the native Systems worker command")
        native = [*worker_prefix, *native]
    elif os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
        raise ValueError("Supply the Systems job's explicit --worker-prefix")
    return [
        "srun",
        f"--mpi={mpi}",
        f"--nodes={nodes}",
        f"--ntasks={nodes * 8}",
        "--ntasks-per-node=8",
        "--gpus-per-task=1",
        "--gres-flags=allow-task-sharing",
        "--kill-on-bad-exit=1",
        "--export=ALL",
        *native,
        "-b",
        str(sizes[0]),
        "-e",
        str(sizes[-1]),
        "-f",
        "2",
        "-t",
        "1",
        "-g",
        "1",
        "-d",
        "float",
        "-o",
        "sum",
        "-w",
        str(warmup),
        "-n",
        str(iterations),
        "-c",
        "1",
        "-a",
        "3",
        "-I",
        "0",
        "-U",
        "0",
        "-C",
        "0",
        "-S",
        "0",
        "-T",
        "120",
    ]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--mode", choices=("run", "parse"), default="parse")
    parser.add_argument("--variant", choices=tuple(PROFILES), default="default")
    parser.add_argument(
        "--binary", type=Path, help="MPI-enabled all_reduce_perf, shared on both nodes"
    )
    parser.add_argument("--mpi", help="MPI integration confirmed by the cluster owner")
    parser.add_argument(
        "--input", type=Path, help="private stdout log for offline parsing"
    )
    parser.add_argument(
        "--exit-code", type=int, help="observed srun exit status for offline parsing"
    )
    parser.add_argument(
        "--diagnostic",
        action="store_true",
        help="INFO diagnostics, never acceptance timing",
    )
    parser.add_argument("--nodes", type=int, choices=(1, 2), default=2)
    parser.add_argument("--min-bytes", type=int, default=8)
    parser.add_argument("--max-bytes", type=int, default=64 * 2**20)
    parser.add_argument("--worker-prefix", nargs=argparse.REMAINDER)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    try:
        sizes = message_sizes(args.min_bytes, args.max_bytes)
        if not 1 <= args.warmup <= 100 or not 3 <= args.iterations <= 1000:
            raise ValueError("Use 1–100 warmups and 3–1000 iterations")
        metadata = {"variant": args.variant}
        if args.mode == "run":
            if args.input is not None or args.exit_code is not None:
                raise ValueError("--input/--exit-code belong to parse mode")
            if not os.environ.get("SLURM_JOB_ID") or os.environ.get(
                "SLURM_JOB_NUM_NODES"
            ) != str(args.nodes):
                raise ValueError(
                    "Use the matching one-/two-node eight-GPU Slurm launcher"
                )
            if args.binary is None or args.mpi is None or shutil.which("srun") is None:
                raise ValueError("Provide --binary and --mpi with srun available")
            binary = args.binary.resolve(strict=True)
            if not binary.is_file() or not os.access(binary, os.X_OK):
                raise ValueError("NCCL Tests binary must be executable")
            env = os.environ.copy()
            settings = profile_settings(args.variant, env)
            env.update(settings)
            if "NCCL_TESTS_DEVICE" in env or "NCCL_TESTS_MIN_BW" in env:
                raise ValueError(
                    "Remove inherited benchmark device/threshold overrides from the job shell"
                )
            # Slurm exposes one assigned GPU per task. The benchmark otherwise
            # uses the MPI local rank, which is outside that one-device view.
            env["NCCL_TESTS_DEVICE"] = "0"
            if not args.diagnostic and env.get("NCCL_DEBUG", "WARN") not in (
                "WARN",
                "VERSION",
            ):
                raise ValueError(
                    "Use --diagnostic for inherited verbose logging, then a clean timing job"
                )
            if args.diagnostic:
                env.update(NCCL_DEBUG="INFO", NCCL_DEBUG_SUBSYS="INIT,NET,GRAPH")
                if "NCCL_DEBUG_FILE" in env:
                    raise ValueError(
                        "Inherited debug-file redirection would split the diagnostic evidence"
                    )
            raw = args.output_dir / f"10_nccl_tests_report-run-{args.run_id}.log"
            command = launch_command(
                binary, args.mpi, sizes, args.warmup, args.iterations, args.nodes, args.worker_prefix
            )
            with open_private_exclusive(raw) as output:
                rank_logs = []
                if env.get("COURSE_PROFILE_TOOL", "none") != "none":
                    # Concurrent profiler progress can split lines in srun's
                    # merged stream. Retain each rank/stream intact and combine
                    # only after every task has exited; never relax the parser.
                    folder = raw.with_suffix(".rank-logs").resolve()
                    folder.mkdir(mode=0o700, exist_ok=False)
                    command[1:1] = [
                        f"--output={folder}/rank-%t.out",
                        f"--error={folder}/rank-%t.err",
                    ]
                    rank_logs = [
                        folder / f"rank-{rank}.{stream}"
                        for rank in range(args.nodes * 8)
                        for stream in ("out", "err")
                    ]
                completed = subprocess.run(
                    command,
                    env=env,
                    stdout=output,
                    stderr=subprocess.STDOUT,
                    timeout=900,
                    check=False,
                )
                if completed.returncode == 0 and rank_logs:
                    if (
                        output.tell() + sum(p.stat().st_size + 1 for p in rank_logs)
                        > MAX_LOG_BYTES
                    ):
                        raise ValueError("Rank logs exceed the 16 MiB parser limit")
                    for path in rank_logs:
                        output.write("\n" + path.read_text(encoding="utf-8"))
            if completed.returncode != 0:
                raise ValueError(
                    "srun failed; private log retained, no successful report published"
                )
            with binary.open("rb") as stream:
                digest = hashlib.file_digest(stream, "sha256").hexdigest()
            metadata.update(
                job_local_overrides=settings,
                launcher_exit_code=0,
                local_binary_sha256=digest,
                reviewed_source_commit=SOURCE_COMMIT,
                remote_binary_parity="requires independent per-node qualification",
            )
        else:
            if args.binary is not None or args.mpi is not None:
                raise ValueError("--binary/--mpi belong to run mode")
            if args.input is None or args.exit_code != 0:
                raise ValueError(
                    "Provide --input and an independently observed --exit-code 0"
                )
            raw = args.input
            metadata.update(
                launcher_exit_code=0,
                exit_status_evidence="learner supplied, not observed by parser",
            )
        if raw.stat().st_size > MAX_LOG_BYTES:
            raise ValueError("Log exceeds the 16 MiB parser limit")
        document = raw.read_text(encoding="utf-8")
        report = parse_output(document, sizes, args.nodes * 8)
        os.environ["WORLD_SIZE"] = str(args.nodes * 8)
        metadata["acceptance_timing"] = acceptance_timing(
            args.mode, args.diagnostic, document
        )
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="10_nccl_tests_report",
            environment={
                "gpu_family": report.pop("gpu_family"),
                "target": "eight-GPU NVLink and InfiniBand workers",
                "evidence_lane": args.mode,
                "rank_count": args.nodes * 8,
            },
            measurements={**metadata, **report},
            correctness={"checked_elements_match": True},
        )
        print(f"Validated NCCL Tests report: {target}")
    except (ValueError, OSError, subprocess.TimeoutExpired) as exc:
        parser.exit(2, f"ERROR: {type(exc).__name__}: {exc}\n")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/10_nccl_tests_report.sbatch default --workload small

# Optional profiling
sbatch slurm/10_nccl_tests_report.sbatch default --workload small --profiler all

Lab 11: Compare flat and hierarchical all-reduce

All-reduce returns the sum to every participant. In this experiment you will measure a baseline, inspect the evidence, and change one control while keeping useful work fixed.

Complete source: labs/11_collective_layout.py
"""Compare NCCL all-reduce with an explicit two-level reduction of identical values."""

import argparse

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 main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--layout", choices=("flat", "hierarchical"), default="flat")
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch, rank, world, local, env = initialize(args.seed)
    try:
        count = (1 if args.workload == "small" else 64) * 2**20 // 4
        # Every rank creates every group in the same order, including nonmembers.
        local_groups = [
            torch.distributed.new_group(list(range(start, start + 8)))
            for start in range(0, world, 8)
        ]
        leaders = list(range(0, world, 8))
        leader_group = torch.distributed.new_group(leaders)
        group = local_groups[rank // 8]
        leader = rank - local
        values = torch.empty(count, device="cuda", dtype=torch.float32)

        def operation():
            values.fill_(rank + 1)
            if args.layout == "flat":
                with evidence_phase("flat_all_reduce"):
                    torch.distributed.all_reduce(values)
            else:
                with evidence_phase("local_reduce"):
                    torch.distributed.reduce(values, dst=leader, group=group)
                with evidence_phase("leader_all_reduce"):
                    if local == 0:
                        torch.distributed.all_reduce(values, group=leader_group)
                with evidence_phase("local_broadcast"):
                    torch.distributed.broadcast(values, src=leader, group=group)

        times = measure(torch, operation, args.warmup, args.iterations)
        expected = world * (world + 1) // 2
        all_correct(
            torch, bool((values == expected).all().item()), "Reduced values differ"
        )
        if rank == 0:
            print(
                write_result(
                    args,
                    lab_id="11_collective_layout",
                    environment=env,
                    measurements={
                        "elements": count,
                        "payload_bytes": count * 4,
                        "ranks": world,
                        "collective": times,
                        "useful_GBps": count * 4 / times["median_ms"] / 1e6,
                    },
                    correctness={"all_elements_exact": True},
                )
            )
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/11_collective_layout.sbatch --workload small --layout flat

# Optional profiling
sbatch slurm/11_collective_layout.sbatch --workload small --layout flat --profiler all

Lab 12: Compare one GPU with two-node DDP

Adding a GPU adds both compute capacity and communication work. This lab runs a bounded training step on one GPU and through two-node DistributedDataParallel while preserving global batch size. Normal execution uses one GPU; --experiment two-node and Systems use two nodes.

Complete source: labs/12_distributed_scaling.py
"""Run the same training step on one H100 or two-node DDP."""

from __future__ import annotations

import argparse
import math
import statistics
import time

from common import (
    add_common_args,
    close_distributed,
    configure_slurm_distributed_env,
    init_nccl,
    load_torch,
    require_course_gpu,
    resolve_int_override,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--global-batch", type=int, default=None)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    global_batch = resolve_int_override(
        args.global_batch,
        64 if args.workload == "small" else 512,
        option="--global-batch",
    )
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    _, detected_world, _ = configure_slurm_distributed_env()
    distributed = detected_world > 1
    if distributed:
        rank, world_size, local_rank = init_nccl(torch)
    else:
        rank, world_size, local_rank = 0, 1, 0
        torch.cuda.set_device(0)
    if global_batch % world_size:
        raise SystemExit("--global-batch must be divisible by the number of ranks")
    local_batch = global_batch // world_size
    width = 2_048 if args.workload == "small" else 8_192
    model = torch.nn.Sequential(
        torch.nn.Linear(width, width * 2, bias=False),
        torch.nn.GELU(),
        torch.nn.Linear(width * 2, width, bias=False),
    ).to(device=f"cuda:{local_rank}", dtype=torch.bfloat16)
    if distributed:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[local_rank]
        )
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
    # Create the synthetic tensors used by this experiment.
    global_inputs = torch.randn(
        (global_batch, width), device=f"cuda:{local_rank}", dtype=torch.bfloat16
    )
    first = rank * local_batch
    inputs = global_inputs[first : first + local_batch]

    def step() -> float:
        # Clear the previous step’s gradients before differentiating again.
        optimizer.zero_grad(set_to_none=True)
        loss = model(inputs).float().square().mean()
        # Differentiate the loss to populate parameter gradients.
        loss.backward()
        # Update the parameters using the gradients from this step.
        optimizer.step()
        return float(loss.detach())

    for _ in range(args.warmup):
        step()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    samples = []
    last_loss = 0.0
    for _ in range(args.iterations):
        if distributed:
            torch.distributed.barrier()
        start = time.perf_counter()
        last_loss = step()
        torch.cuda.synchronize()
        # Create explicit input values on the selected device.
        elapsed = torch.tensor(
            (time.perf_counter() - start) * 1_000,
            device=f"cuda:{local_rank}",
            dtype=torch.float64,
        )
        if distributed:
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
        samples.append(float(elapsed.item()))
    finite = torch.tensor(int(math.isfinite(last_loss)), device=f"cuda:{local_rank}")
    if distributed:
        torch.distributed.all_reduce(finite, op=torch.distributed.ReduceOp.MIN)
    if not bool(finite):
        raise SystemExit("At least one rank produced a non-finite loss.")
    if rank == 0:
        median_ms = statistics.median(samples)
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="12_distributed_scaling",
            environment={**environment, "rank_count": world_size},
            measurements={
                "global_batch": global_batch,
                "timing_scope": "slowest rank per iteration",
                "median_step_ms": round(median_ms, 4),
                "samples_per_second": round(global_batch / (median_ms / 1_000), 2),
            },
            correctness={"all_ranks_finite_loss": True},
        )
        print(f"Completed {world_size}-rank scaling run: {target}")
    close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/12_distributed_scaling.sbatch --workload small --global-batch 64

# Optional profiling
sbatch slurm/12_distributed_scaling.sbatch --workload small --global-batch 64 --profiler all

Lab 13: Test whether communication can overlap independent compute

Communication is not automatically hidden just because an API is asynchronous. This lab compares serialized compute-plus-all-reduce with a schedule that permits the two independent tasks to overlap across two H100 nodes.

Complete source: labs/13_collective_overlap.py
"""Compare serialized and overlapped compute plus two-node all-reduce."""

from __future__ import annotations

import argparse
import math
import statistics
import time
from collections.abc import Callable

from common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    rank, world_size, local_rank = init_nccl(torch)
    device = f"cuda:{local_rank}"
    matrix_size = 2_048 if args.workload == "small" else 4_096
    collective_mib = 64 if args.workload == "small" else 512
    element_count = collective_mib * 2**20 // 2
    collective = torch.empty(element_count, device=device, dtype=torch.bfloat16)
    # Create the synthetic tensors used by this experiment.
    left = torch.randn((matrix_size, matrix_size), device=device, dtype=torch.bfloat16)
    right = torch.randn_like(left)
    product = torch.empty_like(left)
    communication_stream = torch.cuda.Stream(device=local_rank)
    default_stream = torch.cuda.default_stream(device=local_rank)

    def serialized() -> None:
        collective.fill_(rank + 1)
        torch.distributed.all_reduce(collective)
        torch.mm(left, right, out=product)

    def overlapped() -> None:
        collective.fill_(rank + 1)
        communication_stream.wait_stream(default_stream)
        with torch.cuda.stream(communication_stream):
            work = torch.distributed.all_reduce(collective, async_op=True)
        torch.mm(left, right, out=product)
        work.wait()
        default_stream.wait_stream(communication_stream)

    def measure(operation: Callable[[], None]) -> list[float]:
        for _ in range(args.warmup):
            operation()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        samples: list[float] = []
        for _ in range(args.iterations):
            torch.distributed.barrier()
            started = time.perf_counter()
            operation()
            torch.cuda.synchronize()
            # Create explicit input values on the selected device.
            elapsed = torch.tensor(
                (time.perf_counter() - started) * 1_000,
                device=device,
                dtype=torch.float64,
            )
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
            samples.append(float(elapsed.item()))
        return samples

    serialized_samples = measure(serialized)
    overlapped_samples = measure(overlapped)
    overlapped()
    torch.cuda.synchronize()
    expected = float(sum(range(1, world_size + 1)))
    collective_ok = bool(
        torch.all(collective == torch.tensor(expected, device=device)).item()
    )
    compute_ok = bool(torch.isfinite(product).all().item())
    local_ok = torch.tensor(
        int(collective_ok and compute_ok), device=device, dtype=torch.int32
    )
    torch.distributed.all_reduce(local_ok, op=torch.distributed.ReduceOp.MIN)
    if not bool(local_ok.item()):
        raise SystemExit("At least one rank failed the overlap correctness gates.")
    if rank == 0:
        serialized_median = statistics.median(serialized_samples)
        overlapped_median = statistics.median(overlapped_samples)
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="13_collective_overlap",
            environment={**environment, "rank_count": world_size},
            measurements={
                "matrix_size": matrix_size,
                "collective_mib": collective_mib,
                "timing_scope": "slowest rank per iteration",
                "serialized_median_ms": round(serialized_median, 4),
                "overlapped_median_ms": round(overlapped_median, 4),
                "serialized_to_overlap_ratio": round(
                    serialized_median / overlapped_median, 4
                ),
            },
            correctness={
                "all_reduce_exact": True,
                "compute_is_finite": True,
                "ratio_is_finite": math.isfinite(serialized_median / overlapped_median),
            },
        )
        print(f"Completed collective-overlap experiment: {target}")
    close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Serialized versus overlapped two-node work The serialized case places communication and independent compute one after the other on the critical path. The overlap case starts them together on separate timeline rows and joins after both complete, leaving only communication beyond the compute interval exposed. serialized overlap candidate comm compute all-reduce fully exposed independent GEMM starts only after collective asynchronous all-reduce communication path independent GEMM compute path join consume reduced data only after both dependencies have completed consumer waits for the collective tail
Serialized versus overlapped two-node work

The serialized case places communication and independent compute one after the other on the critical path. The overlap case starts them together on separate timeline rows and joins after both complete, leaving only communication beyond the compute interval exposed.

# Normal execution
sbatch slurm/13_collective_overlap.sbatch --workload small

# Optional profiling
sbatch slurm/13_collective_overlap.sbatch --workload small --profiler all

Lab 14: Correlate PyTorch and Systems traces across ranks

Independent compute can overlap an asynchronous all-reduce only until a dependent consumer needs its result. In this experiment you will measure a baseline, inspect the evidence, and change one control while keeping useful work fixed.

Complete source: labs/14_distributed_profiling.py
"""Correlate per-rank traces for independent GEMM and all-reduce work."""

import argparse
import os

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 main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--overlap", choices=("off", "on"), default="off")
    parser.add_argument("--torch-trace", action="store_true")
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    if args.torch_trace:
        if os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
            raise SystemExit("Capture PyTorch and Nsight in separate diagnostic runs.")
        os.environ["COURSE_CAPTURE"] = "1"
    validate_common_args(args)
    torch, rank, world, _local, env = initialize(args.seed)
    try:
        size = 1024 if args.workload == "small" else 4096
        elements = (4 if args.workload == "small" else 64) * 2**20 // 4
        # Create the synthetic tensors used by this experiment.
        x = torch.randn(size, size, device="cuda")
        y = torch.randn_like(x)
        reference = x @ y
        output = torch.empty_like(x)
        values = torch.empty(elements, device="cuda")

        def operation():
            values.fill_(rank + 1)
            with evidence_phase("communication"):
                work = torch.distributed.all_reduce(
                    values, async_op=args.overlap == "on"
                )
            with evidence_phase("independent_compute"):
                torch.mm(x, y, out=output)
            with evidence_phase("wait_for_collective"):
                if work is not None:
                    work.wait()

        times = measure(torch, operation, args.warmup, args.iterations)
        all_correct(
            torch,
            bool(torch.equal(values, torch.full_like(values, world * (world + 1) // 2)))
            and bool(torch.allclose(output, reference, rtol=1e-4, atol=1e-4)),
            "Overlap changed the result",
        )
        if args.torch_trace:
            folder = (
                args.output_dir
                / "14_distributed_profiling"
                / "profiles"
                / ("torch-" + args.run_id)
            )
            folder.mkdir(parents=True, mode=0o700, exist_ok=True)
            # Each rank owns a unique filename; profiling samples are never performance claims.
            trace = folder / f"rank-{rank}.json"
            with torch.profiler.profile(
                activities=[
                    torch.profiler.ProfilerActivity.CPU,
                    torch.profiler.ProfilerActivity.CUDA,
                ],
                schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1),
                on_trace_ready=lambda p: p.export_chrome_trace(str(trace)),
                record_shapes=True,
                profile_memory=True,
                with_stack=False,
            ) as profiler:
                for _ in range(5):
                    with torch.profiler.record_function("training_like_step"):
                        operation()
                        # Wait for queued GPU work to finish at this measurement boundary.
                        torch.cuda.synchronize()
                    profiler.step()
            print(f"Rank {rank} PyTorch trace: {trace}")
        if rank == 0:
            print(
                write_result(
                    args,
                    lab_id="14_distributed_profiling",
                    environment=env,
                    measurements={
                        "matrix_size": size,
                        "elements": elements,
                        "ranks": world,
                        "step": times,
                    },
                    correctness={
                        "collective_exact": True,
                        "matmul_matches_reference": True,
                    },
                )
            )
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/14_distributed_profiling.sbatch --workload small --overlap off

# Optional profiling
sbatch slurm/14_distributed_profiling.sbatch --workload small --overlap off --profiler all

Lab 15: Train replicated models with DDP

DistributedDataParallel lets each GPU process different data while keeping replicated model updates coordinated. This lab trains the tiny language model with one rank on each H100 node.

Complete source: labs/15_ddp_train.py
"""Train the tiny language model with one DDP rank on each H100 node."""

from __future__ import annotations

import argparse
import math

from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--zero-grad-fill",
        action="store_true",
        help="Zero existing gradient buffers instead of releasing them; keep all work fixed.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, local_rank = init_nccl(torch)
    try:
        # Keep random inputs repeatable across comparable runs.
        seed_everything(torch, args.seed)
        hidden, layers, sequence, batch = (
            (512, 4, 256, 8) if args.workload == "small" else (2_048, 12, 1_024, 4)
        )
        vocab_size = 4_096
        model = build_tiny_lm(
            torch,
            vocab_size=vocab_size,
            hidden_size=hidden,
            layers=layers,
            heads=8 if hidden == 512 else 16,
            max_sequence=sequence,
        ).to(local_rank)
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[local_rank]
        )
        optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
        forward = annotated_operation(model, "forward")
        # Differentiate the loss to populate parameter gradients.
        backward = annotated_operation(lambda loss: loss.backward(), "backward")
        update = annotated_operation(optimizer.step, "optimizer")
        clear_gradients = annotated_operation(optimizer.zero_grad, "zero_grad")
        inputs, labels = make_language_batch(
            torch,
            batch_size=batch,
            sequence=sequence,
            vocab_size=vocab_size,
            device=f"cuda:{local_rank}",
            offset=rank * batch,
        )

        def train_step() -> object:
            with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
                logits = forward(inputs)
                step_loss = torch.nn.functional.cross_entropy(
                    logits.reshape(-1, vocab_size), labels.reshape(-1)
                )
            backward(step_loss)
            update()
            clear_gradients(set_to_none=not args.zero_grad_fill)
            return step_loss.detach()

        for _ in range(args.warmup):
            train_step()
        tracked_before = next(model.parameters()).detach().cpu().clone()
        torch.distributed.barrier()
        torch.cuda.reset_peak_memory_stats()
        started = torch.cuda.Event(enable_timing=True)
        ended = torch.cuda.Event(enable_timing=True)
        started.record()
        loss = None
        for _ in range(args.iterations):
            loss = train_step()
        ended.record()
        ended.synchronize()
        assert loss is not None
        # Create explicit input values on the selected device.
        elapsed_ms = torch.tensor(
            float(started.elapsed_time(ended)), device=f"cuda:{local_rank}"
        )
        peak_allocated = torch.tensor(
            torch.cuda.max_memory_allocated(),
            device=f"cuda:{local_rank}",
            dtype=torch.float64,
        )
        torch.distributed.all_reduce(elapsed_ms, op=torch.distributed.ReduceOp.MAX)
        torch.distributed.all_reduce(peak_allocated, op=torch.distributed.ReduceOp.MAX)
        reduced_loss = loss.float()
        torch.distributed.all_reduce(reduced_loss)
        reduced_loss /= world_size
        tracked_after = next(model.parameters()).detach().cpu()
        update_squared = float((tracked_after - tracked_before).float().square().sum())
        update_evidence = torch.tensor(
            [update_squared, float(math.isfinite(update_squared))],
            device=local_rank,
            dtype=torch.float64,
        )
        torch.distributed.all_reduce(update_evidence)
        parameter_updated = bool(
            update_evidence[1] == world_size and update_evidence[0] > 0
        )
        if not parameter_updated:
            raise SystemExit(
                "The tracked distributed parameter did not receive a finite update."
            )
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="15_ddp_train",
                environment=environment,
                measurements={
                    "model_shape": {
                        "hidden": hidden,
                        "layers": layers,
                        "sequence": sequence,
                        "batch": batch,
                        "vocab_size": vocab_size,
                    },
                    "precision": "bf16-forward-fp32-parameters",
                    "world_size": world_size,
                    "global_tokens": world_size * batch * sequence * args.iterations,
                    "slowest_rank_elapsed_ms": round(float(elapsed_ms), 4),
                    "final_mean_loss": round(float(reduced_loss), 5),
                    "max_rank_peak_allocated_mib": round(
                        float(peak_allocated) / 2**20, 2
                    ),
                },
                correctness={
                    "finite_mean_loss": bool(torch.isfinite(reduced_loss)),
                    "parameter_updated": parameter_updated,
                },
            )
            print(f"Completed two-node DDP training: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/15_ddp_train.sbatch --workload small

# Optional profiling
sbatch slurm/15_ddp_train.sbatch --workload small --profiler all

Lab 16: Observe FSDP2 sharded training state

Fully Sharded Data Parallel reduces persistent state per rank by distributing parameters, gradients, and optimizer state, but computation still needs appropriately materialized parameters. This lab applies FSDP2 to the tiny transformer on two H100 nodes.

Complete source: labs/16_fsdp2_train.py
"""Shard tiny-transformer parameters, gradients, and optimizer state with FSDP2."""

from __future__ import annotations

import argparse
import math

from course_evidence import annotated_operation
from tiny_lm import build_tiny_lm, make_language_batch
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--zero-grad-fill",
        action="store_true",
        help="Zero existing gradient buffers instead of releasing them; keep all work fixed.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, local_rank = init_nccl(torch)
    try:
        try:
            from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
        except ImportError as exc:
            raise SystemExit(
                "This lab requires the FSDP2 fully_shard API in the pinned PyTorch release."
            ) from exc
        # Keep random inputs repeatable across comparable runs.
        seed_everything(torch, args.seed)
        hidden, layers, sequence, batch = (
            (512, 6, 256, 8) if args.workload == "small" else (2_048, 16, 1_024, 4)
        )
        vocab_size = 4_096
        model = build_tiny_lm(
            torch,
            vocab_size=vocab_size,
            hidden_size=hidden,
            layers=layers,
            heads=8 if hidden == 512 else 16,
            max_sequence=sequence,
        ).to(local_rank)
        policy = MixedPrecisionPolicy(
            param_dtype=torch.bfloat16,
            reduce_dtype=torch.float32,
            output_dtype=torch.bfloat16,
        )
        for block in model.blocks:
            fully_shard(block, mp_policy=policy)
        fully_shard(model, mp_policy=policy)
        optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
        forward = annotated_operation(model, "forward")
        # Differentiate the loss to populate parameter gradients.
        backward = annotated_operation(lambda loss: loss.backward(), "backward")
        update = annotated_operation(optimizer.step, "optimizer")
        clear_gradients = annotated_operation(optimizer.zero_grad, "zero_grad")
        inputs, labels = make_language_batch(
            torch,
            batch_size=batch,
            sequence=sequence,
            vocab_size=vocab_size,
            device=f"cuda:{local_rank}",
            offset=rank * batch,
        )

        def train_step() -> object:
            logits = forward(inputs)
            step_loss = torch.nn.functional.cross_entropy(
                logits.float().reshape(-1, vocab_size), labels.reshape(-1)
            )
            backward(step_loss)
            update()
            clear_gradients(set_to_none=not args.zero_grad_fill)
            return step_loss.detach()

        for _ in range(args.warmup):
            train_step()
        tracked_before = next(model.parameters()).to_local().detach().cpu().clone()
        torch.distributed.barrier()
        torch.cuda.reset_peak_memory_stats()
        started = torch.cuda.Event(enable_timing=True)
        ended = torch.cuda.Event(enable_timing=True)
        started.record()
        loss = None
        for _ in range(args.iterations):
            loss = train_step()
        ended.record()
        ended.synchronize()
        assert loss is not None
        # Create explicit input values on the selected device.
        elapsed_ms = torch.tensor(
            float(started.elapsed_time(ended)), device=f"cuda:{local_rank}"
        )
        peak_allocated = torch.tensor(
            torch.cuda.max_memory_allocated(),
            device=f"cuda:{local_rank}",
            dtype=torch.float64,
        )
        torch.distributed.all_reduce(elapsed_ms, op=torch.distributed.ReduceOp.MAX)
        torch.distributed.all_reduce(peak_allocated, op=torch.distributed.ReduceOp.MAX)
        reduced_loss = loss
        torch.distributed.all_reduce(reduced_loss)
        reduced_loss /= world_size
        tracked_after = next(model.parameters()).to_local().detach().cpu()
        update_squared = float((tracked_after - tracked_before).float().square().sum())
        update_evidence = torch.tensor(
            [update_squared, float(math.isfinite(update_squared))],
            device=local_rank,
            dtype=torch.float64,
        )
        torch.distributed.all_reduce(update_evidence)
        parameter_updated = bool(
            update_evidence[1] == world_size and update_evidence[0] > 0
        )
        if not parameter_updated:
            raise SystemExit(
                "The tracked distributed parameter did not receive a finite update."
            )
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="16_fsdp2_train",
                environment=environment,
                measurements={
                    "model_shape": {
                        "hidden": hidden,
                        "layers": layers,
                        "sequence": sequence,
                        "batch": batch,
                        "vocab_size": vocab_size,
                    },
                    "precision": "bf16-forward-fp32-parameters",
                    "world_size": world_size,
                    "slowest_rank_elapsed_ms": round(float(elapsed_ms), 4),
                    "final_mean_loss": round(float(reduced_loss), 5),
                    "max_rank_peak_allocated_mib": round(
                        float(peak_allocated) / 2**20, 2
                    ),
                },
                correctness={
                    "finite_mean_loss": bool(torch.isfinite(reduced_loss)),
                    "parameter_updated": parameter_updated,
                },
            )
            print(f"Completed two-node FSDP2 training: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/16_fsdp2_train.sbatch --workload small

# Optional profiling
sbatch slurm/16_fsdp2_train.sbatch --workload small --profiler all

Lab 17: Trace expert routing, gradients, and grouped work

Mixture-of-experts training distributes tokens to selected expert computations, then must return outputs and gradients to the correct owners. This lab implements a bounded two-rank example with explicit routing and reference checks.

Complete source: labs/17_training_expert_parallel.py
"""Measure expert-parallel routing, gradients, updates, and load balance."""

from __future__ import annotations

import argparse
import statistics
import time

from course_evidence import annotated_operation
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    rank, world_size, _ = init_nccl(torch)
    try:
        if world_size != 2:
            raise SystemExit("This bounded mechanics lab requires exactly two ranks.")
        hidden = 1_024 if args.workload == "small" else 8_192
        tokens_per_rank = 32 if args.workload == "small" else 512
        learning_rate = 1e-3
        send_counts = [3 * tokens_per_rank // 4, tokens_per_rank // 4]
        receive_counts = [send_counts[rank]] * world_size
        routed = torch.empty(
            (tokens_per_rank, hidden), device="cuda", dtype=torch.bfloat16
        )
        cursor = 0
        for destination, count in enumerate(send_counts):
            routed[cursor : cursor + count].fill_(rank * 10 + destination + 1)
            cursor += count
        received = torch.empty(
            (sum(receive_counts), hidden), device="cuda", dtype=torch.bfloat16
        )
        returned_output = torch.empty(
            (tokens_per_rank, hidden), device="cuda", dtype=torch.float32
        )
        returned_gradient = torch.empty_like(routed)
        # Create explicit input values on the selected device.
        expert_weight = torch.tensor(
            float(rank + 1), device="cuda", dtype=torch.float32, requires_grad=True
        )
        local_experts = 2
        expert_width = 256 if args.workload == "small" else 1_024
        # Create the synthetic tensors used by this experiment.
        grouped_weights = torch.randn(
            (local_experts, hidden, expert_width),
            device="cuda",
            dtype=torch.bfloat16,
        )

        def loop_experts() -> object:
            output = torch.empty(
                (received.shape[0], expert_width),
                device="cuda",
                dtype=torch.bfloat16,
            )
            for expert in range(local_experts):
                indices = torch.arange(
                    expert,
                    received.shape[0],
                    local_experts,
                    device="cuda",
                )
                output[indices] = received[indices] @ grouped_weights[expert]
            return output

        def grouped_experts() -> object:
            expert_indices = [
                torch.arange(
                    expert,
                    received.shape[0],
                    local_experts,
                    device="cuda",
                )
                for expert in range(local_experts)
            ]
            maximum_tokens = max(int(indices.numel()) for indices in expert_indices)
            padded = torch.zeros(
                (local_experts, maximum_tokens, hidden),
                device="cuda",
                dtype=torch.bfloat16,
            )
            for expert, indices in enumerate(expert_indices):
                padded[expert, : indices.numel()] = received[indices]
            grouped = torch.bmm(padded, grouped_weights)
            output = torch.empty(
                (received.shape[0], expert_width),
                device="cuda",
                dtype=torch.bfloat16,
            )
            for expert, indices in enumerate(expert_indices):
                output[indices] = grouped[expert, : indices.numel()]
            return output

        def measure_experts(operation: object) -> list[float]:
            for _ in range(args.warmup):
                operation()
            # Wait for queued GPU work to finish at this measurement boundary.
            torch.cuda.synchronize()
            samples = []
            for _ in range(args.iterations):
                started = torch.cuda.Event(enable_timing=True)
                finished = torch.cuda.Event(enable_timing=True)
                started.record()
                operation()
                finished.record()
                finished.synchronize()
                samples.append(float(started.elapsed_time(finished)))
            return samples

        def train_step(*, update: bool) -> tuple[float, float, float]:
            expert_weight.grad = None
            torch.distributed.barrier()
            step_started = time.perf_counter()
            forward_started = torch.cuda.Event(enable_timing=True)
            forward_finished = torch.cuda.Event(enable_timing=True)
            forward_started.record()
            torch.distributed.all_to_all_single(
                received,
                routed,
                output_split_sizes=receive_counts,
                input_split_sizes=send_counts,
            )
            forward_finished.record()
            expert_output = received.float() * expert_weight
            loss = expert_output.sum() / received.numel()
            # Differentiate the loss to populate parameter gradients.
            loss.backward()
            returned_output_local = expert_output.detach()
            backward_started = torch.cuda.Event(enable_timing=True)
            backward_finished = torch.cuda.Event(enable_timing=True)
            backward_started.record()
            torch.distributed.all_to_all_single(
                returned_output,
                returned_output_local,
                output_split_sizes=send_counts,
                input_split_sizes=receive_counts,
            )
            received_gradient = torch.ones_like(received)
            received_gradient.mul_(
                expert_weight.detach().to(torch.bfloat16) / received.numel()
            )
            torch.distributed.all_to_all_single(
                returned_gradient,
                received_gradient,
                output_split_sizes=send_counts,
                input_split_sizes=receive_counts,
            )
            backward_finished.record()
            if update:
                with torch.no_grad():
                    expert_weight.add_(expert_weight.grad, alpha=-learning_rate)
            backward_finished.synchronize()
            torch.cuda.synchronize()
            elapsed = torch.tensor(
                (time.perf_counter() - step_started) * 1_000,
                device="cuda",
                dtype=torch.float64,
            )
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
            return (
                float(elapsed.item()),
                float(forward_started.elapsed_time(forward_finished)),
                float(backward_started.elapsed_time(backward_finished)),
            )

        initial_weight = float(expert_weight.detach().item())
        train_step(update=True)
        loop_output = loop_experts()
        grouped_output = grouped_experts()
        grouped_matches_loop = bool(
            torch.allclose(loop_output, grouped_output, rtol=1e-2, atol=1e-2)
        )
        loop_expert_samples = measure_experts(loop_experts)
        grouped_expert_samples = measure_experts(grouped_experts)
        expected_output = routed.float().clone()
        expected_token_gradient = torch.empty_like(routed)
        cursor = 0
        for destination, count in enumerate(send_counts):
            expected_output[cursor : cursor + count].mul_(destination + 1)
            destination_received_elements = world_size * count * hidden
            expected_token_gradient[cursor : cursor + count].fill_(
                (destination + 1) / destination_received_elements
            )
            cursor += count
        expected_weight_gradient = float(received.float().mean().item())
        expected_updated_weight = (
            initial_weight - learning_rate * expected_weight_gradient
        )
        forward_ok = bool(torch.equal(returned_output, expected_output))
        token_gradient_ok = bool(
            torch.equal(returned_gradient, expected_token_gradient)
        )
        weight_gradient_ok = (
            abs(float(expert_weight.grad.item()) - expected_weight_gradient) < 1e-5
        )
        update_ok = (
            abs(float(expert_weight.detach().item()) - expected_updated_weight) < 1e-5
        )
        local_ok = torch.tensor(
            int(
                forward_ok
                and token_gradient_ok
                and weight_gradient_ok
                and update_ok
                and grouped_matches_loop
            ),
            device="cuda",
            dtype=torch.int32,
        )
        torch.distributed.all_reduce(local_ok, op=torch.distributed.ReduceOp.MIN)
        if not bool(local_ok.item()):
            raise SystemExit(
                "Expert-parallel forward, gradient, update, or grouped work diverged."
            )

        for _ in range(args.warmup):
            train_step(update=True)
        step_samples: list[float] = []
        forward_communication: list[float] = []
        backward_communication: list[float] = []
        for _ in range(args.iterations):
            step_ms, forward_ms, backward_ms = train_step(update=True)
            step_samples.append(step_ms)
            forward_communication.append(forward_ms)
            backward_communication.append(backward_ms)

        global_load = [count * world_size for count in send_counts]
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="17_training_expert_parallel",
                environment={**environment, "rank_count": world_size},
                measurements={
                    "hidden_size": hidden,
                    "tokens_sent_to_experts_per_rank": send_counts,
                    "global_expert_token_load": global_load,
                    "expert_load_max_to_mean": round(
                        max(global_load) / statistics.mean(global_load), 4
                    ),
                    "local_experts_per_rank": local_experts,
                    "local_expert_token_counts": [
                        (received.shape[0] + local_experts - expert - 1)
                        // local_experts
                        for expert in range(local_experts)
                    ],
                    "expert_output_width": expert_width,
                    "loop_expert_gemm_median_ms": round(
                        statistics.median(loop_expert_samples), 4
                    ),
                    "padded_grouped_bmm_median_ms": round(
                        statistics.median(grouped_expert_samples), 4
                    ),
                    "grouped_operation_scope": (
                        "end-to-end padding, one batched GEMM, and scatter; compare "
                        "with specialized ragged grouped kernels before production use"
                    ),
                    "training_step_slowest_rank_median_ms": round(
                        statistics.median(step_samples), 4
                    ),
                    "forward_all_to_all_median_ms": round(
                        statistics.median(forward_communication), 4
                    ),
                    "output_and_gradient_return_median_ms": round(
                        statistics.median(backward_communication), 4
                    ),
                    "expert_weight_gradient": round(expected_weight_gradient, 6),
                    "learning_rate": learning_rate,
                    "training_evidence": [
                        "expert token load and imbalance",
                        "forward and backward communication",
                        "expert gradient and optimizer update",
                        "slowest-rank training step time",
                        "loop versus grouped local expert GEMM",
                    ],
                },
                correctness={
                    "routed_outputs_match_reference": True,
                    "returned_token_gradients_match_reference": True,
                    "expert_weight_gradient_matches_reference": True,
                    "optimizer_update_matches_reference": True,
                    "grouped_expert_output_matches_loop": grouped_matches_loop,
                },
            )
            print(f"Completed expert-parallel training experiment: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/17_training_expert_parallel.sbatch --workload small

# Optional profiling
sbatch slurm/17_training_expert_parallel.sbatch --workload small --profiler all

Lab 18: Partition a linear layer and verify its backward pass

Tensor parallelism partitions the computation inside a layer rather than assigning independent examples to complete model replicas. This lab splits a linear operation across two H100 ranks and checks its forward output, gradients, and update against a replicated reference.

Complete source: labs/18_training_tensor_parallel.py
"""Measure tensor-parallel forward, gradient, update, and communication mechanics."""

from __future__ import annotations

import argparse
import math
import statistics
import time

from course_evidence import annotated_operation
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def relative_l2(torch: object, observed: object, expected: object) -> float:
    # Return a failing value so every rank can reach the collective verdict.
    if not bool(torch.isfinite(observed).all() and torch.isfinite(expected).all()):
        return math.inf
    numerator = torch.linalg.vector_norm(observed.float() - expected.float())
    denominator = torch.linalg.vector_norm(expected.float()).clamp_min(1e-12)
    if not bool(torch.isfinite(numerator) and torch.isfinite(denominator)):
        return math.inf
    error = float((numerator / denominator).item())
    return error if math.isfinite(error) else math.inf


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    rank, world_size, local_rank = init_nccl(torch)
    try:
        device = f"cuda:{local_rank}"
        width = 2_048 if args.workload == "small" else 8_192
        batch = 32 if args.workload == "small" else 128
        learning_rate = 1e-2
        if width % world_size:
            raise SystemExit("The hidden width must be divisible by the rank count.")
        # Create the synthetic tensors used by this experiment.
        input_seed = torch.randn((batch, width), device=device, dtype=torch.bfloat16)
        weight_seed = torch.randn((width, width), device=device, dtype=torch.float32)

        reference_input = input_seed.detach().clone().requires_grad_(True)
        reference_weight = weight_seed.detach().clone().requires_grad_(True)
        reference_output = reference_input @ reference_weight.to(torch.bfloat16).T
        reference_loss = reference_output.float().square().mean()
        # Differentiate the loss to populate parameter gradients.
        reference_loss.backward()
        with torch.no_grad():
            reference_updated = reference_weight - learning_rate * reference_weight.grad

        shard_input = input_seed.detach().clone().requires_grad_(True)
        shard_weight = (
            weight_seed.chunk(world_size, dim=0)[rank]
            .contiguous()
            .detach()
            .requires_grad_(True)
        )
        local_output = shard_input @ shard_weight.to(torch.bfloat16).T
        local_loss = local_output.float().square().sum() / reference_output.numel()
        local_loss.backward()
        torch.distributed.all_reduce(shard_input.grad)
        gathered_output = [torch.empty_like(local_output) for _ in range(world_size)]
        torch.distributed.all_gather(gathered_output, local_output.detach())
        with torch.no_grad():
            shard_updated = shard_weight - learning_rate * shard_weight.grad
        gathered_updated = [torch.empty_like(shard_updated) for _ in range(world_size)]
        torch.distributed.all_gather(gathered_updated, shard_updated)
        forward_error = relative_l2(
            torch, torch.cat(gathered_output, dim=-1), reference_output
        )
        weight_gradient_error = relative_l2(
            torch,
            shard_weight.grad,
            reference_weight.grad.chunk(world_size, dim=0)[rank],
        )
        input_gradient_error = relative_l2(
            torch, shard_input.grad, reference_input.grad
        )
        update_error = relative_l2(
            torch, torch.cat(gathered_updated, dim=0), reference_updated
        )

        row_weight = (
            weight_seed.chunk(world_size, dim=1)[rank].contiguous().to(torch.bfloat16)
        )
        row_input = input_seed.chunk(world_size, dim=1)[rank].contiguous()
        row_output = row_input @ row_weight.T
        torch.distributed.all_reduce(row_output)
        row_forward_error = relative_l2(torch, row_output, reference_output)
        maximum_error = max(
            forward_error,
            weight_gradient_error,
            input_gradient_error,
            update_error,
            row_forward_error,
        )
        # Create explicit input values on the selected device.
        local_ok = torch.tensor(
            int(maximum_error < 0.02), device=device, dtype=torch.int32
        )
        torch.distributed.all_reduce(local_ok, op=torch.distributed.ReduceOp.MIN)
        if not bool(local_ok.item()):
            raise SystemExit(f"Tensor-parallel equivalence failed: {maximum_error=}")

        timed_input = input_seed.detach().clone().requires_grad_(True)
        timed_weight = (
            weight_seed.chunk(world_size, dim=0)[rank]
            .contiguous()
            .detach()
            .requires_grad_(True)
        )

        def train_step() -> tuple[float, float]:
            timed_input.grad = None
            timed_weight.grad = None
            torch.distributed.barrier()
            started = time.perf_counter()
            output = timed_input @ timed_weight.to(torch.bfloat16).T
            loss = output.float().square().sum() / (batch * width)
            loss.backward()
            communication_started = torch.cuda.Event(enable_timing=True)
            communication_finished = torch.cuda.Event(enable_timing=True)
            communication_started.record()
            torch.distributed.all_reduce(timed_input.grad)
            communication_finished.record()
            with torch.no_grad():
                timed_weight.add_(timed_weight.grad, alpha=-learning_rate)
            communication_finished.synchronize()
            # Wait for queued GPU work to finish at this measurement boundary.
            torch.cuda.synchronize()
            elapsed = torch.tensor(
                (time.perf_counter() - started) * 1_000,
                device=device,
                dtype=torch.float64,
            )
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
            return float(elapsed.item()), float(
                communication_started.elapsed_time(communication_finished)
            )

        for _ in range(args.warmup):
            train_step()
        step_samples: list[float] = []
        communication_samples: list[float] = []
        for _ in range(args.iterations):
            step_ms, communication_ms = train_step()
            step_samples.append(step_ms)
            communication_samples.append(communication_ms)

        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="18_training_tensor_parallel",
                environment={**environment, "rank_count": world_size},
                measurements={
                    "batch": batch,
                    "width": width,
                    "learning_rate": learning_rate,
                    "replicated_parameter_bytes": weight_seed.numel()
                    * weight_seed.element_size(),
                    "parameter_shard_bytes_per_rank": shard_weight.numel()
                    * shard_weight.element_size(),
                    "input_gradient_all_reduce_bytes": timed_input.numel()
                    * timed_input.element_size(),
                    "training_step_slowest_rank_median_ms": round(
                        statistics.median(step_samples), 4
                    ),
                    "input_gradient_all_reduce_median_ms": round(
                        statistics.median(communication_samples), 4
                    ),
                    "forward_relative_l2": round(forward_error, 8),
                    "weight_gradient_relative_l2": round(weight_gradient_error, 8),
                    "input_gradient_relative_l2": round(input_gradient_error, 8),
                    "parameter_update_relative_l2": round(update_error, 8),
                    "row_parallel_forward_relative_l2": round(row_forward_error, 8),
                },
                correctness={
                    "column_forward_matches_reference": True,
                    "weight_gradient_matches_reference": True,
                    "input_gradient_matches_reference": True,
                    "optimizer_update_matches_reference": True,
                    "row_forward_matches_reference": True,
                },
            )
            print(f"Completed tensor-parallel training experiment: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/18_training_tensor_parallel.sbatch --workload small

# Optional profiling
sbatch slurm/18_training_tensor_parallel.sbatch --workload small --profiler all

Lab 19: Reduce gradients when they become ready

Backward produces parameter gradients at different times, creating opportunities to communicate an earlier gradient while later computation continues. This lab compares serialized reduction with gradient-ready asynchronous reductions across two H100 nodes. Compute captures the local backward companion; Systems captures distributed overlap.

Complete source: labs/19_gradient_overlap.py
"""Compare serialized and gradient-ready bucket all-reduce schedules."""

from __future__ import annotations

import argparse
import math
import statistics
import time
from typing import Any

from course_evidence import annotated_operation
from gradient_overlap_common import (
    bucket_loss,
    bucket_sizes,
    gradient_checks,
    make_bucket_seeds,
    require_gradient_consensus,
)
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--bucket-mib",
        type=int,
        nargs="+",
        default=None,
        help="Two or more BF16 gradient bucket sizes in MiB.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    bucket_mib = bucket_sizes(args.workload, args.bucket_mib)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    rank, world_size, local_rank = init_nccl(torch)
    try:
        device = f"cuda:{local_rank}"

        def run_once(
            seeds: list[tuple[Any, Any]], *, overlap: bool
        ) -> tuple[float, float | None, list[int], list[Any]]:
            parameters = [
                parameter.detach().clone().requires_grad_(True)
                for parameter, _input in seeds
            ]
            pending: list[Any] = []
            ready_order: list[int] = []
            handles = []
            step_started = time.perf_counter()

            def make_hook(index: int):
                def hook(parameter: Any) -> None:
                    ready_order.append(index)
                    if overlap:
                        pending.append(
                            torch.distributed.all_reduce(parameter.grad, async_op=True)
                        )

                return hook

            for index, parameter in enumerate(parameters):
                handles.append(
                    parameter.register_post_accumulate_grad_hook(make_hook(index))
                )
            loss = bucket_loss(parameters, seeds)
            # Differentiate the loss to populate parameter gradients.
            loss.backward()
            if overlap:
                for work in pending:
                    work.wait()
                isolated_collective_device_ms = None
            else:
                collective_started = torch.cuda.Event(enable_timing=True)
                collective_finished = torch.cuda.Event(enable_timing=True)
                collective_started.record()
                for parameter in parameters:
                    torch.distributed.all_reduce(parameter.grad)
                collective_finished.record()
                collective_finished.synchronize()
                isolated_collective_device_ms = float(
                    collective_started.elapsed_time(collective_finished)
                )
            for parameter in parameters:
                parameter.grad.div_(world_size)
            for handle in handles:
                handle.remove()
            # Wait for queued GPU work to finish at this measurement boundary.
            torch.cuda.synchronize()
            # Create explicit input values on the selected device.
            elapsed = torch.tensor(
                (time.perf_counter() - step_started) * 1_000,
                device=device,
                dtype=torch.float64,
            )
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
            return (
                float(elapsed.item()),
                isolated_collective_device_ms,
                ready_order,
                [parameter.grad.detach().clone() for parameter in parameters],
            )

        schedule_results: dict[str, Any] = {}
        all_gradients_match = True
        all_finite = True
        schedules = {
            "ascending": sorted(bucket_mib),
            "descending": sorted(bucket_mib, reverse=True),
        }
        for schedule_name, schedule in schedules.items():
            seeds = make_bucket_seeds(torch, schedule, device=device)
            serialized_reference = run_once(seeds, overlap=False)
            overlapped_reference = run_once(seeds, overlap=True)
            checks = gradient_checks(
                torch, serialized_reference[3], overlapped_reference[3]
            )
            require_gradient_consensus(torch, checks, device=device)
            gradients_match = checks["passed"]
            finite = checks["all_finite"]
            all_gradients_match = all_gradients_match and gradients_match
            all_finite = all_finite and finite
            for _ in range(args.warmup):
                run_once(seeds, overlap=False)
                run_once(seeds, overlap=True)
            serialized_steps: list[float] = []
            serialized_collective_device: list[float] = []
            overlapped_steps: list[float] = []
            observed_ready_order: list[int] = []
            for _ in range(args.iterations):
                serialized = run_once(seeds, overlap=False)
                overlapped = run_once(seeds, overlap=True)
                serialized_steps.append(serialized[0])
                if serialized[1] is None:
                    raise SystemExit("Serialized collective timing was not recorded.")
                serialized_collective_device.append(serialized[1])
                overlapped_steps.append(overlapped[0])
                observed_ready_order = overlapped[2]
            serialized_median = statistics.median(serialized_steps)
            overlapped_median = statistics.median(overlapped_steps)
            schedule_results[schedule_name] = {
                "bucket_mib_in_forward_construction_order": schedule,
                "observed_gradient_ready_bucket_indices": observed_ready_order,
                "serialized_step_median_ms": round(serialized_median, 4),
                "serialized_collective_cuda_event_median_ms": round(
                    statistics.median(serialized_collective_device), 4
                ),
                "overlapped_step_median_ms": round(overlapped_median, 4),
                "serialized_to_overlap_ratio": round(
                    serialized_median / overlapped_median, 4
                ),
                "overlap_timeline_claim": (
                    "pending Nsight Systems confirmation; the step ratio alone "
                    "does not prove exposed communication"
                ),
                "gradients_match": gradients_match,
                "gradient_validation": checks,
            }
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="19_gradient_overlap",
                environment={**environment, "rank_count": world_size},
                measurements={
                    "schedules": schedule_results,
                    "timing_scope": "slowest rank; forward, backward, all-reduce, and wait",
                    "interpretation_boundary": (
                        "a ratio is an observation, not a published speedup, until "
                        "independent H100 runs and profiler ranges confirm overlap"
                    ),
                },
                correctness={
                    "serialized_and_overlapped_gradients_match": all_gradients_match,
                    "all_gradients_finite": all_finite,
                    "all_ratios_finite": all(
                        math.isfinite(result["serialized_to_overlap_ratio"])
                        for result in schedule_results.values()
                    ),
                },
            )
            print(f"Completed gradient-bucket overlap experiment: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/19_gradient_overlap.sbatch --workload small

# Optional profiling
sbatch slurm/19_gradient_overlap.sbatch --workload small --profiler all

Lab 20: Follow pipeline and context partitions through backward

Pipeline parallelism divides layers, while context parallelism divides sequence positions. This lab demonstrates their ownership and gradient mechanics on two ranks with deliberately small computations.

Complete source: labs/20_parallelism_mechanics.py
"""Demonstrate two-rank pipeline- and context-parallel training mechanics."""

from __future__ import annotations

import argparse

from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    validate_common_args,
    write_result,
)


def require_close(
    torch: object, observed: object, expected: object, label: str
) -> None:
    if not torch.allclose(observed, expected, rtol=1e-5, atol=1e-6):
        error = float((observed - expected).abs().max())
        raise SystemExit(f"{label} failed FP32 comparison: max error {error}")


def pipeline_mechanics(torch: object, rank: int, width: int) -> dict[str, object]:
    """Run one forward activation send and backward gradient return."""
    batch = 4
    inputs = (
        torch.arange(batch * width, device="cuda", dtype=torch.float32)
        .reshape(batch, width)
        .div_(batch * width)
        .requires_grad_(True)
    )
    weight0 = torch.eye(width, device="cuda") * 0.75 + 0.01
    weight1 = torch.eye(width, device="cuda") * 0.50 - 0.005
    activation_shape = (batch, width)
    loss_value = torch.zeros(1, device="cuda")
    reference_inputs = inputs.detach().clone().requires_grad_(True)
    reference_weight0 = weight0.clone().requires_grad_(True)
    reference_weight1 = weight1.clone().requires_grad_(True)
    reference_activation = reference_inputs @ reference_weight0
    reference_activation.retain_grad()
    reference_loss = (reference_activation @ reference_weight1).square().mean()
    # Differentiate the loss to populate parameter gradients.
    reference_loss.backward()

    if rank == 0:
        local_weight = weight0.clone().requires_grad_(True)
        activation = inputs @ local_weight
        torch.distributed.send(activation.detach(), dst=1)
        activation_gradient = torch.empty_like(activation)
        torch.distributed.recv(activation_gradient, src=1)
        activation.backward(activation_gradient)
        require_close(
            torch,
            activation_gradient,
            reference_activation.grad,
            "stage 0 activation gradient",
        )
        require_close(
            torch, local_weight.grad, reference_weight0.grad, "stage 0 weight gradient"
        )
        require_close(
            torch, inputs.grad, reference_inputs.grad, "stage 0 input gradient"
        )
    else:
        received = torch.empty(activation_shape, device="cuda")
        torch.distributed.recv(received, src=0)
        received.requires_grad_(True)
        local_weight = weight1.clone().requires_grad_(True)
        output = received @ local_weight
        loss = output.square().mean()
        loss.backward()
        require_close(
            torch, received.grad, reference_activation.grad, "stage 1 input gradient"
        )
        require_close(
            torch, local_weight.grad, reference_weight1.grad, "stage 1 weight gradient"
        )
        torch.distributed.send(received.grad, dst=0)
        loss_value.copy_(loss.detach())

    torch.distributed.broadcast(loss_value, src=1)
    require_close(torch, loss_value, reference_loss.reshape(1), "pipeline loss")
    # Create explicit input values on the selected device.
    gradient_ok = torch.tensor(1, device="cuda", dtype=torch.int32)
    torch.distributed.all_reduce(gradient_ok, op=torch.distributed.ReduceOp.MIN)
    if int(gradient_ok) != 1:
        raise SystemExit("A pipeline stage produced a non-finite local gradient.")
    activation_bytes = (
        batch * width * torch.tensor([], dtype=torch.float32).element_size()
    )
    return {
        "stages": 2,
        "microbatches": 1,
        "activation_shape": list(activation_shape),
        "activation_send_bytes": activation_bytes,
        "activation_gradient_return_bytes": activation_bytes,
        "loss": float(loss_value),
        "all_stage_weight_input_and_activation_gradients_match_reference": True,
    }


def context_mechanics(
    torch: object, rank: int, world_size: int, width: int
) -> dict[str, object]:
    """Partition sequence positions and reconcile a global training statistic."""
    batch = 2
    sequence = 32
    full_context = (
        torch.arange(batch * sequence * width, device="cuda", dtype=torch.float32)
        .reshape(batch, sequence, width)
        .div_(batch * sequence * width)
    )
    local_context = (
        full_context.chunk(world_size, dim=1)[rank]
        .contiguous()
        .clone()
        .requires_grad_(True)
    )
    local_square_sum = local_context.square().sum()
    global_square_sum = local_square_sum.detach().clone()
    torch.distributed.all_reduce(global_square_sum)
    require_close(
        torch, global_square_sum, full_context.square().sum(), "context reduction"
    )
    gathered = [torch.empty_like(local_context) for _ in range(world_size)]
    torch.distributed.all_gather(gathered, local_context.detach())
    reconstructed = torch.cat(gathered, dim=1)
    if not torch.equal(reconstructed, full_context):
        raise SystemExit("Context shards did not reconstruct the full sequence.")
    (local_square_sum / full_context.numel()).backward()
    reference_context = full_context.detach().clone().requires_grad_(True)
    (reference_context.square().sum() / reference_context.numel()).backward()
    expected_local_gradient = reference_context.grad.chunk(world_size, dim=1)[rank]
    require_close(
        torch,
        local_context.grad,
        expected_local_gradient,
        "context shard gradient",
    )
    return {
        "global_shape": list(full_context.shape),
        "local_shape": list(local_context.shape),
        "sequence_fraction_per_rank": 1 / world_size,
        "global_square_sum": float(global_square_sum),
        "collectives": ["all_reduce statistic", "all_gather context shards"],
        "local_gradient_matches_unpartitioned_autograd_reference": True,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser, include_measurement=False)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    width = 64 if args.workload == "small" else 512
    try:
        pipeline = pipeline_mechanics(torch, rank, width)
        context = context_mechanics(torch, rank, world_size, width)
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="20_parallelism_mechanics",
                environment={**environment, "world_size": world_size},
                measurements={
                    "pipeline_parallel": pipeline,
                    "context_parallel": context,
                    "companion_training_labs": {
                        "tensor_parallel": "18_training_tensor_parallel.py",
                        "expert_parallel": "17_training_expert_parallel.py",
                    },
                    "scope": (
                        "two-rank mechanics only; not production PP/CP scaling, "
                        "topology, or overlap evidence"
                    ),
                },
                correctness={
                    "pipeline_forward_backward_gradients_match_reference": True,
                    "context_partition_and_gradient_match_reference": True,
                    "fp32_rtol": 1e-5,
                    "fp32_atol": 1e-6,
                },
            )
            print(f"Wrote PP/CP training-mechanics evidence: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    from course_evidence import annotated_operation

    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/20_parallelism_mechanics.sbatch --workload small

# Optional profiling
sbatch slurm/20_parallelism_mechanics.sbatch --workload small --profiler all

Lab 21: Tune real DDP buckets and communication hooks

Gradient readiness only creates an opportunity for overlap; DDP must group gradients into buckets and communicate them in a valid order. This lab exposes that behavior and compares FP32 reduction with FP16, BF16 and PowerSGD communication hooks.

Complete source: labs/21_ddp_buckets.py
"""Measure real DDP buckets and communication hooks against full-batch FP32 SGD."""

from __future__ import annotations

import argparse
import copy
import math
import time
from typing import Any

from course_evidence import annotated_operation
from training_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.set_defaults(warmup=4)
    parser.add_argument("--bucket-cap-mb", type=float, default=1.0)
    parser.add_argument(
        "--hook", choices=("allreduce", "fp16", "bf16", "powersgd"), default="allreduce"
    )
    parser.add_argument("--power-rank", type=int, default=1)
    parser.add_argument("--power-start", type=int, default=2)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    if not math.isfinite(args.bucket_cap_mb) or not 0.01 <= args.bucket_cap_mb <= 1024:
        parser.error("--bucket-cap-mb must be finite and 0.01..1024")
    if not 1 <= args.power_rank <= 32 or args.power_start < 2:
        parser.error("--power-rank must be 1..32 and --power-start at least 2")
    if args.warmup < 2 or args.iterations < 2 or args.warmup + args.iterations > 200:
        parser.error("Use at least 2 warmup and 2 measured steps, at most 200 total")
    if args.hook == "powersgd" and args.warmup <= args.power_start:
        parser.error("Warmup must include at least one PowerSGD-compressed step")
    return args


def relative_l2(torch: Any, observed: list[Any], reference: list[Any]) -> float:
    if not observed or len(observed) != len(reference):
        raise ValueError("Missing gradient or parameter reference")
    error = 0.0
    scale = 0.0
    for actual, expected in zip(observed, reference, strict=True):
        if actual is None or expected is None or actual.shape != expected.shape:
            raise ValueError("Missing gradient or mismatched reference shape")
        if not bool(torch.isfinite(actual).all() and torch.isfinite(expected).all()):
            raise ValueError("Nonfinite gradient or parameter reference")
        error += float((actual.double() - expected.double()).square().sum())
        scale += float(expected.double().square().sum())
    result = math.sqrt(error / max(scale, 1e-30))
    if not math.isfinite(result):
        raise ValueError("Nonfinite relative error")
    return result


def verify_update(
    torch: Any, before: list[Any], parameters: list[Any], lr: float
) -> None:
    if any(
        p.grad is None or not bool(torch.isfinite(p.grad).all()) for p in parameters
    ):
        raise ValueError("Missing or nonfinite gradient before SGD")
    expected = [
        b.clone().add_(p.grad, alpha=-lr)
        for b, p in zip(before, parameters, strict=True)
    ]
    if not all(torch.equal(p, e) for p, e in zip(parameters, expected, strict=True)):
        raise ValueError("SGD update differs from its gradient reference")
    if not any(not torch.equal(p, b) for p, b in zip(parameters, before, strict=True)):
        raise ValueError("SGD did not update any parameter")


def checked_sgd(torch: Any, model: Any, optimizer: Any, lr: float) -> None:
    parameters = list(model.parameters())
    before = [p.detach().clone() for p in parameters]
    # Update the parameters using the gradients from this step.
    optimizer.step()
    verify_update(torch, before, parameters, lr)


def make_hook(
    torch: Any, args: argparse.Namespace, bucket_log: list[dict[str, int]]
) -> tuple[Any, Any]:
    from torch.distributed.algorithms.ddp_comm_hooks import default_hooks
    from torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook import (
        PowerSGDState,
        powerSGD_hook,
    )

    state = torch.distributed.group.WORLD
    if args.hook == "powersgd":
        state = PowerSGDState(
            state,
            matrix_approximation_rank=args.power_rank,
            start_powerSGD_iter=args.power_start,
            use_error_feedback=True,
            warm_start=True,
            random_seed=args.seed,
            orthogonalization_epsilon=1e-8,
        )
        selected = powerSGD_hook
    else:
        selected = {
            "allreduce": default_hooks.allreduce_hook,
            "fp16": default_hooks.fp16_compress_hook,
            "bf16": default_hooks.bf16_compress_hook,
        }[args.hook]

    # No annotations: DDP validates hook annotations against concrete Torch types.
    def observed_hook(state, bucket):
        bucket_log.append(
            {
                "index": bucket.index(),
                "uncompressed_bytes": bucket.buffer().numel()
                * bucket.buffer().element_size(),
            }
        )
        with torch.cuda.nvtx.range("ddp_bucket_submit"):
            return selected(state, bucket)

    return state, observed_hook


def main() -> None:
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    rank, world_size, local_rank = init_nccl(torch)
    try:
        environment = require_course_gpu(torch)
        # Keep random inputs repeatable across comparable runs.
        seed_everything(torch, args.seed)
        torch.backends.cuda.matmul.allow_tf32 = False
        torch.set_num_threads(1)
        device = torch.device("cuda", local_rank)
        width = 256 if args.workload == "small" else 1024
        model = torch.nn.Sequential(
            *[
                layer
                for _ in range(4)
                for layer in (torch.nn.Linear(width, width), torch.nn.Tanh())
            ]
        ).to(device)
        reference = copy.deepcopy(model)
        ddp = torch.nn.parallel.DistributedDataParallel(
            model,
            device_ids=[local_rank],
            bucket_cap_mb=args.bucket_cap_mb,
        )
        bucket_log: list[dict[str, int]] = []
        state, hook = make_hook(torch, args, bucket_log)
        ddp.register_comm_hook(state, hook)
        lr = 0.05
        optimizer = torch.optim.SGD(ddp.parameters(), lr=lr, foreach=False)
        reference_optimizer = torch.optim.SGD(
            reference.parameters(), lr=lr, foreach=False
        )
        generator = torch.Generator(device=device).manual_seed(args.seed + 1)
        # Create the synthetic tensors used by this experiment.
        inputs = torch.randn(16 * world_size, width, generator=generator, device=device)
        targets = torch.tanh(inputs * 0.2)
        local_inputs = inputs.chunk(world_size)[rank]
        local_targets = targets.chunk(world_size)[rank]
        loss_fn = torch.nn.MSELoss()
        records = []
        timings = []
        total_steps = args.warmup + args.iterations
        for step in range(total_steps):
            bucket_log.clear()
            candidate_before = [p.detach().clone() for p in model.parameters()]
            torch.distributed.barrier()
            # Wait for queued GPU work to finish at this measurement boundary.
            torch.cuda.synchronize()
            started = time.perf_counter()
            with torch.cuda.nvtx.range(
                "ddp_warmup_step" if step < args.warmup else "ddp_measured_step"
            ):
                # Clear the previous step’s gradients before differentiating again.
                optimizer.zero_grad(set_to_none=True)
                loss = loss_fn(ddp(local_inputs), local_targets)
                # Differentiate the loss to populate parameter gradients.
                loss.backward()
                # Acceptance timing includes SGD but excludes expensive oracle checks.
                optimizer.step()
                torch.cuda.synchronize()
            elapsed = (time.perf_counter() - started) * 1000
            # Create explicit input values on the selected device.
            max_elapsed = torch.tensor(elapsed, device=device, dtype=torch.float64)
            torch.distributed.all_reduce(max_elapsed, op=torch.distributed.ReduceOp.MAX)
            if step >= args.warmup:
                timings.append(float(max_elapsed.item()))

            with torch.cuda.nvtx.range("full_batch_reference"):
                verify_update(torch, candidate_before, list(model.parameters()), lr)
                reference_optimizer.zero_grad(set_to_none=True)
                reference_loss = loss_fn(reference(inputs), targets)
                reference_loss.backward()
                ref_parameters = list(reference.parameters())
                parameters = list(model.parameters())
                gradient_error = relative_l2(
                    torch,
                    [p.grad for p in parameters],
                    [p.grad for p in ref_parameters],
                )
                checked_sgd(torch, reference, reference_optimizer, lr)
                parameter_error = relative_l2(torch, parameters, ref_parameters)
                if args.hook == "allreduce":
                    for p, expected in zip(parameters, ref_parameters, strict=True):
                        # Compare the computed values with the numerical reference.
                        torch.testing.assert_close(
                            p.grad, expected.grad, rtol=1e-5, atol=1e-6
                        )
                        torch.testing.assert_close(p, expected, rtol=1e-5, atol=1e-6)
                average_loss = loss.detach().clone()
                torch.distributed.all_reduce(average_loss)
                average_loss.div_(world_size)
                if not bool(torch.isfinite(average_loss)):
                    raise ValueError("Nonfinite candidate loss")
                records.append(
                    {
                        "step": step,
                        "warmup": step < args.warmup,
                        "candidate_global_loss": float(average_loss.item()),
                        "reference_global_loss": float(reference_loss.item()),
                        "gradient_trajectory_relative_l2": gradient_error,
                        "parameter_trajectory_relative_l2": parameter_error,
                        "observed_buckets": list(bucket_log),
                    }
                )
        if not timings or any(not math.isfinite(t) or t <= 0 for t in timings):
            raise ValueError("Invalid DDP step timing")
        if not all(record["observed_buckets"] for record in records):
            raise ValueError("No observed DDP bucket communication")
        if rank == 0:
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="21_ddp_buckets",
                environment={
                    **environment,
                    "rank_count": world_size,
                    "nccl_version": list(torch.cuda.nccl.version()),
                },
                measurements={
                    "hook": args.hook,
                    "bucket_cap_mb": args.bucket_cap_mb,
                    "power_rank": args.power_rank,
                    "power_start": args.power_start,
                    "step": summarize_ms(timings),
                    "slowest_rank_step_samples_ms": timings,
                    "trajectory": records,
                    "timing_scope": "forward, mean loss, backward/hook and SGD; rank barrier and full-batch oracle excluded",
                    "quality_status": "short synthetic trajectory only; task convergence and compression acceptance pending",
                    "bucket_boundary": "observed uncompressed payload, not wire bytes; cap is not an exact bucket size",
                },
                correctness={
                    "finite_gradients_parameters_and_losses": True,
                    "candidate_and_reference_sgd_checked": True,
                    "fp32_reference_agreement": "passed"
                    if args.hook == "allreduce"
                    else "lossy; errors reported, not equivalence",
                },
            )
            print(f"Completed DDP bucket experiment: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/21_ddp_buckets.sbatch --hook allreduce --bucket-cap-mb 1 --workload small

# Optional profiling
sbatch slurm/21_ddp_buckets.sbatch --hook allreduce --bucket-cap-mb 1 --workload small --profiler all

Lab 22: Tune microbatching at fixed global batch

Data parallelism replicates the model and partitions examples. In this experiment you will measure a baseline, inspect the evidence, and change one control while keeping useful work fixed.

Complete source: labs/22_fabric_training.py
"""Keep global batch fixed while changing microbatching across eight/sixteen DDP ranks."""

import argparse
import copy
from contextlib import nullcontext

from course_evidence import evidence_phase
from fabric_common import all_correct, initialize, measure
from training_common import (
    add_common_args,
    close_distributed,
    sgd_updates_match,
    validate_common_args,
    write_result,
)


def batch_geometry(global_batch, world, microbatch):
    if global_batch % world or (global_batch // world) % microbatch:
        raise ValueError(
            "Global batch must divide exactly across ranks and microbatches"
        )
    return global_batch // world, global_batch // world // microbatch


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--microbatch", type=int, choices=(1, 2, 4, 8), default=1)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch, rank, world, local, env = initialize(args.seed)
    try:
        global_batch, width = (128, 512) if args.workload == "small" else (512, 2048)
        local_batch, accumulation = batch_geometry(global_batch, world, args.microbatch)
        # Identical global examples and model on every rank establish a full-batch reference.
        x = torch.randn(global_batch, width, device="cuda")
        # Create the synthetic tensors used by this experiment.
        target = torch.randn(global_batch, width, device="cuda")
        model = torch.nn.Sequential(
            torch.nn.Linear(width, width),
            torch.nn.GELU(),
            torch.nn.Linear(width, width),
        ).cuda()
        initial = {
            key: value.detach().clone() for key, value in model.state_dict().items()
        }
        reference_model = copy.deepcopy(model)
        before = tuple(p.detach().clone() for p in model.parameters())
        reference_loss = torch.nn.functional.mse_loss(reference_model(x), target)
        # Differentiate the loss to populate parameter gradients.
        reference_loss.backward()
        torch.optim.SGD(
            reference_model.parameters(), lr=0.01, foreach=False, fused=False
        ).step()
        model.zero_grad(set_to_none=True)
        ddp = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local])
        optimizer = torch.optim.SGD(
            ddp.parameters(), lr=0.01, foreach=False, fused=False
        )
        start = rank * local_batch
        local_x, local_y = (
            x[start : start + local_batch],
            target[start : start + local_batch],
        )
        loss_sum = torch.zeros((), device="cuda")

        def operation():
            # Controlled replay includes the same reset cost in both variants.
            model.load_state_dict(initial)
            # Clear the previous step’s gradients before differentiating again.
            optimizer.zero_grad(set_to_none=True)
            loss_sum.zero_()
            for index in range(accumulation):
                sync = nullcontext() if index == accumulation - 1 else ddp.no_sync()
                with sync:
                    offset = index * args.microbatch
                    with evidence_phase("forward"):
                        loss = (
                            torch.nn.functional.mse_loss(
                                ddp(local_x[offset : offset + args.microbatch]),
                                local_y[offset : offset + args.microbatch],
                            )
                            / accumulation
                        )
                    loss_sum.add_(loss.detach())
                    with evidence_phase("backward"):
                        loss.backward()
            with evidence_phase("optimizer"):
                # Update the parameters using the gradients from this step.
                optimizer.step()

        torch.cuda.reset_peak_memory_stats()
        times = measure(torch, operation, args.warmup, args.iterations)
        all_correct(
            torch,
            sgd_updates_match(
                torch,
                before,
                tuple(reference_model.parameters()),
                tuple(model.parameters()),
                learning_rate=0.01,
            ),
            "DDP update differs from the fixed global-batch reference",
        )
        loss = loss_sum.clone()
        torch.distributed.all_reduce(loss)
        loss /= world
        # Create explicit input values on the selected device.
        peak = torch.tensor(
            torch.cuda.max_memory_allocated(), device="cuda", dtype=torch.int64
        )
        torch.distributed.all_reduce(peak, op=torch.distributed.ReduceOp.MAX)
        if rank == 0:
            print(
                write_result(
                    args,
                    lab_id="22_fabric_training",
                    environment=env,
                    measurements={
                        "global_batch": global_batch,
                        "width": width,
                        "accumulation": accumulation,
                        "ranks": world,
                        "step": times,
                        "samples_per_second": global_batch / times["median_ms"] * 1000,
                        "peak_allocated_bytes": peak.item(),
                        "loss": loss.item(),
                    },
                    correctness={
                        "update_matches_global_reference": True,
                        "loss_matches_global_reference": bool(
                            torch.allclose(
                                loss, reference_loss.detach(), rtol=1e-4, atol=1e-5
                            )
                        ),
                    },
                )
            )
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/22_fabric_training.sbatch --workload small --microbatch 1

# Optional profiling
sbatch slurm/22_fabric_training.sbatch --workload small --microbatch 1 --profiler all

Lab 23: Route inference tokens to expert owners

Expert-parallel inference sends tokens to the ranks that own their selected experts and returns outputs to the original order. This lab implements that round trip on two H100 nodes and reports expert load balance.

Complete source: labs/23_inference_expert_parallel.py
"""Measure inference expert routing, token-load balance, and latency mechanics."""

from __future__ import annotations

import argparse
import statistics

from course_evidence import annotated_operation
from inference_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    summarize_ms,
    validate_common_args,
    write_result,
)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, _ = init_nccl(torch)
    try:
        if world_size != 2:
            raise SystemExit("This bounded mechanics lab requires exactly two ranks.")
        hidden = 1_024 if args.workload == "small" else 8_192
        tokens_per_rank = 32 if args.workload == "small" else 512
        send_counts = [3 * tokens_per_rank // 4, tokens_per_rank // 4]
        receive_counts = [send_counts[rank]] * world_size
        routed = torch.empty(
            (tokens_per_rank, hidden),
            device="cuda",
            dtype=torch.bfloat16,
        )
        cursor = 0
        for destination, count in enumerate(send_counts):
            routed[cursor : cursor + count].fill_(rank * 10 + destination + 1)
            cursor += count
        received = torch.empty(
            (sum(receive_counts), hidden), device="cuda", dtype=torch.bfloat16
        )
        returned = torch.empty_like(routed)

        def route() -> None:
            torch.distributed.all_to_all_single(
                received,
                routed,
                output_split_sizes=receive_counts,
                input_split_sizes=send_counts,
            )
            received.mul_(rank + 1)
            torch.distributed.all_to_all_single(
                returned,
                received,
                output_split_sizes=send_counts,
                input_split_sizes=receive_counts,
            )

        for _ in range(args.warmup):
            route()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        samples: list[float] = []
        for _ in range(args.iterations):
            started = torch.cuda.Event(enable_timing=True)
            ended = torch.cuda.Event(enable_timing=True)
            started.record()
            route()
            ended.record()
            ended.synchronize()
            samples.append(float(started.elapsed_time(ended)))
        expected = routed.clone()
        cursor = 0
        for destination, count in enumerate(send_counts):
            expected[cursor : cursor + count].mul_(destination + 1)
            cursor += count
        correct = bool(torch.equal(returned, expected))
        # Create explicit input values on the selected device.
        correct_tensor = torch.tensor(int(correct), device="cuda")
        torch.distributed.all_reduce(correct_tensor, op=torch.distributed.ReduceOp.MIN)
        global_expert_token_load = [count * world_size for count in send_counts]
        if rank == 0:
            if not bool(correct_tensor):
                raise SystemExit(
                    "Expert routing did not return the expected rank-specific outputs."
                )
            # Save the actual measurements together with their correctness checks.
            target = write_result(
                args,
                lab_id="23_inference_expert_parallel",
                environment={**environment, "rank_count": world_size},
                measurements={
                    "world_size": world_size,
                    "hidden_size": hidden,
                    "tokens_sent_to_experts_per_rank": send_counts,
                    "global_expert_token_load": global_expert_token_load,
                    "expert_load_max_to_mean": round(
                        max(global_expert_token_load)
                        / statistics.mean(global_expert_token_load),
                        4,
                    ),
                    "toy_expert_parameter_fraction_per_rank": round(1 / world_size, 4),
                    "parameter_fraction_scope": (
                        "expert parameters only; shared and non-expert parameters "
                        "remain replicated in expert parallelism"
                    ),
                    "inference_evidence": [
                        "request token load",
                        "round-trip latency",
                        "toy expert-parameter ownership fraction",
                        "Production expert-parallel serving requires separate model qualification",
                    ],
                    "round_trip": summarize_ms(samples),
                },
                correctness={"all_ranks_routed_to_expected_experts": True},
            )
            print(f"Completed expert-parallel routing: {target}")
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/23_inference_expert_parallel.sbatch --workload small

# Optional profiling
sbatch slurm/23_inference_expert_parallel.sbatch --workload small --profiler all

Lab 24: Compare inference tensor-partition communication patterns

Tensor parallelism can split a layer's weights across GPUs, but partial outputs must be assembled correctly. This lab demonstrates column- and row-parallel linear inference on two H100 ranks and compares both with a full-weight reference.

Complete source: labs/24_inference_tensor_parallel.py
"""Measure inference tensor-parallel fit, latency, and communication mechanics."""

from __future__ import annotations

import argparse
import statistics
import time
from collections.abc import Callable

from course_evidence import annotated_operation
from inference_common import (
    add_common_args,
    close_distributed,
    init_nccl,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)


def partition_operations(torch, inputs, weight, rank: int, world_size: int):
    """Return forward-only column/all-gather and row/all-reduce operations."""
    column_weight = weight.chunk(world_size, dim=0)[rank].contiguous()
    row_weight = weight.chunk(world_size, dim=1)[rank].contiguous()
    row_input = inputs.chunk(world_size, dim=1)[rank].contiguous()

    def column_parallel() -> object:
        local_output = inputs @ column_weight.T
        gathered = [torch.empty_like(local_output) for _ in range(world_size)]
        torch.distributed.all_gather(gathered, local_output)
        return torch.cat(gathered, dim=-1)

    def row_parallel() -> object:
        output = row_input @ row_weight.T
        torch.distributed.all_reduce(output)
        return output

    return column_parallel, row_parallel


def validate_outputs(torch, reference, column_output, row_output) -> dict[str, float]:
    """Check finite results and the recipe-specific BF16 error budgets."""
    if not all(
        bool(torch.isfinite(value).all().item())
        for value in (reference, column_output, row_output)
    ):
        raise ValueError("Tensor-parallel output/reference contains non-finite values.")
    differences = [
        output.float() - reference.float() for output in (column_output, row_output)
    ]
    denominator = torch.linalg.vector_norm(reference.float()).clamp_min(1e-12)
    max_error = max(
        float((torch.linalg.vector_norm(delta) / denominator).item())
        for delta in differences
    )
    # Row partitioning changes the BF16 reduction order; relative L2 bounds its
    # aggregate error without a misleading pointwise test near cancellation.
    if max_error >= 0.02 or not torch.allclose(
        column_output, reference, rtol=1e-2, atol=1e-2
    ):
        raise ValueError(
            f"Tensor-parallel outputs diverged from reference: {max_error=}"
        )
    return {
        "maximum_relative_l2": max_error,
        "maximum_absolute_error": max(
            float(delta.abs().max().item()) for delta in differences
        ),
    }


def run_experiment(
    torch, args, environment, rank: int, world_size: int, local_rank: int
):
    if world_size != 2:
        raise SystemExit("This bounded mechanics lab requires exactly two ranks.")
    device = f"cuda:{local_rank}"
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    width = 2_048 if args.workload == "small" else 8_192
    batch = (
        args.batch_size
        if args.batch_size is not None
        else (32 if args.workload == "small" else 128)
    )
    inputs = torch.empty((batch, width), device=device, dtype=torch.bfloat16)
    weight = torch.empty((width, width), device=device, dtype=torch.bfloat16)
    if rank == 0:
        inputs.normal_()
        weight.normal_()
    # A shared seed is not a substitute for proving that ranks use one model.
    torch.distributed.broadcast(inputs, src=0)
    torch.distributed.broadcast(weight, src=0)
    reference = inputs @ weight.T
    column_parallel, row_parallel = partition_operations(
        torch, inputs, weight, rank, world_size
    )

    def measure(operation: Callable[[], object]) -> list[float]:
        for _ in range(args.warmup):
            operation()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        samples: list[float] = []
        for _ in range(args.iterations):
            torch.distributed.barrier()
            started = time.perf_counter()
            operation()
            torch.cuda.synchronize()
            # Create explicit input values on the selected device.
            elapsed = torch.tensor(
                (time.perf_counter() - started) * 1_000,
                device=device,
                dtype=torch.float64,
            )
            torch.distributed.all_reduce(elapsed, op=torch.distributed.ReduceOp.MAX)
            samples.append(float(elapsed.item()))
        return samples

    column_samples = measure(column_parallel)
    row_samples = measure(row_parallel)
    column_output = column_parallel()
    row_output = row_parallel()
    errors = {}
    failure = None
    try:
        errors = validate_outputs(torch, reference, column_output, row_output)
    except ValueError as exc:
        failure = str(exc)
    # Every rank participates before any rank exits for numerical failure.
    local_ok = torch.tensor(int(failure is None), device=device, dtype=torch.int32)
    torch.distributed.all_reduce(local_ok, op=torch.distributed.ReduceOp.MIN)
    if not bool(local_ok.item()):
        raise SystemExit(
            failure or "Tensor-parallel reference check failed on another rank."
        )
    if rank == 0:
        logical_output_bytes = reference.numel() * reference.element_size()
        # Save the actual measurements together with their correctness checks.
        target = write_result(
            args,
            lab_id="24_inference_tensor_parallel",
            environment={**environment, "rank_count": world_size},
            measurements={
                "batch": batch,
                "width": width,
                "replicated_reference_weight_bytes": weight.numel()
                * weight.element_size(),
                "parameter_shard_bytes_per_rank": weight.numel()
                * weight.element_size()
                // world_size,
                "logical_collective_tensor_bytes": logical_output_bytes,
                "inference_contract": [
                    "weight fit per rank",
                    "operator communication latency",
                    "Dynamo Labs32-34 measure actual server/client performance",
                ],
                "model_fit_fraction_per_rank": round(1 / world_size, 4),
                "timing_scope": "slowest rank per iteration",
                "column_parallel_all_gather_median_ms": round(
                    statistics.median(column_samples), 4
                ),
                "row_parallel_all_reduce_median_ms": round(
                    statistics.median(row_samples), 4
                ),
                "column_parallel_all_gather_samples_ms": column_samples,
                "row_parallel_all_reduce_samples_ms": row_samples,
                **errors,
            },
            correctness={
                "column_parallel_matches_reference": True,
                "row_parallel_matches_reference": True,
            },
        )
        print(f"Completed tensor-parallel linear experiment: {target}")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--batch-size",
        type=int,
        default=None,
        help="Input rows per forward operation; use 1 to examine small-message latency.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.batch_size is not None and args.batch_size <= 0:
        parser.error("--batch-size must be positive")
    torch = load_torch()
    environment = require_course_gpu(torch)
    rank, world_size, local_rank = init_nccl(torch)
    try:
        run_experiment(torch, args, environment, rank, world_size, local_rank)
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/24_inference_tensor_parallel.sbatch --workload small

# Optional profiling
sbatch slurm/24_inference_tensor_parallel.sbatch --workload small --profiler all

Lab 25: Compare request replicas with tensor-parallel decoding

Request replication assigns different requests to independent full-weight replicas. In this experiment you will measure a baseline, inspect the evidence, and change one control while keeping useful work fixed.

Complete source: labs/25_fabric_inference.py
"""Fixed-request projection decoding: replicated requests versus tensor-sharded weights."""

import argparse

from course_evidence import evidence_phase
from fabric_common import all_correct, initialize, measure
from inference_common import (
    add_common_args,
    close_distributed,
    validate_common_args,
    write_result,
)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--placement", choices=("replicated", "tensor"), default="replicated"
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch, rank, world, _local, env = initialize(args.seed)
    try:
        requests, width, tokens = (
            (32, 512, 8) if args.workload == "small" else (128, 4096, 32)
        )
        # Educational recurrent projection, not a complete language model or service.
        prompts = torch.randn(requests, width, device="cuda") * 0.01
        # Create the synthetic tensors used by this experiment.
        weight = torch.randn(width, width, device="cuda") / width**0.5
        reference = prompts.clone()
        for _ in range(tokens):
            reference = torch.tanh(reference @ weight)
        if args.placement == "replicated":
            local_prompts = prompts.chunk(world, dim=0)[rank].contiguous()
            local_weight = weight
            expected = reference.chunk(world, dim=0)[rank]
        else:
            local_prompts = prompts
            local_weight = weight.chunk(world, dim=0)[rank].clone()
            expected = reference
        # Remove the reference weights from measured memory; reference output remains for validation.
        del weight, prompts
        output = None

        def operation():
            nonlocal output
            state = local_prompts.clone()
            for _ in range(tokens):
                with evidence_phase("decode_projection"):
                    if args.placement == "replicated":
                        state = state @ local_weight
                    else:
                        part = state.chunk(world, dim=1)[rank].contiguous()
                        state = part @ local_weight
                if args.placement == "tensor":
                    with evidence_phase("decode_all_reduce"):
                        torch.distributed.all_reduce(state)
                state = torch.tanh(state)
            output = state

        torch.cuda.reset_peak_memory_stats()
        times = measure(torch, operation, args.warmup, args.iterations)
        all_correct(
            torch,
            bool(torch.allclose(output, expected, rtol=3e-3, atol=3e-5)),
            "Sharded decoding differs from full-weight reference",
        )
        # Create explicit input values on the selected device.
        peak = torch.tensor(
            torch.cuda.max_memory_allocated(), device="cuda", dtype=torch.int64
        )
        torch.distributed.all_reduce(peak, op=torch.distributed.ReduceOp.MAX)
        if rank == 0:
            print(
                write_result(
                    args,
                    lab_id="25_fabric_inference",
                    environment=env,
                    measurements={
                        "requests": requests,
                        "width": width,
                        "generated_tokens_per_request": tokens,
                        "ranks": world,
                        "batch": times,
                        "tokens_per_second": requests
                        * tokens
                        / times["median_ms"]
                        * 1000,
                        "peak_allocated_bytes": peak.item(),
                    },
                    correctness={"projection_decode_matches_reference": True},
                )
            )
    finally:
        close_distributed(torch)


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/25_fabric_inference.sbatch --workload small --placement replicated

# Optional profiling
sbatch slurm/25_fabric_inference.sbatch --workload small --placement replicated --profiler all

Lab 26: Separate collective latency from payload throughput

An all-reduce combines values from every rank and returns the result to every participant. For a four-byte payload, launch, protocol and synchronization costs dominate.

Complete source: labs/26_collective_latency.py
"""Separate small-message collective latency from large-message payload rate."""

from network_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("latency")
# Normal execution
sbatch slurm/26_collective_latency.sbatch --workload small --algorithm auto

# Optional profiling
sbatch slurm/26_collective_latency.sbatch --workload small --algorithm auto --profiler all

Lab 27: Measure GPU-memory RDMA read completion latency

Remote direct memory access, or RDMA, lets a network adapter access registered memory without copying every message through the remote CPU. This experiment measures completion latency for reliable-connected RDMA reads.

Complete source: labs/27_rdma_latency.py
"""Measure completed RDMA READ latency separately from bulk write bandwidth."""

from __future__ import annotations

import argparse
import json
import math
import os
import re
import sys
import time

from course_evidence import allocation_gpu_family
from common import add_common_args, validate_common_args, write_result
from fabric_tools import PINS, qualified_binary
from job_processes import Processes, allocated_nodes, private_folder, step


def latency_result(document, size, iterations, memory):
    info, result = document["test_info"], document["results"]
    if (
        info["Connection_type"] != "RC"
        or info["Link_type"] != "IB"
        or result["MsgSize"] != size
        or result["n_iterations"] != iterations
    ):
        raise ValueError("Latency report has a different transport or workload")
    if (memory == "host" and "cuda_device" in info) or (
        memory != "host" and info.get("cuda_device") != 0
    ):
        raise ValueError("Report memory registration differs from the request")
    values = {
        "median_us": result["t_typical"],
        "mean_us": result["t_avg"],
        "p99_us": result["percentile_99"],
    }
    if any(
        type(value) not in (int, float) or not math.isfinite(value) or value <= 0
        for value in values.values()
    ):
        raise ValueError("Invalid latency distribution")
    return values


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.set_defaults(warmup=0, iterations=1000)
    parser.add_argument(
        "--memory", choices=("host", "cuda-peermem", "cuda-dmabuf"), default="host"
    )
    parser.add_argument("--server-device", required=True)
    parser.add_argument("--client-device", required=True)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    if args.iterations < 100 or args.warmup != 0:
        parser.error("Use --iterations >=100 and --warmup 0; the vendor owns timing")
    if not all(
        re.fullmatch(r"mlx5_[0-9]+", name)
        for name in (args.server_device, args.client_device)
    ):
        parser.error("Select observed mlx5 devices from the topology report")
    if os.environ.get("COURSE_PROFILE_TOOL", "none") != "none":
        parser.error("CUDA kernel replay is inapplicable to RDMA completion latency")
    nodes = allocated_nodes()
    binary = qualified_binary("perftest_read_lat")
    folder = private_folder(args, "27_rdma_latency")
    size = 64 if args.workload == "small" else 4096
    port = 35000 + int(os.environ["SLURM_JOB_ID"]) % 10000
    with Processes(folder) as processes:
        children = []
        for rank, role in enumerate(("server", "client")):
            command = [
                str(binary),
                "-d",
                (args.server_device, args.client_device)[rank],
                "-s",
                str(size),
                "-n",
                str(args.iterations),
                "-p",
                str(port),
                "--out_json",
                "--out_json_file=" + str(folder / (role + ".json")),
            ]
            if args.memory != "host":
                command.append("--use_cuda=0")
            if args.memory == "cuda-dmabuf":
                command.append("--use_cuda_dmabuf")
            if role == "client":
                command.append(nodes[0])
            children.append(
                processes.start(
                    role + "-step",
                    step(
                        nodes[rank],
                        [
                            sys.executable,
                            "labs/fabric_tools.py",
                            "--role",
                            role,
                            "--folder",
                            str(folder),
                            "--port",
                            str(port),
                            "--",
                            *command,
                        ],
                    ),
                )
            )
            if role == "server":
                deadline = time.monotonic() + 40
                while not (folder / "ready").exists():
                    processes.healthy()
                    if time.monotonic() > deadline:
                        raise RuntimeError("Owned RDMA endpoint did not become ready")
                    time.sleep(0.1)
        for child in children:
            processes.wait(child, timeout=240)
    report = latency_result(
        json.loads((folder / "client.json").read_text()),
        size,
        args.iterations,
        args.memory,
    )
    print(
        write_result(
            args,
            lab_id="27_rdma_latency",
            environment={
                "gpu_family": allocation_gpu_family(),
                "allocated_gpus": 16,
                "vendor_revision": PINS["perftest_read_lat"],
            },
            measurements={**report, "payload_bytes": size},
            correctness={
                "rc_operations_completed": True,
                "requested_memory_and_transport_reported": True,
            },
        )
    )


if __name__ == "__main__":
    main()

Start with host memory, then replace --memory host with your qualified --memory cuda-dmabuf or --memory cuda-peermem path. Compare the same workload and payload size to isolate the memory path.

# Normal execution
sbatch slurm/27_rdma_latency.sbatch --workload small --server-device "$SERVER_HCA" --client-device "$CLIENT_HCA" --memory host

# Optional profiling
sbatch slurm/27_rdma_latency.sbatch --workload small --server-device "$SERVER_HCA" --client-device "$CLIENT_HCA" --memory host --profiler all

Lab 28: Test NCCL network-adapter selection

A host channel adapter, or HCA, connects a worker to InfiniBand. NCCL selects usable adapters and communication paths from topology.

Complete source: labs/28_nic_selection.py
"""Compare automatic multi-NIC selection with one topology-qualified NIC per node."""

from network_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("rails")
# Normal execution
sbatch slurm/28_nic_selection.sbatch --workload small --server-hca "$SERVER_HCA" --client-hca "$CLIENT_HCA" --hca-policy all

# Optional profiling
sbatch slurm/28_nic_selection.sbatch --workload small --server-hca "$SERVER_HCA" --client-hca "$CLIENT_HCA" --hca-policy all --profiler all

Lab 29: Measure NIXL GPU transfer progress

NVIDIA Inference Xfer Library, or NIXL, moves data between memory regions using transport backends. A progress thread advances transfer work independently of the calling thread.

Complete source: labs/29_nixl_transfer.py
"""Measure NIXL GPU-buffer transfers using its consistency-checked two-process benchmark."""

from __future__ import annotations

import argparse
import hashlib
import math
import os
import re
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
from vendor_capture import add_worker_prefix, validate_worker_prefix, worker_command


def parse_rows(text, block_bytes, batch_size):
    rows = []
    for line in text.splitlines():
        fields = line.split()
        if len(fields) != 10 or not all(
            re.fullmatch(r"[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", value)
            for value in fields
        ):
            continue
        values = list(map(float, fields))
        if int(values[0]) != block_bytes or int(values[1]) != batch_size:
            raise ValueError("NIXL row differs from requested block or batch size")
        if (
            any(not math.isfinite(x) or x < 0 for x in values)
            or values[2] <= 0
            or values[3] <= 0
        ):
            raise ValueError("Invalid NIXL measurement")
        rows.append(
            {
                "block_bytes": int(values[0]),
                "batch_size": int(values[1]),
                "GBps": values[2],
                "amortized_item_us": values[3],
                "preparation_us": values[4],
                "post_us": values[6],
                "transfer_us": values[8],
                "transfer_p99_us": values[9],
            }
        )
    if len(rows) != 1:
        raise ValueError(
            "Expected exactly one two-process SG benchmark row; retain raw output and check the pinned NIXLBench format"
        )
    return rows[0]


def benchmark_command(binary, endpoint, group, args):
    size = 4096 if args.workload == "small" else 4 * 2**20
    return [
        str(binary),
        "--etcd_endpoints",
        endpoint,
        "--benchmark_group",
        group,
        "--backend",
        "UCX",
        "--scheme",
        "pairwise",
        "--mode",
        "SG",
        "--initiator_seg_type",
        "VRAM",
        "--target_seg_type",
        "VRAM",
        "--op_type",
        "WRITE",
        "--check_consistency",
        "--total_buffer_size",
        str(2**30),
        "--start_block_size",
        str(size),
        "--max_block_size",
        str(size),
        "--start_batch_size",
        "1",
        "--max_batch_size",
        "1",
        "--warmup_iter",
        str(args.warmup),
        "--num_iter",
        str(args.iterations),
        "--large_blk_iter_ftr",
        "1",
        "--enable_pt=" + str(args.progress_thread == "on").lower(),
        "--progress_threads",
        "1" if args.progress_thread == "on" else "0",
    ]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.set_defaults(warmup=50, iterations=500)
    parser.add_argument("--progress-thread", choices=("off", "on"), default="off")
    add_worker_prefix(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_worker_prefix(args)
    validate_common_args(args)
    if args.iterations < 100:
        parser.error(
            "Use at least 100 measured transfers for the tail-latency investigation"
        )
    nodes = allocated_nodes()
    binary = Path(os.environ.get("COURSE_NIXLBENCH", ""))
    if not binary.is_file():
        parser.error("Complete the shared README setup and export COURSE_NIXLBENCH")
    folder = private_folder(args, "29_nixl_transfer")
    with Processes(folder) as processes:
        endpoint = start_etcd(processes, nodes[0])
        command = benchmark_command(binary, endpoint, "course-" + args.run_id, args)
        children = [
            processes.start(
                "rank" + str(rank),
                step(
                    node,
                    [
                        "env",
                        "CUDA_VISIBLE_DEVICES=0",
                        *worker_command(
                            command, folder / f"rank{rank}.stdout", ucx=True, prefix=args.worker_prefix
                        ),
                    ],
                ),
            )
            for rank, node in enumerate(nodes)
        ]
        for child in children:
            processes.wait(child, timeout=600)
    reports = []
    for rank in range(2):
        text = (folder / f"rank{rank}.stdout").read_text()
        # Only the benchmark's reporting process prints the aggregated table.
        if re.search(r"^\s*[0-9]+\s+1\s+[0-9]", text, re.MULTILINE):
            reports.append(
                parse_rows(text, 4096 if args.workload == "small" else 4 * 2**20, 1)
            )
    if len(reports) != 1:
        raise ValueError("Expected one authoritative NIXL reporting process")
    print(
        write_result(
            args,
            lab_id="29_nixl_transfer",
            environment={
                "gpu_family": allocation_gpu_family(),
                "participating_gpus": 2,
                "allocated_gpus": 16,
                "nixl_candidate": "1.4.1",
                "launcher_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
            },
            measurements=reports[0],
            correctness={
                "both_processes_succeeded": True,
                "consistency_check_enabled": True,
            },
        )
    )


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/29_nixl_transfer.sbatch --workload small --progress-thread off

# Optional profiling
sbatch slurm/29_nixl_transfer.sbatch --workload small --progress-thread off --profiler all

Lab 30: Overlap Megatron gradient communication

Megatron Bridge connects model configuration to Megatron distributed training. Gradient communication can begin while later backward computation is still running.

Complete source: labs/30_megatron_overlap.py
"""Measure exposed gradient exchange in a real Megatron Bridge training loop."""

from bridge_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("overlap")
# Normal execution
sbatch slurm/30_megatron_overlap.sbatch --workload small --overlap off --reference "$TRAINING_REFERENCE"

# Optional profiling
sbatch slurm/30_megatron_overlap.sbatch --workload small --overlap off --reference "$TRAINING_REFERENCE" --profiler all

Lab 31: Place hierarchical context-parallel communication

Context parallelism partitions a long token sequence across ranks while preserving attention over the full context. Hierarchical context parallelism uses different communication within and between nodes.

Complete source: labs/31_context_parallel.py
"""Compare flat and topology-aware hierarchical context communication."""

from bridge_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("context")
# Normal execution
sbatch slurm/31_context_parallel.sbatch --workload small --layout flat --reference "$CONTEXT_REFERENCE"

# Optional profiling
sbatch slurm/31_context_parallel.sbatch --workload small --layout flat --reference "$CONTEXT_REFERENCE" --profiler all

Lab 32: Compare aggregated and disaggregated Dynamo serving

Prefill processes input tokens and creates the key/value cache; decode repeatedly generates new tokens using that cache. NVIDIA Dynamo can place these phases on different workers and transfer cache data through NIXL.

Complete source: labs/32_dynamo_disaggregation.py
"""Compare two TP8 replicas with TP8 prefill and TP8 decode pools."""

from dynamo_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("disaggregation")
Teaching diagram
Keep sixteen GPUs while changing phase placementThe same sixteen GPUs can serve two aggregated replicas or split prefill and decode into separate eight-GPU workers. Cache transfer crosses the inter-node network only in the disaggregated layout.Worker A: prefill, TP8Input → cache stateWorker B: decode, TP8Cache state → tokensNIXL KV-cache transfer
Keep sixteen GPUs while changing phase placement

The same sixteen GPUs can serve two aggregated replicas or split prefill and decode into separate eight-GPU workers. Cache transfer crosses the inter-node network only in the disaggregated layout.

# Normal execution
sbatch slurm/32_dynamo_disaggregation.sbatch --workload small --layout aggregated

# Optional profiling
sbatch slurm/32_dynamo_disaggregation.sbatch --workload small --layout aggregated --profiler all

Lab 33: Test KV-cache-aware request routing

A key/value cache stores attention state for tokens already processed. When requests reuse prefixes, a router can send work to a worker holding useful cached blocks.

Complete source: labs/33_dynamo_routing.py
"""Measure KV-aware routing on repeated-prefix requests with two TP8 replicas."""

from dynamo_experiments import run

if __name__ == "__main__":
    # The shared implementation owns inputs, measurement and correctness checks.
    run("routing")
# Normal execution
sbatch slurm/33_dynamo_routing.sbatch --workload small --router round-robin

# Optional profiling
sbatch slurm/33_dynamo_routing.sbatch --workload small --router round-robin --profiler all

Lab 34: Tune serving goodput under latency objectives

Goodput is the rate of successfully completed requests that also meet declared service-level objectives. A server can increase raw throughput while violating latency limits.

Complete source: labs/34_serving_goodput.py
"""Compare concurrency using fixed generated-token work and latency SLOs."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
from pathlib import Path

from common import add_common_args, validate_common_args, write_result
from course_evidence import allocation_gpu_family
from dynamo_experiments import MODEL_REVISION, service
from job_processes import private_folder
from vendor_capture import add_worker_prefix, validate_worker_prefix


def aiperf_tokenizer_config(model_dir):
    """Resolve AIPerf offline from the cache snapshot prepared in shared setup."""
    snapshot = model_dir.resolve()
    if (
        snapshot.name != MODEL_REVISION
        or snapshot.parent.name != "snapshots"
        or snapshot.parent.parent.name != "models--Qwen--Qwen3-8B"
        or not all(
            (snapshot / name).is_file()
            for name in ("config.json", "tokenizer.json", "tokenizer_config.json")
        )
    ):
        raise ValueError(
            "Use the shared README setup's complete pinned Qwen3-8B cache snapshot"
        )
    # AIPerf 0.12 resolves offline tokenizers as Hub IDs, even for local paths.
    return [
        "--tokenizer",
        "Qwen/Qwen3-8B",
        "--tokenizer-revision",
        MODEL_REVISION,
    ], {
        **os.environ,
        "HF_HUB_CACHE": str(snapshot.parents[2]),
        "HF_HUB_OFFLINE": "1",
        "TRANSFORMERS_OFFLINE": "1",
    }


def profiling_records(path, expected):
    """Require complete measured evidence; readiness/warm-up is not measured work."""
    try:
        rows = [
            json.loads(line) for line in path.read_text().splitlines() if line.strip()
        ]
    except OSError as error:
        raise ValueError("Missing AIPerf evidence: " + path.name) from error
    if any(
        not isinstance(row, dict) or not isinstance(row.get("metadata"), dict)
        for row in rows
    ):
        raise ValueError("Malformed per-request evidence")
    rows = [
        row for row in rows if row["metadata"].get("benchmark_phase") == "profiling"
    ]
    by_id = {}
    for row in rows:
        identity = row["metadata"].get("x_request_id")
        if (
            not isinstance(identity, str)
            or not identity
            or identity in by_id
            or row.get("error")
            or row["metadata"].get("was_cancelled")
        ):
            raise ValueError(
                "Incomplete, duplicate or unsuccessful per-request evidence"
            )
        by_id[identity] = row
    if len(by_id) != expected:
        raise ValueError("Incomplete per-request evidence")
    return by_id


def fixed_work(raw, output_tokens, seed):
    """Check actual wire controls and final server usage, never re-tokenized text."""
    if type(raw.get("status")) is not int or not 200 <= raw["status"] < 300:
        raise ValueError("Raw request has no successful HTTP status")
    payload = raw.get("payload")
    if not isinstance(payload, dict):
        raise ValueError("Missing transmitted request payload")
    controls = {
        "model": "course-model",
        "seed": seed,
        "min_tokens": output_tokens,
        "max_completion_tokens": output_tokens,
        "ignore_eos": True,
        "n": 1,
        "stream": True,
    }
    if any(
        payload.get(key) != value or type(payload.get(key)) is not type(value)
        for key, value in controls.items()
    ):
        raise ValueError("Transmitted request changed fixed generation controls")
    stream_options = payload.get("stream_options")
    if (
        type(payload.get("temperature")) not in (int, float)
        or payload["temperature"] != 0
        or not isinstance(stream_options, dict)
        or stream_options.get("include_usage") is not True
        or any(
            payload.get(key) is not None
            for key in ("stop", "stop_token_ids", "max_tokens")
        )
        or not isinstance(payload.get("messages"), list)
        or not payload["messages"]
    ):
        raise ValueError("Transmitted request lacks prompts/usage or changes stopping")
    usage, complete = None, False
    responses = raw.get("responses")
    if not isinstance(responses, list):
        raise ValueError("Missing raw streaming responses")
    for response in responses:
        if not isinstance(response, dict) or not isinstance(
            response.get("packets"), list
        ):
            raise ValueError("Malformed raw streaming response")
        packets = response["packets"]
        if any(not isinstance(packet, dict) for packet in packets):
            raise ValueError("Malformed SSE packet")
        values = [
            packet.get("value") for packet in packets if packet.get("name") == "data"
        ]
        if any(not isinstance(value, str) for value in values):
            raise ValueError("Malformed SSE data")
        # Multiple data lines belong to one SSE message, as in the vendor parser.
        value = "\n".join(values).strip()
        if not value:
            continue
        if complete:
            raise ValueError("Trailing streaming data after completion")
        if value == "[DONE]":
            complete = True
            continue
        event = json.loads(value)
        if not isinstance(event, dict) or event.get("error"):
            raise ValueError("Unsuccessful streaming response")
        if event.get("usage"):
            usage = event["usage"]
    if not complete or not isinstance(usage, dict):
        raise ValueError("Incomplete stream or missing server usage")
    prompt_count, completion_count = (
        usage.get("prompt_tokens"),
        usage.get("completion_tokens"),
    )
    if (
        type(prompt_count) is not int
        or prompt_count <= 0
        or type(completion_count) is not int
        or completion_count != output_tokens
    ):
        raise ValueError("Server token counts differ from fixed generated-token work")
    total = usage.get("total_tokens")
    if total is not None and (
        type(total) is not int or total != prompt_count + completion_count
    ):
        raise ValueError("Server total token count is inconsistent")
    details = usage.get("completion_tokens_details")
    if details is not None:
        if not isinstance(details, dict):
            raise ValueError("Malformed reasoning-token details")
        reasoning = details.get("reasoning_tokens")
        if reasoning is not None and (
            type(reasoning) is not int or not 0 <= reasoning <= completion_count
        ):
            raise ValueError("Reasoning tokens must be part of total completion work")
    return payload, prompt_count, completion_count


def summarize(folder, expected, *, output_tokens, seed):
    summary = json.loads((folder / "profile_export_aiperf.json").read_text())
    if summary.get("schema_version") != "1.4" or summary.get("was_cancelled"):
        raise ValueError("Unknown or cancelled AIPerf summary")

    def metric(name, unit, field="avg", optional=False):
        row = summary.get(name)
        if row is None and optional:
            return 0.0
        if not isinstance(row, dict) or row.get("unit") != unit:
            raise ValueError("Missing or unexpected AIPerf metric unit: " + name)
        value = row.get(field)
        if type(value) not in (float, int) or not math.isfinite(value) or value < 0:
            raise ValueError("Invalid AIPerf metric: " + name)
        return value

    completed = metric("request_count", "requests")
    failed = metric("error_request_count", "requests", optional=True)
    good = metric("good_request_count", "requests")
    if (
        completed != expected
        or failed != 0
        or good != int(good)
        or not 0 <= good <= completed
    ):
        raise ValueError(
            "Missing or failed requests are not an accepted performance result"
        )
    by_id = profiling_records(folder / "profile_export.jsonl", expected)
    raw_by_id = profiling_records(folder / "profile_export_raw.jsonl", expected)
    if set(raw_by_id) != set(by_id):
        raise ValueError("Raw responses do not belong to the measured requests")
    outputs = json.loads((folder / "outputs.json").read_text())
    rows = outputs.get("data", [])
    if (
        outputs.get("schema_version") != "1.0"
        or not isinstance(rows, list)
        or len(rows) != expected
        or any(not isinstance(row, dict) for row in rows)
    ):
        raise ValueError("Incomplete generated-output evidence")
    identities = [row.get("x_request_id") for row in rows]
    if (
        any(not isinstance(x, str) or not x for x in identities)
        or len(set(identities)) != expected
    ):
        raise ValueError(
            "Generated-output request identities are missing or duplicated"
        )
    if any(
        not isinstance(row.get("response_text"), str)
        or not row["response_text"].strip()
        for row in rows
    ):
        raise ValueError("Every completed request must contain generated text")
    if set(by_id) != set(identities):
        raise ValueError("Generated outputs do not belong to the successful requests")
    work, sessions = {}, set()
    for output in rows:
        record = by_id[output["x_request_id"]]
        metadata = record["metadata"]
        raw = raw_by_id[output["x_request_id"]]
        session = metadata.get("session_num")
        if (
            type(session) is not int
            or session < 0
            or session in sessions
            or type(metadata.get("turn_index")) is not int
            or metadata["turn_index"] != 0
        ):
            raise ValueError("Require distinct single-turn logical sessions")
        sessions.add(session)
        for field in (
            "session_num",
            "conversation_id",
            "turn_index",
            "request_start_ns",
            "request_end_ns",
            "was_cancelled",
        ):
            if raw["metadata"].get(field) != metadata.get(field):
                raise ValueError("Raw request identity/timestamps differ from metrics")
        payload, prompt_count, completion_count = fixed_work(raw, output_tokens, seed)
        work[session] = payload
        for field in ("session_num", "conversation_id", "turn_index"):
            expected_value = metadata.get(field)
            if field == "conversation_id":
                expected_value = expected_value or ""
            elif field == "turn_index" and expected_value is None:
                expected_value = 0
            if field not in output or output[field] != expected_value:
                raise ValueError("Output session identity differs from its request")
        start, end = metadata.get("request_start_ns"), metadata.get("request_end_ns")
        if type(start) is not int or type(end) is not int or not 0 < start < end:
            raise ValueError("Invalid per-request wall-clock timestamps")
        if (
            output.get("request_start_ns") != start
            or output.get("request_end_ns") != end
        ):
            raise ValueError("Output timestamps differ from the measured request")
        for name, unit in (
            ("time_to_first_token", "ms"),
            ("inter_token_latency", "ms"),
            ("request_latency", "ms"),
            ("input_sequence_length", "tokens"),
            ("output_sequence_length", "tokens"),
        ):
            measured = record.get("metrics", {}).get(name, {})
            value = measured.get("value")
            if (
                measured.get("unit") != unit
                or type(value) not in (int, float)
                or not math.isfinite(value)
                or value < 0
            ):
                raise ValueError("Missing or invalid per-request metric: " + name)
            if unit == "tokens" and value <= (
                1 if name == "output_sequence_length" else 0
            ):
                raise ValueError(
                    "Actual sequence lengths cannot establish token latency"
                )
            if output.get("metrics", {}).get(name) != value:
                raise ValueError("Output metric differs from measured request")
            if unit == "tokens" and value != (
                prompt_count if name == "input_sequence_length" else completion_count
            ):
                raise ValueError("Sequence-length metric differs from server usage")

    if sessions != set(range(expected)):
        raise ValueError("Logical request positions are incomplete")
    # Session order is stable across runs; random request IDs are not comparison labels.
    ordered = sorted(rows, key=lambda row: (row["session_num"], row["turn_index"]))
    for name in ("input_sequence_length", "output_sequence_length"):
        actual_mean = sum(row["metrics"][name] for row in ordered) / expected
        if not math.isclose(
            metric(name, "tokens"), actual_mean, rel_tol=0, abs_tol=1e-6
        ):
            raise ValueError("Summary token counts differ from per-request evidence")
    signature = hashlib.sha256(
        json.dumps(
            [row["response_text"] for row in ordered], ensure_ascii=True
        ).encode()
    ).hexdigest()
    return {
        "measurement_contract": "fixed-token-goodput-v1",
        "workload_sha256": hashlib.sha256(
            json.dumps(
                [work[row["session_num"]] for row in ordered],
                sort_keys=True,
                separators=(",", ":"),
                ensure_ascii=True,
                allow_nan=False,
            ).encode()
        ).hexdigest(),
        "requested_output_tokens": output_tokens,
        "ttft_p99_ms": metric("time_to_first_token", "ms", "p99"),
        "request_mean_itl_p99_ms": metric("inter_token_latency", "ms", "p99"),
        "requests_per_second": metric("request_throughput", "requests/sec"),
        "goodput_per_second": metric("goodput", "requests/sec"),
        "completed_requests": completed,
        "slo_passed_requests": good,
        "output_signature": signature,
        "output_tokens_mean": metric("output_sequence_length", "tokens"),
        "input_tokens_mean": metric("input_sequence_length", "tokens"),
        "input_lengths": [row["metrics"]["input_sequence_length"] for row in ordered],
        "output_lengths": [row["metrics"]["output_sequence_length"] for row in ordered],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.set_defaults(iterations=128, warmup=0)
    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("--concurrency", type=int, choices=(4, 8, 16, 32), default=8)
    parser.add_argument("--ttft-slo-ms", type=float, default=1000)
    parser.add_argument("--itl-slo-ms", type=float, default=50)
    parser.add_argument("--capture", choices=("none", "systems"), default="none")
    add_worker_prefix(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_worker_prefix(args, server=True)
    if (
        args.iterations != 128
        or args.warmup != 0
        or any(
            not math.isfinite(x) or x <= 0 for x in (args.ttft_slo_ms, args.itl_slo_ms)
        )
    ):
        parser.error("Use 128 requests, zero AIPerf warm-up and positive finite SLOs")
    args.layout, args.router = "aggregated", "round-robin"
    validate_common_args(args)
    binary = os.environ.get("COURSE_AIPERF")
    if not binary or not Path(binary).is_file():
        parser.error("Source the shared README setup's COURSE_AIPERF executable")
    tokenizer_args, client_environment = aiperf_tokenizer_config(args.model_dir)
    folder = private_folder(args, "34_serving_goodput")
    output = folder / "aiperf"
    output_tokens = 32 if args.workload == "small" else 128
    with service(args, folder) as (url, processes):
        command = [
            binary,
            "profile",
            "--model",
            "course-model",
            *tokenizer_args,
            "--url",
            url,
            "--endpoint-type",
            "chat",
            "--streaming",
            "--use-server-token-count",
            "--random-seed",
            str(args.seed),
            "--num-dataset-entries",
            "128",
            "--dataset-sampling-strategy",
            "sequential",
            "--synthetic-input-tokens-mean",
            "256" if args.workload == "small" else "2048",
            "--synthetic-input-tokens-stddev",
            "0",
            "--output-tokens-mean",
            str(output_tokens),
            "--output-tokens-stddev",
            "0",
            "--extra-inputs",
            json.dumps(
                {
                    "temperature": 0,
                    "seed": args.seed,
                    "min_tokens": output_tokens,
                    "ignore_eos": True,
                    "n": 1,
                }
            ),
            "--request-count",
            "128",
            "--concurrency",
            str(args.concurrency),
            "--goodput",
            f"time_to_first_token:{args.ttft_slo_ms} inter_token_latency:{args.itl_slo_ms}",
            "--wait-for-model-timeout",
            "900",
            "--wait-for-model-mode",
            "both",
            "--request-timeout-seconds",
            "120",
            "--export-level",
            "raw",
            "--export-outputs-json",
            "--artifact-dir",
            str(output),
        ]
        client = processes.start("aiperf", command, env=client_environment)
        if client.wait(timeout=1800) != 0:
            raise ValueError("AIPerf failed; retain private client and server logs")
        processes.healthy()
    measured = summarize(output, 128, output_tokens=output_tokens, seed=args.seed)
    if args.capture != "none":
        print("Diagnostic server reports and client measurements:", folder)
        return
    print(
        write_result(
            args,
            lab_id="34_serving_goodput",
            environment={
                "gpu_family": allocation_gpu_family(),
                "allocated_gpus": 16,
                "model_revision": MODEL_REVISION,
                "aiperf_candidate": "0.12.0",
            },
            measurements=measured,
            correctness={
                "all_requests_complete": True,
                "generated_content_present": True,
                "fixed_generated_token_work": True,
                "transmitted_workload_verified": True,
            },
        )
    )


if __name__ == "__main__":
    main()
# Normal execution
sbatch slurm/34_serving_goodput.sbatch --workload small --concurrency 8

# Optional profiling
sbatch slurm/34_serving_goodput.sbatch --workload small --concurrency 8 --profiler all

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()
            # Loss tensors are materialized after training; no added timed host synchronization.
            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)
    # A first barrier otherwise falls back to global rank modulo visible GPUs.
    # Bind the communicator to the same local device as the workload tensors.
    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"
        )
    # Lab artifacts can contain profiler and environment metadata. Keep newly
    # created files private even when a learner runs a lab outside Slurm.
    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)
    # A first barrier otherwise falls back to global rank modulo visible GPUs.
    # Bind the communicator to the same local device as the workload tensors.
    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"
    )
    # Stop blocks on collection-end report serialization, which can exceed
    # three minutes for the full LARGE workload. Keep its writer alive until
    # acknowledgment, with a bounded deadline distinct from capture startup.
    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)):
                # A failed acknowledgment can follow a partially started engine.
                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,
            # Preserve the venv path even when its Python is a symlink.
            "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()
    # Capture is diagnostic: never publish timings with profiled GPU servers.
    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)
    # A first barrier otherwise falls back to global rank modulo visible GPUs.
    # Bind the communicator to the same local device as the workload tensors.
    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"
    # Do not force a registration mode or claim IB selection from configuration.
    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)
    # A first barrier otherwise falls back to global rank modulo visible GPUs.
    # Bind the communicator to the same local device as the workload tensors.
    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 redirection isolates the vendor's machine-readable stdout from
    # profiler diagnostics. There is no intervening Python worker process.
    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")

Course guides

Getting started

Read the course · 34 labs · Estimated guided time: 64 hours, excluding provisioning and queue time.

Follow communication from fabric paths and collectives to distributed training, inference and serving. For the full lab route, complete GPU Fundamentals and GPU Performance Optimization, then the relevant training or inference foundations, or bring equivalent readiness to launch Slurm jobs, produce a correct unprofiled result and interpret its GPU timeline. Use GPU Performance Tools for profiling and PyTorch for GPU Performance Engineering for a tensor-reading refresher.

Before the first lab

Use two eight-H100 workers with local NVLink/NVSwitch and active InfiniBand. The two one-GPU TCP workers used for local labs do not qualify this fabric. Sixteen GPUs are allocated; some mechanics use only two participating ranks.

Complete the Lab Guide, check Versions and environment, then follow the readiness checks on the qualified cluster. For the full route, begin with Lab 01's topology and rank-placement check. For Fundamentals Lesson 12, read through that lesson, complete Lab 02, verify its placement and correctness results, then run Lab 08. Optimization, a specialization, Lab 01 and Labs 03–07 are not prerequisites for this assignment. Both entry points require the same prepared, qualified fabric. After Lab 08, return to Fundamentals to complete the course.

Runtime preparation

The Lab Guide's single setup command prepares the available communication runtimes, profiling tools and model dependencies in separate pinned environments. Dynamo labs use the larger model. Check the completion summary for failures or hardware skips before submitting a lab. Preparation records candidate software; it does not prove GPU, fabric or serving compatibility.

NIXL and Dynamo start a private job-owned etcd process on the first worker. Both worker names must resolve to reachable IPv4 addresses. The prepared runtime supplies COURSE_ETCD and DYNAMO_UCX_PREFIX; use its recorded runtime rather than mixing libraries from another environment. Qualify each vendor lab with its small workload before performance comparisons.

Learning route

For the full route, follow the groups below. Keep each lab's identity when selecting commands, dashboards and results.

Qualify placement and fabric
Understand collectives and rank timelines
Train with distributed state and communication
Inspect inference parallelism
Isolate network latency and transport
Apply current NVIDIA training and serving techniques

Completion

Choose a training or inference workload. State a hypothesis, change one control, repeat clean baseline/candidate runs in reversed order, and explain the result with correctness, variation and a limitation. A negative result can pass. Retain the matching artifacts, topology/software identity, selected dashboard and relevant rank or server traces privately.

For training, explain useful tokens per second and the collective tail. For inference, explain first-token latency, streamed delivery and requests meeting latency objectives. Labs 32–33 require equivalent outputs; Lab 34 fixes transmitted requests and server-verified generated-token work, allowing different answer text and valid zero-goodput results. These contracts are not interchangeable.

Use Where to Go Next for optional reading.

Reference guides

Versions and environment

Completed prepared-environment runs

All 34 practical labs completed both small and large profiles (68 verified exports) on the prepared NVIDIA H200 cluster. See lab results and the catalog validation record for evidence scope and limitations.

Recorded framework environments include PyTorch 2.14.0+cu130 with CUDA 13.0 and 2.13.0a0+8145d630e8.nv26.06 with CUDA 13.3. Vendor engines retain their separate prepared environments. Allocation GPU counts do not establish the number of active ranks; use each lab's launch and result records.

The observed profiler CLI/viewer pairs were Nsight Systems 2026.4.1 and Nsight Compute 2026.2.1; the scheduler reported Slurm 25.11.3. These runs qualify the recorded experiments in their prepared environments. They do not establish a clean installation, every optional extension, or performance on H100.

H100 target and installation candidates

The following targets and pending checks describe the H100 teaching environment. Keep them separate from the completed H200 evidence above.

EnvironmentQualification candidateIdentity and boundary
Course PyTorchrequirements.txtSeparate shared virtual environment for the mechanics labs; record resolved packages.
Nsight Systems / ComputeCluster-managed CLI/viewer pairRecord matching tool and viewer versions and qualify both-worker counter permissions; completed campaign versions remain above.
NIXLBenchv1.4.1Commit 778edd1d1a50936b12c264879e12ef465e629002; UCX 1.22.0 isolated from Dynamo.
Megatron Bridgetag v0.6.0Commit 51885cf132b2814188b6855c25a8588254274c2a; tag declares package 0.6.1 plus source suffix. Python 3.12 and the isolated pinned Bridge runtime are prepared for its selected labs; ABI and execution still need qualification.
Dynamo1.4.2Source 2ecbdfdf192c69c02c6d21e931d20d3b4a0bb64a; vLLM 0.26.0, Torch 2.11 / CUDA 13. Joint NIXL/NIXL-EP 1.3.2 cu13 build from de8115ca97d3f8fb63a4988e9b4d4a038b2e0f72 against the prepared runtime UCX/RDMA stack; SM90.
AIPerf0.12.0Source be53bf2953d30e46c500e6a80fc1f8b6f84bc718; separate environment, emitted schema checked.
Serving modelQwen/Qwen3-8B BF16Revision b968826d9c46dd6066d109eabc6255188de91218; fixed tokenizer and weights.

Use the Lab Guide to prepare all available lab software with one command, including fabric tools, NCCL Tests, model dependencies and optional container exercises. Exact source pins reduce drift; they do not prove that the native dependencies or GPU/network runtime work together. Retain the resolved dependency inventory, actual package versions, driver, CUDA, NCCL, UCX, topology and binary hashes privately after qualification. Retain the resolved native package inventory for a delivered runtime and immutable image digests for prepared container variants.

A Bridge tag name is not its distribution version. The pinned source and editable Megatron-Core submodule are the authority. Its reduced dense-workload dependency selection needs qualification for each new target; do not assert that a generic empty Python environment is equivalent to NVIDIA's prepared training stack.

Validate 16-GPU topology and vendor smoke runs before using their measured comparisons. Systems captures add overhead. Compute replay is restricted to isolated local kernels, not live distributed collectives. The two one-GPU TCP workers cannot qualify this platform's NVLink/NVSwitch or InfiniBand behavior.

Readiness checks

Complete Lab Preparation on the dedicated two-worker eight-H100 cluster and check the completion summary for failures or hardware skips affecting the selected labs. Qualification is a gate, not an optimization. Inspect each job's exit state and completed artifact; submitting a job does not pass this gate.

For the Fundamentals Lesson 12 assignment, read through that lesson, run Lab 02 and verify its placement and correctness before running Lab 08. This assignment does not require Optimization, a specialization, Lab 01 or Labs 03–07. Both labs reserve sixteen GPUs and use one participating rank per worker; their supplied launchers perform the fabric checks independently.

For the full Advanced route, begin qualification in this order:

sbatch slurm/01_fabric_topology.sbatch --workload small
sbatch slurm/02_collective_readiness.sbatch --workload small
sbatch slurm/03_training_readiness.sbatch --workload small
sbatch slurm/04_inference_readiness.sbatch --workload small
sbatch slurm/05_transport_readiness.sbatch --workload small

Both entry points require full non-MIG H100 devices, local NVLink/NVSwitch, active InfiniBand and the documented correctness checks. Require sixteen distinct ranks for Lab 01 and two participating ranks on distinct workers for the mechanics preflights. Ask the cluster owner to verify NVSwitch/Fabric Manager and driver registration readiness independently. NCCL initialization does not prove every intended transport or every later workload is supported.

Before the vendor labs, record the exact runtime and binary identities and run their small profiles. Opening one valid Systems report, one isolated Compute report and the setup dashboard is required. Keep vendor environment, counter permission, live transport and model-run status separate; any missing gate remains pending.

Lab mechanisms and evidence

A topology map identifies possible paths. A vendor transfer test measures an exercised path. A collective combines transfer and coordination across a group. A training step or inference request adds computation, scheduling and dependencies. Explain each result at the boundary actually measured.

Lab 06 measures directed pairwise NVLink paths, not concurrent switch saturation. Labs 07 and 27 separate RDMA bandwidth from completion latency. Labs 08–14 identify collective ordering and overlap. Labs 15–25 connect communication to model state and outputs. Labs 26–34 connect small-message latency, adapter choice and current NVIDIA runtimes to training throughput and serving objectives.

Use Nsight Systems for CPU gaps, CUDA work, NCCL activity and NVTX phases. PyTorch traces attribute work to framework operations and input shapes; memory profiling records tensor allocations and deallocations during collection. Lab 14 reuses preallocated tensors, so its trace may contain no allocation events. Nsight Compute investigates a selected local kernel's memory traffic, occupancy and stalls; replaying a collective while its peers run normally can hang or distort the experiment. Grafana compares authoritative measured summaries and correlates the job window with device and node activity.

For every independent investigation, predict an observable change before running. Keep useful work and correctness fixed, select one control, repeat clean timings, and inspect diagnostic traces separately. Explain a failed hypothesis rather than searching only for a speedup.

Read distributed evidence

  • Readiness Labs 03–04 must retain two participating ranks on distinct workers and pass their NCCL checks. Lab 01's topology check does not benchmark the prepared native fabric tools.
  • Lab 06 measures directed peer paths, not simultaneous switch saturation. Keep bandwidth and latency populations separate: GB/s uses decimal bytes, GiB uses powers of 1024, and a request p99 is not a token-interval p99.
  • Match Grafana's worker/local-GPU selectors to the private allocation record. A short run can fall between telemetry samples. Inspect reports from both workers rather than treating low sampled activity as idle kernels.
  • Lab 19 checks gradients against BF16 bucket magnitudes with rank-wide agreement. Its Compute companion isolates one local backward kernel without collectives; Systems explains the distributed schedule.
  • Bridge training keeps seeded input and its sequential dataloader fixed. NIXL evidence needs both launcher and native binary identities; the launcher alone may be a library-path wrapper.

Interpret Dynamo comparisons

Keep the supplied batch-invariance, attention, RMSNorm and compiler settings fixed across policies. Labs 32–33 require matching outputs. Lab 34 instead requires identical transmitted requests and verified generated-token work; answer text can differ and zero goodput can be valid.

Readiness includes worker health and frontend model discovery. For profiling, both workers must acknowledge collection and produce nonempty reports before shutdown. Inspect request-phase GPU activity and warnings in each report. Labs 32–33 retain private request/cohort timestamps; correlate them with server traces only after checking clock alignment. Keep instrumented timings separate from clean comparisons.

Benchmark worksheet

Record the immutable workload, correctness criterion, independent variable, software and H100 environment, timer boundary, warm-up, raw sample summary, memory, profiler evidence, observation, inference, and keep/reject decision.

Microbenchmarks must use CUDA events and an end-to-end wall-time check. Distributed trials must include per-rank work, topology, message volume, and exposed communication. Never publish one best sample as the result.

Comparison worksheet

Copy this worksheet into the private experiment record before changing one factor. Fill both columns for equivalent work; mark unavailable evidence explicitly. Retain raw artifacts privately and publish only separately reviewed aggregates following evidence-security.md.

FieldBaselineCandidate / observation
Date and random course run ID (keep artifact location private)To recordTo record
Lab, source/commit identity, exact arguments, single changeTo recordTo record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)To recordTo record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versionsTo recordTo record
Input shapes, layouts, dtype, seeds, batch/workload semanticsTo recordTo record
Primary metric, timer, included operations, completion condition, correctness/quality tolerancesTo recordTo record
Warm-up, measured iterations, three independent trial IDs and orderTo recordTo record
Correctness result and maximum error; missing/non-finite dataTo recordTo record
Raw timing distribution, minimum, median, p90/p95 and dispersionTo recordTo record
Baseline allocated memory, peak allocated/reserved memory, incremental peakTo recordTo record
Sanitized profiler observation, selected range/kernel, tool versionTo recordTo record
Supporting observation and disconfirming controlTo recordTo record
Decision: keep, reject, or investigate; limitation and next experimentTo recordTo record
Suspected limiter and measured critical-path fractionTo recordTo record
Exposed collective time, fixed total work, scaling efficiencyTo recordTo record
Copy-ready gaps, allocation lifetime, compile/capture/replay costsTo recordTo record
Labs 19/20 stream mode, slots, batches, work/sink, whole-loop distribution and final-drain correctness; separate timeline overlap and pool capacityTo recordTo record

A faster result is accepted only when its declared correctness, workload, timed operations, and environment constraints all hold. Record rejected hypotheses and slower candidates; they are useful evidence for the next choice.

Networking comparison addendum

Before a tuning run, record the effective site configuration privately, then freeze one profile difference. Record IP interface and RDMA HCA selection separately; do not publish their identifying names or raw logs.

Networking evidenceBaselineCandidate
Platform capability versus selected transport versus qualified GDR pathTo recordTo record
Benchmark source, per-node binary hashes, MPI mode, NCCL headers and loaded libraryTo recordTo record
Message bytes, float/sum, buffer mode, rank count, validation enabledTo recordTo record
Time unit, algbw, normalized busbw, both incorrect-element countsTo recordTo record
Three independent per-size values, median and range across runsTo recordTo record
Diagnostic versus timing run, exit status and complete size curveTo recordTo record
Single job-local override and unchanged QP splitting/interface policyTo recordTo record
Follow-up application time and exposed collective timeTo recordTo record

A parsed log proves only the validated content. A benchmark run does not prove fabric administration, remote binary parity or application benefit. Keep negative or inconclusive results and missing evidence visible.

Evidence and privacy

The course source is designed to be public, but runtime evidence is sensitive by default. Slurm output, PyTorch traces, Nsight reports, DCGM discovery, and serving benchmarks can contain infrastructure identifiers, filesystem paths, command lines, workload shapes, model names, or request content even when the course labs themselves use synthetic data.

Collect privately

  1. Use synthetic or explicitly public inputs. Do not profile customer prompts, proprietary model inputs, credentials, or regulated data.
  2. Complete software preparation in the Lab Guide and review its completion summary. Follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Its private parent directories protect scheduler logs even when Slurm opens them before the job body starts.
  3. Keep results/, original profiler reports, traces, and Slurm output in storage that only the learner or approved course reviewers can read.
  4. Do not pass credentials on command lines or enable shell tracing. Remove unrelated secret-bearing environment variables before profiling, following the cluster owner's approved procedure.
  5. Never commit generated evidence. The course .gitignore reduces accidental staging; it is not an access-control or redaction boundary.

Shared viewer copies

A successful profiling stage automatically delivers a verified copy of its native reports to the installed Nsight viewer directory. These copies are readable by the existing shared viewer audience; the viewer does not provide per-user report isolation. Submit only workloads whose report contents are approved for that audience. Private originals, logs and other results remain in the job directory. Check viewer_delivery and use the exact viewer paths printed by the job; no manual copy or permission change is needed after sbatch.

Share summaries, not raw artifacts

Before material leaves the approved environment, create a separate summary that excludes:

  • hostnames, node lists, job IDs, GPU UUIDs, serial numbers, and account or project identifiers;
  • usernames, home directories, executable paths, internal endpoints, and private repository paths;
  • environment-variable values, tokens, cookies, request headers, and command lines containing credentials;
  • customer data, prompts, model names that are not public, raw traces, and raw logs.

Report only the evidence needed for the learning decision: anonymized run ID, node count, GPU family, software versions, public workload definition, correctness result, aggregate timing, and a written interpretation of relevant profiler evidence. A reviewer should inspect the sanitized copy before it is shared. Redact by producing a new file; do not overwrite the private original.

Course-specific safeguards

  • Lab JSON uses the canonical gpu-course-result/v1 schema and a random run ID instead of a Slurm job ID.
  • New result files are created exclusively with owner-only permissions.
  • Profiler launchers create owner-only, randomly named result directories.
  • The tooling preflight suppresses hostnames, executable paths, GPU UUIDs, and DCGM discovery output.
  • The normal course validator performs static validation and does not execute Python labs or Slurm launchers.
  • The portable tree rejects Python bytecode and Ruff cache directories, and every launcher disables Python bytecode creation before Python starts.
  • requirements.txt is a direct compatibility constraint. The prepared runtime records the installed package and component identities; retain those receipts with qualification evidence. Optional containers also have immutable image identities.

Live site policy remains authoritative. If a profiler or telemetry command is not approved, record a sanitized blocker and ask the cluster owner rather than weakening permissions.

Where to Go Next

These optional directions extend the completed labs without adding completion requirements.

  • Scale the workload before scaling the claim

    Repeat a matched comparison on a larger transformer and representative token lengths after the small run is numerically valid. Inspect whether compute, memory or communication becomes the limiting phase. Long training additionally needs convergence evidence; a short synthetic trajectory does not establish final model quality.

    Megatron Bridge training documentation

  • Study GPU-initiated communication

    Investigate NVSHMEM and device-initiated communication after establishing the host-initiated baselines. Ask which synchronization and progress work moves to the GPU, what ordering guarantees change, and how to validate data before trusting overlap. These are optional extensions, not installed requirements.

    NVIDIA NVSHMEM documentation

  • Extend expert-parallel serving

    Use the existing expert-routing exercises to distinguish dispatch volume, token imbalance and combine cost. A production MoE backend requires its own model, transport and correctness qualification. Do not transfer dense-model serving conclusions directly to routed models or assume a technique requiring Blackwell hardware works on H100.

    NVIDIA Dynamo documentation

Glossary

AIPerf
The workload and measurement client used here to report request latency, throughput and service-objective results.
All-gather
A collective that collects each rank’s contribution and gives the complete set to every participating rank.
All-reduce
A collective that combines corresponding values across ranks with an operation such as sum and returns the combined result to every rank.
All-to-all (a2a)
An exchange in which each participating rank sends a portion of its data to every rank, used here for token or state redistribution.
BF16
Bfloat16; a 16-bit floating-point format with FP32-like exponent range and fewer significand bits.
Collective
A coordinated operation such as all-reduce, all-gather or all-to-all across a process group.
CP
Context parallelism; partitioning sequence context or attention work across ranks with communication of the needed state.
DDP
DistributedDataParallel; replicated model training with gradient synchronization across processes.
DMA
Direct memory access; transfer hardware moves bytes without CPU instructions copying each byte.
EP
Expert parallelism; assigning mixture-of-experts networks to ranks and routing tokens to their owning experts.
Exposed communication
Communication that remains on the critical path after useful overlap.
FP16
16-bit floating point; its narrower exponent range can require gradient scaling during training.
FP32
32-bit floating point; used for reference calculations and selected model, gradient or optimizer state.
FSDP2
Fully sharded data parallelism, second-generation PyTorch interface; shards training state and materializes parameters for computation.
GEMM
General matrix multiplication; a major compute operation in model layers and local expert processing.
Goodput
Completed requests per second that meet every declared latency objective.
GPUDirect RDMA
A device path allowing the network adapter to access registered GPU memory without staging each transfer through host memory.
HCA
Host channel adapter connecting a worker to the InfiniBand fabric.
InfiniBand
The inter-node fabric used by the eight-GPU platform; link state and selected transport need separate evidence.
ITL
Inter-token latency; AIPerf reports a per-request average under its declared token-count and timestamp conventions, rather than the distribution of individual token gaps.
KV cache
Attention keys and values retained for previously processed tokens.
MoE
Mixture of experts; a layer routes each token to a selected subset of expert networks.
MPI
Message Passing Interface; a standard for communication between participating processes, used by the NCCL Tests launch path.
MSE
Mean squared error; the average squared difference between predictions and targets in a training objective.
NCCL
NVIDIA Collective Communications Library; provides GPU collective and point-to-point communication operations.
NIC
Network interface controller; the adapter connecting a worker to the network fabric.
NIXL
NVIDIA Inference Xfer Library, used to transfer cache and other data between memory regions.
NVLink / NVSwitch
GPU links and switching that connect GPUs within the selected H100 node. A topology label alone does not prove switch health.
NVSHMEM
NVIDIA’s GPU-oriented shared-memory programming library, providing communication and synchronization over a partitioned global address space.
NVTX
NVIDIA Tools Extension Library; annotations that name diagnostic markers and ranges without synchronizing or timing GPU execution by themselves.
PMIx
Process Management Interface for Exascale; an interface for process-management services whose integration with MPI and Slurm must be qualified.
Point-to-point (p2p)
Communication between a source and destination rank; unlike a collective, it does not by itself prescribe a whole-group exchange.
PowerSGD
Low-rank gradient compression for stochastic gradient descent (SGD), with approximation error and configurable feedback state.
PP
Pipeline parallelism; placing layer ranges on different ranks and scheduling microbatches through the stages.
Rank
One process participating in a distributed group; global rank identifies the process across workers.
RDMA
Remote direct memory access between registered memory regions.
Reduce-scatter
A collective that combines corresponding values across ranks, then distributes distinct portions of the reduced result among the ranks.
SGD
Stochastic gradient descent; parameter updates driven by gradients estimated from sampled data.
SLO
Service-level objective; a declared threshold, such as a latency bound, used to determine whether completed work counts toward goodput.
TP
Tensor parallelism; partitioning tensor operations within model layers across ranks, with communication of intermediate results.
TTFT
Time to first token, from a declared request boundary to the first observed output token. Labs 32 and 33 time the first nonempty content chunk as a proxy; a chunk can contain more than one token.
UCX
Unified Communication X; a communication framework used by supported transfer backends to access available network and memory transports.

Official references

  1. NCCL environment and transport controls
  2. NCCL Tests performance interpretation
  3. NVIDIA NVBandwidth
  4. RDMA perftest source
  5. NIXL benchmark v1.4.1
  6. Megatron Bridge v0.6.0
  7. Dynamo release artifacts v1.4.2
  8. Dynamo disaggregated launch source
  9. AIPerf v0.12.0 metrics
  10. PyTorch profiler
  11. Nsight Systems documentation
  12. Nsight Compute profiling guide
  13. Soperator source
  14. Megatron Bridge training documentation
  15. NVIDIA NVSHMEM documentation
  16. NVIDIA Dynamo documentation