Intro
In this example, we will show a simple example of parametric quantum program (PQC). We will take 1 input from the user, and consider 1 weight, while utilizing 1 qubit in the PQC. During this example, the goal of the learning process is to assess the right angle for aRx gate for performing a “NOT” operation (spoiler, the correct answer is ).
General flow
In section 1 we will see the code required for defining a quantum layer. This will include:- section 1.1: defining the quantum model and synthesizing it to a quantum program
- section 1.2: defining the post-process callable
- section 1.3: defining a
torch.nn.Modulenetwork
- Creating Models
- Build the Neural Network
- Optimizing the Model Parameters
- Tensors
- Datasets & DataLoaders
Step 1 - Create our torch.nn.Module
Step 1.1 - Create our parametric quantum program
Our quantum model will be defined and synthesized as follows:input_0), logically indicating the state |0> or |1>, is transformed into an angle, either 0 or pi.
Step 1.2 - Create the Post-processing
Post-process the result of executing the quantum program to obtain a single number (float) and a single dimension Tensor.
Step 1.3 - Create a network
Now we’re going to define a network, just like any other PyTorch network, only that this time, we will have only 1 layer, and it will be a quantum layer.Step 2 - Choose a dataset, loss function, and optimizer
We will use theDATALOADER_NOT dataset, defined here, as well as L1Loss and SGD
Step 3 - Train
For the training process, we will use a loop similar to the one recommended by PyTorchStep 4 - Test
Lastly, we will test our network accuracy, using the following answermodel.qlayer.weight, which is a tensor of shape (1,1), which should, after training, be close to .
Finally, we safely teardown the QLayer instance.
Summary
In this example, we wrote a fully working Quantum Neural Network from scratch, trained it, and saw its success at learning the requested transformation. In section 1 we defined our parametric quantum program, as well as our post-processing function. Together, these two are sent as arguments to theQLayer object.
In section 2 we set some hyperparameters, and in section 3 we trained our model.
Section 4 helped us verify that our network is working as intended.