动手学习深度学习(9)使用和购买GPU

茴香豆 Lv5

首先查看设备时候具有GPU,在控制台输入

1
nvidia-smi

如果显示显卡信息说明具有GPU。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import torch
from torch import nn

# 查询可用gpu数量
print(torch.cuda.device_count())
# 访问cpu,gpu,某个gpu
print(torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1'))
# 这两个函数允许我们在请求的GPU不存在的情况下运行代码
def try_gpu(i=0): #@save
"""如果存在,则返回gpu(i),否则返回cpu()"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')

def try_all_gpus(): #@save
"""返回所有可用的GPU,如果没有GPU,则返回[cpu(),]"""
devices = [torch.device(f'cuda:{i}')
for i in range(torch.cuda.device_count())]
return devices if devices else [torch.device('cpu')]

print(try_gpu(), try_gpu(10), try_all_gpus())
  • Title: 动手学习深度学习(9)使用和购买GPU
  • Author: 茴香豆
  • Created at : 2022-10-30 15:11:42
  • Updated at : 2022-10-30 16:28:47
  • Link: https://hxiangdou.github.io/2022/10/30/DL_9/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
动手学习深度学习(9)使用和购买GPU