我们可以使用torch.Tensor([1., 2.], device='cuda')在GPU上分配张量。使用这种方式而不是使用torch.cuda.Tensor([1., 2.])有什么不同,除了我们可以将一个特定的CUDA设备传递给前者吗?
或者换句话说,在哪种场景中需要torch.cuda.Tensor()?
发布于 2018-12-05 10:36:46
因此,一般来说,torch.Tensor和torch.cuda.Tensor都是等价的。你可以用他们做任何你喜欢的事。
关键的区别是torch.Tensor占用CPU内存,而torch.cuda.Tensor占用GPU内存。当然,CPU张量上的操作是用CPU计算的,而GPU / CUDA张量的操作是在GPU上计算的。
您需要这两种张量类型的原因是底层硬件接口完全不同。除了这一点外,在计算上没有意义,只要您尝试在torch.Tensor和torch.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张量只与CPU张量兼容,visa张量只与GPU张量兼容。
编辑:
正如你在这里看到的,一个张量被移动到GPU实际上是一个类型的张量:torch.cuda.*Tensor,即torch.cuda.FloatTensor,__。
因此,cpu_tensor.to(device)或torch.Tensor([1., 2.], device='cuda')实际上会返回torch.cuda.FloatTensor__类型的张量。
在哪种场景中需要torch.cuda.Tensor() ?
当您想要为您的程序使用GPU加速(在大多数情况下要快得多)时,您需要使用torch.cuda.Tensor,但是您必须确保使用的所有张量都是CUDA张量,在这里不可能混合。
https://stackoverflow.com/questions/53628940
复制相似问题