如何將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.