qml.QNode

class QNode(func, device, interface='autograd', diff_method='best', expansion_strategy='gradient', max_expansion=10, mode='best', cache=True, cachesize=10000, max_diff=1, **gradient_kwargs)[source]

Bases: object

Represents a quantum node in the hybrid computational graph.

A quantum node contains a quantum function (corresponding to a variational circuit) and the computational device it is executed on.

The QNode calls the quantum function to construct a QuantumTape instance representing the quantum circuit.

Parameters
  • func (callable) – a quantum function

  • device (Device) – a PennyLane-compatible device

  • interface (str) –

    The interface that will be used for classical backpropagation. This affects the types of objects that can be passed to/returned from the QNode. See qml.interfaces.SUPPORTED_INTERFACES for a list of all accepted strings.

    • "autograd": Allows autograd to backpropagate through the QNode. The QNode accepts default Python types (floats, ints, lists, tuples, dicts) as well as NumPy array arguments, and returns NumPy arrays.

    • "torch": Allows PyTorch to backpropagate through the QNode. The QNode accepts and returns Torch tensors.

    • "tf": Allows TensorFlow in eager mode to backpropagate through the QNode. The QNode accepts and returns TensorFlow tf.Variable and tf.tensor objects.

    • "jax": Allows JAX to backpropagate through the QNode. The QNode accepts and returns JAX DeviceArray objects.

    • None: The QNode accepts default Python types (floats, ints, lists, tuples, dicts) as well as NumPy array arguments, and returns NumPy arrays. It does not connect to any machine learning library automatically for backpropagation.

    • "auto": The QNode automatically detects the interface from the input values of the quantum function.

  • diff_method (str or gradient_transform) –

    The method of differentiation to use in the created QNode. Can either be a gradient_transform, which includes all quantum gradient transforms in the qml.gradients module, or a string. The following strings are allowed:

    • "best": Best available method. Uses classical backpropagation or the device directly to compute the gradient if supported, otherwise will use the analytic parameter-shift rule where possible with finite-difference as a fallback.

    • "device": Queries the device directly for the gradient. Only allowed on devices that provide their own gradient computation.

    • "backprop": Use classical backpropagation. Only allowed on simulator devices that are classically end-to-end differentiable, for example default.qubit. Note that the returned QNode can only be used with the machine-learning framework supported by the device.

    • "adjoint": Uses an adjoint method that reverses through the circuit after a forward pass by iteratively applying the inverse (adjoint) gate. Only allowed on supported simulator devices such as default.qubit.

    • "parameter-shift": Use the analytic parameter-shift rule for all supported quantum operation arguments, with finite-difference as a fallback.

    • "finite-diff": Uses numerical finite-differences for all quantum operation arguments.

    • None: QNode cannot be differentiated. Works the same as interface=None.

  • expansion_strategy (str) –

    The strategy to use when circuit expansions or decompositions are required.

    • gradient: The QNode will attempt to decompose the internal circuit such that all circuit operations are supported by the gradient method. Further decompositions required for device execution are performed by the device prior to circuit execution.

    • device: The QNode will attempt to decompose the internal circuit such that all circuit operations are natively supported by the device.

    The gradient strategy typically results in a reduction in quantum device evaluations required during optimization, at the expense of an increase in classical preprocessing.

  • max_expansion (int) – The number of times the internal circuit should be expanded when executed on a device. Expansion occurs when an operation or measurement is not supported, and results in a gate decomposition. If any operations in the decomposition remain unsupported by the device, another expansion occurs.

  • mode (str) – Whether the gradients should be computed on the forward pass (forward) or the backward pass (backward). Only applies if the device is queried for the gradient; gradient transform functions available in qml.gradients are only supported on the backward pass.

  • cache (bool or dict or Cache) – Whether to cache evaluations. This can result in a significant reduction in quantum evaluations during gradient computations. If True, a cache with corresponding cachesize is created for each batch execution. If False, no caching is used. You may also pass your own cache to be used; this can be any object that implements the special methods __getitem__(), __setitem__(), and __delitem__(), such as a dictionary.

  • cachesize (int) – The size of any auto-created caches. Only applies when cache=True.

  • max_diff (int) – If diff_method is a gradient transform, this option specifies the maximum number of derivatives to support. Increasing this value allows for higher order derivatives to be extracted, at the cost of additional (classical) computational overhead during the backwards pass.

Keyword Arguments

**kwargs – Any additional keyword arguments provided are passed to the differentiation method. Please refer to the qml.gradients module for details on supported options for your chosen gradient transform.

Example

QNodes can be created by decorating a quantum function:

>>> dev = qml.device("default.qubit", wires=1)
>>> @qml.qnode(dev)
... def circuit(x):
...     qml.RX(x, wires=0)
...     return expval(qml.PauliZ(0))

or by instantiating the class directly:

>>> def circuit(x):
...     qml.RX(x, wires=0)
...     return expval(qml.PauliZ(0))
>>> dev = qml.device("default.qubit", wires=1)
>>> qnode = qml.QNode(circuit, dev)

interface

The interface used by the QNode

qtape

The quantum tape

tape

The quantum tape

interface

The interface used by the QNode

qtape

The quantum tape

tape

The quantum tape

__call__(*args, **kwargs)

Call self as a function.

best_method_str(device, interface)

Similar to get_best_method(), except return the ‘best’ differentiation method in human-readable format.

construct(args, kwargs)

Call the quantum function with a tape context, ensuring the operations get queued.

get_best_method(device, interface)

Returns the ‘best’ differentiation method for a particular device and interface combination.

get_gradient_fn(device, interface[, diff_method])

Determine the best differentiation method, interface, and device for a requested device, interface, and diff method.

__call__(*args, **kwargs)[source]

Call self as a function.

static best_method_str(device, interface)[source]

Similar to get_best_method(), except return the ‘best’ differentiation method in human-readable format.

This method attempts to determine support for differentiation methods using the following order:

  • "device"

  • "backprop"

  • "parameter-shift"

  • "finite-diff"

The first differentiation method that is supported (going from top to bottom) will be returned.

This method is intended only for debugging purposes. Otherwise, get_best_method() should be used instead.

Parameters
  • device (Device) – PennyLane device

  • interface (str) – name of the requested interface

Returns

The gradient function to use in human-readable format.

Return type

str

construct(args, kwargs)[source]

Call the quantum function with a tape context, ensuring the operations get queued.

static get_best_method(device, interface)[source]

Returns the ‘best’ differentiation method for a particular device and interface combination.

This method attempts to determine support for differentiation methods using the following order:

  • "device"

  • "backprop"

  • "parameter-shift"

  • "finite-diff"

The first differentiation method that is supported (going from top to bottom) will be returned.

Parameters
  • device (Device) – PennyLane device

  • interface (str) – name of the requested interface

Returns

Tuple containing the gradient_fn, gradient_kwargs, and the device to use when calling the execute function.

Return type

tuple[str or gradient_transform, dict, Device

static get_gradient_fn(device, interface, diff_method='best')[source]

Determine the best differentiation method, interface, and device for a requested device, interface, and diff method.

Parameters
  • device (Device) – PennyLane device

  • interface (str) – name of the requested interface

  • diff_method (str or gradient_transform) – The requested method of differentiation. If a string, allowed options are "best", "backprop", "adjoint", "device", "parameter-shift", or "finite-diff". A gradient transform may also be passed here.

Returns

Tuple containing the gradient_fn, gradient_kwargs, and the device to use when calling the execute function.

Return type

tuple[str or gradient_transform, dict, Device

Contents

Using PennyLane

Development

API

Internals