-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy path0_tfq_vg.py
56 lines (47 loc) · 1.49 KB
/
0_tfq_vg.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
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
nwires, nlayers = 6, 3
qubits = [cirq.GridQubit(0, i) for i in range(nwires)]
symbols = sympy.symbols("params_0:" + str(nlayers * nwires * 2))
circuit = cirq.Circuit()
for i in range(nwires):
circuit.append(cirq.H(qubits[i]))
for j in range(nlayers):
for i in range(nwires - 1):
circuit.append(
cirq.ZZPowGate(exponent=symbols[j * nwires * 2 + i])(
qubits[i], qubits[(i + 1)]
)
)
for i in range(nwires):
circuit.append(cirq.rx(symbols[j * nwires * 2 + nwires + i])(qubits[i]))
circuit = tfq.convert_to_tensor([circuit])
hamiltonian = tfq.convert_to_tensor(
[
[
sum(
[cirq.Z(qubits[i]) * cirq.Z(qubits[i + 1]) for i in range(nwires - 1)]
+ [-1.0 * cirq.X(qubits[i]) for i in range(nwires)]
)
]
]
)
ep = tfq.layers.Expectation()
@tf.function
def tf_vg(symbol_values):
with tf.GradientTape() as g:
g.watch(symbol_values)
expectations = ep(
circuit,
symbol_names=symbols,
symbol_values=symbol_values,
operators=hamiltonian,
)
grads = g.gradient(expectations, [symbol_values])
return expectations, grads
symbol_values = [np.random.normal(size=[nlayers * nwires * 2]).astype(np.float32)]
symbol_values = tf.Variable(tf.convert_to_tensor(symbol_values))
print(tf_vg(symbol_values))