qp.Backline

class Backline(*, controller, coprocessors=(), transport, qec_code=None, shots=None)[source]

Bases: Device

A device for heterogeneous compilation and execution over a backline placement.

The device stores the Placement consisting of a transport, controller, and coprocessors. Its wires are taken from the controller’s device, so a QNode is written exactly as it would be against that device alone. This device requires the Catalyst compiler.

Warning

Backline is experimental and only usable through the Catalyst compiler.

Keyword Arguments:
  • controller (Controller) – The Controller that drives the QPU and runs the QNode.

  • coprocessors (Sequence[Coprocessor]) – Zero or more Coprocessor accelerators.

  • transport (str, Transport) – The transfer protocol between nodes, by registry name ("rdma", "memcpy" or "none") or a Transport. "none" runs the controller alone and cannot be used with coprocessors.

  • qec_code (str, None) – The quantum error-correcting code to implicitly encode the circuit. Currently the only supported option is "steane". Defaults to None, leaving the circuit unencoded.

  • shots (int, None) – Number of shots. Defaults to None (analytic); set shots on the QNode with set_shots() instead.

Example

The minimal device runs everything in this process, on a default null.qubit controller:

>>> dev = qp.Backline(controller=qp.Controller(), transport="rdma")
>>> dev.transport
Transport(name='rdma')

A real placement names where each node runs and how the compiler reaches it:

import pennylane as qp

ctrl = qp.Controller(
    device=qp.device("null.qubit", wires=4),
    name="cpu-controller",
    executor_options={"host": "192.168.3.15", "port": 7810},
)

coproc = qp.Coprocessor(
    coprocessor_fn="decoder",
    name="decoder-0",
    hardware="gpu",
    endpoint=qp.Endpoint("198.51.100.2", 7760),
    executor_options={"host": "192.0.2.11", "port": 7813},
)

dev = qp.Backline(
    controller=ctrl, coprocessors=[coproc], transport="rdma", qec_code="steane"
)

@qp.qjit
@qp.qnode(dev)
def circuit(x):
    qp.RX(x, wires=0)
    return qp.expval(qp.Z(0))

For more usage details, see the Backline demo.

capabilities

A DeviceCapabilities object describing the capabilities of the backend device.

config_filepath

A device can use a toml file to specify the capabilities of the backend device.

controller

The Controller node of the placement.

coprocessors

The Coprocessor nodes of the placement.

name

The name of the device or set of devices.

placement

The Placement the device was configured with.

qec_code

The quantum error-correcting code used for logical qubit encoding.

shots

Default shots for execution workflows containing this device.

tracker

A Tracker that can store information about device executions, shots, batches, intermediate results, or any additional device dependent information.

transport

The Transport carrying data between nodes.

wires

The device wires.

capabilities = None

A DeviceCapabilities object describing the capabilities of the backend device.

config_filepath = None

A device can use a toml file to specify the capabilities of the backend device. If this is provided, the file will be loaded into a DeviceCapabilities object assigned to the capabilities attribute.

controller

The Controller node of the placement.

Type:

Controller

coprocessors

The Coprocessor nodes of the placement.

Type:

tuple[Coprocessor, …]

name
placement

The Placement the device was configured with.

Type:

Placement

qec_code

The quantum error-correcting code used for logical qubit encoding.

Type:

str | None

shots

Default shots for execution workflows containing this device.

Note that the device itself should always pull shots from the provided QuantumTape and its shots, not from this property. This property is used to provide a default at the start of a workflow.

tracker = Tracker(active=False, totals={}, history={}, latest={}, persistent=False, callback=None)

A Tracker that can store information about device executions, shots, batches, intermediate results, or any additional device dependent information.

A plugin developer can store information in the tracker by:

# querying if the tracker is active
if self.tracker.active:

    # store any keyword: value pairs of information
    self.tracker.update(executions=1, shots=self._shots, results=results)

    # Calling a user-provided callback function
    self.tracker.record()
transport

The Transport carrying data between nodes.

Type:

Transport

wires

The device wires.

Note that wires are optional, and the default value of None means any wires can be used. If a device has wires defined, they will only be used for certain features. This includes:

  • Validation of tapes being executed on the device

  • Defining the wires used when evaluating a state() measurement

compute_derivatives(circuits[, execution_config])

Calculate the jacobian of either a single or a batch of circuits on the device.

compute_jvp(circuits, tangents[, ...])

The jacobian vector product used in forward mode calculation of derivatives.

compute_vjp(circuits, cotangents[, ...])

The vector jacobian product used in reverse-mode differentiation.

execute(circuits[, execution_config])

Execution is handled by the Catalyst compiler; there is no Python execution path.

execute_and_compute_derivatives(circuits[, ...])

Compute the results and jacobians of circuits at the same time.

execute_and_compute_jvp(circuits, tangents)

Execute a batch of circuits and compute their jacobian vector products.

execute_and_compute_vjp(circuits, cotangents)

Calculate both the results and the vector jacobian product used in reverse-mode differentiation.

preprocess(*args, **kwargs)

Device preprocessing function.

preprocess_transforms([execution_config])

Returns the compile pipeline to preprocess a circuit for execution.

setup_execution_config([config, circuit])

Sets up an ExecutionConfig that configures the execution behaviour.

supports_derivatives([execution_config, circuit])

Determine whether or not a device provided derivative is potentially available.

supports_jvp([execution_config, circuit])

Whether or not a given device defines a custom jacobian vector product.

supports_vjp([execution_config, circuit])

Whether or not a given device defines a custom vector jacobian product.

compute_derivatives(circuits, execution_config=None)

Calculate the jacobian of either a single or a batch of circuits on the device.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the circuits to calculate derivatives for

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

The jacobian for each trainable parameter

Return type:

Tuple

Execution Config:

The execution config has gradient_method and order property that describes the order of differentiation requested. If the requested method or order of gradient is not provided, the device should raise a NotImplementedError. The supports_derivatives() method can pre-validate supported orders and gradient methods.

Return Shape:

If a batch of quantum scripts is provided, this method should return a tuple with each entry being the gradient of each individual quantum script. If the batch is of length 1, then the return tuple should still be of length 1, not squeezed.

compute_jvp(circuits, tangents, execution_config=None)

The jacobian vector product used in forward mode calculation of derivatives.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the circuit or batch of circuits

  • tangents (tensor-like) – Gradient vector for input parameters.

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

A numeric result of computing the jacobian vector product

Return type:

Tuple

Definition of jvp:

If we have a function with jacobian:

\[\vec{y} = f(\vec{x}) \qquad J_{i,j} = \frac{\partial y_i}{\partial x_j}\]

The Jacobian vector product is the inner product with the derivatives of \(x\), yielding only the derivatives of the output \(y\):

\[\text{d}y_i = \Sigma_{j} J_{i,j} \text{d}x_j\]

Shape of tangents:

The tangents tuple should be the same length as circuit.get_parameters() and have a single number per parameter. If a number is zero, then the gradient with respect to that parameter does not need to be computed.

compute_vjp(circuits, cotangents, execution_config=None)

The vector jacobian product used in reverse-mode differentiation.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the circuit or batch of circuits

  • cotangents (Tuple[Number, Tuple[Number]]) – Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. If the circuit has a single output, cotangents may be a single number, not an iterable of numbers.

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

A numeric result of computing the vector jacobian product

Return type:

tensor-like

Definition of vjp:

If we have a function with jacobian:

\[\vec{y} = f(\vec{x}) \qquad J_{i,j} = \frac{\partial y_i}{\partial x_j}\]

The vector jacobian product is the inner product of the derivatives of the output y with the Jacobian matrix. The derivatives of the output vector are sometimes called the cotangents.

\[\text{d}x_i = \Sigma_{i} \text{d}y_i J_{i,j}\]

Shape of cotangents:

The value provided to cotangents should match the output of execute().

execute(circuits, execution_config=None)[source]

Execution is handled by the Catalyst compiler; there is no Python execution path.

execute_and_compute_derivatives(circuits, execution_config=None)

Compute the results and jacobians of circuits at the same time.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the circuits or batch of circuits

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

A numeric result of the computation and the gradient.

Return type:

tuple

See execute() and compute_derivatives() for more information about return shapes and behaviour. If compute_derivatives() is defined, this method should be as well.

This method can be used when the result and execution need to be computed at the same time, such as during a forward mode calculation of gradients. For certain gradient methods, such as adjoint diff gradients, calculating the result and gradient at the same can save computational work.

execute_and_compute_jvp(circuits, tangents, execution_config=None)

Execute a batch of circuits and compute their jacobian vector products.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – circuit or batch of circuits

  • tangents (tensor-like) – Gradient vector for input parameters.

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

A numeric result of execution and of computing the jacobian vector product

Return type:

Tuple, Tuple

See also

execute() and compute_jvp()

execute_and_compute_vjp(circuits, cotangents, execution_config=None)

Calculate both the results and the vector jacobian product used in reverse-mode differentiation.

Parameters:
  • circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the circuit or batch of circuits to be executed

  • cotangents (Tuple[Number, Tuple[Number]]) – Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. If the circuit has a single output, cotangents may be a single number, not an iterable of numbers.

  • execution_config (ExecutionConfig) – a datastructure with all additional information required for execution

Returns:

the result of executing the scripts and the numeric result of computing the vector jacobian product

Return type:

Tuple, Tuple

See also

execute() and compute_vjp()

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

Device preprocessing function.

Warning

This function is tracked by machine learning interfaces and should be fully differentiable. The pennylane.math module can be used to construct fully differentiable transformations.

Additional preprocessing independent of machine learning interfaces can be done inside of the execute() method.

Parameters:

execution_config (ExecutionConfig) – A datastructure describing the parameters needed to fully describe the execution.

Returns:

A compile pipeline that is called before execution, and a configuration

with unset specifications filled in.

Return type:

CompilePipeline, ExecutionConfig

Raises:

Exception – An exception can be raised if the input cannot be converted into a form supported by the device.

Preprocessing program may include:

  • expansion to Operator’s and MeasurementProcess objects supported by the device.

  • splitting a circuit with the measurement of non-commuting observables or Hamiltonians into multiple executions

  • splitting circuits with batched parameters into multiple executions

  • gradient specific preprocessing, such as making sure trainable operators have generators

  • validation of configuration parameters

  • choosing a best gradient method and grad_on_execution value.

Example

All the transforms that are part of the preprocessing need to respect the transform contract defined in pennylane.transform().

from pennylane.core.qscript import QuantumScriptBatch
from pennylane.typing import PostprocessingFn

@qp.transform
def my_preprocessing_transform(tape: qp.tape.QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]:
    # e.g. valid the measurements, expand the tape for the hardware execution, ...

    def blank_processing_fn(results):
        return results[0]

    return [tape], processing_fn

Then we can define the preprocess method on the custom device. The program can accept an arbitrary number of transforms.

def preprocess(config):
    program = CompilePipeline()
    program.add_transform(my_preprocessing_transform)
    return program, config

See also

transform() and CompilePipeline

preprocess_transforms(execution_config=None)

Returns the compile pipeline to preprocess a circuit for execution.

Parameters:

execution_config (ExecutionConfig) – The execution configuration object

Returns:

A compile pipeline that is called before execution

Return type:

CompilePipeline

The compile pipeline is composed of a list of individual transforms, which may include:

  • Decomposition of operations and measurements to what is supported by the device.

  • Splitting a circuit with measurements of non-commuting observables or Hamiltonians into multiple executions.

  • Splitting a circuit with batched parameters into multiple executions.

  • Validation of wires, measurements, and observables.

  • Gradient specific preprocessing, such as making sure trainable operators have generators.

Example

All transforms that are part of the preprocessing compile pipeline need to respect the transform contract defined in pennylane.transform().

from pennylane.core.qscript import QuantumScriptBatch
from pennylane.typing import PostprocessingFn

@qp.transform
def my_preprocessing_transform(tape: qp.tape.QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]:
    # e.g. valid the measurements, expand the tape for the hardware execution, ...

    def blank_processing_fn(results):
        return results[0]

    return [tape], processing_fn

A compile pipeline can hold an arbitrary number of individual transforms:

def preprocess(self, config):
    program = CompilePipeline()
    program.add_transform(my_preprocessing_transform)
    return program

See also

transform() and CompilePipeline

setup_execution_config(config=None, circuit=None)

Sets up an ExecutionConfig that configures the execution behaviour.

The execution config stores information on how the device should perform the execution, as well as how PennyLane should interact with the device. See ExecutionConfig for all available options and what they mean.

An ExecutionConfig is constructed from arguments passed to the QNode, and this method allows the device to update the config object based on device-specific requirements or preferences. See Execution Config for more details.

Parameters:
  • config (ExecutionConfig) – The initial ExecutionConfig object that describes the parameters needed to configure the execution behaviour.

  • circuit (QuantumScript) – The quantum circuit to customize the execution config for.

Returns:

The updated ExecutionConfig object

Return type:

ExecutionConfig

supports_derivatives(execution_config=None, circuit=None)

Determine whether or not a device provided derivative is potentially available.

Default behaviour assumes first order device derivatives for all circuits exist if compute_derivatives() is overridden.

Parameters:
  • execution_config (ExecutionConfig) – A description of the hyperparameters for the desired computation.

  • circuit (None, QuantumTape) – A specific circuit to check differentiation for.

Returns:

Bool

The device can support multiple different types of “device derivatives”, chosen via execution_config.gradient_method. For example, a device can natively calculate "parameter-shift" derivatives, in which case compute_derivatives() will be called for the derivative instead of execute() with a batch of circuits.

>>> config = ExecutionConfig(gradient_method="parameter-shift")
>>> custom_device.supports_derivatives(config)
True

In this case, compute_derivatives() or execute_and_compute_derivatives() will be called instead of execute() with a batch of circuits.

If circuit is not provided, then the method should return whether or not device derivatives exist for any circuit.

Example:

For example, the Python device will support device differentiation via the adjoint differentiation algorithm if the order is 1 and the execution occurs with no shots (shots=None).

>>> config = ExecutionConfig(derivative_order=1, gradient_method="adjoint")
>>> dev.supports_derivatives(config)
True
>>> circuit_analytic = qp.tape.QuantumScript([qp.RX(0.1, wires=0)], [qp.expval(qp.Z(0))], shots=None)
>>> dev.supports_derivatives(config, circuit=circuit_analytic)
True
>>> circuit_finite_shots = qp.tape.QuantumScript([qp.RX(0.1, wires=0)], [qp.expval(qp.Z(0))], shots=10)
>>> dev.supports_derivatives(config, circuit = circuit_finite_shots)
False
>>> config = ExecutionConfig(derivative_order=2, gradient_method="adjoint")
>>> dev.supports_derivatives(config)
False

Adjoint differentiation will only be supported for circuits with expectation value measurements. If a circuit is provided and it cannot be converted to a form supported by differentiation method by preprocess(), then supports_derivatives should return False.

>>> config = ExecutionConfig(derivative_order=1, gradient_method="adjoint")
>>> circuit = qp.tape.QuantumScript([qp.RX(2.0, wires=0)], [qp.probs(wires=(0,1))])
>>> dev.supports_derivatives(config, circuit=circuit)
False

If the circuit is not natively supported by the differentiation method but can be converted into a form that is supported, it should still return True. For example, Rot gates are not natively supported by adjoint differentiation, as they do not have a generator, but they can be compiled into operations supported by adjoint differentiation. Therefore this method may reproduce compilation and validation steps performed by preprocess().

>>> config = ExecutionConfig(derivative_order=1, gradient_method="adjoint")
>>> circuit = qp.tape.QuantumScript([qp.Rot(1.2, 2.3, 3.4, wires=0)], [qp.expval(qp.Z(0))])
>>> dev.supports_derivatives(config, circuit=circuit)
True

Backpropagation:

This method is also used be to validate support for backpropagation derivatives. Backpropagation is only supported if the device is transparent to the machine learning framework from start to finish.

>>> config = ExecutionConfig(gradient_method="backprop")
>>> python_device.supports_derivatives(config)
True
>>> cpp_device.supports_derivatives(config)
False
supports_jvp(execution_config=None, circuit=None)

Whether or not a given device defines a custom jacobian vector product.

Parameters:
  • execution_config (ExecutionConfig) – A description of the hyperparameters for the desired computation.

  • circuit (None, QuantumTape) – A specific circuit to check differentiation for.

Default behaviour assumes this to be True if compute_jvp() is overridden.

supports_vjp(execution_config=None, circuit=None)

Whether or not a given device defines a custom vector jacobian product.

Parameters:
  • execution_config (ExecutionConfig) – A description of the hyperparameters for the desired computation.

  • circuit (None, QuantumTape) – A specific circuit to check differentiation for.

Default behaviour assumes this to be True if compute_vjp() is overridden.