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!
相关推荐
Xzaveir44 分钟前
别把所有“认证”都塞进 AuthService:实名、一键登录与号码身份的领域拆分
android·人工智能
BerrySen1781 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·人工智能
战族狼魂1 小时前
高频面试题精选:分治与AI Agent架构
人工智能·算法·大模型·大语言模型
zSD55rt5a2 小时前
方差在扩散模型保护中的作用
人工智能·harmonyos
人生百态,人生如梦2 小时前
情感交互仿生人从技术到落地构想3——技术交流贴(2026.7)
人工智能·机器学习·人机交互·交互·具身智能
用户652238438112 小时前
为什么成熟的 LLM 应用,都把"后端地址"做成可切换的配置
人工智能
Aa99883342 小时前
AI视觉检测设备厂家的技术评估框架——以及AI视觉检测的检出边界与适用条件
人工智能
wuhanzhanhui2 小时前
当AI遇见储能!2026武汉国际数字能源产业与新型电力及储能技术展览会
人工智能·能源
Tangyuewei2 小时前
给 AI 套上缰绳:Harness Engineering 是什么
人工智能