Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizations for the qibo.quantum_info.basis.pauli_basis and vectorization function #1459

Merged
merged 26 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
8fa006b
feat: building the basis using einsum
BrunoLiegiBastonLiegi Sep 20, 2024
01e7fda
feat: testing numba jittifcation
BrunoLiegiBastonLiegi Sep 20, 2024
183645a
fix: pylint disable
BrunoLiegiBastonLiegi Sep 23, 2024
71d53aa
fix: removed numba version
BrunoLiegiBastonLiegi Sep 24, 2024
591a736
feat: using int indices in place of letters
BrunoLiegiBastonLiegi Sep 24, 2024
d5ca0d3
Update src/qibo/quantum_info/basis.py
BrunoLiegiBastonLiegi Sep 24, 2024
aa4f97d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 24, 2024
94d7e85
fix: removed unnecessary cast
BrunoLiegiBastonLiegi Sep 24, 2024
0e12cf1
feat: adding batch support to vectorize, to be fixed
BrunoLiegiBastonLiegi Sep 24, 2024
3e9d9a8
fix: fixing nonzero for tensorflow and torch
BrunoLiegiBastonLiegi Sep 25, 2024
f492af0
fix: fix typo
BrunoLiegiBastonLiegi Sep 25, 2024
ee16ade
test: added test for batched vectorization
BrunoLiegiBastonLiegi Sep 25, 2024
f73cdc5
Merge branch 'master' into pauli_basis_speedup
renatomello Sep 26, 2024
6b1ce6b
Update src/qibo/quantum_info/superoperator_transformations.py
renatomello Sep 26, 2024
8a82dee
Apply suggestions from code review
BrunoLiegiBastonLiegi Sep 26, 2024
a671398
Update src/qibo/quantum_info/superoperator_transformations.py
BrunoLiegiBastonLiegi Sep 26, 2024
c7e0c0a
Update src/qibo/quantum_info/superoperator_transformations.py
BrunoLiegiBastonLiegi Sep 26, 2024
9022920
Apply suggestions from code review
BrunoLiegiBastonLiegi Sep 26, 2024
d16f5e3
Update tests/test_quantum_info_basis.py
BrunoLiegiBastonLiegi Sep 26, 2024
d71185e
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 2, 2024
d6ce942
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 2, 2024
a64c242
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 4, 2024
a61e7e2
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 7, 2024
fa9a96e
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 7, 2024
2fc4114
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 7, 2024
30fb9bb
Merge branch 'master' into pauli_basis_speedup
renatomello Oct 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 22 additions & 24 deletions src/qibo/quantum_info/basis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from functools import reduce
from itertools import product
from typing import Optional

Expand Down Expand Up @@ -92,43 +91,42 @@ def pauli_basis(
backend = _check_backend(backend)

pauli_labels = {"I": matrices.I, "X": matrices.X, "Y": matrices.Y, "Z": matrices.Z}
basis_single = [pauli_labels[label] for label in pauli_order]
basis_single = backend.cast([pauli_labels[label] for label in pauli_order])
einsum = np.einsum if backend.name == "tensorflow" else backend.np.einsum

if nqubits > 1:
basis_full = list(product(basis_single, repeat=nqubits))
basis_full = [reduce(np.kron, row) for row in basis_full]
dim = 2**nqubits
input_indices = [range(3 * i, 3 * (i + 1)) for i in range(nqubits)]
output_indices = (i for indices in zip(*input_indices) for i in indices)
operands = [basis_single for _ in range(nqubits)]
inputs = [item for pair in zip(operands, input_indices) for item in pair]
basis_full = einsum(*inputs, output_indices).reshape(4**nqubits, dim, dim)
else:
dim = 2
basis_full = basis_single

basis_full = backend.cast(basis_full, dtype=basis_full[0].dtype)

if vectorize and sparse:
basis, indexes = [], []
for row in basis_full:
row = vectorization(row, order=order, backend=backend)
row_indexes = backend.np.flatnonzero(row)
indexes.append(row_indexes)
basis.append(row[row_indexes])
del row
if backend.name == "tensorflow":
nonzero = np.nonzero
elif backend.name == "pytorch":
nonzero = lambda x: backend.np.nonzero(x, as_tuple=True)
else:
nonzero = backend.np.nonzero
basis = vectorization(basis_full, order=order, backend=backend)
indices = nonzero(basis)
basis = basis[indices].reshape(-1, dim)
indices = indices[1].reshape(-1, dim)

elif vectorize and not sparse:
basis = [
vectorization(
backend.cast(matrix, dtype=matrix.dtype), order=order, backend=backend
)
for matrix in basis_full
]
basis = vectorization(basis_full, order=order, backend=backend)
else:
basis = basis_full

basis = backend.cast(basis, dtype=basis[0].dtype)

if normalize:
basis = basis / np.sqrt(2**nqubits)

if vectorize and sparse:
indexes = backend.cast(indexes, dtype=indexes[0][0].dtype)

return basis, indexes
return basis, indices

return basis

Expand Down
34 changes: 22 additions & 12 deletions src/qibo/quantum_info/superoperator_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ def vectorization(state, order: str = "row", backend=None):
.. math::
|\\rho) = \\sum_{k, l} \\, \\rho_{kl} \\, \\ket{l} \\otimes \\ket{k}

If ``state`` is a 3-dimensional tensor it is interpreted as a batch of states.
Args:
state: state vector or density matrix.
state: state vector, density matrix or batch of those.
order (str, optional): If ``"row"``, vectorization is performed
row-wise. If ``"column"``, vectorization is performed
column-wise. If ``"system"``, a block-vectorization is
Expand All @@ -40,13 +41,13 @@ def vectorization(state, order: str = "row", backend=None):
ndarray: Liouville representation of ``state``.
"""
if (
(len(state.shape) >= 3)
(len(state.shape) > 3)
or (len(state) == 0)
or (len(state.shape) == 2 and state.shape[0] != state.shape[1])
):
raise_error(
TypeError,
f"Object must have dims either (k,) or (k,k), but have dims {state.shape}.",
f"Object must have dims either (k,), (k, k), (n, 1, k) or (n, k, k), but have dims {state.shape}.",
)

if not isinstance(order, str):
Expand All @@ -64,23 +65,32 @@ def vectorization(state, order: str = "row", backend=None):

if len(state.shape) == 1:
state = backend.np.outer(state, backend.np.conj(state))
elif len(state.shape) == 3 and state.shape[1] == 1:
state = backend.np.einsum(
"aij,akl->aijkl", state, backend.np.conj(state)
).reshape(state.shape[0], state.shape[-1], state.shape[-1])

if order == "row":
state = backend.np.reshape(state, (1, -1))[0]
state = backend.np.reshape(state, (-1, state.shape[-1] ** 2))
elif order == "column":
state = state.T
state = backend.np.reshape(state, (1, -1))[0]
indices = list(range(len(state.shape)))
indices[-2:] = reversed(indices[-2:])
state = backend.np.transpose(state, indices)
state = backend.np.reshape(state, (-1, state.shape[-1] ** 2))
else:
dim = len(state)
nqubits = int(np.log2(dim))
nqubits = int(np.log2(state.shape[-1]))

new_axis = []
new_axis = [0]
for qubit in range(nqubits):
new_axis += [qubit + nqubits, qubit]
new_axis.extend([qubit + nqubits + 1, qubit + 1])

state = backend.np.reshape(state, [2] * 2 * nqubits)
state = backend.np.reshape(state, [-1] + [2] * 2 * nqubits)
state = backend.np.transpose(state, new_axis)
state = backend.np.reshape(state, (-1,))
state = backend.np.reshape(state, (-1, 2 ** (nqubits * 2)))

state = backend.np.squeeze(
state, axis=tuple(i for i, ax in enumerate(state.shape) if ax == 1)
)

return state

Expand Down
2 changes: 2 additions & 0 deletions tests/test_quantum_info_basis.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ def test_pauli_basis(
basis_test = list(product(basis_test, repeat=nqubits))
basis_test = [reduce(np.kron, matrices) for matrices in basis_test]

# if order == "system" and nqubits ==2 and vectorize:
# breakpoint()
if vectorize:
basis_test = [
vectorization(backend.cast(matrix), order=order, backend=backend)
Expand Down
25 changes: 25 additions & 0 deletions tests/test_quantum_info_superoperator_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,31 @@ def test_vectorization(backend, nqubits, order, statevector):
backend.assert_allclose(matrix, matrix_test, atol=PRECISION_TOL)


@pytest.mark.parametrize("order", ["row", "column", "system"])
@pytest.mark.parametrize("nqubits", [1, 2, 3])
@pytest.mark.parametrize("statevector", [True, False])
def test_batched_vectorization(backend, nqubits, order, statevector):
if statevector:
state = backend.cast(
[random_statevector(2**nqubits, 42, backend=backend) for _ in range(3)]
).reshape(3, 1, -1)
else:
state = backend.cast(
[
random_density_matrix(2**nqubits, seed=42, backend=backend)
for _ in range(3)
]
)

batched_vec = vectorization(state, order=order, backend=backend)
for i, element in enumerate(state):
if statevector:
element = element.ravel()
backend.assert_allclose(
batched_vec[i], vectorization(element, order=order, backend=backend)
)


@pytest.mark.parametrize("order", ["row", "column", "system"])
@pytest.mark.parametrize("nqubits", [2, 3, 4, 5])
def test_unvectorization(backend, nqubits, order):
Expand Down