qml.qnn.TorchLayer

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.

Parameters
  • 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]\).

Example

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)

@qml.qnode(dev)
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)

@qml.qnode(dev)
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:
        opt.zero_grad()

        loss_evaluated = loss(model(x), y)
        loss_evaluated.backward()

        opt.step()

        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

T_destination

alias of TypeVar(‘T_destination’)

dump_patches

This allows better BC support for load_state_dict().

input_arg

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

input_arg

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

add_module(name, module)

Adds a child module to the current module.

apply(fn)

Applies fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Returns an iterator over module buffers.

children()

Returns an iterator over immediate children modules.

cpu()

Moves all model parameters and buffers to the CPU.

cuda([device])

Moves all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Sets the module in evaluation mode.

extra_repr()

Set the extra representation of the module

float()

Casts all floating point parameters and buffers to float datatype.

forward(inputs)

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

half()

Casts all floating point parameters and buffers to half datatype.

load_state_dict(state_dict[, strict])

Copies parameters and buffers from state_dict into this module and its descendants.

modules()

Returns an iterator over all modules in the network.

named_buffers([prefix, recurse])

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix])

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse])

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Returns an iterator over module parameters.

register_backward_hook(hook)

Registers a backward hook on the module.

register_buffer(name, tensor[, persistent])

Adds a buffer to the module.

register_forward_hook(hook)

Registers a forward hook on the module.

register_forward_pre_hook(hook)

Registers a forward pre-hook on the module.

register_parameter(name, param)

Adds a parameter to the module.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

share_memory()

state_dict([destination, prefix, keep_vars])

Returns a dictionary containing a whole state of the module.

to(*args, **kwargs)

Moves and/or casts the parameters and buffers.

train([mode])

Sets the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

zero_grad([set_to_none])

Sets gradients of all model parameters to zero.

forward(inputs)[source]

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

Parameters

inputs (tensor) – data to be processed

Returns

output data

Return type

tensor