pytorch---之什么时候in-place操作不能用

原文发表在 知乎上 在这里就做一下同步吧。
(本文章适用于 pytorch0.4.0 版本, 既然 Variable 和 Tensor merge 到一块了, 那就叫 Tensor吧)

在编写 pytorch 代码的时候, 如果模型很复杂, 代码写的很随意, 那么很有可能就会碰到由 inplace operation 导致的问题. 所以本文将对 pytorch 的 inplace operation 做一个简单的总结.

在 pytorch 中, 有两种情况不能使用 inplace operation:

  • 对于 requires_grad=True 的 叶子张量(leaf tensor) 不能使用 inplace operation
  • 对于在 求梯度阶段需要用到的张量 不能使用 inplace operation

下面将通过代码来说明以上两种情况:

第一种情况: requires_grad=True 的 leaf tensor

import torch

w = torch.FloatTensor(10) # w 是个 leaf tensor
w.requires_grad = True    # 将 requires_grad 设置为 True
w.normal_()               # 在执行这句话就会报错
# 报错信息为
#  RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
  •  

很多人可能会有疑问, 模型的参数就是 requires_grad=true 的 leaf tensor, 那么模型参数的初始化应该怎么执行呢? 如果看一下 nn.Module._apply() 的代码, 这问题就会很清楚了

w.data = w.data.normal() # 可以使用曲线救国的方法来初始化参数

第二种情况: 求梯度阶段需要用到的张量

import torch
x = torch.FloatTensor([[1., 2.]])
w1 = torch.FloatTensor([[2.], [1.]])
w2 = torch.FloatTensor([3.])
w1.requires_grad = True
w2.requires_grad = True

d = torch.matmul(x, w1)
f = torch.matmul(d, w2)
d[:] = 1 # 因为这句, 代码报错了 RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

f.backward()
  •  

为什么呢?

因为 f=matmul(d, w2) , ∂f∂w2=g(d)

--------------------- 本文来自 ke1th 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/u012436149/article/details/80819523?utm_source=copy

扫描二维码关注公众号,回复: 3538435 查看本文章

猜你喜欢

转载自blog.csdn.net/zxyhhjs2017/article/details/82843657