【问题标题】:How to understand creating leaf tensors in PyTorch?如何理解在 PyTorch 中创建叶张量?
【发布时间】:2021-03-17 17:14:06
【问题描述】:

来自 PyTorch documentation:

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() 转换的?

【问题讨论】:

    标签: python pytorch documentation


    【解决方案1】:

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

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-08
      • 2021-10-30
      • 2019-02-21
      • 2020-11-01
      • 2019-04-25
      • 2021-12-25
      • 2021-11-04
      • 2021-02-01
      相关资源
      最近更新 更多