
Run Megatron-LM on SLURM
OfficialFreeEfficiently launch Megatron-LM training jobs on SLURM clusters.
Free · Opens the source repo
What Run Megatron-LM on SLURM does
The Run Megatron-LM on SLURM skill provides a comprehensive guide for launching distributed training jobs of the Megatron-LM model on SLURM clusters. It includes a minimal sbatch script template and essential environment variable configurations necessary for setting up torch.distributed.run. This skill is particularly useful for developers and researchers working with large-scale language models who require efficient resource management and job submission on SLURM-managed GPU clusters.
The skill covers critical aspects such as the correct setup of CUDA_DEVICE_MAX_CONNECTIONS based on the hardware configuration, ensuring that the training process runs smoothly without encountering common pitfalls. It emphasizes the importance of using a shared filesystem for code and data access across nodes, which is crucial for multi-node training scenarios. Additionally, it provides monitoring commands to track job status and diagnose potential issues during training.
For those already familiar with SLURM and Megatron-LM, this skill serves as a valuable reference to streamline the setup process, reduce errors, and enhance productivity. It is particularly aimed at data scientists, machine learning engineers, and researchers who are involved in training large models and need to utilize distributed computing resources effectively.
By following the guidelines provided in this skill, users can avoid common mistakes such as improper environment setups and local path issues, ensuring that their training jobs are executed efficiently and effectively on SLURM clusters.
When to use it
Use this skill when you need to set up and run Megatron-LM training jobs on a SLURM cluster, especially in distributed environments.
When not to use it
This skill is not suitable for users who are not using SLURM for job scheduling or those who are not working with Megatron-LM.
What you can build with it
Launching a Training Job
Use this skill to create and submit an sbatch script for training Megatron-LM on your SLURM cluster.
Monitoring Job Progress
Utilize the provided monitoring commands to check the status of your SLURM jobs and diagnose issues.
Configuring Multi-Node Training
Follow the guidelines to set up a multi-node training environment, ensuring all nodes can access shared resources.
How to install Run Megatron-LM on SLURM
View source1. Install with the skills CLI
npx skills add nvidia/skills/mcore-run-on-slurm --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by nvidiaRun Megatron-LM on SLURM
Answer-First Constants
For text-only SLURM setup questions, answer with these constants before the full script:
- Submit from a shared worktree path visible to every node;
cdthere in the script before launching training. - Use one
sruntask per node and launch workers withuv run python -m torch.distributed.run, not baretorchrun. - Set
MASTER_ADDRfromscontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1, setMASTER_PORT,NNODES=${SLURM_NNODES},GPUS_PER_NODE=<GPUS_PER_NODE>, andWORLD_SIZE=$((NNODES * GPUS_PER_NODE)). - Pass
--nnodes,--nproc-per-node,--node-rank,--master-addr, and--master-porttotorch.distributed.run. CUDA_DEVICE_MAX_CONNECTIONS: pre-Blackwell Hopper/Ampere with TP>1 or CP>1 and non-FSDP uses1; Blackwell/GB200 does not need it; Torch-FSDP2 or Megatron-FSDP must not use1;overlap_moe_expert_parallel_commuses32.
Prerequisites
- A SLURM cluster login with submission rights to a GPU partition.
- Megatron-LM checked out on a filesystem visible to all nodes in the allocation (NFS, Lustre, or similar). All nodes must reach the same paths for code, data, checkpoints, and output.
uvinstalled; runuv sync --extra training --extra dev(or--extra lts) on the worktree once before submission so the.venvis materialized and visible to every node.
Minimal sbatch script
Save as run_megatron.slurm in the worktree:
#!/bin/bash
#SBATCH --job-name=megatron
#SBATCH --account=<SLURM_ACCOUNT>
#SBATCH --partition=<SLURM_PARTITION>
#SBATCH --nodes=<NODES>
#SBATCH --ntasks-per-node=1
#SBATCH --gpus-per-node=<GPUS_PER_NODE>
#SBATCH --time=<HH:MM:SS>
#SBATCH --output=logs/%x-%j.out
#SBATCH --error=logs/%x-%j.err
set -euo pipefail
cd <MEGATRON_WORKTREE>
export MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1)
export MASTER_PORT=${MASTER_PORT:-29500}
export NNODES=${SLURM_NNODES}
export GPUS_PER_NODE=<GPUS_PER_NODE>
export WORLD_SIZE=$((NNODES * GPUS_PER_NODE))
# Set CUDA_DEVICE_MAX_CONNECTIONS only when your configuration requires it
# (see the section below). Example for pre-Blackwell with TP>1 or CP>1
# (non-FSDP):
# export CUDA_DEVICE_MAX_CONNECTIONS=1
srun --ntasks=${NNODES} --ntasks-per-node=1 bash -c '
# NODE_RANK comes from SLURM_NODEID with one task per node.
NODE_RANK=${SLURM_NODEID}
uv run python -m torch.distributed.run \
--nnodes='"${NNODES}"' \
--nproc-per-node='"${GPUS_PER_NODE}"' \
--node-rank=${NODE_RANK} \
--master-addr='"${MASTER_ADDR}"' \
--master-port='"${MASTER_PORT}"' \
pretrain_gpt.py \
<MEGATRON_ARGS>
'
Submit:
mkdir -p logs && JOB_ID=$(sbatch --parsable run_megatron.slurm)
echo "Submitted ${JOB_ID}"
Multi-node rules
- Submit from the worktree you intend to run, or
cdto it in the script. All nodes must reach the same path on a shared filesystem (NFS, Lustre, or similar) — node-local paths will not be visible to peer ranks. - Use one
torchrunworker group across all nodes; do not start independent single-node jobs. --nproc-per-nodeshould equal the number of visible GPUs per node.- Write checkpoints, tensorboard data, and structured logs to shared storage.
CUDA_DEVICE_MAX_CONNECTIONS
The right value depends on your hardware and parallelism mode. Do not export it unconditionally:
- Pre-Blackwell (Hopper, Ampere) with TP>1 or CP>1, non-FSDP: set to
1. The relevant code path asserts on this — you will get an assertion error if it is not1, not a silent deadlock. - Blackwell: not required; setting it has no effect.
- Torch-FSDP2 or Megatron-FSDP: must NOT be
1. Leave the env var unset, or set it to a value greater than1. overlap_moe_expert_parallel_commenabled: set to32.
Set it explicitly in the sbatch script when your configuration calls for it.
Containers
Many sites run Megatron-LM inside a container (enroot/pyxis on some clusters, singularity on others). If you do, the uv-managed .venv must live on a path that is visible from inside the container, and the container image must provide the CUDA / NCCL / torch versions the repo expects (see docker/.ngc_version.dev and .ngc_version.lts). The skeleton above stays the same; wrap the srun invocation with your scheduler's container flags (--container-image=…, --container-mounts=…, etc.).
Monitor and collect
squeue -j "$JOB_ID" -o "%.10i %.8T %.10M %.6D %R"
sacct -j "$JOB_ID" --format=JobID,State,ExitCode,Elapsed
scancel "$JOB_ID"
If your training script writes a result artifact (a JSON metrics file from rank 0, a final checkpoint, etc.), poll for the artifact rather than waiting only on squeue state. Useful output usually appears before SLURM marks the job complete, and polling on the artifact lets you cancel the job as soon as it lands instead of holding the allocation until the timeout.
Failure diagnosis
Scan stderr from every rank, not just rank 0. The earliest non-NCCL Python traceback is usually the root cause; later NCCL timeouts on other ranks are downstream symptoms of the first crash.
Classify quickly:
- OOM: record rank, phase (forward / backward / optimizer), batch size, sequence length, parallelism (TP/DP/CP/PP), and peak memory before adjusting.
- Shape / divisibility error: check
WORLD_SIZE = TP × DP × CP × PPand head-count divisibility (num_attention_heads % TP == 0). - Import error: wrong worktree, missing
uv sync, or stalePYTHONPATH. Confirmcd <MEGATRON_WORKTREE>before launch. - NCCL failure with no Python traceback: verify allocation, port reachability,
MASTER_ADDRresolution, and command consistency across ranks.
Common pitfalls
- Forgetting
uv syncbefore the first submission. If the venv is missing, every job rebuilds it from insidesrun, costing minutes per job. - Writing logs to a node-local path that disappears at job exit. Always write to the shared filesystem.
- Setting
CUDA_DEVICE_MAX_CONNECTIONS=1blindly. The right value depends on hardware and parallelism mode (see the dedicated section above). Setting it to1with FSDP causes a different problem; on Blackwell it has no effect; on pre-Blackwell with TP>1 or CP>1 (non-FSDP) the code asserts, it does not deadlock. - Running bare
torchruninstead ofuv run python -m torch.distributed.run. Baretorchrunmay dispatch through a python interpreter that does not see venv packages, depending on how the venv is set up.
Frequently asked questions about Run Megatron-LM on SLURM
Similar skills
Turborepo
Optimized build system for JavaScript/TypeScript monorepos.
Azure Pipelines Validation
Streamline your Azure DevOps pipeline changes locally.
Azure Developer CLI
Streamline your Azure project workflows with best practices.
Azure Container Registry CLI
Manage Azure Container Registry resources with ease.
Aspire
Build and orchestrate polyglot distributed applications seamlessly.
Vercel CLI
Manage and deploy Vercel projects from the command line.
