当前位置:   article > 正文

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

python 指定显卡

1 在pychram环境变量中设置

        在pycharm端操作,操作步骤如下:

(1)操作右上角:Edit Configurations...

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

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

 (4)最后Apply就好;

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

        代码书写 直接:

model = model.cuda()

2 利用CUDA_VISIBLE_DEVICES设置可用显卡

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

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

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

举例:

  1. import os
  2. os.environ['CUDA_VISIBLE_DEVICES'] = '1,2,3'
  3. import torch
  4. print("torch版本号:", end="")
  5. print(torch.__version__)
  6. print("判断torch是否可用:", end="")
  7. print(torch.cuda.is_available())
  8. print("gpu数量:", end="")
  9. print(torch.cuda.device_count())
  10. print("gpu名字,设备索引默认从0开始:", end="")
  11. print(torch.cuda.get_device_name(0))
  12. print("现在正在使用的GPU编号:", end="")
  13. print(torch.cuda.current_device())
  14. # 输出
  15. torch版本号:1.12.1+cu102
  16. 判断torch是否可用:True
  17. gpu数量:3
  18. gpu名字,设备索引默认从0开始:Tesla V100-PCIE-32GB
  19. 现在正在使用的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()

(1)cuda()

  1. model.cuda('3') # gpu_id为int类型变量,只能指定一张显卡
  2. model.cuda('cuda:3') #输入参数为str类型,可指定多张显卡
  3. model.cuda('cuda:1,2') #指定多张显卡的一个示例

(2)torch.cuda.set_device()

  1. torch.cuda.set_device('3') #单卡
  2. 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博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53792
推荐阅读
相关标签
  

闽ICP备14008679号