qml.beta.devices.DefaultTensorTF¶

class
DefaultTensorTF
(wires, shots=None, representation='exact', contraction_method='auto')[source]¶ Bases:
pennylane.beta.devices.default_tensor.DefaultTensor
Experimental TensorFlow Tensor Network simulator device for PennyLane.
Short name:
default.tensor.tf
This experimental device extends
default.tensor
by making use of the TensorFlow backend of TensorNetwork. As a result, it supports classical backpropagation as a means to compute the Jacobian. 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 TensorFlow and TensorNetwork:
pip install tensornetwork>=0.2 tensorflow>=2.0
Example
The
default.tensor.tf
device supports endtoend classical backpropagation with the TensorFlow interface.Using this method, the created QNode is a ‘whitebox’, and is tightly integrated with your TensorFlow computation:
>>> dev = qml.device("default.tensor.tf", wires=1) >>> @qml.qnode(dev, interface="tf", 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)) >>> vars = tf.Variable([0.2, 0.5, 0.1]) >>> with tf.GradientTape() as tape: ... res = circuit(vars) >>> tape.gradient(res, vars) <tf.Tensor: shape=(3,), dtype=float32, numpy=array([2.2526717e01, 1.0086454e+00, 1.3877788e17], dtype=float32)>
In this mode, you must use the
"tf"
interface, as TensorFlow is used as the device backend. Parameters
wires (int) – number of subsystems in the quantum state represented by the device
shots (None, int) – Number of circuit evaluations/random samples to return when sampling from the device. Defaults to
None
if not specified, which means that the device returns analytical results.representation (str) – Underlying representation used for the tensor network simulation. Valid options are “exact” (no approximations made) or “mps” (simulated quantum state is approximated as a Matrix Product State).
contraction_method (str) – Method used to perform tensor network contractions. Only applicable for the “exact” representation. Valid options are “auto”, “greedy”, “branch”, or “optimal”. See documentation of the TensorNetwork library for more information about contraction methods.
Attributes
Whether shots is None or not.
The contraction method used by the tensor network.
Number of times this device is executed by the evaluation of QNodes running on this device
The observables to be measured and returned.
Get the supported set of observables.
The operation queue to be applied.
Get the supported set of operations.
Mapping from free parameter index to the list of
Operations
in the device queue that depend on it.Returns the shot vector, a sparse representation of the shot sequence used by the device when evaluating QNodes.
Number of circuit evaluations/random samples used to estimate expectation values of observables
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

C_DTYPE
= tf.complex128¶

R_DTYPE
= tf.float64¶

analytic
¶ Whether shots is None or not. Kept for backwards compatability.

backend
= 'tensorflow'¶

contraction_method
¶ The contraction method used by the tensor network. Available options are “auto”, “greedy”, “branch”, or “optimal”. See TensorNetwork library documentation for more details.

name
= 'PennyLane TensorNetwork (TensorFlow) simulator plugin'¶

num_executions
¶ Number of times this device is executed by the evaluation of QNodes running on this device
 Returns
number of executions
 Return type
int

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
¶

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
¶

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]]

pennylane_requires
= '0.18.0'¶

short_name
= 'default.tensor.tf'¶

shot_vector
¶ Returns the shot vector, a sparse representation of the shot sequence used by the device when evaluating QNodes.
Example
>>> dev = qml.device("default.qubit", wires=2, shots=[3, 1, 2, 2, 2, 2, 6, 1, 1, 5, 12, 10, 10]) >>> dev.shots 57 >>> dev.shot_vector [ShotTuple(shots=3, copies=1), ShotTuple(shots=1, copies=1), ShotTuple(shots=2, copies=4), ShotTuple(shots=6, copies=1), ShotTuple(shots=1, copies=2), ShotTuple(shots=5, copies=1), ShotTuple(shots=12, copies=1), ShotTuple(shots=10, copies=2)]
The sparse representation of the shot sequence is returned, where tuples indicate the number of times a shot integer is repeated.
 Type
list[ShotTuple[int, int]]

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

version
= '0.18.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
apply
(operation, wires, par)Apply a quantum operation.
batch_execute
(circuits)Execute a batch of quantum circuits on the device.
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.
ev
(obs_nodes, obs_wires)Expectation value of observables on specified wires.
execute
(queue, observables[, parameters])Execute a queue of quantum operations on the device and then measure the given observables.
execute_and_gradients
(circuits[, method])Execute a batch of quantum circuits on the device, and return both the results and the gradients.
The device execution context used during calls to
execute()
.expval
(observable, wires, par)Returns the expectation value of observable on specified wires.
gradients
(circuits[, method])Return the gradients of a batch of quantum circuits on the device.
map_wires
(wires)Map the wire labels of wires using this device’s wire map.
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 the (marginal) probability of each computational basis state from the last run of the device.
reset
()Reset the device.
sample
(observable, wires, par)Return a sample of an observable.
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, wires, par)Returns the variance of observable on specified wires.

apply
(operation, wires, par)¶ Apply a quantum operation.
For plugin developers: this function should apply the operation on the device.
 Parameters
operation (str) – name of the operation
wires (Wires) – wires that the operation is applied to
par (tuple) – parameters for the operation

batch_execute
(circuits)¶ Execute a batch of quantum circuits on the device.
The circuits are represented by tapes, and they are executed onebyone using the device’s
execute
method. The results are collected in a list.For plugin developers: This function should be overwritten if the device can efficiently run multiple circuits on a backend, for example using parallel and/or asynchronous executions.
 Parameters
circuits (list[tape.QuantumTape]) – circuits to execute on the device
 Returns
list of measured value(s)
 Return type
list[array[float]]

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]>)])

ev
(obs_nodes, obs_wires)¶ Expectation value of observables on specified wires.
 Parameters
obs_nodes (Sequence[tn.Node]) – the observables as TensorNetwork Nodes
obs_wires (Sequence[Wires]) – measured wires for each observable
 Returns
expectation value \(\expect{A} = \bra{\psi}A\ket{\psi}\)
 Return type
float

execute
(queue, observables, parameters={}, **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
pre_apply()
,apply()
,post_apply()
,pre_measure()
,expval()
,var()
,sample()
,post_measure()
, andexecution_context()
. Parameters
queue (Iterable[Operation]) – operations to execute on the device
observables (Iterable[Observable]) – observables to measure and return
parameters (dict[int, list[ParameterDependency]]) – Mapping from free parameter index to the list of
Operations
(in the queue) that depend on it.
 Keyword Arguments
return_native_type (bool) – If True, return the result in whatever type the device uses internally, otherwise convert it into array[float]. Default: False.
 Raises
QuantumFunctionError – if the value of
return_type
is not supported Returns
measured value(s)
 Return type
array[float]

execute_and_gradients
(circuits, method='jacobian', **kwargs)¶ Execute a batch of quantum circuits on the device, and return both the results and the gradients.
The circuits are represented by tapes, and they are executed onebyone using the device’s
execute
method. The results and the corresponding Jacobians are collected in a list.For plugin developers: This method should be overwritten if the device can efficiently run multiple circuits on a backend, for example using parallel and/or asynchronous executions, and return both the results and the Jacobians.
 Parameters
circuits (list[tape.QuantumTape]) – circuits to execute on the device
method (str) – the device method to call to compute the Jacobian of a single circuit
**kwargs – keyword argument to pass when calling
method
 Returns
Tuple containing list of measured value(s) and list of Jacobians. Returned Jacobians should be of shape
(output_shape, num_params)
. Return type
tuple[list[array[float]], list[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, wires, par)¶ 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

gradients
(circuits, method='jacobian', **kwargs)¶ Return the gradients of a batch of quantum circuits on the device.
The gradient method
method
is called sequentially for each circuit, and the corresponding Jacobians are collected in a list.For plugin developers: This method should be overwritten if the device can efficiently compute the gradient of multiple circuits on a backend, for example using parallel and/or asynchronous executions.
 Parameters
circuits (list[tape.QuantumTape]) – circuits to execute on the device
method (str) – the device method to call to compute the Jacobian of a single circuit
**kwargs – keyword argument to pass when calling
method
 Returns
List of Jacobians. Returned Jacobians should be of shape
(output_shape, num_params)
. Return type
list[array[float]]

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

probability
(wires=None)¶ Return the (marginal) probability of each computational basis state from the last run of the device.
 Parameters
wires (Sequence[int]) – Sequence of wires to return marginal probabilities for. Wires not provided are traced out of the system.
 Returns
Dictionary mapping a tuple representing the state to the resulting probability. The dictionary should be sorted such that the state tuples are in lexicographical order.
 Return type
OrderedDict[tuple, float]

reset
()¶ Reset the device.

sample
(observable, wires, par)¶ 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]

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, wires, par)¶ 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