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!
相关推荐
故事挺秃然6 分钟前
NLP模型优化
人工智能·自然语言处理·nlp
文火冰糖的硅基工坊14 分钟前
[人工智能-大模型-78]:模型层技术 - 深度神经网络的网络架构的演进,这不仅是一条技术路线图,更是一部 “机器如何逐步逼近人类认知方式” 的进化史诗。
人工智能·架构·dnn
IT古董16 分钟前
【第六章:项目实战之推荐/广告系统】3.精排算法-(2)精排算法模型精讲: DNN、deepFM、ESMM、PLE、MMOE算法精讲与实现- DNN 精排模型
人工智能·神经网络·dnn
IT古董17 分钟前
【第六章:项目实战之推荐/广告系统】3.精排算法-(2)精排算法模型精讲: DNN、deepFM、ESMM、PLE、MMOE算法精讲与实现- PLE 模型
人工智能·神经网络·dnn
Serverless 社区21 分钟前
吉利汽车携手阿里云函数计算,打造新一代 AI 座舱推理引擎
人工智能·阿里云·汽车
没有梦想的咸鱼185-1037-166339 分钟前
AI大模型支持下的:ArcGIS数据处理、空间分析、可视化及多案例综合应用
人工智能·arcgis·chatgpt·数据分析
青春不败 177-3266-052039 分钟前
AI+ArcGIS:数据处理、空间分析、可视化前沿技术应
人工智能·arcgis·gis·生态学·可视化·数据处理
新智元1 小时前
老黄亲自站台,英伟达编程神器!Cursor 2.0 自研模型狂飙 4 倍
人工智能·openai
新智元1 小时前
AI是「天才」还是「话术大师」?Anthropic颠覆性实验,终揭答案!
人工智能·openai
TG:@yunlaoda360 云老大1 小时前
2025云栖大会举行:阿里云旗舰模型Qwen3-Max、下一代架构Qwen3-Next重磅发布,加速构建“云智一体”AI超级计算机
人工智能·阿里云·架构