-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathvqe_tfquantum.py
216 lines (197 loc) · 6.95 KB
/
vqe_tfquantum.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
import sys
import tensorflow as tf
import cirq
import sympy
import numpy as np
import time
import datetime
import cpuinfo
import os
import uuid
import utils
def tfquantum_benchmark(
uuid, nwires, nlayer, nitrs, timeLimit, isgpu, check_ps=False, minus=1
):
meta = {}
if isgpu == 0:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
meta["isgpu"] = "off"
else:
gpu = tf.config.list_physical_devices("GPU")
tf.config.experimental.set_memory_growth(device=gpu[0], enable=True)
meta["isgpu"] = "on"
meta["Gpuinfo"] = utils.gpuinfo()
import tensorflow_quantum as tfq
meta["Software"] = "tensorflow quantum"
meta["minus"] = minus
meta["Cpuinfo"] = cpuinfo.get_cpu_info()["brand_raw"]
meta["Version"] = {
"sys": sys.version,
"cirq": cirq.__version__,
"tensorflow": tf.__version__,
"tensorflow_quantum": tfq.__version__,
"numpy": np.__version__,
}
meta["VQE test parameters"] = {
"nQubits": nwires,
"nlayer": nlayer,
"nitrs": nitrs,
"timeLimit": timeLimit,
}
meta["UUID"] = uuid
meta["Benchmark Time"] = (
datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
)
meta["Results"] = {}
qubits = [cirq.GridQubit(0, i) for i in range(nwires)]
# using differentiable op interface
my_op = tfq.get_expectation_op()
adjoint_differentiator = tfq.differentiators.Adjoint()
op = adjoint_differentiator.generate_differentiable_op(analytic_op=my_op)
my_symbol = sympy.symbols("params_0:" + str(nlayer * nwires * 2))
circuit = cirq.Circuit()
for i in range(nwires):
circuit.append(cirq.H(qubits[i]))
for j in range(nlayer):
for i in range(nwires - minus):
circuit.append(
cirq.ZZPowGate(exponent=my_symbol[j * nwires * 2 + i])(
qubits[i], qubits[(i + 1) % nwires]
)
)
for i in range(nwires):
circuit.append(cirq.rx(my_symbol[j * nwires * 2 + nwires + i])(qubits[i]))
circuit = tfq.convert_to_tensor([circuit])
psums = tfq.convert_to_tensor(
[
[
sum(
[
cirq.Z(qubits[i]) * cirq.Z(qubits[(i + 1) % nwires])
for i in range(nwires - 1)
]
+ [-1.0 * cirq.X(qubits[i]) for i in range(nwires)]
)
]
]
)
symbol_values = np.array(
[np.random.normal(size=[nlayer * nwires * 2])], dtype=np.float32
)
# Calculate tfq gradient.
symbol_values_t = tf.Variable(tf.convert_to_tensor(symbol_values))
symbol_names = tf.convert_to_tensor(
["params_" + str(i) for i in range(nwires * 2 * nlayer)]
)
opt_tf = tf.keras.optimizers.Adam(learning_rate=0.1)
@tf.function
def f():
with tf.GradientTape() as g:
g.watch(symbol_values_t)
expectations = op(circuit, symbol_names, symbol_values_t, psums)
grads = g.gradient(expectations, [symbol_values_t])
# opt_tf.apply_gradients(zip(grads, [symbol_values_t]))
return expectations
ct, it, Nitrs = utils.timing(f, nitrs, timeLimit)
meta["Results"]["differentiable operation"] = {
"Construction time": ct,
"Iteration time": it,
"# of actual iterations": Nitrs,
}
# using keras layer interface
qubits = [cirq.GridQubit(0, i) for i in range(nwires)]
my_symbol = sympy.symbols("params_0:" + str(nwires * 2 * nlayer))
circuit = cirq.Circuit()
for i in range(nwires):
circuit.append(cirq.H(qubits[i]))
for j in range(nlayer):
for i in range(nwires - minus):
circuit.append(
cirq.ZZPowGate(exponent=my_symbol[j * nwires * 2 + i])(
qubits[i], qubits[(i + 1) % nwires]
)
)
for i in range(nwires):
circuit.append(cirq.rx(my_symbol[j * nwires * 2 + nwires + i])(qubits[i]))
symbol_values = np.array(
[np.random.normal(size=[nlayer * nwires * 2])], dtype=np.float32
)
# Calculate tfq gradient.
symbol_values_t = tf.Variable(tf.convert_to_tensor(symbol_values))
symbol_names = tf.convert_to_tensor(
["params_" + str(i) for i in range(nwires * 2 * nlayer)]
)
ins = tf.keras.layers.Input(shape=(), dtype=tf.dtypes.string)
oprs = [
sum(
[
cirq.Z(qubits[i]) * cirq.Z(qubits[(i + 1) % nwires])
for i in range(nwires - 1)
]
+ [-cirq.X(qubits[i]) for i in range(nwires)]
)
]
ep = tfq.layers.Expectation(
dtype=tf.float32 # , differentiator=tfq.differentiators.ParameterShift()
)
opt_tf = tf.keras.optimizers.Adam(learning_rate=0.1)
# tfq.convert_to_tensor is very time consuming, thus shall be done out of iteration loops
cc = tfq.convert_to_tensor([circuit])
@tf.function
def f():
with tf.GradientTape() as g:
g.watch(symbol_values_t)
expectations = ep(
cc,
symbol_names=symbol_names,
symbol_values=symbol_values_t,
operators=oprs,
)
grads = g.gradient(expectations, [symbol_values_t])
# opt_tf.apply_gradients(zip(grads, [symbol_values_t]))
return expectations
ct, it, Nitrs = utils.timing(f, nitrs, timeLimit)
meta["Results"]["keras layer & adjoint"] = {
"Construction time": ct,
"Iteration time": it,
"# of actual iterations": Nitrs,
}
if check_ps:
ep = tfq.layers.Expectation(
dtype=tf.float32, differentiator=tfq.differentiators.ParameterShift()
)
symbol_values_t.assign(
np.array([np.random.normal(size=[nlayer * nwires * 2])], dtype=np.float32)
)
@tf.function
def f():
with tf.GradientTape() as g:
g.watch(symbol_values_t)
expectations = ep(
cc,
symbol_names=symbol_names,
symbol_values=symbol_values_t,
operators=oprs,
)
grads = g.gradient(expectations, [symbol_values_t])
# opt_tf.apply_gradients(zip(grads, [symbol_values_t]))
return expectations
ct, it, Nitrs = utils.timing(f, nitrs, timeLimit)
meta["Results"]["keras layer & Parameter shift"] = {
"Construction time": ct,
"Iteration time": it,
"# of actual iterations": Nitrs,
}
print(meta)
return meta
if __name__ == "__main__":
_uuid = str(uuid.uuid4())
n, nlayer, nitrs, timeLimit, isgpu, minus, path, check = utils.arg(check=True)
if check == 1:
checkbool = True
else:
checkbool = False
results = tfquantum_benchmark(
_uuid, n, nlayer, nitrs, timeLimit, isgpu, check_ps=checkbool, minus=minus
)
utils.save(results, _uuid, path)