qml.numpy

Overview

The PennyLane NumPy subpackage provides a differentiable wrapper around NumPy, that enables backpropagation through standard NumPy code.

This version of NumPy must be used when using PennyLane with the Autograd interface:

>>> from pennylane import numpy as np

Note

If using other interfaces, such as TensorFlow PyTorch, or JAX, then the PennyLane-provided NumPy should not be used; instead, simply use the standard NumPy import.

This package is a wrapper around autograd.numpy; for details on all available functions, please refer to the Autograd docs.

PennyLane additionally extends Autograd with the following classes, errors, and functions:

wrap_arrays

Loop through an object's symbol table, wrapping each function with tensor_wrapper().

extract_tensors

Iterate through an iterable, and extract any PennyLane tensors that appear.

tensor_wrapper

Decorator that wraps callable objects and classes so that they both accept a requires_grad keyword argument, as well as returning a PennyLane tensor.

tensor

Constructs a PennyLane tensor for use with Autograd QNodes.

NonDifferentiableError

Exception raised if attempting to differentiate non-trainable tensor using Autograd.

Caveats

This package is a wrapper around autograd.numpy, and therefore comes with several caveats inherited from Autograd:

Do not use:

  • Assignment to arrays, such as A[0, 0] = x.

  • Implicit casting of lists to arrays, for example A = np.sum([x, y]). Make sure to explicitly cast to a NumPy array first, i.e., A = np.sum(np.array([x, y])) instead.

  • A.dot(B) notation. Use np.dot(A, B) or A @ B instead.

  • In-place operations such as a += b. Use a = a + b instead.

  • Some isinstance checks, like isinstance(x, np.ndarray) or isinstance(x, tuple), without first doing from autograd.builtins import isinstance, tuple.

For more details, please consult the Autograd docs.