#!/bin/bash -l

# Script for running a PyTorch application on multiple nodes using torchrun.

# Set Slurm directives to define job requirements.
#SBATCH --job-name=multinode  # name that identifies job in queue
#SBATCH --output=%x_%j.log    # output file name, formed from job name and id
#SBATCH --account=my_account  # account to which resource usage is to be debited
#SBATCH --partition=mi355x    # cluster partition to be used
#SBATCH --nodes=2             # number of nodes to be allocated
#SBATCH --gres=gpu:8          # number of GPUs to be allocated per node;
                              # must be all GPUs if using more than 1 node
#SBATCH --time=00:30:00       # run-time limit (HH:MM:SS)


# Initialise timing.
T1=$SECONDS
echo "Job start on $(hostname): $(date)"

# Exit at first failure.
set -e

# Perform environment setup.
module purge
module load rhel9/default-amdgpu-zenith
module load openmpi

source /path/to/user/script/for/pytorch/setup

# Set PyTorch global variables.
export WORLD_SIZE=$((SLURM_NNODES * SLURM_GPUS_ON_NODE))
export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
export MASTER_PORT=$(((SLURM_JOB_ID % 10000) + 50000))

# Define command to set PyTorch variables for an individual process.
RUNTIME_SETUP="export RANK=\$PMI_RANK LOCAL_RANK=\$SLURM_LOCALID"

# Define Python script to run, together with its arguments.
# For multinode.py, the positional arguments are
# number of epochs and number of epochs between checkpoints.
TO_RUN="multinode.py 10000 100 --batch_size 32"

# Define command to launch PyTorch application for all GPUS of a single node.
TORCHRUN_LAUNCH="bash -c '$RUNTIME_SETUP; torchrun --nnodes ${SLURM_NNODES} --nproc_per_node ${SLURM_GPUS_ON_NODE} --rdzv-backend=c10d --rdzv-endpoint=${MASTER_ADDR}:${MASTER_PORT} ${TO_RUN}'"

# Define command to launch PyTorch application for all nodes and GPUs.
SRUN_TORCHRUN_LAUNCH="srun --nodes=${SLURM_NNODES} --ntasks-per-node=1 ${TORCHRUN_LAUNCH}"

# Launch and time PyTorch application for all nodes and GPUs.
T2=$SECONDS
echo ""
echo "PyTorch distributed processing start:" 
echo "$SRUN_TORCHRUN_LAUNCH"
echo ""
eval "$SRUN_TORCHRUN_LAUNCH"
echo ""
echo "PyTorch processing completed: $(date)"
echo "Run time: $((SECONDS - T2)) seconds"
echo ""
echo "Job time: $((SECONDS - T1)) seconds"
