pytorch小知识点(一)-------in-place operation

一、什么是in-place

在pytorch的很多函数中经常看到in-place选项,具体是什么意思一直一知半解。这次专门来学习一下,in-place operation在pytorch中是指改变一个tensor的值的时候,不经过复制操作,而是直接在原来的内存上改变它的值。可以把它称为原地操作符。

在pytorch中经常加后缀“_”来代表原地in-place operation,比如说.add_() 或者.scatter()。我们可以将in_place操作简单的理解类似于python中的"+=","-="等操作。

举个例子,下面是正常的加操作,执行结束后x的值没有变化

import torch

x = torch.rand(2)

x
Out[3]: tensor([0.3486, 0.2924])   #<-----这是x初始值


y = torch.rand(2)

y
Out[5]: tensor([0.6301, 0.0101])   #<-----这是y初始值

x.add(y)
Out[6]: tensor([0.9788, 0.3026])     #<-----这是x+y的结果

x
Out[7]: tensor([0.3486, 0.2924])    #<-----这是执行操作之后x的值

y
Out[8]: tensor([0.6301, 0.0101])     #<-----这是执行操作之后y的值

我们可以发现,在正常操作之后原操作数的值不会发生变化。

下面我们来看看in_place操作

import torch

x = torch.rand(2)

x
Out[3]: tensor([0.3486, 0.2924])   #<-----这是x初始值


y = torch.rand(2)

y
Out[5]: tensor([0.6301, 0.0101])   #<-----这是y初始值

x.add_(y)
Out[9]: tensor([0.9788, 0.3026])   #<-----这是x+y结果

x
Out[10]: tensor([0.9788, 0.3026])  #<-----这是操作后x的值

y
Out[11]: tensor([0.6301, 0.0101])   #<-----这是操作后y的值

通过对比可以发现,in_place操作之后,原操作数等于表达式计算结果。也就是说将计算结果赋给了原操作数。

二、不能使用in-place的情况

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

参考资料:

【1】关于pytorch-inplace operation你需要知道的几件事

猜你喜欢

转载自blog.csdn.net/goodxin_ie/article/details/89577224
今日推荐