VQSD_CN.ipynb 12.2 KB
Notebook
Newer Older
Q
Quleaf 已提交
1 2
{
 "cells": [
Q
Quleaf 已提交
3 4 5 6
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
7 8
    "# 变分量子态对角化算法\n",
    "\n",
Q
Quleaf 已提交
9 10 11 12 13 14 15
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
16
    "## 概览\n",
Q
Quleaf 已提交
17
    "\n",
Q
Quleaf 已提交
18
    "- 在本案例中,我们将通过 Paddle Quantum 训练量子神经网络来完成量子态的对角化\n",
Q
Quleaf 已提交
19
    "\n",
Q
Quleaf 已提交
20
    "- 首先,让我们通过下面几行代码引入必要的 library 和 package。"
Q
Quleaf 已提交
21 22 23 24
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
25
   "execution_count": 1,
Q
Quleaf 已提交
26
   "metadata": {
Q
Quleaf 已提交
27
    "ExecuteTime": {
Q
Quleaf 已提交
28 29
     "end_time": "2021-04-30T09:17:03.603558Z",
     "start_time": "2021-04-30T09:17:00.931471Z"
Q
Quleaf 已提交
30 31 32 33 34 35
    }
   },
   "outputs": [],
   "source": [
    "import numpy\n",
    "from numpy import diag\n",
Q
Quleaf 已提交
36
    "from numpy import pi as PI\n",
Q
Quleaf 已提交
37
    "import scipy\n",
Q
Quleaf 已提交
38 39 40
    "import scipy.stats\n",
    "import paddle\n",
    "from paddle import matmul, trace\n",
Q
Quleaf 已提交
41
    "from paddle_quantum.circuit import UAnsatz\n",
Q
Quleaf 已提交
42
    "from paddle_quantum.utils import dagger"
Q
Quleaf 已提交
43 44 45 46
   ]
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
47
   "metadata": {},
Q
Quleaf 已提交
48 49
   "source": [
    "## 背景\n",
Q
Quleaf 已提交
50
    "量子态对角化算法(variational quantum state diagonalization, VQSD)[1-3] 目标是输出一个量子态的本征谱,即其所有本征值。求解量子态的本征值在量子计算中有着诸多应用,比如可以用于计算保真度和冯诺依曼熵,也可以用于主成分分析。\n",
51
    "- 量子态通常是一个混合态,表示如下 $\\rho_{\\text{mixed}} = \\sum_i P_i |\\psi_i\\rangle\\langle\\psi_i|$\n",
Q
Quleaf 已提交
52
    "- 作为一个简单的例子,我们考虑一个 2 量子位的量子态,它的本征谱为 $(0.5, 0.3, 0.1, 0.1)$,我们先通过随机作用一个酉矩阵来生成具有这样本征谱的随机量子态。"
Q
Quleaf 已提交
53 54 55 56
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
57
   "execution_count": 2,
Q
Quleaf 已提交
58
   "metadata": {
Q
Quleaf 已提交
59
    "ExecuteTime": {
Q
Quleaf 已提交
60 61
     "end_time": "2021-04-30T09:17:03.622120Z",
     "start_time": "2021-04-30T09:17:03.609542Z"
Q
Quleaf 已提交
62 63
    }
   },
Q
Quleaf 已提交
64 65 66 67 68
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
69 70
      "[[ 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 已提交
71 72
      " [-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"
Q
Quleaf 已提交
73 74 75
     ]
    }
   ],
Q
Quleaf 已提交
76
   "source": [
Q
Quleaf 已提交
77
    "scipy.random.seed(13)                  # 固定随机种子,方便复现结果\n",
Q
Quleaf 已提交
78 79
    "V = scipy.stats.unitary_group.rvs(4)   # 随机生成一个酉矩阵\n",
    "D = diag([0.5, 0.3, 0.1, 0.1])         # 输入目标态 rho 的谱\n",
Q
Quleaf 已提交
80
    "V_H = V.conj().T \n",
Q
Quleaf 已提交
81 82
    "rho = V @ D @ V_H                      # 通过逆向的谱分解生成 rho\n",
    "print(numpy.around(rho, 4))            # 打印量子态 rho"
Q
Quleaf 已提交
83 84 85 86 87 88 89
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 搭建量子神经网络\n",
Q
Quleaf 已提交
90
    "- 在这个案例中,我们将通过训练量子神经网络 QNN(也可以理解为参数化量子电路)来学习量子态的本征谱。这里,我们提供一个预设的 2 量子位量子电路。\n",
Q
Quleaf 已提交
91
    "\n",
Q
Quleaf 已提交
92
    "- 我们预设一些该参数化电路的参数,比如宽度为 2 量子位。\n",
Q
Quleaf 已提交
93
    "\n",
Q
Quleaf 已提交
94
    "- 初始化其中的变量参数,${\\bf{\\theta }}$ 代表我们量子神经网络中的参数组成的向量。"
Q
Quleaf 已提交
95 96 97 98
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
99
   "execution_count": 3,
Q
Quleaf 已提交
100
   "metadata": {
Q
Quleaf 已提交
101
    "ExecuteTime": {
Q
Quleaf 已提交
102 103
     "end_time": "2021-04-30T09:17:03.646986Z",
     "start_time": "2021-04-30T09:17:03.637134Z"
Q
Quleaf 已提交
104 105 106 107
    }
   },
   "outputs": [],
   "source": [
Q
Quleaf 已提交
108 109 110
    "N = 2            # 量子神经网络的宽度\n",
    "SEED = 14        # 固定随机种子\n",
    "THETA_SIZE = 15  # 量子神经网络中参数的数量\n",
Q
Quleaf 已提交
111 112 113
    "\n",
    "def U_theta(theta, N):\n",
    "    \"\"\"\n",
Q
Quleaf 已提交
114
    "    Quantum Neural Network\n",
Q
Quleaf 已提交
115
    "    \"\"\"\n",
Q
Quleaf 已提交
116 117
    "    \n",
    "    # 按照量子比特数量/网络宽度初始化量子神经网络\n",
Q
Quleaf 已提交
118
    "    cir = UAnsatz(N)\n",
Q
Quleaf 已提交
119
    "    # 调用内置的量子神经网络模板\n",
Q
Quleaf 已提交
120
    "    cir.universal_2_qubit_gate(theta, [0, 1])\n",
Q
Quleaf 已提交
121 122
    "    # 返回量子神经网络的电路\n",
    "    return cir"
Q
Quleaf 已提交
123 124 125 126
   ]
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
127
   "metadata": {},
Q
Quleaf 已提交
128
   "source": [
Q
Quleaf 已提交
129
    "## 配置训练模型——损失函数\n",
Q
Quleaf 已提交
130
    "- 现在我们已经有了数据和量子神经网络的架构,我们将进一步定义训练参数、模型和损失函数。\n",
Q
Quleaf 已提交
131 132
    "- 通过作用量子神经网络 $U(\\theta)$ 在量子态 $\\rho$ 后得到的量子态记为 $\\tilde\\rho$,我们设定损失函数为 $\\tilde\\rho$ 与用来标记的量子态 $\\sigma=0.1 |00\\rangle\\langle 00| + 0.2 |01\\rangle \\langle 01| + 0.3 |10\\rangle \\langle10| + 0.4 |11 \\rangle\\langle 11|$ 的内积。\n",
    "- 具体的,设定损失函数为 $\\mathcal{L}(\\boldsymbol{\\theta})  = \\text{Tr}(\\tilde\\rho\\sigma)$。"
Q
Quleaf 已提交
133 134 135 136
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
137
   "execution_count": 4,
Q
Quleaf 已提交
138
   "metadata": {
Q
Quleaf 已提交
139
    "ExecuteTime": {
Q
Quleaf 已提交
140 141
     "end_time": "2021-04-30T09:17:03.676479Z",
     "start_time": "2021-04-30T09:17:03.660557Z"
Q
Quleaf 已提交
142 143 144 145
    }
   },
   "outputs": [],
   "source": [
Q
Quleaf 已提交
146 147
    "# 输入用来标记的量子态sigma\n",
    "sigma = diag([0.1, 0.2, 0.3, 0.4]).astype('complex128') \n",
Q
Quleaf 已提交
148
    "\n",
Q
Quleaf 已提交
149
    "class Net(paddle.nn.Layer):\n",
Q
Quleaf 已提交
150 151 152 153
    "    \"\"\"\n",
    "    Construct the model net\n",
    "    \"\"\"\n",
    "\n",
Q
Quleaf 已提交
154
    "    def __init__(self, shape, rho, sigma, dtype='float64'):\n",
Q
Quleaf 已提交
155
    "        super(Net, self).__init__()\n",
Q
Quleaf 已提交
156
    "        \n",
Q
Quleaf 已提交
157 158
    "        \n",
    "        \n",
Q
Quleaf 已提交
159 160 161
    "        # 将 numpy.ndarray 转换成 Paddle 中支持的 Tensor\n",
    "        self.rho = paddle.to_tensor(rho)\n",
    "        self.sigma = paddle.to_tensor(sigma)\n",
Q
Quleaf 已提交
162 163
    "        \n",
    "        # 初始化 theta 参数列表,并用 [0, 2*pi] 的均匀分布来填充初始值\n",
Q
Quleaf 已提交
164 165 166
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2*PI),\n",
    "                                           dtype=dtype, is_bias=False)\n",
Q
Quleaf 已提交
167
    "\n",
Q
Quleaf 已提交
168
    "    # 定义损失函数和前向传播机制\n",
Q
Quleaf 已提交
169
    "    def forward(self, N):\n",
Q
Quleaf 已提交
170 171
    "        \n",
    "        # 施加量子神经网络\n",
Q
Quleaf 已提交
172 173 174
    "        cir = U_theta(self.theta, N)\n",
    "        U = cir.U\n",
    "        \n",
Q
Quleaf 已提交
175
    "        # rho_tilde 是将 U 作用在 rho 后得到的量子态 U*rho*U^dagger \n",
Q
Quleaf 已提交
176
    "        rho_tilde = matmul(matmul(U, self.rho), dagger(U))\n",
Q
Quleaf 已提交
177
    "\n",
Q
Quleaf 已提交
178
    "        # 计算损失函数\n",
Q
Quleaf 已提交
179 180
    "        loss = trace(matmul(self.sigma, rho_tilde))\n",
    "\n",
Q
Quleaf 已提交
181
    "        return paddle.real(loss), rho_tilde, cir"
Q
Quleaf 已提交
182 183 184 185 186 187
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
188
    "## 配置训练模型——模型参数\n",
Q
Quleaf 已提交
189
    "\n",
Q
Quleaf 已提交
190
    "在进行量子神经网络的训练之前,我们还需要进行一些训练的超参数设置,主要是学习速率 (learning rate, LR)和迭代次数(iteration, ITR)。这里我们设定学习速率为 0.1,迭代次数为 50 次。读者不妨自行调整来直观感受下超参数调整对训练效果的影响。"
Q
Quleaf 已提交
191 192 193 194
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
195
   "execution_count": 5,
Q
Quleaf 已提交
196
   "metadata": {
Q
Quleaf 已提交
197
    "ExecuteTime": {
Q
Quleaf 已提交
198 199
     "end_time": "2021-04-30T09:17:04.114466Z",
     "start_time": "2021-04-30T09:17:04.099242Z"
Q
Quleaf 已提交
200 201 202 203
    }
   },
   "outputs": [],
   "source": [
Q
Quleaf 已提交
204 205
    "ITR = 50  # 设置训练的总的迭代次数\n",
    "LR = 0.1  # 设置学习速率"
Q
Quleaf 已提交
206 207 208 209 210 211 212 213
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 进行训练\n",
    "\n",
Q
Quleaf 已提交
214
    "- 当训练模型的各项参数都设置完成后,我们将数据转化为 Paddle 中的张量,进而进行量子神经网络的训练。\n",
Q
Quleaf 已提交
215
    "- 过程中我们用的是 Adam Optimizer,也可以调用 Paddle 中提供的其他优化器。\n",
Q
Quleaf 已提交
216 217 218 219 220
    "- 我们将训练过程中的结果依次输出。"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
221
   "execution_count": 6,
Q
Quleaf 已提交
222
   "metadata": {
Q
Quleaf 已提交
223
    "ExecuteTime": {
Q
Quleaf 已提交
224 225
     "end_time": "2021-04-30T09:17:10.042819Z",
     "start_time": "2021-04-30T09:17:08.580527Z"
Q
Quleaf 已提交
226 227
    }
   },
Q
Quleaf 已提交
228 229 230 231 232
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
233 234 235 236
      "iter: 0 loss: 0.2494\n",
      "iter: 10 loss: 0.1958\n",
      "iter: 20 loss: 0.1843\n",
      "iter: 30 loss: 0.1816\n",
Q
Quleaf 已提交
237 238 239 240 241 242 243
      "iter: 40 loss: 0.1805\n",
      "\n",
      "训练后的电路:\n",
      "--U----X----Rz(1.489)----*-----------------X----U--\n",
      "       |                 |                 |       \n",
      "--U----*----Ry(1.367)----X----Ry(2.749)----*----U--\n",
      "                                                   \n"
Q
Quleaf 已提交
244 245 246
     ]
    }
   ],
Q
Quleaf 已提交
247
   "source": [
Q
Quleaf 已提交
248
    "paddle.seed(SEED)\n",
Q
Quleaf 已提交
249
    "\n",
Q
Quleaf 已提交
250 251 252 253 254 255 256 257 258 259 260
    "# 确定网络的参数维度\n",
    "net = Net(shape=[THETA_SIZE], rho=rho, sigma=sigma)\n",
    "\n",
    "# 一般来说,我们利用 Adam 优化器来获得相对好的收敛\n",
    "# 当然你可以改成 SGD 或者是 RMS prop.\n",
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 前向传播计算损失函数并返回估计的能谱\n",
Q
Quleaf 已提交
261
    "    loss, rho_tilde, cir = net(N)\n",
Q
Quleaf 已提交
262 263 264 265 266 267 268 269 270
    "    rho_tilde_np = rho_tilde.numpy()\n",
    "\n",
    "    # 反向传播极小化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 打印训练结果\n",
    "    if itr % 10 == 0:\n",
Q
Quleaf 已提交
271 272 273 274
    "        print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])\n",
    "    if itr == ITR - 1:\n",
    "        print(\"\\n训练后的电路:\")\n",
    "        print(cir)"
Q
Quleaf 已提交
275 276 277 278 279 280 281
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
Q
Quleaf 已提交
282 283
    "\n",
    "根据上面训练得到的结果,通过大概50次迭代,我们就比较好的完成了对角化。我们可以通过打印 $\\tilde{\\rho} = U(\\boldsymbol{\\theta})\\rho U^\\dagger(\\boldsymbol{\\theta})$ 的来验证谱分解的效果。特别的,我们可以验证它的对角线与目标谱非常接近。"
Q
Quleaf 已提交
284 285 286 287
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
288
   "execution_count": 7,
Q
Quleaf 已提交
289
   "metadata": {
Q
Quleaf 已提交
290
    "ExecuteTime": {
Q
Quleaf 已提交
291 292
     "end_time": "2021-04-30T09:17:13.536415Z",
     "start_time": "2021-04-30T09:17:13.527756Z"
Q
Quleaf 已提交
293 294
    }
   },
Q
Quleaf 已提交
295 296 297 298 299
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
300
      "The estimated spectrum is: [0.49938069 0.29916354 0.10103808 0.10041768]\n",
Q
Quleaf 已提交
301 302 303 304
      "The target spectrum is: [0.5 0.3 0.1 0.1]\n"
     ]
    }
   ],
Q
Quleaf 已提交
305 306 307 308 309 310 311
   "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",
Q
Quleaf 已提交
312
   "metadata": {},
Q
Quleaf 已提交
313
   "source": [
Q
Quleaf 已提交
314 315
    "_______\n",
    "\n",
Q
Quleaf 已提交
316
    "## 参考文献\n",
Q
Quleaf 已提交
317
    "\n",
Q
Quleaf 已提交
318
    "[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",
Q
Quleaf 已提交
319
    "\n",
Q
Quleaf 已提交
320
    "[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",
Q
Quleaf 已提交
321
    "\n",
Q
Quleaf 已提交
322
    "[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)"
Q
Quleaf 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
   ]
  }
 ],
 "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 已提交
342
   "version": "3.7.0"
Q
Quleaf 已提交
343
  },
Q
Quleaf 已提交
344 345 346 347 348 349 350 351 352 353 354 355
  "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
Q
Quleaf 已提交
356 357 358
  }
 },
 "nbformat": 4,
Q
Quleaf 已提交
359
 "nbformat_minor": 4
Q
Quleaf 已提交
360
}