【设置gpu设备】os.environ[‘CUDA_VISIBLE_DEVICES‘] 和 torch.cuda.set_device()

【设置gpu设备】os.environ[‘CUDA_VISIBLE_DEVICES‘] 和 torch.cuda.set_device()

1. 介绍

官方文档:当使用 PyTorch 进行深度学习训练时,通常需要使用 CUDA 加速计算。在使用 PyTorch 进行训练之前,需要确保已经正确设置了可见的 GPU 设备,并且已经初始化了 CUDA 环境。

2. 方法

2.1 方法1:os.environ[‘CUDA_VISIBLE_DEVICES‘] (推荐)

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'

os.environ[‘CUDA_VISIBLE_DEVICES’] 是一个环境变量,可以通过设置它来限制程序所能看到的可用 GPU 设备列表,从而确保程序只使用指定的 GPU 设备。

  • 设置该环境变量可以使用 os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘0,1’,其中的 ‘0,1’ 表示程序只能看到编号为 0 和 1 的 GPU 设备。

2.2 方法2:torch.cuda.set_device(0)

import torch
torch.cuda.set_device(0)

torch.cuda.set_device() 则是一个 PyTorch 提供的函数,用于将程序的运行环境切换到指定的 GPU 设备上。可以使用 torch.cuda.set_device(0) 将程序的运行环境切换到编号为 0 的 GPU 设备上。

2.3 说明

当你发现你用方式一没有办法使用你指定的GPU,可以用方式二。

  • data.cuda(gpu_id, non_blocking=non_blocking)

如果报错,可以改为data.cuda()。

3. 参考

【1】https://blog.csdn.net/weixin_46141646/article/details/129052145

猜你喜欢

转载自blog.csdn.net/qq_51392112/article/details/129739768