no_grad

class paddle. no_grad

创建一个上下文来禁用动态图梯度计算。在此模式下,每次计算的结果都将具有stop_gradient=True。

也可以用作一个装饰器(需要创建实例对象作为装饰器)。

代码示例

  1. import numpy as np
  2. import paddle
  3. # 用作生成器
  4. data = np.array([[2, 3], [4, 5]]).astype('float32')
  5. l0 = paddle.nn.Linear(2, 2) # l0.weight.gradient() is None
  6. l1 = paddle.nn.Linear(2, 2)
  7. with paddle.no_grad():
  8. # l1.weight.stop_gradient is False
  9. tmp = l1.weight * 2 # tmp.stop_gradient is True
  10. x = paddle.to_tensor(data)
  11. y = l0(x) + tmp
  12. o = l1(y)
  13. o.backward()
  14. print(tmp.gradient() is None) # True
  15. print(l0.weight.gradient() is None) # False
  16. # 用作装饰器
  17. @paddle.no_grad()
  18. def test_layer():
  19. inp = np.ones([3, 1024], dtype='float32')
  20. t = paddle.to_tensor(inp)
  21. linear1 = paddle.nn.Linear(1024, 4, bias_attr=False)
  22. linear2 = paddle.nn.Linear(4, 4)
  23. ret = linear1(t)
  24. dy_ret = linear2(ret)
  25. test_layer()