提交 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,35 +253,33 @@
"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",
......@@ -267,7 +287,7 @@
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" opt.clear_grad()\n",
"\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
......@@ -277,8 +297,7 @@
" 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"
" \"%.4f Ha\" % loss.numpy())\n"
]
},
{
......@@ -297,35 +316,33 @@
"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",
......@@ -333,7 +350,7 @@
" # 在动态图机制下,反向传播极小化损失函数\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" opt.clear_grad()\n",
"\n",
" # 更新优化结果\n",
" summary_loss.append(loss.numpy())\n",
......@@ -343,7 +360,7 @@
" if itr % 20 == 0:\n",
" print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
" print(\"iter:\", itr, \"Ground state energy:\", \n",
" \"%.4f Ha\" % loss.numpy())"
" \"%.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,22 +271,20 @@
],
"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",
......@@ -277,7 +292,7 @@
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" opt.clear_grad()\n",
"\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
......@@ -306,35 +321,33 @@
"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",
......@@ -342,7 +355,7 @@
" # Under the dynamic graph mechanism, back propagation minimizes the loss function\n",
" loss.backward()\n",
" opt.minimize(loss)\n",
" net.clear_gradients()\n",
" opt.clear_grad()\n",
"\n",
" # Update optimization results\n",
" summary_loss.append(loss.numpy())\n",
......@@ -392,7 +405,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.9"
"version": "3.7.10"
},
"toc": {
"base_numbering": 1,
......
......@@ -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,26 +100,24 @@ 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)
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 = fluid.optimizer.AdamOptimizer(learning_rate=LR, parameter_list=net.parameters())
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 propogation to minimize loss function
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
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)
......@@ -132,6 +128,7 @@ def Paddle_GIBBS(hamiltonian, rho_G, N=4, N_SYS_B=3, beta=1.5, D=1, ITR=50, LR=0
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,7 +178,6 @@ 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])
......@@ -190,7 +188,7 @@ def Paddle_QAOA(classical_graph_adjacency, N, P, METHOD, ITR, LR):
raise ValueError("Wrong method called!")
# Classical optimizer
opt = fluid.optimizer.AdamOptimizer(learning_rate=LR, parameter_list=net.parameters())
opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())
# Gradient descent loop
summary_iter, summary_loss = [], []
......@@ -200,7 +198,7 @@ def Paddle_QAOA(classical_graph_adjacency, N, P, METHOD, ITR, LR):
)
loss.backward()
opt.minimize(loss)
net.clear_gradients()
opt.clear_grad()
if itr % 10 == 0:
print("iter:", itr, " loss:", "%.4f" % loss.numpy())
......@@ -208,7 +206,7 @@ def Paddle_QAOA(classical_graph_adjacency, N, P, METHOD, ITR, LR):
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,7 +263,6 @@ 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)
......
......@@ -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,7 +49,7 @@ def benchmark_QAOA(classical_graph_adjacency=None, N=None):
# Plot it
pyplot.figure(1)
loss_QAOA, = pyplot.plot(x1['iter'], x1['energy'], \
loss_QAOA, = pyplot.plot(x1['iter'], x1['energy'],
alpha=0.7, marker='', linestyle="--", linewidth=2, color='m')
benchmark, = pyplot.plot(
x1['iter'],
......@@ -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,7 +74,6 @@ 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)
......
......@@ -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
......@@ -95,16 +95,14 @@ def Paddle_SSVQE(H, N=2, THETA_SIZE=15, ITR=50, LR=0.3):
: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)
hamiltonian = paddle.to_tensor(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())
opt = paddle.optimizer.Adagrad(learning_rate=LR, parameters=net.parameters())
# Optimization iterations
for itr in range(1, ITR + 1):
......@@ -112,10 +110,10 @@ def Paddle_SSVQE(H, N=2, THETA_SIZE=15, ITR=50, LR=0.3):
# 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
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
opt.clear_grad()
# Print results
if itr % 10 == 0:
......@@ -124,6 +122,7 @@ def Paddle_SSVQE(H, N=2, THETA_SIZE=15, ITR=50, LR=0.3):
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,14 +88,11 @@ 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())
opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())
# Record optimization results
summary_iter, summary_loss = [], []
......@@ -106,10 +103,10 @@ def Paddle_VQE(Hamiltonian, N, D=2, ITR=80, LR=0.2):
# Run forward propagation to calculate loss function
loss = net(Hamiltonian, N, D)
# In dynamic graph, run backward propogation to minimize loss function
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
opt.clear_grad()
# Update optimized results
summary_loss.append(loss.numpy())
......
......@@ -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,13 +88,12 @@ 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())
opt = paddle.optimizer.Adagrad(learning_rate=LR, parameters=net.parameters())
# Optimization iterations
for itr in range(ITR):
......@@ -103,14 +102,15 @@ def Paddle_VQSD(rho, sigma, N=2, THETA_SIZE=15, ITR=50, LR=0.1):
loss, rho_tilde = net(N)
rho_tilde_np = rho_tilde.numpy()
# In dynamic graph, run backward propogation to minimize loss function
# In dynamic graph, run backward propagation to minimize loss function
loss.backward()
opt.minimize(loss)
net.clear_gradients()
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
......@@ -12,14 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
import numpy as np
import paddle.fluid as fluid
import paddle
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.utils import NKron, partial_trace, dagger
from paddle.complex import matmul, trace, elementwise_div, kron, elementwise_add, elementwise_mul
from paddle.fluid.framework import ComplexVariable
from paddle.fluid.layers import diag, sin, cos, concat, zeros, ones
from paddle import matmul, trace, divide, kron, add, multiply
from paddle import sin, cos, concat, zeros, ones, real
from paddle_quantum.state import isotropic_state, bell_state
from math import log2, sqrt
from numpy import pi as PI
......@@ -46,8 +45,8 @@ class LoccStatus(object):
"""
super(LoccStatus, self).__init__()
if state is None and prob is None and measured_result is None:
self.state = fluid.dygraph.to_variable(np.array([1], dtype=np.complex128))
self.prob = fluid.dygraph.to_variable(np.array([1], dtype=np.float64))
self.state = paddle.to_tensor(np.array([1], dtype=np.complex128))
self.prob = paddle.to_tensor(np.array([1], dtype=np.float64))
self.measured_result = ""
else:
self.state = state
......@@ -75,7 +74,7 @@ class LoccStatus(object):
def __repr__(self):
return f"state: {self.state.numpy()}\nprob: {self.prob.numpy()[0]}\nmeasured_result: {self.measured_result}"
def __str(self):
def __str__(self):
return f"state: {self.state.numpy()}\nprob: {self.prob.numpy()[0]}\nmeasured_result: {self.measured_result}"
......@@ -158,7 +157,7 @@ class LoccAnsatz(UAnsatz):
r"""添加关于 x 轴的单量子比特旋转门。
Args:
theta (Variable): 量子门的角度
theta (Tensor): 量子门的角度
which_qubit (int): 添加该门量子比特编号
"""
which_qubit = self.party[which_qubit]
......@@ -168,7 +167,7 @@ class LoccAnsatz(UAnsatz):
r"""添加关于 y 轴的单量子比特旋转门。
Args:
theta (Variable): 量子门的角度
theta (Tensor): 量子门的角度
which_qubit (int): 添加该门量子比特编号
"""
which_qubit = self.party[which_qubit]
......@@ -178,7 +177,7 @@ class LoccAnsatz(UAnsatz):
r"""添加关于 z 轴的单量子比特旋转门。
Args:
theta (Variable): 量子门的角度
theta (Tensor): 量子门的角度
which_qubit (int): 添加该门量子比特编号
"""
which_qubit = self.party[which_qubit]
......@@ -197,7 +196,7 @@ class LoccAnsatz(UAnsatz):
r"""添加一个 SWAP 门。
Args:
control (list): 作用在的 qubit 的编号,``control[0]`` 和``control[1]`` 是想要交换的位,其值都应该在 :math:`[0, m)`范围内, :math:`m` 为该参与方的量子比特数
control (list): 作用在的 qubit 的编号,``control[0]`` 和 ``control[1]`` 是想要交换的位,其值都应该在 :math:`[0, m)`范围内, :math:`m` 为该参与方的量子比特数
"""
control = [self.party[which_qubit] for which_qubit in control]
super(LoccAnsatz, self).swap(control)
......@@ -260,9 +259,9 @@ class LoccAnsatz(UAnsatz):
r"""添加一个单量子比特的旋转门。
Args:
theta (Variable): 旋转角度 :math:`\theta` 。
phi (Variable): 旋转角度 :math:`\phi` 。
lam (Variable): 旋转角度 :math:`\lambda` 。
theta (Tensor): 旋转角度 :math:`\theta` 。
phi (Tensor): 旋转角度 :math:`\phi` 。
lam (Tensor): 旋转角度 :math:`\lambda` 。
which_qubit (int): 作用在的 qubit 的编号,其值应该在 :math:`[0, m)` 范围内, :math:`m` 为该量子线路的量子比特数
"""
which_qubit = self.party[which_qubit]
......@@ -277,7 +276,7 @@ class LoccAnsatz(UAnsatz):
def weak_superposition_layer(self):
r"""添加一层旋转角度为 :math:`\pi/4` 的 Ry 门。
"""
_theta = fluid.dygraph.to_variable(np.array([np.pi / 4]))
_theta = paddle.to_tensor(np.array([np.pi / 4]))
for which_qubit in self.party.qubits:
self.ry(_theta, which_qubit)
......@@ -291,7 +290,7 @@ class LoccAnsatz(UAnsatz):
``theta`` 的维度为 ``(depth, m, 1)``
Args:
theta (Variable): Ry 门的旋转角度
theta (Tensor): Ry 门的旋转角度
depth (int): 纠缠层的深度
which_qubits(list): 作用的量子比特编号
"""
......@@ -318,7 +317,7 @@ class LoccAnsatz(UAnsatz):
``theta`` 的维度为 ``(depth, m, 3)``,最低维内容为对应的 ``u3`` 的参数 ``(theta, phi, lam)``
Args:
theta (Variable): U3 门的旋转角度
theta (Tensor): U3 门的旋转角度
depth (int): 纠缠层的深度
which_qubits(list): 作用的量子比特编号
"""
......@@ -340,7 +339,7 @@ class LoccAnsatz(UAnsatz):
r"""添加 2-qubit 通用门,这个通用门需要 15 个参数。
Args:
theta (Variable): 2-qubit 通用门的参数,其维度为 ``(15, )``
theta (Tensor): 2-qubit 通用门的参数,其维度为 ``(15, )``
which_qubits(list): 作用的量子比特编号
"""
......@@ -353,7 +352,7 @@ class LoccAnsatz(UAnsatz):
参考: https://cds.cern.ch/record/708846/files/0401178.pdf
Args:
theta (Variable): 3-qubit 通用门的参数,其维度为 ``(81, )``
theta (Tensor): 3-qubit 通用门的参数,其维度为 ``(81, )``
which_qubits(list): 作用的量子比特编号
"""
......@@ -452,7 +451,7 @@ class LoccAnsatz(UAnsatz):
self.__add_complex_block(theta[int((i - position[0]) / 2)], [i, i + 1])
class LoccNet(fluid.dygraph.Layer):
class LoccNet(paddle.nn.Layer):
r"""用于设计我们的 LOCC 下的 protocol,并进行验证或者训练。
"""
......@@ -467,8 +466,23 @@ class LoccNet(fluid.dygraph.Layer):
def set_init_status(self, state, which_qubits):
r"""对 LoccNet 的初始 LOCC 态节点进行初始化。
Warning:
该方法已弃用,请使用 ``set_init_state()`` 方法以代替。
Args:
state (Tensor): 输入的量子态的矩阵形式
which_qubits (tuple or list): 该量子态所对应的量子比特,其形式为 ``(party_id, qubit_id)`` 的 ``tuple`` ,或者由其组成的 ``list``
"""
warnings.warn('The member method set_init_status() is deprecated and please use set_init_state() instead.',
DeprecationWarning)
self.set_init_state(state, which_qubits)
def set_init_state(self, state, which_qubits):
r"""对 LoccNet 的初始 LOCC 态节点进行初始化。
Args:
state (ComplexVariable): 输入的量子态的矩阵形式
state (Tensor): 输入的量子态的矩阵形式
which_qubits (tuple or list): 该量子态所对应的量子比特,其形式为 ``(party_id, qubit_id)`` 的 ``tuple`` ,或者由其组成的 ``list``
"""
if isinstance(which_qubits, tuple):
......@@ -552,7 +566,7 @@ class LoccNet(fluid.dygraph.Layer):
Args:
status (LoccStatus or list): 输入的 LOCC 态节点,其类型应该为 ``LoccStatus`` 或者由其组成的 ``list``
state (ComplexVariable): 输入的量子态的矩阵形式
state (Tensor): 输入的量子态的矩阵形式
which_qubits (tuple or list): 指定需要被重置的量子比特编号,其形式为 ``(party_id, qubit_id)`` 的 ``tuple``,或者由其组成的 ``list``
Returns:
......@@ -664,63 +678,63 @@ class LoccNet(fluid.dygraph.Layer):
r"""进行参数化的测量。
Args:
state (ComplexVariable): 输入的量子态
state (Tensor): 输入的量子态
which_qubits (list): 测量作用的量子比特编号
result_desired (list): 期望得到的测量结果,如 ``"0"``、``"1"`` 或者 ``["0", "1"]``
theta (Variable): 测量运算的参数
result_desired (str): 期望得到的测量结果
theta (Tensor): 测量运算的参数
Returns:
ComplexVariable: 测量坍塌后的量子态
Variable:测量坍塌得到的概率
list: 测量得到的结果(0 或 1)
Tensor: 测量坍塌后的量子态
Tensor:测量坍塌得到的概率
str: 测量得到的结果
"""
n = self.get_qubit_number()
assert len(which_qubits) == len(result_desired), \
"the length of qubits wanted to be measured and the result desired should be same"
op_list = [fluid.dygraph.to_variable(np.eye(2, dtype=np.complex128))] * n
op_list = [paddle.to_tensor(np.eye(2, dtype=np.complex128))] * n
for idx in range(0, len(which_qubits)):
i = which_qubits[idx]
ele = result_desired[idx]
if int(ele) == 0:
basis0 = fluid.dygraph.to_variable(np.array([[1, 0], [0, 0]], dtype=np.complex128))
basis1 = fluid.dygraph.to_variable(np.array([[0, 0], [0, 1]], dtype=np.complex128))
rho0 = elementwise_mul(basis0, cos(theta[idx]))
rho1 = elementwise_mul(basis1, sin(theta[idx]))
rho = elementwise_add(rho0, rho1)
basis0 = paddle.to_tensor(np.array([[1, 0], [0, 0]], dtype=np.complex128))
basis1 = paddle.to_tensor(np.array([[0, 0], [0, 1]], dtype=np.complex128))
rho0 = multiply(basis0, cos(theta[idx]))
rho1 = multiply(basis1, sin(theta[idx]))
rho = add(rho0, rho1)
op_list[i] = rho
elif int(ele) == 1:
# rho = diag(concat([cos(theta[idx]), sin(theta[idx])]))
# rho = ComplexVariable(rho, zeros((2, 2), dtype="float64"))
basis0 = fluid.dygraph.to_variable(np.array([[1, 0], [0, 0]], dtype=np.complex128))
basis1 = fluid.dygraph.to_variable(np.array([[0, 0], [0, 1]], dtype=np.complex128))
rho0 = elementwise_mul(basis0, sin(theta[idx]))
rho1 = elementwise_mul(basis1, cos(theta[idx]))
rho = elementwise_add(rho0, rho1)
# rho = paddle.to_tensor(rho, zeros((2, 2), dtype="float64"))
basis0 = paddle.to_tensor(np.array([[1, 0], [0, 0]], dtype=np.complex128))
basis1 = paddle.to_tensor(np.array([[0, 0], [0, 1]], dtype=np.complex128))
rho0 = multiply(basis0, sin(theta[idx]))
rho1 = multiply(basis1, cos(theta[idx]))
rho = add(rho0, rho1)
op_list[i] = rho
else:
print("cannot recognize the results_desired.")
# rho = ComplexVariable(ones((2, 2), dtype="float64"), zeros((2, 2), dtype="float64"))
measure_operator = fluid.dygraph.to_variable(op_list[0])
print("cannot recognize the result_desired.")
# rho = paddle.to_tensor(ones((2, 2), dtype="float64"), zeros((2, 2), dtype="float64"))
measure_operator = paddle.to_tensor(op_list[0])
if n > 1:
for idx in range(1, len(op_list)):
measure_operator = kron(measure_operator, op_list[idx])
state_measured = matmul(matmul(measure_operator, state), dagger(measure_operator))
prob = trace(matmul(matmul(dagger(measure_operator), measure_operator), state)).real
state_measured = elementwise_div(state_measured, prob)
prob = real(trace(matmul(matmul(dagger(measure_operator), measure_operator), state)))
state_measured = divide(state_measured, prob)
return state_measured, prob, result_desired
def __measure_parameterless(self, state, which_qubits, result_desired):
r"""进行 01 测量。
Args:
state (ComplexVariable): 输入的量子态
state (Tensor): 输入的量子态
which_qubits (list): 测量作用的量子比特编号
result_desired (list): 期望得到的测量结果,如 ``"0"``、``"1"`` 或者 ``["0", "1"]``
result_desired (str): 期望得到的测量结果
Returns:
ComplexVariable: 测量坍塌后的量子态
ComplexVariable:测量坍塌得到的概率
list: 测量得到的结果(0 或 1)
Tensor: 测量坍塌后的量子态
Tensor:测量坍塌得到的概率
str: 测量得到的结果
"""
n = self.get_qubit_number()
assert len(which_qubits) == len(result_desired), \
......@@ -732,22 +746,22 @@ class LoccNet(fluid.dygraph.Layer):
rho[int(k), int(k)] = 1
op_list[i] = rho
if n > 1:
measure_operator = fluid.dygraph.to_variable(NKron(*op_list))
measure_operator = paddle.to_tensor(NKron(*op_list))
else:
measure_operator = fluid.dygraph.to_variable(op_list[0])
measure_operator = paddle.to_tensor(op_list[0])
state_measured = matmul(matmul(measure_operator, state), dagger(measure_operator))
prob = trace(matmul(matmul(dagger(measure_operator), measure_operator), state)).real
state_measured = elementwise_div(state_measured, prob)
prob = real(trace(matmul(matmul(dagger(measure_operator), measure_operator), state)))
state_measured = divide(state_measured, prob)
return state_measured, prob, result_desired
def measure(self, status, which_qubits, results_desired, theta=None):
r"""对 LOCC 态节点进行 01 测量或者含参测量。
Args:
state (LoccStatus or list): 输入的量子态,其类型应该为 ``LoccStatus`` 或者由其组成的 ``list``
status (LoccStatus or list): 输入的量子态,其类型应该为 ``LoccStatus`` 或者由其组成的 ``list``
which_qubits (tuple or list): 测量作用的量子比特编号,其形式为 ``(party_id, qubit_id)`` 的 ``tuple`` ,或者由其组成的 ``list``
result_desired (str or list): 期望得到的测量结果,用字符串进行表示,其类型为 ``str`` 或者由 ``str`` 组成的 ``list``
theta (Variable): 测量运算的参数,默认是 ``None``,表示 01 测量;若要使用含参测量则需要赋值
results_desired (str or list): 期望得到的测量结果,用字符串进行表示,其类型为 ``str`` 或者由 ``str`` 组成的 ``list``,如 ``"0"``、``"1"`` 或者 ``["0", "1"]``
theta (Tensor): 测量运算的参数,默认是 ``None``,表示 01 测量;若要使用含参测量则需要赋值
Returns:
LoccStatus or list: 测量后得到的 LOCC 态节点,其类型为 ``LoccStatus`` 或者由其组成的 ``list``
......
# 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.
......@@ -34,7 +34,6 @@ probability and SINGLE is by the state collapse method. Former is significant fa
import numpy as np
import paddle
import paddle.fluid
import gc
from collections import Counter
import copy
......@@ -43,72 +42,70 @@ from enum import Enum
import random
### InitPorcess ###
# InitProcess
def init_state_10(n):
"""
Generate state with n qubits
:param n: number of qubits
:return: tensor of state
"""
re1 = paddle.fluid.layers.ones([1], 'float64')
re0 = paddle.fluid.layers.zeros([2 ** n - 1], 'float64')
re = paddle.fluid.layers.concat([re1, re0])
del re1, re0
state1 = paddle.ones([1], 'float64')
state0 = paddle.zeros([2 ** n - 1], 'float64')
state = paddle.concat([state1, state0])
del state1, state0
gc.collect() # free the intermediate big data immediately
im = paddle.fluid.layers.zeros([2 ** n], 'float64')
state = paddle.fluid.ComplexVariable(re, im)
del re, im
state = paddle.cast(state, 'complex128')
gc.collect() # free the intermediate big data immediately
# print(state.numpy())
return state
def init_state_gen(n, i = 0):
def init_state_gen(n, i=0):
"""
Generate state with n qubits
:param n: number of qubits
:param i: the ith vector in computational basis
:return: tensor of state
"""
assert 0 <= i < 2**n, 'Invalid index'
assert 0 <= i < 2 ** n, 'Invalid index'
if n == 1:
re1 = paddle.fluid.layers.ones([1], 'float64')
re0 = paddle.fluid.layers.zeros([2 ** n - 1], 'float64')
state1 = paddle.ones([1], 'float64')
state0 = paddle.zeros([2 ** n - 1], 'float64')
if i == 0:
re = paddle.fluid.layers.concat([re1, re0])
state = paddle.concat([state1, state0])
else:
re = paddle.fluid.layers.concat([re0, re1])
im = paddle.fluid.layers.zeros([2 ** n], 'float64')
state = paddle.fluid.ComplexVariable(re, im)
state = paddle.concat([state0, state1])
else:
if i == 0:
re1 = paddle.fluid.layers.ones([1], 'float64')
re0 = paddle.fluid.layers.zeros([2 ** n - 1], 'float64')
re = paddle.fluid.layers.concat([re1, re0])
state1 = paddle.ones([1], 'float64')
state0 = paddle.zeros([2 ** n - 1], 'float64')
state = paddle.concat([state1, state0])
elif i == 2 ** n - 1:
re1 = paddle.fluid.layers.ones([1], 'float64')
re0 = paddle.fluid.layers.zeros([2 ** n - 1], 'float64')
re = paddle.fluid.layers.concat([re0, re1])
state1 = paddle.ones([1], 'float64')
state0 = paddle.zeros([2 ** n - 1], 'float64')
state = paddle.concat([state0, state1])
else:
re1 = paddle.fluid.layers.ones([1], 'float64')
re0 = paddle.fluid.layers.zeros([i], 'float64')
re00 = paddle.fluid.layers.zeros([2 ** n - i - 1], 'float64')
re = paddle.fluid.layers.concat([re0, re1, re00])
state1 = paddle.ones([1], 'float64')
state0 = paddle.zeros([i], 'float64')
state00 = paddle.zeros([2 ** n - i - 1], 'float64')
state = paddle.concat([state0, state1, state00])
del re1, re0
del state1, state0
try:
del state00
except NameError:
pass
gc.collect() # free the intermediate big data immediately
im = paddle.fluid.layers.zeros([2 ** n], 'float64')
state = paddle.fluid.ComplexVariable(re, im)
del re, im
state = paddle.cast(state, 'complex128')
gc.collect() # free the intermediate big data immediately
return state
return state
### DEFINE_GATE ###
# Define gate
def x_gate_matrix():
"""
Pauli x
......@@ -154,20 +151,22 @@ def u_gate_matrix(params):
"""
theta, phi, lam = params
if (type(theta) is paddle.fluid.core_avx.VarBase and
type(phi) is paddle.fluid.core_avx.VarBase and
type(lam) is paddle.fluid.core_avx.VarBase):
re_a = paddle.fluid.layers.cos(theta / 2)
re_b = - paddle.fluid.layers.cos(lam) * paddle.fluid.layers.sin(theta / 2)
re_c = paddle.fluid.layers.cos(phi) * paddle.fluid.layers.sin(theta / 2)
re_d = paddle.fluid.layers.cos(phi + lam) * paddle.fluid.layers.cos(theta / 2)
im_a = paddle.fluid.layers.zeros([1], 'float64')
im_b = - paddle.fluid.layers.sin(lam) * paddle.fluid.layers.sin(theta / 2)
im_c = paddle.fluid.layers.sin(phi) * paddle.fluid.layers.sin(theta / 2)
im_d = paddle.fluid.layers.sin(phi + lam) * paddle.fluid.layers.cos(theta / 2)
re = paddle.fluid.layers.reshape(paddle.fluid.layers.concat([re_a, re_b, re_c, re_d]), [2, 2])
im = paddle.fluid.layers.reshape(paddle.fluid.layers.concat([im_a, im_b, im_c, im_d]), [2, 2])
return paddle.fluid.framework.ComplexVariable(re, im)
if (type(theta) is paddle.Tensor and
type(phi) is paddle.Tensor and
type(lam) is paddle.Tensor):
re_a = paddle.cos(theta / 2)
re_b = - paddle.cos(lam) * paddle.sin(theta / 2)
re_c = paddle.cos(phi) * paddle.sin(theta / 2)
re_d = paddle.cos(phi + lam) * paddle.cos(theta / 2)
im_a = paddle.zeros([1], 'float64')
im_b = - paddle.sin(lam) * paddle.sin(theta / 2)
im_c = paddle.sin(phi) * paddle.sin(theta / 2)
im_d = paddle.sin(phi + lam) * paddle.cos(theta / 2)
re = paddle.reshape(paddle.concat([re_a, re_b, re_c, re_d]), [2, 2])
im = paddle.reshape(paddle.concat([im_a, im_b, im_c, im_d]), [2, 2])
return re + im * paddle.to_tensor([1j], 'complex128')
elif (type(theta) is float and
type(phi) is float and
type(lam) is float):
......@@ -182,10 +181,9 @@ def u_gate_matrix(params):
# compare the paddle and np version, they should be equal
# a = u_gate_matrix([1.0, 2.0, 3.0])
# print(a)
# with paddle.fluid.dygraph.guard():
# a = u_gate_matrix([paddle.fluid.dygraph.to_variable(np.array([1.0])),
# paddle.fluid.dygraph.to_variable(np.array([2.0])),
# paddle.fluid.dygraph.to_variable(np.array([3.0]))])
# a = u_gate_matrix([paddle.to_tensor(np.array([1.0])),
# paddle.to_tensor(np.array([2.0])),
# paddle.to_tensor(np.array([3.0]))])
# print(a.numpy())
......@@ -197,7 +195,8 @@ def cx_gate_matrix():
return np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]], dtype=complex).reshape(2, 2, 2, 2)
[0, 0, 1, 0]], dtype=complex).reshape((2, 2, 2, 2))
def swap_gate_matrix():
"""
......@@ -210,7 +209,7 @@ def swap_gate_matrix():
[0, 0, 0, 1]], dtype=complex).reshape(2, 2, 2, 2)
### PaddleE ###
# PaddleE
def normalize_axis(axis, ndim):
if axis < 0:
axis += ndim
......@@ -261,7 +260,7 @@ def moveaxis(m, source, destination):
for dest, src in sorted(zip(destination, source)):
order.insert(dest, src)
result = paddle.fluid.layers.transpose(m, order)
result = paddle.transpose(m, order)
return result
......@@ -284,25 +283,26 @@ def complex_moveaxis(m, source, destination):
for dest, src in sorted(zip(destination, source)):
order.insert(dest, src)
result = paddle.complex.transpose(m, order)
result = paddle.transpose(m, order)
return result
def complex_abs(m):
# check1 = np.abs(m.numpy())
re = paddle.fluid.layers.elementwise_mul(m.real, m.real)
im = paddle.fluid.layers.elementwise_mul(m.imag, m.imag)
m = paddle.fluid.layers.elementwise_add(re, im)
m = paddle.fluid.layers.sqrt(m) # m = paddle.fluid.layers.elementwise_pow(m, paddle.fluid.layers.ones_like(m) * 0.5)
# check2 = m.numpy()
# assert (check1 == check2).all()
return m
# def complex_abs(m):
# # check1 = np.abs(m.numpy())
#
# re = paddle.multiply(paddle.real(m), paddle.real(m))
# im = paddle.multiply(paddle.imag(m), paddle.imag(m))
# m = paddle.add(re, im)
# m = paddle.sqrt(m)
# # m = paddle.pow(m, paddle.ones_like(m) * 0.5)
#
# # check2 = m.numpy()
# # assert (check1 == check2).all()
#
# return m
### TransferProcess ###
# TransferProcess
def transfer_state(state, gate_matrix, bits):
"""
Transfer to the next state
......@@ -312,9 +312,10 @@ def transfer_state(state, gate_matrix, bits):
:return:
"""
assert type(gate_matrix) is np.ndarray or type(gate_matrix) is paddle.fluid.framework.ComplexVariable
assert (type(gate_matrix) is np.ndarray) or \
(type(gate_matrix) is paddle.Tensor and gate_matrix.dtype.name == "COMPLEX128")
assert type(state) is paddle.fluid.ComplexVariable and len(state.shape) == 1
assert type(state) is paddle.Tensor and state.dtype.name == "COMPLEX128" and len(state.shape) == 1
# calc source_pos target_pos
n = int(np.log2(state.shape[0]))
source_pos = copy.deepcopy(bits) # copy bits, it should NOT change the order of bits
......@@ -323,8 +324,8 @@ def transfer_state(state, gate_matrix, bits):
target_pos = list(range(len(bits)))
# ### check
# state_check = transfer_state(paddle.complex.reshape(state, [2] * n), gate_matrix, bits)
# state_check = paddle.complex.reshape(state_check, [2 ** n])
# state_check = transfer_state(paddle.reshape(state, [2] * n), gate_matrix, bits)
# state_check = paddle.reshape(state_check, [2 ** n])
# compressed moveaxis
# compress the continuous dim before moveaxis
......@@ -346,31 +347,31 @@ def transfer_state(state, gate_matrix, bits):
# print('->')
# print(compressed_shape)
# print(compressed_source_pos) # always [1], [1, 3], or [3, 1]
state = paddle.complex.reshape(state, compressed_shape_before_moveaxis)
state = paddle.reshape(state, compressed_shape_before_moveaxis)
state = complex_moveaxis(state, compressed_source_pos, target_pos)
compressed_shape_after_moveaxis = state.shape
# reshape
state_new_shape = [2 ** len(bits), 2 ** (n - len(bits))]
state = paddle.complex.reshape(state, state_new_shape)
state = paddle.reshape(state, state_new_shape)
# gate_matrix
if type(gate_matrix) is np.ndarray:
gate_new_shape = [2 ** (len(gate_matrix.shape) - len(bits)), 2 ** len(bits)]
gate_matrix = gate_matrix.reshape(gate_new_shape)
gate_matrix = paddle.fluid.dygraph.to_variable(gate_matrix)
elif type(gate_matrix) is paddle.fluid.framework.ComplexVariable:
gate_matrix = paddle.to_tensor(gate_matrix)
elif type(gate_matrix) is paddle.Tensor and gate_matrix.dtype.name == "COMPLEX128":
pass
else:
assert False
# matmul
state = paddle.complex.matmul(gate_matrix, state)
state = paddle.matmul(gate_matrix, state)
# restore compressed moveaxis reshape
state = paddle.complex.reshape(state, compressed_shape_after_moveaxis)
state = paddle.reshape(state, compressed_shape_after_moveaxis)
state = complex_moveaxis(state, target_pos, compressed_source_pos)
state = paddle.complex.reshape(state, [2 ** n])
state = paddle.reshape(state, [2 ** n])
# ### check
# assert (np.all(state.numpy() == state_check.numpy()))
......@@ -378,8 +379,8 @@ def transfer_state(state, gate_matrix, bits):
return state
### StateTranfer ###
def StateTranfer(state, gate_name, bits, params=None):
# StateTransfer
def StateTransfer(state, gate_name, bits, params=None):
"""
To transfer state by only gate name and bits
:param state: the last step state, can be init vector or the last step vector.
......@@ -416,7 +417,7 @@ def StateTranfer(state, gate_name, bits, params=None):
return state
### MeasureProcess ###
# MeasureProcess
class MEAS_METHOD(Enum):
"""
To control the measure method
......@@ -513,10 +514,10 @@ def measure_by_probability(state, times):
"""
# print("Measure method Probability")
assert type(state) is paddle.fluid.ComplexVariable and len(state.shape) == 1
assert type(state) is paddle.Tensor and state.dtype.name == "COMPLEX128" and len(state.shape) == 1
n = int(np.log2(state.shape[0]))
prob_array = complex_abs(state) # complex -> real
prob_array = paddle.fluid.layers.elementwise_mul(prob_array, prob_array)
prob_array = paddle.abs(state) # complex -> real
prob_array = paddle.multiply(prob_array, prob_array)
prob_array = prob_array.numpy()
gc.collect()
......@@ -536,11 +537,11 @@ def measure_by_probability(state, times):
samples = np.random.choice(range(2 ** n), times, p=prob_array)
count_samples = Counter(samples)
result = {}
for idex in count_samples:
for idx in count_samples:
"""
result[prob_key[idex]] = count_samples[idex]
result[prob_key[idx]] = count_samples[idx]
"""
result[oct_to_bin_str(idex, n)] = count_samples[idex]
result[oct_to_bin_str(idx, n)] = count_samples[idx]
return result
......@@ -559,7 +560,7 @@ def measure_state(state, shots):
raise Exception("Measure Error")
### RandomCircuit ###
# RandomCircuit
def GenerateRandomCirc(state, circ_depth, n):
"""
Generate random circ
......@@ -576,7 +577,7 @@ def GenerateRandomCirc(state, circ_depth, n):
rand_gate_bits = random.sample(range(n), 2)
else:
rand_gate_bits = random.sample(range(n), 1)
internal_state = StateTranfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
internal_state = StateTransfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
state = internal_state
return state
......@@ -603,19 +604,19 @@ def GenerateRandomCircAndRev(state, circ_depth, n):
rand_gate_pos_all.append(rand_gate_pos)
rand_gate_bits_all.append(rand_gate_bits)
internal_state = StateTranfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
internal_state = StateTransfer(internal_state, gate_string[rand_gate_pos], rand_gate_bits)
rand_gate_pos_all = list(reversed(rand_gate_pos_all))
rand_gate_bits_all = list(reversed(rand_gate_bits_all))
for idex, item in enumerate(rand_gate_pos_all):
internal_state = StateTranfer(internal_state, gate_string[item], rand_gate_bits_all[idex])
internal_state = StateTransfer(internal_state, gate_string[item], rand_gate_bits_all[idex])
state = internal_state
return state
### Tester ###
# Tester
def RandomTestIt(bits_num, circ_num):
"""
Random Check
......@@ -645,9 +646,9 @@ def Test_x_h_CNOT(): # 3 bits coverage test
"""
state = init_state_10(3)
state = StateTranfer(state, 'x', [0])
state = StateTranfer(state, 'h', [1])
state = StateTranfer(state, 'CNOT', [1, 2])
state = StateTransfer(state, 'x', [0])
state = StateTransfer(state, 'h', [1])
state = StateTransfer(state, 'CNOT', [1, 2])
re = measure_state(state, 2 ** 10)
# print(re)
assert ('001' in list(re.keys()) and '111' in list(re.keys()))
......@@ -662,14 +663,14 @@ def Test_cnot_1():
"""
state = init_state_10(3)
state = StateTranfer(state, 'h', [0])
state = StateTranfer(state, 'CNOT', [0, 1])
state = StateTranfer(state, 'CNOT', [0, 2])
state = StateTranfer(state, 'CNOT', [1, 2])
state = StateTranfer(state, 'CNOT', [1, 2])
state = StateTranfer(state, 'CNOT', [0, 2])
state = StateTranfer(state, 'CNOT', [0, 1])
state = StateTranfer(state, 'h', [0])
state = StateTransfer(state, 'h', [0])
state = StateTransfer(state, 'CNOT', [0, 1])
state = StateTransfer(state, 'CNOT', [0, 2])
state = StateTransfer(state, 'CNOT', [1, 2])
state = StateTransfer(state, 'CNOT', [1, 2])
state = StateTransfer(state, 'CNOT', [0, 2])
state = StateTransfer(state, 'CNOT', [0, 1])
state = StateTransfer(state, 'h', [0])
re = measure_state(state, 2 ** 10)
assert ('000' in list(re.keys()))
assert (2 ** 10 in list(re.values()))
......@@ -683,14 +684,14 @@ def Test_cnot_2():
"""
state = init_state_10(3)
state = StateTranfer(state, 'h', [2])
state = StateTranfer(state, 'CNOT', [2, 1])
state = StateTranfer(state, 'CNOT', [2, 0])
state = StateTranfer(state, 'CNOT', [1, 0])
state = StateTranfer(state, 'CNOT', [1, 0])
state = StateTranfer(state, 'CNOT', [2, 0])
state = StateTranfer(state, 'CNOT', [2, 1])
state = StateTranfer(state, 'h', [2])
state = StateTransfer(state, 'h', [2])
state = StateTransfer(state, 'CNOT', [2, 1])
state = StateTransfer(state, 'CNOT', [2, 0])
state = StateTransfer(state, 'CNOT', [1, 0])
state = StateTransfer(state, 'CNOT', [1, 0])
state = StateTransfer(state, 'CNOT', [2, 0])
state = StateTransfer(state, 'CNOT', [2, 1])
state = StateTransfer(state, 'h', [2])
re = measure_state(state, 2 ** 10)
assert ('000' in list(re.keys()))
assert (2 ** 10 in list(re.values()))
......@@ -705,7 +706,7 @@ def Test3All():
return Test_x_h_CNOT() and Test_cnot_1() and Test_cnot_2()
### Sim2Main ###
# Sim2Main
def main(bits_num=None, circ_num=None):
"""
:param bits_num: the number of qubits
......@@ -727,18 +728,18 @@ def main(bits_num=None, circ_num=None):
state = init_state_10(bits_num)
# ------------------tik-------
# state = StateTranfer(state, 'h', [0])
# state = StateTranfer(state, 'x', [1])
# state = StateTranfer(state, 'x', [2])
# state = StateTranfer(state, 'u', [3], [0.3, 0.5, 0.7])
# state = StateTranfer(state, 'CNOT', [0, 1])
# state = StateTranfer(state, 'CNOT', [2, 1])
# state = StateTransfer(state, 'h', [0])
# state = StateTransfer(state, 'x', [1])
# state = StateTransfer(state, 'x', [2])
# state = StateTransfer(state, 'u', [3], [0.3, 0.5, 0.7])
# state = StateTransfer(state, 'CNOT', [0, 1])
# state = StateTransfer(state, 'CNOT', [2, 1])
# -----------------tok---------
# ------------------tik-------
state = StateTranfer(state, 'x', [0])
state = StateTranfer(state, 'h', [1])
#state = StateTranfer(state, 'CNOT', [0, 1])
state = StateTransfer(state, 'x', [0])
state = StateTransfer(state, 'h', [1])
# state = StateTransfer(state, 'CNOT', [0, 1])
# -----------------tok---------
# ------------------tik-------
......@@ -767,11 +768,11 @@ def Tester(bits_num=None, circ_num=None):
if __name__ == '__main__':
with paddle.fluid.dygraph.guard():
paddle.set_device('cpu')
# main(bits_num=5, circ_num=50)
main(bits_num=5)
# RandomTestIt(bits_num=5, circ_num=50)
# print(Test3All())
# print(Tester(bits_num=5, circ_num=50))
#Tester(bits_num=6, circ_num=100)
# Tester(bits_num=6, circ_num=100)
# 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]])
......
此差异已折叠。
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.
先完成此消息的编辑!
想要评论请 注册