torch.Tensor.is_leaf¶
- Tensor.is_leaf¶
所有
requires_grad
为False
的张量将按惯例成为叶子张量。对于具有
requires_grad
属性为True
的张量,如果它们是由用户创建的,那么它们将是叶子张量。这意味着它们不是操作的结果,因此grad_fn
为None。只有在调用
backward()
时,叶张量才会填充其grad
。 要为非叶张量填充grad
,您可以使用retain_grad()
。示例:
>>> a = torch.rand(10, requires_grad=True) >>> a.is_leaf True >>> b = torch.rand(10, requires_grad=True).cuda() >>> b.is_leaf False # b 是由将 cpu Tensor 转换为 cuda Tensor 的操作创建的 >>> c = torch.rand(10, requires_grad=True) + 2 >>> c.is_leaf False # c 是由加法操作创建的 >>> d = torch.rand(10).cuda() >>> d.is_leaf True # d 不需要梯度,因此没有创建它的操作(由 autograd 引擎跟踪) >>> e = torch.rand(10).cuda().requires_grad_() >>> e.is_leaf True # e 需要梯度并且没有创建它的操作 >>> f = torch.rand(10, requires_grad=True, device="cuda") >>> f.is_leaf True # f 需要梯度,没有创建它的操作