VQCC_EN.ipynb 28.0 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8a69d69c",
   "metadata": {},
   "source": [
    "# Variational Quantum Circuit Compiling"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a24d6cf3",
   "metadata": {},
   "source": [
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "596b716a",
   "metadata": {},
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07a15fd1",
   "metadata": {},
   "source": [
    "Variational quantum circuit compilation is the process of simulating an unknown unitary operator by optimizing a parameterized quantum circuit. In this tutorial we will discuss two cases of unknown unitary operators. One is that the target $U$ is given as a matrix form, the other is that the $U$ is given as a black-box. We show how to obtain the loss function in both cases in Paddle Quantum. With auto-differentiation and optimizer provided with PaddlePaddle, we could easily approximate $U$ into a trainable sequence of quantum gates (here we use $V(\\vec{\\theta})$ to denote the unitary operator represented by the sequence of parameterized quantum gates, and for simplicity, we use $V$ below). Finally, we validate the optimized circuit by comparing the trace distance of various output density matrices transformed by the approximate circuit and the target $U$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "166a3d1c",
   "metadata": {},
   "source": [
    "## Background\n",
    "\n",
    "Earlier compilations of classical computers transformed binary numbers into electrical signals to drive the computer's electronic devices to perform operations, and then gradually developed into an assembly language for easy processing and writing. For quantum computers, similar to classical compilation, quantum compilation is a process of converting the unitary in a quantum algorithm into a series of the quantum gates to implement the algorithm. The current noisy intermediate-scale quantum (NISQ) devices have limitations such as the number of qubits, circuit depth, etc., which pose a great challenge to quantum compilation algorithms. In [1], a quantum compilation algorithm, the Quantum-assisted Quantum Compiling (QAQC), has been proposed for efficient implementation on NISQ devices. The idea of QAQC is to compile the unknown target unitary operator $U$ into the unitary $V$, define the loss function using the gate fidelity, and continuously optimize a variational quantum circuit by minimizing the loss function. But how to measure the similarity of the two unitary operators? Here we consider the probability that the unitary evolution of the $V$ can simulate the $U$, i.e., the degree of overlap between $U|\\psi\\rangle$ and $V|\\psi\\rangle$ for the input state $|\\psi\\rangle$, which is the average of the fidelity on the Haar distribution:\n",
    "\n",
    "$$\n",
    "F(U,V)=\\int_{\\psi}|\\langle\\psi|V^{\\dagger}U|\\psi\\rangle|^2d\\psi,\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "When $F(U,V)=1$, there is a $\\phi$ such that $V=e^{i\\phi}U$, i.e., the two unitary operators differ by a global phase factor, at which point we call $V$ an exact compilation of $U$. When $F(U,V)\\geq 1-\\epsilon$, we call $V$ an approximate compilation of $U$, where $\\epsilon$ is an error and $\\epsilon\\in[0,1]$. Based on this, we can construct the following loss function:\n",
    "\n",
    "$$\n",
    "\\begin{aligned} C(U,V)&=\\frac{d+1}{d}(1-F(U,V))\\\\\n",
    "&=1-\\frac{1}{d^2}|\\langle V,U\\rangle|^2\\\\\n",
    "&=1-\\frac{1}{d^2}|\\text{tr}(V^{\\dagger} U)|^2,\n",
    "\\end{aligned}\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "where $n$ is the number of qubits, $d=2^n$ and $\\frac{1}{d^2}|\\text{tr}(V^{\\dagger} U)|^2$ is the gate fidelity.\n",
    "\n",
    "From (2), we have that $C(V,U)=0$ if and only if $F(U,V)=1$, so we can obtain $V$ that approximates the target unitary operator $U$ by training a sequence of rotational gates with adjustable angles to minimize the loss function."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "189c9359",
   "metadata": {},
   "source": [
    "## The First Scenario - Matrix Form of $U$\n",
    "\n",
    "In the first case, we suppose that $U$ is given in the form of a matrix. Taking the Toffoli gate as an example, we note its matrix representation as $U_0$. We wish to construct a quantum neural network (QNN, i.e., parameterized quantum circuit) to obtain an approximate circuit decomposition of $U_0$ by training.\n",
    "\n",
    "Let us import the necessary packages:"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
78
   "execution_count": 1,
Q
Quleaf 已提交
79 80
   "id": "ae8f2fdb",
   "metadata": {},
Q
Quleaf 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/openfermion/hamiltonians/hartree_fock.py:11: DeprecationWarning: Please use `OptimizeResult` from the `scipy.optimize` namespace, the `scipy.optimize.optimize` namespace is deprecated.\n",
      "  from scipy.optimize.optimize import OptimizeResult\n",
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  if data.dtype == np.object:\n",
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  if data.dtype == np.object:\n"
     ]
    }
   ],
Q
Quleaf 已提交
97 98 99
   "source": [
    "import numpy as np\n",
    "import paddle\n",
Q
Quleaf 已提交
100 101 102 103
    "import paddle_quantum\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.linalg import dagger\n",
    "from paddle_quantum.state import random_state, zero_state"
Q
Quleaf 已提交
104 105 106 107 108 109 110 111 112 113 114 115
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83d5d086",
   "metadata": {},
   "source": [
    "We need to get the Toffoli gate's unitary matrix:"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
116
   "execution_count": 2,
Q
Quleaf 已提交
117 118 119 120 121
   "id": "4663732b",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 3  # Number of qubits\n",
Q
Quleaf 已提交
122
    "\n",
Q
Quleaf 已提交
123 124 125 126 127 128 129 130 131
    "# The matrix form of Toffoli gate\n",
    "U_0 = paddle.to_tensor(np.matrix([[1, 0, 0, 0, 0, 0, 0, 0],\n",
    "                                  [0, 1, 0, 0, 0, 0, 0, 0],\n",
    "                                  [0, 0, 1, 0, 0, 0, 0, 0],\n",
    "                                  [0, 0, 0, 1, 0, 0, 0, 0],\n",
    "                                  [0, 0, 0, 0, 1, 0, 0, 0],\n",
    "                                  [0, 0, 0, 0, 0, 1, 0, 0],\n",
    "                                  [0, 0, 0, 0, 0, 0, 0, 1],\n",
    "                                  [0, 0, 0, 0, 0, 0, 1, 0]],\n",
Q
Quleaf 已提交
132
    "                       dtype=\"float32\"))"
Q
Quleaf 已提交
133 134 135 136 137 138 139 140 141
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfc61ad3",
   "metadata": {},
   "source": [
    "### Constructing quantum circuits\n",
    "\n",
Q
Quleaf 已提交
142
    "Different QNNs have different expressibility. Here we choose the `complex_entangled_layer()` function built-in in Paddle Quantum to construct QNN:"
Q
Quleaf 已提交
143 144 145 146
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
147
   "execution_count": 3,
Q
Quleaf 已提交
148 149 150 151 152
   "id": "4e400e2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Constructing quantum circuit\n",
Q
Quleaf 已提交
153
    "def qcircuit(n, D):\n",
Q
Quleaf 已提交
154
    "    # Initialize the circuit\n",
Q
Quleaf 已提交
155
    "    cir = Circuit(n)\n",
Q
Quleaf 已提交
156
    "    # Call the built-in QNN template\n",
Q
Quleaf 已提交
157
    "    cir.complex_entangled_layer('full', D)\n",
Q
Quleaf 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    "\n",
    "    return cir"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d97698f3",
   "metadata": {},
   "source": [
    "\n",
    "### Setting up the training model - loss function\n",
    "\n",
    "Next we define the loss function $C(U,V) = 1-\\frac{1}{d^2}|\\text{tr}(V^{\\dagger} U)|^2$ and training parameters in order to optimize the parameterized circuit. "
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
175
   "execution_count": 4,
Q
Quleaf 已提交
176 177 178 179
   "id": "29c9ed4a",
   "metadata": {},
   "outputs": [],
   "source": [
Q
Quleaf 已提交
180 181 182 183 184 185
    "# Define the loss function\n",
    "def loss_func(cir, target_u):\n",
    "    # The matrix form of the circuit\n",
    "    V = cir.unitary_matrix()\n",
    "    # Construct Eq.(1) as the loss function\n",
    "    loss = 1 - (dagger(V).matmul(target_u).trace().abs() / V.shape[0]) ** 2\n",
Q
Quleaf 已提交
186
    "\n",
Q
Quleaf 已提交
187
    "    return loss "
Q
Quleaf 已提交
188 189 190 191 192 193 194 195 196
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8229500e",
   "metadata": {},
   "source": [
    "### Setting up the training model - model parameters\n",
    "\n",
Q
Quleaf 已提交
197
    "Before training the QNN, we also need to set some training hyperparameters, mainly the depth (D) of repeated blocks, the learning rate (LR), and the number of iterations (ITR). Here we set the learning rate to 0.2 and the number of iterations to 150. The reader can adjust the hyperparameters to observe the impact on the training effect."
Q
Quleaf 已提交
198 199 200 201
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
202
   "execution_count": 5,
Q
Quleaf 已提交
203 204 205 206 207
   "id": "4046e5b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "D = 5  # Set the depth of QNN\n",
Q
Quleaf 已提交
208
    "LR = 0.2  # Set the learning rate\n",
Q
Quleaf 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221
    "ITR = 150   # Set the number of optimization iterations"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcde30e5",
   "metadata": {},
   "source": [
    "### Training"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
222
   "execution_count": 6,
Q
Quleaf 已提交
223 224 225
   "id": "7103bf1c",
   "metadata": {},
   "outputs": [
Q
Quleaf 已提交
226 227 228 229 230 231 232 233 234
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/fluid/framework.py:1104: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  elif dtype == np.bool:\n"
     ]
    },
Q
Quleaf 已提交
235 236 237 238
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
239 240 241 242 243
      "iter: 30 loss: 0.1692\n",
      "iter: 60 loss: 0.1476\n",
      "iter: 90 loss: 0.1465\n",
      "iter: 120 loss: 0.1464\n",
      "iter: 150 loss: 0.1464\n",
Q
Quleaf 已提交
244
      "\n",
Q
Quleaf 已提交
245
      "The trained circuit:\n",
Q
Quleaf 已提交
246 247 248 249 250 251 252
      "--U----*---------x----U----*---------x----U----*---------x----U----*---------x----U----*---------x--\n",
      "       |         |         |         |         |         |         |         |         |         |  \n",
      "--U----x----*----|----U----x----*----|----U----x----*----|----U----x----*----|----U----x----*----|--\n",
      "            |    |              |    |              |    |              |    |              |    |  \n",
      "--U---------x----*----U---------x----*----U---------x----*----U---------x----*----U---------x----*--\n",
      "                                                                                                    \n",
      "The trained parameter theta:\n",
Q
Quleaf 已提交
253 254 255 256
      " [[[[ 3.142e+00  2.169e+00  1.385e+00]\n",
      "   [-1.571e+00  1.569e+00  2.356e+00]\n",
      "   [ 3.141e+00  5.280e+00 -1.279e+00]]]\n",
      "\n",
Q
Quleaf 已提交
257
      "\n",
Q
Quleaf 已提交
258 259 260
      " [[[ 4.712e+00  1.570e+00  3.141e+00]\n",
      "   [ 3.927e+00  3.138e+00  3.139e+00]\n",
      "   [ 4.713e+00  4.712e+00  6.283e+00]]]\n",
Q
Quleaf 已提交
261 262
      "\n",
      "\n",
Q
Quleaf 已提交
263 264 265
      " [[[ 3.142e+00  2.963e+00  1.393e+00]\n",
      "   [ 3.142e+00 -3.700e-01  1.201e+00]\n",
      "   [ 2.356e+00  3.144e+00  6.283e+00]]]\n",
Q
Quleaf 已提交
266
      "\n",
Q
Quleaf 已提交
267 268 269 270 271 272 273 274 275
      "\n",
      " [[[ 3.142e+00  4.092e+00  9.500e-01]\n",
      "   [ 3.280e+00  1.572e+00  7.860e-01]\n",
      "   [ 3.927e+00  1.571e+00  6.281e+00]]]\n",
      "\n",
      "\n",
      " [[[-1.570e+00  3.279e+00 -4.000e-03]\n",
      "   [ 4.712e+00 -1.380e-01  6.284e+00]\n",
      "   [ 1.571e+00  6.421e+00  6.283e+00]]]]\n"
Q
Quleaf 已提交
276 277 278 279
     ]
    }
   ],
   "source": [
Q
Quleaf 已提交
280
    "cir = qcircuit(n, D)\n",
Q
Quleaf 已提交
281
    "# Using Adam optimizer to obtain relatively good convergence\n",
Q
Quleaf 已提交
282
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=cir.parameters())\n",
Q
Quleaf 已提交
283 284 285
    "\n",
    "# Optimization loop\n",
    "for itr in range(1, ITR + 1):\n",
Q
Quleaf 已提交
286
    "    loss = loss_func(cir, U_0)\n",
Q
Quleaf 已提交
287 288 289 290 291 292 293
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    if itr % 30 == 0:\n",
    "        print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
    "    if itr == ITR:\n",
Q
Quleaf 已提交
294
    "        print(\"\\nThe trained circuit:\")\n",
Q
Quleaf 已提交
295 296
    "        print(cir)\n",
    "\n",
Q
Quleaf 已提交
297
    "theta_opt = cir.parameters()\n",
Q
Quleaf 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    "print(\"The trained parameter theta:\\n\", np.around(theta_opt, decimals=3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca9f9196",
   "metadata": {},
   "source": [
    "In this case, we construct a five-layer QNN and train it with an Adam optimizer. After around 150 iterations, the loss function reaches 0."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5f13518",
   "metadata": {},
   "source": [
    "### Validation of results\n",
    "\n",
    "In the following, we randomly select 10 density matrices, which are evolved by the target unitary operator $U$ and the approximate unitary operator $V$. Then we calculate the trace distance $ d(\\rho, \\sigma) = \\frac{1}{2}\\text{tr}\\sqrt{(\\rho-\\sigma)^{\\dagger}(\\rho-\\sigma)}$ between the real output `real_output` $\\rho$ and the approximate output `simulated_output` $\\sigma$. The smaller the trace distance, the better the approximation effect."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
321
   "execution_count": 7,
Q
Quleaf 已提交
322 323 324 325 326 327 328 329
   "id": "12678dff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample 1 :\n",
Q
Quleaf 已提交
330
      "  trace distance is 0.19792\n",
Q
Quleaf 已提交
331
      "sample 2 :\n",
Q
Quleaf 已提交
332
      "  trace distance is 0.2463\n",
Q
Quleaf 已提交
333
      "sample 3 :\n",
Q
Quleaf 已提交
334
      "  trace distance is 0.2343\n",
Q
Quleaf 已提交
335
      "sample 4 :\n",
Q
Quleaf 已提交
336
      "  trace distance is 0.18177\n",
Q
Quleaf 已提交
337
      "sample 5 :\n",
Q
Quleaf 已提交
338
      "  trace distance is 0.18689\n",
Q
Quleaf 已提交
339
      "sample 6 :\n",
Q
Quleaf 已提交
340
      "  trace distance is 0.18345\n",
Q
Quleaf 已提交
341
      "sample 7 :\n",
Q
Quleaf 已提交
342
      "  trace distance is 0.22967\n",
Q
Quleaf 已提交
343
      "sample 8 :\n",
Q
Quleaf 已提交
344
      "  trace distance is 0.22579\n",
Q
Quleaf 已提交
345
      "sample 9 :\n",
Q
Quleaf 已提交
346
      "  trace distance is 0.21692\n",
Q
Quleaf 已提交
347
      "sample 10 :\n",
Q
Quleaf 已提交
348
      "  trace distance is 0.25945\n"
Q
Quleaf 已提交
349 350 351 352 353 354 355
     ]
    }
   ],
   "source": [
    "s = 10 # Set the number of randomly generated density matrices\n",
    "\n",
    "for i in range(s):\n",
Q
Quleaf 已提交
356 357 358 359
    "    paddle_quantum.set_backend('density_matrix')  # change to density matrix mode     \n",
    "    sampled = random_state(3) # randomly generated density matrix of 3 qubits sampled\n",
    "    simulated_output = paddle.matmul(paddle.matmul(cir.unitary_matrix(), sampled.data), dagger(cir.unitary_matrix())) # sampled after approximate unitary evolution\n",
    "    real_output = paddle.matmul(paddle.matmul(paddle.to_tensor(U_0), sampled.data), dagger(paddle.to_tensor(U_0))) # sampled after target unitary evolution\n",
Q
Quleaf 已提交
360
    "    print('sample', i + 1, ':')\n",
Q
Quleaf 已提交
361 362
    "    A = simulated_output.numpy() - real_output.numpy()\n",
    "    d = 1 / 2 * np.sum(np.abs(np.linalg.eigvals(A)))\n",
Q
Quleaf 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    "    print('  trace distance is', np.around(d, decimals=5)) # print trace distance\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "567a77a3",
   "metadata": {},
   "source": [
    "We can see that the trace distance of each sample after the evolution of $U$ and $V$ is close to 0, which means the $V$ approximates $U$ very well."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2f3d7d5",
   "metadata": {},
   "source": [
    "## The Second Scenario - Circuit Form of $U$\n",
    "\n",
    "In the second case, we suppose the $U$ needs approximation is given in the form of a black-box, and we only have access to its input and output. As a results, the fidelity can no longer be computed directly. Instead, it needs to be evaluate by a circuit.\n",
    "Next we will show how to calculate fidelity with a quantum circuit.\n",
    "\n",
    "### Calculate fidelity with a quantum circuit"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a62ac66",
   "metadata": {},
   "source": [
    "The QNN of QAQC that needs in a large quantum circuit. The whole circuit is shown below, where $U$ denotes the unitary operator to be approximated, and $V^{\\dagger}$ is the QNN we want to train. Here we use the Toffoli gate as the black-box.\n",
    "\n",
    "![circuit](./figures/vqcc-fig-circuit.png \"Figure 1: The circuit of the QAQC [1].\")\n",
    "<center>Figure 1: The circuit of the QAQC [1].</center>\n",
    "\n",
    "The circuit requires a total of $2n$ qubits, and we call the first $n$ qubits system $A$ and the last $n$ qubits system $B$. The whole circuit involves the following three steps:\n",
    "\n",
    "- First creating a maximally entangled state between $A$ and $B$ by performing Hadamard and CNOT gates.\n",
    "- Then acting with $U$ on system $A$ and with $V^{\\dagger}$ on system $B$ ($V^{\\dagger}$ is the complex conjugate of $V$), note that these two gates are performed in parallel.\n",
    "- Finally measuring in the bell basis(i.e., undoing the CNOTS and Hadamards then measuring in the standard basis).\n",
    "\n",
    "After the above operation, the probability of the full zero state obtained by the measurement is $\\frac{1}{d^2}|\\text{tr}(V^{\\dagger} U)|^2$. For a detailed explanation of Figure 1 please refer to the literature [1]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44f2ea35",
   "metadata": {},
   "source": [
    "Here we use the same QNN that we used in the first case and use the Toffoli gate as the black-bx. \n",
    "\n",
    "Next we will implement variational quantum circuit compiling in Paddle Quantum as follows:"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
418
   "execution_count": 8,
Q
Quleaf 已提交
419 420 421 422 423 424 425
   "id": "d6852694",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 3 # Number of qubits\n",
    "\n",
    "# Construct the total quantum circuit\n",
Q
Quleaf 已提交
426
    "def qcircuit(n, D):\n",
Q
Quleaf 已提交
427 428
    "    \n",
    "    # Initialize the circuit of 2n qubits \n",
Q
Quleaf 已提交
429 430
    "    cir = Circuit(2 * n)\n",
    "    cir.h(list(range(n)))\n",
Q
Quleaf 已提交
431 432
    "    for i in range(n):\n",
    "        cir.cnot([i, n + i])\n",
Q
Quleaf 已提交
433
    "\n",
Q
Quleaf 已提交
434
    "    # Construct the circuit of U\n",
Q
Quleaf 已提交
435
    "    cir.toffoli([0, 1, 2])\n",
Q
Quleaf 已提交
436 437
    "\n",
    "    # Construct QNN\n",
Q
Quleaf 已提交
438
    "    cir.complex_entangled_layer([3, 4, 5], D)\n",
Q
Quleaf 已提交
439 440 441
    "    \n",
    "    for l in range(n):\n",
    "        cir.cnot([n - 1 - l, 2 * n - 1 - l])\n",
Q
Quleaf 已提交
442
    "    cir.h(list(range(n)))\n",
Q
Quleaf 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    " \n",
    "    return cir"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0d141c7",
   "metadata": {},
   "source": [
    "### Setting up the training model - loss function\n",
    "\n",
    "Next we define the loss function $C(U,V) = 1-\\frac{1}{d^2}|\\text{tr}(V^{\\dagger} U)|^2$ and training parameters in order to optimize the QNN. "
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
459
   "execution_count": 9,
Q
Quleaf 已提交
460 461 462 463
   "id": "7ee10c61",
   "metadata": {},
   "outputs": [],
   "source": [
Q
Quleaf 已提交
464 465 466 467 468 469 470 471
    "# Define loss function\n",
    "def loss_func(self):\n",
    "    paddle_quantum.set_backend('density_matrix')      \n",
    "    # Output the density matrix rho of the quantum state after the circuit\n",
    "    init_state = zero_state(2 * n)\n",
    "    rho = cir(init_state)\n",
    "    # Define loss function\n",
    "    loss = 1 - paddle.real(rho.data[0][0])\n",
Q
Quleaf 已提交
472
    "\n",
Q
Quleaf 已提交
473
    "    return loss"
Q
Quleaf 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bfa7b24",
   "metadata": {},
   "source": [
    "### Setting up the training model - model parameters\n",
    "\n",
    "Here we set the learning rate to 0.1 and the number of iterations to 120. The reader can also adjust them to observe the impact on the training effect."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
488
   "execution_count": 10,
Q
Quleaf 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
   "id": "280e2858",
   "metadata": {},
   "outputs": [],
   "source": [
    "D = 5  # Set the depth of QNN\n",
    "LR = 0.1  # Set the learning rate\n",
    "ITR = 120   # Set the number of optimization iterations"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb400510",
   "metadata": {},
   "source": [
    "### Training\n",
    "\n",
    "Then we commence the training process with an Adam optimizer."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
510
   "execution_count": 11,
Q
Quleaf 已提交
511 512 513 514 515 516 517
   "id": "77919a34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
518 519 520 521 522 523
      "iter: 20 loss: 0.4525\n",
      "iter: 40 loss: 0.1755\n",
      "iter: 60 loss: 0.0066\n",
      "iter: 80 loss: 0.0021\n",
      "iter: 100 loss: 0.0005\n",
      "iter: 120 loss: 0.0001\n",
Q
Quleaf 已提交
524
      "\n",
Q
Quleaf 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538
      "The trained circuit:\n",
      "Approximate circuit of U with circuit form input:\n",
      " --H----*--------------*-------------------------------------------------------------------------------------------------------------*----H--\n",
      "       |              |                                                                                                             |       \n",
      "--H----|----*---------*--------------------------------------------------------------------------------------------------------*----|----H--\n",
      "       |    |         |                                                                                                        |    |       \n",
      "--H----|----|----*----X---------------------------------------------------------------------------------------------------*----|----|----H--\n",
      "       |    |    |                                                                                                        |    |    |       \n",
      "-------x----|----|----U----*---------x----U----*---------x----U----*---------x----U----*---------x----U----*---------x----|----|----x-------\n",
      "            |    |         |         |         |         |         |         |         |         |         |         |    |    |            \n",
      "------------x----|----U----x----*----|----U----x----*----|----U----x----*----|----U----x----*----|----U----x----*----|----|----x------------\n",
      "                 |              |    |              |    |              |    |              |    |              |    |    |                 \n",
      "-----------------x----U---------x----*----U---------x----*----U---------x----*----U---------x----*----U---------x----*----x-----------------\n",
      "                                                                                                                                            \n"
Q
Quleaf 已提交
539 540 541 542
     ]
    }
   ],
   "source": [
Q
Quleaf 已提交
543
    "cir = qcircuit(n, D)\n",
Q
Quleaf 已提交
544
    "# Use Adam optimizer for better performance\n",
Q
Quleaf 已提交
545
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=cir.parameters())\n",
Q
Quleaf 已提交
546 547 548
    "\n",
    "# Optimization loop\n",
    "for itr in range(1, ITR + 1):\n",
Q
Quleaf 已提交
549
    "    loss = loss_func(cir)\n",
Q
Quleaf 已提交
550 551 552 553 554 555 556 557
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # Print training results\n",
    "    if itr % 20 == 0:\n",
    "        print(\"iter:\",itr,\"loss:\",\"%.4f\" % loss.numpy())\n",
    "    if itr == ITR:\n",
Q
Quleaf 已提交
558 559
    "        print(\"\\nThe trained circuit:\")\n",
    "        print('Approximate circuit of U with circuit form input:\\n', cir)\n"
Q
Quleaf 已提交
560 561 562 563
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
564
   "execution_count": 12,
Q
Quleaf 已提交
565 566 567 568 569
   "id": "777ca58e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Storage optimized parameters\n",
Q
Quleaf 已提交
570
    "theta_opt = cir.parameters()"
Q
Quleaf 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c65d72dd",
   "metadata": {},
   "source": [
    "In this case, we construct a one-layer QNN and train it with a Adam optimizer. After around 100 iterations, the loss function reaches 0."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "040bf7d5",
   "metadata": {},
   "source": [
    "### Validation of results\n",
    "\n",
    "Similar to before, we also randomly select 10 density matrices, which are evolved by the target unitary operator $U$ and the approximate unitary operator $V$. Then calculate the trace distance between the real output `real_output` and the approximate output `simulated_output`. The smaller the trace distance, the better the approximation."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
593
   "execution_count": 13,
Q
Quleaf 已提交
594 595 596 597 598 599 600 601 602 603
   "id": "0c339ca3",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample 1 :\n",
Q
Quleaf 已提交
604
      "  trace distance is 0.20575\n",
Q
Quleaf 已提交
605
      "sample 2 :\n",
Q
Quleaf 已提交
606
      "  trace distance is 0.2397\n",
Q
Quleaf 已提交
607
      "sample 3 :\n",
Q
Quleaf 已提交
608
      "  trace distance is 0.23174\n",
Q
Quleaf 已提交
609
      "sample 4 :\n",
Q
Quleaf 已提交
610
      "  trace distance is 0.15452\n",
Q
Quleaf 已提交
611
      "sample 5 :\n",
Q
Quleaf 已提交
612
      "  trace distance is 0.2846\n",
Q
Quleaf 已提交
613
      "sample 6 :\n",
Q
Quleaf 已提交
614
      "  trace distance is 0.2477\n",
Q
Quleaf 已提交
615
      "sample 7 :\n",
Q
Quleaf 已提交
616
      "  trace distance is 0.21579\n",
Q
Quleaf 已提交
617
      "sample 8 :\n",
Q
Quleaf 已提交
618
      "  trace distance is 0.1746\n",
Q
Quleaf 已提交
619
      "sample 9 :\n",
Q
Quleaf 已提交
620
      "  trace distance is 0.18502\n",
Q
Quleaf 已提交
621
      "sample 10 :\n",
Q
Quleaf 已提交
622
      "  trace distance is 0.32651\n"
Q
Quleaf 已提交
623 624 625 626 627 628
     ]
    }
   ],
   "source": [
    "s = 10 # Set the number of randomly generated density matrices\n",
    "for i in range(s):\n",
Q
Quleaf 已提交
629 630
    "    paddle_quantum.set_backend('density_matrix')  # change to density matrix mode    \n",
    "    sampled = random_state(3) # randomly generated density matrix of 4 qubits sampled\n",
Q
Quleaf 已提交
631 632
    "\n",
    "    # Construct the circuit of target unitary\n",
Q
Quleaf 已提交
633 634
    "    cir_1 = Circuit(3)\n",
    "    cir.toffoli([0, 1, 2])\n",
Q
Quleaf 已提交
635
    "    # sampled after target unitary evolution\n",
Q
Quleaf 已提交
636
    "    real_output = paddle.matmul(paddle.matmul(cir_1.unitary_matrix(), sampled.data), dagger(cir_1.unitary_matrix()))\n",
Q
Quleaf 已提交
637 638
    "\n",
    "    # Construct the circuit of approximate unitary\n",
Q
Quleaf 已提交
639 640
    "    cir_2 = Circuit(3)\n",
    "    for j in range(D):\n",
Q
Quleaf 已提交
641
    "        cir_2.u3(qubits_idx='full', param=theta_opt[j])\n",
Q
Quleaf 已提交
642
    "        cir_2.cnot(qubits_idx='cycle')\n",
Q
Quleaf 已提交
643
    "    # sampled after approximate unitary evolution\n",
Q
Quleaf 已提交
644
    "    simulated_output = paddle.matmul(paddle.matmul(cir_2.unitary_matrix(), sampled.data), dagger(cir_2.unitary_matrix()))\n",
Q
Quleaf 已提交
645
    "\n",
Q
Quleaf 已提交
646 647
    "    A = simulated_output.numpy() - real_output.numpy()\n",
    "    d = 1 / 2 * np.sum(np.abs(np.linalg.eigvals(A)))\n",
Q
Quleaf 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    "    print('sample', i + 1, ':')\n",
    "    print('  trace distance is',  np.around(d, decimals=5)) # print trace distance"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8b3d6c4",
   "metadata": {},
   "source": [
    "We can see that the trace distance of each sample after the evolution of $U$ and $V$ is close to 0, which means the $V$ approximates $U$ very well."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afe8ea7c",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "In this tutorial, the variational quantum circuit compiling is carried out from the input form of the target unitary operator as a matrix and as a circuit. The results of the quantum compilation are demonstrated by two simple examples using Paddle Quantum. Then the approximate effect is checked by the trace distance of the quantum states after the evolution of the target unitary and the approximate unitary respectively. Finally the results in Paddle Quantum show that the quantum compilation is good."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc610a2f",
   "metadata": {},
   "source": [
    "_______\n",
    "\n",
    "## References"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62dd936d",
   "metadata": {},
   "source": [
    "[1] Khatri, Sumeet, et al. \"Quantum-assisted quantum compiling.\" [Quantum 3 (2019): 140](https://quantum-journal.org/papers/q-2019-05-13-140/)."
   ]
  }
 ],
 "metadata": {
Q
Quleaf 已提交
690 691 692
  "interpreter": {
   "hash": "f7cfecff1ef1940b21a48efa1b88278bb096bd916f13c2df11af4810c38b47e1"
  },
Q
Quleaf 已提交
693
  "kernelspec": {
Q
Quleaf 已提交
694
   "display_name": "Python 3.8.0 ('pq')",
Q
Quleaf 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
Q
Quleaf 已提交
708
   "version": "3.8.13"
Q
Quleaf 已提交
709 710 711 712 713
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}