提交 476abd12 编写于 作者: Q Quleaf

update to v2.0.0

上级 4208c1da
......@@ -33,7 +33,7 @@ English | [简体中文](README_CN.md)
</a>
<!-- PyPI -->
<a href="https://pypi.org/project/paddle-quantum/">
<img src="https://img.shields.io/badge/pypi-v1.2.0-orange.svg?style=flat-square&logo=pypi"/>
<img src="https://img.shields.io/badge/pypi-v2.0.0-orange.svg?style=flat-square&logo=pypi"/>
</a>
<!-- Python -->
<a href="https://www.python.org/">
......@@ -71,7 +71,7 @@ Paddle Quantum aims at establishing a bridge between artificial intelligence (AI
### Install PaddlePaddle
This dependency will be automatically satisfied when users install Paddle Quantum. Please refer to [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick)'s official installation and configuration page. This project requires PaddlePaddle 1.8.5.
This dependency will be automatically satisfied when users install Paddle Quantum. Please refer to [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick)'s official installation and configuration page. This project requires PaddlePaddle 2.0.1+.
### Install Paddle Quantum
......@@ -96,8 +96,8 @@ pip install -e .
Once the user confirms the above OS constraint, OpenFermion can be installed with the following command. These packages are used for quantum chemistry calculations and could be potentially used in the VQE tutorial.
```bash
pip install openfermion==0.11.0
pip install openfermionpyscf==0.4
pip install openfermion
pip install openfermionpyscf
```
### Run example
......
......@@ -34,7 +34,7 @@
</a>
<!-- PyPI -->
<a href="https://pypi.org/project/paddle-quantum/">
<img src="https://img.shields.io/badge/pypi-v1.2.0-orange.svg?style=flat-square&logo=pypi"/>
<img src="https://img.shields.io/badge/pypi-v2.0.0-orange.svg?style=flat-square&logo=pypi"/>
</a>
<!-- Python -->
<a href="https://www.python.org/">
......@@ -70,7 +70,7 @@
### 安装 PaddlePaddle
当用户安装 Paddle Quantum 时会自动下载安装这个关键依赖包。关于 PaddlePaddle 更全面的安装信息请参考 [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick) 安装配置页面。此项目需求 PaddlePaddle 1.8.5
当用户安装 Paddle Quantum 时会自动下载安装这个关键依赖包。关于 PaddlePaddle 更全面的安装信息请参考 [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick) 安装配置页面。此项目需求 PaddlePaddle 2.0.1+
### 安装 Paddle Quantum
......@@ -95,8 +95,8 @@ pip install -e .
VQE中调用 OpenFermion 读取分子 .xyz 文件并计算,因此需要安装 openfermion 和 openfermionpyscf。
```bash
pip install openfermion==0.11.0
pip install openfermionpyscf==0.4
pip install openfermion
pip install openfermionpyscf
```
### 运行
......
......@@ -35,7 +35,7 @@
"\n",
"这里,我们介绍如何在 x64 平台上的 Windows10 系统中配置 CUDA 环境。首先,在[CUDA GPUs | NVIDIA Developer](https://developer.nvidia.com/cuda-gpus)上查看你的GPU是否可以安装CUDA环境。然后,在[NVIDIA 驱动程序下载](https://www.nvidia.cn/Download/index.aspx?lang=cn)下载你的显卡的最新版驱动,并安装到电脑上。\n",
"\n",
"在[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中,我们发现,**Paddle Paddle 在 Windows 下仅支持 CUDA 9.0/10.0 的单卡模式;不支持 CUDA 9.1/9.2/10.1**,所以,我们需要安装 CUDA10.0(CUDA9.0在理论上也可以)。在[CUDA Toolkit Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-toolkit-archive)找到 CUDA 10.0 的下载地址:[CUDA Toolkit 10.0 Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-10.0-download-archive),下载CUDA后,运行安装。\n",
"在[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中,我们发现,**PaddlePaddle 的 GPU版本支持CUDA 9.0/10.0/10.1/10.2/11.0,且仅支持单卡**。所以这里,我们安装 CUDA10.2。在[CUDA Toolkit Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-toolkit-archive)找到 CUDA 10.2 的下载地址:[CUDA Toolkit 10.2 Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-10.2-download-archive),下载CUDA后,运行安装。\n",
"\n",
"在安装过程中,选择**自定义安装**,在 CUDA 选项中,勾选除 Visual Studio Intergration 外的其他内容(除非你理解 Visual Studio Intergration 的作用),然后除 CUDA 之外,其他选项均不勾选。然后安装位置选择默认位置(请留意你的 CUDA 的安装位置,后面需要设置环境变量),等待安装完成。\n",
"\n",
......@@ -43,18 +43,18 @@
"\n",
"### 安装 cuDNN\n",
"\n",
"在[NVIDIA cuDNN | NVIDIA Developer](https://developer.nvidia.com/cudnn)下载 cuDNN,根据[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中的要求,我们**需要使用 cuDNN 7.6+** ,因此我们下载支持 CUDA 10.0 的最新版 cuDNN 即可。下载完成 cuDNN 后进行解压缩。然后,假设我们的 CUDA 的安装路径为`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0`,我们将 cuDNN 解压缩后里面的`bin`、`include`和`lib`中的文件都替换 CUDA 的安装路径下的对应文件(如果文件已存在则进行替换,如果未存在则直接粘贴到对应目录中)。到这里,cuDNN 也就安装完成了。\n",
"在[NVIDIA cuDNN | NVIDIA Developer](https://developer.nvidia.com/cudnn)下载 cuDNN,根据[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中的要求,我们**需要使用 cuDNN 7.6.5+** ,因此我们下载支持 CUDA 10.2 的 7.6.5 版 cuDNN 即可。下载完成 cuDNN 后进行解压缩。然后,假设我们的 CUDA 的安装路径为`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2`,我们将 cuDNN 解压缩后里面的`bin`、`include`和`lib`中的文件都替换 CUDA 的安装路径下的对应文件(如果文件已存在则进行替换,如果未存在则直接粘贴到对应目录中)。到这里,cuDNN 也就安装完成了。\n",
"\n",
"\n",
"### 配置环境变量\n",
"\n",
"接下来还需要配置环境变量。右键电脑桌面上的“此电脑”(或“文件资源管理器”左栏的“此电脑”),选择“属性”,然后选择左侧的“高级系统设置”,在“高级”这一栏下选择“环境变量”。\n",
"\n",
"现在就进入到了环境变量的设置页面,在系统变量中选择`Path`,点击“编辑”。在出现的页面中,查看是否有`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\bin`和`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\libnvvp`这两个地址(其前缀`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0`应该为你的 CUDA 的安装位置),如果没有,请手动添加。\n",
"现在就进入到了环境变量的设置页面,在系统变量中选择`Path`,点击“编辑”。在出现的页面中,查看是否有`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin`和`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\libnvvp`这两个地址(其前缀`C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2`应该为你的 CUDA 的安装位置),如果没有,请手动添加。\n",
"\n",
"### 验证是否安装成功\n",
"\n",
"打开命令行,输入`cd C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\extras\\demo_suite`进入到 CUDA 安装路径(这里也应该为你的 CUDA 的安装位置)。然后分别执行`.\\bandwidthTest.exe`和`.\\deviceQuery.exe`,如果都出现`Result = PASS`,则说明安装成功。\n",
"打开命令行,输入`cd C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\extras\\demo_suite`进入到 CUDA 安装路径(这里也应该为你的 CUDA 的安装位置)。然后分别执行`.\\bandwidthTest.exe`和`.\\deviceQuery.exe`,如果都出现`Result = PASS`,则说明安装成功。\n",
"\n"
]
},
......@@ -64,13 +64,13 @@
"source": [
"## 在 CUDA 环境上安装 PaddlePaddle\n",
"\n",
"根据[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中的说明,我们首先需要确定自己的python环境,用`python --version`来查看 python 版本,保证**python版本是3.5.1+/3.6+/3.7+**,并且用`python -m ensurepip`和`python -m pip --version`来查看 pip 版本,**确认是 9.0.1+**。然后,使用`python -m pip install paddlepaddle-gpu==1.8.4.post107 -i https://pypi.tuna.tsinghua.edu.cn/simple`来安装 GPU 版本的 PaddlePaddle。\n",
"根据[飞桨的安装步骤](https://www.paddlepaddle.org.cn/install/quick)中的说明,我们首先需要确定自己的python环境,用`python --version`来查看 python 版本,保证**python版本是3.5.1+/3.6+/3.7/3.8**,并且用`python -m ensurepip`和`python -m pip --version`来查看 pip 版本,**确认是 20.2.2+**。然后,使用`python -m pip install paddlepaddle-gpu -i https://mirror.baidu.com/pypi/simple`来安装 GPU 版本的 PaddlePaddle。\n",
"\n",
"## 安装 Paddle Quantum\n",
"\n",
"下载 Paddle Quantum 的安装包,修改`setup.py`,将其中的`paddlepaddle`改为`paddlepaddle-gpu`,然后按照 Paddle Quantum 的安装要求,执行`pip install -e .`即可。\n",
"下载 Paddle Quantum 的安装包,修改`setup.py`和`requirements.txt`,将其中的`paddlepaddle`改为`paddlepaddle-gpu`,然后按照 Paddle Quantum 的从源代码安装的要求,执行`pip install -e .`即可。\n",
"\n",
"> 如果你是在一个新的 python 环境中安装了 paddlepaddle-gpu 和 paddle_quantum,请在新 python 环境中安装 jupyter,并在新的 jupyter 下重新打开本教程并运行。\n",
"> 如果你是在一个新的 python 环境中安装了 paddlepaddle-gpu 和 paddle_quantum,请在新 python 环境中安装 jupyter,并在新的 jupyter 下重新打开本教程并运行。\n",
"\n",
"## 检测是否安装成功\n",
"\n",
......@@ -91,9 +91,8 @@
}
],
"source": [
"import paddle \n",
"from paddle import fluid\n",
"print(fluid.is_compiled_with_cuda())"
"import paddle\n",
"print(paddle.is_compiled_with_cuda())"
]
},
{
......@@ -111,9 +110,8 @@
"source": [
"```python\n",
"# 0 表示使用编号为0的GPU\n",
"place = fluid.CUDAPlace(0)\n",
"with fluid.dygraph.guard(place):\n",
" # build and train your quantum circuit model\n",
"paddle.set_device(\"gpu:0\")\n",
"# build and train your quantum circuit model\n",
"```"
]
},
......@@ -129,9 +127,8 @@
"metadata": {},
"source": [
"```python\n",
"place = fluid.CPUPlace()\n",
"with fluid.dygraph.guard(place):\n",
" # build and train your quantum circuit model\n",
"paddle.set_device(\"cpu\")\n",
"# build and train your quantum circuit model\n",
"```"
]
},
......@@ -151,17 +148,40 @@
"outputs": [],
"source": [
"import os\n",
"import numpy\n",
"from numpy import concatenate\n",
"from numpy import pi as PI\n",
"from numpy import savez, zeros\n",
"from paddle import fluid\n",
"from paddle.complex import matmul, transpose\n",
"from paddle import matmul, transpose\n",
"from paddle_quantum.circuit import UAnsatz\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy\n",
"from paddle_quantum.VQE.chemistrysub import H2_generator\n",
"from time import time\n",
"\n",
"\n",
"def H2_generator():\n",
" \n",
" H = [\n",
" [-0.04207897647782277, 'i0'],\n",
" [0.17771287465139946, 'z0'],\n",
" [0.1777128746513994, 'z1'],\n",
" [-0.2427428051314046, 'z2'],\n",
" [-0.24274280513140462, 'z3'],\n",
" [0.17059738328801055, 'z0,z1'],\n",
" [0.04475014401535163, 'y0,x1,x2,y3'],\n",
" [-0.04475014401535163, 'y0,y1,x2,x3'],\n",
" [-0.04475014401535163, 'x0,x1,y2,y3'],\n",
" [0.04475014401535163, 'x0,y1,y2,x3'],\n",
" [0.12293305056183797, 'z0,z2'],\n",
" [0.1676831945771896, 'z0,z3'],\n",
" [0.1676831945771896, 'z1,z2'],\n",
" [0.12293305056183797, 'z1,z3'],\n",
" [0.1762764080431959, 'z2,z3']\n",
" ]\n",
" N = 4\n",
" \n",
" return H, N\n",
"\n",
"\n",
"Hamiltonian, N = H2_generator()\n",
"\n",
......@@ -190,18 +210,20 @@
" return expectation_val\n",
"\n",
"\n",
"class StateNet(fluid.dygraph.Layer):\n",
"class StateNet(paddle.nn.Layer):\n",
" \"\"\"\n",
" Construct the model net\n",
" \"\"\"\n",
"\n",
" def __init__(self, shape, param_attr=fluid.initializer.Uniform(\n",
" low=0.0, high=2 * PI), dtype=\"float64\"):\n",
" def __init__(self, shape, dtype=\"float64\"):\n",
" super(StateNet, self).__init__()\n",
"\n",
" # 初始化 theta 参数列表,并用 [0, 2*pi] 的均匀分布来填充初始值\n",
" self.theta = self.create_parameter(\n",
" shape=shape, attr=param_attr, dtype=dtype, is_bias=False)\n",
" shape=shape,\n",
" default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2 * PI), \n",
" dtype=dtype, \n",
" is_bias=False)\n",
"\n",
" # 定义损失函数和前向传播机制\n",
" def forward(self, Hamiltonian, N, D):\n",
......@@ -231,54 +253,51 @@
"name": "stdout",
"output_type": "stream",
"text": [
"iter: 20 loss: -1.0599\n",
"iter: 20 Ground state energy: -1.0599 Ha\n",
"iter: 40 loss: -1.1229\n",
"iter: 40 Ground state energy: -1.1229 Ha\n",
"iter: 60 loss: -1.1347\n",
"iter: 60 Ground state energy: -1.1347 Ha\n",
"iter: 80 loss: -1.1359\n",
"iter: 80 Ground state energy: -1.1359 Ha\n"
"iter: 20 loss: -0.9686\n",
"iter: 20 Ground state energy: -0.9686 Ha\n",
"iter: 40 loss: -1.1056\n",
"iter: 40 Ground state energy: -1.1056 Ha\n",
"iter: 60 loss: -1.1235\n",
"iter: 60 Ground state energy: -1.1235 Ha\n",
"iter: 80 loss: -1.1317\n",
"iter: 80 Ground state energy: -1.1317 Ha\n"
]
}
],
"source": [
"# 0 表示使用编号为0的GPU\n",
"place_gpu = fluid.CUDAPlace(0)\n",
"with fluid.dygraph.guard(place_gpu):\n",
"paddle.set_device(\"gpu:0\")\n",
" \n",
" # 确定网络的参数维度\n",
" net = StateNet(shape=[D + 1, N, 1])\n",
"# 确定网络的参数维度\n",
"net = StateNet(shape=[D + 1, N, 1])\n",
"\n",
" # 一般来说,我们利用Adam优化器来获得相对好的收敛\n",
" # 当然你可以改成SGD或者是RMS prop.\n",
" opt = fluid.optimizer.AdamOptimizer(\n",
" learning_rate=LR, parameter_list=net.parameters())\n",
"# 一般来说,我们利用Adam优化器来获得相对好的收敛\n",
"# 当然你可以改成SGD或者是RMSProp\n",
"opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
"\n",
" # 记录优化结果\n",
" summary_iter, summary_loss = [], []\n",
"# 记录优化结果\n",
"summary_iter, summary_loss = [], []\n",
"\n",
" # 优化循环\n",
" for itr in range(1, ITR + 1):\n",
"# 优化循环\n",
"for itr in range(1, ITR + 1):\n",
"\n",
" # 前向传播计算损失函数\n",
" loss = net(Hamiltonian, N, D)\n",
" # 前向传播计算损失函数\n",
" loss = net(Hamiltonian, N, D)\n",
"\n",
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" opt.clear_grad()\n",
"\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
"\n",
" # 打印结果\n",
" if itr % 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\", \n",
" \"%.4f Ha\" % loss.numpy())\n",
"\n"
" # 打印结果\n",
" if itr % 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\", \n",
" \"%.4f Ha\" % loss.numpy())\n"
]
},
{
......@@ -297,53 +316,51 @@
"name": "stdout",
"output_type": "stream",
"text": [
"iter: 20 loss: -1.0865\n",
"iter: 20 Ground state energy: -1.0865 Ha\n",
"iter: 40 loss: -1.1153\n",
"iter: 40 Ground state energy: -1.1153 Ha\n",
"iter: 60 loss: -1.1338\n",
"iter: 60 Ground state energy: -1.1338 Ha\n",
"iter: 80 loss: -1.1359\n",
"iter: 80 Ground state energy: -1.1359 Ha\n"
"iter: 20 loss: -1.1080\n",
"iter: 20 Ground state energy: -1.1080 Ha\n",
"iter: 40 loss: -1.1301\n",
"iter: 40 Ground state energy: -1.1301 Ha\n",
"iter: 60 loss: -1.1357\n",
"iter: 60 Ground state energy: -1.1357 Ha\n",
"iter: 80 loss: -1.1361\n",
"iter: 80 Ground state energy: -1.1361 Ha\n"
]
}
],
"source": [
"# 表示使用 CPU\n",
"place_cpu = fluid.CPUPlace()\n",
"with fluid.dygraph.guard(place_cpu):\n",
"paddle.set_device(\"cpu\")\n",
" \n",
" # 确定网络的参数维度\n",
" net = StateNet(shape=[D + 1, N, 1])\n",
"# 确定网络的参数维度\n",
"net = StateNet(shape=[D + 1, N, 1])\n",
"\n",
" # 一般来说,我们利用Adam优化器来获得相对好的收敛\n",
" # 当然你可以改成SGD或者是RMS prop.\n",
" opt = fluid.optimizer.AdamOptimizer(\n",
" learning_rate=LR, parameter_list=net.parameters())\n",
"# 一般来说,我们利用Adam优化器来获得相对好的收敛\n",
"# 当然你可以改成SGD或者是RMSProp\n",
"opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
"\n",
" # 记录优化结果\n",
" summary_iter, summary_loss = [], []\n",
"# 记录优化结果\n",
"summary_iter, summary_loss = [], []\n",
"\n",
" # 优化循环\n",
" for itr in range(1, ITR + 1):\n",
"# 优化循环\n",
"for itr in range(1, ITR + 1):\n",
"\n",
" # 前向传播计算损失函数\n",
" loss = net(Hamiltonian, N, D)\n",
" # 前向传播计算损失函数\n",
" loss = net(Hamiltonian, N, D)\n",
"\n",
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" opt.clear_grad()\n",
"\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
"\n",
" # 打印结果\n",
" if itr % 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\", \n",
" \"%.4f Ha\" % loss.numpy())"
" # 打印结果\n",
" if itr % 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\", \n",
" \"%.4f Ha\" % loss.numpy())\n"
]
},
{
......@@ -382,7 +399,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.9"
"version": "3.7.10"
},
"toc": {
"base_numbering": 1,
......
......@@ -34,7 +34,7 @@
"\n",
"Here, we introduce how to configure the CUDA environment in Windows 10 on the x64 platform. First, check on [CUDA GPUs | NVIDIA Developer](https://developer.nvidia.com/cuda-gpus) to see if your GPU support the CUDA environment. Then, download the latest version of your graphics card driver from [NVIDIA Driver Download](https://www.nvidia.cn/Download/index.aspx?lang=cn) and install it on your computer.\n",
"\n",
"In [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick), we found that **Paddle Paddle only supports CUDA 9.0/10.0 single card mode under Windows; it does not support CUDA 9.1/9.2/10.1**, so we need to install CUDA10.0 (CUDA 9.0 is also possible in theory). Find the download link of CUDA 10.0 in [CUDA Toolkit Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-toolkit-archive): [CUDA Toolkit 10.0 Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-10.0-download-archive). After downloading CUDA, run the installation.\n",
"In [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick), we found that **Paddle Paddle only supports CUDA CUDA 9.0/10.0/10.1/10.2/11.0 single card mode under Windows**, so we install CUDA10.2 here. Find the download link of CUDA 10.2 in [CUDA Toolkit Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-toolkit-archive): [CUDA Toolkit 10.2 Archive | NVIDIA Developer](https://developer.nvidia.com/cuda-10.2-download-archive). After downloading CUDA, run the installation.\n",
"\n",
"During the installation process, select **Custom Installation** in the CUDA options, check all the boxes except for Visual Studio Integration (unless you are familiar with it). Then check CUDA option only. Then select the default location for the installation location (please pay attention to the installation location of your CUDA, you need to set environment variables later), and wait for the installation to complete.\n",
"\n",
......@@ -42,17 +42,17 @@
"\n",
"### Install cuDNN\n",
"\n",
"Download cuDNN in [NVIDIA cuDNN | NVIDIA Developer](https://developer.nvidia.com/cudnn), according to [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick) requirements, we **need to use cuDNN 7.6+**, so we can download the latest version of cuDNN that supports CUDA 10.0. After downloading cuDNN, unzip it. Assuming the installation path of our CUDA is `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0`. After decompressing cuDNN, we take the files in `bin`, `include` and `lib` and replace the corresponding original files in the CUDA installation path (if the file already exists, replace it, if it does not exist, paste it directly into the corresponding directory). At this point, cuDNN has been installed.\n",
"Download cuDNN in [NVIDIA cuDNN | NVIDIA Developer](https://developer.nvidia.com/cudnn), according to [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick) requirements, we **need to use cuDNN 7.6.5+**, so we can download the version 7.6.5 of cuDNN that supports CUDA 10.2. After downloading cuDNN, unzip it. Assuming the installation path of our CUDA is `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2`. After decompressing cuDNN, we take the files in `bin`, `include` and `lib` and replace the corresponding original files in the CUDA installation path (if the file already exists, replace it, if it does not exist, paste it directly into the corresponding directory). At this point, cuDNN has been installed.\n",
"\n",
"### Configure environment variables\n",
"\n",
"Next, you need to configure environment variables. Right-click \"This PC\" on the desktop of the computer (or \"This PC\" in the left column of \"File Explorer\"), select \"Properties\", and then select \"Advanced System Settings\" on the left, under the \"Advanced\" column Select \"Environmental Variables\".\n",
"\n",
"Now you enter the setting page of environment variables, select `Path` in the `System variables`, and click `Edit`. In the page that appears, check if there are two addresses `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\bin` and `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\libnvvp` (the prefix `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0` should be your CUDA installation location), if not, please add them manually.\n",
"Now you enter the setting page of environment variables, select `Path` in the `System variables`, and click `Edit`. In the page that appears, check if there are two addresses `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\bin` and `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\libnvvp` (the prefix `C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2` should be your CUDA installation location), if not, please add them manually.\n",
"\n",
"### Verify that the installation is successful\n",
"\n",
"Open the command line and enter `cd C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\extras\\demo_suite` to enter the CUDA installation path (this should also be your CUDA installation location). Then execute `.\\bandwidthTest.exe` and `.\\deviceQuery.exe` respectively. If both `Result = PASS` appear, the installation is successful.\n",
"Open the command line and enter `cd C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.2\\extras\\demo_suite` to enter the CUDA installation path (this should also be your CUDA installation location). Then execute `.\\bandwidthTest.exe` and `.\\deviceQuery.exe` respectively. If both `Result = PASS` appear, the installation is successful.\n",
"\n"
]
},
......@@ -62,19 +62,13 @@
"source": [
"## Install PaddlePaddle on CUDA environment\n",
"\n",
"According to the instructions in [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick), we first need to make sure our python environment is correct and use `python --version` to check the python version. Ensure that the **python version is 3.5.1+/3.6+/3.7+**, and use `python -m ensurepip` and `python -m pip --version` to check the pip version, **confirm it is 9.0.1+**. Then, use `python -m pip install paddlepaddle-gpu==1.8.4.post107 -i https://pypi.tuna.tsinghua.edu.cn/simple` to install the GPU version of PaddlePaddle.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"According to the instructions in [PaddlePaddle Installation Steps](https://www.paddlepaddle.org.cn/install/quick), we first need to make sure our python environment is correct and use `python --version` to check the python version. Ensure that the **python version is 3.5.1+/3.6+/3.7/3.8**, and use `python -m ensurepip` and `python -m pip --version` to check the pip version, **confirm it is 20.2.2+**. Then, use `python -m pip install paddlepaddle-gpu -i https://mirror.baidu.com/pypi/simple` to install the GPU version of PaddlePaddle.\n",
"\n",
"## Install Paddle Quantum\n",
"\n",
"Download the Paddle Quantum installation package, modify `setup.py`, change paddlepaddle` to `paddlepaddle-gpu`, and then execute `pip install -e .` according to the installation requirements of Paddle Quantum.\n",
"Download the Paddle Quantum installation package, modify `setup.py` and `requirements.txt`, change `paddlepaddle` to `paddlepaddle-gpu`, and then execute `pip install -e .` according to the installation guide of Paddle Quantum from source code.\n",
"\n",
"> If you have installed paddlepaddle-gpu and paddle_quantum in a new python environment, please also install jupyter in the new python environment, and reopen this tutorial under the new jupyter notebook and run it."
"> If you have installed paddlepaddle-gpu and paddle_quantum in a new python environment, please also install jupyter in the new python environment, and reopen this tutorial under the new jupyter notebook and run it.\n"
]
},
{
......@@ -102,8 +96,7 @@
],
"source": [
"import paddle \n",
"from paddle import fluid\n",
"print(fluid.is_compiled_with_cuda())"
"print(paddle.is_compiled_with_cuda())"
]
},
{
......@@ -121,9 +114,8 @@
"source": [
"```python\n",
"# 0 means to use GPU number 0\n",
"place = fluid.CUDAPlace(0)\n",
"with fluid.dygraph.guard(place):\n",
" # build and train your quantum circuit model\n",
"paddle.set_device('gpu:0')\n",
"# build and train your quantum circuit model\n",
"```"
]
},
......@@ -139,9 +131,8 @@
"metadata": {},
"source": [
"```python\n",
"place = fluid.CPUPlace()\n",
"with fluid.dygraph.guard(place):\n",
" # build and train your quantum circuit model\n",
"paddle.set_device('cpu')\n",
"# build and train your quantum circuit model\n",
"```"
]
},
......@@ -161,17 +152,41 @@
"outputs": [],
"source": [
"import os\n",
"import numpy\n",
"from numpy import concatenate\n",
"from numpy import pi as PI\n",
"from numpy import savez, zeros\n",
"from paddle import fluid\n",
"from paddle.complex import matmul, transpose\n",
"from paddle import matmul, transpose\n",
"from paddle_quantum.circuit import UAnsatz\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy\n",
"from paddle_quantum.VQE.chemistrysub import H2_generator\n",
"from time import time\n",
"\n",
"\n",
"def H2_generator():\n",
" \n",
" H = [\n",
" [-0.04207897647782277, 'i0'],\n",
" [0.17771287465139946, 'z0'],\n",
" [0.1777128746513994, 'z1'],\n",
" [-0.2427428051314046, 'z2'],\n",
" [-0.24274280513140462, 'z3'],\n",
" [0.17059738328801055, 'z0,z1'],\n",
" [0.04475014401535163, 'y0,x1,x2,y3'],\n",
" [-0.04475014401535163, 'y0,y1,x2,x3'],\n",
" [-0.04475014401535163, 'x0,x1,y2,y3'],\n",
" [0.04475014401535163, 'x0,y1,y2,x3'],\n",
" [0.12293305056183797, 'z0,z2'],\n",
" [0.1676831945771896, 'z0,z3'],\n",
" [0.1676831945771896, 'z1,z2'],\n",
" [0.12293305056183797, 'z1,z3'],\n",
" [0.1762764080431959, 'z2,z3']\n",
" ]\n",
" N = 4\n",
" \n",
" return H, N\n",
"\n",
"\n",
"\n",
"Hamiltonian, N = H2_generator()\n",
"\n",
......@@ -200,18 +215,20 @@
" return expectation_val\n",
"\n",
"\n",
"class StateNet(fluid.dygraph.Layer):\n",
"class StateNet(paddle.nn.Layer):\n",
" \"\"\"\n",
" Construct the model net\n",
" \"\"\"\n",
"\n",
" def __init__(self, shape, param_attr=fluid.initializer.Uniform(\n",
" low=0.0, high=2 * PI), dtype=\"float64\"):\n",
" def __init__(self, shape, dtype=\"float64\"):\n",
" super(StateNet, self).__init__()\n",
"\n",
" # Initialize the theta parameter list and fill the initial value with the uniform distribution of [0, 2*pi]\n",
" self.theta = self.create_parameter(\n",
" shape=shape, attr=param_attr, dtype=dtype, is_bias=False)\n",
" shape=shape, \n",
" default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2 * PI), \n",
" dtype=dtype, \n",
" is_bias=False)\n",
"\n",
" # Define loss function and forward propagation mechanism\n",
" def forward(self, Hamiltonian, N, D):\n",
......@@ -241,12 +258,12 @@
"name": "stdout",
"output_type": "stream",
"text": [
"iter: 20 loss: -0.8634\n",
"iter: 20 Ground state energy: -0.8634 Ha\n",
"iter: 40 loss: -1.1203\n",
"iter: 40 Ground state energy: -1.1203 Ha\n",
"iter: 60 loss: -1.1350\n",
"iter: 60 Ground state energy: -1.1350 Ha\n",
"iter: 20 loss: -1.0305\n",
"iter: 20 Ground state energy: -1.0305 Ha\n",
"iter: 40 loss: -1.1111\n",
"iter: 40 Ground state energy: -1.1111 Ha\n",
"iter: 60 loss: -1.1342\n",
"iter: 60 Ground state energy: -1.1342 Ha\n",
"iter: 80 loss: -1.1359\n",
"iter: 80 Ground state energy: -1.1359 Ha\n"
]
......@@ -254,40 +271,38 @@
],
"source": [
"# 0 means to use GPU number 0\n",
"place_gpu = fluid.CUDAPlace(0)\n",
"with fluid.dygraph.guard(place_gpu):\n",
"paddle.set_device('gpu:0')\n",
" \n",
" # Determine the parameter dimension of the network\n",
" net = StateNet(shape=[D + 1, N, 1])\n",
"# Determine the parameter dimension of the network\n",
"net = StateNet(shape=[D + 1, N, 1])\n",
"\n",
" # Generally speaking, we use Adam optimizer to get relatively good convergence\n",
" # Of course, you can change to SGD or RMS prop.\n",
" opt = fluid.optimizer.AdamOptimizer(\n",
" learning_rate=LR, parameter_list=net.parameters())\n",
"# Generally speaking, we use Adam optimizer to get relatively good convergence\n",
"# Of course, you can change to SGD or RMSProp\n",
"opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
"\n",
" # Record optimization results\n",
" summary_iter, summary_loss = [], []\n",
"# Record optimization results\n",
"summary_iter, summary_loss = [], []\n",
"\n",
" # Optimization cycle\n",
" for itr in range(1, ITR + 1):\n",
"# Optimization cycle\n",
"for itr in range(1, ITR + 1):\n",
"\n",
" # Forward propagation to calculate loss function\n",
" loss = net(Hamiltonian, N, D)\n",
" # Forward propagation to calculate loss function\n",
" loss = net(Hamiltonian, N, D)\n",
"\n",
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" opt.clear_grad()\n",
"\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
"\n",
" # Print results\n",
" if itr% 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\"% loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\",\n",
" \"%.4f Ha\"% loss.numpy())"
" # Print results\n",
" if itr% 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\"% loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\",\n",
" \"%.4f Ha\"% loss.numpy())"
]
},
{
......@@ -306,53 +321,51 @@
"name": "stdout",
"output_type": "stream",
"text": [
"iter: 20 loss: -0.7789\n",
"iter: 20 Ground state energy: -0.7789 Ha\n",
"iter: 40 loss: -1.0741\n",
"iter: 40 Ground state energy: -1.0741 Ha\n",
"iter: 60 loss: -1.1271\n",
"iter: 60 Ground state energy: -1.1271 Ha\n",
"iter: 80 loss: -1.1351\n",
"iter: 80 Ground state energy: -1.1351 Ha\n"
"iter: 20 loss: -1.0639\n",
"iter: 20 Ground state energy: -1.0639 Ha\n",
"iter: 40 loss: -1.1209\n",
"iter: 40 Ground state energy: -1.1209 Ha\n",
"iter: 60 loss: -1.1345\n",
"iter: 60 Ground state energy: -1.1345 Ha\n",
"iter: 80 loss: -1.1360\n",
"iter: 80 Ground state energy: -1.1360 Ha\n"
]
}
],
"source": [
"# Use CPU\n",
"place_cpu = fluid.CPUPlace()\n",
"with fluid.dygraph.guard(place_cpu):\n",
" \n",
" # Determine the parameter dimension of the network\n",
" net = StateNet(shape=[D + 1, N, 1])\n",
"paddle.set_device(\"cpu\")\n",
"\n",
"# Determine the parameter dimension of the network\n",
"net = StateNet(shape=[D + 1, N, 1])\n",
"\n",
" # Generally speaking, we use Adam optimizer to get relatively good convergence\n",
" # Of course you can change to SGD or RMS prop.\n",
" opt = fluid.optimizer.AdamOptimizer(\n",
" learning_rate=LR, parameter_list=net.parameters())\n",
"# Generally speaking, we use Adam optimizer to get relatively good convergence\n",
"# Of course you can change to SGD or RMSProp\n",
"opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
"\n",
" # Record optimization results\n",
" summary_iter, summary_loss = [], []\n",
"# Record optimization results\n",
"summary_iter, summary_loss = [], []\n",
"\n",
" # Optimization cycle\n",
" for itr in range(1, ITR + 1):\n",
"# Optimization cycle\n",
"for itr in range(1, ITR + 1):\n",
"\n",
" # Forward propagation to calculate loss function\n",
" loss = net(Hamiltonian, N, D)\n",
" # Forward propagation to calculate loss function\n",
" loss = net(Hamiltonian, N, D)\n",
"\n",
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" opt.clear_grad()\n",
"\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
" summary_iter.append(itr)\n",
"\n",
" # Print results\n",
" if itr% 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\"% loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\",\n",
" \"%.4f Ha\"% loss.numpy())"
" # Print results\n",
" if itr% 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\"% loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\",\n",
" \"%.4f Ha\"% loss.numpy())"
]
},
{
......@@ -392,7 +405,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.9"
"version": "3.7.10"
},
"toc": {
"base_numbering": 1,
......
......@@ -42,4 +42,4 @@ def H_generator():
# Convert to the data type supported by Paddle Quantum
hamiltonian = hamiltonian.astype("complex128")
rho_G = rho_G.astype("complex128")
return hamiltonian, rho_G
\ No newline at end of file
return hamiltonian, rho_G
......@@ -16,12 +16,10 @@
Paddle_GIBBS
"""
import scipy
from numpy import pi as PI
from paddle import fluid
from paddle.complex import matmul, trace
import paddle
from paddle import matmul, trace
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.state import density_op
from paddle_quantum.utils import state_fidelity, partial_trace
......@@ -51,38 +49,38 @@ def U_theta(initial_state, theta, N, D):
for i in range(N):
cir.ry(theta=theta[D][i][0], which_qubit=i)
# Act quantum neural network on initilized state
# Act quantum neural network on initialized state
final_state = cir.run_density_matrix(initial_state)
return final_state
class Net(fluid.dygraph.Layer):
class Net(paddle.nn.Layer):
"""
Construct the model net
"""
def __init__(self, N, shape, param_attr=fluid.initializer.Uniform(low=0.0, high=2 * PI, seed=SEED),
def __init__(self, N, shape, param_attr=paddle.nn.initializer.Uniform(low=0.0, high=2 * PI),
dtype='float64'):
super(Net, self).__init__()
# Initialize theta by sampling from a uniform distribution [0, 2*pi]
self.theta = self.create_parameter(shape=shape, attr=param_attr, dtype=dtype, is_bias=False)
# Set the initial state as rho = |0..0><0..0|
self.initial_state = fluid.dygraph.to_variable(density_op(N))
self.initial_state = paddle.to_tensor(density_op(N))
# Define the loss function and forward propagation mechanism
def forward(self, H, N, N_SYS_B, beta, D):
# Apply quantum neural network onto the initial state
rho_AB = U_theta(self.initial_state, self.theta, N, D)
# Calculate the partial tarce to get the state rho_B of subsystem B
rho_B = partial_trace(rho_AB, 2 ** (N - N_SYS_B), 2 ** (N_SYS_B), 1)
# Calculate the partial trace to get the state rho_B of subsystem B
rho_B = partial_trace(rho_AB, 2 ** (N - N_SYS_B), 2 ** N_SYS_B, 1)
# Calculate the three components of the loss function
rho_B_squre = matmul(rho_B, rho_B)
loss1 = (trace(matmul(rho_B, H))).real
loss2 = (trace(rho_B_squre)).real * 2 / beta
loss3 = - ((trace(matmul(rho_B_squre, rho_B))).real + 3) / (2 * beta)
loss1 = paddle.real(trace(matmul(rho_B, H)))
loss2 = paddle.real(trace(rho_B_squre)) * 2 / beta
loss3 = - (paddle.real(trace(matmul(rho_B_squre, rho_B))) + 3) / (2 * beta)
# Get the final loss function
loss = loss1 + loss2 + loss3
......@@ -90,7 +88,7 @@ class Net(fluid.dygraph.Layer):
return loss, rho_B
def Paddle_GIBBS(hamiltonian, rho_G, N=4, N_SYS_B=3, beta=1.5, D=1, ITR=50, LR=0.5):
def Paddle_GIBBS(hamiltonian, rho_G, N=4, N_SYS_B=3, beta=1.5, D=1, ITR=50, LR=0.2):
r"""
Paddle_GIBBS
:param hamiltonian: Hamiltonian
......@@ -102,36 +100,35 @@ def Paddle_GIBBS(hamiltonian, rho_G, N=4, N_SYS_B=3, beta=1.5, D=1, ITR=50, LR=0
:param LR: Learning rate
:return: State prepared by optimized QNN
"""
# Initialize PaddlePaddle dynamic graph machanism
with fluid.dygraph.guard():
# We need to convert Numpy array to variable supported in PaddlePaddle
H = fluid.dygraph.to_variable(hamiltonian)
# Fix the dimensions of network
net = Net(N, shape=[D + 1, N, 1])
# Usually, we recommend Adam optimizer for better results. If you wish, you could use SGD or RMS prop.
opt = fluid.optimizer.AdamOptimizer(learning_rate=LR, parameter_list=net.parameters())
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function and obtain state rho_B
loss, rho_B = net(H, N, N_SYS_B, beta, D)
# In dynamic graph, run backward propogation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
# Convert variable to Numpy array to calculate fidelity F(rho_B, rho_G)
rho_B = rho_B.numpy()
fid = state_fidelity(rho_B, rho_G)
# Print results
if itr % 5 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy(), 'fid:', '%.4f' % fid)
# We need to convert Numpy array to variable supported in PaddlePaddle
H = paddle.to_tensor(hamiltonian)
# Fix the dimensions of network
net = Net(N, shape=[D + 1, N, 1])
# Usually, we recommend Adam optimizer for better results. If you wish, you could use SGD or RMS prop.
opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function and obtain state rho_B
loss, rho_B = net(H, N, N_SYS_B, beta, D)
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
opt.clear_grad()
# Convert variable to Numpy array to calculate fidelity F(rho_B, rho_G)
rho_B = rho_B.numpy()
fid = state_fidelity(rho_B, rho_G)
# Print results
if itr % 5 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy(), 'fid:', '%.4f' % fid)
return rho_B
def main():
paddle.seed(SEED)
# Generate gibbs Hamiltonian
hamiltonian, rho_G = H_generator()
rho_B = Paddle_GIBBS(hamiltonian, rho_G)
......
......@@ -17,6 +17,7 @@ main
"""
import scipy
import paddle
from numpy import trace as np_trace
from paddle_quantum.utils import pauli_str_to_matrix
from paddle_quantum.GIBBS.Paddle_GIBBS import Paddle_GIBBS
......
......@@ -17,13 +17,12 @@ Paddle_QAOA: To learn more about the functions and properties of this applicatio
you could check the corresponding Jupyter notebook under the Tutorial folder.
"""
from paddle import fluid
import os
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import paddle
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.utils import pauli_str_to_matrix
from paddle_quantum.QAOA.QAOA_Prefunc import generate_graph, H_generator
......@@ -114,7 +113,7 @@ def circuit_extend_QAOA(theta, adjacency_matrix, N, P):
return cir
class Net(fluid.dygraph.Layer):
class Net(paddle.nn.Layer):
"""
It constructs the net for QAOA which combines the QAOA circuit with the classical optimizer which sets rules
to update parameters described by theta introduced in the QAOA circuit.
......@@ -124,7 +123,7 @@ class Net(fluid.dygraph.Layer):
def __init__(
self,
shape,
param_attr=fluid.initializer.Uniform(low=0.0, high=np.pi, seed=SEED),
param_attr=paddle.nn.initializer.Uniform(low=0.0, high=np.pi),
dtype="float64",
):
super(Net, self).__init__()
......@@ -179,36 +178,35 @@ def Paddle_QAOA(classical_graph_adjacency, N, P, METHOD, ITR, LR):
Returns:
the optimized QAOA circuit
"""
with fluid.dygraph.guard():
# Construct the net or QAOA circuits based on the standard modules
if METHOD == 1:
net = Net(shape=[P, 2])
# Construct the net or QAOA circuits based on the extended modules
elif METHOD == 2:
net = Net(shape=[P, 4])
else:
raise ValueError("Wrong method called!")
# Classical optimizer
opt = fluid.optimizer.AdamOptimizer(learning_rate=LR, parameter_list=net.parameters())
# Gradient descent loop
summary_iter, summary_loss = [], []
for itr in range(1, ITR + 1):
loss, cir = net(
classical_graph_adjacency, N, P, METHOD
)
loss.backward()
opt.minimize(loss)
net.clear_gradients()
# Construct the net or QAOA circuits based on the standard modules
if METHOD == 1:
net = Net(shape=[P, 2])
# Construct the net or QAOA circuits based on the extended modules
elif METHOD == 2:
net = Net(shape=[P, 4])
else:
raise ValueError("Wrong method called!")
# Classical optimizer
opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())
# Gradient descent loop
summary_iter, summary_loss = [], []
for itr in range(1, ITR + 1):
loss, cir = net(
classical_graph_adjacency, N, P, METHOD
)
loss.backward()
opt.minimize(loss)
opt.clear_grad()
if itr % 10 == 0:
print("iter:", itr, " loss:", "%.4f" % loss.numpy())
summary_loss.append(loss[0][0].numpy())
summary_iter.append(itr)
if itr % 10 == 0:
print("iter:", itr, " loss:", "%.4f" % loss.numpy())
summary_loss.append(loss[0][0].numpy())
summary_iter.append(itr)
theta_opt = net.parameters()[0].numpy()
print("Optmized parameters theta:\n", theta_opt)
# print("Optimized parameters theta:\n", theta_opt)
os.makedirs("output", exist_ok=True)
np.savez("./output/summary_data", iter=summary_iter, energy=summary_loss)
......@@ -217,6 +215,7 @@ def Paddle_QAOA(classical_graph_adjacency, N, P, METHOD, ITR, LR):
def main(N=4):
paddle.seed(SEED)
# number of qubits or number of nodes in the graph
N = 4
classical_graph, classical_graph_adjacency = generate_graph(N, GRAPHMETHOD=1)
......@@ -264,9 +263,8 @@ def main(N=4):
# Show the plot
plt.show()
with fluid.dygraph.guard():
# Measure the output state of the QAOA circuit for 1024 shots by default
prob_measure = opt_cir.measure(plot=True)
# Measure the output state of the QAOA circuit for 1024 shots by default
prob_measure = opt_cir.measure(plot=True)
# Find the max value in measured probability of bitstrings
max_prob = max(prob_measure.values())
......
......@@ -15,6 +15,7 @@
"""
Benchmark
"""
from matplotlib import pyplot
from numpy import diag, max, min, load, ones
from paddle_quantum.utils import pauli_str_to_matrix
......@@ -48,8 +49,8 @@ def benchmark_QAOA(classical_graph_adjacency=None, N=None):
# Plot it
pyplot.figure(1)
loss_QAOA, = pyplot.plot(x1['iter'], x1['energy'], \
alpha=0.7, marker='', linestyle="--", linewidth=2, color='m')
loss_QAOA, = pyplot.plot(x1['iter'], x1['energy'],
alpha=0.7, marker='', linestyle="--", linewidth=2, color='m')
benchmark, = pyplot.plot(
x1['iter'],
H_min,
......@@ -78,7 +79,6 @@ def main():
"""
main
"""
benchmark_QAOA()
......
......@@ -16,13 +16,11 @@
main
"""
from paddle import fluid
import os
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import paddle
from paddle_quantum.utils import pauli_str_to_matrix
from paddle_quantum.QAOA.Paddle_QAOA import Paddle_QAOA
from paddle_quantum.QAOA.QAOA_Prefunc import generate_graph, H_generator
......@@ -76,9 +74,8 @@ def main(N=4):
# Show the plot
plt.show()
with fluid.dygraph.guard():
# Measure the output state of the QAOA circuit for 1024 shots by default
prob_measure = opt_cir.measure(plot=True)
# Measure the output state of the QAOA circuit for 1024 shots by default
prob_measure = opt_cir.measure(plot=True)
# Find the max value in measured probability of bitstrings
max_prob = max(prob_measure.values())
......
......@@ -30,6 +30,6 @@ def H_generator(N):
hamiltonian = random_pauli_str_generator(N, terms=10)
print("Random Hamiltonian in Pauli string format = \n", hamiltonian)
# Generate the marix form of the Hamiltonian
# Generate the matrix form of the Hamiltonian
H = pauli_str_to_matrix(hamiltonian, N)
return H
......@@ -19,8 +19,8 @@ you could check the corresponding Jupyter notebook under the Tutorial folder.
import numpy
from paddle.complex import matmul
from paddle import fluid
import paddle
from paddle import matmul
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.utils import dagger
from paddle_quantum.SSVQE.HGenerator import H_generator
......@@ -43,18 +43,18 @@ def U_theta(theta, N):
cir = UAnsatz(N)
# Use a built-in QNN template
cir.universal_2_qubit_gate(theta)
cir.universal_2_qubit_gate(theta, [0, 1])
# Return the Unitary matrix simulated by QNN
return cir.U
class Net(fluid.dygraph.Layer):
class Net(paddle.nn.Layer):
"""
Construct the model net
"""
def __init__(self, shape, param_attr=fluid.initializer.Uniform(low=0.0, high=2 * numpy.pi, seed=SEED),
def __init__(self, shape, param_attr=paddle.nn.initializer.Uniform(low=0.0, high=2 * numpy.pi),
dtype='float64'):
super(Net, self).__init__()
......@@ -67,7 +67,7 @@ class Net(fluid.dygraph.Layer):
U = U_theta(self.theta, N)
# Calculate loss function
loss_struct = matmul(matmul(dagger(U), H), U).real
loss_struct = paddle.real(matmul(matmul(dagger(U), H), U))
# Use computational basis to calculate each expectation value, which is the same
# as a diagonal element in U^dagger*H*U
......@@ -94,36 +94,35 @@ def Paddle_SSVQE(H, N=2, THETA_SIZE=15, ITR=50, LR=0.3):
:param LR: Learning rate
:return: First several smallest eigenvalues of the Hamiltonian
"""
# Initialize PaddlePaddle dynamic graph machanism
with fluid.dygraph.guard():
# We need to convert Numpy array to variable supported in PaddlePaddle
hamiltonian = fluid.dygraph.to_variable(H)
# Fix the dimensions of network
net = Net(shape=[THETA_SIZE])
# Use Adagrad optimizer
opt = fluid.optimizer.AdagradOptimizer(learning_rate=LR, parameter_list=net.parameters())
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function and obtain energy spectrum
loss, loss_components = net(hamiltonian, N)
# In dynamic graph, run backward propogation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
# Print results
if itr % 10 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])
# We need to convert Numpy array to variable supported in PaddlePaddle
hamiltonian = paddle.to_tensor(H)
# Fix the dimensions of network
net = Net(shape=[THETA_SIZE])
# Use Adagrad optimizer
opt = paddle.optimizer.Adagrad(learning_rate=LR, parameters=net.parameters())
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function and obtain energy spectrum
loss, loss_components = net(hamiltonian, N)
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
opt.clear_grad()
# Print results
if itr % 10 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])
return loss_components
def main():
paddle.seed(SEED)
N = 2
H = H_generator(N)
......
......@@ -17,6 +17,7 @@ main
"""
import numpy
import paddle
from paddle_quantum.SSVQE.HGenerator import H_generator
from paddle_quantum.SSVQE.Paddle_SSVQE import Paddle_SSVQE
......
......@@ -20,9 +20,9 @@ you could check the corresponding Jupyter notebook under the Tutorial folder.
import os
import platform
import paddle
from numpy import pi as PI
from numpy import savez
from paddle import fluid
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.VQE.benchmark import benchmark_result
from paddle_quantum.VQE.chemistrysub import H2_generator
......@@ -58,12 +58,12 @@ def U_theta(theta, Hamiltonian, N, D):
return expectation_val
class StateNet(fluid.dygraph.Layer):
class StateNet(paddle.nn.Layer):
"""
Construct the model net
"""
def __init__(self, shape, param_attr=fluid.initializer.Uniform(low=0.0, high=2 * PI), dtype="float64"):
def __init__(self, shape, param_attr=paddle.nn.initializer.Uniform(low=0.0, high=2 * PI), dtype="float64"):
super(StateNet, self).__init__()
# Initialize theta by sampling from a uniform distribution [0, 2*pi]
......@@ -88,41 +88,38 @@ def Paddle_VQE(Hamiltonian, N, D=2, ITR=80, LR=0.2):
:return: No return
"""
# Initialize PaddlePaddle dynamic graph machanism
with fluid.dygraph.guard():
# Determine the dimensions of network
# 确定网络的参数维度
net = StateNet(shape=[D + 1, N, 1])
# Usually, we recommend Adam optimizer for better result. If you wish, you could use SGD or RMS prop.
opt = fluid.optimizer.AdamOptimizer(learning_rate=LR, parameter_list=net.parameters())
# Record optimization results
summary_iter, summary_loss = [], []
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function
loss = net(Hamiltonian, N, D)
# In dynamic graph, run backward propogation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
# Update optimized results
summary_loss.append(loss.numpy())
summary_iter.append(itr)
# Print results
if itr % 20 == 0:
print("iter:", itr, "loss:", "%.4f" % loss.numpy())
print("iter:", itr, "Ground state energy:", "%.4f Ha" % loss.numpy())
# Save results in the 'output' directory
os.makedirs("output", exist_ok=True)
savez("./output/summary_data", iter=summary_iter, energy=summary_loss)
# Determine the dimensions of network
net = StateNet(shape=[D + 1, N, 1])
# Usually, we recommend Adam optimizer for better result. If you wish, you could use SGD or RMS prop.
opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())
# Record optimization results
summary_iter, summary_loss = [], []
# Optimization iterations
for itr in range(1, ITR + 1):
# Run forward propagation to calculate loss function
loss = net(Hamiltonian, N, D)
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
opt.clear_grad()
# Update optimized results
summary_loss.append(loss.numpy())
summary_iter.append(itr)
# Print results
if itr % 20 == 0:
print("iter:", itr, "loss:", "%.4f" % loss.numpy())
print("iter:", itr, "Ground state energy:", "%.4f Ha" % loss.numpy())
# Save results in the 'output' directory
os.makedirs("output", exist_ok=True)
savez("./output/summary_data", iter=summary_iter, energy=summary_loss)
def main():
......
......@@ -40,7 +40,7 @@ def benchmark_result():
elif sysStr == 'Linux' or sysStr == 'Darwin':
# for linux only
from paddle_quantum.VQE.chemistrygen import read_calc_H
# Harmiltonian and cnot module preparing, must be executed under Linux
# Hamiltonian and cnot module preparing, must be executed under Linux
# Read the H2 molecule data
print('Molecule data will be read from h2.xyz')
Hamiltonian, N = read_calc_H(geo_fn='h2.xyz')
......
......@@ -113,20 +113,12 @@ def read_calc_H(geo_fn, multiplicity=1, charge=0):
geo.append([species, (float(x), float(y), float(z))])
# meanfield data
mol = openfermion.hamiltonians.MolecularData(geo, 'sto-3g', multiplicity,
charge)
openfermionpyscf.run_pyscf(mol)
terms_molecular_hamiltonian = mol.get_molecular_hamiltonian(
)
fermionic_hamiltonian = openfermion.transforms.get_fermion_operator(
terms_molecular_hamiltonian)
qubit_op = openfermion.transforms.jordan_wigner(
fermionic_hamiltonian)
molecular_hamiltonian = openfermionpyscf.generate_molecular_hamiltonian(geo, 'sto-3g', multiplicity, charge)
qubit_op = openfermion.transforms.jordan_wigner(molecular_hamiltonian)
# calc H
Hamiltonian = Hamiltonian_str_convert(qubit_op)
return Hamiltonian, mol.n_qubits
return Hamiltonian, molecular_hamiltonian.n_qubits
def main():
......
......@@ -18,6 +18,7 @@ main
import platform
import paddle
from paddle_quantum.VQE.Paddle_VQE import Paddle_VQE
from paddle_quantum.VQE.benchmark import benchmark_result
from paddle_quantum.VQE.chemistrysub import H2_generator
......
......@@ -18,6 +18,7 @@ HGenerator
from numpy import diag
import scipy
import scipy.stats
SEED = 13
......
......@@ -18,10 +18,10 @@ you could check the corresponding Jupyter notebook under the Tutorial folder.
"""
import numpy
from paddle import fluid
import paddle
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.utils import dagger
from paddle.complex import matmul, trace
from paddle import matmul, trace
from paddle_quantum.VQSD.HGenerator import generate_rho_sigma
SEED = 14
......@@ -42,23 +42,23 @@ def U_theta(theta, N):
cir = UAnsatz(N)
# Use built-in template
cir.universal_2_qubit_gate(theta)
cir.universal_2_qubit_gate(theta, [0, 1])
# Return the Unitary matrix simulated by QNN
return cir.U
class Net(fluid.dygraph.Layer):
class Net(paddle.nn.Layer):
"""
Construct the model net
"""
def __init__(self, shape, rho, sigma, param_attr=fluid.initializer.Uniform(low=0.0, high=2 * numpy.pi, seed=SEED),
def __init__(self, shape, rho, sigma, param_attr=paddle.nn.initializer.Uniform(low=0.0, high=2 * numpy.pi),
dtype='float64'):
super(Net, self).__init__()
# Convert Numpy array to variable supported in PaddlePaddle
self.rho = fluid.dygraph.to_variable(rho)
self.sigma = fluid.dygraph.to_variable(sigma)
self.rho = paddle.to_tensor(rho)
self.sigma = paddle.to_tensor(sigma)
# Initialize theta by sampling from a uniform distribution [0, 2*pi]
self.theta = self.create_parameter(shape=shape, attr=param_attr, dtype=dtype, is_bias=False)
......@@ -74,10 +74,10 @@ class Net(fluid.dygraph.Layer):
# Calculate loss function
loss = trace(matmul(self.sigma, rho_tilde))
return loss.real, rho_tilde
return paddle.real(loss), rho_tilde
def Paddle_VQSD(rho, sigma, N=2, THETA_SIZE=15, ITR=50, LR=0.1):
def Paddle_VQSD(rho, sigma, N=2, THETA_SIZE=15, ITR=50, LR=0.2):
r"""
Paddle_VQSD
:param rho: Qauntum state to be diagonalized
......@@ -88,29 +88,29 @@ def Paddle_VQSD(rho, sigma, N=2, THETA_SIZE=15, ITR=50, LR=0.1):
:param LR: Learning rate
:return: Diagonalized quantum state after optimization
"""
# Initialize PaddlePaddle dynamic graph machanism
with fluid.dygraph.guard():
# Fix the dimensions of network
net = Net(shape=[THETA_SIZE], rho=rho, sigma=sigma)
# Use Adagrad optimizer
opt = fluid.optimizer.AdagradOptimizer(learning_rate=LR, parameter_list=net.parameters())
# Optimization iterations
for itr in range(ITR):
# Run forward propagation to calculate loss function and obtain energy spectrum
loss, rho_tilde = net(N)
rho_tilde_np = rho_tilde.numpy()
# In dynamic graph, run backward propogation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
# Print results
if itr % 10 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])
# Fix the dimensions of network
net = Net(shape=[THETA_SIZE], rho=rho, sigma=sigma)
# Use Adagrad optimizer
opt = paddle.optimizer.Adagrad(learning_rate=LR, parameters=net.parameters())
# Optimization iterations
for itr in range(ITR):
# Run forward propagation to calculate loss function and obtain energy spectrum
loss, rho_tilde = net(N)
rho_tilde_np = rho_tilde.numpy()
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
opt.clear_grad()
# Print results
if itr % 10 == 0:
print('iter:', itr, 'loss:', '%.4f' % loss.numpy()[0])
return rho_tilde_np
......
......@@ -18,6 +18,7 @@ Main
import numpy
import paddle
from paddle_quantum.VQSD.HGenerator import generate_rho_sigma
from paddle_quantum.VQSD.Paddle_VQSD import Paddle_VQSD
......
......@@ -17,4 +17,4 @@ Paddle Quantum Library
"""
name = "paddle_quantum"
__version__= "1.2.0"
\ No newline at end of file
__version__ = "2.0.0"
此差异已折叠。
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
......@@ -17,9 +17,7 @@ import numpy as np
from numpy import binary_repr
import paddle
import paddle.fluid as fluid
from paddle.fluid.framework import ComplexVariable
from paddle.complex.tensor.math import elementwise_mul, elementwise_add
from paddle import multiply, add, to_tensor
def dic_between2and10(n):
......@@ -87,7 +85,7 @@ def single_H_vec(H, vec):
coef, target_update = single_H_vec_i(H, dic10to2[i])
index_update = dic2to10[target_update]
new_vec[index_update] = coef * old_vec[i]
return fluid.dygraph.to_variable(new_vec)
return to_tensor(new_vec)
def H_vec(H, vec):
......@@ -97,13 +95,13 @@ def H_vec(H, vec):
Note:
这是内部函数,你并不需要直接调用到该函数。
"""
coefs = fluid.dygraph.to_variable(np.array([coef for coef, Hi in H], dtype=np.float64))
coefs = to_tensor(np.array([coef for coef, Hi in H], dtype=np.float64))
# Convert all strings to lowercase
H_list = [Hi.lower() for coef, Hi in H]
result = fluid.layers.zeros(shape=vec.shape, dtype='float64')
result = paddle.zeros(shape=vec.shape, dtype='float64')
for i in range(len(coefs)):
xi = elementwise_mul(coefs[i], single_H_vec(H_list[i], vec))
result = elementwise_add(result, xi)
xi = multiply(coefs[i], single_H_vec(H_list[i], vec))
result = add(result, xi)
return result
......@@ -114,6 +112,6 @@ def vec_expecval(H, vec):
Note:
这是内部函数,你并不需要直接调用到该函数。
"""
vec_conj = ComplexVariable(vec.real, -vec.imag)
result = paddle.complex.sum(elementwise_mul(vec_conj, H_vec(H, vec)))
vec_conj = paddle.conj(vec)
result = paddle.sum(multiply(vec_conj, H_vec(H, vec)))
return result
此差异已折叠。
此差异已折叠。
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
......@@ -296,8 +296,8 @@ def bell_diagonal_state(p1, p2, p3, p4):
[0. +0.j 0. +0.j 0.25+0.j 0. +0.j]
[0. +0.j 0. +0.j 0. +0.j 0.25+0.j]]
"""
# p4 = 1 - p1 - p2 - p3
# assert 0 <= p1 <= 1 and 0 <= p2 <= 1 and 0 <= p3 <= 1 and 0 <= p4 <= 1, "Probability must be in [0, 1]"
assert 0 <= p1 <= 1 and 0 <= p2 <= 1 and 0 <= p3 <= 1 and 0 <= p4 <= 1, "Each probability must be in [0, 1]"
assert abs(p1 + p2 + p3 + p4 - 1) < 1e-6, "The sum of probabilities should be 1"
coeff = np.sqrt(0.5)
phi_p_vec = np.array([[coeff, 0, 0, coeff]])
......
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
......@@ -14,7 +14,7 @@
from functools import reduce
import numpy
import numpy as np
from numpy import absolute, log
from numpy import diag, dot, identity
from numpy import kron as np_kron
......@@ -26,18 +26,18 @@ from numpy import sum as np_sum
from numpy import transpose as np_transpose
from numpy import zeros as np_zeros
from paddle.complex import elementwise_add
from paddle.complex import kron as pp_kron
from paddle.complex import matmul
from paddle.complex import transpose as pp_transpose
from paddle import add, to_tensor
from paddle import kron as pp_kron
from paddle import matmul
from paddle import transpose as pp_transpose
from paddle.fluid.dygraph import to_variable
from paddle.fluid.framework import ComplexVariable
from paddle.fluid.layers import concat, cos, ones, reshape, sin
from paddle.fluid.layers import zeros as pp_zeros
from paddle import concat, cos, ones, reshape, sin
from paddle import zeros as pp_zeros
from scipy.linalg import logm, sqrtm
import paddle
__all__ = [
"partial_trace",
"state_fidelity",
......@@ -61,43 +61,40 @@ def partial_trace(rho_AB, dim1, dim2, A_or_B):
r"""计算量子态的偏迹。
Args:
rho_AB (ComplexVariable): 输入的量子态
rho_AB (Tensor): 输入的量子态
dim1 (int): 系统A的维数
dim2 (int): 系统B的维数
A_or_B (int): 1或者2,1表示计算系统A上的偏迹,2表示计算系统B上的偏迹
Returns:
ComplexVariable: 输入的量子态的偏迹
Tensor: 输入的量子态的偏迹
"""
if A_or_B == 2:
dim1, dim2 = dim2, dim1
idty_np = identity(dim2).astype("complex128")
idty_B = to_variable(idty_np)
idty_B = to_tensor(idty_np)
zero_np = np_zeros([dim2, dim2], "complex128")
res = to_variable(zero_np)
res = to_tensor(zero_np)
for dim_j in range(dim1):
row_top = pp_zeros([1, dim_j], dtype="float64")
row_mid = ones([1, 1], dtype="float64")
row_bot = pp_zeros([1, dim1 - dim_j - 1], dtype="float64")
bra_j_re = concat([row_top, row_mid, row_bot], axis=1)
bra_j_im = pp_zeros([1, dim1], dtype="float64")
bra_j = ComplexVariable(bra_j_re, bra_j_im)
bra_j = concat([row_top, row_mid, row_bot], axis=1)
bra_j = paddle.cast(bra_j, 'complex128')
if A_or_B == 1:
row_tmp = pp_kron(bra_j, idty_B)
res = elementwise_add(res, matmul(matmul(row_tmp, rho_AB),
pp_transpose(ComplexVariable(row_tmp.real, -row_tmp.imag),
perm=[1, 0]), ), )
row_tmp_conj = paddle.conj(row_tmp)
res = add(res, matmul(matmul(row_tmp, rho_AB), pp_transpose(row_tmp_conj, perm=[1, 0]), ), )
if A_or_B == 2:
row_tmp = pp_kron(idty_B, bra_j)
res = elementwise_add(res, matmul(matmul(row_tmp, rho_AB),
pp_transpose(ComplexVariable(row_tmp.real, -row_tmp.imag),
perm=[1, 0]), ), )
row_tmp_conj = paddle.conj(row_tmp)
res = add(res, matmul(matmul(row_tmp, rho_AB), pp_transpose(row_tmp_conj, perm=[1, 0]), ), )
return res
......@@ -116,7 +113,7 @@ def state_fidelity(rho, sigma):
float: 输入的量子态之间的保真度
"""
assert rho.shape == sigma.shape, 'The shape of two quantum states are different'
fidelity = numpy.trace(sqrtm(sqrtm(rho) @ sigma @ sqrtm(rho))).real
fidelity = np.trace(sqrtm(sqrtm(rho) @ sigma @ sqrtm(rho))).real
return fidelity
......@@ -196,7 +193,7 @@ def relative_entropy(rho, sig):
float: 输入的量子态之间的相对熵
"""
assert rho.shape == sig.shape, 'The shape of two quantum states are different'
res = numpy.trace(rho @ logm(rho) - rho @ logm(sig))
res = np.trace(rho @ logm(rho) - rho @ logm(sig))
return res.real
......@@ -209,7 +206,7 @@ def NKron(matrix_A, matrix_B, *args):
*args (numpy.ndarray): 其余矩阵
Returns:
ComplexVariable: 输入矩阵的Kronecker积
Tensor: 输入矩阵的Kronecker积
.. code-block:: python
......@@ -229,28 +226,27 @@ def dagger(matrix):
r"""计算矩阵的埃尔米特转置,即Hermitian transpose。
Args:
matrix (ComplexVariable): 需要埃尔米特转置的矩阵
matrix (Tensor): 需要埃尔米特转置的矩阵
Returns:
ComplexVariable: 输入矩阵的埃尔米特转置
Tensor: 输入矩阵的埃尔米特转置
代码示例:
.. code-block:: python
from paddle_quantum.utils import dagger
from paddle import fluid
import numpy as np
with fluid.dygraph.guard():
rho = fluid.dygraph.to_variable(np.array([[1+1j, 2+2j], [3+3j, 4+4j]]))
print(dagger(rho).numpy())
rho = paddle.to_tensor(np.array([[1+1j, 2+2j], [3+3j, 4+4j]]))
print(dagger(rho).numpy())
::
[[1.-1.j 3.-3.j]
[2.-2.j 4.-4.j]]
"""
matrix_dagger = pp_transpose(ComplexVariable(matrix.real, -matrix.imag), perm=[1, 0])
matrix_conj = paddle.conj(matrix)
matrix_dagger = pp_transpose(matrix_conj, perm=[1, 0])
return matrix_dagger
......@@ -294,8 +290,8 @@ def pauli_str_to_matrix(pauli_str, n):
Returns:
numpy.ndarray: 输入列表对应的可观测量的矩阵形式
"""
pauli_dict = {'i': numpy.eye(2) + 0j, 'x': numpy.array([[0, 1], [1, 0]]) + 0j,
'y': numpy.array([[0, -1j], [1j, 0]]), 'z': numpy.array([[1, 0], [0, -1]]) + 0j}
pauli_dict = {'i': np.eye(2) + 0j, 'x': np.array([[0, 1], [1, 0]]) + 0j,
'y': np.array([[0, -1j], [1j, 0]]), 'z': np.array([[1, 0], [0, -1]]) + 0j}
# Parse pauli_str; 'x0,z1,y4' to 'xziiy'
new_pauli_str = []
......@@ -321,6 +317,7 @@ def pauli_str_to_matrix(pauli_str, n):
return sum(matrices)
def partial_transpose_2(density_op, sub_system=None):
r"""计算输入量子态的 partial transpose :math:`\rho^{T_A}`
......@@ -349,7 +346,7 @@ def partial_transpose_2(density_op, sub_system=None):
sys_idx = 2 if sub_system is None else 1
# Copy the density matrix and not corrupt the original one
transposed_density_op = numpy.copy(density_op)
transposed_density_op = np.copy(density_op)
if sys_idx == 2:
for j in [0, 2]:
for i in [0, 2]:
......@@ -372,13 +369,14 @@ def partial_transpose(density_op, n):
"""
# Copy the density matrix and not corrupt the original one
transposed_density_op = numpy.copy(density_op)
transposed_density_op = np.copy(density_op)
for j in range(0, 2**n, 2):
for i in range(0, 2**n, 2):
transposed_density_op[i:i+2, j:j+2] = density_op[i:i+2, j:j+2].transpose()
return transposed_density_op
def negativity(density_op):
r"""计算输入量子态的 Negativity :math:`N = ||\frac{\rho^{T_A}-1}{2}||`。
......@@ -406,12 +404,13 @@ def negativity(density_op):
# Calculate through the equivalent expression N = sum(abs(\lambda_i)) when \lambda_i<0
n = 0
eigen_val, _ = numpy.linalg.eig(density_op_T)
eigen_val, _ = np.linalg.eig(density_op_T)
for val in eigen_val:
if val < 0:
n = n + numpy.abs(val)
n = n + np.abs(val)
return n
def logarithmic_negativity(density_op):
r"""计算输入量子态的 Logarithmic Negativity :math:`E_N = ||\rho^{T_A}||`。
......@@ -438,7 +437,7 @@ def logarithmic_negativity(density_op):
n = negativity(density_op)
# Calculate through the equivalent expression
log2_n = numpy.log2(2*n + 1)
log2_n = np.log2(2*n + 1)
return log2_n
......
paddlepaddle==1.8.5
networkx>=2.4
matplotlib>=3.3.0
interval>=1.0.0
progressbar>=2.5
\ No newline at end of file
paddlepaddle>=2.0.1
scipy
networkx
matplotlib
interval
tqdm
\ No newline at end of file
......@@ -23,7 +23,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
setuptools.setup(
name='paddle-quantum',
version='1.2.0',
version='2.0.0',
author='Institute for Quantum Computing, Baidu INC.',
author_email='quantum@baidu.com',
description='Paddle Quantum is a quantum machine learning (QML) toolkit developed based on Baidu PaddlePaddle.',
......@@ -32,7 +32,7 @@ setuptools.setup(
url='http://qml.baidu.com',
packages=['paddle_quantum', 'paddle_quantum.GIBBS', 'paddle_quantum.QAOA', 'paddle_quantum.SSVQE', 'paddle_quantum.VQE', 'paddle_quantum.VQSD',
'paddle_quantum.GIBBS.example', 'paddle_quantum.QAOA.example', 'paddle_quantum.SSVQE.example', 'paddle_quantum.VQE.example', 'paddle_quantum.VQSD.example'],
install_requires=['paddlepaddle==1.8.5', 'networkx>=2.4', 'matplotlib>=3.3.0', 'interval>=1.0.0', 'progressbar>=2.5'],
install_requires=['paddlepaddle>=2.0.1', 'scipy', 'networkx', 'matplotlib', 'interval', 'tqdm'],
python_requires='>=3.6, <4',
classifiers=[
'Programming Language :: Python :: 3',
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
tutorial/Q-GAN/figures/loss.gif

130.5 KB | W: | H:

tutorial/Q-GAN/figures/loss.gif

77.8 KB | W: | H:

tutorial/Q-GAN/figures/loss.gif
tutorial/Q-GAN/figures/loss.gif
tutorial/Q-GAN/figures/loss.gif
tutorial/Q-GAN/figures/loss.gif
  • 2-up
  • Swipe
  • Onion skin
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册