如何将Torch张量在CPU和GPU之间移动?


CPU上定义的Torch张量可以移动到GPU,反之亦然。对于高维张量计算,GPU利用并行计算的能力来减少计算时间。

诸如图像之类的多维张量计算密集型且耗时,如果在CPU上运行则需要很长时间。因此,我们需要将此类张量移动到GPU。

语法

  • 要将Torch张量从CPU移动到GPU,可以使用以下语法:

Tensor.to("cuda:0")
or
Tensor.to(cuda)

并且,

Tensor.cuda()
  • 要将Torch张量从GPU移动到CPU,可以使用以下语法:

Tensor.to("cpu")

并且,

Tensor.cpu()

让我们来看几个例子,演示如何将张量从CPU移动到GPU,反之亦然。

注意 - 我为每个程序提供了两个不同的输出。一个输出适用于只有CPU的系统,另一个输出适用于同时具有GPU和CPU的系统。

示例1

# Python program to move a tensor from CPU to GPU
# import torch library
import torch

# create a tensor
x = torch.tensor([1.0,2.0,3.0,4.0])
print("Tensor:", x)

# check tensor device (cpu/cuda)
print("Tensor device:", x.device)

# Move tensor from CPU to GPU
# check CUDA GPU is available or not
print("CUDA GPU:", torch.cuda.is_available())
if torch.cuda.is_available():
   x = x.to("cuda:0")
   # or x=x.to("cuda")
print(x)

# now check the tensor device
print("Tensor device:", x.device)

输出1 - 当GPU不可用时

Tensor: tensor([1., 2., 3., 4.])
Tensor device: cpu
CUDA GPU: False
tensor([1., 2., 3., 4.])
Tensor device: cpu

输出2 - 当GPU可用时

Tensor: tensor([1., 2., 3., 4.])
Tensor device: cpu
CUDA GPU: True
tensor([1., 2., 3., 4.], device='cuda:0')
Tensor device: cuda:0

示例2

# Python program to move a tensor from CPU to GPU
# import torch library
import torch

# create a tensor on CPU
x = torch.tensor([1.0,2.0,3.0,4.0])
print("Tensor:", x)
print("Tensor device:", x.device)

# Move tensor from CPU to GPU
if torch.cuda.is_available():
   x = x.cuda()
print(x)
# now check the tensor device
print("Tensor device:", x.device)

输出1 - 如果GPU不可用

Tensor: tensor([1., 2., 3., 4.])
Tensor device: cpu
tensor([1., 2., 3., 4.])
Tensor device: cpu

输出2 - 如果GPU可用

Tensor: tensor([1., 2., 3., 4.])
Tensor device: cpu
tensor([1., 2., 3., 4.], device='cuda:0')
Tensor device: cuda:0

示例3

# Python program to move a tensor from GPU to CPU
# import torch library
import torch

# create a tensor on GPU
if torch.cuda.is_available():
   x = torch.tensor([1.0,2.0,3.0,4.0], device = "cuda")
print("Tensor:", x)
print("Tensor device:", x.device)

# Move tensor from GPU to CPU
x = x.to("cpu")
# x = x.cpu()
print(x)

# Now check the tensor device
print("Tensor device:", x.device)

输出1 - 如果GPU不可用

Tensor: tensor([1., 2., 3., 4.])
Tensor device: cpu
tensor([1., 2., 3., 4.])
Tensor device: cpu

输出2 - 如果GPU可用

Tensor: tensor([1., 2., 3., 4.], device='cuda:0')
Tensor device: cuda:0
tensor([1., 2., 3., 4.])
Tensor device: cpu

更新于:2023年11月6日

25K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.