gpt4 book ai didi

pytorch - `torch.Tensor` 和 `torch.cuda.Tensor` 的区别

转载 作者:行者123 更新时间:2023-12-01 01:43:34 26 4
gpt4 key购买 nike

我们可以使用 torch.Tensor([1., 2.], device='cuda') 在 GPU 上分配张量.使用这种方式而不是torch.cuda.Tensor([1., 2.])有什么不同吗? ,除了我们可以将特定的 CUDA 设备传递给前一个?

或者换句话说,在哪种情况下是torch.cuda.Tensor()必要的?

最佳答案

所以一般都是torch.Tensortorch.cuda.Tensor是等价的。你可以用它们做任何你喜欢的事情。

关键区别在于 torch.Tensor torch.cuda.Tensor 时占用 CPU 内存占用GPU内存。当然,CPU 张量上的操作是用 CPU 计算的,而 GPU/CUDA 张量的操作是在 GPU 上计算的。

您需要这两种张量类型的原因是底层硬件接口(interface)完全不同。除了它在计算上没有意义之外,一旦你尝试在 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'

由于底层硬件接口(interface)完全不同,CPU Tensor 只兼容 CPU Tensor,而 verse Visa GPU Tensors 只兼容 GPU Tensor。

编辑:

正如您在此处看到的,移动到 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 张量,这里不能混合。

关于pytorch - `torch.Tensor` 和 `torch.cuda.Tensor` 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com