簡體   English   中英

`torch.Tensor`和`torch.cuda.Tensor`之間的區別

[英]Differences between `torch.Tensor` and `torch.cuda.Tensor`

我們可以使用torch.Tensor([1., 2.], device='cuda')在GPU上分配張量。 使用這種方式有什么不同而不是torch.cuda.Tensor([1., 2.]) ,除了我們可以將特定的CUDA設備傳遞給前者嗎?

或者換句話說,在哪種情況下, torch.cuda.Tensor()必要的?

所以一般來說, torch.Tensortorch.cuda.Tensor都是等價的。 你可以用它們做你喜歡的一切。

關鍵區別在於torch.Tensor占用CPU內存,而torch.cuda.Tensor占用GPU內存。 當然在CPU張量運算計算具有CPU,而對於GPU操作CUDA張量計算上GPU /。

您需要這兩種張量類型的原因是底層硬件接口完全不同。 除了它在計算上沒有意義之外,一旦你嘗試在torch.Tensortorch.cuda.Tensor之間進行計算,你就會收到錯誤:

import torch

# device will be 'cuda' if a GPU is available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# creating a CPU tensor
cpu_tensor = torch.rand(10)
# moving same tensor to GPU
gpu_tensor = cpu_tensor.to(device)

print(cpu_tensor, cpu_tensor.dtype, type(cpu_tensor), cpu_tensor.type())
print(gpu_tensor, gpu_tensor.dtype, type(gpu_tensor), gpu_tensor.type())

print(cpu_tensor*gpu_tensor)

輸出:

tensor([0.8571, 0.9171, 0.6626, 0.8086, 0.6440, 0.3682, 0.9920, 0.4298, 0.0172,
        0.1619]) torch.float32 <class 'torch.Tensor'> torch.FloatTensor
tensor([0.8571, 0.9171, 0.6626, 0.8086, 0.6440, 0.3682, 0.9920, 0.4298, 0.0172,
        0.1619], device='cuda:0') torch.float32 <class 'torch.Tensor'> torch.cuda.FloatTensor
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-15-ac794171c178> in <module>()
     12 print(gpu_tensor, gpu_tensor.dtype, type(gpu_tensor), gpu_tensor.type())
     13 
---> 14 print(cpu_tensor*gpu_tensor)

RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument #2 'other'

由於底層硬件接口完全不同,CPU Tensors只與CPU Tensor和verse visa兼容GPU張量只與GPU Tensors兼容。

編輯:

正如你在這里看到的那樣,移動到GPU的張量實際上是一種類型的張量: torch.cuda.*Tensortorch.cuda.FloatTensor

所以cpu_tensor.to(device)torch.Tensor([1., 2.], device='cuda')實際上會返回一個類型為torch.cuda.FloatTensor的張量。

在哪種情況下, torch.cuda.Tensor()必要的?

如果你想為你的程序使用GPU加速(在大多數情況下速度要快得多) ,你需要使用torch.cuda.Tensor ,但你必須確保你使用的所有張量都是CUDA張量,混合是不可能的這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM