Skip to main content

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 a Rx gate for performing a “NOT” operation (spoiler, the correct answer is π\pi).

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.Module network
In section 2 we will choose our dataset, loss function, and optimizer. Section 3 will demostrate how to handle the learning process, and section 4 will test our network’s performance. If you’re not familiar with PyTorch, it is highly recommended that you’ll check out the following pages from their documentation:

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:
The input (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 the DATALOADER_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 PyTorch

Step 4 - Test

Lastly, we will test our network accuracy, using the following answer
The results show that the accuracy is 11, meaning a 100% success rate at performing the required transformation (i.e. the network learned to perform a X-gate). We may further test it by printing the value of model.qlayer.weight, which is a tensor of shape (1,1), which should, after training, be close to π\pi. 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 the QLayer 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.