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!
相关推荐
维克兜率天3 分钟前
【维克】统计套利:寻找市场的“定价误差“
人工智能·python·算法
论文复现现场5 分钟前
自动驾驶 BEV 模型训练,2 张 A100 80GB 够不够?显存、双卡训练与租赁成本
人工智能·深度学习·机器学习·自动驾驶·分布式训练·a100·bevformer
陈嘿萌5 分钟前
TPAMI 2026|红外、SAR、深度与地图能否用一套特征匹配?北理工HIMO给出无需预训练的通用路线
图像处理·人工智能·深度学习·计算机视觉·图像匹配·学术研究与理论基础
天云数据7 分钟前
帮手如何用一句话配置消防任务
人工智能
const_qiu8 分钟前
第一章 1.3:System Prompt 定义模型角色 —— 告诉 AI“你是谁“
人工智能·ubuntu·prompt
鲲穹AI种草8 分钟前
全能 AI 智能体助手怎么选?鲲穹 KQBOT 功能实测与横向对比
人工智能
AI工具学习测评13 分钟前
低空经济入法100天:统一低空数字监管平台的技术架构与建设路径
大数据·人工智能·物联网·无人机·智慧城市
HUIBUR科技18 分钟前
AI 中枢,面向企业场景构建的 AI 智能体
前端·数据库·人工智能
在所不辞兄19 分钟前
为什么物理嵌入神经网络的收敛性和泛化误差缺乏统一的理论保证?
人工智能·深度学习·神经网络·机器学习·有限元
一水鉴天20 分钟前
声调韵的序:从古汉语音韵到系统科学语言的场效应推演 20261013(千问)
开发语言·人工智能