• pytorch中.to(device) 和.cuda()的区别


    在PyTorch中,使用GPU加速可以显著提高模型的训练速度。在将数据传递给GPU之前,需要将其转换为GPU可用的格式。

    函数原型如下:

    1. def cuda(self: T, device: Optional[Union[int, device]] = None) -> T:
    2. return self._apply(lambda t: t.cuda(device))
    3. def cpu(self: T) -> T:
    4. return self._apply(lambda t: t.cpu())
    5. def to(self, *args, **kwargs):
    6. ...
    7. def convert(t):
    8. if convert_to_format is not None and t.dim() == 4:
    9. return t.to(device, dtype if t.is_floating_point() else None, non_blocking, memory_format=convert_to_format)
    10. return t.to(device, dtype if t.is_floating_point() else None, non_blocking)
    11. return self._apply(convert)

    1 .to(device)

    .to(device)是PyTorch中的一个方法,可以将张量、模型转换为指定设备(如CPU或GPU)可用的格式。示例代码如下:

    1. import torch
    2. # 创建一个张量
    3. x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
    4. print(x)
    5. # 将张量转换为GPU可用的格式
    6. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    7. x = x.to(device)
    8. print(x)

     运行结果如下:

    1. tensor([[1., 2., 3.],
    2. [4., 5., 6.]])
    3. tensor([[1., 2., 3.],
    4. [4., 5., 6.]], device='cuda:0')

    在上述代码中,我们首先创建了一个形状为(2, 3)的张量x,然后使用x.to(device)将其转换为GPU可用的格式。其中,device是一个torch.device对象,可以使用torch.cuda.is_available()函数来判断是否支持GPU加速。

    1. import torch
    2. from torch import nn
    3. from torch import optim
    4. # 创建一个模型
    5. class Net(nn.Module):
    6. def __init__(self):
    7. super(Net, self).__init__()
    8. self.fc1 = nn.Linear(3, 2)
    9. self.fc2 = nn.Linear(2, 1)
    10. def forward(self, x):
    11. x = self.fc1(x)
    12. x = self.fc2(x)
    13. return x
    14. net = Net()
    15. # 将模型参数和优化器转换为GPU可用的格式
    16. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    17. net = net.to(device)
    18. print(net)
    19. optimizer = optim.SGD(net.parameters(), lr=0.01)

    运行结果显示如下:

    1. Net(
    2. (fc1): Linear(in_features=3, out_features=2, bias=True)
    3. (fc2): Linear(in_features=2, out_features=1, bias=True)
    4. )

    在上述代码中,首先创建了一个模型net,然后使用net.to(device)将其模型参数转换为GPU可用的格式。

    2 .cuda()

    .cuda()是PyTorch中的一个方法,可以将张量、模型转换为GPU可用的格式,示例代码如下:

    1. import torch
    2. # 创建一个张量
    3. x = torch.Tensor([[1, 2, 3], [4, 5, 6]])
    4. print(x)
    5. # 将张量转换为GPU可用的格式
    6. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    7. x = x.cuda()
    8. print(x)

    运行结果显示如下:

    1. tensor([[1., 2., 3.],
    2. [4., 5., 6.]])
    3. tensor([[1., 2., 3.],
    4. [4., 5., 6.]], device='cuda:0')

    在上述代码中,我们首先创建了一个形状为(2, 3)的张量x,然后使用x.cuda()将其转换为GPU可用的格式。 

    1. import torch
    2. from torch import nn
    3. from torch import optim
    4. # 创建一个模型
    5. class Net(nn.Module):
    6. def __init__(self):
    7. super(Net, self).__init__()
    8. self.fc1 = nn.Linear(3, 2)
    9. self.fc2 = nn.Linear(2, 1)
    10. def forward(self, x):
    11. x = self.fc1(x)
    12. x = self.fc2(x)
    13. return x
    14. net = Net()
    15. # 将模型参数和优化器转换为GPU可用的格式
    16. net = net.cuda()
    17. optimizer = optim.SGD(net.parameters(), lr=0.01)

    在上述代码中,首先创建了一个模型net,然后使用net.cuda()将模型转换为GPU可用的格式。

    3 总结

    推荐使用to(device)的方式,主要原因在于这样的编程方式更加易于扩展,而cuda()必须要求机器有GPU,否则需要修改所有代码;to(device)的方式则不受此限制,device既可以是CPU也可以是GPU;

  • 相关阅读:
    MFC程序设计——用button更改静态文本+显示内容并弹出新内容+静态文本动态打开位图
    软件系统测试和验收测试有什么联系与区别?专业软件测试方案推荐
    互联网程序设计课程 第2讲 网络对话程序设计
    前端工作总结114-JS-JS创建数组的三种方法
    k8s 容忍和污点
    HCIP 第十六天笔记(SVI、生成树协议)
    uniapp快速入门系列(3)- CSS技巧与布局
    可视化+多人协同技术原理和案例分享
    AI题目整理
    5、Elasticsearch 索引文档的CRUD
  • 原文地址:https://blog.csdn.net/lsb2002/article/details/134531689