PyTorch默认使用从0开始的GPU,如果GPU0正在运行程序,需要指定其他GPU。那么在有多个GPU的情况下怎么选择使用哪张卡呢?
有如下三种方法来指定需要使用的GPU。
- 使用CUDA_VISIBLE_DEVICES,直接在终端中设定
CUDA_VISIBLE_DEVICES=id python demo.py - 在 python代码中设定:
import os
os.environ[“CUDA_VISIBLE_DEVICES”] = “id” - python代码中使用函数 set_device设定
import torch
torch.cuda.set_device(id)
我这里有四张卡,id也就是0-4,即为你想要使用的GPU序号。