动手学深度学习(pytorch)学习记录22-GPU[学习记录]

本次代码在kaggle平台上运行。使用两个T4的GPU
在这里插入图片描述

使用nvidia-smi命令来查看显卡信息

!nvidia-smi
Fri Aug 30 05:31:53 2024       
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 550.90.07              Driver Version: 550.90.07      CUDA Version: 12.4     |
|-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  Tesla T4                       Off |   00000000:00:04.0 Off |                    0 |
| N/A   54C    P8             10W /   70W |       1MiB /  15360MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+
|   1  Tesla T4                       Off |   00000000:00:05.0 Off |                    0 |
| N/A   50C    P8              9W /   70W |       1MiB /  15360MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+
                                                                                         
+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI        PID   Type   Process name                              GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|  No running processes found                                                             |
+-----------------------------------------------------------------------------------------+

计算设备

指定用于存储和计算的设备,如CPU和GPU。 默认情况下,张量是在内存中创建的,然后使用CPU计算它。
在PyTorch中,CPU和GPU可以用torch.device(‘cpu’) 和torch.device(‘cuda’)表示。 应该注意的是,cpu设备意味着所有物理CPU和内存, 这意味着PyTorch的计算将尝试使用所有CPU核心。 然而,gpu设备只代表一个卡和相应的显存。 如果有多个GPU,我们使用torch.device(f’cuda:{i}') 来表示第i块GPU(i从0开始)。 另外,cuda:0和cuda是等价的。

import torch
from torch import nn

torch.device('cpu')
device(type='cpu')

查看可用gpu的数量

torch.cuda.device_count()
2
torch.device('cuda'), torch.device('cuda:1')
(device(type='cuda'), device(type='cuda', index=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')]

try_gpu(), try_gpu(10), try_all_gpus()
(device(type='cuda', index=0),
 device(type='cpu'),
 [device(type='cuda', index=0), device(type='cuda', index=1)])

张量与GPU

可以查询张量所在的设备。 默认情况下,张量是在CPU上创建的。

x = torch.tensor([1, 2, 3])
x.device
device(type='cpu')

存储在GPU上

有几种方法可以在GPU上存储张量。 比如在创建张量时指定存储设备。在GPU上创建的张量只消耗这个GPU的显存。 可以使用nvidia-smi命令查看显存使用情况。 当然,在GPU上存储的数据大小不能超过显存。

X = torch.ones(2, 3, device=try_gpu())
X
tensor([[1., 1., 1.],
        [1., 1., 1.]], device='cuda:0')

kaggle平台这里有两个GPU,下面的代码将在第二个GPU上创建一个随机张量。

Y = torch.rand(2, 3, device=try_gpu(1))
Y
tensor([[0.9261, 0.4336, 0.2264],
        [0.7796, 0.0434, 0.2683]], device='cuda:1')

复制

如果要对多个项进行操作, 它们都必须在同一个设备上。
比如上面创建的X和Y在两个不同的GPU上,要进行相加操作,直接相加会出问题。

X + Y
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[9], line 1
----> 1 X + Y

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1!

须将X复制到第二个GPU上,或者将Y复制到第一个GPU上。

# 将X复制到第二个GPU上
Z = X.cuda(1)
print(X)
print(Z)
tensor([[1., 1., 1.],
        [1., 1., 1.]], device='cuda:0')
tensor([[1., 1., 1.],
        [1., 1., 1.]], device='cuda:1')

这时,Z和Y都在第二个GPU上,就可以相加了。

Y + Z
tensor([[1.9261, 1.4336, 1.2264],
        [1.7796, 1.0434, 1.2683]], device='cuda:1')

Z已经存在于第二个GPU上。 如果再次调用Z.cuda(1)会发生什么? 它将返回Z,而不会复制并分配新内存。

Z.cuda(1) is Z
True

神经网络与GPU

神经网络模型可以指定设备。 下面的代码将模型参数放在GPU上。

net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())

当输入为GPU上的张量时,模型将在同一GPU上计算结果。

net(X)
tensor([[0.0620],
        [0.0620]], device='cuda:0', grad_fn=<AddmmBackward0>)

确认一下模型参数是否存储在同一个GPU上。

net[0].weight.data.device

device(type=‘cuda’, index=0)
封面图片来源

欢迎点击我的主页查看更多文章。
本人学习地址https://zh-v2.d2l.ai/
恳请大佬批评指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

walfar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值