diff --git a/tutorials/training/source_en/advanced_use/parameterized_quantum_circuit.md b/tutorials/training/source_en/advanced_use/parameterized_quantum_circuit.md index efa3e922dcc37e3b82b60422781be3f15e46c1dd..cbac17dbc03bab2b3b0de1c436eba6cc01916974 100644 --- a/tutorials/training/source_en/advanced_use/parameterized_quantum_circuit.md +++ b/tutorials/training/source_en/advanced_use/parameterized_quantum_circuit.md @@ -1,5 +1,256 @@ -# Parameterized Quantum Circuit +# Parameterize Quantum Circuit -No English version right now, welcome to contribute. +`Linux` `CPU` `Total Access` `Junior` `Intermediate` `Advanced` - +[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/tutorials/training/source_zh_cn/advanced_use/parameterized_quantum_circuit.ipynb) [![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/mindspore_parameterized_quantum_circuit.ipynb) [![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9vYnMuZHVhbHN0YWNrLmNuLW5vcnRoLTQubXlodWF3ZWljbG91ZC5jb20vbWluZHNwb3JlLXdlYnNpdGUvbm90ZWJvb2svbW9kZWxhcnRzL21pbmRzcG9yZV9wYXJhbWV0ZXJpemVkX3F1YW50dW1fY2lyY3VpdC5pcHluYg==&imagename=MindSpore1.1.1) + +## Summary + +Parameterized quantum circuit(PQC), is an approach to Quantum Machine Learning. The MindQuantum (mixing framework of quantum and classic machine learning) can process parameterized quantum circuit and get the derivation of all observation to every parameter respectively by auto differential the circuit using quantum neural network. + +The procession of constructing quantum circuit and circuit evolution by parameterized simulator operators: + +1. Initialize quantum circuit. +2. As requested, add parameterized quantum gate or non-parameterized quantum gate in circuit. +3. Process gradient solution or state of evolution by PQC simulator operators. + +## Prepare Environment + +import requested modules + + +```python +import numpy as np +import mindquantum as mq +from mindquantum.gate import H, X, Y, RY, RX +``` + +## Quantum Gate + +Quantum gate is the basic logic unit to operate quantum bit. For classic circuit, any logic circuit can consist of some basic logic gate, similarly, any quantum circuit can consist of some basic quantum gate like gate or C-NOT gate acting on solo bit. There some typical quantum gate like $\text{X}$, $\text{Y}$, $\text{Z}$, $\text{Hadamard}$, $\text{CNOT}$ and some revolving gates. For example, the gate $\text{Y}$: + + +```python +print('Gate name: ', Y) +print('Gate matrix: \n', Y.matrix()) +``` + + Gate name: Y + Gate matrix: + [[ 0.+0.j -0.-1.j] + [ 0.+1.j 0.+0.j]] + + +Gate $\text{Z}$ is a non-parameterized gate. Relatively, some revolving gates(like $\text{RY}$)are parameterized gates, which can make different effect to quantum bit by taking various revolving angle$\theta$, like the matrix expression of gate $\text{RY}$: + +$$\text{RY}(\theta)=e^{-i\theta Y/2}=\begin{pmatrix}\cos(\theta/2)&-\sin(\theta/2)\\\sin(\theta/2)&\cos(\theta/2)\end{pmatrix}$$ + +The $i$ is imaginary quantity basic unit. Quantum gate with parameters like above is the important component in constructing quantum neural network. Then, we print the matrix formulation of gate $\text{RY}$ when the revolving angle is $0.5$. + + +```python +ry = RY('a') +ry.matrix({'a': 0.5}) +``` + + + + + array([[ 0.96891242, -0.24740396], + [ 0.24740396, 0.96891242]]) + + + +## Quantum Circuit + +Quantum Circuit is the structure for arrange various quantum basic gates, in which we can initialize quantum circuit by the list of quantum gate, or increase a quantum gate or circuit by addition(`+`), or expand quantum circuit by multiplication(`*`). We will construct quantum circuit as follow and print some relative information. In the following figure, `q0`, `q1` and `q2` denote three quantum bit respectively. The quantum circuit constructed by three quantum gate, whose gate Hadamard act on bit `q0`, gate $CNOT$ act on bit `q1` and be acted by gate $CNOT$(controlled by bit `q0`), and revolving gate $\text{RY}$ act on bit `q2`. + +![quantum circuit](https://gitee.com/mindspore/docs/raw/master/tutorials/training/source_zh_cn/advanced_use/images/quantum_circuit.png) + +### [HiQsimulator](https://hiq.huaweicloud.com/doc/index.html) Compatible quantum line building format + +1. Constructing quantum circuit by `CircuitEngine`. + + We can take quantum gate act on corresponding quantum bit by operator `|`. + + +```python +eng = mq.engine.CircuitEngine() +qubits = eng.allocate_qureg(3) +H | qubits[0] +X | (qubits[0], qubits[1]) +RY('p1') | qubits[2] +encoder = eng.circuit +print(encoder) +encoder.summary() +``` + + H(0) + X(1 <-: 0) + RY(p1|2) + ========Circuit Summary======== + |Total number of gates : 3. | + |Parameter gates : 1. | + |with 1 parameters are : p1. | + |Number qubit of circuit: 3 | + =============================== + + + the `X(1 <-: 0)` means gate `X` is controlled by bit 0, and acts on bit 1, namely C-NOT gate.`RY(p1|2)` means revolving gate revolve around axis Y and acts on bit 2, which `p1` is revolving angle. As printing the summary information, we can know that this quantum circuit is construted by three quantum gates, where a quantum gate is parameterized quantum gate and whole quantum circuit involve three quantum bits. + +2. Constructing quantum circuit by decorator. + + Constructing quantum circuit by decorator can omit some repeat engine declaration. + + +```python +from mindquantum.engine import circuit_generator + +@circuit_generator(3) +def encoder(qubits): + H | qubits[0] + X | (qubits[0], qubits[1]) + RY('p1') | qubits[2] + +print(encoder) +encoder.summary() +``` + + H(0) + X(1 <-: 0) + RY(p1|2) + ========Circuit Summary======== + |Total number of gates : 3. | + |Parameter gates : 1. | + |with 1 parameters are : p1. | + |Number qubit of circuit: 3 | + =============================== + + + We can also make provision for circuit generation through input more parameters into decorator. For example, it can input a string and use to add a prefix for every parameter when we construct quantum circuit, which can make help for generating quantum circuit with same structure but different parameter names. + + +```python +@circuit_generator(3, prefix='encoder') +def encoder(qubits, prefix): + H | qubits[0] + X | (qubits[0], qubits[1]) + RY(prefix + '_1') | qubits[2] + +print(encoder) +encoder.summary() +``` + + H(0) + X(1 <-: 0) + RY(encoder_1|2) + ===========Circuit Summary=========== + |Total number of gates : 3. | + |Parameter gates : 1. | + |with 1 parameters are : encoder_1.| + |Number qubit of circuit: 3 | + ===================================== + + +### A More Convenient Circuit Generation + +We can construct quantum circuit quickly through increasing quantum gates acting on different bits into quantum circuit. + + + +```python +from mindquantum import Circuit + +encoder = Circuit() +encoder += H.on(0) +encoder += X.on(1,0) +encoder += RY('p1').on(2) +print(encoder) +encoder.summary() +``` + + H(0) + X(1 <-: 0) + RY(p1|2) + ========Circuit Summary======== + |Total number of gates : 3. | + |Parameter gates : 1. | + |with 1 parameters are : p1. | + |Number qubit of circuit: 3 | + =============================== + + +## Simulate quantum circuit by MindSpore operator + +a normal quantum neural network usually consist of three part as follow: + +- one(or more) encode circuit, for encoding the classic data to quantum data. +- one(or more) circuit for training.(as we say Ansatz) +- one(or more) physical quantity for measuring. + +As follow, we will construct a quantum neural network, whose encoder consist of two $\text{RY}$ gate, and circuit Ansatz consist of an $\text{CNOT}$ gate and two $\text{RX}$ gate, where physical quantity for training is operator $\text{Z}$ acting on bit 1. + +![simple qnn](https://gitee.com/mindspore/docs/raw/master/tutorials/training/source_zh_cn/advanced_use/images/simple_qnn.png) + + + +```python +from projectq.ops import QubitOperator + +@circuit_generator(2) +def encoder(qubits): + RY('a') | qubits[0] + RY('b') | qubits[1] + +@circuit_generator(2) +def ansatz(qubits): + X | (qubits[0],qubits[1]) + RX('p1') | qubits[0] + RX('p2') | qubits[1] + +ham = mq.Hamiltonian(QubitOperator('Z1')) +encoder_names = ['a', 'b'] +ansatz_names = ['p1', 'p2'] +``` + +We generated Encoder circuit and Ansatz circuit through decorator. We also generated a circuit simulation operator by `generate_pqc_operator`, and get the gradients of quantum neural network output to every parameter respectively by processing simulation computing of quantum circuit. In `generate_pqc_operator`, we need to provide parameters name of Encoder circuit and Ansatz circuit, whole quantum circuit and physical quantity for measuring. + + +```python +from mindquantum.nn import generate_pqc_operator +from mindspore import Tensor +from mindspore import context +context.set_context(mode=context.GRAPH_MODE, device_target="CPU") + +pqc = generate_pqc_operator(encoder_names, ansatz_names, encoder+ansatz, ham) +encoder_data = Tensor(np.array([[0.1,0.2]]).astype(np.float32)) +ansatz_data = Tensor(np.array([0.3,0.4]).astype(np.float32)) +measure_result, encoder_grad, ansatz_grad = pqc(encoder_data, ansatz_data) +print('Measurement result: ', measure_result.asnumpy()) +print('Gradient of encoder parameters: ', encoder_grad.asnumpy()) +print('Gradient of ansatz parameters: ', ansatz_grad.asnumpy()) +``` + + Measurement result: [[0.89819133]] + Gradient of encoder parameters: [[[-0.09011973 -0.1820724 ]]] + Gradient of ansatz parameters: [[[-2.7755576e-17 -3.7974921e-01]]] + + +Above three result express the output of quantum neural network, the parameters gradient in Encoder circuit and the parameters gradient of trained Ansatz circuit. Sometimes, quantum neural is the first layer of whole mixing quantum and classic neural network, so we do not need to derivate the gradient of Encoder circuit, and we can designate the quantum circuit which do not need to compute gradient do not to derivate by `no_grad`. + + +```python +encoder.no_grad() +pqc = generate_pqc_operator(encoder_names, ansatz_names, encoder+ansatz, ham) +measure_result, encoder_grad, ansatz_grad = pqc(encoder_data, ansatz_data) +print('Measurement result: ', measure_result.asnumpy()) +print('Gradient of encoder parameters: ', encoder_grad.asnumpy()) +print('Gradient of ansatz parameters: ', ansatz_grad.asnumpy()) +``` + + Measurement result: [[0.89819133]] + Gradient of encoder parameters: [[[0. 0.]]] + Gradient of ansatz parameters: [[[-2.7755576e-17 -3.7974921e-01]]] + + +As we know above, all the derivation of Encoder circuit parameters in quantum neural network are zero and we do not take the derivative of it in the actual simulation calculation.