forked from tencent-quantum-lab/tensorcircuit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqaoa_shot_noise.py
216 lines (174 loc) · 5.99 KB
/
qaoa_shot_noise.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
QAOA with finite measurement shot noise
"""
from functools import partial
import numpy as np
from scipy import optimize
import networkx as nx
import optax
import cotengra as ctg
import tensorcircuit as tc
from tensorcircuit import experimental as E
from tensorcircuit.applications.graphdata import maxcut_solution_bruteforce
K = tc.set_backend("jax")
# note this script only supports jax backend
opt_ctg = ctg.ReusableHyperOptimizer(
methods=["greedy", "kahypar"],
parallel="ray",
minimize="combo",
max_time=10,
max_repeats=128,
progbar=True,
)
tc.set_contractor("custom", optimizer=opt_ctg, preprocessing=True)
def get_graph(n, d, weights=None):
g = nx.random_regular_graph(d, n)
if weights is not None:
i = 0
for e in g.edges:
g[e[0]][e[1]]["weight"] = weights[i]
i += 1
return g
def get_exact_maxcut_loss(g):
cut, _ = maxcut_solution_bruteforce(g)
totalw = 0
for e in g.edges:
totalw += g[e[0]][e[1]].get("weight", 1)
loss = totalw - 2 * cut
return loss
def get_pauli_string(g):
n = len(g.nodes)
pss = []
ws = []
for e in g.edges:
l = [0 for _ in range(n)]
l[e[0]] = 3
l[e[1]] = 3
pss.append(l)
ws.append(g[e[0]][e[1]].get("weight", 1))
return pss, ws
def generate_circuit(param, g, n, nlayers):
# construct the circuit ansatz
c = tc.Circuit(n)
for i in range(n):
c.H(i)
for j in range(nlayers):
c = tc.templates.blocks.QAOA_block(c, g, param[j, 0], param[j, 1])
return c
def ps2z(psi):
# ps2xyz([1, 2, 2, 0]) = {"x": [0], "y": [1, 2], "z": []}
zs = [] # no x or y for QUBO problem
for i, j in enumerate(psi):
if j == 3:
zs.append(i)
return zs
rkey = K.get_random_state(42)
def main_benchmark_suite(n, nlayers, d=3, init=None):
g = get_graph(n, d, weights=np.random.uniform(size=[int(d * n / 2)]))
loss_exact = get_exact_maxcut_loss(g)
print("exact minimal loss by max cut bruteforce: ", loss_exact)
pss, ws = get_pauli_string(g)
if init is None:
init = np.random.normal(scale=0.1, size=[nlayers, 2])
@partial(K.jit, static_argnums=(2))
def exp_val(param, key, shots=10000):
# expectation with shot noise
# ps, w: H = \sum_i w_i ps_i
# describing the system Hamiltonian as a weighted sum of Pauli string
c = generate_circuit(param, g, n, nlayers)
loss = 0
s = c.state()
mc = tc.quantum.measurement_counts(
s,
counts=shots,
format="sample_bin",
random_generator=key,
jittable=True,
is_prob=False,
)
for ps, w in zip(pss, ws):
loss += w * tc.quantum.correlation_from_samples(ps2z(ps), mc, c._nqubits)
return K.real(loss)
@K.jit
def exp_val_analytical(param):
c = generate_circuit(param, g, n, nlayers)
loss = 0
for ps, w in zip(pss, ws):
loss += w * c.expectation_ps(z=ps2z(ps))
return K.real(loss)
# 0. Exact result double check
hm = tc.quantum.PauliStringSum2COO(
K.convert_to_tensor(pss), K.convert_to_tensor(ws), numpy=True
)
hm = K.to_dense(hm)
e, _ = np.linalg.eigh(hm)
print("exact minimal loss via eigenstate: ", e[0])
# 1.1 QAOA with numerically exact expectation: gradient free
print("QAOA without shot noise")
exp_val_analytical_sp = tc.interfaces.scipy_interface(
exp_val_analytical, shape=[nlayers, 2], gradient=False
)
r = optimize.minimize(
exp_val_analytical_sp,
init,
method="Nelder-Mead",
options={"maxiter": 5000},
)
print(r)
print("double check the value?: ", exp_val_analytical_sp(r["x"]))
# cobyla seems to have issue to given consistent x and cobyla
# 1.2 QAOA with numerically exact expectation: gradient based
exponential_decay_scheduler = optax.exponential_decay(
init_value=1e-2, transition_steps=500, decay_rate=0.9
)
opt = K.optimizer(optax.adam(exponential_decay_scheduler))
param = init # zeros stall the gradient
param = tc.array_to_tensor(init, dtype=tc.rdtypestr)
exp_val_grad_analytical = K.jit(K.value_and_grad(exp_val_analytical))
for i in range(1000):
e, gs = exp_val_grad_analytical(param)
param = opt.update(gs, param)
if i % 100 == 99:
print(e)
print("QAOA energy after gradient descent:", e)
# 2.1 QAOA with finite shot noise: gradient free
print("QAOA with shot noise")
def exp_val_wrapper(param):
global rkey
rkey, skey = K.random_split(rkey)
# maintain stateless randomness in scipy optimize interface
return exp_val(param, skey)
exp_val_sp = tc.interfaces.scipy_interface(
exp_val_wrapper, shape=[nlayers, 2], gradient=False
)
r = optimize.minimize(
exp_val_sp,
init,
method="Nelder-Mead",
options={"maxiter": 5000},
)
print(r)
# the real energy position after optimization
print("converged as: ", exp_val_analytical_sp(r["x"]))
# 2.2 QAOA with finite shot noise: gradient based
exponential_decay_scheduler = optax.exponential_decay(
init_value=1e-2, transition_steps=500, decay_rate=0.9
)
opt = K.optimizer(optax.adam(exponential_decay_scheduler))
param = tc.array_to_tensor(init, dtype=tc.rdtypestr)
exp_grad = E.parameter_shift_grad_v2(
exp_val, argnums=0, random_argnums=1, shifts=(0.001, 0.002)
)
# parameter shift doesn't directly apply in QAOA case
rkey = K.get_random_state(42)
for i in range(1000):
rkey, skey = K.random_split(rkey)
gs = exp_grad(param, skey)
param = opt.update(gs, param)
if i % 100 == 99:
rkey, skey = K.random_split(rkey)
print(exp_val(param, skey))
# the real energy position after optimization
print("converged as:", exp_val_analytical(param))
if __name__ == "__main__":
main_benchmark_suite(8, 4)