• pytorch深度学习实战lesson17


    第十七课 GPU is all u need

    可以在终端输入nvidia-smi来看自己的显卡信息。

    然后就是关于GPU的一些操作。这里要提醒的一点就是,程序的计算一定要选好是使用GPU进行计算还是使用CPU,因为本来CPU往GPU传输数据的时间就长,所以假如你没有设置好计算的设备,或者设置乱了的话,就会导致你设置出来的东西性能没有那么好。所以要三思。

    1. #计算设备
    2. import torch
    3. from torch import nn
    4. print(torch.device('cpu'), torch.cuda.device('cuda'), torch.cuda.device('cuda:1'))
    5. #查询可用gpu的数量
    6. print(torch.cuda.device_count())
    7. #这两个函数允许我们在请求的GPU不存在的情况下运行代码
    8. def try_gpu(i=0):
    9. """如果存在,则返回gpu(i),否则返回cpu()。"""
    10. if torch.cuda.device_count() >= i + 1:
    11. return torch.device(f'cuda:{i}')
    12. return torch.device('cpu')
    13. def try_all_gpus():
    14. """返回所有可用的GPU,如果没有GPU,则返回[cpu(),]。"""
    15. devices = [
    16. torch.device(f'cuda:{i}') for i in range(torch.cuda.device_count())]
    17. return devices if devices else [torch.device('cpu')]
    18. print(try_gpu(), try_gpu(10), try_all_gpus())
    19. #查询张量所在的设备
    20. x = torch.tensor([1, 2, 3])
    21. print(x.device)
    22. #存储在GPU上
    23. X = torch.ones(2, 3, device=try_gpu())
    24. print(X)
    25. #第二个GPU上创建一个随机张量
    26. Y = torch.rand(2, 3, device=try_gpu(0))
    27. print(Y)
    28. #要计算X + Y,我们需要决定在哪里执行这个操作
    29. Z = X.cuda(0)
    30. print(X)
    31. print(Z)
    32. #现在数据在同一个GPU上(Z和Y都在),我们可以将它们相加
    33. print(Y + Z)
    34. print(Z.cuda(0) is Z)
    35. #神经网络与GPU
    36. net = nn.Sequential(nn.Linear(3, 1))
    37. net = net.to(device=try_gpu())
    38. print(net(X))
    39. #确认模型参数存储在同一个GPU上
    40. print(net[0].weight.data.device)

    输出:

    cpu


    1


    cuda:0 cpu [device(type='cuda', index=0)]


    cpu


    tensor([[1., 1., 1.],
            [1., 1., 1.]], device='cuda:0')


    tensor([[0.9217, 0.0568, 0.5230],
            [0.0626, 0.0854, 0.6800]], device='cuda:0')


    tensor([[1., 1., 1.],
            [1., 1., 1.]], device='cuda:0')


    tensor([[1., 1., 1.],
            [1., 1., 1.]], device='cuda:0')


    tensor([[1.9217, 1.0568, 1.5230],
            [1.0626, 1.0854, 1.6800]], device='cuda:0')


    True


    tensor([[-0.2915],
            [-0.2915]], device='cuda:0', grad_fn=)
    cuda:0

    沐神还教了如何购买GPU,有想了解的同学可以自行查看b站视频。

    使用 GPU_哔哩哔哩_bilibili

  • 相关阅读:
    [坐标系转换]车体坐标系 转 像素坐标系
    CLR内存管理机制与IDisposable对象的GC原理
    Linux命令(22)之chage
    configure: error: library ‘crypto‘ is required for OpenSSL
    NLP之多循环神经网络情感分析
    吃透Chisel语言.20.Chisel组合电路(二)——Chisel编码器与解码器实现
    SpringCLoud——Feign的远程调用
    JavaEE——SmartTomcat的使用教程与常见错误
    orm连接mysql
    一文介绍回归和分类的本质区别 !!
  • 原文地址:https://blog.csdn.net/weixin_48304306/article/details/127892250