BraketAwsQubitDevice¶
- class BraketAwsQubitDevice(wires: int | Iterable, device_arn: str, s3_destination_folder: S3DestinationFolder = None, *, shots: int | Shots | None = Shots.DEFAULT, poll_timeout_seconds: float = 432000, poll_interval_seconds: float = 1, aws_session: AwsSession | None = None, max_connections: int = 100, max_retries: int = 3, **run_kwargs)[source]¶
Bases:
BraketQubitDeviceAmazon Braket AwsDevice qubit device for PennyLane.
- Parameters:
wires (int or Iterable[Number, str]]) – Number of subsystems represented by the device, or iterable that contains unique labels for the subsystems as numbers (i.e.,
[-1, 0, 2]) or strings (['ancilla', 'q1', 'q2']).device_arn (str) – The ARN identifying the
AwsDeviceto be used to run circuits; The corresponding AwsDevice must support quantum circuits via OpenQASM. You can get device ARNs usingAwsDevice.get_devices, from the Amazon Braket console or from the Amazon Braket Developer Guide.s3_destination_folder (AwsSession.S3DestinationFolder) – Name of the S3 bucket and folder, specified as a tuple.
poll_timeout_seconds (float) – Total time in seconds to wait for results before timing out.
poll_interval_seconds (float) – The polling interval for results in seconds.
shots (int, None or Shots.DEFAULT) – Number of circuit evaluations or random samples included, to estimate expectation values of observables. If set to Shots.DEFAULT, uses the default number of shots specified by the remote device. If
shotsis set to0orNone, the device runs in analytic mode (calculations will be exact). Analytic mode is not available on QPU and hence an error will be raised. Default: Shots.DEFAULTaws_session (AwsSession | None) – An AwsSession object created to manage interactions with AWS services, to be supplied if extra control is desired. Default: None Default: False
max_connections (int) – The maximum number of connections in the Boto3 connection pool. Also the maximum number of thread pool workers for the batch. Ignored if
parallel=False.max_retries (int) – The maximum number of retries to use for batch execution. When executing tasks in parallel, failed tasks will be retried up to
max_retriestimes. Ignored ifparallel=False.verbatim (bool) – Whether to verbatim mode for the device. Note that verbatim mode only supports the native gate set of the device. Default False.
**run_kwargs – Variable length keyword arguments for
braket.devices.Device.run().
Attributes
A
DeviceCapabilitiesobject describing the capabilities of the backend device.The last circuit run on this device.
A device can use a toml file to specify the capabilities of the backend device.
Whether the device supports parallel execution of batches.
Dictionary of constants set by the hardware (qubit resonant frequencies, inter-qubit connection graph, wires and anharmonicities).
Default shots for execution workflows containing this device.
The task corresponding to the last run circuit.
A
Trackerthat can store information about device executions, shots, batches, intermediate results, or any additional device dependent information.The device wires.
- author = 'Amazon Web Services'¶
- capabilities: DeviceCapabilities | None = None¶
A
DeviceCapabilitiesobject describing the capabilities of the backend device.
- circuit¶
The last circuit run on this device.
- Type:
Circuit
- config_filepath: str | None = 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
DeviceCapabilitiesobject assigned to thecapabilitiesattribute.
- name = 'braket.aws.qubit'¶
- parallel¶
Whether the device supports parallel execution of batches.
- Type:
bool
- pulse_settings¶
Dictionary of constants set by the hardware (qubit resonant frequencies, inter-qubit connection graph, wires and anharmonicities).
Used to enable initializing hardware-consistent Hamiltonians by returning values that would need to be passed, i.e.:
>>> import pennylane as qp >>> dev_remote = qp.device('braket.aws.qubit', >>> wires=8, >>> arn='arn:aws:braket:eu-west-2::device/qpu/oqc/Lucy') >>> pulse_settings = dev_remote.pulse_settings >>> H_int = qp.pulse.transmon_interaction(**pulse_settings, coupling=0.02)
By passing the
pulse_settingsfrom the remote device totransmon_interaction, anH_intHamiltonian term is created using the constants specific to the hardware. This is relevant for simulating the hardware in PennyLane on thedefault.qubitdevice.Note that the user must supply coupling coefficients, as these are not available from the hardware backend.
- short_name = 'braket.aws.qubit'¶
- shots¶
Default shots for execution workflows containing this device.
Note that the device itself should always pull shots from the provided
QuantumTapeand itsshots, not from this property. This property is used to provide a default at the start of a workflow.
- task¶
The task corresponding to the last run circuit.
- Type:
QuantumTask
- tracker: Tracker = <pennylane.devices.tracker.Tracker object>¶
A
Trackerthat 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()
- version = '1.36.1'¶
- 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
apply(operations[, rotations, ...])Instantiate Braket Circuit object.
classical_shadow(obs, circuit)compute_derivatives(circuits[, execution_config])Return Braket adjoint Jacobians for a batch of circuits.
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.
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[, ...])Execute circuits and return their Braket adjoint Jacobians.
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.
jaxpr_jvp(jaxpr, args, tangents[, ...])An experimental method for computing the results and jvp for PLXPR.
preprocess([execution_config])Device preprocessing function.
preprocess_transforms([execution_config])Returns the compile pileline to preprocess a circuit for execution.
setup_execution_config([config, circuit])Sets up an
ExecutionConfigthat configures the execution behaviour.shadow_expval(obs, circuit)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.
- apply(operations: Sequence[Operation], rotations: Sequence[Operation] | None = None, use_unique_params: bool = False, *, trainable_indices: frozenset[int] | None = None, apply_identities: bool = True, **run_kwargs) Circuit¶
Instantiate Braket Circuit object.
- classical_shadow(obs, circuit)¶
- compute_derivatives(circuits: Sequence[QuantumScript], execution_config: ExecutionConfig | None = None) tuple[source]¶
Return Braket adjoint Jacobians for a batch of circuits.
- compute_jvp(circuits: QuantumScript | Sequence[QuantumScript], tangents: tuple[Number, ...], execution_config: ExecutionConfig | None = 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
tangentstuple 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: QuantumScript | Sequence[QuantumScript], cotangents: tuple[Number, ...], execution_config: ExecutionConfig | None = 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
ywith 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
cotangentsshould match the output ofexecute().
- eval_jaxpr(jaxpr: jax.extend.core.Jaxpr, consts: list[int | float | bool | complex | bytes | list | tuple | ndarray | generic | ArrayBox | InterfaceTensor], *args, execution_config: ExecutionConfig | None = None, shots: Shots = Shots(total_shots=None, shot_vector=())) list[int | float | bool | complex | bytes | list | tuple | ndarray | generic | ArrayBox | InterfaceTensor]¶
An experimental method for natively evaluating PLXPR. See the
capturemodule for more details.- Parameters:
jaxpr (jax.extend.core.Jaxpr) – Pennylane variant jaxpr containing quantum operations and measurements
consts (list[TensorLike]) – the closure variables
constscorresponding to the jaxpr*args (TensorLike) – the variables to use with the jaxpr.
- Keyword Arguments:
execution_config (Optional[ExecutionConfig]) – a data structure with additional information required for execution
shots (Shots) – the number of shots to use for the evaluation
- Returns:
the result of evaluating the jaxpr with the given parameters.
- Return type:
list[TensorLike]
- execute(circuits: Sequence[QuantumScript], execution_config: ExecutionConfig | None = None) tuple¶
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]]
Interface parameters:
The provided
circuitsmay contain interface specific data-types liketorch.Tensororjax.Arraywhengradient_methodof"backprop"is requested. If the gradient method is not backpropagation, then only vanilla numpy parameters or builtins will be present in the circuits.Return Shape
See Return Type Specification for more detailed information.
The result for each
QuantumTapemust match the shape specified byshape.The level of priority for dimensions from outer dimension to inner dimension is:
Quantum Script in batch
Shot choice in a shot vector
Measurement in the quantum script
Parameter broadcasting
Measurement shape for array-valued measurements like probabilities
For a batch of quantum scripts with multiple measurements, a shot vector, and parameter broadcasting:
result[0]: the results for the first scriptresult[0][0]: the first shot number in the shot vectorresult[0][0][0]: the first measurement in the quantum scriptresult[0][0][0][0]: the first parameter broadcasting choiceresult[0][0][0][0][0]: the first value for an array-valued measurement
With the exception of quantum script batches, dimensions with only a single component should be eliminated.
For example:
With a single script and a single measurement process, execute should return just the measurement value in a numpy array.
shapecurrently accepts a device, as historically devices stored shot information. In the future, this method will accept anExecutionConfiginstead.>>> tape = qp.tape.QuantumScript(measurements=[qp.expval(qp.Z(0))]) >>> dev.execute(tape) np.float64(1.0)
If execute recieves a batch of scripts, then it should return a tuple of results:
>>> dev.execute([tape, tape]) (np.float64(1.0), np.float64(1.0)) >>> dev.execute([tape]) (np.float64(1.0),)
If the script has multiple measurements, then the device should return a tuple of measurements.
>>> tape = qp.tape.QuantumTape(measurements=[qp.expval(qp.Z(0)), qp.probs(wires=(0,1))]) >>> dev.execute(tape) (np.float64(1.0), array([1., 0., 0., 0.]))
- execute_and_compute_derivatives(circuits: Sequence[QuantumScript], execution_config: ExecutionConfig | None = None) tuple[tuple, tuple][source]¶
Execute circuits and return their Braket adjoint Jacobians.
- execute_and_compute_jvp(circuits: QuantumScript | Sequence[QuantumScript], tangents: tuple[Number, ...], execution_config: ExecutionConfig | None = 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: QuantumScript | Sequence[QuantumScript], cotangents: tuple[Number, ...], execution_config: ExecutionConfig | None = 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()andcompute_vjp()
- jaxpr_jvp(jaxpr: jax.extend.core.Jaxpr, args, tangents, execution_config: ExecutionConfig | None = None)¶
An experimental method for computing the results and jvp for PLXPR. See the
capturemodule for more details.- Parameters:
jaxpr (jax.extend.core.Jaxpr) – Pennylane variant jaxpr containing quantum operations and measurements
args (Sequence[TensorLike]) – the
constsfollowed by the normal argumentstangents (Sequence[TensorLike]) – the tangents corresponding to
args. May containjax.interpreters.ad.Zero.
- Keyword Arguments:
execution_config (Optional[ExecutionConfig]) – a data structure with additional information required for execution
- Returns:
the results and jacobian vector products
- Return type:
Sequence[TensorLike], Sequence[TensorLike]
>>> qp.capture.enable() >>> import jax >>> closure_var = jax.numpy.array(0.5) >>> def f(x): ... qp.RX(closure_var, 0) ... qp.RX(x, 1) ... return qp.expval(qp.Z(0)), qp.expval(qp.Z(1)) >>> jaxpr = jax.make_jaxpr(f)(1.2) >>> args = (closure_var, 1.2) >>> zero = jax.interpreters.ad.Zero(jax.core.ShapedArray((), float)) >>> tangents = (zero, 1.0) >>> config = qp.devices.ExecutionConfig(gradient_method="adjoint") >>> dev = qp.device('default.qubit', wires=2) >>> res, jvps = dev.jaxpr_jvp(jaxpr.jaxpr, args, tangents, execution_config=config) >>> res [Array(0.87758256, dtype=float64), Array(0.36235775, dtype=float64)] >>> jvps [Array(0., dtype=float64), Array(-0.93203909, dtype=float64)]
- preprocess(execution_config: ExecutionConfig | None = None) tuple[CompilePipeline, ExecutionConfig]¶
Device preprocessing function.
Warning
This function is tracked by machine learning interfaces and should be fully differentiable. The
pennylane.mathmodule 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 pileline 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 andMeasurementProcessobjects 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_executionvalue.
Example
All the transforms that are part of the preprocessing need to respect the transform contract defined in
pennylane.transform().from pennylane.tape 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()andCompilePipeline
- preprocess_transforms(execution_config: ExecutionConfig | None = None) CompilePipeline[source]¶
Returns the compile pileline to preprocess a circuit for execution.
- Parameters:
execution_config (ExecutionConfig) – The execution configuration object
- Returns:
A compile pileline that is called before execution
- Return type:
CompilePipeline
The compile pileline 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 pileline need to respect the transform contract defined in
pennylane.transform().from pennylane.tape 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 pileline 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()andCompilePipeline
- setup_execution_config(config: ExecutionConfig | None = None, circuit: QuantumScript | None = None) ExecutionConfig[source]¶
Sets up an
ExecutionConfigthat 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
ExecutionConfigfor all available options and what they mean.An
ExecutionConfigis 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.
circuit (QuantumScript) – The quantum circuit to customize the execution config for.
- Returns:
The updated ExecutionConfig object
- Return type:
ExecutionConfig
- shadow_expval(obs, circuit)¶
- supports_derivatives(execution_config: ExecutionConfig | None = None, circuit: QuantumScript | None = None) bool[source]¶
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 overriden.- Parameters:
execution_config (ExecutionConfig) – A description of the hyperparameters for the desired computation.
circuit (None, QuantumTape) – A specific circuit to check differentation 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 casecompute_derivatives()will be called for the derivative instead ofexecute()with a batch of circuits.>>> config = ExecutionConfig(gradient_method="parameter-shift") >>> custom_device.supports_derivatives(config) True
In this case,
compute_derivatives()orexecute_and_compute_derivatives()will be called instead ofexecute()with a batch of circuits.If
circuitis 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
1and 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(), thensupports_derivativesshould 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,Rotgates are not natively supported by adjoint differentation, 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 bypreprocess().>>> 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: ExecutionConfig | None = None, circuit: QuantumScript | None = 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
Trueifcompute_jvp()is overridden.
- supports_vjp(execution_config: ExecutionConfig | None = None, circuit: QuantumScript | None = None) bool¶
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 differentation for.
Default behaviour assumes this to be
Trueifcompute_vjp()is overridden.