You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

parameterized_quantum_circuit.ipynb 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# 参数化量子线路\n",
  8. "\n",
  9. "`Linux` `CPU` `全流程` `初级` `中级` `高级`\n",
  10. "\n",
  11. "[![](https://gitee.com/mindspore/docs/raw/master/tutorials/training/source_zh_cn/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/tutorials/training/source_zh_cn/advanced_use/parameterized_quantum_circuit.ipynb)\n",
  12. "\n",
  13. "## 概述\n",
  14. "\n",
  15. "参数化量子线路(Parameterized quantum circuit, PQC)是进行量子机器学习的一种途径,量子-经典混合机器学习架构MindQuantum能够处理带参数的量子线路,并利用量子神经网络的可逆性来对线路进行自动微分,得到观测值对各参数的导数。\n",
  16. "\n",
  17. "构建参数化量子线路并用参数化模拟器算子进行线路演化的大致流程如下:\n",
  18. "\n",
  19. "1. 初始化量子线路。\n",
  20. "2. 根据需求,在量子线路中加入参数化的量子门或者非参数的量子门。\n",
  21. "3. 利用PQC模拟器算子来进行态演化或者梯度求解。\n",
  22. "\n",
  23. "## 环境准备\n",
  24. "\n",
  25. "导入本教程所依赖模块。"
  26. ]
  27. },
  28. {
  29. "cell_type": "code",
  30. "execution_count": 1,
  31. "metadata": {},
  32. "outputs": [],
  33. "source": [
  34. "import numpy as np\n",
  35. "import mindquantum as mq\n",
  36. "from mindquantum.gate import H, X, Y, RY, RX"
  37. ]
  38. },
  39. {
  40. "cell_type": "markdown",
  41. "metadata": {},
  42. "source": [
  43. "## 量子门\n",
  44. "\n",
  45. "量子门是对量子比特进行操作的基本逻辑单元。对于经典电路来说,任意的逻辑电路都可以由一些基本逻辑门构成,类似的,任意的量子线路都可以由一些基本的量子门构成,如作用在单比特上的门和受控非门。常用的量子门有$\\text{X}$门、$\\text{Y}$门、$\\text{Z}$门、$\\text{Hadamard}$门、$\\text{CNOT}$门以及一些旋转门。例如,$\\text{Y}$门的形式如下:"
  46. ]
  47. },
  48. {
  49. "cell_type": "code",
  50. "execution_count": 2,
  51. "metadata": {},
  52. "outputs": [
  53. {
  54. "name": "stdout",
  55. "output_type": "stream",
  56. "text": [
  57. "Gate name: Y\n",
  58. "Gate matrix: \n",
  59. " [[ 0.+0.j -0.-1.j]\n",
  60. " [ 0.+1.j 0.+0.j]]\n"
  61. ]
  62. }
  63. ],
  64. "source": [
  65. "print('Gate name: ', Y)\n",
  66. "print('Gate matrix: \\n', Y.matrix())"
  67. ]
  68. },
  69. {
  70. "cell_type": "markdown",
  71. "metadata": {},
  72. "source": [
  73. "上面的$\\text{Z}$门是一个非参数门,而一些旋转门(比如$\\text{RY}$门)则是含参数门,通过给予不同的旋转角度$\\theta$,旋转门将对量子比特产生不同的影响,如$\\text{RY}$门矩阵的表达式为:\n",
  74. "\n",
  75. "$$\\text{RY}(\\theta)=e^{-i\\theta Y/2}=\\begin{pmatrix}\\cos(\\theta/2)&-\\sin(\\theta/2)\\\\\\sin(\\theta/2)&\\cos(\\theta/2)\\end{pmatrix}$$\n",
  76. "\n",
  77. "其中$i$为虚数基本单位。这种含参数的量子门是后续搭建量子神经网络的重要组成单元。下面,我们打印$\\text{RY}$门在旋转角度为$0.5$时的矩阵形式。"
  78. ]
  79. },
  80. {
  81. "cell_type": "code",
  82. "execution_count": 3,
  83. "metadata": {},
  84. "outputs": [
  85. {
  86. "data": {
  87. "text/plain": [
  88. "array([[ 0.96891242, -0.24740396],\n",
  89. " [ 0.24740396, 0.96891242]])"
  90. ]
  91. },
  92. "execution_count": 3,
  93. "metadata": {},
  94. "output_type": "execute_result"
  95. }
  96. ],
  97. "source": [
  98. "ry = RY('a')\n",
  99. "ry.matrix({'a': 0.5})"
  100. ]
  101. },
  102. {
  103. "cell_type": "markdown",
  104. "metadata": {},
  105. "source": [
  106. "## 量子线路\n",
  107. "\n",
  108. "量子线路是用来对各种量子逻辑门进行有效组织的结构,我们可以通过量子门的list来初始化量子线路,也可以通过加法(`+`)加一个量子门或者线路,乘法(`*`)乘一个整数来扩充量子线路。这里我们来构建如下的量子线路,并打印量子线路的相关信息。下图中`q0`、`q1`和`q2`分别表示三个量子比特,量子线路由三个量子门构成,分别为作用在`q0`比特上的Hadamard门,作用在`q1`比特并受`q0`比特控制的$CNOT$门和作用在`q2`比特上的$\\text{RY}$旋转门。\n",
  109. "\n",
  110. "![quantum circuit](https://gitee.com/mindspore/docs/raw/master/tutorials/training/source_zh_cn/advanced_use/images/quantum_circuit.png)\n",
  111. "\n",
  112. "### [HiQsimulator](https://hiq.huaweicloud.com/doc/index.html) 兼容的量子线路搭建格式\n",
  113. "\n",
  114. "1. 使用`CircuitEngine`线路引擎来搭建量子线路\n",
  115. "\n",
  116. " 我们通过操作符“|”,将量子门作用在相应的量子比特上。"
  117. ]
  118. },
  119. {
  120. "cell_type": "code",
  121. "execution_count": 4,
  122. "metadata": {},
  123. "outputs": [
  124. {
  125. "name": "stdout",
  126. "output_type": "stream",
  127. "text": [
  128. "H(0)\n",
  129. "X(1 <-: 0)\n",
  130. "RY(p1|2)\n",
  131. "========Circuit Summary========\n",
  132. "|Total number of gates : 3. |\n",
  133. "|Parameter gates : 1. |\n",
  134. "|with 1 parameters are : p1. |\n",
  135. "|Number qubit of circuit: 3 |\n",
  136. "===============================\n"
  137. ]
  138. }
  139. ],
  140. "source": [
  141. "eng = mq.engine.CircuitEngine()\n",
  142. "qubits = eng.allocate_qureg(3)\n",
  143. "H | qubits[0]\n",
  144. "X | (qubits[0], qubits[1])\n",
  145. "RY('p1') | qubits[2]\n",
  146. "encoder = eng.circuit\n",
  147. "print(encoder)\n",
  148. "encoder.summary()"
  149. ]
  150. },
  151. {
  152. "cell_type": "markdown",
  153. "metadata": {},
  154. "source": [
  155. " 这里`X(1 <-: 0)`表示受0比特控制、作用在1比特上的`X`门,也即CNOT门。`RY(p1|2)`表示作用在2比特上的绕Y轴旋转门,`p1`为旋转角度。通过打印出的Summary信息我们可以发现,该量子线路由三个量子门构成,其中有一个量子门是参数化量子门,整个量子线路用到的量子比特为3个。"
  156. ]
  157. },
  158. {
  159. "cell_type": "markdown",
  160. "metadata": {},
  161. "source": [
  162. "2. 使用装饰器来搭建量子线路\n",
  163. "\n",
  164. " 通过装饰器来搭建量子线路能够省去一些重复的引擎声明步骤。"
  165. ]
  166. },
  167. {
  168. "cell_type": "code",
  169. "execution_count": 5,
  170. "metadata": {},
  171. "outputs": [
  172. {
  173. "name": "stdout",
  174. "output_type": "stream",
  175. "text": [
  176. "H(0)\n",
  177. "X(1 <-: 0)\n",
  178. "RY(p1|2)\n",
  179. "========Circuit Summary========\n",
  180. "|Total number of gates : 3. |\n",
  181. "|Parameter gates : 1. |\n",
  182. "|with 1 parameters are : p1. |\n",
  183. "|Number qubit of circuit: 3 |\n",
  184. "===============================\n"
  185. ]
  186. }
  187. ],
  188. "source": [
  189. "from mindquantum.engine import circuit_generator\n",
  190. "\n",
  191. "@circuit_generator(3)\n",
  192. "def encoder(qubits):\n",
  193. " H | qubits[0]\n",
  194. " X | (qubits[0], qubits[1])\n",
  195. " RY('p1') | qubits[2]\n",
  196. "\n",
  197. "print(encoder)\n",
  198. "encoder.summary()"
  199. ]
  200. },
  201. {
  202. "cell_type": "markdown",
  203. "metadata": {},
  204. "source": [
  205. " 我们还可以给装饰器传入更多的参数来供线路生成时使用。例如可以传入一个字符串,搭建量子线路时,可以利用该字符串来给每个参数添加一个前缀,这样有利于生成结构相同,但参数名不同的量子线路。"
  206. ]
  207. },
  208. {
  209. "cell_type": "code",
  210. "execution_count": 6,
  211. "metadata": {},
  212. "outputs": [
  213. {
  214. "name": "stdout",
  215. "output_type": "stream",
  216. "text": [
  217. "H(0)\n",
  218. "X(1 <-: 0)\n",
  219. "RY(encoder_1|2)\n",
  220. "===========Circuit Summary===========\n",
  221. "|Total number of gates : 3. |\n",
  222. "|Parameter gates : 1. |\n",
  223. "|with 1 parameters are : encoder_1.|\n",
  224. "|Number qubit of circuit: 3 |\n",
  225. "=====================================\n"
  226. ]
  227. }
  228. ],
  229. "source": [
  230. "@circuit_generator(3, prefix='encoder')\n",
  231. "def encoder(qubits, prefix):\n",
  232. " H | qubits[0]\n",
  233. " X | (qubits[0], qubits[1])\n",
  234. " RY(prefix + '_1') | qubits[2]\n",
  235. "\n",
  236. "print(encoder)\n",
  237. "encoder.summary()"
  238. ]
  239. },
  240. {
  241. "cell_type": "markdown",
  242. "metadata": {},
  243. "source": [
  244. "### 更便捷的线路生成方式\n",
  245. "\n",
  246. "通过往量子线路中不断地添加作用在不同比特上的量子门可快速完成量子线路的搭建。\n"
  247. ]
  248. },
  249. {
  250. "cell_type": "code",
  251. "execution_count": 7,
  252. "metadata": {},
  253. "outputs": [
  254. {
  255. "name": "stdout",
  256. "output_type": "stream",
  257. "text": [
  258. "H(0)\n",
  259. "X(1 <-: 0)\n",
  260. "RY(p1|2)\n",
  261. "========Circuit Summary========\n",
  262. "|Total number of gates : 3. |\n",
  263. "|Parameter gates : 1. |\n",
  264. "|with 1 parameters are : p1. |\n",
  265. "|Number qubit of circuit: 3 |\n",
  266. "===============================\n"
  267. ]
  268. }
  269. ],
  270. "source": [
  271. "from mindquantum import Circuit\n",
  272. "\n",
  273. "encoder = Circuit()\n",
  274. "encoder += H.on(0)\n",
  275. "encoder += X.on(1,0)\n",
  276. "encoder += RY('p1').on(2)\n",
  277. "print(encoder)\n",
  278. "encoder.summary()"
  279. ]
  280. },
  281. {
  282. "cell_type": "markdown",
  283. "metadata": {},
  284. "source": [
  285. "## 利用 MindSpore 算子进行量子线路的模拟"
  286. ]
  287. },
  288. {
  289. "cell_type": "markdown",
  290. "metadata": {},
  291. "source": [
  292. "一个常见的量子神经网络通常由如下三个部分构成:\n",
  293. "\n",
  294. "- 一个(或多个)编码线路,用于将经典数据编码为量子数据\n",
  295. "- 一个(或多个)待训练线路(通常称为Ansatz)\n",
  296. "- 一个(或多个)待测量物理量\n",
  297. "\n",
  298. "下面我们搭建如下的量子神经网络,该量子神经网络的编码部分由两个$\\text{RY}$门构成,而Ansatz线路由一个$\\text{CNOT}$门和两个$\\text{RX}$门构成,待测量物理量是作用在1号比特上的$\\text{Z}$算符。\n",
  299. "\n",
  300. "![simple qnn](https://gitee.com/mindspore/docs/raw/master/tutorials/training/source_zh_cn/advanced_use/images/simple_qnn.png)\n"
  301. ]
  302. },
  303. {
  304. "cell_type": "code",
  305. "execution_count": 8,
  306. "metadata": {},
  307. "outputs": [],
  308. "source": [
  309. "from mindquantum.ops import QubitOperator\n",
  310. "\n",
  311. "@circuit_generator(2)\n",
  312. "def encoder(qubits):\n",
  313. " RY('a') | qubits[0]\n",
  314. " RY('b') | qubits[1]\n",
  315. "\n",
  316. "@circuit_generator(2)\n",
  317. "def ansatz(qubits):\n",
  318. " X | (qubits[0],qubits[1])\n",
  319. " RX('p1') | qubits[0]\n",
  320. " RX('p2') | qubits[1]\n",
  321. "\n",
  322. "ham = mq.Hamiltonian(QubitOperator('Z1'))\n",
  323. "encoder_names = ['a', 'b']\n",
  324. "ansatz_names = ['p1', 'p2']"
  325. ]
  326. },
  327. {
  328. "cell_type": "markdown",
  329. "metadata": {},
  330. "source": [
  331. "这里我们通过装饰器的方式生成了Encoder线路和Ansatz线路。并利用`generate_pqc_operator`方法来产生一个线路模拟算子,对该量子线路进行模拟计算,并求取量子神经网络的输出对各参数的梯度值。在`generate_pqc_operator`方法中,我们需要提供Encoder线路的参数名、Ansatz线路的参数名、整个量子线路和待测量的物理量。"
  332. ]
  333. },
  334. {
  335. "cell_type": "code",
  336. "execution_count": 9,
  337. "metadata": {},
  338. "outputs": [
  339. {
  340. "name": "stdout",
  341. "output_type": "stream",
  342. "text": [
  343. "Measurement result: [[0.89819133]]\n",
  344. "Gradient of encoder parameters: [[[-0.09011973 -0.1820724 ]]]\n",
  345. "Gradient of ansatz parameters: [[[-2.7755576e-17 -3.7974921e-01]]]\n"
  346. ]
  347. }
  348. ],
  349. "source": [
  350. "from mindquantum.nn import generate_pqc_operator\n",
  351. "from mindspore import Tensor\n",
  352. "from mindspore import context\n",
  353. "context.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\n",
  354. "\n",
  355. "pqc = generate_pqc_operator(encoder_names, ansatz_names, encoder+ansatz, ham)\n",
  356. "encoder_data = Tensor(np.array([[0.1,0.2]]).astype(np.float32))\n",
  357. "ansatz_data = Tensor(np.array([0.3,0.4]).astype(np.float32))\n",
  358. "measure_result, encoder_grad, ansatz_grad = pqc(encoder_data, ansatz_data)\n",
  359. "print('Measurement result: ', measure_result.asnumpy())\n",
  360. "print('Gradient of encoder parameters: ', encoder_grad.asnumpy())\n",
  361. "print('Gradient of ansatz parameters: ', ansatz_grad.asnumpy())"
  362. ]
  363. },
  364. {
  365. "cell_type": "markdown",
  366. "metadata": {},
  367. "source": [
  368. "上面的三个结果分别表示量子神经网络的输出值、编码线路中参数的梯度值和带训练Ansatz线路中参数的梯度值。有的时候,量子神经网络是作为整个量子经典混合神经网络的第一层,因此我们不用对编码线路中的梯度求导数,对于这种不需要求梯度的线路,可以通过`no_grad`方法指定不需要计算梯度的量子线路不求导。"
  369. ]
  370. },
  371. {
  372. "cell_type": "code",
  373. "execution_count": 10,
  374. "metadata": {},
  375. "outputs": [
  376. {
  377. "name": "stdout",
  378. "output_type": "stream",
  379. "text": [
  380. "Measurement result: [[0.89819133]]\n",
  381. "Gradient of encoder parameters: [[[0. 0.]]]\n",
  382. "Gradient of ansatz parameters: [[[-2.7755576e-17 -3.7974921e-01]]]\n"
  383. ]
  384. }
  385. ],
  386. "source": [
  387. "encoder.no_grad()\n",
  388. "pqc = generate_pqc_operator(encoder_names, ansatz_names, encoder+ansatz, ham)\n",
  389. "measure_result, encoder_grad, ansatz_grad = pqc(encoder_data, ansatz_data)\n",
  390. "print('Measurement result: ', measure_result.asnumpy())\n",
  391. "print('Gradient of encoder parameters: ', encoder_grad.asnumpy())\n",
  392. "print('Gradient of ansatz parameters: ', ansatz_grad.asnumpy())"
  393. ]
  394. },
  395. {
  396. "cell_type": "markdown",
  397. "metadata": {},
  398. "source": [
  399. "如上可知,量子神经网络中的编码线路参数的导数都为零,实际模拟计算过程中没有对其求导。"
  400. ]
  401. }
  402. ],
  403. "metadata": {
  404. "kernelspec": {
  405. "display_name": "Python 3",
  406. "language": "python",
  407. "name": "python3"
  408. },
  409. "language_info": {
  410. "codemirror_mode": {
  411. "name": "ipython",
  412. "version": 3
  413. },
  414. "file_extension": ".py",
  415. "mimetype": "text/x-python",
  416. "name": "python",
  417. "nbconvert_exporter": "python",
  418. "pygments_lexer": "ipython3",
  419. "version": "3.8.5"
  420. }
  421. },
  422. "nbformat": 4,
  423. "nbformat_minor": 4
  424. }

MindQuantum是结合MindSpore和HiQ开发的量子机器学习框架,支持多种量子神经网络的训练和推理。得益于华为HiQ团队的量子计算模拟器和MindSpore高性能自动微分能力,MindQuantum能够高效处理量子机器学习、量子化学模拟和量子优化等问题,性能达到业界TOP1,为广大的科研人员、老师和学生提供了快速设计和验证量子机器学习算法的高效平台。