【问题标题】:In pytorch, what is difference between detach().requires_grad_(True) vs .cpu()?在 pytorch 中,detach().requires_grad_(True) 与 .cpu() 有什么区别?
【发布时间】:2022-11-01 16:41:18
【问题描述】:

在 pytorch 中,给定 x 是张量,x.detach().requires_grad_(True) 和 x.cpu() 有什么区别?

它们是相同的操作吗?

【问题讨论】:

    标签: pytorch


    【解决方案1】:
    1. tensor.cpu() 在 CPU 内存中返回此对象的副本,之后 x 的计算将在 cpu 上完成。

    2. tensor.detach() 返回一个新的张量,与当前计算图分离。结果永远不需要渐变。

    3. tensor.requires_grad_() 如果 autograd 应该记录此张量上的操作,则更改:就地设置此张量的 requires_grad 属性。如果使用x.requires_grad_(True),表示对x的操作会被记录下来,可以用来计算梯度。

      参考some resultstensor.requires_grad_()tensor.detach()不要更改变量所在的设备,这与tensor.cpu()不同。

      根据pytorch.org/docs/stable/generated/torch.Tensor.detach.html,现在不允许对tensor.detach() 进行就地修改,如add_(),如some results 所示。但是对tensor.cpu() 的这些操作是允许的。

    【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2018-12-10
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2014-03-22
    • 2021-05-13
    • 2012-11-22
    • 2019-12-23
    相关资源
    最近更新 更多