LightningKokkos¶
- class LightningKokkos(wires: ~typing.Union[int, ~typing.List], *, c_dtype: ~typing.Union[~numpy.complex128, ~numpy.complex64] = <class 'numpy.complex128'>, shots: ~typing.Optional[~typing.Union[int, ~typing.List]] = None, batch_obs: bool = False, kokkos_args=None)[source]¶
Bases:
LightningBase
PennyLane Lightning Kokkos device.
A device that interfaces with C++ to perform fast linear algebra calculations.
Use of this device requires pre-built binaries or compilation from source. Check out the Lightning-Kokkos installation guide for more details.
- Parameters
wires (int) – the number of wires to initialize the device with
c_dtype – Datatypes for statevector representation. Must be one of
np.complex64
ornp.complex128
.shots (int) – How many times the circuit should be evaluated (or sampled) to estimate the expectation values. Defaults to
None
if not specified. Setting toNone
results in computing statistics like expectation values and variances analytically.sync (bool) – immediately sync with host-sv after applying operations
kokkos_args (InitializationSettings) – binding for Kokkos::InitializationSettings (threading parameters).
Attributes
State vector complex data type.
A
DeviceCapabilities
object describing the capabilities of the backend device.A device can use a toml file to specify the capabilities of the backend device.
State vector complex data type.
The name of the device.
Default shots for execution workflows containing this device.
A
Tracker
that can store information about device executions, shots, batches, intermediate results, or any additional device dependent information.The device wires.
- c_dtype¶
State vector complex data type.
- capabilities: Optional[DeviceCapabilities] = DeviceCapabilities(operations={'CNOT': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'ControlledPhaseShift': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CRot': OperatorProperties(invertible=True, controllable=False, differentiable=False, conditions=[]), 'CRX': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CRY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CRZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CSWAP': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'CZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'DoubleExcitationMinus': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'DoubleExcitationPlus': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'DoubleExcitation': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'GlobalPhase': OperatorProperties(invertible=True, controllable=True, differentiable=True, conditions=[]), 'Hadamard': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'Identity': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'IsingXX': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'IsingXY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'IsingYY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'IsingZZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'MultiRZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'PauliX': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'PauliY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'PauliZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'PhaseShift': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'QubitUnitary': OperatorProperties(invertible=True, controllable=False, differentiable=False, conditions=[]), 'Rot': OperatorProperties(invertible=True, controllable=False, differentiable=False, conditions=[]), 'RX': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'RY': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'RZ': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'SingleExcitationMinus': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'SingleExcitationPlus': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'SingleExcitation': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'S': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'SWAP': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'Toffoli': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'T': OperatorProperties(invertible=True, controllable=False, differentiable=True, conditions=[]), 'MultiControlledX': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'ControlledQubitUnitary': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'BlockEncode': OperatorProperties(invertible=False, controllable=True, differentiable=False, conditions=[]), 'DiagonalQubitUnitary': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'ECR': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'ISWAP': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'OrbitalRotation': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'PSWAP': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'QubitCarry': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'QubitSum': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'SISWAP': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'SQISW': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[]), 'SX': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[])}, observables={'Identity': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'PauliX': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'PauliY': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'PauliZ': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Hadamard': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Hermitian': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'SparseHamiltonian': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Sum': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'SProd': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Prod': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Exp': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'LinearCombination': OperatorProperties(invertible=False, controllable=False, differentiable=True, conditions=[]), 'Projector': OperatorProperties(invertible=False, controllable=False, differentiable=False, conditions=[])}, measurement_processes={'ExpectationMP': [], 'VarianceMP': [], 'ProbabilityMP': [], 'StateMP': [<ExecutionCondition.ANALYTIC_MODE_ONLY: 'analytic'>], 'SampleMP': [<ExecutionCondition.FINITE_SHOTS_ONLY: 'finiteshots'>], 'CountsMP': [<ExecutionCondition.FINITE_SHOTS_ONLY: 'finiteshots'>]}, qjit_compatible=True, runtime_code_generation=False, dynamic_qubit_management=False, overlapping_observables=True, non_commuting_observables=True, initial_state_prep=True, supported_mcm_methods=['one-shot'])¶
A
DeviceCapabilities
object describing the capabilities of the backend device.
- config_filepath: Optional[str] = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/xanaduai-pennylane-lightning/envs/latest/lib/python3.10/site-packages/pennylane_lightning/lightning_kokkos/lightning_kokkos.toml')¶
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 thecapabilities
attribute.
- dtype¶
State vector complex data type.
- kokkos_config = {}¶
- name¶
The name of the device.
- shots¶
Default shots for execution workflows containing this device.
Note that the device itself should always pull shots from the provided
QuantumTape
and itsshots
, not from this property. This property is used to provide a default at the start of a workflow.
- tracker: Tracker = <pennylane.tracker.Tracker object>¶
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()
- 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
Methods
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.
Lightning[Device]
uses the adjoint differentiation method to compute the VJP. :param circuits: the circuit or batch of circuits :type circuits: Union[QuantumTape, Sequence[QuantumTape]] :param cotangents: 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. :type cotangents: Tuple[Number, Tuple[Number]] :param execution_config: a datastructure with all additional information required for execution :type execution_config: ExecutionConfig.eval_jaxpr
(jaxpr, consts, *args)An experimental method for natively evaluating PLXPR.
execute
(circuits[, execution_config])Execute a circuit or a batch of circuits and turn it into results.
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. :param circuits: the circuit or batch of circuits to be executed :type circuits: Union[QuantumTape, Sequence[QuantumTape]] :param cotangents: 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. :type cotangents: Tuple[Number, Tuple[Number]] :param execution_config: a datastructure with all additional information required for execution :type execution_config: ExecutionConfig.Returns a tuple consisting of the device name, and the location to the shared object with the C/C++ device implementation.
jacobian
(circuit, state[, batch_obs, wire_map])Compute the Jacobian for a single quantum script.
preprocess
([execution_config])This function defines the device transform program to be applied and an updated device configuration.
preprocess_transforms
([execution_config])Returns the transform program to preprocess a circuit for execution.
setup_execution_config
([config])Sets up an
ExecutionConfig
that configures the execution behaviour.simulate
(circuit, state[, postselect_mode])Simulate a single quantum script.
simulate_and_jacobian
(circuit, state[, ...])Simulate a single quantum script and compute its Jacobian.
simulate_and_vjp
(circuit, cotangents, state)Simulate a single quantum script and compute its Vector-Jacobian Product (VJP). :param circuit: The single circuit to simulate :type circuit: QuantumTape :param cotangents: 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. :type cotangents: Tuple[Number, Tuple[Number]] :param state: handle to the Lightning state vector :type state: Lightning [Device] StateVector :param batch_obs: Determine whether we process observables in parallel when computing the jacobian. :type batch_obs: bool :param wire_map: a map from wire labels to simulation indices :type wire_map: Optional[dict].supports_derivatives
([execution_config, circuit])Check whether or not derivatives are available for a given configuration and circuit.
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 this device defines a custom vector jacobian product.
vjp
(circuit, cotangents, state[, batch_obs, ...])Compute the Vector-Jacobian Product (VJP) for a single quantum script. :param circuit: The single circuit to simulate :type circuit: QuantumTape :param cotangents: 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. :type cotangents: Tuple[Number, Tuple[Number]] :param state: handle to the Lightning state vector :type state: Lightning [Device] StateVector :param batch_obs: Determine whether we process observables in parallel when computing the VJP. :type batch_obs: bool :param wire_map: a map from wire labels to simulation indices :type wire_map: Optional[dict].- compute_derivatives(circuits: Union[QuantumTape, Sequence[QuantumTape]], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=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
- compute_jvp(circuits: Union[QuantumScript, Sequence[QuantumScript]], tangents: tuple[numbers.Number, ...], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=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 ascircuit.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: Union[QuantumTape, Sequence[QuantumTape]], cotangents: Tuple[Number], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=None))) Tuple ¶
The vector jacobian product used in reverse-mode differentiation.
Lightning[Device]
uses the adjoint differentiation method to compute the VJP. :param circuits: the circuit or batch of circuits :type circuits: Union[QuantumTape, Sequence[QuantumTape]] :param cotangents: Gradient-output vector. Must have shape matching the output shape of thecorresponding circuit. If the circuit has a single output,
cotangents
may be a single number, not an iterable of numbers.- Parameters
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: .. math:
\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. .. math:\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 ofexecute()
. For computing the full Jacobian, the cotangents can be batched to vectorize the computation. In this case, the cotangents can have the following shapes.batch_size
below refers to the number of entries in the Jacobian: * For a state measurement, the cotangents must have shape(batch_size, 2 ** n_wires)
* Forn
expectation values, the cotangents must have shape(n, batch_size)
. Ifn = 1
,then the shape must be
(batch_size,)
.
- eval_jaxpr(jaxpr: jax.core.Jaxpr, consts: list[pennylane.typing.TensorLike], *args) list[pennylane.typing.TensorLike] ¶
An experimental method for natively evaluating PLXPR. See the
capture
module for more details.- Parameters
jaxpr (jax.core.Jaxpr) – Pennylane variant jaxpr containing quantum operations and measurements
consts (list[TensorLike]) – the closure variables
consts
corresponding to the jaxpr*args (TensorLike) – the variables to use with the jaxpr’.
- Returns
the result of evaluating the jaxpr with the given parameters.
- Return type
list[TensorLike]
- execute(circuits: Union[QuantumTape, Sequence[QuantumTape]], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=None))) Union[Result, Sequence[Result]] [source]¶
Execute a circuit or a batch of circuits and turn it into results.
- Parameters
circuits (Union[QuantumTape, Sequence[QuantumTape]]) – the quantum circuits to be executed
execution_config (ExecutionConfig) – a datastructure with additional information required for execution
- Returns
A numeric result of the computation.
- Return type
TensorLike, tuple[TensorLike], tuple[tuple[TensorLike]]
- execute_and_compute_derivatives(circuits: Union[QuantumTape, Sequence[QuantumTape]], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=None))) Tuple ¶
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
- execute_and_compute_jvp(circuits: Union[QuantumScript, Sequence[QuantumScript]], tangents: tuple[numbers.Number, ...], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=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()
andcompute_jvp()
- execute_and_compute_vjp(circuits: Union[QuantumTape, Sequence[QuantumTape]], cotangents: Tuple[Number], execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=None))) Tuple ¶
Calculate both the results and the vector jacobian product used in reverse-mode differentiation. :param circuits: the circuit or batch of circuits to be executed :type circuits: Union[QuantumTape, Sequence[QuantumTape]] :param cotangents: 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.- Parameters
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
- static get_c_interface()[source]¶
Returns a tuple consisting of the device name, and the location to the shared object with the C/C++ device implementation.
- jacobian(circuit: QuantumTape, state, batch_obs: bool = False, wire_map: Optional[dict] = None)¶
Compute the Jacobian for a single quantum script.
- Parameters
circuit (QuantumTape) – The single circuit to simulate
state (Lightning [Device] StateVector) – handle to the Lightning state vector
batch_obs (bool) – Determine whether we process observables in parallel when computing the jacobian. Default is False.
wire_map (Optional[dict]) – a map from wire labels to simulation indices
- Returns
The Jacobian of the quantum script
- Return type
TensorLike
- preprocess(execution_config: ExecutionConfig = ExecutionConfig(grad_on_execution=None, use_device_gradient=None, use_device_jacobian_product=None, gradient_method=None, gradient_keyword_arguments={}, device_options={}, interface=None, derivative_order=1, mcm_config=MCMConfig(mcm_method=None, postselect_mode=None)))[source]¶
This function defines the device transform program to be applied and an updated device configuration.
- Parameters
execution_config (Union[ExecutionConfig, Sequence[ExecutionConfig]]) – A data structure describing the parameters needed to fully describe the execution.
- Returns
A transform program that when called returns
QuantumTape
’s that the device can natively execute as well as a postprocessing function to be called after execution, and a configuration with unset specifications filled in.- Return type
TransformProgram, ExecutionConfig
This device:
Supports any qubit operations that provide a matrix
Currently does not support finite shots
Currently does not intrinsically support parameter broadcasting
- preprocess_transforms(execution_config: Optional[ExecutionConfig] = None) TransformProgram ¶
Returns the transform program to preprocess a circuit for execution.
- Parameters
execution_config (ExecutionConfig) – The execution configuration object
- Returns
A transform program that is called before execution
- Return type
TransformProgram
The transform program 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 transform program need to respect the transform contract defined in
pennylane.transform()
.from pennylane.tape import QuantumScriptBatch from pennylane.typing import PostprocessingFn @qml.transform def my_preprocessing_transform(tape: qml.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 transform program can hold an arbitrary number of individual transforms:
def preprocess(self, config): program = TransformProgram() program.add_transform(my_preprocessing_transform) return program
See also
transform()
andTransformProgram
Post processing function and derivatives
Derivatives and Jacobian products will be bound to the machine learning library before the postprocessing function is called on the results. Therefore, the machine learning library will be responsible for combining and post-processing derivatives returned from the device.
from pennylane.interfaces.jax import execute as jax_boundary def f(x): circuit = qml.tape.QuantumScript([qml.Rot(*x, wires=0)], [qml.expval(qml.Z(0))]) config = ExecutionConfig(gradient_method="adjoint") config = dev.setup_execution_config(config) program = dev.preprocess_transforms(config) circuit_batch, postprocessing = program((circuit, )) def execute_fn(tapes): return dev.execute_and_compute_derivatives(tapes, config) results = jax_boundary(circuit_batch, dev, execute_fn, None, {}) return postprocessing(results) x = jax.numpy.array([1.0, 2.0, 3.0]) jax.grad(f)(x)
In the above code, the quantum derivatives are registered with jax in the
jax_boundary
function. Only then is the classical postprocessing called on the result object.
- setup_execution_config(config: Optional[ExecutionConfig] = None) ExecutionConfig ¶
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 theQNode
, 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.
- Returns
The updated ExecutionConfig object
- Return type
ExecutionConfig
- simulate(circuit: QuantumScript, state: LightningKokkosStateVector, postselect_mode: Optional[str] = None) Result [source]¶
Simulate a single quantum script.
- Parameters
circuit (QuantumTape) – The single circuit to simulate
state (LightningKokkosStateVector) – handle to Lightning state vector
postselect_mode (str) – Configuration for handling shots with mid-circuit measurement postselection. Use
"hw-like"
to discard invalid shots and"fill-shots"
to keep the same number of shots. Default isNone
.
- Returns
The results of the simulation
- Return type
Tuple[TensorLike]
Note that this function can return measurements for non-commuting observables simultaneously.
- simulate_and_jacobian(circuit: QuantumTape, state, batch_obs: bool = False, wire_map: Optional[dict] = None) Tuple ¶
Simulate a single quantum script and compute its Jacobian.
- Parameters
circuit (QuantumTape) – The single circuit to simulate
state (Lightning [Device] StateVector) – handle to the Lightning state vector
batch_obs (bool) – Determine whether we process observables in parallel when computing the jacobian. Default is False.
wire_map (Optional[dict]) – a map from wire labels to simulation indices
- Returns
The results of the simulation and the calculated Jacobian
- Return type
Tuple[TensorLike]
Note that this function can return measurements for non-commuting observables simultaneously.
- simulate_and_vjp(circuit: QuantumTape, cotangents: Tuple[Number], state, batch_obs: bool = False, wire_map: Optional[dict] = None) Tuple ¶
Simulate a single quantum script and compute its Vector-Jacobian Product (VJP). :param circuit: The single circuit to simulate :type circuit: QuantumTape :param cotangents: 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.- Parameters
state (Lightning [Device] StateVector) – handle to the Lightning state vector
batch_obs (bool) – Determine whether we process observables in parallel when computing the jacobian.
wire_map (Optional[dict]) – a map from wire labels to simulation indices
- Returns
The results of the simulation and the calculated VJP
- Return type
Tuple[TensorLike]
Note that this function can return measurements for non-commuting observables simultaneously.
- supports_derivatives(execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumTape] = None) bool [source]¶
Check whether or not derivatives are available for a given configuration and circuit.
LightningKokkos
supports adjoint differentiation with analytic results.- Parameters
execution_config (ExecutionConfig) – The configuration of the desired derivative calculation
circuit (QuantumTape) – An optional circuit to check derivatives support for.
- Returns
Whether or not a derivative can be calculated provided the given information
- Return type
Bool
- supports_jvp(execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumScript] = None) bool ¶
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 differentation for.
Default behaviour assumes this to be
True
ifcompute_jvp()
is overridden.
- supports_vjp(execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumTape] = None) bool ¶
Whether or not this device defines a custom vector jacobian product.
Lightning[Device]
will check if supports adjoint differentiation with analytic results. :param execution_config: The configuration of the desired derivative calculation :type execution_config: ExecutionConfig :param circuit: An optional circuit to check derivatives support for. :type circuit: QuantumTape- Returns
Whether or not a derivative can be calculated provided the given information
- Return type
Bool
- vjp(circuit: QuantumTape, cotangents: Tuple[Number], state, batch_obs: bool = False, wire_map: Optional[dict] = None)¶
Compute the Vector-Jacobian Product (VJP) for a single quantum script. :param circuit: The single circuit to simulate :type circuit: QuantumTape :param cotangents: 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.- Parameters
state (Lightning [Device] StateVector) – handle to the Lightning state vector
batch_obs (bool) – Determine whether we process observables in parallel when computing the VJP.
wire_map (Optional[dict]) – a map from wire labels to simulation indices
- Returns
The VJP of the quantum script
- Return type
TensorLike