Skip to content

Commit e1fc061

Browse files
dc sum for paulis2coo
1 parent f44564a commit e1fc061

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
- Add `templates.ensemble.bagging` module for bagging ensemble method
3434

35+
- The speed of Pauli string sum Hamiltonian generation is improved by a divide-and-conquer sum
36+
3537
### Fixed
3638

3739
- Circuit nosify in noise model now support all circuit attributes apart from qubit number

tensorcircuit/quantum.py

+32-10
Original file line numberDiff line numberDiff line change
@@ -1333,25 +1333,47 @@ def PauliStringSum2COO(
13331333
# numpy version is 3* faster!
13341334

13351335
nterms = len(ls)
1336-
n = len(ls[0])
1337-
s = 0b1 << n
1336+
# n = len(ls[0])
1337+
# s = 0b1 << n
13381338
if weight is None:
13391339
weight = [1.0 for _ in range(nterms)]
13401340
if not (isinstance(weight, tf.Tensor) or isinstance(weight, tf.Variable)):
13411341
weight = tf.constant(weight, dtype=getattr(tf, dtypestr))
1342-
rsparse = get_backend("numpy").coo_sparse_matrix(
1343-
indices=np.array([[0, 0]], dtype=np.int64),
1344-
values=np.array([0.0], dtype=getattr(np, dtypestr)),
1345-
shape=(s, s),
1346-
)
1347-
for i in range(nterms):
1348-
rsparse += get_backend("tensorflow").numpy(PauliString2COO(ls[i], weight[i])) # type: ignore
1349-
# auto transformed into csr format!!
1342+
# rsparse = get_backend("numpy").coo_sparse_matrix(
1343+
# indices=np.array([[0, 0]], dtype=np.int64),
1344+
# values=np.array([0.0], dtype=getattr(np, dtypestr)),
1345+
# shape=(s, s),
1346+
# )
1347+
rsparses = [
1348+
get_backend("tensorflow").numpy(PauliString2COO(ls[i], weight[i])) # type: ignore
1349+
for i in range(nterms)
1350+
]
1351+
rsparse = _dc_sum(rsparses)
1352+
# auto transformed into csr format!!
1353+
1354+
# for i in range(nterms):
1355+
# rsparse += get_backend("tensorflow").numpy(PauliString2COO(ls[i], weight[i])) # type: ignore
13501356
rsparse = rsparse.tocoo()
13511357
if numpy:
13521358
return rsparse
13531359
return backend.coo_sparse_matrix_from_numpy(rsparse)
13541360

1361+
def _dc_sum(l: List[Any]) -> Any:
1362+
"""
1363+
For the sparse sum, the speed is determined by the non zero terms,
1364+
so the DC way to do the sum can indeed bring some speed advantage (several times)
1365+
1366+
:param l: _description_
1367+
:type l: List[Any]
1368+
:return: _description_
1369+
:rtype: Any
1370+
"""
1371+
n = len(l)
1372+
if n > 2:
1373+
return _dc_sum(l[: n // 2]) + _dc_sum(l[n // 2 :])
1374+
else:
1375+
return sum(l)
1376+
13551377
PauliStringSum2COO_numpy = partial(PauliStringSum2COO, numpy=True)
13561378

13571379
def PauliStringSum2COO_tf(

0 commit comments

Comments
 (0)