Skip to content

Commit 1646df0

Browse files
breaking API:keras output_loss, shape of circuit wavefunction;some refactor on application codebase and reactivate some example demos into CI
1 parent bc23188 commit 1646df0

18 files changed

+141
-100
lines changed

.github/workflows/ci.yml

+8-6
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@ jobs:
3636
run: |
3737
cd docs
3838
make html
39-
# - name: run example demos
40-
# run: |
41-
# cd examples
42-
# python GHZ_DQAS.py
43-
# python QEM_DQAS.py
44-
# python QAOA_DQAS.py
39+
- name: run example demos
40+
run: |
41+
cd examples
42+
python mcnoise_check.py
43+
python vqnhe_h6.py
44+
python qaoa_dqas.py
45+
# python GHZ_DQAS.py
46+
# python QEM_DQAS.py
4547
- name: setup build
4648
run: |
4749
python3 setup.py build

examples/H6_hamiltonian.npy

60.5 KB
Binary file not shown.

examples/adiabatic_vqnhe.py

+8-20
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,13 @@
1-
import cirq
2-
import numpy as np
3-
import scipy
4-
import sympy as sy
5-
import networkx as nx
6-
import tensorflow_quantum as tfq
7-
import tensorflow as tf
81
from functools import partial
9-
from functools import lru_cache
10-
import tensornetwork as tn
11-
from itertools import product
12-
import json
132
import sys
143

154
sys.path.insert(0, "../")
5+
6+
import numpy as np
7+
import tensorflow as tf
8+
169
import tensorcircuit as tc
17-
from tensorcircuit.applications.layers import *
18-
from tensorcircuit.applications.van import *
19-
from tensorcircuit.applications.graphdata import *
20-
from tensorcircuit.applications.dqas import *
21-
from tensorcircuit.applications.vags import *
22-
from tensorcircuit.applications.vqes import *
10+
from tensorcircuit.applications.vqes import VQNHE, JointSchedule
2311

2412
tc.set_backend("tensorflow")
2513
tc.set_dtype("complex128")
@@ -34,8 +22,8 @@ def initial_param(t, last=None, lastlast=None):
3422
qw.numpy() + np.random.uniform(low=-0.1, high=0.1, size=qw.numpy().shape)
3523
)
3624
cw = last[-2]
37-
for i, t in enumerate(cw):
38-
cw[i] = t + np.random.uniform(low=-0.1, high=0.1, size=t.shape)
25+
for i, b in enumerate(cw):
26+
cw[i] = b + np.random.uniform(low=-0.1, high=0.1, size=t.shape)
3927
return {"c": cw, "q": qw}
4028

4129
return {}
@@ -106,7 +94,7 @@ def learn_c():
10694
if __name__ == "__main__":
10795
history = []
10896
lihh = np.load("data_file")
109-
for i, h in enumerate(lihh[3:6]):
97+
for h in lihh[3:6]:
11098
history.append(adiabatic_range(h.tolist(), history))
11199
print(history)
112100
# vqeinstance = VQNHE(

examples/mcnoise_check.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
n = 5
1313
nlayer = 3
14-
mctries = 100000
14+
mctries = 100 # 100000
1515

1616
print(jax.devices())
1717

@@ -59,7 +59,12 @@ def f(key):
5959
for i in tqdm(range(mctries)):
6060
key, subkey = jax.random.split(key)
6161
psi = f(subkey) # [1, 2**n]
62-
rho += 1 / mctries * tc.backend.transpose(psi) @ tc.backend.conj(psi)
62+
rho += (
63+
1
64+
/ mctries
65+
* tc.backend.reshape(psi, [-1, 1])
66+
@ tc.backend.conj(tc.backend.reshape(psi, [1, -1]))
67+
)
6368

6469
print(rho)
6570
print("difference\n", tc.backend.abs(rho - rho0))

examples/qaoa_parallel_opt.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
sys.path.insert(0, "../")
44

5-
import numpy as np
6-
import tensorflow as tf
75
import tensorcircuit as tc
86
from tensorcircuit.applications.dqas import (
97
parallel_qaoa_train,
@@ -16,7 +14,10 @@
1614
tc.set_backend("tensorflow")
1715

1816
set_op_pool([Hlayer, rxlayer, rylayer, rzlayer, xxlayer, yylayer, zzlayer])
17+
18+
1919
if __name__ == "__main__":
20+
# old fashion example, prefer vvag for new generation software for this task
2021
parallel_qaoa_train(
2122
[0, 6, 1, 6, 1],
2223
single_generator(get_graph("8B")),

examples/vqnhe_h6.py

+4-21
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,14 @@
1-
import cirq
21
import numpy as np
3-
import scipy
4-
import sympy as sy
5-
import networkx as nx
6-
import tensorflow_quantum as tfq
7-
import tensorflow as tf
8-
from functools import partial
9-
from functools import lru_cache
10-
import tensornetwork as tn
11-
from itertools import product
12-
import json
132
import sys
143

154
sys.path.insert(0, "../")
165
import tensorcircuit as tc
17-
from tensorcircuit.applications.layers import *
18-
from tensorcircuit.applications.van import *
19-
from tensorcircuit.applications.graphdata import *
20-
from tensorcircuit.applications.dqas import *
21-
from tensorcircuit.applications.vags import *
22-
from tensorcircuit.applications.vqes import *
6+
from tensorcircuit.applications.vqes import VQNHE, JointSchedule
237

248
tc.set_backend("tensorflow")
259
tc.set_dtype("complex128")
2610

27-
h6h = np.load("/PATH") # reported in 0.99 A
11+
h6h = np.load("./H6_hamiltonian.npy") # reported in 0.99 A
2812

2913
vqeinstance = VQNHE(
3014
10,
@@ -41,14 +25,13 @@ def learn_q():
4125

4226

4327
def learn_c():
44-
# return 0.
4528
lr = np.random.choice([0.004, 0.006, 0.008, 0.1])
4629
return JointSchedule(200, 0.0006, 10000, lr, 5000)
4730

4831

4932
rs = vqeinstance.multi_training(
50-
tries=10,
51-
maxiter=15000, # 10000
33+
tries=2, # 10
34+
maxiter=500, # 10000
5235
threshold=0.5e-8,
5336
learn_q=learn_q,
5437
learn_c=learn_c,

tensorcircuit/applications/graphdata.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from functools import partial
77
from typing import Any, Dict, Iterator, Sequence, Tuple, Optional
88

9-
import cirq
109
import networkx as nx
1110
import numpy as np
1211

@@ -468,6 +467,9 @@ def two2one(x: int, y: int) -> int:
468467

469468

470469
def dress_graph_with_cirq_qubit(g: Graph) -> Graph:
470+
# deprecated cirq related utilities
471+
import cirq
472+
471473
for i in range(len(g.nodes)):
472474
g.nodes[i]["qubit"] = cirq.GridQubit(i, 0)
473475
return g

tensorcircuit/applications/layers.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ def f(circuit: Circuit, symbol: Union[Tensor, float], g: Graph = None) -> Circui
166166

167167

168168
def generate_double_gate_layer_bitflip(gates: str) -> None:
169+
# deprecated, as API are consistent now for DMCircuit and Circuit
169170
def f(
170171
circuit: DMCircuit, symbol: Union[Tensor, float], g: Graph, *params: float
171172
) -> DMCircuit:
@@ -259,7 +260,7 @@ def f(circuit: Circuit, symbol: Tensor, g: Graph = None) -> Circuit:
259260
def anyswaplayer(circuit: Circuit, symbol: Tensor, g: Graph) -> Circuit:
260261
for i, e in enumerate(g.edges):
261262
qubit1, qubit2 = e
262-
circuit.exp( # type: ignore
263+
circuit.exp1( # type: ignore
263264
qubit1,
264265
qubit2,
265266
unitary=array_to_tensor(_swap_matrix),
@@ -274,7 +275,7 @@ def anyswaplayer_bitflip_mc(
274275
) -> Circuit:
275276
for i, e in enumerate(g.edges):
276277
qubit1, qubit2 = e
277-
circuit.exp( # type: ignore
278+
circuit.exp1( # type: ignore
278279
qubit1,
279280
qubit2,
280281
unitary=array_to_tensor(_swap_matrix),
@@ -322,7 +323,8 @@ def bitfliplayer_mc(ci: Circuit, g: Graph, px: float, py: float, pz: float) -> N
322323

323324

324325
## below is similar layer but in cirq API instead of tensrocircuit native API
325-
## special notes to the API, the arguments order are different due to historical reason
326+
## special notes to the API, the arguments order are different due to historical reason compared to tc layers API
327+
## and we have no attention to further maintain the cirq codebase below, availability is not guaranteend
326328

327329
basis_rotation = {
328330
"x": (cirq.H, cirq.H),

tensorcircuit/applications/vags.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ def exp_forward(
377377
layer, graph = cset[j]
378378
layer(ci, theta[i], graph)
379379

380-
state = ci.wavefunction()[0]
380+
state = ci.wavefunction()
381381
losses = ave_func(state, g, *fs)
382382
return losses
383383

tensorcircuit/applications/van.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,8 @@ def _build_masks(
103103
assert (
104104
hidden_space % (input_space - 1) == 0
105105
), "hidden space must be multiple of input space -1 when you set evenly as True"
106-
m = np.arange(
107-
1, input_space
108-
) # TODO: whether 0 is ok need further scrunity, this is a bit away from original MADE idea
106+
m = np.arange(1, input_space)
107+
# TODO: whether 0 is ok need further scrunity, this is a bit away from original MADE idea
109108
self._m.append(
110109
np.hstack([m for _ in range(hidden_space // (input_space - 1))])
111110
)
@@ -177,9 +176,8 @@ def call(self, inputs):
177176
if self.probamp is not None:
178177
inputs = self.probamp + inputs
179178
if self.nonmerge:
180-
inputs = (
181-
nonmerge_block + inputs
182-
) # TODO: to be investigated whether the nonmerge block can affect on unity of probability
179+
inputs = nonmerge_block + inputs
180+
# TODO: to be investigated whether the nonmerge block can affect on unity of probability
183181
outputs = tf.keras.layers.Softmax()(inputs)
184182
return outputs
185183

0 commit comments

Comments
 (0)