The QNode decorator

Module name: pennylane.decorator

Decorator for converting a quantum circuit function containing PennyLane quantum operations to a QNode that will run on a quantum device.

This decorator is provided for convenience, and allows a quantum circuit function to be converted to a QNode implicitly, avoiding the need to manually instantiate a QNode object.

Note that the decorator completely replaces the Python-defined function with a QNode of the same name - as such, the original function is no longer accessible (but is accessible via the func attribute).

Example

dev1 = qml.device('default.qubit', wires=2)

@qml.qnode(dev1)
def qfunc1(x):
    qml.RZ(x, wires=0)
    qml.CNOT(wires=[0,1])
    qml.RY(x, wires=1)
    return qml.expval.PauliZ(0)

result = qfunc1(0.543)

Once defined, the QNode can then be used like any other function in Python. This includes combining it with other QNodes and classical functions to build a hybrid computation. For example,

dev2 = qml.device('default.gaussian', wires=2)

@qml.qnode(dev2)
def qfunc2(x, y):
    qml.Displacement(x, 0, wires=0)
    qml.Beamsplitter(y, 0, wires=[0, 1])
    return qml.expval.MeanPhoton(0)

def hybrid_computation(x, y):
    return np.sin(qfunc1(y))*np.exp(-qfunc2(x+y, x)**2)

Note

Applying the qnode() decorator to a user-defined function is equivalent to instantiating the QNode object manually. For example, the above example can also be written as follows:

def qfunc1(x):
    qml.RZ(x, wires=0)
    qml.CNOT(wires=[0,1])
    qml.RY(x, wires=1)
    return qml.expval.PauliZ(0)

qnode1 = qml.QNode(qfunc1, dev1)
result = qnode1(0.543)

Classical interface support (experimental)

To try one of the new classical machine learning interfaces, you can specify the interface keyword argument when using the QNode decorator.

Current classical interfaces include:

If not specified, the standard NumPy/autograd classical interface,

from pennylane import numpy as np

is used, which enhances standard NumPy functions with automatic differentiation via the Autograd package.

Code details

qnode(device, interface='numpy')[source]

QNode decorator.

Parameters:
  • device (Device) – a PennyLane-compatible device
  • interface (str) –

    the interface that will be used for automatic differentiation and classical processing. This affects the types of objects that can be passed to/returned from the QNode:

    • interface='numpy': The QNode accepts default Python types (floats, ints, lists) as well as NumPy array arguments, and returns NumPy arrays.
    • interface='torch': The QNode accepts and returns Torch tensors.
    • interface='tfe': The QNode accepts and returns eager execution TensorFlow tfe.Variable objects.