class TorchLayer(qnode, weight_shapes: dict, init_method: Optional[Callable] = None)[source]

Bases: torch.nn.modules.module.Module

Converts a QNode() to a Torch layer.

The result can be used within the torch.nn Sequential or Module classes for creating quantum and hybrid models.

  • qnode (qml.QNode) – the PennyLane QNode to be converted into a Torch layer

  • weight_shapes (dict[str, tuple]) – a dictionary mapping from all weights used in the QNode to their corresponding shapes

  • init_method (callable) – a torch.nn.init function for initializing the QNode weights. If not specified, weights are randomly initialized using the uniform distribution over \([0, 2 \pi]\).


First let’s define the QNode that we want to convert into a Torch layer:

n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)

def qnode(inputs, weights_0, weight_1):
    qml.RX(inputs[0], wires=0)
    qml.RX(inputs[1], wires=1)
    qml.Rot(*weights_0, wires=0)
    qml.RY(weight_1, wires=1)
    qml.CNOT(wires=[0, 1])
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

The signature of the QNode must contain an inputs named argument for input data, with all other arguments to be treated as internal weights. We can then convert to a Torch layer with:

>>> weight_shapes = {"weights_0": 3, "weight_1": 1}
>>> qlayer = qml.qnn.TorchLayer(qnode, weight_shapes)

The internal weights of the QNode are automatically initialized within the TorchLayer and must have their shapes specified in a weight_shapes dictionary. It is then easy to combine with other neural network layers from the torch.nn module and create a hybrid:

>>> clayer = torch.nn.Linear(2, 2)
>>> model = torch.nn.Sequential(qlayer, clayer)

QNode signature

The QNode must have a signature that satisfies the following conditions:

  • Contain an inputs named argument for input data.

  • All other arguments must accept an array or tensor and are treated as internal weights of the QNode.

  • All other arguments must have no default value.

  • The inputs argument is permitted to have a default value provided the gradient with respect to inputs is not required.

  • There cannot be a variable number of positional or keyword arguments, e.g., no *args or **kwargs present in the signature.

Initializing weights

The optional init_method argument of TorchLayer allows for the initialization method of the QNode weights to be specified. The function passed to the argument must be from the torch.nn.init module. For example, weights can be randomly initialized from the normal distribution by passing:

init_method = torch.nn.init.normal_

If init_method is not specified, weights are randomly initialized from the uniform distribution on the interval \([0, 2 \pi]\).

Full code example

The code block below shows how a circuit composed of templates from the qml.templates module can be combined with classical Linear layers to learn the two-dimensional moons dataset.

import numpy as np
import pennylane as qml
import torch
import sklearn.datasets

n_qubits = 2
dev = qml.device("default.qubit", wires=n_qubits)

def qnode(inputs, weights):
    qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
    qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

weight_shapes = {"weights": (3, n_qubits, 3)}

qlayer = qml.qnn.TorchLayer(qnode, weight_shapes)
clayer1 = torch.nn.Linear(2, 2)
clayer2 = torch.nn.Linear(2, 2)
softmax = torch.nn.Softmax(dim=1)
model = torch.nn.Sequential(clayer1, qlayer, clayer2, softmax)

samples = 100
x, y = sklearn.datasets.make_moons(samples)
y_hot = np.zeros((samples, 2))
y_hot[np.arange(samples), y] = 1

X = torch.tensor(x).float()
Y = torch.tensor(y_hot).float()

opt = torch.optim.SGD(model.parameters(), lr=0.5)
loss = torch.nn.L1Loss()

The model can be trained using:

epochs = 8
batch_size = 5
batches = samples // batch_size

data_loader = torch.utils.data.DataLoader(list(zip(X, Y)), batch_size=batch_size,
                                          shuffle=True, drop_last=True)

for epoch in range(epochs):

    running_loss = 0

    for x, y in data_loader:

        loss_evaluated = loss(model(x), y)


        running_loss += loss_evaluated

    avg_loss = running_loss / batches
    print("Average loss over epoch {}: {:.4f}".format(epoch + 1, avg_loss))

An example output is shown below:

Average loss over epoch 1: 0.5089
Average loss over epoch 2: 0.4765
Average loss over epoch 3: 0.2710
Average loss over epoch 4: 0.1865
Average loss over epoch 5: 0.1670
Average loss over epoch 6: 0.1635
Average loss over epoch 7: 0.1528
Average loss over epoch 8: 0.1528


Name of the argument to be used as the input to the Torch layer.


Name of the argument to be used as the input to the Torch layer. Set to "inputs".


Evaluates a forward pass through the QNode based upon input data and the initialized weights.


Evaluates a forward pass through the QNode based upon input data and the initialized weights.


inputs (tensor) – data to be processed


output data

Return type