CPU(central processing unit,中央处理器):主要包括控制器和运算器
GPU(Graphics processing unit, 图形处理器):处理统一的,无依赖的大规模数据运算
to函数: 转换数据类型/设备
1、tensor.to(*args, **kwargs)
2、tensor.to(*args, **kwargs)
区别: 张量不执行inplace, 模型执行inplace
tensor to cuda
import torch
import torch.nn as nn
import time
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# ========================== tensor to cuda
# flag = 0
flag = 1
if flag:
x_cpu = torch.ones((3,3))
print("x_cpu:\ndevice: {} is_cuda: {} id: {}".format(x_cpu.device, x_cpu.is_cuda, id(x_cpu)))
x_gpu = x_cpu.to(device)
print("x_gpu:\ndevice: {} is_cuda: {} id: {}".format(x_gpu.device, x_gpu.is_cuda, id(x_gpu)))
# 弃用
# x_gpu = x_cpu.cuda()

module to cuda
# ========================== module to cuda
# flag = 0
flag = 1
if flag:
net = nn.Sequential(nn.Linear(3, 3))
print("\nid:{} is_cuda: {}".format

本文探讨了CPU和GPU在PyTorch框架中的角色,包括如何将张量和模型迁移到GPU上,利用GPU加速计算。同时介绍了PyTorch中与CUDA相关的常用方法,以及如何使用DataParallel实现多GPU并行计算。
最低0.47元/天 解锁文章
9739

被折叠的 条评论
为什么被折叠?



