# The quantum node object¶

Module name: pennylane.qnode

The QNode class is used to construct quantum nodes, encapsulating a quantum function or variational circuit and the computational device it is executed on.

The computational device is an instance of the Device class, and can represent either a simulator or hardware device. They can be instantiated using the device() loader. PennyLane comes included with some basic devices; additional devices can be installed as plugins (see Plugins and ecosystem for more details).

## Quantum circuit functions¶

The quantum circuit function encapsulated by the QNode must be of the following form:

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


Quantum circuit functions are a restricted subset of Python functions, adhering to the following constraints:

• The body of the function must consist of only supported PennyLane operations, one per line.

• The function must always return either a single or a tuple of measured observable values, by applying a measurement function to an observable.

• Classical processing of function arguments, either by arithmetic operations or external functions, is not allowed. One current exception is simple scalar multiplication.

Note

The quantum operations cannot be used outside of a quantum circuit function, as all Operations require a QNode in order to perform queuing on initialization.

Note

Measured observables must come after all other operations at the end of the circuit function as part of the return statement, and cannot appear in the middle.

After the device and quantum circuit function are defined, a QNode object must be created which wraps this function and binds it to the device. Once created, the QNode can be used to evaluate the specified quantum circuit function on the particular device.

For example:

device = qml.device('default.qubit', wires=2)
qnode1 = qml.QNode(my_quantum_function, device)
result = qnode1(np.pi/4, 0.7)


Note

The qnode() decorator is provided as a convenience to automate the process of creating quantum nodes. The decorator is used as follows:

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

result = my_quantum_function(np.pi/4, 0.7)


## QNode methods¶

 __call__(*args, **kwargs) Wrapper for evaluate(). evaluate(**kwargs) Evaluates the quantum function on the specified device. evaluate_obs(obs, args, **kwargs) Evaluate the value of the given observables. jacobian(params[, which, method, h, order]) Compute the Jacobian of the QNode.

## QNode internal methods¶

 construct(args[, kwargs]) Constructs a representation of the quantum circuit. Determine the correct gradient computation method for a free parameter. Appends a quantum operation into the circuit queue. _op_successors(o_idx[, only, get_nodes]) Successors of the given operation in the quantum circuit. _pd_finite_diff(params, idx[, h, order, y0]) Partial derivative of the node using the finite difference method. _pd_analytic(params, idx[, force_order2]) Partial derivative of the node using the analytic method.

### Code details¶

pop_jacobian_kwargs(kwargs)[source]

Remove QNode.jacobian specific keyword arguments from a dictionary.

This is required to correctly pass the user-defined keyword arguments to the QNode quantum function.

Parameters

kwargs (dict) – dictionary of keyword arguments

Returns

keyword arguments with all QNode.jacobian keyword arguments removed

Return type

dict

exception QuantumFunctionError[source]

Exception raised when an illegal operation is defined in a quantum function.

__weakref__

list of weak references to the object (if defined)

class QNode(func, device, cache=False)[source]

Quantum node in the hybrid computational graph.

Parameters
• func (callable) – a Python function containing Operation constructor calls, returning a tuple of measured Observable instances.

• device (Device) – device to execute the function on

• cache (bool) – If True, the quantum function used to generate the QNode will only be called to construct the quantum circuit once, on first execution, and this circuit structure (i.e., the placement of templates, gates, measurements, etc.) will be cached for all further executions. The circuit parameters can still change with every call. Only activate this feature if your quantum circuit structure will never change.

_current_context = None

for building Operation sequences by executing quantum circuit functions

Type

QNode

__init__(func, device, cache=False)[source]

Initialize self. See help(type(self)) for accurate signature.

variable_ops = None

Mapping from free parameter index to the list of Operations (in this circuit) that depend on it.

The first element of the tuple is the index of the Operation in the program queue, the second the index of the parameter within the Operation.

Type

dict[int->list[(int, int)]]

__str__()[source]

String representation

__repr__()[source]

REPL representation

_append_op(op)[source]

Appends a quantum operation into the circuit queue.

Parameters

op (Operation) – quantum operation to be added to the circuit

construct(args, kwargs=None)[source]

Constructs a representation of the quantum circuit.

The user should never have to call this method.

This method is called automatically the first time QNode.evaluate() or QNode.jacobian() is called. It executes the quantum function, stores the resulting sequence of Operation instances, and creates the variable mapping.

Parameters
• args (tuple) – Represent the free parameters passed to the circuit. Here we are not concerned with their values, but with their structure. Each free param is replaced with a Variable instance.

• kwargs (dict) – Additional keyword arguments may be passed to the quantum circuit function, however PennyLane does not support differentiating with respect to keyword arguments. Instead, keyword arguments are useful for providing data or ‘placeholders’ to the quantum circuit function.

construct_metric_tensor(args, **kwargs)[source]

Create metric tensor subcircuits for each parameter.

If the parameter appears in a gate $$G$$, the subcircuit contains all gates which precede $$G$$, and $$G$$ is replaced by the variance value of its generator.

Parameters

args (tuple) – Represent the free parameters passed to the circuit. Here we are not concerned with their values, but with their structure. Each free param is replaced with a Variable instance.

Keyword Arguments

diag_approx (bool) – If True, forces the diagonal approximation. Default is False.

Note

Additional keyword arguments may be passed to the quantum circuit function, however PennyLane does not support differentiating with respect to keyword arguments. Instead, keyword arguments are useful for providing data or ‘placeholders’ to the quantum circuit function.

_op_successors(o_idx, only='G', get_nodes=False)[source]

Successors of the given operation in the quantum circuit.

Parameters
• o_idx (int) – index of the operation in the operation queue

• only (str) –

the type of successors to return.

• 'G': only return non-observables (default)

• 'E': only return observables

• None: return all successors

• get_nodes (bool) – if True, returns nodes instead of operations

Returns

successors in a topological order

Return type

list[Operation]

_best_method(idx)[source]

Determine the correct gradient computation method for a free parameter.

Use the analytic method iff every gate that depends on the parameter supports it. If not, use the finite difference method.

Note that If even one gate does not support differentiation, we cannot differentiate with respect to this parameter at all.

Parameters

idx (int) – free parameter index

Returns

Return type

str

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

Wrapper for evaluate().

evaluate(**kwargs)

Evaluates the quantum function on the specified device.

Parameters

args (tuple) – input parameters to the quantum function

Returns

output measured value(s)

Return type

float, array[float]

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

Evaluate the value of the metric tensor.

Parameters
• args – qfunc positional arguments

• kwargs – qfunc keyword arguments

Keyword Arguments

diag_approx (bool) – If True, forces the diagonal approximation. Default is False.

Returns

measured values

Return type

array[float]

evaluate_obs(obs, args, **kwargs)[source]

Evaluate the value of the given observables.

Assumes construct() has already been called.

Parameters
• obs (Iterable[Observable]) – observables to measure

• args (array[float]) – circuit input parameters

Returns

measured values

Return type

array[float]

jacobian(params, which=None, *, method='B', h=1e-07, order=1, **kwargs)[source]

Compute the Jacobian of the QNode.

Returns the Jacobian of the parametrized quantum circuit encapsulated in the QNode.

The Jacobian can be computed using several methods:

• Finite differences ('F'). The first order method evaluates the circuit at $$n+1$$ points of the parameter space, the second order method at $$2n$$ points, where n = len(which).

• Analytic method ('A'). Works for all one-parameter gates where the generator only has two unique eigenvalues; this includes one-parameter qubit gates, as well as Gaussian circuits of order one or two. Additionally, can be used in CV systems for Gaussian circuits containing first- and second-order observables.

The circuit is evaluated twice for each incidence of each parameter in the circuit.

• Best known method for each parameter ('B'): uses the analytic method if possible, otherwise finite difference.

Note

The finite difference method is sensitive to statistical noise in the circuit output, since it compares the output at two points infinitesimally close to each other. Hence the ‘F’ method requires exact expectation values, i.e., analytic=True in simulation plugins.

Parameters
• params (nested Sequence[Number], Number) – point in parameter space at which to evaluate the gradient

• which (Sequence[int], None) – return the Jacobian with respect to these parameters. None (the default) means with respect to all parameters. Note that keyword arguments to the QNode are always treated as fixed values and not included in the Jacobian calculation.

• method (str) – Jacobian computation method, see above.

Keyword Arguments
• h (float) – finite difference method step size

• order (int) – finite difference method order, 1 or 2

• shots (int) – How many times the circuit should be evaluated (or sampled) to estimate the expectation values.

Returns

Jacobian matrix, with shape (n_out, len(which)), where len(which) is the number of free parameters, and n_out is the number of expectation values returned by the QNode.

Return type

array[float]

_pd_finite_diff(params, idx, h=1e-07, order=1, y0=None, **kwargs)[source]

Partial derivative of the node using the finite difference method.

Parameters
• params (array[float]) – point in parameter space at which to evaluate the partial derivative

• idx (int) – return the partial derivative with respect to this parameter

• h (float) – step size

• order (int) – finite difference method order, 1 or 2

• y0 (float) – Value of the circuit at params. Should only be computed once.

Returns

partial derivative of the node.

Return type

float

static _transform_observable(observable, ob_successors, w, Z)[source]

Transform the observable

Parameters
• observable (Observable) – the observable to perform the transformation on

• ob_successors (list[Observable]) – list of observable successors to current operation

• w (int) – number of wires

• Z (array[float]) – the Heisenberg picture representation of the linear transformation

Returns

expectation value

Return type

float

_pd_analytic(params, idx, force_order2=False, **kwargs)[source]

Partial derivative of the node using the analytic method.

The 2nd order method can handle also first order observables, but 1st order method may be more efficient unless it’s really easy to experimentally measure arbitrary 2nd order observables.

Parameters
• params (array[float]) – point in free parameter space at which to evaluate the partial derivative

• idx (int) – return the partial derivative with respect to this free parameter

Returns

partial derivative of the node.

Return type

float

_pd_analytic_var(param_values, param_idx, **kwargs)[source]

Partial derivative of variances of observables using the analytic method.

Parameters
• param_values (array[float]) – point in free parameter space at which to evaluate the partial derivative

• param_idx (int) – return the partial derivative with respect to this free parameter

Returns

partial derivative of the node.

Return type

float

to_torch()[source]

Convert the standard PennyLane QNode into a TorchQNode().

to_tfe()[source]

Convert the standard PennyLane QNode into a TFEQNode().

__weakref__

list of weak references to the object (if defined)

QNode_vjp(ans, self, args, **kwargs)[source]

Returns the vector Jacobian product operator for a QNode, as a function of the QNode evaluation for specific argnums at the specified parameter values.

This function is required for integration with Autograd.