mindspore.ops.vjp

mindspore.ops.vjp(fn, inputs, v)[source]

Compute the vector-jacobian-product of the given network. vjp matches reverse-mode differentiation.

Note

This function is subjected to change in the future.

Parameters
  • fn (Union[Function, Cell]) – The function or net that takes Tensor inputs and returns single Tensor or tuple of Tensors.

  • inputs (Union[Tensor, tuple[Tensor], list[Tensor]]) – The inputs to fn .

  • v (Union[Tensor, tuple[Tensor], list[Tensor]]) – The vector in vector-jacobian-product. The shape and type of v should be the same as fn(inputs) .

Returns

  • net_output (Union[Tensor, tuple[Tensor]]) - The result of fn(inputs) .

  • vjp (Union[Tensor, tuple[Tensor]]) - The result of vector-jacobian-product.

Raises

TypeErrorinputs or v does not belong to required types.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import ops
>>> from mindspore import Tensor
>>> class Net(nn.Cell):
...     def construct(self, x, y):
...         return x**3 + y
>>> x = Tensor(np.array([[1, 2], [3, 4]]).astype(np.float32))
>>> y = Tensor(np.array([[1, 2], [3, 4]]).astype(np.float32))
>>> v = Tensor(np.array([[1, 1], [1, 1]]).astype(np.float32))
>>> output = ops.vjp(Net(), (x, y), v)
>>> print(output[0])
[[ 2. 10.]
 [30. 68.]]
>>> print(output[1])
(Tensor(shape=[2, 2], dtype=Float32, value=
[[ 3.00000000e+00,  1.20000000e+01],
 [ 2.70000000e+01,  4.80000000e+01]]), Tensor(shape=[2, 2], dtype=Float32, value=
[[ 1.00000000e+00,  1.00000000e+00],
 [ 1.00000000e+00,  1.00000000e+00]]))