How to use Huggingface Trainer with multiple GPUs?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
The Hugging Face Trainer class supports multi-GPU training out of the box. For data parallelism on a single machine, launch with torchrun or accelerate launch and the Trainer automatically distributes data across GPUs using PyTorch's DistributedDataParallel (DDP). For model parallelism or multi-node training, use DeepSpeed or FSDP integration via TrainingArguments.
Single Command Multi-GPU (Simplest)
If you have a standard training script using Trainer, multi-GPU works by changing only the launch command:
The per_device_train_batch_size is per GPU. With 4 GPUs and per_device_train_batch_size=16, the effective batch size is 64.
Controlling GPU Selection
Gradient Accumulation
When GPU memory is limited, accumulate gradients over multiple steps to simulate a larger batch:
DeepSpeed Integration
For large models that do not fit on a single GPU, use DeepSpeed ZeRO:
DeepSpeed ZeRO stages:
- Stage 1: Partitions optimizer states across GPUs
- Stage 2: Also partitions gradients
- Stage 3: Also partitions model parameters (enables training models larger than single GPU memory)
FSDP (Fully Sharded Data Parallel)
PyTorch-native alternative to DeepSpeed:
Mixed Precision Training
Reduce memory usage and speed up training with fp16 or bf16:
Multi-Node Training
For training across multiple machines:
Common Pitfalls
- Running with
python train.pyinstead oftorchrun: The Trainer detects multi-GPU only when launched withtorchrunoraccelerate launch. Running with plainpythonuses a single GPU regardless of how many are available. - Confusing per-device and total batch size:
per_device_train_batch_sizeis per GPU. The effective batch size isper_device * gradient_accumulation_steps * num_gpus. Accidentally setting it to the total desired batch size results in OOM errors. - Not setting
CUDA_VISIBLE_DEVICES: Without this, all GPUs are used. On shared machines, this conflicts with other users. Always setCUDA_VISIBLE_DEVICESto restrict which GPUs your job uses. - Saving/loading checkpoints in multi-GPU: The Trainer handles this correctly by default (only the main process saves). But custom saving code must check
trainer.is_world_process_zero()to avoid duplicate writes from all processes. - DeepSpeed config conflicting with TrainingArguments: When using DeepSpeed, set batch size and gradient accumulation to
"auto"in the DeepSpeed config to let the Trainer control them. Hardcoded values that conflict withTrainingArgumentscause silent misconfiguration.
Summary
- Launch with
torchrun --nproc_per_node=N train.pyfor multi-GPU training per_device_train_batch_sizeis per GPU — effective batch = per_device * accumulation * num_gpus- Use
gradient_accumulation_stepsto simulate larger batches when GPU memory is limited - Use DeepSpeed ZeRO (stage 2 or 3) for models too large for a single GPU
- Use
fp16=Trueorbf16=Truefor mixed precision training to reduce memory and increase speed - Set
CUDA_VISIBLE_DEVICESon shared machines to avoid GPU conflicts
Related reading
- How to use hyperopt for hyperparameter optimization of Keras deep learning network?
- How to use image_summary to view images from different batches in Tensorflow?
- How to use k-fold cross validation in a neural network
- How to use keras attention layer on top of LSTM/GRU?
- How to use Isolation Forest
- How to use KBinsDiscretizer to make continuous data into bins in Sklearn?
- How to use JUnit to test asynchronous processes
- How to use JUnit to test asynchronous processes
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.