mindspore.ops.InsertGradientOf

class mindspore.ops.InsertGradientOf(f)[source]

Attaches callback to the graph node that will be invoked on the node’s gradient.

Parameters

f (Function) – MindSpore’s Function. Callback function.

Inputs:
  • input_x (Any) - The graph node to attach to.

Outputs:

Tensor, returns input_x directly. InsertGradientOf does not affect the forward result.

Raises

TypeError – If f is not a function of mindspore.

Supported Platforms:

Ascend GPU CPU

Examples

>>> def clip_gradient(dx):
...     ret = dx
...     if ret > 1.0:
...         ret = 1.0
...
...     if ret < 0.2:
...         ret = 0.2
...
...     return ret
...
>>> clip = ops.InsertGradientOf(clip_gradient)
>>> grad_all = ops.GradOperation(get_all=True)
>>> def InsertGradientOfClipDemo():
...     def clip_test(x, y):
...         x = clip(x)
...         y = clip(y)
...         c = x * y
...         return c
...
...     @ms_function
...     def f(x, y):
...         return clip_test(x, y)
...
...     def fd(x, y):
...         return grad_all(clip_test)(x, y)
...
...     print("forward: ", f(1.1, 0.1))
...     print("clip_gradient:", fd(1.1, 0.1))
...