VQSD_EN.ipynb 11.6 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Variational Quantum State Diagonalization \n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>\n",
    "\n",
    "## Overview\n",
    "\n",
    "- In this tutorial, we will train a quantum neural network (QNN) through Paddle Quantum to complete the diagonalization of quantum states.\n",
    "\n",
    "- First, import the following packages."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
20
   "execution_count": 8,
Q
Quleaf 已提交
21 22
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
23 24
     "end_time": "2021-04-30T09:16:42.117977Z",
     "start_time": "2021-04-30T09:16:38.578847Z"
Q
Quleaf 已提交
25 26 27 28 29 30
    }
   },
   "outputs": [],
   "source": [
    "import numpy\n",
    "from numpy import diag\n",
Q
Quleaf 已提交
31
    "from numpy import pi as PI\n",
Q
Quleaf 已提交
32
    "import scipy\n",
Q
Quleaf 已提交
33 34 35
    "import scipy.stats\n",
    "import paddle\n",
    "from paddle import matmul, trace\n",
Q
Quleaf 已提交
36 37 38 39
    "import paddle_quantum\n",
    "from paddle_quantum import intrinsic\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.linalg import dagger"
Q
Quleaf 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Background\n",
    "The Variational Quantum State Diagonalization [1-3] aims to output the eigen-spectrum (eigenvalues) of a quantum state. Solving the eigenvalues ​​of quantum states has many applications in quantum computation, such as calculating fidelity and Von Neumann entropy.\n",
    "\n",
    "- Quantum state is usually a mixed state which can be expressed as follows: \n",
    "\n",
    "$$\n",
    "\\rho_{\\text{mixed}} = \\sum_i P_i |\\psi_i\\rangle\\langle\\psi_i|. \\tag{1}\n",
    "$$\n",
    "\n",
    "- As an example, we consider a mixed 2-qubit quantum state with eigen-spectrum $[0.5, 0.3, 0.1, 0.1]$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
63 64
     "end_time": "2021-04-30T09:16:42.139676Z",
     "start_time": "2021-04-30T09:16:42.121581Z"
Q
Quleaf 已提交
65 66 67 68 69 70 71
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
72 73
      "[[ 0.2569-0.j     -0.012 +0.0435j -0.0492-0.0055j -0.0548+0.0682j]\n",
      " [-0.012 -0.0435j  0.2959+0.j      0.1061-0.0713j -0.0392-0.0971j]\n",
Q
Quleaf 已提交
74 75 76 77 78 79 80
      " [-0.0492+0.0055j  0.1061+0.0713j  0.2145-0.j      0.0294-0.1132j]\n",
      " [-0.0548-0.0682j -0.0392+0.0971j  0.0294+0.1132j  0.2327+0.j    ]]\n"
     ]
    }
   ],
   "source": [
    "# Fixed random seed\n",
Q
Quleaf 已提交
81
    "numpy.random.seed(13) \n",
Q
Quleaf 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    "V = scipy.stats.unitary_group.rvs(4)  # Randomly generate a unitary matrix\n",
    "D = diag([0.5, 0.3, 0.1, 0.1])        # Input the spectrum of the target state rho\n",
    "V_H = V.conj().T                      # Conjugate transpose operation\n",
    "rho = V @ D @ V_H                     # Generate rho by inverse spectral decomposition\n",
    "print(numpy.around(rho, 4))           # Print quantum state rho"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building a quantum neural network\n",
    "\n",
    "- In this case, we will learn the eigen-spectrum of quantum state $\\rho$ defined above by training a QNN (also known as the parameterized quantum circuit). Here, we provide a predefined 2-qubit quantum circuit.\n",
    "\n",
    "- One can randomly initialize the QNN parameters ${\\bf{\\vec{\\theta }}}$ containing 15 parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
105 106
     "end_time": "2021-04-30T09:16:42.152252Z",
     "start_time": "2021-04-30T09:16:42.144220Z"
Q
Quleaf 已提交
107 108 109 110 111 112 113 114
    }
   },
   "outputs": [],
   "source": [
    "N = 2           # The width of the quantum neural network\n",
    "SEED = 14       # Fixed random seed\n",
    "THETA_SIZE = 15 # The number of parameters in the quantum neural network\n",
    "\n",
Q
Quleaf 已提交
115
    "def U_theta(N: int) -> Circuit:\n",
Q
Quleaf 已提交
116 117 118 119
    "    \"\"\"\n",
    "    Quantum Neural Network\n",
    "    \"\"\"\n",
    "    # Initialize the quantum neural network according to the number of qubits/network width\n",
Q
Quleaf 已提交
120
    "    cir = Circuit(N)\n",
Q
Quleaf 已提交
121
    "    # Call the built-in quantum neural network template\n",
Q
Quleaf 已提交
122
    "    cir.universal_two_qubits([0, 1])\n",
Q
Quleaf 已提交
123 124
    "    # Return the circuit of the quantum neural network\n",
    "    return cir"
Q
Quleaf 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training model and loss function\n",
    "\n",
    "- After setting up the quantum state and the QNN architecture, we will further define the parameters to be trained, loss function, and optimization methods. \n",
    "- The quantum state obtained by acting the quantum neural network $U(\\theta)$ on $\\rho$  is denoted by $\\tilde\\rho$, and we set the loss function to be the inner product of the quantum state $\\sigma$ and $\\tilde\\rho$ where\n",
    "\n",
    "$$\n",
    "\\sigma=0.1 |00\\rangle\\langle 00| + 0.2 |01\\rangle \\langle 01| + 0.3 |10\\rangle \\langle10| + 0.4 |11 \\rangle\\langle 11|, \\tag{2}\n",
    "$$\n",
    "\n",
    "- In specific, the loss function is defined as the state overlap \n",
    "\n",
    "$$\n",
    "\\mathcal{L}(\\boldsymbol{\\theta}) = \\text{Tr}(\\tilde\\rho\\sigma). \\tag{3}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
152 153
     "end_time": "2021-04-30T09:16:42.172611Z",
     "start_time": "2021-04-30T09:16:42.155186Z"
Q
Quleaf 已提交
154 155 156 157 158
    }
   },
   "outputs": [],
   "source": [
    "# Enter the quantum state sigma \n",
Q
Quleaf 已提交
159
    "sigma = diag([0.1, 0.2, 0.3, 0.4])\n",
Q
Quleaf 已提交
160
    "\n",
Q
Quleaf 已提交
161
    "class Net(paddle.nn.Layer):\n",
Q
Quleaf 已提交
162 163 164 165
    "    \"\"\"\n",
    "    Construct the model net\n",
    "    \"\"\"\n",
    "\n",
Q
Quleaf 已提交
166
    "    def __init__(self, rho, sigma):\n",
Q
Quleaf 已提交
167 168
    "        super(Net, self).__init__()\n",
    "        \n",
Q
Quleaf 已提交
169
    "        # Convert Numpy array to Tensor supported in Paddle \n",
Q
Quleaf 已提交
170 171 172 173 174 175
    "        complex_dtype = paddle_quantum.get_dtype()\n",
    "        self.rho = paddle.cast(paddle.to_tensor(rho), complex_dtype)\n",
    "        self.sigma = paddle.cast(paddle.to_tensor(sigma), complex_dtype)\n",
    "\n",
    "        # Apply quantum neural network\n",
    "        self.cir = U_theta(N)\n",
Q
Quleaf 已提交
176 177 178 179 180
    "\n",
    "    # Define loss function and forward propagation mechanism\n",
    "    def forward(self, N):\n",
    "        \n",
    "        # rho_tilde is the quantum state U*rho*U^dagger \n",
Q
Quleaf 已提交
181
    "        U = self.cir.unitary_matrix()\n",
Q
Quleaf 已提交
182 183 184 185 186
    "        rho_tilde = matmul(matmul(U, self.rho), dagger(U))\n",
    "\n",
    "        # Calculate the loss function\n",
    "        loss = trace(matmul(self.sigma, rho_tilde))\n",
    "\n",
Q
Quleaf 已提交
187
    "        return paddle.real(loss), rho_tilde, self.cir"
Q
Quleaf 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hyper-parameters\n",
    "\n",
    "Before training the quantum neural network, we also need to set up several hyper-parameters, mainly the learning rate LR and the number of iterations ITR. Here we set the learning rate to be LR = 0.1 and the number of iterations to ITR = 50. One can adjust these hyper-parameters accordingly and check how they influence the training performance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
204 205
     "end_time": "2021-04-30T09:16:42.468056Z",
     "start_time": "2021-04-30T09:16:42.457529Z"
Q
Quleaf 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219
    }
   },
   "outputs": [],
   "source": [
    "ITR = 50 # Set the total number of iterations of training\n",
    "LR = 0.1 # Set the learning rate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training process\n",
    "\n",
Q
Quleaf 已提交
220
    "- After setting all the parameters of SSVQE model, we need to convert all the data into Tensor in the PaddlePaddle, and then train the quantum neural network.\n",
Q
Quleaf 已提交
221 222 223 224 225
    "- We used Adam Optimizer in training, and one can also call other optimizers provided in Paddle."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
226
   "execution_count": 9,
Q
Quleaf 已提交
227 228
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
229 230
     "end_time": "2021-04-30T09:16:50.340636Z",
     "start_time": "2021-04-30T09:16:48.778551Z"
Q
Quleaf 已提交
231 232 233 234 235 236 237
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
238
      "iter: 0 loss: 0.2494\n",
Q
Quleaf 已提交
239
      "iter: 10 loss: 0.1959\n",
Q
Quleaf 已提交
240 241
      "iter: 20 loss: 0.1843\n",
      "iter: 30 loss: 0.1816\n",
Q
Quleaf 已提交
242
      "iter: 40 loss: 0.1805\n"
Q
Quleaf 已提交
243 244 245 246
     ]
    }
   ],
   "source": [
Q
Quleaf 已提交
247 248 249
    "paddle.seed(SEED)\n",
    "\n",
    "# Determine the parameter dimension of the network\n",
Q
Quleaf 已提交
250
    "net = Net(rho=rho, sigma=sigma)\n",
Q
Quleaf 已提交
251 252 253 254 255 256 257 258 259
    "\n",
    "# We use Adam optimizer for better performance\n",
    "# One can change it to SGD or RMSprop.\n",
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
    "\n",
    "# Optimization loop\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # Forward propagation calculates the loss function and returns the estimated energy spectrum\n",
Q
Quleaf 已提交
260
    "    loss, rho_tilde, cir = net(N)\n",
Q
Quleaf 已提交
261 262 263 264 265 266 267 268 269
    "    rho_tilde_np = rho_tilde.numpy()\n",
    "\n",
    "    # Back propagation minimizes the loss function\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # Print training results\n",
    "    if itr% 10 == 0:\n",
Q
Quleaf 已提交
270
    "        print('iter:', itr,'loss:','%.4f'% loss.numpy()[0])"
Q
Quleaf 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Benchmarking\n",
    "\n",
    "After 50 iterations, we have completed the diagonalization procedure. The next step is to verify the results of spectral decomposition by printing out $\\tilde{\\rho} = U(\\boldsymbol{\\theta})\\rho U^\\dagger(\\boldsymbol{\\theta})$. One can see the results are very close to what we expect."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
Q
Quleaf 已提交
287 288
     "end_time": "2021-04-30T09:16:52.099611Z",
     "start_time": "2021-04-30T09:16:52.087176Z"
Q
Quleaf 已提交
289 290 291 292 293 294 295
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
296
      "The estimated spectrum is: [0.49938068 0.29916352 0.10103808 0.10041767]\n",
Q
Quleaf 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
      "The target spectrum is: [0.5 0.3 0.1 0.1]\n"
     ]
    }
   ],
   "source": [
    "print(\"The estimated spectrum is:\", numpy.real(numpy.diag(rho_tilde_np)))\n",
    "print(\"The target spectrum is:\", numpy.diag(D))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_______\n",
    "\n",
    "\n",
    "## References\n",
    "\n",
    "[1] Larose, R., Tikku, A., Neel-judy, É. O., Cincio, L. & Coles, P. J. Variational quantum state diagonalization. [npj Quantum Inf. (2019) doi:10.1038/s41534-019-0167-6.](https://www.nature.com/articles/s41534-019-0167-6)\n",
    "\n",
    "[2] Nakanishi, K. M., Mitarai, K. & Fujii, K. Subspace-search variational quantum eigensolver for excited states. [Phys. Rev. Res. 1, 033062 (2019).](https://journals.aps.org/prresearch/pdf/10.1103/PhysRevResearch.1.033062)\n",
    "\n",
    "[3] Cerezo, M., Sharma, K., Arrasmith, A. & Coles, P. J. Variational Quantum State Eigensolver. [arXiv:2004.01372 (2020).](https://arxiv.org/pdf/2004.01372.pdf)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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 已提交
339
   "version": "3.8.13"
Q
Quleaf 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}