赞
踩
在pycharm端操作,操作步骤如下:
(1)操作右上角:Edit Configurations...

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

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

(4)最后Apply就好;
(5)需要注意的是在代码端默认,设置的第三块卡的编号为0,为起始显卡,第四块编号为1;
代码书写 直接:
model = model.cuda()
(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
(1)cuda()
- model.cuda('3') # gpu_id为int类型变量,只能指定一张显卡
-
- model.cuda('cuda:3') #输入参数为str类型,可指定多张显卡
-
- model.cuda('cuda:1,2') #指定多张显卡的一个示例
(2)torch.cuda.set_device()
- torch.cuda.set_device('3') #单卡
-
- torch.cuda.set_device('cuda:2,3') #可指定多卡
但是这种写法的优先级低,如果model.cuda()中指定了参数,那么torch.cuda.set_device()会失效;
而且pytorch的官方文档中明确说明,不建议用户使用该方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。