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

CliffordBackend with packed bits #1239

Merged
merged 39 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
dc55f20
refactor: packing symplectic matrix's bits
BrunoLiegiBastonLiegi Mar 1, 2024
8d6a313
feat: added _get_dim to _clifford_operations
BrunoLiegiBastonLiegi Mar 1, 2024
c6e6d28
build: pointing at qiboijt branch
BrunoLiegiBastonLiegi Mar 4, 2024
aa56857
feat: moved bits packing inside of the engine
BrunoLiegiBastonLiegi Mar 4, 2024
78205f6
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 6, 2024
5e7b3ae
update lock
renatomello Mar 6, 2024
c60f424
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 9, 2024
b54bee4
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 12, 2024
56fd5e8
feat: added bits packing to measurements
BrunoLiegiBastonLiegi Mar 13, 2024
6780a86
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 14, 2024
fcb6616
update
BrunoLiegiBastonLiegi Mar 14, 2024
3074faa
feat: small adapations for the numba support
BrunoLiegiBastonLiegi Mar 14, 2024
6cceb6a
feat: starting to adapt cupy for packed measurements
BrunoLiegiBastonLiegi Mar 14, 2024
cbe5712
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 14, 2024
13b7053
fix: added repacking after measurements for collapse
BrunoLiegiBastonLiegi Mar 14, 2024
cd87111
build: lock update
BrunoLiegiBastonLiegi Mar 14, 2024
441fe70
fix: increased shots in test
BrunoLiegiBastonLiegi Mar 14, 2024
29ab99e
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 14, 2024
c0245e8
Merge branch 'clifford_simulator_numba' of https://github.com/qibotea…
renatomello Mar 14, 2024
cba20bd
fix: minor adjustments for cupy compatibility
BrunoLiegiBastonLiegi Mar 18, 2024
e4e8834
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 18, 2024
657b4e5
Merge branch 'clifford_simulator_numba' of https://github.com/qibotea…
renatomello Mar 18, 2024
db87b94
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 18, 2024
6c6b9fd
fix: removed reshape before measurements
BrunoLiegiBastonLiegi Mar 21, 2024
dc714b7
fix: removed doc files
BrunoLiegiBastonLiegi Mar 21, 2024
b7c8e45
Merge branch 'master' into clifford_simulator_numba
renatomello Mar 23, 2024
b8f67c7
Merge branch 'clifford_simulator_numba' of https://github.com/qibotea…
renatomello Mar 23, 2024
9785030
fix: tidying up
BrunoLiegiBastonLiegi Mar 25, 2024
6bfc03e
Update src/qibo/backends/_clifford_operations.py
BrunoLiegiBastonLiegi Apr 4, 2024
5dd5847
feat: minor docstring improvements
BrunoLiegiBastonLiegi Apr 8, 2024
bfe3f88
Merge branch 'master' into clifford_simulator_numba
BrunoLiegiBastonLiegi Apr 8, 2024
9f2997d
Merge branch 'master' into clifford_simulator_numba
renatomello Apr 22, 2024
f591f2f
build: removed lock
BrunoLiegiBastonLiegi Apr 29, 2024
c47dca2
build: lock update
BrunoLiegiBastonLiegi Apr 29, 2024
7d47231
fix: fix _exponent type hint + changed naming of _get functions
BrunoLiegiBastonLiegi Apr 29, 2024
070f9e3
fix: changing target in test depending on the system
BrunoLiegiBastonLiegi Apr 29, 2024
267cad3
feat: removed pack arg from pre_execution_reshape
BrunoLiegiBastonLiegi Apr 30, 2024
9057285
build: merge master
BrunoLiegiBastonLiegi Apr 30, 2024
5544e50
build: dropped dependency on qibotn/py3.12
BrunoLiegiBastonLiegi Apr 30, 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
376 changes: 228 additions & 148 deletions poetry.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pylint = "^3.0.3"
matplotlib = "^3.7.0"
tensorflow = { version = "^2.14.1,<2.16", markers = "sys_platform == 'linux'" }
torch = "^2.1.1"
qibojit = { git = "https://github.com/qiboteam/qibojit.git" }
qibojit = { git = "https://github.com/qiboteam/qibojit.git", branch="clifford_simulator_numba" }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a reminder to avoid merging until we merge the corresponding PR in qibojit

qibotn = { git = "https://github.com/qiboteam/qibotn.git" }
stim = "^1.12.0"

Expand All @@ -87,7 +87,7 @@ optional = true
[tool.poetry.group.cuda11.dependencies]
cupy-cuda11x = "^12.0.0"
cuquantum-python-cu11 = "^23.3.0"
qibojit = { git = "https://github.com/qiboteam/qibojit.git" }
qibojit = { git = "https://github.com/qiboteam/qibojit.git", branch="clifford_simulator_numba" }
qibotn = { git = "https://github.com/qiboteam/qibotn.git" }

[tool.poetry.group.cuda12]
Expand All @@ -96,7 +96,7 @@ optional = true
[tool.poetry.group.cuda12.dependencies]
cupy-cuda12x = "^12.0.0"
cuquantum-python-cu12 = "^23.3.0"
qibojit = { git = "https://github.com/qiboteam/qibojit.git" }
qibojit = { git = "https://github.com/qiboteam/qibojit.git", branch="clifford_simulator_numba" }
qibotn = { git = "https://github.com/qiboteam/qibotn.git" }

[tool.poetry.extras]
Expand Down
124 changes: 95 additions & 29 deletions src/qibo/backends/_clifford_operations.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from functools import reduce
from functools import cache, reduce

import numpy as np
from scipy import sparse
Expand Down Expand Up @@ -329,7 +329,7 @@ def ECR(symplectic_matrix, control_q, target_q, nqubits):
return X(symplectic_matrix, control_q, nqubits)


def _exponent(x1, z1, x2, z2):
def _exponent(x1: np.array, z1: np.array, x2: np.array, z2: np.array) -> np.array:
"""Helper function that computes the exponent to which i is raised for the product of the x and z paulis encoded in the symplectic matrix. This is used in _rowsum. The computation is performed parallely over the separated paulis x1[i], z1[i], x2[i] and z2[i].
BrunoLiegiBastonLiegi marked this conversation as resolved.
Show resolved Hide resolved

Args:
Expand All @@ -341,13 +341,7 @@ def _exponent(x1, z1, x2, z2):
Returns:
(np.array): The calculated exponents.
"""
x1_ = x1.astype(np.int8)
x2_ = x2.astype(np.int8)
z1_ = z1.astype(np.int8)
z2_ = z2.astype(np.int8)
return (
2 * (x1_ * x2_ * (z2_ - z1_) + z1_ * z2_ * (x1_ - x2_)) - x1_ * z2_ + x2_ * z1_
)
return 2 * (x1 * x2 * (z2 - z1) + z1 * z2 * (x1 - x2)) - x1 * z2 + x2 * z1

BrunoLiegiBastonLiegi marked this conversation as resolved.
Show resolved Hide resolved

def _rowsum(symplectic_matrix, h, i, nqubits, determined=False):
Expand All @@ -362,16 +356,16 @@ def _rowsum(symplectic_matrix, h, i, nqubits, determined=False):
Returns:
(np.array): The updated symplectic matrix.
"""
xi, xh = symplectic_matrix[i, :nqubits], symplectic_matrix[h, :nqubits]
zi, zh = symplectic_matrix[i, nqubits:-1], symplectic_matrix[h, nqubits:-1]
xi, zi = symplectic_matrix[i, :nqubits], symplectic_matrix[i, nqubits:-1]
xh, zh = symplectic_matrix[h, :nqubits], symplectic_matrix[h, nqubits:-1]
exponents = _exponent(xi, zi, xh, zh)
ind = (
2 * symplectic_matrix[h, -1]
+ 2 * symplectic_matrix[i, -1]
+ np.sum(exponents, axis=-1)
) % 4 == 0
r = np.ones(h.shape[0], dtype=bool)
r[ind] = False
r = np.ones(h.shape[0], dtype=np.uint8)
r[ind] = 0

xi_xh = xi ^ xh
zi_zh = zi ^ zh
Expand All @@ -390,57 +384,108 @@ def _rowsum(symplectic_matrix, h, i, nqubits, determined=False):


def _determined_outcome(state, q, nqubits):
state[-1, :] = False
state[-1, :] = 0
idx = (state[:nqubits, q].nonzero()[0] + nqubits).astype(np.uint)
state = _pack_for_measurements(state, nqubits)
state = _rowsum(
state,
2 * nqubits * np.ones(idx.shape, dtype=np.uint),
idx.astype(np.uint),
nqubits,
idx,
_get_packed_size(nqubits),
True,
)
return state, np.uint(state[-1, -1])
state = _unpack_for_measurements(state, nqubits)
return state, state[-1, -1]


def _random_outcome(state, p, q, nqubits):
p = p[0] + nqubits
tmp = state[p, q].copy()
state[p, q] = False
state[p, q] = 0
h = state[:-1, q].nonzero()[0]
state[p, q] = tmp
if h.shape[0] > 0:
state = _pack_for_measurements(state, nqubits)
state = _rowsum(
state,
h.astype(np.uint),
p * np.ones(h.shape[0], dtype=np.uint),
nqubits,
_get_packed_size(nqubits),
False,
)
state = _unpack_for_measurements(state, nqubits)
state[p - nqubits, :] = state[p, :]
outcome = np.random.randint(2, size=1).item()
state[p, :] = False
state[p, :] = 0
state[p, -1] = outcome
state[p, nqubits + q] = True
state[p, nqubits + q] = 1
return state, outcome


def _get_p(state, q, nqubits):
return state[nqubits:-1, q].nonzero()[0]
@cache
def _get_dim(nqubits):
"""Returns the dimension of the symplectic matrix for a given number of qubits."""
return 2 * nqubits + 1


@cache
def _get_packed_size(n):
"""Returns the size of an array of `n` booleans after packing."""
return np.ceil(n / 8).astype(int)

andrea-pasquale marked this conversation as resolved.
Show resolved Hide resolved

def _packbits(array, axis):
return np.packbits(array, axis=axis)


def _unpackbits(array, axis):
return np.unpackbits(array, axis=axis)

andrea-pasquale marked this conversation as resolved.
Show resolved Hide resolved

def _pack_for_measurements(state, nqubits):
"""Prepares the state for measurements by packing the rows of the X and Z sections of the symplectic matrix."""
r, x, z = _get_rxz(state, nqubits)
x = _packbits(x, axis=1)
z = _packbits(z, axis=1)
return np.hstack((x, z, r[:, None]))

Comment on lines +449 to +452
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you packing x and z separately?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the motivation is the _rowsum function above, in which you need to treat separately x, z, and r, but just to get a confirmation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes precisely, because a single row of the matrix contains the encoding for both x, z and r, thus you cannot pack the complete row in one go but pack the different sections of the row separately.


@cache
def _get_pad_size(n):
"""Returns the size of the pad added to an array of original dimension `n` after unpacking."""
BrunoLiegiBastonLiegi marked this conversation as resolved.
Show resolved Hide resolved
return 8 - (n % 8)


def _unpack_for_measurements(state, nqubits):
"""Unpacks the symplectc matrix that was packed for measurements."""
xz = _unpackbits(state[:, :-1], axis=1)
padding_size = _get_pad_size(nqubits)
x, z = xz[:, :nqubits], xz[:, nqubits + padding_size : -padding_size]
return np.hstack((x, z, state[:, -1][:, None]))


def _init_state_for_measurements(state, nqubits, collapse):
if collapse:
return _unpackbits(state, axis=0)[: _get_dim(nqubits)]
else:
return state.copy()


# valid for a standard basis measurement only
def M(state, qubits, nqubits, collapse=False):
sample = []
state_copy = state if collapse else state.copy()
state = _init_state_for_measurements(state, nqubits, collapse)
for q in qubits:
p = _get_p(state_copy, q, nqubits)
p = state[nqubits:-1, q].nonzero()[0]
# random outcome, affects the state
if len(p) > 0:
state_copy, outcome = _random_outcome(state_copy, p, q, nqubits)
state, outcome = _random_outcome(state, p, q, nqubits)
# determined outcome, state unchanged
else:
state_copy, outcome = _determined_outcome(state_copy, q, nqubits)
state, outcome = _determined_outcome(state, q, nqubits)
sample.append(outcome)
if collapse:
state = _packbits(state, axis=0)
return sample


Expand All @@ -454,11 +499,32 @@ def cast(x, dtype=None, copy=False):
return np.array(x, dtype=dtype, copy=copy)


def _clifford_pre_execution_reshape(state):
def _clifford_pre_execution_reshape(state, pack: bool = False):
"""Reshape and packing applied to the symplectic matrix before execution to prepare the state in the form needed by each engine.

Args:
state (np.array): Input state.
pack (bool): Whether to pack the bits of the symplectic matrix.

Returns:
(np.array) The packed and reshaped state.
"""
if pack:
state = _packbits(state, axis=0)
return state


def _clifford_post_execution_reshape(state, nqubits):
def _clifford_post_execution_reshape(state, nqubits: int):
"""Reshape and unpacking applied to the state after execution to retrieve the standard symplectic matrix form.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is asymmetric with respect to the one above, i.e. there is no pack flag (and it is always unpacking).

What's the reason?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember that the pre- function was called both before execution, but also in correspondence of collapsing measurements, where packing is not needed. But I will doublecheck because after I updated the measurement I might have changed this mechanism.

Copy link
Contributor Author

@BrunoLiegiBastonLiegi BrunoLiegiBastonLiegi Apr 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I double checked and indeed the pack arg can be dropped, thanks for spotting this


Args:
state (np.array): Input state.
nqubits (int): Number of qubits.

Returns:
(np.array) The unpacked and reshaped state.
"""
state = _unpackbits(state, axis=0)[: _get_dim(nqubits)]
return state


Expand Down
18 changes: 6 additions & 12 deletions src/qibo/backends/clifford.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def zero_state(self, nqubits: int):
symplectic_matrix[nqubits:-1, nqubits : 2 * nqubits] = self.np.copy(identity)
return symplectic_matrix

def _clifford_pre_execution_reshape(self, state):
def _clifford_pre_execution_reshape(self, state, pack: bool = False):
"""Reshape the symplectic matrix to the shape needed by the engine before circuit execution.

Args:
Expand All @@ -116,10 +116,10 @@ def _clifford_pre_execution_reshape(self, state):
ndarray: Reshaped state.
"""
return self.engine._clifford_pre_execution_reshape( # pylint: disable=protected-access
state
state, pack
)

def _clifford_post_execution_reshape(self, state, nqubits):
def _clifford_post_execution_reshape(self, state, nqubits: int):
"""Reshape the symplectic matrix to the shape needed by the engine after circuit execution.

Args:
Expand Down Expand Up @@ -205,7 +205,7 @@ def execute_circuit( # pylint: disable=R1710

state = self.zero_state(nqubits) if initial_state is None else initial_state

state = self._clifford_pre_execution_reshape(state)
state = self._clifford_pre_execution_reshape(state, pack=True)

for gate in circuit.queue:
gate.apply_clifford(self, state, nqubits)
Expand Down Expand Up @@ -294,17 +294,11 @@ def sample_shots(
if isinstance(qubits, list):
qubits = tuple(qubits)

state = self._clifford_pre_execution_reshape(state)

if collapse:
samples = [
self.engine.M(state, qubits, nqubits) for _ in range(nshots - 1)
] # parallelize?
samples = [self.engine.M(state, qubits, nqubits) for _ in range(nshots - 1)]
samples.append(self.engine.M(state, qubits, nqubits, collapse))
else:
samples = [
self.engine.M(state, qubits, nqubits) for _ in range(nshots)
] # parallelize?
samples = [self.engine.M(state, qubits, nqubits) for _ in range(nshots)]

return self.engine.cast(samples, dtype=int)

Expand Down
2 changes: 1 addition & 1 deletion src/qibo/gates/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ def apply_density_matrix(self, backend, state, nqubits):
return backend.apply_gate_density_matrix(self, state, nqubits)

def apply_clifford(self, backend, state, nqubits):
return backend.apply_gate_clifford(self, state[:-1], nqubits)
return backend.apply_gate_clifford(self, state, nqubits)
renatomello marked this conversation as resolved.
Show resolved Hide resolved


class SpecialGate(Gate):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_backends_clifford.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,10 @@ def test_collapsing_measurements(backend, seed):
c2.add(gates.M(*range(3)))

clifford_bkd.set_seed(seed)
clifford_res = clifford_bkd.execute_circuit(c1, nshots=100)
clifford_res = clifford_bkd.execute_circuit(c1, nshots=1000)

numpy_bkd.set_seed(seed)
numpy_res = numpy_bkd.execute_circuit(c2, nshots=100)
numpy_res = numpy_bkd.execute_circuit(c2, nshots=1000)

backend.assert_allclose(
clifford_res.probabilities(), backend.cast(numpy_res.probabilities()), atol=1e-1
Expand Down
Loading