Tensor 基本操作5 device 管理,使用 GPU 设备 | PyTorch 深度学习实战

前一篇文章,Tensor 基本操作4 理解 indexing,加减乘除和 broadcasting 运算 | PyTorch 深度学习实战

本系列文章 GitHub Repo: https://github.com/hailiang-wang/pytorch-get-started

Tensor 基本使用

  • 检查设备
  • [创建 tensor 时声明设备](#创建 tensor 时声明设备)
  • 更改默认设备
  • [创建 tensor 后移动 tensor.to](#创建 tensor 后移动 tensor.to)
  • 注意事项
    • [1. 运算的发生位置](#1. 运算的发生位置)
    • [2. 当两个 tensor 进行运算时,需要在同一个设备上](#2. 当两个 tensor 进行运算时,需要在同一个设备上)

检查设备

  • 默认为 CPU,根据是否有 GPU 设定 device。

    device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'))

  • 检查默认设备

    device = torch.get_default_device()

创建 tensor 时声明设备

复制代码
    # 声明为 CPU 设备
    device_cpu = torch.device('cpu')
    points_cpu = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]], device=device_cpu)

更改默认设备

将默认设备,设置为 GPU。

复制代码
device_gpu = torch.device('cuda')
torch.set_default_device(device_gpu) 
points_default = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]]) # 此时,points_default  被定义到 GPU 上

创建 tensor 后移动 tensor.to

将一个 tensor 移动到指定设备。

复制代码
    device_gpu = torch.device('cuda')
    points2 = points.to(device_gpu)  # 将 Tensor 复制到 GPU
    print(points2)

注意事项

1. 运算的发生位置

复制代码
    device_gpu = torch.device('cuda')
    points2 = points.to(device_gpu)  # 将 Tensor 复制到 GPU
    points3 = points2 * 2   # points3 还是在 GPU 上
    points4 = points2 + 2  # points4 还是在 GPU 上

但是,打印 points3 或 points4 时,将会复制该值到 CPU 上输出。

2. 当两个 tensor 进行运算时,需要在同一个设备上

复制代码
  File "C:\devel\Python\Python311\Lib\site-packages\torch\utils\_device.py", line 79, in __torch_function__
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
相关推荐
火山引擎开发者社区1 分钟前
火山引擎 Milvus 发布官方 CLI + Skill ,终端与对话双通道掌控向量数据库
人工智能
weixin_549808364 分钟前
从“大海捞针“到“精准定位“:易薪路AI人才罗盘如何用AI重构企业人才选拔与组织发展
大数据·人工智能·重构
步步为营DotNet8 分钟前
Blazor 在边缘计算客户端应用中的创新实践与深度解析
人工智能·microsoft·边缘计算
阿演13 分钟前
DataDjinn 新版本更新:国产数据库支持、连接树体验、AI 查询和表格编辑继续增强
数据库·人工智能·ai·ai编程
城事漫游Molly17 分钟前
质性研究AI工作流(六):质性研究质量检验的5维清单
人工智能·ai for science·定性研究
keykey6.18 分钟前
迁移学习实战:用预训练模型做图像分类
开发语言·人工智能·深度学习·机器学习
码农小旋风20 分钟前
上下文工程
人工智能·chatgpt·claude
火山引擎开发者社区23 分钟前
开启报名 | 首届火山「AI安全攻防」挑战赛邀你参赛
人工智能
DXM052123 分钟前
第8期| 传统机器学习遥感解译:SVM & 随机森林分类全流程实操
人工智能·python·随机森林·机器学习·支持向量机·arcgis·自然语言处理
程序员差不多先生23 分钟前
Copilot 取消年费改按量计费:AI Coding 工具进入了什么新阶段?
人工智能·copilot·github copilot