enable_grad

class paddle. enable_grad [source]
Api_attr

imperative

Create a context which enable dygraph gradient calculation, if it has been disabled by no_grad or set_grad_enabled.

In this mode, the result of every computation will have stop_gradient set to False.

Also functions as a decorator. (Make sure to use an instance.)

Examples

import paddle

# use as generator

x = paddle.to_tensor([1.], stop_gradient=False)
with paddle.no_grad():
    with paddle.enable_grad():
        y = x * 2
assert(y.stop_gradient == False)
y.backward()
assert(x.grad is not None)

# use as decorator

@paddle.enable_grad()
def double(x):
    return x * 2

with paddle.no_grad():
    z = double(x)

assert(z.stop_gradient == False)