从PyTorch文档中:
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
但是,当叶子e
和f
张量也都从CPU张量转换为Cuda张量(操作)时,为什么它们又被保留?
是因为在就地操作之前将Tensore
放入了Cuda吗?requires_grad_()
并且由于f
是通过赋值device="cuda"
而不是方法进行强制转换.cuda()
?
首次创建张量时,它成为叶节点。
基本上,神经网络的所有输入和权重都是计算图的叶节点。
在张量上执行任何操作时,它不再是叶节点。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句