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!
相关推荐
AI医影跨模态组学1 小时前
Ann Oncol(IF=65.4)广东省人民医院放射科刘再毅&阿里巴巴达摩院等团队:基于非增强CT与深度学习的结直肠癌检测
人工智能·深度学习·论文·医学影像
学习论之费曼学习法1 小时前
AI 入门 30 天挑战 - Day 19 费曼学习法版 - GAN 生成对抗网络
人工智能·学习·生成对抗网络
数智工坊1 小时前
【Anchor DETR论文阅读】:基于锚点查询设计的Transformer检测器,50epoch收敛且速度精度双升
论文阅读·深度学习·transformer
guslegend1 小时前
第17节:模型忽略关键实体怎么办?注意力权重分配机制引导生成拒绝重点
人工智能·大模型·rag
Deepoch1 小时前
Deepoc 具身模型开发板赋能智能轮椅自主随行与安全控制技术研究
人工智能·科技·安全·开发板·deepoc·智能轮椅
Magic-Yuan1 小时前
算力的迷雾
人工智能·算法·机器学习
Hello未来1 小时前
llamafactory 的使用和安装
python·深度学习·语言模型·自然语言处理·nlp
财迅通Ai1 小时前
德福科技2025年净利增长145.91% 高端突破引领成长新篇
大数据·人工智能·科技·德福科技
AI医影跨模态组学1 小时前
Nature Reviews Cancer(IF=66.8)澳门科技大学张康教授等团队:人工智能推动多组学与临床数据整合在基础和转化癌症研究中的进展
人工智能·科技·深度学习·论文·医学影像
天使的翅膀20251 小时前
BM25为何精准匹配专有名词?
人工智能