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

Minor improvement to quantum_info.random_clifford #1259

Merged
merged 13 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 8 additions & 7 deletions src/qibo/gates/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ def __init__(self):

self.clifford = False
self.unitary = False
self._target_qubits = tuple()
self._control_qubits = set()
self._parameters = tuple()
self._target_qubits = ()
self._control_qubits = ()
self._parameters = ()
config.ALLOW_SWITCHERS = False

self.symbolic_parameters = {}
Expand Down Expand Up @@ -158,13 +158,13 @@ def _set_target_qubits(self, qubits: Sequence[int]):

def _set_control_qubits(self, qubits: Sequence[int]):
"""Helper method for setting control qubits."""
self._control_qubits = set(qubits)
if len(self._control_qubits) != len(qubits):
if len(set(qubits)) != len(qubits):
repeated = self._find_repeated(qubits)
raise_error(
ValueError,
f"Control qubit {repeated} was given twice for gate {self.__class__.__name__}.",
)
self._control_qubits = qubits

@target_qubits.setter
def target_qubits(self, qubits: Sequence[int]):
Expand Down Expand Up @@ -204,11 +204,12 @@ def _find_repeated(qubits: Sequence[int]) -> int:
def _check_control_target_overlap(self):
"""Checks that there are no qubits that are both target and
controls."""
common = set(self._target_qubits) & self._control_qubits
control_and_target = self._control_qubits + self._target_qubits
common = len(set(control_and_target)) != len(control_and_target)
if common:
raise_error(
ValueError,
Copy link
Member

Choose a reason for hiding this comment

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

common used to be a set but now it is a bool, therefore the error message defined under this line (GitHub does not let me comment there because it is not changed in this PR) will stop making sense. It will probably read:

ValueError("True qubits are both targets and controls for gate ...")

which doesn't make much sense. It should be modified accordingly.

Other than that, what is the motivation of switching _control_qubits from set to tuple? Just symmetry with _target_qubits? (not intending to say that the current code is the best, I am sure it can be simplified in many ways)

Copy link
Contributor

@renatomello renatomello Mar 19, 2024

Choose a reason for hiding this comment

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

Other than that, what is the motivation of switching _control_qubits from set to tuple? Just symmetry with _target_qubits? (not intending to say that the current code is the best, I am sure it can be simplified in many ways)

In [1]: %timeit set()
63.8 ns ± 4.93 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [2]: %timeit set()
55.9 ns ± 2.81 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [3]: %timeit list()
61.4 ns ± 3.49 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [4]: %timeit tuple()
28.8 ns ± 0.179 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [5]: %timeit []
23 ns ± 2.33 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [6]: %timeit ()
7.33 ns ± 0.0883 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)

It's 7x faster. Even though it's in the ns scale, it makes a difference when creating tens or even hundreds of thousands of gates e.g. random_clifford for 1000+ qubits.

f"{common} qubits are both targets and controls "
f"{set(self._target_qubits) & set(self._control_qubits)} qubits are both targets and controls "
+ f"for gate {self.__class__.__name__}.",
)

Expand Down
38 changes: 27 additions & 11 deletions src/qibo/quantum_info/random_ensembles.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import math
import warnings
from functools import cache
from typing import Optional, Union

import numpy as np
Expand Down Expand Up @@ -1101,6 +1102,21 @@ def _sample_from_quantum_mallows_distribution(nqubits: int, local_state):
return hadamards, permutations


@cache
def _create_S(q):
return gates.S(q)


@cache
def _create_CZ(cq, tq):
return gates.CZ(cq, tq)


@cache
def _create_CNOT(cq, tq):
return gates.CNOT(cq, tq)


def _operator_from_hadamard_free_group(
gamma_matrix, delta_matrix, density_matrix: bool = False, pauli_operator=None
):
Expand Down Expand Up @@ -1138,19 +1154,19 @@ def _operator_from_hadamard_free_group(
if pauli_operator is not None:
circuit += pauli_operator

for qubit, gamma in enumerate(np.diag(gamma_matrix)):
if gamma == 1:
circuit.add(gates.S(qubit))
idx = np.tril_indices(nqubits, k=-1)
gamma_ones = gamma_matrix[idx].nonzero()[0]
delta_ones = delta_matrix[idx].nonzero()[0]

for j in range(nqubits):
for k in range(j + 1, nqubits):
if gamma_matrix[k, j] == 1:
circuit.add(gates.CZ(j, k))
S_gates = [_create_S(q) for q in np.diag(gamma_matrix).nonzero()[0]]
CZ_gates = [
_create_CZ(cq, tq) for cq, tq in zip(idx[1][gamma_ones], idx[0][gamma_ones])
]
CNOT_gates = [
_create_CNOT(cq, tq) for cq, tq in zip(idx[1][delta_ones], idx[0][delta_ones])
]

for j in range(nqubits):
for k in range(j + 1, nqubits):
if delta_matrix[k, j] == 1:
circuit.add(gates.CNOT(j, k))
circuit.add(S_gates + CZ_gates + CNOT_gates)

return circuit

Expand Down
Loading