(三十六)CPU、GPU 与数据移动
# 项目文件:demos/device_move.py
import torch
from torch import nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Linear(2, 1).to(device)
x = torch.tensor([[1.0, 2.0]]).to(device)
with torch.inference_mode():
prediction = model(x)
print("本次设备", str(device), "输出形状", tuple(prediction.shape))
# 导出普通数值前回到 CPU;to 返回的张量要接住。
print("回到 CPU", prediction.cpu().device.type)torch.device 描述计算位置。模型的 .to(device) 移动已登记参数和缓冲数据,输入、目标也要移动到同一设备,后续计算才能组合。张量的 to 会交回转换结果,写成 x=x.to(device) 接住它。
本章锁定的是 CPU 包,这次输出设备为 cpu。准备 CUDA 环境时,在 官方安装选择器 中选择操作系统、Python 和对应计算平台,在另一份虚拟环境安装给出的包,再用 torch.cuda.is_available() 核对。运行设备与安装的计算后端、显卡驱动一起决定本次数据能去哪里。
把已训练检查点带到 CPU 上推理,读取时使用 map_location="cpu",模型也放在 CPU;参数名称和结构保持一致。.cpu().numpy() 可把结果交给 NumPy,带求导联系的中间结果先 detach();只取一个数时可用 item()。