Advanced gradient calculation of variational quantum circuits

Translator: unseenme

In MindQuantum, we can obtain the gradient of a variable quantum circuit by the get_expectation_with_grad method of the Simulator class. In this tutorial, we will further introduce other functions of this method to help you achieve more advanced usage methods.

Model introduction

The get_expectation_with_grad method is mainly used to calculate the value of the following expression and the gradient of the parameters in the circuit.

\[E(\boldsymbol{\theta})=\left<\varphi\right|U^\dagger_l(\boldsymbol{\theta})HU_r(\boldsymbol{\theta})\left|\psi\right>\]

The interface of this method is defined as follows

Simulator.get_expectation_with_grad(
    hams,
    circ_right,
    circ_left=None,
    simulator_left=None,
    parallel_worker=None
)

Then, we will introduce the meaning of each parameter one by one.

  1. hams. The type of Hamiltonian required for the Hamiltonian in the circuit is Hamiltonian in mindquantum, or a list array containing multiple Hamiltonians. For the latter case, the framework will calculate the expected values of the circuit with respect to all Hamiltonians and the gradient of each expected value with respect to the circuit parameters at the same time.

  2. circ_right. It is the \(U_r(\boldsymbol{\theta})\) in the formula.

  3. circ_left. It is the \(U_l^\dagger(\boldsymbol{theta})\) in the formula. When it is the default value None, circ_left and circ_right are the same circuits.

  4. simulator_left. It is the simulator that contains the \(\left|\varphi\right>\) in the formula. You can set the state of the emulator to the state you need by the emulator’s set_qs, apply_gate or apply_circuit methods. When it is the default value None, \(\left|\varphi\right>=\left|\psi\right>\), and \(\left|\psi\right>\) is the quantum state contained in the current simulator.

  5. parallel_worker. When the hams contains multiple Hamiltonians or the input of the encoder contains multiple sample points, MindQuantum will reasonably perform parallel operations based on this integer as a reference.

Expected values of multiple Hamiltonians at multiple input sample points

In this task, we want to calculate the expected value of the Hamiltonian \(Z_0, X_0, Y_0\) for the following quantum circuit when \(\alpha=\text{arctan}(\sqrt{2}), \pi/2\).

import numpy as np
from mindquantum.core.operators import QubitOperator, TimeEvolution, Hamiltonian
from mindquantum.simulator import Simulator
from mindquantum.core.circuit import Circuit
from mindquantum.core.gates import H

# Define the axis of rotation in Hilbert space
axis = QubitOperator('Y0', 1 / np.sqrt(2)) + QubitOperator('X0', -1 / np.sqrt(2))
# Define the order of the trotter decomposition
trotter_order = 4
# Trotter decomposition of rotation using TimeEvolution
encoder = TimeEvolution(axis, {'alpha': 0.5 / trotter_order}).circuit * trotter_order
encoder
q0: ──RY(√2/4*alpha)────RX(-√2/4*alpha)────RY(√2/4*alpha)────RX(-√2/4*alpha)────RY(√2/4*alpha)────RX(-√2/4*alpha)────RY(√2/4*alpha)────RX(-√2/4*alpha)──

Next, define the Hamiltonian of the expected value to be calculated:

# Define the Hamiltonian Set
hams = [Hamiltonian(QubitOperator('X0')), Hamiltonian(QubitOperator('Y0')), Hamiltonian(QubitOperator('Z0'))]
hams
[1.0 [X0] , 1.0 [Y0] , 1.0 [Z0] ]

Get the operator for the expected value and gradient:

grad_ops = Simulator('mqvector', 1).get_expectation_with_grad(hams, encoder.as_encoder(), parallel_worker=6)
grad_ops
<mindquantum.simulator.simulator.GradOpsWrapper at 0x7f03a4a60430>

Define the value of alpha:

alpha = np.array([[np.arctan(np.sqrt(2))], [np.pi/2]])
alpha
array([[0.95531662],
       [1.57079633]])
f, g = grad_ops(alpha)
print(f)
print(f'shape: {f.shape}')
print('\n')
print(g)
print(f'shape: {g.shape}')
[[0.59389047+0.j 0.55828416+0.j 0.57932107+0.j]
 [0.77269648+0.j 0.63465887+0.j 0.01217645+0.j]]
shape: (2, 3)


[[[ 0.45790207+0.j]
  [ 0.35200884+0.j]
  [-0.80864423+0.j]]

 [[ 0.10989151+0.j]
  [-0.11512098+0.j]
  [-0.9732094 +0.j]]]
shape: (2, 3, 1)

Result analysis

According to the above results, we can see that the dimension of the expected value f is (2, 3). It is not difficult to find that each row of f corresponds to a different expected value of the Hamiltonian for each sample point, and each column of f corresponds to the expected value of each Hamiltonian under different samples. For the gradient g, we also have similar conclusions, except that the last dimension represents different circuit parameters.

Calculating the inner product of different quantum states

According to the model, we only need to set the Hamiltonian as the unit operator and \(U_l(\boldsymbol{\theta})\) as an empty quantum circuit, then we can use \(U_r(\boldsymbol{\theta})\) to rotate \(\left|\psi\right>\) to \(\left|\varphi\right>\), which requires calculating the inner product between \(\left|\varphi\right>\) and the rotated quantum state.

Here, we compute the inner product between the quantum state after the evolution of the zero state by the following quantum circuit and the uniform superposition.

circuit = Circuit().ry('a', 0).rz('b', 0).ry('c', 0)
circuit
q0: ──RY(a)────RZ(b)────RY(c)──

Prepare a simulator containing uniform superposition states:

sim_l = Simulator('mqvector', 1)
sim_l.apply_gate(H.on(0))
sim_l
mqvector simulator with 1 qubit.
Current quantum state:
√2/2¦0⟩
√2/2¦1⟩

Prepare the unit Hamiltonian:

ham = Hamiltonian(QubitOperator(""))

Get the inner product and gradient computation operators:

grad_ops = Simulator('mqvector', 1).get_expectation_with_grad(ham, circuit, Circuit(), simulator_left=sim_l)

Choose the appropriate parameters:

rot_angle = np.array([7.902762e-01, 2.139225e-04, 7.795934e-01])
f, g = grad_ops(rot_angle)
print(f)
print('\n')
print(g)
[[0.99999989-7.52279618e-05j]]


[[[ 2.31681689e-04+3.80179652e-05j -5.34806192e-05-3.51659884e-01j
    2.31681689e-04-3.80179652e-05j]]]

Result analysis

According to the calculation results, we find that the inner product of the last two states is close to 1, indicating that we can prepare a uniform superposition state with high fidelity by the above circuit.

print(circuit.get_qs(pr=rot_angle, ket=True))
(0.7074343486186319-0.00010695972396782116j)¦0⟩
(0.7067790538448511+√5/3906250j)¦1⟩

To find out more about MindQuantum’s API, please click: https://mindspore.cn/mindquantum/