AI Job Orchestration I: Slurm for Large-Scale Distributed Training

December 1, 2026

Inside Slurm's bare-metal control plane: topology-aware InfiniBand placement, backfill scheduling, Pyxis/Enroot containers, and 16,000-GPU fault recovery.

AI Job Orchestration I: Slurm for Large-Scale Distributed Training

Series: Part 22 of GPU Architecture, Scale-Up Interconnects, and AI Datacenter Infrastructure Series | (Previous) Coolant Distribution Units (CDUs) in AI Datacenters: Hardware Anatomy, OCP Project Deschutes, and Vendor Reference (Vertiv, Motivair, CoolIT)

Summary

Building a 16,000-GPU AI factory with InfiniBand NDR/XDR switches, NVLink/NVSwitch fabrics, and megawatt liquid-cooling loops is only half the engineering battle. The moment you turn the power on, you face a brutal orchestration problem: how do you launch thousands of tightly coupled GPUs simultaneously, pack their ranks onto the exact same network leaf switches to avoid collective bottlenecks, keep the cluster above 90% utilization, and recover automatically when a GPU or optical transceiver dies at 3:00 AM?

Across frontier AI labs—including Meta’s Llama 3 clusters, xAI’s Colossus supercomputers, and national exascale systems—the answer is almost universally Slurm (Simple Linux Utility for Resource Management). In this post, we dissect Slurm’s bare-metal control plane (slurmctld, slurmd, slurmdbd), explain how topology/tree and sched/backfill prevent network fragmentation and head-of-line blocking, walk through rootless container execution with NVIDIA Pyxis and Enroot plus PMIx / NCCL rendezvous, and build a zero-dependency Python 3 simulator proving why topology-aware scheduling boosts effective cluster goodput from 62.4% to 92.2%.

Prior Reading Material

Before diving into cluster-wide job scheduling, these four earlier installments in the series provide the hardware, networking, and datacenter foundation that Slurm directly orchestrates:


1. Why Frontier AI Training Still Runs on Slurm

If you come from cloud-native web engineering, your first instinct when handed 10,000 GPUs might be to install Kubernetes and treat training workers like stateless microservices. In practice, frontier pre-training behaves like the exact opposite of a web service.

A web application scales horizontally through independent replicas: if 498 out of 500 pods start while 2 wait for capacity, the service still handles 99.6% of user traffic. Distributed LLM pre-training using 3D parallelism (Tensor Parallelism, Pipeline Parallelism, and FSDP/ZeRO Data Parallelism) operates in bulk-synchronous lockstep. Every forward and backward step terminates in global AllReduce or ReduceScatter collectives over NCCL. If 16,383 GPUs are ready and GPU #16,384 is missing—or stranded on a congested network switch—the entire 16,384-GPU run either refuses to start or slows down to the pace of that single straggler.

Slurm dominates large-scale AI training for four architectural reasons:

  1. Native Gang Scheduling (All-or-Nothing Allocation): Slurm natively reserves the entire requested node set—whether 16 nodes or 2,048 nodes—and launches all ranks atomically. It never partially schedules half of a distributed training job while deadlocking against another half-scheduled job.
  2. Bare-Metal Latency and Zero OS Jitter: Slurm’s compute daemon (slurmd) is a lightweight compiled C process consuming negligible CPU cycles and memory. There is no overlay network (VXLAN/Geneve), no kube-proxy iptables churn, and no sidecar proxies competing for host PCIe lanes or interrupting CUDA kernel launches.
  3. First-Class Hardware Topology Awareness: Slurm reads a static topology.conf map of your physical InfiniBand or RoCEv2 / Ultra Ethernet leaf-spine switches—and even rack-level NVL72 NVLink domains—so multi-node jobs stay physically adjacent on the wire.
  4. Sub-Second Multi-Thousand-Node Fan-Out: Instead of pushing thousands of individual container manifests through an HTTP API server and etcd, Slurm uses a hierarchical tree-based message fan-out (TreeWidth) to dispatch job steps across thousands of nodes in seconds.
Architectural DimensionSlurm (HPC / Bare-Metal AI)Default Kubernetes (Unextended)
Scheduling ModelAtomic gang scheduling + shadow-window backfillPod-by-pod eventual placement (requires Volcano/Kueue for gang scheduling)
Network Fabric PathBare-metal RDMA (ibverbs) directly to ConnectX HCAsCNI overlay by default; requires Multus + SR-IOV / RDMA device plugins
Topology PlacementBuilt-in topology/tree & topology/block switch matchingTopology-blind by default; requires custom topology scheduler plugins
Control Plane OverheadSingle active C daemon (slurmctld), tens of thousands of nodeskube-apiserver + etcd watch fan-out; typically sharded around 5,000 nodes
Best-Fit AI WorkloadMulti-week frontier pre-training, massive batch RLHF/SFTOnline LLM inference, microservices, elastic multi-tenant APIs

(We will explore how Kubernetes closes many of these gaps using NVIDIA GPU Operator, Volcano, and Kueue in Part 23.)


2. Anatomy of the Slurm Control Plane

Think of a Slurm cluster like an air traffic control tower coordinating a fleet of wide-body cargo jets. Rather than letting every pilot negotiate runway space independently, one ultra-fast central controller maintains the complete global state in memory while lightweight ground crews on each compute server enforce hardware boundaries.

Slurm Control Plane and GPU Execution Stack Figure 1: The four-tier Slurm bare-metal orchestration stack, from accounting and fair-share policy in slurmdbd down to rootless Pyxis/Enroot containers and NCCL RDMA collectives on compute nodes. Source: SchedMD Slurm Documentation & NVIDIA Pyxis/Enroot Reference Architecture.

The Three Core Daemons

  1. slurmctld (The Central Scheduler Brain): Runs on a dedicated controller node (with an active/standby backup configured via SlurmctldHost for high availability). It keeps the entire cluster state—every node, GPU count, memory footprint, switch link, and queued job—in RAM. Every few seconds (or immediately upon job completion), its scheduling loop evaluates pending jobs and assigns resources.
  2. slurmd and slurmstepd (Per-Node Compute Daemons): Every 8-GPU HGX compute server runs a single slurmd daemon. When slurmctld dispatches a job, slurmd spawns a dedicated slurmstepd shepherd process for that step, sets up Linux cgroups v2 to pin exact CPU cores, NUMA domains, RAM, and GPU devices, executes pre-flight health checks, and launches the training processes.
  3. slurmdbd (Accounting & Fair-Share Database Daemon): Sits in front of MySQL or MariaDB to record every completed GPU-hour, enforce organizational budgets, and feed decaying fair-share priority scores back to slurmctld. If Research Team A burned 80% of the cluster yesterday, priority/multifactor automatically lowers their queue priority today so Team B gets immediate access.

Partitions, QoS Tiers, and GRES (--gres=gpu:8)

Slurm organizes raw hardware into logical slices using three primitives:

  • Partitions: Logical queues grouping physical nodes (for example, pretrain for 128-node minimum runs, dev for interactive 1-node debugging with a 2-hour walltime, and scavenge for preemptible low-priority runs).
  • Quality of Service (QoS): Policy overlays that control priority boosts, maximum GPUs per user, and preemption rights (PreemptMode=REQUEUE). A frontier-high QoS can preempt scavenge jobs when an urgent pre-training run enters the queue.
  • Generic Resources (GRES): Slurm’s hardware plugin system for accelerators. In gres.conf, administrators map every physical GPU device (/dev/nvidia0 through /dev/nvidia7) to its exact host CPU socket (Cores=0-31) and PCIe affinity. When a user requests --gres=gpu:8 (or --gpus-per-node=8), slurmd isolates those GPUs via cgroups and exports CUDA_VISIBLE_DEVICES automatically.

Backfill Scheduling: Eliminating Giant-Job Head-of-Line Blocking

Without backfill, a strict priority queue destroys cluster utilization. Imagine a 1,024-GPU cluster where 800 GPUs are currently busy and 224 GPUs are idle. A top-priority 512-GPU pre-training job arrives at the head of the queue. It cannot start until 288 more GPUs finish in 45 minutes. Under naive FIFO, those 224 idle GPUs sit completely dark for 45 minutes—burning thousands of dollars of depreciated silicon and datacenter power—while dozens of 8-GPU evaluation jobs sit waiting behind the giant job.

Slurm’s sched/backfill plugin solves this with a shadow-window reservation:

  1. slurmctld inspects the highest-priority pending job (the 512-GPU run) and calculates its exact earliest start time based on the remaining --time walltimes of currently running jobs (45 minutes from now).
  2. It locks a virtual reservation for that giant job starting at T + 45 min.
  3. It then scans lower-priority jobs deeper in the queue. Any job that fits in the 224 currently idle GPUs and has a requested walltime under 45 minutes is immediately launched into the gap!

Because backfilled jobs are mathematically guaranteed to finish before T + 45 min, the 512-GPU job never suffers a single second of delay, while small evaluation, checkpoint-conversion, and debugging jobs get near-instant turnaround.


3. Topology-Aware Placement & Multi-Node NCCL Rendezvous

In a modern AI datacenter, all GPUs are not created equal in network distance. Two GPUs inside the same HGX node communicate over NVLink/NVSwitch at 900 GB/s to 1.8 TB/s. Two nodes plugged into the same InfiniBand Quantum leaf switch talk across a single network hop. Two nodes stranded on different leaf switches must climb up to the spine layer and back down across three hops, sharing oversubscribed or contention-prone spine uplinks with neighboring training jobs.

If a scheduler hands a 64-node training job 64 scattered nodes spread across 20 different leaf switches, every gradient synchronization step (AllReduce) saturates the spine tier, triggers adaptive-routing tail latency, and drags down Model FLOPs Utilization (MFU) by 15–25%.

Mapping the Physical Fabric with topology/tree

Slurm solves this via TopologyPlugin=topology/tree and a /etc/slurm/topology.conf file describing every switch and rack domain:

# Example /etc/slurm/topology.conf for a 2-tier InfiniBand Fat-Tree
SwitchName=ib-leaf-01 Nodes=dgx-[001-004]
SwitchName=ib-leaf-02 Nodes=dgx-[005-008]
SwitchName=ib-leaf-03 Nodes=dgx-[009-012]
SwitchName=ib-leaf-04 Nodes=dgx-[013-016]
SwitchName=ib-spine-01 Switches=ib-leaf-[01-04]

When a researcher submits a 4-node (32-GPU) job, slurmctld uses a best-fit switch search to pack all 4 nodes onto a single leaf switch (ib-leaf-01). Even better, users can enforce strict locality budgets directly in their submission script using --switches=1@00:30:00, telling Slurm: “Wait up to 30 minutes to place all my nodes under a single InfiniBand leaf switch; only relax to 2 switches if a single leaf does not free up in time.” On rack-scale GB200 NVL72 systems, Slurm 24.11+ extends this further with topology/block to align jobs cleanly onto 18-node (72-GPU) NVLink coherent blocks.

Launching 1,000+ Ranks: sbatch, srun, Pyxis/Enroot, and PMIx

Once slurmctld allocates topology-aligned nodes, how does your PyTorch training script actually bootstrap across 128 nodes without Docker daemon bottlenecks or fragile SSH loops?

flowchart TD
    A["1. Researcher submits sbatch script<br/>(--nodes=16 --gres=gpu:8 --switches=4)"] --> B["2. slurmctld evaluates priority/multifactor<br/>and topology/tree leaf-switch packing"]
    B --> C["3. Atomic gang allocation reserved;<br/>slurmd runs DCGM Prolog health check"]
    C --> D["4. Pyxis + Enroot mount squashfs<br/>PyTorch container rootlessly on all nodes"]
    D --> E["5. srun --mpi=pmix launches 128 ranks<br/>and exchanges RDMA endpoints via PMIx"]
    E --> F["6. NCCL forms NVLink + InfiniBand rings<br/>and begins synchronized training steps"]

    style A fill:#1e1b4b,stroke:#6366f1,stroke-width:2px,color:#ffffff
    style B fill:#0d2b45,stroke:#00e5ff,stroke-width:2px,color:#ffffff
    style C fill:#132a3e,stroke:#38bdf8,stroke-width:2px,color:#ffffff
    style D fill:#1a3d3c,stroke:#14b8a6,stroke-width:2px,color:#ffffff
    style E fill:#0f382c,stroke:#10b981,stroke-width:2px,color:#ffffff
    style F fill:#2e1065,stroke:#a855f7,stroke-width:2px,color:#ffffff

Figure 2: End-to-end execution lifecycle of a multi-node distributed PyTorch job from sbatch submission through rootless Enroot container startup and PMIx/NCCL rendezvous.

  • NVIDIA Enroot & Pyxis: Running dockerd as root on shared HPC clusters is a security and stability non-starter. Instead, Enroot converts OCI/Docker images (nvcr.io/nvidia/pytorch:24.10-py3) into immutable .sqsh (squashfs) files stored on shared Lustre/GPFS storage and unpacks them into unprivileged Linux user namespaces. Pyxis is a Slurm SPANK plugin that wires Enroot directly into srun via --container-image and --container-mounts flags.
  • PMIx (Process Management Interface for Exascale): Instead of relying on slow TCP rendezvous (torchrun hammering a single master node’s socket on port 29500 across 1,024 nodes), srun --mpi=pmix uses Slurm’s internal tree network to exchange rank identities, IP addresses, and InfiniBand Queue Pair (QP) metadata in parallel.

Here is a production-grade batch script (scripts/train_llama_16node.sbatch, submitted via sbatch scripts/train_llama_16node.sbatch) combining topology constraints, Pyxis containers, graceful checkpoint signals, and automatic requeue:

#!/bin/bash
# File: scripts/train_llama_16node.sbatch
# Execution: sbatch scripts/train_llama_16node.sbatch

#SBATCH --job-name=llama-pretrain-128gpu
#SBATCH --partition=pretrain
#SBATCH --qos=frontier-high
#SBATCH --nodes=16
#SBATCH --ntasks-per-node=8
#SBATCH --gpus-per-node=8
#SBATCH --cpus-per-task=16
#SBATCH --switches=4@00:30:00
#SBATCH --time=24:00:00
#SBATCH --signal=B:USR1@120
#SBATCH --requeue
#SBATCH --output=/mnt/lustre/logs/%x-%j.out

export MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)
export MASTER_PORT=29500
export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7
export NCCL_DEBUG=WARN
export TORCH_NCCL_ASYNC_ERROR_HANDLING=1

# Launch 128 ranks inside an immutable Enroot PyTorch squashfs image
srun --mpi=pmix \
  --container-image=/mnt/lustre/images/pytorch_24.10.sqsh \
  --container-mounts=/mnt/lustre/datasets:/data,/mnt/lustre/checkpoints:/ckpt \
  --kill-on-bad-exit=1 \
  python3 /workspace/train.py \
    --config /workspace/configs/70b_fsdp.yaml \
    --checkpoint-dir /ckpt/run_0190 \
    --auto-resume

Notice --kill-on-bad-exit=1: if a single rank crashes with a CUDA illegal memory access or HBM ECC error, Slurm immediately tears down all 127 sibling ranks instead of letting them burn idle GPU-hours waiting on a dead barrier.


4. Fault Tolerance, Node Draining, and Auto-Requeue at Scale

When you scale from 8 GPUs to 16,384 GPUs, hardware failure stops being an edge case and becomes a daily mathematical certainty. Meta’s Llama 3 405B engineering report documented 419 unexpected job interruptions over 54 days on a 16,384-GPU H100 cluster—roughly one hardware or network disruption every three hours—driven primarily by GPU HBM3 ECC faults, NVLink errors, and InfiniBand optical transceiver flaps.

If engineers had to manually SSH into failed nodes, inspect dmesg, cordon bad GPUs, and resubmit jobs, a frontier training run would spend half its life sitting idle. Production Slurm clusters automate the entire fault-recovery loop.

Automated Fault Recovery and Checkpoint Requeue Loop Figure 3: The four-stage self-healing pipeline connecting NVIDIA DCGM health checks, scontrol DRAIN quarantine, --signal checkpoint flushing, and --requeue resumption. Source: NVIDIA DCGM Documentation & Meta Llama 3 Infrastructure Engineering Practices.

1. Proactive Health Checks (DCGM + Prolog / Epilog)

Slurm supports three automated health hooks:

  • HealthCheckProgram: Runs periodically (e.g., every 5 minutes) across all nodes to query NVIDIA DCGM (dcgmi diag -r 1), check InfiniBand port states (ibstat), and scan kernel logs for fatal GPU XID errors (such as XID 79 GPU fallen off the bus, XID 94 contained ECC error, or XID 95 uncontained HBM ECC error).
  • Prolog: Runs on allocated nodes right before the training job starts, ensuring no job inherits a poisoned GPU state or leaked IPC memory from the previous tenant.
  • Epilog: Runs immediately after a job exits or crashes. If the job exited non-zero and DCGM flags a hardware fault, the Epilog quarantines the node automatically.

2. Quarantine via scontrol DRAIN (Preventing Black-Hole Nodes)

Without automatic draining, a single broken GPU node becomes a “black-hole node”: it fails a job in 10 seconds, becomes IDLE again, immediately grabs the next pending job from the queue, kills it in 10 seconds, and repeats until it drains the entire cluster queue.

When the Epilog or health check detects a fault on dgx-042, it executes:

scontrol update NodeName=dgx-042 State=DRAIN Reason="DCGM XID 95 uncontained HBM ECC"

The node transitions to DRAINED, immediately blocking any new job placements while preserving diagnostic logs for datacenter technicians or automated GPU reset scripts.

3. Graceful Preemption Signals & Automatic --requeue

For planned interruptions—such as walltime expiration or a frontier-high job preempting a lower-priority scavenge job—the flag #SBATCH --signal=B:USR1@120 instructs Slurm to send SIGUSR1 to the batch shell 120 seconds before termination. PyTorch’s signal handler catches SIGUSR1, finishes the current micro-batch, triggers an asynchronous sharded checkpoint save to Lustre/GPFS, and exits cleanly. Because #SBATCH --requeue is set, slurmctld automatically places the job back into the queue with its preserved priority, assigns a healthy replacement node from the hot-spare pool, and resumes training from the latest step with zero human intervention.


5. Simulation: Naive Fragmented Placement vs. Slurm topology/tree + Backfill

To quantify exactly how much performance topology-aware placement and backfill scheduling recover, we built a zero-dependency Python 3 discrete-event simulator (scripts/slurm_topology_scheduler_sim.py).

Cluster & Workload Model

  • Physical Cluster: 64 GPU compute nodes (512 GPUs total) arranged across 16 InfiniBand leaf switches (4 nodes / 32 GPUs per leaf switch) under a 2-tier fat-tree spine.
  • Mixed AI Workload: 60 deterministic jobs spanning giant frontier pre-training runs (32 nodes / 256 GPUs and 16 nodes / 128 GPUs), mid-sized SFT/RLHF runs (4–8 nodes), and short evaluation/debugging probes (1–2 nodes).
  • Policies Compared:
    1. Naive FIFO + Fragmented: Strict arrival-order queue with topology-blind node assignment across scattered leaf switches.
    2. Slurm topology/tree (FIFO): Priority-ordered queue with best-fit leaf-switch packing to minimize cross-spine hops, but no backfill.
    3. Slurm topology/tree + Backfill: Best-fit leaf-switch packing combined with shadow-window backfill so short jobs slip into idle gaps without delaying giant training runs.

Placement Strategy Impact on a 512-GPU InfiniBand Cluster Figure 4: Verified simulation comparison across 60 mixed AI training and evaluation jobs on a 64-node (512-GPU) 16-leaf InfiniBand cluster.

Verified Simulation Results

Running python3 scripts/slurm_topology_scheduler_sim.py produces the exact metrics below:

Scheduling PolicyEffective GoodputAvg Leaf Switches (Multi-Node)Cross-Spine Ring RatioAvg AllReduce Step PenaltyMean Queue WaitTotal MakespanBackfilled Jobs
Naive FIFO + Fragmented62.4%7.4091.0%23.64%301.0 min853 min0
Slurm topology/tree (FIFO)92.2%2.6012.2%0.98%308.4 min577 min0
Slurm topology/tree + Backfill92.2%2.6012.2%0.98%274.3 min577 min4

Three Key Engineering Takeaways

  1. Fragmented Placement Silently Destroys 30% of Cluster Goodput: Under naive scattered allocation, multi-node jobs span an average of 7.40 leaf switches, forcing 91.0% of inter-node ring collectives across the spine tier and inflicting a 23.64% AllReduce step penalty. Even when GPUs appear “busy,” effective training goodput collapses to 62.4% and total makespan stretches to 853 minutes.
  2. topology/tree Recovers Massive Network Bandwidth: Best-fit leaf packing cuts average switch spread by nearly 3x (7.40 down to 2.60 leaves), slashes cross-spine traffic from 91.0% to 12.2%, and reduces AllReduce overhead to just 0.98%. That single scheduler policy lifts effective goodput to 92.2% and finishes the entire 60-job workload 276 minutes faster (-32.4% makespan).
  3. Backfill Eliminates Priority Queue Wait Penalties: Notice that switching from Naive FIFO to Priority FIFO slightly increased average wait time (301.0 min to 308.4 min) because giant high-priority 256-GPU jobs blocked smaller evaluation runs behind them. Enabling Slurm Backfill slipped 4 short jobs into idle shadow windows, cutting mean queue wait time by 34.1 minutes (-11.1%) down to 274.3 min while keeping the 256-GPU frontier runs 100% on schedule.
Click to expand runnable code script
#!/usr/bin/env python3
"""
Zero-Dependency Python 3 Simulator: Slurm Topology-Aware & Backfill GPU Scheduler

Models a 64-node (512-GPU) InfiniBand fat-tree cluster (16 leaf switches x 4 nodes/leaf
x 8 GPUs/node) running a realistic mixed AI training workload. Compares three policies:
  1. Naive FIFO + Fragmented Placement (head-of-line blocking, topology-blind)
  2. Slurm topology/tree (best-fit leaf-switch packing, strict FIFO)
  3. Slurm topology/tree + Backfill (leaf packing + gap-filling without delaying reservations)
"""

from dataclasses import dataclass
import random
from typing import Dict, List, Tuple


NUM_LEAVES = 16
NODES_PER_LEAF = 4
GPUS_PER_NODE = 8
TOTAL_NODES = NUM_LEAVES * NODES_PER_LEAF  # 64 nodes = 512 GPUs


@dataclass
class Job:
    job_id: int
    name: str
    nodes_req: int
    base_runtime_min: int
    submit_time: int
    priority: int  # higher = more urgent


@dataclass
class CompletedJob:
    job: Job
    start_time: int
    end_time: int
    assigned_nodes: List[int]
    switches_used: int
    optimal_switches: int
    cross_spine_ratio: float
    allreduce_penalty_pct: float
    backfilled: bool


def node_to_leaf(node_id: int) -> int:
    return node_id // NODES_PER_LEAF


def generate_workload(seed: int = 42, num_jobs: int = 60) -> List[Job]:
    """Generate a realistic heavily-loaded frontier AI cluster job trace."""
    rng = random.Random(seed)
    jobs: List[Job] = []
    t = 0
    profiles = [
        ("frontier-pretrain", 32, (80, 130), 100, 0.12),   # 256 GPUs (8 full leaves)
        ("large-pretrain", 16, (60, 100), 85, 0.16),       # 128 GPUs (4 full leaves)
        ("mid-sft", 8, (40, 75), 70, 0.18),                # 64 GPUs (2 full leaves)
        ("rlhf-run", 4, (25, 55), 55, 0.20),               # 32 GPUs (1 full leaf)
        ("eval-sweep", 2, (10, 24), 40, 0.16),             # 16 GPUs (half leaf)
        ("debug-probe", 1, (6, 16), 30, 0.18),             # 8 GPUs (1 node)
    ]
    weights = [p[4] for p in profiles]

    for jid in range(1, num_jobs + 1):
        choice = rng.choices(profiles, weights=weights, k=1)[0]
        label, nodes_req, (r_min, r_max), prio, _ = choice
        runtime = rng.randint(r_min, r_max)
        if jid > 1:
            t += rng.randint(1, 6)
        jobs.append(
            Job(
                job_id=jid,
                name=f"{label}-{jid:02d}",
                nodes_req=nodes_req,
                base_runtime_min=runtime,
                submit_time=t,
                priority=prio,
            )
        )
    return jobs


def compute_topology_metrics(
    assigned_nodes: List[int],
) -> Tuple[int, int, float, float]:
    """Compute switch spread, cross-spine traffic ratio, and AllReduce step penalty."""
    n = len(assigned_nodes)
    if n <= 1:
        return 1, 1, 0.0, 0.0

    leaf_counts: Dict[int, int] = {}
    for nd in assigned_nodes:
        lf = node_to_leaf(nd)
        leaf_counts[lf] = leaf_counts.get(lf, 0) + 1

    switches_used = len(leaf_counts)
    optimal_switches = (n + NODES_PER_LEAF - 1) // NODES_PER_LEAF

    if switches_used == 1:
        cross_spine_ratio = 0.0
    else:
        cross_spine_ratio = min(1.0, switches_used / float(n))

    extra_switches = max(0, switches_used - optimal_switches)
    base_spine_overhead = 2.0 if switches_used > 1 else 0.0
    penalty_pct = base_spine_overhead + (extra_switches * 4.5)
    return switches_used, optimal_switches, cross_spine_ratio, penalty_pct


def pick_nodes_fragmented(
    free_nodes: List[int], count: int, rng: random.Random
) -> List[int]:
    """Topology-blind allocation: picks scattered free nodes across leaf switches."""
    strided = sorted(free_nodes, key=lambda nd: (nd % NODES_PER_LEAF, nd // NODES_PER_LEAF))
    return strided[:count]


def pick_nodes_topology_tree(free_nodes: List[int], count: int) -> List[int]:
    """Slurm topology/tree best-fit leaf-switch packing."""
    by_leaf: Dict[int, List[int]] = {}
    for nd in sorted(free_nodes):
        lf = node_to_leaf(nd)
        by_leaf.setdefault(lf, []).append(nd)

    single_leaf_candidates = [
        (len(nds), lf, nds) for lf, nds in by_leaf.items() if len(nds) >= count
    ]
    if single_leaf_candidates:
        single_leaf_candidates.sort(key=lambda x: (x[0], x[1]))
        return single_leaf_candidates[0][2][:count]

    leaves_desc = sorted(by_leaf.items(), key=lambda x: (-len(x[1]), x[0]))
    selected: List[int] = []
    for _, nds in leaves_desc:
        need = count - len(selected)
        if need <= 0:
            break
        selected.extend(nds[:need])
    return selected


def simulate(
    jobs: List[Job], policy: str
) -> Tuple[List[CompletedJob], Dict[str, float]]:
    """Discrete-event minute-by-minute cluster simulation."""
    rng = random.Random(99)
    pending = sorted(jobs, key=lambda j: (j.submit_time, j.job_id))
    queue: List[Job] = []
    running: List[Tuple[int, Job, List[int], bool, Tuple[int, int, float, float]]] = []
    completed: List[CompletedJob] = []

    free_nodes = set(range(TOTAL_NODES))
    busy_node_minutes = 0
    now = 0
    next_pending_idx = 0

    def allocate_and_start(job: Job, backfilled: bool) -> None:
        free_list = sorted(free_nodes)
        if policy == "naive_fifo":
            chosen = pick_nodes_fragmented(free_list, job.nodes_req, rng)
        else:
            chosen = pick_nodes_topology_tree(free_list, job.nodes_req)

        for nd in chosen:
            free_nodes.remove(nd)

        metrics = compute_topology_metrics(chosen)
        penalty_pct = metrics[3]
        effective_runtime = int(round(job.base_runtime_min * (1.0 + penalty_pct / 100.0)))
        end_t = now + max(1, effective_runtime)
        running.append((end_t, job, chosen, backfilled, metrics))

    def estimate_earliest_start(nodes_needed: int) -> int:
        if len(free_nodes) >= nodes_needed:
            return now
        avail = len(free_nodes)
        for end_t, _, nds, _, _ in sorted(running, key=lambda r: r[0]):
            avail += len(nds)
            if avail >= nodes_needed:
                return end_t
        return now + 10_000

    while next_pending_idx < len(pending) or queue or running:
        still_running = []
        for item in running:
            end_t, job, chosen, backfilled, metrics = item
            if end_t <= now:
                for nd in chosen:
                    free_nodes.add(nd)
                completed.append(
                    CompletedJob(
                        job=job,
                        start_time=end_t - max(1, int(round(job.base_runtime_min * (1.0 + metrics[3] / 100.0)))),
                        end_time=end_t,
                        assigned_nodes=chosen,
                        switches_used=metrics[0],
                        optimal_switches=metrics[1],
                        cross_spine_ratio=metrics[2],
                        allreduce_penalty_pct=metrics[3],
                        backfilled=backfilled,
                    )
                )
            else:
                still_running.append(item)
        running = still_running

        while next_pending_idx < len(pending) and pending[next_pending_idx].submit_time <= now:
            queue.append(pending[next_pending_idx])
            next_pending_idx += 1

        if policy != "naive_fifo":
            queue.sort(key=lambda j: (-j.priority, j.submit_time, j.job_id))
        else:
            queue.sort(key=lambda j: (j.submit_time, j.job_id))

        while queue and len(free_nodes) >= queue[0].nodes_req:
            job = queue.pop(0)
            allocate_and_start(job, backfilled=False)

        if policy == "slurm_topo_backfill" and queue:
            head_job = queue[0]
            shadow_start = estimate_earliest_start(head_job.nodes_req)
            nodes_freed_by_shadow = sum(
                len(nds) for end_t, _, nds, _, _ in running if end_t <= shadow_start
            )
            surplus_at_shadow = (len(free_nodes) + nodes_freed_by_shadow) - head_job.nodes_req

            idx = 1
            while idx < len(queue):
                cand = queue[idx]
                if len(free_nodes) >= cand.nodes_req:
                    est_end = now + int(round(cand.base_runtime_min * 1.10))
                    if est_end <= shadow_start:
                        queue.pop(idx)
                        allocate_and_start(cand, backfilled=True)
                        continue
                    elif cand.nodes_req <= surplus_at_shadow:
                        queue.pop(idx)
                        allocate_and_start(cand, backfilled=True)
                        surplus_at_shadow -= cand.nodes_req
                        continue
                idx += 1

        if running or queue or next_pending_idx < len(pending):
            busy_node_minutes += (TOTAL_NODES - len(free_nodes))
            now += 1

    makespan = max(c.end_time for c in completed)
    utilization_pct = (busy_node_minutes / float(makespan * TOTAL_NODES)) * 100.0
    useful_node_minutes = sum(c.job.nodes_req * c.job.base_runtime_min for c in completed)
    goodput_util_pct = (useful_node_minutes / float(makespan * TOTAL_NODES)) * 100.0

    multi_node = [c for c in completed if c.job.nodes_req > 1]
    avg_switches = sum(c.switches_used for c in multi_node) / len(multi_node)
    avg_opt_switches = sum(c.optimal_switches for c in multi_node) / len(multi_node)
    avg_cross_spine_pct = (sum(c.cross_spine_ratio for c in multi_node) / len(multi_node)) * 100.0
    avg_penalty_pct = sum(c.allreduce_penalty_pct for c in multi_node) / len(multi_node)
    mean_wait = sum(c.start_time - c.job.submit_time for c in completed) / len(completed)
    backfilled_count = sum(1 for c in completed if c.backfilled)

    summary = {
        "makespan_min": float(makespan),
        "gpu_util_pct": utilization_pct,
        "goodput_util_pct": goodput_util_pct,
        "avg_switches_multinode": avg_switches,
        "avg_opt_switches": avg_opt_switches,
        "cross_spine_ratio_pct": avg_cross_spine_pct,
        "avg_allreduce_penalty_pct": avg_penalty_pct,
        "mean_queue_wait_min": mean_wait,
        "backfilled_jobs": float(backfilled_count),
    }
    return completed, summary


def main() -> None:
    jobs = generate_workload(seed=42, num_jobs=60)
    print(f"Cluster: {TOTAL_NODES} nodes ({TOTAL_NODES * GPUS_PER_NODE} GPUs) | "
          f"{NUM_LEAVES} InfiniBand leaf switches ({NODES_PER_LEAF} nodes/leaf)")
    print(f"Workload: {len(jobs)} mixed AI training/eval jobs\n")

    policies = [
        ("naive_fifo", "Naive FIFO + Fragmented"),
        ("slurm_topo_fifo", "Slurm topology/tree (FIFO)"),
        ("slurm_topo_backfill", "Slurm topology/tree + Backfill"),
    ]

    header = (
        f"{'Policy':<32} | {'Goodput':>8} | {'Avg Leaf':>8} | "
        f"{'Cross-Spine':>11} | {'AllReduce Pen':>13} | {'Avg Wait':>9} | "
        f"{'Makespan':>8} | {'Backfill':>8}"
    )
    print(header)
    print("-" * len(header))

    for key, label in policies:
        _, s = simulate(jobs, key)
        print(
            f"{label:<32} | "
            f"{s['goodput_util_pct']:>7.1f}% | "
            f"{s['avg_switches_multinode']:>8.2f} | "
            f"{s['cross_spine_ratio_pct']:>10.1f}% | "
            f"{s['avg_allreduce_penalty_pct']:>12.2f}% | "
            f"{s['mean_queue_wait_min']:>7.1f} m | "
            f"{s['makespan_min']:>6.0f} m | "
            f"{int(s['backfilled_jobs']):>8d}"
        )


if __name__ == "__main__":
    main()

Frequently Asked Questions

Why not just run Docker directly on Slurm compute nodes?

Answer The standard Docker daemon (`dockerd`) runs with root privileges, introduces an extra process layer outside Slurm's `cgroups v2` resource tracking, and creates severe I/O storms when hundreds of nodes pull container layers simultaneously. By contrast, NVIDIA Enroot + Pyxis mounts pre-built `.sqsh` squashfs images from shared Lustre/GPFS storage completely unprivileged, inheriting Slurm's exact GPU GRES isolation, CPU affinity, and RDMA device mappings with near-zero startup overhead.

Why is specifying an accurate --time walltime critical for Slurm backfill?

Answer Slurm's `sched/backfill` engine relies strictly on each job's requested `--time` limit to calculate whether it can finish before the highest-priority pending job's reserved shadow-window start time. If a researcher submits a 20-minute evaluation script but lazily sets `--time=72:00:00`, Slurm cannot prove the job will finish inside a 45-minute idle gap—so the job misses backfill and sits stuck in the queue for hours.
Answer On NVL72 racks, 18 compute trays (72 GPUs) share a single coherent NVLink Switch fabric that is dramatically faster than cross-rack InfiniBand. Modern Slurm deployments use `TopologyPlugin=topology/block` (alongside `topology/tree`) to define each 18-node NVL72 rack as a fixed scheduling block, ensuring 72-GPU tensor-parallel and expert-parallel domains stay strictly inside one physical rack before scaling out across InfiniBand.

Can Slurm serve real-time LLM inference APIs alongside batch training?

Answer While you can technically launch a long-running vLLM or SGLang server inside an `sbatch` job, Slurm lacks native HTTP ingress routing, L7 load balancing, health-probe-driven pod autoscaling, and zero-downtime rolling upgrades. Most AI organizations therefore split their fleet—or use hybrid architectures like Slurm-on-Kubernetes (Slinky)—keeping Slurm dedicated to massive synchronous training while running online inference on Kubernetes.

What’s Next

Slurm excels at packing 16,000 bare-metal GPUs into synchronous training jobs with minimal jitter—but modern AI platforms also need elastic inference autoscaling, multi-tenant microservice isolation, declarative GitOps, and unified serving-plus-training clusters.

In Part 23: AI Job Orchestration II: Kubernetes, NVIDIA GPU Operator, and Volcano / Kueue, we cross over to the cloud-native side of the stack and dissect how Kubernetes bridges the HPC gap with device plugins, DRA (Dynamic Resource Allocation), gang scheduling via Volcano and Kueue, and RDMA networking via Multus and SR-IOV.