如何理解在PyTorch中创建叶张量?

2024-05-05 02:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

来自PyTorchdocumentation

b = torch.rand(10, requires_grad=True).cuda()
b.is_leaf
False
# b was created by the operation that cast a cpu Tensor into a cuda Tensor

e = torch.rand(10).cuda().requires_grad_()
e.is_leaf
True
# e requires gradients and has no operations creating it

f = torch.rand(10, requires_grad=True, device="cuda")
f.is_leaf
True
# f requires grad, has no operation creating it

但是ef叶张量为什么也从CPU张量转换成Cuda张量(一种操作)

是因为张量e在原位操作requires_grad_()之前被投射到Cuda

因为f是通过赋值device="cuda"而不是通过方法.cuda()强制转换的


Tags: nocreatingtrueisdeviceittorchoperation
1条回答
网友
1楼 · 发布于 2024-05-05 02:51:43

第一次创建张量时,它将成为叶节点

基本上,神经网络的所有输入和权重都是计算图的叶节点

当对张量执行任何操作时,它不再是叶节点

b = torch.rand(10, requires_grad=True) # create a leaf node
b.is_leaf # True
b = b.cuda() # perform a casting operation
b.is_leaf # False

requires_grad_()不是与cuda()或其他操作相同的操作。
它创建了一个新的张量,因为需要梯度(可训练权重)的张量不能依赖于其他任何东西

e = torch.rand(10) # create a leaf node
e.is_leaf # True
e = e.cuda() # perform a casting operation
e.is_leaf # False
e = e.requires_grad_() # this creates a NEW tensor
e.is_leaf # True

另外,detach()操作创建一个不需要梯度的新张量:

b = torch.rand(10, requires_grad=True)
b.is_leaf # True
b = b.detach()
b.is_leaf # True

在上一个示例中,我们创建了一个新的张量,它已经在cuda设备上了。
我们不需要任何手术来投下它

f = torch.rand(10, requires_grad=True, device="cuda") # create a leaf node on cuda

相关问题 更多 >