qml.devices.default_qubit_autograd.DefaultQubitAutograd¶

class
DefaultQubitAutograd
(wires, *, shots=1000, analytic=True)[source]¶ Bases:
pennylane.devices.default_qubit.DefaultQubit
Simulator plugin based on
"default.qubit"
, written using Autograd.Short name:
default.qubit.autograd
This device provides a purestate qubit simulator written using Autograd. As a result, it supports classical backpropagation as a means to compute the gradient. This can be faster than the parametershift rule for analytic quantum gradients when the number of parameters to be optimized is large.
To use this device, you will need to install Autograd:
pip install autograd
Example
The
default.qubit.autograd
is designed to be used with endtoend classical backpropagation (diff_method="backprop"
) with the Autograd interface. This is the default method of differentiation when creating a QNode with this device.Using this method, the created QNode is a ‘whitebox’, and is tightly integrated with your Autograd computation:
>>> dev = qml.device("default.qubit.autograd", wires=1) >>> @qml.qnode(dev, interface="autograd", diff_method="backprop") ... def circuit(x): ... qml.RX(x[1], wires=0) ... qml.Rot(x[0], x[1], x[2], wires=0) ... return qml.expval(qml.PauliZ(0)) >>> weights = np.array([0.2, 0.5, 0.1]) >>> grad_fn = qml.grad(circuit) >>> print(grad_fn(weights)) array([2.2526717e01 1.0086454e+00 1.3877788e17])
There are a couple of things to keep in mind when using the
"backprop"
differentiation method for QNodes:You must use the
"autograd"
interface for classical backpropagation, as Autograd is used as the device backend.Only exact expectation values, variances, and probabilities are differentiable. When instantiating the device with
analytic=False
, differentiating QNode outputs will result in an error.
 Parameters
wires (int) – the number of wires to initialize the device with
Attributes
The hash of the circuit upon the last execution.
The observables to be measured and returned.
The operation queue to be applied.
Mapping from free parameter index to the list of
Operations
in the device queue that depend on it.Number of circuit evaluations/random samples used to estimate expectation values of observables
Returns the state vector of the circuit prior to measurement.
Ordered dictionary that defines the map from userprovided wire labels to the wire labels used on this device
All wires that can be addressed on this device

circuit_hash
¶ The hash of the circuit upon the last execution.
This can be used by devices in
apply()
for parametric compilation.

name
= 'Default qubit (Autograd) PennyLane plugin'¶

obs_queue
¶ The observables to be measured and returned.
Note that this property can only be accessed within the execution context of
execute()
. Raises
ValueError – if outside of the execution context
 Returns
list[~.operation.Observable]

observables
= {'Hadamard', 'Hermitian', 'Identity', 'PauliX', 'PauliY', 'PauliZ'}¶

op_queue
¶ The operation queue to be applied.
Note that this property can only be accessed within the execution context of
execute()
. Raises
ValueError – if outside of the execution context
 Returns
list[~.operation.Operation]

operations
= {'BasisState', 'CNOT', 'CRX', 'CRY', 'CRZ', 'CRot', 'CSWAP', 'CY', 'CZ', 'DiagonalQubitUnitary', 'Hadamard', 'MultiRZ', 'PauliX', 'PauliY', 'PauliZ', 'PhaseShift', 'QubitStateVector', 'QubitUnitary', 'RX', 'RY', 'RZ', 'Rot', 'S', 'SWAP', 'T', 'Toffoli'}¶

parameters
¶ Mapping from free parameter index to the list of
Operations
in the device queue that depend on it.Note that this property can only be accessed within the execution context of
execute()
. Raises
ValueError – if outside of the execution context
 Returns
the mapping
 Return type
dict[int>list[ParameterDependency]]

parametric_ops
= {'CRX': <function CRX>, 'CRY': <function CRY>, 'CRZ': <function CRZ>, 'MultiRZ': <function MultiRZ>, 'PhaseShift': <function PhaseShift>, 'RX': <function RX>, 'RY': <function RY>, 'RZ': <function RZ>, 'Rot': <function Rot>}¶

pennylane_requires
= '0.12'¶

short_name
= 'default.qubit.autograd'¶

shots
¶ Number of circuit evaluations/random samples used to estimate expectation values of observables

state
¶ Returns the state vector of the circuit prior to measurement.
Note
Only state vector simulators support this property. Please see the plugin documentation for more details.

version
= '0.12.0'¶

wire_map
¶ Ordered dictionary that defines the map from userprovided wire labels to the wire labels used on this device

wires
¶ All wires that can be addressed on this device
Methods
Check that the device has access to an internal state and return it if available.
active_wires
(operators)Returns the wires acted on by a set of operators.
analytic_probability
([wires])Return the (marginal) probability of each computational basis state from the last run of the device.
apply
(operations[, rotations])Apply quantum operations, rotate the circuit into the measurement basis, and compile and execute the quantum circuit.
Get the capabilities of this device class.
check_validity
(queue, observables)Checks whether the operations and observables in queue are all supported by the device.
define_wire_map
(wires)Create the map from userprovided wire labels to the wire labels used by the device.
estimate_probability
([wires])Return the estimated probability of each computational basis state using the generated samples.
execute
(circuit, **kwargs)Execute a queue of quantum operations on the device and then measure the given observables.
The device execution context used during calls to
execute()
.expval
(observable)Returns the expectation value of observable on specified wires.
generate_basis_states
(num_wires[, dtype])Generates basis states in binary representation according to the number of wires specified.
Returns the computational basis samples generated for all wires.
map_wires
(wires)Map the wire labels of wires using this device’s wire map.
marginal_prob
(prob[, wires])Return the marginal probability of the computational basis states by summing the probabiliites on the nonspecified wires.
Called during
execute()
after the individual operations have been executed.Called during
execute()
after the individual observables have been measured.Called during
execute()
before the individual operations are executed.Called during
execute()
before the individual observables are measured.probability
([wires])Return either the analytic probability or estimated probability of each computational basis state.
reset
()Reset the device
sample
(observable)Return a sample of an observable.
sample_basis_states
(number_of_states, …)Sample from the computational basis states based on the state probability.
states_to_binary
(samples, num_wires[, dtype])Convert basis states from base 10 to binary representation.
statistics
(observables)Process measurement results from circuit execution and return statistics.
supports_observable
(observable)Checks if an observable is supported by this device. Raises a ValueError,
supports_operation
(operation)Checks if an operation is supported by this device.
var
(observable)Returns the variance of observable on specified wires.

access_state
()¶ Check that the device has access to an internal state and return it if available.
 Raises
QuantumFunctionError – if the device is not capable of returning the state
 Returns
the state of the device
 Return type
array or tensor

static
active_wires
(operators)¶ Returns the wires acted on by a set of operators.
 Parameters
operators (list[Operation]) – operators for which we are gathering the active wires
 Returns
wires activated by the specified operators
 Return type

analytic_probability
(wires=None)¶ Return the (marginal) probability of each computational basis state from the last run of the device.
PennyLane uses the convention \(q_0,q_1,\dots,q_{N1}\rangle\) where \(q_0\) is the most significant bit.
If no wires are specified, then all the basis states representable by the device are considered and no marginalization takes place.
Note
marginal_prob()
may be used as a utility method to calculate the marginal probability distribution. Parameters
wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.
 Returns
list of the probabilities
 Return type
List[float]

apply
(operations, rotations=None, **kwargs)¶ Apply quantum operations, rotate the circuit into the measurement basis, and compile and execute the quantum circuit.
This method receives a list of quantum operations queued by the QNode, and should be responsible for:
Constructing the quantum program
(Optional) Rotating the quantum circuit using the rotation operations provided. This diagonalizes the circuit so that arbitrary observables can be measured in the computational basis.
Compile the circuit
Execute the quantum circuit
Both arguments are provided as lists of PennyLane
Operation
instances. Useful properties includename
,wires
, andparameters
, andinverse
:>>> op = qml.RX(0.2, wires=[0]) >>> op.name # returns the operation name "RX" >>> op.wires # returns a Wires object representing the wires that the operation acts on <Wires = [0]> >>> op.parameters # returns a list of parameters [0.2] >>> op.inverse # check if the operation should be inverted False >>> op = qml.RX(0.2, wires=[0]).inv >>> op.inverse True
 Parameters
operations (list[Operation]) – operations to apply to the device
 Keyword Arguments
rotations (list[Operation]) – operations that rotate the circuit premeasurement into the eigenbasis of the observables.
hash (int) – the hash value of the circuit constructed by CircuitGraph.hash

classmethod
capabilities
()[source]¶ Get the capabilities of this device class.
Inheriting classes that change or add capabilities must override this method, for example via
@classmethod def capabilities(cls): capabilities = super().capabilities().copy() capabilities.update( supports_inverse_operations=False, supports_a_new_capability=True, ) return capabilities
 Returns
results
 Return type
dict[str>*]

check_validity
(queue, observables)¶ Checks whether the operations and observables in queue are all supported by the device. Includes checks for inverse operations.
 Parameters
queue (Iterable[Operation]) – quantum operation objects which are intended to be applied on the device
observables (Iterable[Observable]) – observables which are intended to be evaluated on the device
 Raises
DeviceError – if there are operations in the queue or observables that the device does not support

define_wire_map
(wires)¶ Create the map from userprovided wire labels to the wire labels used by the device.
The default wire map maps the user wire labels to wire labels that are consecutive integers.
However, by overwriting this function, devices can specify their preferred, nonconsecutive and/or noninteger wire labels.
 Parameters
wires (Wires) – userprovided wires for this device
 Returns
dictionary specifying the wire map
 Return type
OrderedDict
Example
>>> dev = device('my.device', wires=['b', 'a']) >>> dev.wire_map() OrderedDict( [(<Wires = ['a']>, <Wires = [0]>), (<Wires = ['b']>, <Wires = [1]>)])

estimate_probability
(wires=None)¶ Return the estimated probability of each computational basis state using the generated samples.
 Parameters
wires (Iterable[Number, str], Number, str, Wires) – wires to calculate marginal probabilities for. Wires not provided are traced out of the system.
 Returns
list of the probabilities
 Return type
List[float]

execute
(circuit, **kwargs)¶ Execute a queue of quantum operations on the device and then measure the given observables.
For plugin developers: instead of overwriting this, consider implementing a suitable subset of
Additional keyword arguments may be passed to the this method that can be utilised by
apply()
. An example would be passing theQNode
hash that can be used later for parametric compilation. Parameters
circuit (CircuitGraph) – circuit to execute on the device
 Raises
QuantumFunctionError – if the value of
return_type
is not supported Returns
measured value(s)
 Return type
array[float]

execution_context
()¶ The device execution context used during calls to
execute()
.You can overwrite this function to return a context manager in case your quantum library requires that; all operations and method calls (including
apply()
andexpval()
) are then evaluated within the context of this context manager (see the source ofDevice.execute()
for more details).

expval
(observable)¶ Returns the expectation value of observable on specified wires.
Note: all arguments accept _lists_, which indicate a tensor product of observables.
 Parameters
observable (str or list[str]) – name of the observable(s)
wires (Wires) – wires the observable(s) are to be measured on
par (tuple or list[tuple]]) – parameters for the observable(s)
 Returns
expectation value \(\expect{A} = \bra{\psi}A\ket{\psi}\)
 Return type
float

static
generate_basis_states
(num_wires, dtype=<class 'numpy.uint32'>)¶ Generates basis states in binary representation according to the number of wires specified.
The states_to_binary method creates basis states faster (for larger systems at times over x25 times faster) than the approach using
itertools.product
, at the expense of using slightly more memory.Due to the large size of the integer arrays for more than 32 bits, memory allocation errors may arise in the states_to_binary method. Hence we constraint the dtype of the array to represent unsigned integers on 32 bits. Due to this constraint, an overflow occurs for 32 or more wires, therefore this approach is used only for fewer wires.
For smaller number of wires speed is comparable to the next approach (using
itertools.product
), hence we resort to that one for testing purposes. Parameters
num_wires (int) – the number wires
dtype=np.uint32 (type) – the data type of the arrays to use
 Returns
the sampled basis states
 Return type
np.ndarray

generate_samples
()¶ Returns the computational basis samples generated for all wires.
Note that PennyLane uses the convention \(q_0,q_1,\dots,q_{N1}\rangle\) where \(q_0\) is the most significant bit.
Warning
This method should be overwritten on devices that generate their own computational basis samples, with the resulting computational basis samples stored as
self._samples
. Returns
array of samples in the shape
(dev.shots, dev.num_wires)
 Return type
array[complex]

map_wires
(wires)¶ Map the wire labels of wires using this device’s wire map.

marginal_prob
(prob, wires=None)¶ Return the marginal probability of the computational basis states by summing the probabiliites on the nonspecified wires.
If no wires are specified, then all the basis states representable by the device are considered and no marginalization takes place.
Note
If the provided wires are not in the order as they appear on the device, the returned marginal probabilities take this permutation into account.
For example, if the addressable wires on this device are
Wires([0, 1, 2])
and this function gets passedwires=[2, 0]
, then the returned marginal probability vector will take this ‘reversal’ of the two wires into account:\[\mathbb{P}^{(2, 0)} = \left[ 00\rangle, 10\rangle, 01\rangle, 11\rangle \right]\] Parameters
prob – The probabilities to return the marginal probabilities for
wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.
 Returns
array of the resulting marginal probabilities.
 Return type
array[float]

probability
(wires=None)¶ Return either the analytic probability or estimated probability of each computational basis state.
If no
analytic
attributes exists for the device, then return the estimated probability. Parameters
wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.
 Returns
list of the probabilities
 Return type
List[float]

reset
()¶ Reset the device

sample
(observable)¶ Return a sample of an observable.
The number of samples is determined by the value of
Device.shots
, which can be directly modified.Note: all arguments support _lists_, which indicate a tensor product of observables.
 Parameters
observable (str or list[str]) – name of the observable(s)
wires (Wires) – wires the observable(s) is to be measured on
par (tuple or list[tuple]]) – parameters for the observable(s)
 Raises
NotImplementedError – if the device does not support sampling
 Returns
samples in an array of dimension
(shots,)
 Return type
array[float]

sample_basis_states
(number_of_states, state_probability)¶ Sample from the computational basis states based on the state probability.
This is an auxiliary method to the generate_samples method.
 Parameters
number_of_states (int) – the number of basis states to sample from
 Returns
the sampled basis states
 Return type
List[int]

static
states_to_binary
(samples, num_wires, dtype=<class 'numpy.int64'>)¶ Convert basis states from base 10 to binary representation.
This is an auxiliary method to the generate_samples method.
 Parameters
samples (List[int]) – samples of basis states in base 10 representation
num_wires (int) – the number of qubits
dtype (type) – Type of the internal integer array to be used. Can be important to specify for large systems for memory allocation purposes.
 Returns
basis states in binary representation
 Return type
List[int]

statistics
(observables)¶ Process measurement results from circuit execution and return statistics.
This includes returning expectation values, variance, samples, probabilities and states.
 Parameters
observables (List[
Observable
]) – the observables to be measured Raises
QuantumFunctionError – if the value of
return_type
is not supported Returns
the corresponding statistics
 Return type
Union[float, List[float]]

supports_observable
(observable)¶  Checks if an observable is supported by this device. Raises a ValueError,
if not a subclass or string of an Observable was passed.
 Parameters
observable (type or str) – observable to be checked
 Raises
ValueError – if observable is not a
Observable
class or string Returns
True
iff supplied observable is supported Return type
bool

supports_operation
(operation)¶ Checks if an operation is supported by this device.
 Parameters
operation (type or str) – operation to be checked
 Raises
ValueError – if operation is not a
Operation
class or string Returns
True
iff supplied operation is supported Return type
bool

var
(observable)¶ Returns the variance of observable on specified wires.
Note: all arguments support _lists_, which indicate a tensor product of observables.
 Parameters
observable (str or list[str]) – name of the observable(s)
wires (Wires) – wires the observable(s) is to be measured on
par (tuple or list[tuple]]) – parameters for the observable(s)
 Raises
NotImplementedError – if the device does not support variance computation
 Returns
variance \(\mathrm{var}(A) = \bra{\psi}A^2\ket{\psi}  \bra{\psi}A\ket{\psi}^2\)
 Return type
float
Contents
Using PennyLane
Development
API
Downloads