iTranslated by AI
Playing with cuQuantum (7) — Rethinking Expectation Value Calculation
Purpose
In Playing with cuQuantum (6) — Max-Cut Problem, QUBO, and QAOA, I handled expectation value calculations for a QAOA-like Hamiltonian using cuQuantum. While this calculation is straightforward and easy to understand, I feel there are some inefficiencies. Specifically, it involves calling CircuitToEinsum and contract multiple times. First, I would like to consider whether we can reduce the number of contract calls.
Problem Setting
In a 3-qubit quantum circuit, let's calculate the expectation value of the Hamiltonian
We take the state vector as
Let
Verifying with Qiskit
The easiest first step is to verify the answer with Qiskit.
Import the necessary modules.
from __future__ import annotations
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit import Parameter
from qiskit.primitives import Estimator
Then perform the expectation value calculation, testing parameters
qc = QuantumCircuit(3)
qc.ry(Parameter("θ"), 0)
qc.x(1)
H = SparsePauliOp(["IZZ", "ZZI"])
estimator = Estimator()
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])
expvals = estimator.run(
[qc]*len(angles),
[H]*len(angles),
angles.reshape(-1, 1)
).result().values
for angle, expval in zip(angles.tolist(), expvals):
answer = -1 - np.cos(angle)
print(f"angle={angle}: expval={expval} answer={answer}")
angle=0.0: expval=-2.0 answer=-2.0
angle=0.52: expval=-1.87 answer=-1.87
angle=0.79: expval=-1.71 answer=-1.71
angle=1.05: expval=-1.5 answer=-1.5
angle=1.57: expval=-1.0 answer=-1.0
It looks good as it matches the theoretical values calculated directly with NumPy.
Tensor Calculation
I intend to write the tensor calculations manually this time. Since I won't be relying on APIs, let's review as a preparation. Let's solve the following as a practice problem.
Write each vector and matrix as 1st-order and 2nd-order tensors as follows:
x = (x_i)_{0 \leq i \leq 1} = \begin{pmatrix} 1 \\ 2 \end{pmatrix} A = (A_i^j)_{\substack{0 \leq i \leq 1 \\ 0 \leq j \leq 1}} = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} y = (y^j)_{0 \leq j \leq 1} = \begin{pmatrix} -1 \ \; -2 \end{pmatrix}
Then, what we are looking for in terms of tensor calculation is
or it can be written simply as
Using this, the practice problem can be solved as follows:
import cupy as cp
from cuquantum import contract
x = cp.array([1., 2.])
A = cp.array([
[1., 2.],
[3., 4.]
])
y = cp.array([-1., -2.])
# Calculate one by one:
Ax = contract("a,ba->b", x, A)
yAx = contract("b,b->", Ax, y)
# Or you can perform the contraction calculation all at once like this:
yAx_ = contract("a,ba,b->", x, A, y)
print(Ax)
print(yAx)
print(yAx_)
[ 5. 11.]
-27.0
-27.0
Tackling Expectation Value Calculation (cuTensorNet)
First Stage
Since we had contract is called as many times as there are partial Hamiltonians.
ZERO = cp.array([1., 0.])
ONE = cp.array([0., 1.])
I = cp.eye(2)
Z = cp.array([
[1., 0.],
[0., -1.]
])
# Returns R_Y(θ)|0>
def Ry0(theta) -> cp.ndarray:
return cp.array([np.cos(theta/2), np.sin(theta/2)])
for angle in angles:
expr1 = ",".join(["a,b", "da,eb", "d,e"]) + "->"
operands1 = [
Ry0(angle),
ONE,
Z,
Z,
Ry0(angle),
ONE
]
expr2 = ",".join(["b,c", "eb,fc", "e,f"]) + "->"
operands2 = [
ONE,
ZERO,
Z,
Z,
ONE,
ZERO
]
expval = contract(expr1, *operands1).real + contract(expr2, *operands2).real
answer = -1 - np.cos(angle)
print(f"angle={angle}: expval={expval} answer={answer}")
By the way, since expr1 = "a,b,da,eb,d,e->" and expr2 = "b,c,eb,fc,e,f->", the contents are different. This makes it difficult to group the tensors, but there is a way to make these contents match. It can be achieved by supplementing the omitted identity matrix I.
Second Stage
By supplementing the identity matrix I, some waste is generated in the form of network paths where calculation and inverse calculation cancel each other out, but in exchange, the expr = "a,b,c,da,eb,fc,d,e,f->" can be standardized.
for angle in angles:
expr = ",".join(["a,b,c", "da,eb,fc", "d,e,f"]) + "->"
operands1 = [
Ry0(angle),
ONE,
ZERO,
Z,
Z,
I,
Ry0(angle),
ONE,
ZERO
]
operands2 = [
Ry0(angle),
ONE,
ZERO,
I,
Z,
Z,
Ry0(angle),
ONE,
ZERO
]
expval = contract(expr, *operands1).real + contract(expr, *operands2).real
answer = -1 - np.cos(angle)
print(f"angle={angle}: expval={expval} answer={answer}")
Here,
Z,
Z,
I,
corresponds to
I,
Z,
Z,
corresponds to
At this stage, the number of contract calls has not yet been reduced, but in the next stage, by "stacking" all partial Hamiltonians into a single large tensor, we can reduce the number of contract calls to just one.
Third Stage
Turn the Hamiltonian into just one large tensor. To achieve this, let's write down what we did in the second stage using mathematical formulas.
Reviewing the second stage with formulas
Let the following part be written as tensor
Ry0(angle),
ONE,
ZERO,
Let the following part be written as tensor
Z,
Z,
I,
Let the following part be written as tensor
I,
Z,
Z,
Let the following part be written as tensor
Ry0(-angle),
ONE,
ZERO
Written this way, the second stage calculates:
It would be very convenient if
To do this, we introduce an index
By combining equations (1) and (2), we find that the expectation value we want to find can be written as the following tensor calculation:
Implementation
Stacking the partial Hamiltonians is done horizontally, so it requires some attention, but it looks like this:
for angle in angles:
expr = ",".join(["a,b,c", "gda,geb,gfc", "d,e,f"]) + "->"
operands = [
Ry0(angle),
ONE,
ZERO,
cp.array([Z, I]),
cp.array([Z, Z]),
cp.array([I, Z]),
Ry0(angle),
ONE,
ZERO
]
expval = contract(expr, *operands).real
answer = -1 - np.cos(angle)
print(f"angle={angle}: expval={expval} answer={answer}")
Summary
Setting aside whether this actually speeds up the calculation, I discussed a method to reduce the number of contract calls to just one.
To apply this to actual QAOA calculations, the processing of the Hamiltonian part must be handled carefully, making the implementation somewhat tedious, but I would like to try it out.
Appendix (When the Hamiltonian has coefficients)
The Hamiltonian might not be
Currently, expr = "a,b,c,gda,geb,gfc,d,e,f->", but you can change it to expr = "a,b,c,gda,geb,gfc,d,e,f->g" so as not to contract the index g. This way, the calculation result becomes a 1st-order tensor where each element is the partial expectation value for the corresponding partial Hamiltonian. Then, you can take the sum while multiplying by the coefficients. This is equivalent to taking the element-wise Hadamard product and then summing, which are types of calculations that CuPy and NumPy excel at.
Discussion