python在多卡服务器中指定某块显卡允许程序 -- 本机为mac,服务器为Linux, nvidia_python 指定使用显卡

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

1 在pychram环境变量中设置

        在pycharm端操作操作步骤如下

1操作右上角Edit Configurations...

 (2)在 Edit Configurations界面可以选择设置哪个程序的cuda如图

 3还是2的界面添加CUDA_VISIBLE_DEVICES=33可以改成任何可使用的显卡序号

 4最后Apply就好

5需要注意的是在代码端默认设置的第三块卡的编号为0为起始显卡第四块编号为1

        代码书写 直接

model = model.cuda()

2 利用CUDA_VISIBLE_DEVICES设置可用显卡

1在代码中直接指定显卡 -- 该操作和上述 环境变量操作等价

import os

os.environ['CUDA_VISIBLE_DEVICES'] = '3'

        注意该代码需要放在 import torch 之前否则会失效;

举例

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1,2,3'

import torch

print("torch版本号:", end="")
print(torch.__version__)
print("判断torch是否可用:", end="")
print(torch.cuda.is_available())

print("gpu数量:", end="")
print(torch.cuda.device_count())

print("gpu名字设备索引默认从0开始:", end="")
print(torch.cuda.get_device_name(0))
print("现在正在使用的GPU编号:", end="")
print(torch.cuda.current_device())

# 输出
torch版本号:1.12.1+cu102
判断torch是否可用:True
gpu数量:3
gpu名字设备索引默认从0开始:Tesla V100-PCIE-32GB
现在正在使用的GPU编号:0

2在命令行中指定GPU运行

CUDA_VISIBLE_DEVICES='3' python3 train.py

3在命令行执行脚本文件中指定

CUDA_VISIBLE_DEVICES='3' sh run.sh

3 cuda()方法和torch.cuda.set_device()

1cuda()

model.cuda('3') # gpu_id为int类型变量只能指定一张显卡

model.cuda('cuda:3') #输入参数为str类型可指定多张显卡

model.cuda('cuda:1,2') #指定多张显卡的一个示例

2torch.cuda.set_device()

torch.cuda.set_device('3') #单卡

torch.cuda.set_device('cuda:2,3') #可指定多卡

        但是这种写法的优先级低如果model.cuda()中指定了参数那么torch.cuda.set_device()会失效;

        而且pytorch的官方文档中明确说明不建议用户使用该方法。

参考python直接控制显卡_在pytorch中指定显卡_weixin_39630855的博客-CSDN博客

使用指定GPU训练模型os.environ[‘CUDA_VISIBLE_DEVICES‘]设置无效问题解决——随笔_"os.environ[\"cuda_visible_devices\"]"_BXDBB的博客-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6