{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Simulating noisy quantum circuits with Paddle Quantum\n", "\n", " Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction to quantum noises\n", "\n", "In ideal models, we usually assume that quantum circuits are operating on a **closed physical system**. However, real quantum devices suffer from **incoherent noises** introduced by unwanted interactions between the system and the environment. This type of noise can significantly change the performance of quantum computation tasks and hence can hardly be ignored for near-term quantum devices. Consequently, designing robust quantum algorithms under the presence of noise is crucial for utilizing quantum computation in the real world. With the noise module of Paddle Quantum, we can now not only design and simulate quantum algorithms but also examine various noises' influence and further develop error mitigation schemes.\n", "\n", "## Building noise models in Paddle Quantum\n", "\n", "### Noise model and quantum channel\n", " \n", "The evolution of a closed quantum system is always unitary. Mathematically, we can describe such a process as implementing a parameterized quantum circuit $U(\\vec{\\theta})$,\n", "\n", "$$\n", "\\rho \\longrightarrow U(\\vec{\\theta}) \\rho U^\\dagger(\\vec{\\theta}),\n", "\\tag{1}\n", "$$\n", "\n", "where $\\rho$ is the initial quantum state, $\\vec{\\theta}$ is a vector containing all the parameters. The most intuitive type of noise one can think of is the error that appears in these parameters, \n", "$$\n", "\\rho \\longrightarrow U(\\vec{\\theta}+\\vec{\\epsilon}) \\rho U^\\dagger(\\vec{\\theta}+\\vec{\\epsilon}),\n", "\\tag{2}\n", "$$\n", "\n", "$\\vec{\\epsilon}$ can be a white noise sampled from Gaussian distributions. This kind of noise is a specific example of **coherent noises**. Coherent noise usually occurs due to device calibration errors or quantum control errors. We want to emphasize that one also uses unitary transformation $U(\\vec{\\epsilon})$ to describe coherent noises. In certain cases, coherent noises can be more damaging than incoherent noises [1]. \n", "\n", "Most of the time, the real problem lies on the evolution of an **open quantum system** that is non-unitary. Under this circumstance, we need a more general description beyond the unitary transformation to characterize incoherent noises, the language of **quantum channels**. To keep the discussion precise, we use *operator-sum representation* [2] to introduce a quantum channel as \n", "\n", "$$\n", "\\mathcal{E}(\\rho) = \\sum_{k=0}^{m-1} E_k \\rho E_k^{\\dagger},\n", "\\tag{3}\n", "$$\n", "\n", "where $\\{E_k\\}$ are *Kraus* operators, and they satisfy the completeness condition $\\sum_k E_k^\\dagger E_k = I$. Mathematically, a quantum channel is completely positive and trace-preserving [2].\n", "\n", "Under this representation, we can explicitly observe the results of implementing a quantum channel: Suppose we start with a pure state $\\rho = |\\psi\\rangle\\langle \\psi|$, then we send it through a noisy quantum channel (e.g., $m = 2$ ). Eventually, we will get a mixed state $\\mathcal{E}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger$. Let's take the bit flip noise as an example: \n", "\n", "$$\n", "\\mathcal{E}_{BF}(\\rho) = (1 - p) I \\rho I+ p X \\rho X,\n", "\\tag{4}\n", "$$\n", "\n", "where $X,I$ are Pauli operators. The corresponding *Kraus* operators are:\n", "\n", "$$\n", "E_0 = \\sqrt{1-p}\n", "\\begin{bmatrix}\n", "1&0 \\\\\n", "0&1\n", "\\end{bmatrix},\n", "E_1 = \\sqrt{p}\n", "\\begin{bmatrix}\n", "0& 1 \\\\\n", "1 &0\n", "\\end{bmatrix}.\n", "\\tag{5}\n", "$$\n", "\n", "The physical meaning of this quantum channel is there exist a probability $p$ that the state $|0\\rangle$ will flip into $|1\\rangle$, and vice versa. In Paddle Quantum, we can use this quantum channel by `Circuit.bit_flip(p, which_qubit)`, where `p` is the noise level.\n", "\n", "**Note:** For a quantum channel, the Kraus operator representation is not necessarily unique [3]." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Implementation with Paddle Quantum\n", "\n", "In this section, we will learn how to build a noise model in Paddle Quantum. First, we initialize a qubit to $|0\\rangle$. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T02:32:24.919291Z", "start_time": "2021-04-09T02:32:22.237264Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/openfermion/hamiltonians/hartree_fock.py:11: DeprecationWarning: Please use `OptimizeResult` from the `scipy.optimize` namespace, the `scipy.optimize.optimize` namespace is deprecated.\n", " from scipy.optimize.optimize import OptimizeResult\n", "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n", "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n", " if data.dtype == np.object:\n", "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n", "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n", " if data.dtype == np.object:\n", "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/fluid/framework.py:1104: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here.\n", "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n", " elif dtype == np.bool:\n" ] }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEDCAYAAAA4FgP0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAARcklEQVR4nO3debRdZX3G8e+TMKngBKlVkgDW0DYOoEZwaQdUsGBVnKogDlgktoKVpdJiq2DRrjq7akVrHCrqEkSrNNUIWgVtHQnIYILRiCBBXYIgDlQQ+fWPs5HD5d57TvDuc0ne72ets+7e7373Pr9kZe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a4O7Ajgze6HcrSXYEHgF8ZDDaBcDIeQ5pXAaBtmbrGQz//EY3NPS7DIZ0HsCtz4p3mOVYmz2GWlUXARcl+QDwXaYPgvcBT6qqC5IcDuw3TZ8FwE+qau/NrUEah0ND2pp9FrhzkucAJFkIvAl4Wzd2fymwd5IFSZYwuOv6Zgu4JUSeCfzvNMf/GbDT1MYkOybZb6hpb255xtPUfXYCftBNMB823bG74azvJvmL7vhJstdsf3BpcxgE2mrV4EqIJwNP656x9GPgpqr6p67LFxn8pr4eeCtw3tDuvwD2SfINBhO6J07zFauAM5KcNaU9wN8m2ZDkfOAfueVs4FTg2O7S0t8DXgl8tatlePJ3ar/DgCOSXACsY/BeCWlOeNWQmtFdtXMK8OSqOm9Uf6kVBoEkNc6hIUlqnEEgSY0zCCSpcQaBJDXOIJCkxhkEktQ4g0CSGvf/vuhhSsmwwdkAAAAASUVORK5CYII=", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" }, { "data": { "text/plain": [ "{'0': 1.0, '1': 0.0}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import paddle_quantum\n", "from paddle_quantum.ansatz import Circuit\n", "\n", "# Change to density matrix mode\n", "paddle_quantum.set_backend('density_matrix')\n", "\n", "# Define the number of qubits, here we use one single qubit\n", "num_qubits = 1\n", "\n", "# Initialize the quantum circuit\n", "cir = Circuit(num_qubits)\n", "\n", "# Initialize the qubit to |0><0| \n", "init_state = paddle_quantum.state.zero_state(num_qubits)\n", "\n", "# Mesure in the computational basis \n", "cir(init_state).measure(shots = 1024, plot = True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we add a bit flip channel with $p=0.1$, and measure the qubit after this channel.\n", "**Note:** Noisy module in Paddle Quantum only supports density matrix operation mode." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T02:32:25.168455Z", "start_time": "2021-04-09T02:32:24.926709Z" }, "scrolled": true }, "output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g9DPgicOKM47wT+C7wpOEQ6Lb9kMHb965IcmqSI5LMq6ovd+3HVdVeVfUt4GNV9ZjuzOFi4KiN9FsJvLyqHg28Gnj3Zv9vSBvhfQTSaLcAH+6WP8hgiGliVfXiJI8A9mfwi/sA4MgRXR+e5I3AfYEdGbzR73aS7Ag8HvjIYLQLgLHzHNKkDALNZesYDP/8Wjc09JsMhnQezu3PinfYxLE2ewy1qi4CLkryAeDbjA6C9wPPrKoLkhwJ7DeizzzgR1W11+bWIE3CoSHNZZ8H7pnkjwCSzAfeDryrG7u/HNgrybwkixjcdX2redwWIs8H/mfE8W8EdprZmGTHJPsNNe3Fbc94mrnPTsD3ugnmI0YduxvO+naSP+yOnyR7buofLm0Og0BzVg2uhHgW8JzuGUvXAbdU1d92Xc5h8Jf6OuCdwHlDu/8U2CfJ/zKY0D1pxLdYCXwmyVkz2gP8RZL1Sc4H/obbzgZOA47rLi39LeB1wNe6WoYnf2f2OwI4KskFwFoG75WQtgivGlIzuqt2TgWeVVXnjesvtcIgkKTGOTQkSY0zCCSpcQaBJDXOIJCkxhkEktQ4g0CSGmcQSFLj/h+FihdAQLomqQAAAABJRU5ErkJggg==", "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Quantum state after the bit flip quantum channel:\n", " [[0.8999999+0.j 0. +0.j]\n", " [0. +0.j 0.1 +0.j]]\n" ] } ], "source": [ "# Noise level\n", "p = 0.1\n", "\n", "# Add the bit flip noisy channel\n", "cir.bit_flip(p, 0)\n", "\n", "# Execute the circuit\n", "# Note: Noisy module in Paddle Quantum only supports density matrix operation mode\n", "fin_state = cir(init_state)\n", "\n", "# Measure in the computational basis\n", "fin_state.measure(shots = 1024, plot = True)\n", "print('Quantum state after the bit flip quantum channel:\\n', fin_state.data.numpy())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see, the quantum state has been transformed to a mixed state $0.9 | 0 \\rangle \\langle 0 | + 0.1 | 1 \\rangle \\langle 1 |$ (with probability $p=0.1$ ) after the bit flip channel.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Common quantum channels\n", "\n", "Paddle Quantum supports many other common noisy channels.\n", "\n", "- **Phase Flip Channel**\n", "\n", " Similar to the bit-flip channel, the phase flip channel flips the phase of a qubit with probability $p$, \n", " \n", " $$\n", " \\mathcal{E}_{PF}(\\rho) = (1 - p) \\rho + p Z \\rho Z.\n", " \\tag{6}\n", " $$\n", "\n", "\n", "- **Bit-Phase Flip Channel**\n", "\n", " $$\n", " \\mathcal{E}_{BPF}(\\rho) = (1-p) \\rho + p Y \\rho Y.\n", " \\tag{7}\n", " $$\n", "\n", "\n", "- **Depolarizing Channel**\n", "\n", " The quantum state will be in the maximally mixed state $I/2$ with probability $p$ or in the original state with probability $1-p$ after the single qubit depolarizing channel. The depolarizing channel can also be understood as applying Pauli noises symmetrically, \n", " \n", " $$\n", " \\mathcal{E}_{D}(\\rho) = (1 - p) \\rho + \\frac{p}{3}\n", " \\left( X \\rho X+ Y \\rho Y + Z \\rho Z \\right).\n", " \\tag{8}\n", " $$\n", "\n", "\n", "- **Pauli Channel**\n", "\n", " The Pauli channel applies Pauli noises asymmetrically, \n", " \n", " $$\n", " \\mathcal{E}_{Pauli}(\\rho) = (1 - p_x - p_y - p_z) \\rho + p_x X \\rho X + p_y Y \\rho Y + p_z Z \\rho Z.\n", " \\tag{9}\n", " $$\n", "\n", "\n", "- **Amplitude Damping Channel**\n", "\n", " The amplitude damping channel can be used to model the process of **energy dissipation**, \n", " \n", " $$\n", " \\mathcal{E}_{AD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n", " \\tag{10}\n", " $$\n", " \n", " where $\\gamma$ is the damping factor,\n", " \n", " $$\n", " E_0 = \n", " \\begin{bmatrix}\n", " 1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n", " \\end{bmatrix},\n", " E_1 = \n", " \\begin{bmatrix}\n", " 0 & \\sqrt{\\gamma} \\\\ 0 & 0\n", " \\end{bmatrix}.\n", " \\tag{11}\n", " $$ \n", "\n", "\n", "- **Phase Damping Channel**\n", "\n", " The phase damping channel describes the loss of **quantum information** without loss of energy, \n", " \n", " $$\n", " \\mathcal{E}_{PD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n", " \\tag{12}\n", " $$\n", " \n", " where $\\gamma$ is the damping factor,\n", " \n", " $$\n", " E_0 = \n", " \\begin{bmatrix}\n", " 1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n", " \\end{bmatrix}, \n", " E_1 = \n", " \\begin{bmatrix}\n", " 0 & 0 \\\\ 0 & \\sqrt{\\gamma}\n", " \\end{bmatrix}.\n", " \\tag{13}\n", " $$\n", "\n", "\n", "- **Generalized Amplitude Damping Channel**\n", "\n", " The generalized amplitude damping channel describes energy exchange between the system and the environment at **finite temperatures**. It is a common noise in superconducting quantum computations [4]. Interested readers can find more information here [API document](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html).\n", "\n", "\n", "**Note:** In Paddle Quantum, we can use these noisy channels through `Circuit.phase_flip()`, `Circuit.bit_phase_flip()`, `Circuit.depolarizing()`, `Circuit.pauli_channel()`, `Circuit.amplitude_damping()`, `Circuit.phase_damping()`, and `Circuit.generalized_amplitude_damping()`.\n", "\n", "**Note:** One usually choose the amplitude damping channel and the phase damping channel to model noises since they describe the physical process in real quantum systems (modeling $T_1$ and $T_2$ process)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Customized Channel\n", "\n", "One can also use `Circuit.customized_channel()` in Paddle Quantum to add customized noisy channels. This is accomplished through user-defined Kraus operators. Here, we provide an example to reproduce the bit flip channel using customized_channel function:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T02:54:20.758898Z", "start_time": "2021-04-09T02:54:20.599327Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "quantum state after the customized channel:\n", " [[0.90000004+0.j 0. +0.j]\n", " [0. +0.j 0.1 +0.j]]\n", "\n", " quantum state after the bit flip channel:\n", " [[0.8999999+0.j 0. +0.j]\n", " [0. +0.j 0.1 +0.j]]\n", "\n", " are the two the same? True\n" ] } ], "source": [ "import paddle\n", "import numpy as np\n", "\n", "# Noise level\n", "p = 0.1\n", "\n", "# We use customized Kraus operator to represent the bit flip channel\n", "complex_dtype = paddle_quantum.get_dtype()\n", "a_0 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[1, 0], [0, 1]], dtype=complex_dtype))\n", "a_1 = paddle.to_tensor(np.sqrt(p) * np.array([[0, 1], [1, 0]], dtype=complex_dtype))\n", "Kraus_ops = [a_0, a_1]\n", "\n", "# Initialize the circuit\n", "num_qubits = 1\n", "cir = Circuit(num_qubits)\n", "\n", "# Add customized channel, input is a list of Kraus operators\n", "cir.kraus_channel(Kraus_ops, 0)\n", "\n", "# Execute the circuit\n", "fin_state = cir(init_state)\n", "\n", "# Compare the results\n", "cir_1 = Circuit(num_qubits)\n", "cir_1.bit_flip(p, 0)\n", "fin_state_1 = cir_1(init_state)\n", "print('quantum state after the customized channel:\\n', fin_state.data.numpy())\n", "print('\\n quantum state after the bit flip channel:\\n', fin_state_1.data.numpy())\n", "print('\\n are the two the same?', bool((fin_state.data - fin_state_1.data).abs().sum() < 1e-6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Discussion: Simulating noisy entanglement resources with Paddle Quantum\n", "\n", "Many important quantum technologies require pre-shared entanglement resources, including quantum teleportation, state transformation, and distributed quantum computing. For instance, we want the allocated entanglement resources are in **maximally entangled states** under ideal circumstances. But in reality, noise always exists due to interactions between the system and the environment during preparation stage, transmission, and preservation. Here, we use the depolarizing channel to simulate how a white noise could affect Bell states: " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T02:58:30.352039Z", "start_time": "2021-04-09T02:58:30.311223Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fidelity between the initial state and the Bell state 1\n", "after transmission (depolarizing channel), the fidelity between the entangled state and Bell state 0.85750\n", "after preservation (amplitude damping channel), the fidelity between the entangled state and Bell state 0.73556\n" ] } ], "source": [ "import paddle\n", "from paddle import matmul, trace\n", "from paddle_quantum.ansatz import Circuit\n", "from paddle_quantum.state import bell_state\n", "\n", "# Noise level\n", "p_trans = 0.1\n", "p_store = 0.01\n", "\n", "# Initialize the circuit\n", "num_qubits = 2\n", "cir = Circuit(num_qubits)\n", "\n", "# The initial state is Bell state\n", "init_state = bell_state(2)\n", "\n", "# Apply the depolarizing channel to each qubit, modeling the noise introduced by transmission\n", "cir.depolarizing(p_trans, 0)\n", "cir.depolarizing(p_trans, 1)\n", "\n", "# Execute the circuit \n", "status_mid = cir(init_state)\n", "\n", "# Apply the amplitude damping channel to each qubit, modeling the noise introduced by storage\n", "cir.amplitude_damping(p_store, 0)\n", "cir.amplitude_damping(p_store, 1)\n", "\n", "# Execute the circuit\n", "status_fin = cir(status_mid)\n", "fidelity_mid = paddle.real(trace(matmul(init_state.data, status_mid.data)))\n", "fidelity_fin = paddle.real(trace(matmul(init_state.data, status_fin.data)))\n", "\n", "print(\"Fidelity between the initial state and the Bell state\", 1)\n", "print(\"after transmission (depolarizing channel), the fidelity between the entangled state and Bell state {:.5f}\".format(fidelity_mid.numpy()[0]))\n", "print(\"after preservation (amplitude damping channel), the fidelity between the entangled state and Bell state {:.5f}\".format(fidelity_fin.numpy()[0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note:** Interested readers can check tutorials on the LOCCNet module of Paddle Quantum, where we discuss the concept of [entanglement distillation](../locc/EntanglementDistillation_LOCCNET_EN.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Application: Simulating noisy VQE with Paddle Quantum\n", "\n", "\n", "Variational Quantum Eigensolver (VQE) [5] is designed to find the ground state energy of a given molecular Hamiltonian using variational quantum circuits. Interested readers can find more details from the previous tutorial [VQE](../quantum_simulation/VQE_EN.ipynb).\n", "\n", "For illustration purposes, we use VQE to find the ground state energy for the following Hamiltonian: \n", "\n", "$$ \n", "H = 0.4 \\, Z \\otimes I + 0.4 \\, I \\otimes Z + 0.2 \\, X \\otimes X. \n", "\\tag{14}\n", "$$\n", "\n", "Then, we add the amplitude damping channel and compare the performance of the noisy circuit and the noiseless circuit on this task:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T03:06:13.534545Z", "start_time": "2021-04-09T03:06:13.523978Z" } }, "outputs": [], "source": [ "import numpy as np\n", "import paddle\n", "from paddle_quantum.ansatz import Circuit\n", "from paddle_quantum.qinfo import pauli_str_to_matrix\n", "\n", "# Hyperparameters\n", "num_qubits = 2\n", "theta_size = 4\n", "ITR = 100\n", "LR = 0.4\n", "SEED = 999 \n", "p = 0.1\n", "\n", "# Construct Hamiltonian using Pauli string\n", "H_info = [[0.4, 'z0'], [0.4, 'z1'], [0.2, 'x0,x1']]\n", "\n", "# Convert the Pauli string to a matrix\n", "complex_dtype = paddle_quantum.get_dtype()\n", "H_matrix = pauli_str_to_matrix(H_info, num_qubits).numpy().astype(complex_dtype)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-04-09T03:06:36.986422Z", "start_time": "2021-04-09T03:06:32.444713Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "========== Training Noisy VQE ==========\n", "iter: 0 loss: -0.2233\n", "iter: 10 loss: -0.6082\n", "iter: 20 loss: -0.6373\n", "iter: 30 loss: -0.6554\n", "iter: 40 loss: -0.6618\n", "iter: 50 loss: -0.6614\n", "iter: 60 loss: -0.6621\n", "iter: 70 loss: -0.6620\n", "iter: 80 loss: -0.6621\n", "iter: 90 loss: -0.6621\n", "========== Training Noise Free VQE ==========\n", "iter: 0 loss: -0.1235\n", "iter: 10 loss: -0.7679\n", "iter: 20 loss: -0.7933\n", "iter: 30 loss: -0.8177\n", "iter: 40 loss: -0.8219\n", "iter: 50 loss: -0.8239\n", "iter: 60 loss: -0.8244\n", "iter: 70 loss: -0.8245\n", "iter: 80 loss: -0.8245\n", "iter: 90 loss: -0.8246\n", "\n", "Ground state energy from noisy circuit: -0.6621509 Ha\n", "Ground state energy from noiseless circuit: -0.82461375 Ha\n", "Actual ground state energy: -0.82462114 Ha\n" ] } ], "source": [ "class vqe_noisy(paddle.nn.Layer):\n", " \n", " def __init__(self):\n", " super(vqe_noisy, self).__init__()\n", "\n", " # Initialize circuit\n", " self.cir = Circuit(num_qubits)\n", " \n", " # Add parameterized gates\n", " self.cir.ry([0, 1])\n", " \n", " self.cir.cnot([0, 1])\n", " \n", " self.cir.ry([0, 1])\n", " \n", " # Add amplitude damping channel\n", " self.cir.amplitude_damping(p, [0, 1])\n", " \n", " # Define loss function and forward function\n", " def forward(self):\n", " \n", " # Execute the circuit\n", " state = self.cir(init_state)\n", " \n", " # Expectation value of Hamiltonian \n", " loss = loss_func(state)\n", " \n", " return loss, self.cir\n", " \n", "# Construct a noiseless circuit\n", "class vqe_noise_free(paddle.nn.Layer):\n", " \n", " def __init__(self):\n", " super(vqe_noise_free, self).__init__()\n", " \n", " self.cir = Circuit(num_qubits)\n", " self.cir.ry([0, 1])\n", " self.cir.cnot([0, 1])\n", " self.cir.ry([0, 1])\n", "\n", " def forward(self):\n", " \n", " state = self.cir(init_state)\n", " loss = loss_func(state)\n", " \n", " return loss, self.cir\n", " \n", "# Train noisy VQE circuit\n", "print('========== Training Noisy VQE ==========')\n", "loss_list = []\n", "parameter_list = []\n", "\n", "# Define the dimension of parameters\n", "vqe = vqe_noisy()\n", "\n", "# Generally, we use Adam optimizer to get a better convergence, you can change to SVG or RMS prop.\n", "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe.parameters()) \n", "\n", "# Define initial state\n", "init_state = paddle_quantum.state.zero_state(num_qubits)\n", "\n", "# Define loss function\n", "loss_func = paddle_quantum.loss.ExpecVal(paddle_quantum.Hamiltonian(H_info))\n", "\n", "# Optimization iteration\n", "for itr in range(ITR):\n", "\n", " # Forward, to calculate loss function\n", " loss, cir = vqe()\n", "\n", " # Backpropagate to minimize the loss function\n", " loss.backward()\n", " opt.minimize(loss)\n", " opt.clear_grad()\n", "\n", " # Record the learning curve\n", " loss_list.append(loss.numpy()[0])\n", " parameter_list.append(vqe.parameters()[0].numpy())\n", " if itr % 10 == 0:\n", " print('iter:', itr, ' loss: %.4f' % loss.numpy())\n", " \n", "# Train the noiseless VQE in the same way\n", "print('========== Training Noise Free VQE ==========')\n", "loss_list_no_noise = []\n", "parameter_list_no_noise = []\n", "\n", "vqe_no_noise = vqe_noise_free()\n", "opt_no_noise = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe_no_noise.parameters()) \n", "\n", "for itr in range(ITR):\n", "\n", " loss, cir = vqe_no_noise()\n", "\n", " loss.backward()\n", " opt_no_noise.minimize(loss)\n", " opt_no_noise.clear_grad()\n", "\n", " loss_list_no_noise.append(loss.numpy()[0])\n", " parameter_list_no_noise.append(vqe_no_noise.parameters()[0].numpy())\n", " if itr % 10 == 0:\n", " print('iter:', itr, ' loss: %.4f' % loss.numpy())\n", "\n", "\n", "print('\\nGround state energy from noisy circuit: ', loss_list[-1], \"Ha\")\n", "print('Ground state energy from noiseless circuit: ', loss_list_no_noise[-1], \"Ha\")\n", "print('Actual ground state energy: ', np.linalg.eigh(H_matrix)[0][0], \"Ha\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see, noisy VQE behaves much worse than the noiseless version as expected and couldn't satisfy chemical accuracy $\\varepsilon = 0.0016$ Ha." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion\n", "\n", "Noise is an unavoidable feature of quantum devices in the NISQ era. Therefore, designing robust quantum algorithms under the presence of noise and further developing error mitigation schemes are two important research directions. With the noise module in Paddle Quantum, we hope to provide a platform simulating real physical systems and help developing near-term quantum computation applications. Standing together with the research community, the noise module will help us explore what we can achieve with noisy devices, design more robust quantum algorithms, and eventually leads to trustworthy quantum solutions in areas including AI and quantum chemistry.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "## References\n", "\n", "[1] Iverson, J. K., & Preskill, J. Coherence in logical quantum channels. [New Journal of Physics, 22(7), 073066 (2020).](https://iopscience.iop.org/article/10.1088/1367-2630/ab8e5c)\n", "\n", "[2] Nielsen, M. A. & Chuang, I. L. Quantum computation and quantum information. Cambridge university press (2010).\n", "\n", "[3] Preskill, J. Quantum Information Lecture Notes. Chapter 3 (2018).\n", "\n", "[4] Chirolli, L., & Burkard, G. Decoherence in solid-state qubits. [Advances in Physics, 57(3), 225-285 (2008).](https://www.tandfonline.com/doi/abs/10.1080/00018730802218067)\n", "\n", "[5] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)" ] } ], "metadata": { "interpreter": { "hash": "4261e4eef114648d37e4a637967bd8d2966507f48b194e5e336ba3366b740269" }, "kernelspec": { "display_name": "Python 3.8.13 ('pq-ns-icode')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.13" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 5 }