How to Specify Which GPU to Use with Hugging Face Trainer
In this article
To specify which GPU to use with the Hugging Face Trainer, set the CUDA_VISIBLE_DEVICES environment variable to the GPU index (e.g., CUDA_VISIBLE_DEVICES=1) before running your script, or pass the device argument to the TrainingArguments (e.g., device='cuda:1') in recent versions of the library. This makes only the chosen GPU visible to PyTorch, and the Trainer will use it automatically.
Background: How Trainer Uses GPUs
The Hugging Face Trainer is built on top of PyTorch and relies on PyTorch's device management. By default, PyTorch uses GPU 0 (the first visible device) if any GPU is available. The Trainer inherits this behavior—it checks torch.cuda.is_available() and then uses cuda:0 unless told otherwise. This is why specifying a GPU often comes down to controlling which devices are visible to the process, rather than telling the Trainer directly which one to use.
In distributed training (multi-GPU), the Trainer uses torch.distributed and each process is assigned a local rank. The environment variable CUDA_VISIBLE_DEVICES still plays a central role because it maps physical GPUs to logical indices. For example, if you have four GPUs and set CUDA_VISIBLE_DEVICES=2,3, then logical devices 0 and 1 correspond to physical GPUs 2 and 3.
How to Choose a GPU: Step-by-Step
Here are the common ways to specify a GPU, from simplest to most flexible.
- Environment variable (recommended for single GPU): Before running your script, set
CUDA_VISIBLE_DEVICES=1in your shell. Example:CUDA_VISIBLE_DEVICES=1 python train.py. This works for any PyTorch code, not just Hugging Face. - Inside the script (before importing torch): Add
import os; os.environ['CUDA_VISIBLE_DEVICES'] = '1'at the very top of your script, before any PyTorch or Hugging Face imports. This is useful when you need to set it programmatically. - Using
devicein TrainingArguments: In recent versions of Transformers (v4.30+), you can passdevice='cuda:1'toTrainingArguments. However, this only works if the GPU is already visible. It does not overrideCUDA_VISIBLE_DEVICES; it just tells the Trainer which visible device to use. - For distributed training: Use
torchrun --nproc_per_node=Nand setCUDA_VISIBLE_DEVICESto the list of GPUs you want to use. Each process will automatically get a different local rank.
Example of using device in code:
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir='./results',
device='cuda:1', # only works if GPU 1 is visible
)
Common Problems and Misconceptions
A frequent mistake is setting CUDA_VISIBLE_DEVICES after importing PyTorch. The environment variable is read only once at the time CUDA is initialized. If you set it after import torch, it has no effect. Always set it before any CUDA-related imports.
Another misconception is that the device argument in TrainingArguments can select a GPU that is not visible. It cannot—it only picks among the visible devices. If you set device='cuda:1' but only GPU 0 is visible, you will get an error.
Also, note that CUDA_VISIBLE_DEVICES uses physical GPU indices as reported by nvidia-smi. The numbering starts at 0. If you have multiple GPUs, you can check their IDs with nvidia-smi.
How to Verify Which GPU Is Being Used
To confirm that your training is using the intended GPU, you can add a simple check in your script:
import torch
print('Visible devices:', torch.cuda.device_count())
print('Current device:', torch.cuda.current_device())
This prints the number of visible GPUs and the index of the current device (which should be 0 if you set CUDA_VISIBLE_DEVICES=1, because it becomes the first visible). You can also monitor GPU usage in real time with nvidia-smi in another terminal.
Alternatives for Multi-GPU and Distributed Training
If you need to use multiple GPUs, the Trainer supports distributed training out of the box. You can specify the number of GPUs with --nproc_per_node in torchrun, or use the --num_processes flag in the accelerate launcher. The accelerate library is integrated with Trainer and provides a more flexible configuration file where you can set num_processes and gpu_ids.
For example, with accelerate, you can create a config file with accelerate config and specify which GPUs to use. Then launch your script with accelerate launch. This is often easier than manually setting environment variables, especially for multi-node training.
Safety and Hardware Considerations
When working with multiple GPUs, always ensure that your power supply and cooling can handle the load. If you are physically installing or removing GPUs, unplug the computer and ground yourself to avoid static discharge. Never open a power supply unit—it contains high-voltage capacitors that can be dangerous.
Overclocking or undervolting GPUs can cause instability and may affect your warranty. If you choose to do so, proceed with caution and do not push beyond safe limits. Always monitor temperatures during training.
Frequently Asked Questions
Does CUDA_VISIBLE_DEVICES work with Hugging Face Trainer?
Yes, it works exactly as with any PyTorch code. The Trainer respects the visible devices set by this variable. It is the most reliable way to select a single GPU.
Can I specify a GPU in TrainingArguments without using environment variables?
Yes, you can pass device='cuda:1' to TrainingArguments in recent versions of Transformers. However, the GPU must already be visible. If you have multiple GPUs and want to use one that is not the default, you still need to set CUDA_VISIBLE_DEVICES to make it visible first.
Why does my Trainer always use GPU 0 even when I set device='cuda:1'?
This usually happens because CUDA_VISIBLE_DEVICES was not set correctly, or because you set it after importing PyTorch. The device argument only selects among visible devices. If GPU 1 is not visible, it will fall back to GPU 0.
How do I use a specific GPU in Google Colab?
In Colab, you can only use the single GPU that is provided. You cannot choose which one. However, you can still set CUDA_VISIBLE_DEVICES=0 to make it explicit, but it has no practical effect.
What is the difference between CUDA_VISIBLE_DEVICES and device in Trainer?
CUDA_VISIBLE_DEVICES controls which physical GPUs are visible to the process, effectively remapping indices. The device argument tells the Trainer which visible device to use. The former is more fundamental; the latter is a convenience.