Run LLM experiments with persistent containers using Apptainer on Yale’s Slurm cluster with up to 4 H100 GPUs and multi-node support.
📦 Why Use Apptainer on HPC?
Apptainer (formerly Singularity) is ideal for running containers on multi-user, GPU-accelerated, Slurm-managed clusters where Docker is not allowed.
| Feature | Docker | Apptainer (Singularity) |
|---|---|---|
| Rootless containers | ❌ No | ✅ Yes |
| Works on HPC clusters | ❌ Not allowed | ✅ Designed for HPC |
| Persistent named containers | ✅ Yes (docker create) | ✅ Yes (apptainer instance) |
| GPU support | ✅ --gpus all | ✅ --nv |
| User home directory bind | Manual bind required | Defaults to bind $HOME |
| Docker image support | ✅ Yes | ✅ Pulls Docker images |
🧱 Apptainer Commands Reference
Instances (Like Docker containers)
apptainer instance start [options] <image> <instance_name> # Create & start instance
apptainer shell instance://<name> # Connect (like docker exec -it)
apptainer exec instance://<name> <command> # Run command
apptainer instance list # List active instances
apptainer instance stop <name> # StopOne-Time Execution (Like docker run)
apptainer run <image>
apptainer exec --nv --bind $PWD:/workspace <image> python script.py
apptainer shell <image>Build or Pull Images
apptainer pull verl.sif docker://hiyouga/verl:tag
apptainer build verl.sif docker://hiyouga/verl:tag🔧 Step 1: Directory Setup and Smart Cache
Project Directories
# Code and scripts
mkdir -p /gpfs/radev/home/zy279/project/llm_docker_space
# Datasets, checkpoints, model weights
mkdir -p /gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storageSmart Cache Selection
if [ -d "/dev/shm" ] && [ $(df /dev/shm | tail -1 | awk '{print $4}') -gt 10485760 ]; then
export APPTAINER_CACHEDIR=/dev/shm/.apptainer_cache_$USER
else
export APPTAINER_CACHEDIR=/gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage/apptainer_cache
fi
mkdir -p $APPTAINER_CACHEDIR
# Optional: persist in shell
echo 'export APPTAINER_CACHEDIR=/dev/shm/.apptainer_cache_$USER' >> ~/.bashrc🛠️ Step 2: Build the Container Image
Run this once (CPU only — no GPUs needed):
srun --partition=general --mem=32G --time=2:00:00 --pty bash
apptainer build /gpfs/radev/home/zy279/project/llm_docker_space/containers/verl.sif \
docker://hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.4-flashinfer0.2.2-cxx11abi0Fallback (if general nodes busy):
srun --partition=gpu --gres=gpu:a40:1 --mem=32G --time=2:00:00 --pty bash🚀 Step 3: Create the Container (Single Node)
Interactive script:
# Request node
srun --partition=gpu --gres=gpu:h200:4 --mem=256G --time=48:00:00 --ntasks=3 --cpus-per-task=96 --pty bash
# Start container
apptainer instance start --nv \
--bind /gpfs/radev/home/zy279/project/llm_docker_space:/workspace \
--bind /gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage:/storage \
--writable-tmpfs \
/gpfs/radev/home/zy279/project/llm_docker_space/containers/verl.sif \
llm_container
# Connect
apptainer shell instance://llm_container
📝 Script: create_container.sh
#!/bin/bash
GPU_TYPE="h100"
GPU_COUNT=4
MEMORY="256G"
TIME="48:00:00"
WORKSPACE="/gpfs/radev/home/zy279/project/llm_docker_space"
STORAGE="/gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage"
SIF="$WORKSPACE/containers/verl.sif"
NAME="llm_container"
CACHE="$STORAGE/apptainer_cache"
export APPTAINER_CACHEDIR=$CACHE
mkdir -p $CACHE
if apptainer instance list | grep -q "$NAME"; then
echo "Container '$NAME' already running."
exit 0
fi
apptainer instance start --nv \
--bind $WORKSPACE:/workspace \
--bind $STORAGE:/storage \
--writable-tmpfs \
$SIF $NAME
echo "Container $NAME started."✅ Usage:
srun --partition=gpu --gres=gpu:h100:8 --mem=256G --time=48:00:00 --cpus-per-task=96 --pty bash
./create_container.sh
apptainer shell instance://llm_container🌐 Step 3’: Multi-Node Setup (2 Nodes × 4 GPUs)
📝 Script: create_multinode_container.sh
#!/bin/bash
NODES=2
GPU_PER_NODE=4
WORKSPACE="/gpfs/radev/home/zy279/project/llm_docker_space"
STORAGE="/gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage"
SIF="$WORKSPACE/containers/verl.sif"
NAME="llm_container_multinode"
CACHE="$STORAGE/apptainer_cache"
export APPTAINER_CACHEDIR=$CACHE
mkdir -p $CACHE
srun --partition=gpu --nodes=$NODES --gres=gpu:h100:$GPU_PER_NODE \
--mem=128G --time=48:00:00 --pty bash -c "
apptainer instance start --nv \
--bind $WORKSPACE:/workspace \
--bind $STORAGE:/storage \
--writable-tmpfs \
$SIF $NAME;
apptainer shell instance://$NAME"🧪 Step 4: Inside the Container (One-Time Setup)
Modify the pip directory to make sure that pip install packages to the scratch partition
# Create directories if they don't exist
# Set conda to use storage for everything
export PIP_USER=false
export PIP_CACHE_DIR=/storage/pip_cache
export PYTHONUSERBASE=/storage/python_packages
export PATH="/storage/python_packages/bin:$PATH"
export PYTHONPATH="/storage/python_packages/lib/python3.11/site-packages:$PYTHONPATH"
# Create directories
mkdir -p /storage/pip_cache
mkdir -p /storage/python_packages
# Now run your pip install commands
pip install your_package_name
# Or your requirements.txt
# pip install -r requirements.txtInstall VERL-Agent
# Clone verl-agent to workspace (code)
cd /workspace
git clone https://github.com/langfengQ/verl-agent.git
# Install verl-agent packages to storage (large files)
cd /workspace/verl-agent
pip3 install --user --cache-dir /storage/pip_cache -e .[vllm]
# Test installation
python -c "import verl; print('VERL-agent installed to storage!')"Install Claude Code and other other packages
# Install dev tools
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc && nvm install --lts && nvm use --lts
npm install -g @anthropic-ai/claude-code
pip install --user --cache-dir matplotlib seaborn jupyter wandb🎯 Step 5: Run Your Training Jobs
✅ Single Node
export HF_HOME=/storage/cache
cd /workspace/verl
torchrun --nproc_per_node=8 examples/train_ppo.py \
--model_name microsoft/DialoGPT-medium \
--output_dir /storage/checkpoints/run_$(date +%Y%m%d_%H%M%S)✅ Multi-Node (2 × 4 GPUs)
On Node 0:
export MASTER_ADDR=$(hostname -I | cut -d' ' -f1)
torchrun --nnodes=2 --nproc_per_node=4 --node_rank=0 \
--master_addr=$MASTER_ADDR --master_port=12345 \
examples/train_ppo.py --model_name microsoft/DialoGPT-medium \
--output_dir /storage/checkpoints/dist_run_$(date +%Y%m%d_%H%M%S)On Node 1:
torchrun --nnodes=2 --nproc_per_node=4 --node_rank=1 \
--master_addr=<MASTER_ADDR> --master_port=12345 ...📦 Step 6: Persistence and Monitoring
- Files in
/workspaceand/storagepersist - Processes inside container are killed when job ends
Monitoring
apptainer instance list
squeue -u zy279
watch -n 1 nvidia-smiResume a Job
srun --jobid=<ID> --pty bash
apptainer shell instance://llm_containerExample Code — ALFworld on verl-agent
- After installing the container, install verl-agent package and dependencies
cd verl-agent
pip3 install -e .[vllm]
export PIP_CACHE_DIR=/tmp/pip_cache
pip3 install --no-cache-dir --user gymnasium==0.29.1
pip3 install --no-cache-dir --user stable-baselines3==2.6.0
pip install --no-cache-dir --user alfworld
pip install --no-cache-dir --user seaborn matplotlib jupyter tqdm
alfworld-download -f- WandB log in
wandb login
- Modify the example script (https://github.com/langfengQ/verl-agent/blob/master/examples/grpo_trainer/run_alfworld.sh). We need to explicitly specify the number of CPUs used by Ray.
set -x
ENGINE=${1:-vllm}
export VLLM_ATTENTION_BACKEND=XFORMERS
train_data_size=8
val_data_size=8
group_size=5
# actor_rollout_ref.model.path=Qwen/Qwen2.5-1.5B-Instruct \
# We only use data preparation to indicate the modality and the data size.
python3 -m examples.data_preprocess.prepare \
--mode 'text' \
--train_data_size $train_data_size \
--val_data_size $val_data_size
python3 -m verl.trainer.main_ppo \
algorithm.adv_estimator=grpo \
data.train_files=$HOME/data/verl-agent/text/train.parquet \
data.val_files=$HOME/data/verl-agent/text/test.parquet \
data.train_batch_size=$train_data_size \
data.val_batch_size=$val_data_size \
data.max_prompt_length=2048 \
data.max_response_length=512 \
data.filter_overlong_prompts=True \
data.truncation='error' \
data.return_raw_chat=True \
actor_rollout_ref.model.path=Qwen/Qwen2.5-1.5B-Instruct \
actor_rollout_ref.actor.optim.lr=1e-6 \
actor_rollout_ref.model.use_remove_padding=True \
actor_rollout_ref.actor.ppo_mini_batch_size=256 \
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=8 \
actor_rollout_ref.actor.use_kl_loss=True \
actor_rollout_ref.actor.kl_loss_coef=0.01 \
actor_rollout_ref.actor.kl_loss_type=low_var_kl \
actor_rollout_ref.model.enable_gradient_checkpointing=True \
actor_rollout_ref.actor.fsdp_config.param_offload=False \
actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=16 \
actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
actor_rollout_ref.rollout.name=$ENGINE \
+actor_rollout_ref.rollout.num_cpus_per_worker=1 \
+actor_rollout_ref.rollout.num_gpus_per_worker=0.2 \
actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
actor_rollout_ref.rollout.enable_chunked_prefill=False \
actor_rollout_ref.rollout.enforce_eager=False \
actor_rollout_ref.rollout.free_cache_engine=False \
actor_rollout_ref.rollout.val_kwargs.temperature=0.6 \
actor_rollout_ref.rollout.val_kwargs.do_sample=True \
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=16 \
actor_rollout_ref.ref.fsdp_config.param_offload=True \
actor_rollout_ref.actor.use_invalid_action_penalty=True \
actor_rollout_ref.actor.invalid_action_penalty_coef=0.1 \
algorithm.use_kl_in_reward=False \
env.env_name=alfworld/AlfredTWEnv \
env.seed=0 \
env.max_steps=50 \
env.rollout.n=$group_size \
trainer.critic_warmup=0 \
trainer.logger=['console','wandb'] \
trainer.project_name='verl_agent_alfworld' \
trainer.experiment_name='grpo_qwen2.5_1.5b' \
trainer.n_gpus_per_node=4 \
trainer.nnodes=1 \
trainer.save_freq=-1 \
trainer.test_freq=-1 \
trainer.total_epochs=150 \
trainer.val_before_train=True \
+ray_init.num_cpus=${SLURM_CPUS_PER_TASK:-96}
$@Note: we need to modify /agent_system/environments/env_pacakge/alfworld/env.py. This follows this issue (https://github.com/langfengQ/verl-agent/issues/70#issuecomment-2959477490).
@ray.remote(num_cpus=0.15)
class AlfworldWorker:Monitor the Running Job
➊ Find and attach to the job
# show my running Slurm jobs
squeue -u $USER
# assume JOBID=123456
# show which node(s) the job is on
scontrol show job 123456 | grep -oP 'NodeList=\K\S+'
scontrol show hostnames <NodeList> # expands to e.g. "gpu042"
# open an interactive shell **inside** the allocation
srun --jobid=123456 --pty bash # or: ssh gpu042
# enter the running Apptainer instance
apptainer shell instance://llm_container➋ Quick Ray health checks
ray status # resources & autoscaler messages
ray list actors # which actors exist / are pending
ray list tasks # current task queue
ray memory # shared‑memory usageWhat the numbers mean
| Section | Field | Indicates |
|---|---|---|
| Resources | Usage 0.0/4.0 GPU | GPUs free; if already at 4/4, nothing else fits. |
Demands {'CPU':1,'GPU':1} | at least one actor still waiting for 1 CPU + 1 GPU. | |
| Actors list | PENDING_CREATION | Ray can’t find a node with the requested bundle. |
ALIVE / RUNNING | actor successfully placed. |
➌ Typical fixes when actors stay pending
| Symptom | Fix |
|---|---|
PENDING_CREATION & demand {'CPU':1,'GPU':1} but GPUs free | Add +ray_init.num_cpus=<allocation> |
Demand {'GPU':4} and all GPUs in use | Lower tensor_model_parallel_size or move some roll‑outs to CPU |
| Object store errors | +ray_init.object_store_memory=8_000_000_000 |
Restart Ray after each config edit:
ray stop --force
nohup bash run_ppo.sh … &📘 Frequently Asked Questions (FAQ)
Q1: What happens to my container when my job finishes?
A: The container instance is automatically removed when your Slurm job ends. However, any files saved in mounted directories like /workspace and /storage are safe and persist across jobs. Think of the container as temporary, and your mounted directories as permanent storage.
Q2: Where are my files and how do I access them?
Outside the container (host system):
/gpfs/radev/home/zy279/project/llm_docker_space/ # Your project code
/gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage/ # Datasets, models, logs
Inside the container:
/workspace/ # Maps to your project code
/storage/ # Maps to your scratch storage
You can access them using ls, scp, or other standard tools.
Q3: How do I configure paths for my projects inside the container?
Always use the mounted paths:
python train.py --output_dir /storage/checkpoints/my_project
python analyze.py --data_dir /storage/datasetsSet environment variables for convenience:
export HF_HOME=/storage/cache
export TRANSFORMERS_CACHE=/storage/cache
export OUTPUT_DIR=/storage/checkpoints/$(date +%Y%m%d_%H%M%S)Q4: Can I run multiple containers at the same time?
Yes, just give each container a unique name when starting it:
apptainer instance start ... llm_container_train
apptainer instance start ... llm_container_dev
apptainer instance list # Lists all running containersQ5: What if I need to install additional Python packages?
You can install packages temporarily like this:
pip install some_packageBut this gets wiped when the container stops. To make installations persistent:
-
Install into a mounted directory:
pip install --target /workspace/local_packages my_package export PYTHONPATH=/workspace/local_packages:$PYTHONPATH -
Use a
requirements.txt:echo "my_package" >> /workspace/requirements.txt pip install -r /workspace/requirements.txt
Q6: How do I check if my container is still running?
Use these commands:
apptainer instance list # Check active containers
squeue -u zy279 # Check running jobs
apptainer exec instance://llm_container ps aux # See processes insideQ7: My training job failed. How do I debug?
Check logs, resources, and running processes:
tail -f /storage/logs/training.log # Logs
apptainer exec instance://llm_container nvidia-smi # GPU status
df -h /workspace /storage # Disk space
ps aux | grep python # Python processesQ8: How do I transfer files between my local machine and the container?
Use scp:
# Upload from local to cluster
scp myfile.py zy279@cluster:/gpfs/radev/home/zy279/project/llm_docker_space/
# Download from cluster
scp zy279@cluster:/gpfs/radev/scratch/zhuoran_yang/zy279/llm_container_storage/results.txt ./Files are automatically available inside the container at /workspace/ or /storage/.
Q9: Can I use VSCode with my container?
Yes, in two ways:
Option 1: Port forwarding for Jupyter
# Inside container
jupyter lab --ip=0.0.0.0 --port=8888 --no-browser --allow-root
# On your local machine
ssh -L 8888:<compute-node>:8888 zy279@clusterOption 2: VSCode Remote-SSH
- Connect via VSCode Remote-SSH to the cluster
- Start your container interactively
- Open a terminal inside VSCode and attach to the container
Q10: What’s the difference between /workspace and /storage?
/workspace: Permanent, smaller quota, for code/scripts. Backed up./storage: Large, scratch space for datasets, models, logs. 60-day retention.
Use:
/workspace→ code, config, notebooks/storage→ models, checkpoints, logs, datasets
Q11: How do I monitor my training progress remotely?
Start your training with logging:
nohup python train.py > /storage/logs/training.log 2>&1 &Then monitor from another terminal:
tail -f /storage/logs/training.logYou can also implement custom monitoring:
python /workspace/monitor_training.py --checkpoint_dir /storage/checkpoints/Q12: What if I run out of storage space?
Check usage:
df -h /storage
du -sh /storage/*Clean up old runs:
rm -rf /storage/checkpoints/old_run_*Use checkpoint rotation in training:
python train.py --save_total_limit 3 # Keep only last 3 checkpointsQ13: My laptop disconnected — is my job still running?
Yes! The Slurm cluster is independent of your local machine.
What happens:
- You disconnect or your laptop sleeps
- The Slurm job and container continue running
- You can reconnect later
How to resume:
ssh zy279@cluster
squeue -u zy279 # Find your job ID
srun --jobid=YOUR_JOB_ID --pty bash # Reconnect to node
apptainer shell instance://llm_container
tail -f /storage/logs/training.log