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!
相关推荐
longerVR13 小时前
自动驾驶(FSD/Autopilot)的数据采集-特斯拉纯视觉方案
人工智能·机器学习·自动驾驶
运维帮手大橙子13 小时前
自动驾驶各模块协作与本质
人工智能·机器学习·自动驾驶
captain_AIouo13 小时前
Captain AI以视频运营破局!助Ozon商家抢占流量红利
大数据·人工智能·经验分享·aigc·音视频
AI医影跨模态组学13 小时前
NPJ Precis Oncol(IF=8)中国科学院深圳先进技术研究院吴红艳教授等团队:深度可解释放射基因组学解析乳腺MRI肿瘤微环境
人工智能·深度学习·论文·医学·医学影像
Artdesign_E13 小时前
如何让AI图文自动生成视频?一键图文转视频指南
图像处理·人工智能·aigc
大模型最新论文速读13 小时前
05-15 · LLM 最新论文速览
论文阅读·人工智能·深度学习·机器学习·自然语言处理
数智工坊13 小时前
【DINOv2论文阅读】:无需监督的通用视觉特征提取器——机器人VLA模型的“眼睛“基石
论文阅读·人工智能·深度学习·计算机视觉·transformer
m0_6174939413 小时前
PyTorch CUDA设备不可用错误解决方案
人工智能·pytorch·python
Soari13 小时前
告别玩具级 Demo!深度拆解 agents-towards-production,用硬核工程把 AI Agent 推向工业级生产线
人工智能·软件工程·llmops·架构优化·genai·aiagent·生产级部署
minhuan13 小时前
RTX 4090显存终极优化:模型分层加载、CPU Offload显存和内存动态置换实践.179
人工智能·大模型应用·rtx 4090显存优化·模型分层加载·cpu offload优化