qml.templates.layers.RandomLayers

class RandomLayers(weights, wires, ratio_imprim=0.3, imprimitive=None, rotations=None, seed=42, do_queue=True)[source]

Bases: pennylane.operation.Operation

Layers of randomly chosen single qubit rotations and 2-qubit entangling gates, acting on randomly chosen qubits.

Warning

This template uses random number generation inside qnodes. Find more details about how to invoke the desired random behaviour in the “Usage Details” section below.

The argument weights contains the weights for each layer. The number of layers \(L\) is therefore derived from the first dimension of weights.

The two-qubit gates of type imprimitive and the rotations are distributed randomly in the circuit. The number of random rotations is derived from the second dimension of weights. The number of two-qubit gates is determined by ratio_imprim. For example, a ratio of 0.3 with 30 rotations will lead to the use of 10 two-qubit gates.

Note

If applied to one qubit only, this template will use no imprimitive gates.

This is an example of two 4-qubit random layers with four Pauli-Y/Pauli-Z rotations \(R_y, R_z\), controlled-Z gates as imprimitives, as well as ratio_imprim=0.3:

../../_images/layer_rnd.png
Parameters
  • weights (tensor_like) – weight tensor of shape (L, k),

  • wires (Iterable) – wires that the template acts on

  • ratio_imprim (float) – value between 0 and 1 that determines the ratio of imprimitive to rotation gates

  • imprimitive (pennylane.ops.Operation) – two-qubit gate to use, defaults to CNOT

  • rotations (list[pennylane.ops.Operation]) – List of Pauli-X, Pauli-Y and/or Pauli-Z gates. The frequency determines how often a particular rotation type is used. Defaults to the use of all three rotations with equal frequency.

  • seed (int) – seed to generate random architecture, defaults to 42

Default seed

RandomLayers always uses a seed to initialize the construction of a random circuit. This means that the template creates the same circuit every time it is called. If no seed is provided, the default seed of 42 is used.

import pennylane as qml
import numpy as np
from pennylane.templates.layers import RandomLayers

dev = qml.device("default.qubit", wires=2)
weights = [[0.1, -2.1, 1.4]]

@qml.qnode(dev)
def circuit1(weights):
    RandomLayers(weights=weights, wires=range(2))
    return qml.expval(qml.PauliZ(0))

@qml.qnode(dev)
def circuit2(weights):
    RandomLayers(weights=weights, wires=range(2))
    return qml.expval(qml.PauliZ(0))
>>> np.allclose(circuit1(weights), circuit2(weights))
True

You can verify this by drawing the circuits.

>>> print(circuit1.draw())
0: ─────────────────────╭X──╭X──RZ(1.4)──┤ ⟨Z⟩
1: ──RX(0.1)──RX(-2.1)──╰C──╰C───────────┤
>>> print(circuit2.draw())
0: ─────────────────────╭X──╭X──RZ(1.4)──┤ ⟨Z⟩
1: ──RX(0.1)──RX(-2.1)──╰C──╰C───────────┤

Changing the seed

To change the randomly generated circuit architecture, you have to change the seed passed to the template. For example, these two calls of RandomLayers do not create the same circuit:

@qml.qnode(dev)
def circuit_9(weights):
    RandomLayers(weights=weights, wires=range(2), seed=9)
    return qml.expval(qml.PauliZ(0))

@qml.qnode(dev)
def circuit_12(weights):
    RandomLayers(weights=weights, wires=range(2), seed=12)
    return qml.expval(qml.PauliZ(0))
>>> np.allclose(circuit_9(weights), circuit_12(weights))
>>> False
>>> print(circuit_9.draw())
0: ──╭X──RX(0.1)────────────┤ ⟨Z⟩
1: ──╰C──RY(-2.1)──RX(1.4)──┤
>>> print(circuit_12.draw())
0: ──╭X──RZ(0.1)───╭C──╭X───────────┤ ⟨Z⟩
1: ──╰C──RX(-2.1)──╰X──╰C──RZ(1.4)──┤

Automatic creation of random circuits

To automate the process of creating different circuits with RandomLayers, you can set seed=None to avoid specifying a seed. However, in this case care needs to be taken. In the default setting, a quantum node is mutable, which means that the quantum function is re-evaluated every time it is called. This means that the circuit is re-constructed from scratch each time you call the qnode:

@qml.qnode(dev)
def circuit_rnd(weights):
    RandomLayers(weights=weights, wires=range(2), seed=None)
    return qml.expval(qml.PauliZ(0))

first_call = circuit_rnd(weights)
second_call = circuit_rnd(weights)
>>> np.allclose(first_call, second_call)
False

This can be rectified by making the quantum node immutable.

@qml.qnode(dev, mutable=False)
def circuit_rnd(weights):
    RandomLayers(weights=weights, wires=range(2), seed=None)
    return qml.expval(qml.PauliZ(0))

first_call = circuit_rnd(weights)
second_call = circuit_rnd(weights)
>>> np.allclose(first_call, second_call)
True

Parameter shape

The expected shape for the weight tensor can be computed with the static method shape() and used when creating randomly initialised weight tensors:

shape = RandomLayers.shape(n_layers=2, n_rotations=3)
weights = np.random.random(size=shape)

base_name

Get base name of the operator.

eigvals

Eigenvalues of an instantiated operator.

generator

Generator of the operation.

grad_method

Gradient computation method.

grad_recipe

Gradient recipe for the parameter-shift method.

inverse

Boolean determining if the inverse of the operation was requested.

matrix

Matrix representation of an instantiated operator in the computational basis.

name

Get and set the name of the operator.

num_params

num_wires

par_domain

parameters

Current parameter values.

string_for_inverse

wires

Wires of this operator.

base_name

Get base name of the operator.

eigvals
generator

Generator of the operation.

A length-2 list [generator, scaling_factor], where

  • generator is an existing PennyLane operation class or \(2\times 2\) Hermitian array that acts as the generator of the current operation

  • scaling_factor represents a scaling factor applied to the generator operation

For example, if \(U(\theta)=e^{i0.7\theta \sigma_x}\), then \(\sigma_x\), with scaling factor \(s\), is the generator of operator \(U(\theta)\):

generator = [PauliX, 0.7]

Default is [None, 1], indicating the operation has no generator.

grad_method

Gradient computation method.

  • 'A': analytic differentiation using the parameter-shift method.

  • 'F': finite difference numerical differentiation.

  • None: the operation may not be differentiated.

Default is 'F', or None if the Operation has zero parameters.

grad_recipe = None

Gradient recipe for the parameter-shift method.

This is a tuple with one nested list per operation parameter. For parameter \(\phi_k\), the nested list contains elements of the form \([c_i, a_i, s_i]\) where \(i\) is the index of the term, resulting in a gradient recipe of

\[\frac{\partial}{\partial\phi_k}f = \sum_{i} c_i f(a_i \phi_k + s_i).\]

If None, the default gradient recipe containing the two terms \([c_0, a_0, s_0]=[1/2, 1, \pi/2]\) and \([c_1, a_1, s_1]=[-1/2, 1, -\pi/2]\) is assumed for every parameter.

Type

tuple(Union(list[list[float]], None)) or None

inverse

Boolean determining if the inverse of the operation was requested.

matrix
name

Get and set the name of the operator.

num_params = 1
num_wires = -1
par_domain = 'A'
parameters

Current parameter values.

string_for_inverse = '.inv'
wires

Wires of this operator.

Returns

wires

Return type

Wires

adjoint([do_queue])

Create an operation that is the adjoint of this one.

decomposition(*params, wires)

Returns a template decomposing the operation into other quantum operations.

expand()

Returns a tape containing the decomposed operations, rather than a list.

get_parameter_shift(idx[, shift])

Multiplier and shift for the given parameter, based on its gradient recipe.

inv()

Inverts the operation, such that the inverse will be used for the computations by the specific device.

queue()

Append the operator to the Operator queue.

shape(n_layers, n_rotations)

Returns the expected shape of the weights tensor.

adjoint(do_queue=False)

Create an operation that is the adjoint of this one.

Adjointed operations are the conjugated and transposed version of the original operation. Adjointed ops are equivalent to the inverted operation for unitary gates.

Parameters

do_queue – Whether to add the adjointed gate to the context queue.

Returns

The adjointed operation.

static decomposition(*params, wires)

Returns a template decomposing the operation into other quantum operations.

expand()[source]

Returns a tape containing the decomposed operations, rather than a list.

Returns

Returns a quantum tape that contains the operations decomposition, or if not implemented, simply the operation itself.

Return type

JacobianTape

get_parameter_shift(idx, shift=1.5707963267948966)

Multiplier and shift for the given parameter, based on its gradient recipe.

Parameters

idx (int) – parameter index

Returns

multiplier, shift

Return type

float, float

inv()

Inverts the operation, such that the inverse will be used for the computations by the specific device.

This method concatenates a string to the name of the operation, to indicate that the inverse will be used for computations.

Any subsequent call of this method will toggle between the original operation and the inverse of the operation.

Returns

operation to be inverted

Return type

Operator

queue()

Append the operator to the Operator queue.

static shape(n_layers, n_rotations)[source]

Returns the expected shape of the weights tensor.

Parameters
  • n_layers (int) – number of layers

  • n_rotations (int) – number of rotations

Returns

shape

Return type

tuple[int]