diff --git a/src/qldpc/codes/distance/_connected_cluster/coset.py b/src/qldpc/codes/distance/_connected_cluster/coset.py index 1e0aa3d05..6a7b1b752 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset.py @@ -2,33 +2,49 @@ """Connected-cluster coset searches of ``CosetLeaderSearch``, with checks made sparser first. -The module also holds the batch queries of ``CosetLeaderSearch`` by its one or two connected-cluster -coset searches. Several threads can run the queries of a coset search at once, as Section 3.8 of -``connected_cluster.md`` says, and a change must keep the requirements on threads of its Section 5. +The batch queries of a coset search answer each block of a batch in one compiled call. Several +threads can run these calls at once, as Section 3.11 of ``connected_cluster.md`` says, so a change +must keep the requirements on threads of its Section 5. """ from __future__ import annotations -from collections.abc import Callable - import numpy as np import numpy.typing as npt -from qldpc._binary import get_num_words, int_to_words, row_ints, words_to_int - -from .. import _threads, _tuning +from qldpc._binary import ( + get_num_words, + int_to_words, + pack_bits, + row_ints, + trailing_zeros_word, + words_to_int, +) +from qldpc._compilation import always_compiled + +from .. import _threads from .._code_matrices import swap_pauli_halves -from .._cosets import get_unit_syndrome_words, tabulate_singles, xor_selected +from .._cosets import get_unit_syndrome_words, tabulate_singles, xor_selected, xor_selected_rows +from .._tuning import MAX_VALUE from ..min_weight_bounds import MinWeightBound -from .search import SupportSearch +from .search import SupportSearch, _CutTables, _get_fixed_words, _search_supports from .sparse_checks import get_sparser_rows -# Maps the syndrome of a ``CosetLeaderSearch`` query to the syndromes of the X and Z parts of the -# errors in its class. -_SplitSyndrome = Callable[[int], tuple[int, int]] - -# Joins the bounds of the cosets of X parts and of Z parts into a bound of a syndrome class. -_JoinPartBounds = Callable[[MinWeightBound, MinWeightBound], MinWeightBound] +# The tables of the compiled batch queries: the packed columns of the map of syndromes to the +# sparser checks, then the tables of their search that ``_search_supports`` reads, in its order, +# with those of the checks and of the cuts each a tuple. They are a plain tuple, whose type Numba +# infers faster than that of a record at each call. +_BatchTables = tuple[ + npt.NDArray[np.uint64], + tuple[ + npt.NDArray[np.int64], npt.NDArray[np.int64], npt.NDArray[np.uint64], npt.NDArray[np.uint64] + ], + npt.NDArray[np.int64], + npt.NDArray[np.int64], + tuple[int, ...], + bool, + _CutTables, +] #################################################################################################### # coset searches @@ -40,20 +56,15 @@ class ConnectedClusterCosetSearch: The words and syndromes are those of a ``BrouwerZimmermannCosetSearch``: packed Paulis, or X or Z parts of Paulis. The coset search makes its checks sparser, with the same span, and searches from the syndrome of each query, mapped to them (Section 3.8 of ``connected_cluster.md``). - ``get_min_weight_bound``, and the batch queries of this module through - ``_get_min_weight_bound_and_states``, give these lower bounds on the weight of the words of a - coset: + ``get_min_weight_bound`` searches only the weight limit ``max_weight``, and gives these lower + bounds on the weight of the words of a coset: - The weight of the word, for a coset with a word of weight zero or one, which a table finds. - - Two, for any other coset whose word the search finds within its first weight limit - (``max_weight`` for ``get_min_weight_bound``), since the word can be lighter than that limit. - - The weight limit, for a coset whose word the search finds within a later limit, which is then - the weight of the lightest words. - - The larger of two and ``max_weight + 1``, for any other coset without a word within - ``max_weight``. + - Two, for any other coset with a word within ``max_weight``, since the word can be lighter. + - The larger of two and ``max_weight + 1``, for any other coset. - So with a first limit of two, every coset with a word within ``max_weight`` gets the weight of - its lightest words. + The batch queries instead try increasing weight limits, and so find the weight of the lightest + words of each coset that has a word within ``max_weight`` (see ``get_min_weights``). Args: matrix: Independent checks, whose kernel is the code: the stabilizers, in ``[X|Z]`` order, @@ -98,13 +109,16 @@ def __init__( self._rows = rows # Row ``i`` of ``rows`` sums the given rows that row ``i`` of ``transform`` selects, so a # given syndrome maps to the sum of the columns of ``transform`` that its bits select. + # Single queries map their syndromes as integers, and the compiled batch queries as packed + # words. self._syndrome_map_columns = row_ints(np.ascontiguousarray(transform.T)) + self._packed_map_columns = pack_bits(np.ascontiguousarray(transform.T)) # Without a function that finds automorphisms, the search never asks for them. self._search = SupportSearch( rows, np.zeros((0, matrix.shape[1]), dtype=np.uint8), symplectic=symplectic, - automorphism_minimum_states=_tuning.MAX_VALUE, + automorphism_minimum_states=MAX_VALUE, restrict_viable_symbols=restrict_viable_symbols, stabilizer_overlap_cuts=stabilizer_overlap_cuts, # Sums of pairs of checks made queries slower (Section 3.8 of connected_cluster.md). @@ -143,44 +157,135 @@ def get_min_weight_bound(self, syndrome: int, max_weight: int) -> MinWeightBound The search tries only the weight limit ``max_weight``, if it is at least two (Section 3.8 of ``connected_cluster.md``). The class docstring states the lower bounds of the answers. """ - return self._get_min_weight_bound_and_states(syndrome, max_weight, None)[0] - - def _get_min_weight_bound_and_states( - self, syndrome: int, max_weight: int, first_limit: int | None - ) -> tuple[MinWeightBound, int]: - """Run ``get_min_weight_bound`` from a first weight limit, and count the states it visits. - - The search tries each weight limit from ``max(min(first_limit, max_weight), 2)`` through - ``max_weight``, and stops at the first within which it finds a word (Section 3.8 of - ``connected_cluster.md``). Without ``first_limit``, it tries only ``max_weight``, if that - is at least two. A first limit above two suits callers to which any word within it gives - the same answer. The class docstring states the lower bounds of the answers. - """ # Look up a word of weight zero or one. word = self._singles.get(syndrome) if word is not None: weight = int(word != 0) - return MinWeightBound(weight <= max_weight, word, weight), 0 + return MinWeightBound(weight <= max_weight, word, weight) # Map the syndrome to the sparser checks, which are independent, so the search keeps them # all, in order. The map is invertible and the lookup answers the zero syndrome, so the # mapped syndrome is not zero, as ``find_vector_with_packed_syndrome`` requires. syndrome = xor_selected(self._syndrome_map_columns, syndrome) - packed_syndrome = int_to_words(syndrome, get_num_words(len(self._rows))) # The lookup leaves only cosets without a word below weight two, so search no limit below - # two, and raise the lower bound above each limit within which the search finds no word. - lower_bound = 2 - num_states = 0 - first = max_weight if first_limit is None else min(first_limit, max_weight) - for limit in range(max(2, first), max_weight + 1): - symbols, states = self._search.find_vector_with_packed_syndrome(packed_syndrome, limit) - num_states += states + # two. + if max_weight >= 2: + packed_syndrome = int_to_words(syndrome, get_num_words(len(self._rows))) + symbols, _ = self._search.find_vector_with_packed_syndrome(packed_syndrome, max_weight) if symbols is not None: - return MinWeightBound(True, self._get_word(symbols), lower_bound), num_states - lower_bound = limit + 1 + return MinWeightBound(True, self._get_word(symbols), 2) representative = xor_selected(self._inverse_rows, syndrome) - return MinWeightBound(False, representative, lower_bound), num_states + return MinWeightBound(False, representative, max(2, max_weight + 1)) + + def find_first_not_within_max_weight( + self, + syndromes: npt.NDArray[np.uint64], + max_weight: int, + *, + num_threads: int = 1, + split_work: int = 0, + ) -> tuple[int, MinWeightBound | None]: + """Find the first syndrome whose coset has no word of weight at most ``max_weight``. + + The syndromes are those of the given checks, packed as for + ``CosetLeaderSearch.find_first_not_within_max_weight``. The search of a syndrome tries the + weight limits 2, 3, ..., ``max_weight`` in turn, unless it looks up a word of weight at most + one (``_get_min_weight``). On more than one thread, the calling thread searches the batch + alone until its queries have done ``split_work`` work, one unit for each state that their + searches visit, and ``num_threads`` threads then search the rest of it + (``_threads.run_blocks``; Section 3.11 of ``connected_cluster.md``). The result is the same + on any number of threads. ``CosetLeaderSearch`` passes the thread options of its tuning. + The defaults search on the calling thread alone. + + Returns: + The index of the first such syndrome and the ``MinWeightBound`` that + ``get_min_weight_bound`` gives for it; or the number of syndromes and None if there is + none. + """ + floors = np.zeros(len(syndromes), dtype=np.int64) + index, _ = self._search_batch(syndromes, max_weight, floors, True, num_threads, split_work) + if index == len(syndromes): + return index, None + return index, self.get_min_weight_bound(words_to_int(syndromes[index]), max_weight) + + def get_min_weights( + self, + syndromes: npt.NDArray[np.uint64], + max_weight: int, + floors: npt.NDArray[np.int64], + *, + num_threads: int = 1, + split_work: int = 0, + ) -> npt.NDArray[np.int64]: + """Find the minimum weight of the coset of each syndrome, if it is at most ``max_weight``. + + The syndromes are packed as for ``find_first_not_within_max_weight``. The search of a + syndrome tries the weight limits from the larger of two and its floor in ``floors``, which + must be at most ``max_weight``, unless it looks up a word of weight at most one + (``_get_min_weight``). A batch moves to ``num_threads`` threads as in + ``find_first_not_within_max_weight``, and each weight is the same on any number of threads. + + Returns: + For each syndrome, a weight at most its floor if its coset has a word within the floor, + and otherwise the minimum weight of its coset, or ``max_weight + 1`` if that is larger. + So the larger of the floor and this weight is the larger of the floor and the minimum + weight, up to ``max_weight + 1``. + """ + return self._search_batch(syndromes, max_weight, floors, False, num_threads, split_work)[1] + + def _search_batch( + self, + syndromes: npt.NDArray[np.uint64], + max_weight: int, + floors: npt.NDArray[np.int64], + stop_above_max_weight: bool, + num_threads: int, + split_work: int, + ) -> tuple[int, npt.NDArray[np.int64]]: + """Search the blocks of a batch with ``_find_min_weights``, run by ``_threads.run_blocks``. + + Returns: + The index that ``_threads.run_blocks`` returns, and the weights that the blocks wrote. + """ + syndromes = np.ascontiguousarray(syndromes) + floors = np.ascontiguousarray(floors) + weights = np.empty(len(syndromes), dtype=np.int64) + tables = self._get_batch_tables() + + def search_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: + """Search rows in order, and write their weights.""" + index, ends = _find_min_weights( + syndromes[start:end], + max_weight, + floors[start:end], + max_work, + stop_above_max_weight, + weights[start:end], + tables, + ) + return start + index + int(ends), bool(ends) + + index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) + return index, weights + + def _get_batch_tables(self) -> _BatchTables: + """The tables that the compiled batch queries read, as a plain tuple (see ``_BatchTables``). + + The search adds no sums of pairs of checks, so the syndrome of a query needs no map to them. + The cuts of queries are tabulated (see ``SupportSearch.find_vector_with_packed_syndrome``). + """ + search = self._search + assert search._query_cuts is not None + return ( + self._packed_map_columns, + search._check_tables[:], + search._ranks, + search._inverse_overlaps, + _get_fixed_words(search._check_tables.symbol_masks.shape[1]), + search._restrict_viable_symbols, + search._query_cuts, + ) def _get_word(self, symbols: npt.NDArray[np.int64]) -> int: """Pack symbols into a word, in which the values 0, 1, and 2 of a symbol are X, Z, and Y. @@ -199,135 +304,132 @@ def _get_word(self, symbols: npt.NDArray[np.int64]) -> int: #################################################################################################### -# batch queries +# compiled coset search -def find_first_cluster_bound( - searches: tuple[ConnectedClusterCosetSearch, ...], +@always_compiled(nogil=True) +def _find_min_weights( syndromes: npt.NDArray[np.uint64], max_weight: int, - split_syndrome: _SplitSyndrome, - join_part_bounds: _JoinPartBounds, - num_threads: int, - split_work: int, -) -> tuple[int, MinWeightBound | None]: - """Run ``CosetLeaderSearch.find_first_not_within_max_weight`` with connected-cluster searches. - - ``searches`` holds the search of Pauli errors, or the searches of X parts and of Z parts, whose - syndromes ``split_syndrome`` gives, and whose bounds ``join_part_bounds`` joins. - ``_threads.run_blocks`` moves the rest of a costly batch to ``num_threads`` threads once its - work reaches ``split_work``, and returns the least index of a syndrome whose class has no error - within ``max_weight``, which, with its bound, is that of one thread. The work of a query is the - number of states that its searches visit (see ``SearchTuning.search_chunk_exponent``). A query - that looks up its error and visits no state does none, since it spends its time holding Python's - global interpreter lock. Threads run ``run_rows`` at once, so the code that it calls must keep - the requirements on threads in Section 5 of ``connected_cluster.md``. - """ - # The bound of each syndrome that ends a call of ``run_rows``. - found: dict[int, MinWeightBound] = {} - - def run_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: - """Answer the queries of rows in turn, up to the first without an error in reach.""" - work = 0 - for index in range(start, end): - bound, states = _get_batch_cluster_bound( - searches, - words_to_int(syndromes[index]), - max_weight, - split_syndrome, - join_part_bounds, - ) - if not bound.within_max_weight: - found[index] = bound - return index + 1, True - work += states - if work >= max_work: - return index + 1, False - return end, False + floors: npt.NDArray[np.int64], + max_work: int, + stop_above_max_weight: bool, + weights: npt.NDArray[np.int64], + tables: _BatchTables, +) -> tuple[int, bool]: + """Search the coset of each syndrome in turn with ``_get_min_weight``, within a budget of work. + + The search of syndrome ``i`` starts from its floor ``floors[i]``, and writes its weight to + ``weights[i]``. The work of a query is the number of states that its searches visit. The + search stops after the last syndrome, or once the work of this call reaches ``max_work``, or, if + ``stop_above_max_weight``, at the first syndrome whose coset has no word within ``max_weight``. + It writes only ``weights`` and arrays that it allocates, so calls that run at once may share + every argument but ``weights``. - index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: run_rows) - return index, found.get(index) - - -def get_min_cluster_weights( - searches: tuple[ConnectedClusterCosetSearch, ...], - syndromes: npt.NDArray[np.uint64], - max_weight: int, - split_syndrome: _SplitSyndrome, - num_threads: int, - split_work: int, -) -> npt.NDArray[np.int64]: - """Run ``CosetLeaderSearch.get_min_weights`` with connected-cluster searches. - - The searches, the split of syndromes, the threads, the work, and the requirements on threads are - as in ``find_first_cluster_bound``. Each weight depends only on its syndrome, so the weights - are those of one thread. + Returns: + If the search stopped at a syndrome whose coset has no word within ``max_weight``, the index + of that syndrome and True. Otherwise the number of syndromes searched and False. """ - weights = np.empty(len(syndromes), dtype=np.int64) - - def run_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: - """Write the weights of the syndromes of rows in turn.""" - work = 0 - for row in range(start, end): - weights[row], states = _get_min_cluster_weight( - searches, words_to_int(syndromes[row]), max_weight, split_syndrome - ) - work += states - if work >= max_work: - return row + 1, False - return end, False - - _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: run_rows) - return weights - - -def _get_min_cluster_weight( - searches: tuple[ConnectedClusterCosetSearch, ...], - syndrome: int, + # A buffer for the packed syndrome of a query for the sparser checks (see ``_get_min_weight``). + mapped = np.empty(tables[0].shape[1], dtype=np.uint64) + work = 0 + for index in range(len(syndromes)): + weight, num_states = _get_min_weight( + syndromes[index], max_weight, floors[index], mapped, tables + ) + weights[index] = weight + if stop_above_max_weight and weight > max_weight: + return index, True + work += num_states + if work >= max_work: + return index + 1, False + return len(syndromes), False + + +@always_compiled(inline=True) +def _get_min_weight( + syndrome: npt.NDArray[np.uint64], max_weight: int, - split_syndrome: _SplitSyndrome, + first_limit: int, + mapped: npt.NDArray[np.uint64], + tables: _BatchTables, ) -> tuple[int, int]: - """Find the minimum weight of the class of a syndrome with connected-cluster searches. - - The searches try increasing weight limits from two. A Z-part search starts instead at the - weight of the X part, if that is more than two, since any Z part within it gives the class that - weight (Section 3.8 of ``connected_cluster.md``). + """Find the weight of a word of the coset of a syndrome, by increasing weight limits. + + ``syndrome`` is a packed syndrome of the given checks, and row ``j`` of ``map_columns``, the + first of ``tables``, is the packed syndrome for the sparser checks of the word whose given + syndrome has only bit ``j`` set (see ``ConnectedClusterCosetSearch``). The search writes the + mapped syndrome to ``mapped``. It gives the weight zero to the zero syndrome, and one to the + syndrome of a symbol, which flips the first check of the syndrome. Otherwise it tries each + weight limit from ``max(2, first_limit)`` through ``max_weight`` with ``_search_supports``, as + ``SupportSearch.find_vector_with_packed_syndrome`` does, and stops at the first within which it + finds a word (Section 3.8 of ``connected_cluster.md``). The other tables are those of + ``_search_supports``, from the search of the sparser checks. Returns: - The minimum weight of the class, or ``max_weight + 1`` if that is larger, and the number of - states that the searches visited. - """ - if len(searches) == 1: - bound, states = searches[0]._get_min_weight_bound_and_states(syndrome, max_weight, 2) - return (bound.lower_bound if bound.within_max_weight else max_weight + 1), states - x_syndrome, z_syndrome = split_syndrome(syndrome) - x_bound, x_states = searches[0]._get_min_weight_bound_and_states(x_syndrome, max_weight, 2) - if not x_bound.within_max_weight: - return max_weight + 1, x_states - z_bound, z_states = searches[1]._get_min_weight_bound_and_states( - z_syndrome, max_weight, x_bound.lower_bound - ) - if not z_bound.within_max_weight: - return max_weight + 1, x_states + z_states - return max(x_bound.lower_bound, z_bound.lower_bound), x_states + z_states - - -def _get_batch_cluster_bound( - searches: tuple[ConnectedClusterCosetSearch, ...], - syndrome: int, - max_weight: int, - split_syndrome: _SplitSyndrome, - join_part_bounds: _JoinPartBounds, -) -> tuple[MinWeightBound, int]: - """Answer a query of a batch with connected-cluster searches, by increasing limits. - - The syndrome of the query must be in range (see ``CosetLeaderSearch._check_syndromes``). - Section 3.8 of ``connected_cluster.md`` says why the limits increase. Also returns the number - of states that the searches visited. + A weight and the number of states that the searches visited. The weight is the minimum + weight ``w`` of the coset, or ``max_weight + 1`` if that is smaller, unless ``2 <= w < + first_limit``, when it is ``first_limit``, which must then be at most ``max_weight``. """ - if len(searches) == 1: - return searches[0]._get_min_weight_bound_and_states(syndrome, max_weight, 2) - x_syndrome, z_syndrome = split_syndrome(syndrome) - x_bound, x_states = searches[0]._get_min_weight_bound_and_states(x_syndrome, max_weight, 2) - z_bound, z_states = searches[1]._get_min_weight_bound_and_states(z_syndrome, max_weight, 2) - return join_part_bounds(x_bound, z_bound), x_states + z_states + map_columns, check_tables, ranks, inverse_overlaps, fixed_words, restrict, cuts = tables + check_starts, check_symbols, symbol_masks, test_columns = check_tables + + # Map the syndrome to the sparser checks. The map is invertible, so only the zero syndrome maps + # to zero. + mapped[:] = 0 + xor_selected_rows(syndrome, map_columns, mapped) + first_check = -1 + for word in range(len(mapped)): + if mapped[word]: + first_check = 64 * word + int(trailing_zeros_word(mapped[word])) + break + if first_check < 0: + return 0, 0 + + # A word of weight one is a symbol whose checks are those of the syndrome. + for position in range(check_starts[first_check], check_starts[first_check + 1]): + symbol = check_symbols[position] + equal = True + for word in range(len(mapped)): + if symbol_masks[symbol, word] != mapped[word]: + equal = False + break + if equal: + return 1, 0 + + # Every other word weighs at least two, so search no limit below two. + roots = np.full(1, -1, dtype=np.int64) + paths = np.empty((1, 0), dtype=np.int64) + no_path = np.empty(0, dtype=np.int64) + num_states = 0 + for limit in range(max(2, first_limit), max_weight + 1): + # Name each table, since star-unpacking the tuples here makes queries a few percent slower. + support, item_states, _, _, _ = _search_supports( + check_starts, + check_symbols, + symbol_masks, + test_columns, + roots, + paths, + 0, + ranks, + inverse_overlaps, + min(limit, len(ranks)), + no_path, + no_path, + MAX_VALUE, + mapped, + fixed_words, + True, + restrict, + cuts[0], + cuts[1], + cuts[2], + cuts[3], + cuts[4], + cuts[5], + ) + num_states += item_states[0] + if len(support): + return limit, num_states + return max_weight + 1, num_states diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 5c8ddfd5c..3722cc287 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -12,9 +12,10 @@ import numpy.typing as npt import pytest -from qldpc._binary import get_kernel +from qldpc._binary import get_kernel, get_num_words, int_to_words -from .._tuning import use_tuning +from .._cosets import xor_selected +from .._tuning import MAX_VALUE, use_tuning from ..conftest import ( get_binary_minima, get_binary_syndrome, @@ -91,8 +92,8 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: def test_connected_cluster_queries_only_read_their_search(monkeypatch: pytest.MonkeyPatch) -> None: """A coset search tabulates the overlap cuts of its queries before its first query. - It does so even before ``use_query_overlap_words`` gives it words, so that its queries only read - the search. + It does so even before ``use_query_overlap_words`` gives it words, so that its queries, single + or in batches, only read the search. """ tabulated: list[object] = [] get_overlap_cuts = search._get_overlap_cuts @@ -118,6 +119,9 @@ def record(*args: Any) -> Any: assert num_tabulated for syndrome in (0b101, 0b111, 0b100): assert coset_search.get_min_weight_bound(syndrome, 2).within_max_weight + batch = split_syndromes_into_words([0b101, 0b111, 0b100], 3) + coset_search.find_first_not_within_max_weight(batch, 2) + coset_search.get_min_weights(batch, 2, np.zeros(3, dtype=np.int64)) assert len(tabulated) == num_tabulated @@ -125,7 +129,10 @@ def record(*args: Any) -> Any: def test_connected_cluster_queries_read_their_restriction( monkeypatch: pytest.MonkeyPatch, restrict_viable_symbols: bool ) -> None: - """A coset search passes ``restrict_viable_symbols`` to its queries.""" + """A coset search passes ``restrict_viable_symbols`` to its single queries. + + ``test_connected_cluster_batches_search_as_single_queries`` checks its batch queries. + """ settings: list[bool] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -156,7 +163,11 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: def test_connected_cluster_queries_cut_by_their_overlap_words_if_switched_on( monkeypatch: pytest.MonkeyPatch, cuts: bool ) -> None: - """A coset search given overlap words cuts its queries exactly when its switch is on.""" + """A coset search given overlap words cuts its single queries exactly when its switch is on. + + ``test_connected_cluster_batches_search_as_single_queries`` checks that its batch queries cut + as its single queries do. + """ num_cuts_per_query: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -183,6 +194,129 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: assert all(bool(num_cuts) == cuts for num_cuts in num_cuts_per_query) +def test_connected_cluster_batches_search_as_single_queries() -> None: + """Batch queries visit the states of single queries, with the restriction on and off. + + So they search with the restriction and the overlap cuts of the coset search, which are on. On + this CSS state, the lightest errors with the syndrome 57 weigh two, and the number of states + that its query visits at limit two depends on the restriction. The batch loop stops after a + query once its work reaches its budget, so of two copies of the syndrome, it searches one within + a budget of the states of a single query, and both within one more. + """ + matrix = get_random_css_state(6, 3, np.random.default_rng(0)) + syndrome = 57 + assert get_exhaustive_minima(matrix, False)[syndrome] == 2 + batch = split_syndromes_into_words([syndrome, syndrome], len(matrix)) + floors, weights = np.zeros(2, dtype=np.int64), np.empty(2, dtype=np.int64) + counts = [] + for restrict_viable_symbols in (True, False): + coset_search = coset.ConnectedClusterCosetSearch( + matrix, + symplectic=True, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=restrict_viable_symbols, + stabilizer_overlap_cuts=True, + ) + coset_search.use_query_overlap_words(coset_search.checks) + mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) + packed_syndrome = int_to_words(mapped, get_num_words(len(matrix))) + num_states = coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, 2)[1] + tables = coset_search._get_batch_tables() + for max_work, num_searched in [(num_states, 1), (num_states + 1, 2)]: + result = coset._find_min_weights(batch, 2, floors, max_work, False, weights, tables) + assert result == (num_searched, False) + counts.append(num_states) + assert counts[0] != counts[1] + + +def test_connected_cluster_batch_loop_matches_the_minima_of_random_cosets( + pytestconfig: pytest.Config, +) -> None: + """The compiled batch loop agrees with the minima of the cosets of random syndromes. + + For the identity checks I64 and I65, which fill one 64-bit word or spill into a second, a + syndrome is the lightest word of its coset, so its bit count is its minimum weight. A batch + starts with a syndrome of at most one bit, which the loop looks up, and goes on, in random + order, with random bits of each word alone, a bit of the first word with bits of the last, and + random bits. Bit counts up to five let some searches start from floors between two and their + minima. + + At each ``max_weight`` up to five, with random floors, the loop gives the weights that + ``_get_min_weight`` states, with the tables of the search and with an empty ``fixed_words``, + which selects the version of ``_search_supports`` for any number of words. A loop that stops at + the first syndrome without a word within ``max_weight``, which gets the bound of a single query, + writes the weights up to it. + """ + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + + def get_bits(checks: range, num_bits: int) -> set[int]: + """Random distinct bits of a syndrome, from some checks.""" + return set(rng.choice(checks, size=min(num_bits, len(checks)), replace=False).tolist()) + + for num_checks in (64, 65): + coset_search = coset.ConnectedClusterCosetSearch( + np.eye(num_checks, dtype=np.uint8), + symplectic=False, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=True, + stabilizer_overlap_cuts=True, + ) + tables = coset_search._get_batch_tables() + num_words = get_num_words(num_checks) + words = [range(64 * word, min(64 * word + 64, num_checks)) for word in range(num_words)] + bit_sets = [get_bits(word_checks, int(rng.integers(1, 6))) for word_checks in words] + bit_sets.append(get_bits(words[0], 1) | get_bits(words[-1], int(rng.integers(1, 5)))) + bit_sets += [get_bits(range(num_checks), int(rng.integers(6))) for _ in range(6)] + syndromes = [sum(1 << bit for bit in bits) for bits in bit_sets] + rng.shuffle(syndromes) + leading_bits = get_bits(range(num_checks), int(rng.integers(2))) + syndromes.insert(0, sum(1 << bit for bit in leading_bits)) + minima = np.array([syndrome.bit_count() for syndrome in syndromes]) + batch = split_syndromes_into_words(syndromes, num_checks) + + for max_weight in range(6): + floors = rng.integers(max_weight + 1, size=len(batch)) + expected = _get_batch_weights(minima, floors, max_weight) + for batch_tables in (tables, tables[:4] + ((),) + tables[5:]): + weights = np.full(len(batch), -1, dtype=np.int64) + assert coset._find_min_weights( + batch, max_weight, floors, MAX_VALUE, False, weights, batch_tables + ) == (len(batch), False) + assert np.array_equal(weights, expected) + above = np.flatnonzero(minima > max_weight).tolist() + index, bound = coset_search.find_first_not_within_max_weight(batch, max_weight) + assert index == (above[0] if above else len(batch)) + if above: + assert bound == coset_search.get_min_weight_bound(syndromes[index], max_weight) + weights = np.full(len(batch), -1, dtype=np.int64) + assert coset._find_min_weights( + batch, max_weight, floors, MAX_VALUE, True, weights, tables + ) == ((index, True) if above else (index, False)) + num_written = min(index + 1, len(batch)) + assert np.array_equal(weights[:num_written], expected[:num_written]) + + +def test_connected_cluster_batches_count_words_of_checks_not_of_variables() -> None: + """Batch queries size the syndromes of their searches by the checks, not by the variables. + + The two checks ``[I2 | 0]`` act on the first two of 65 variables, so the bit count of a + syndrome is its minimum weight. A syndrome fills one 64-bit word, and the variables fill two. + """ + checks = np.hstack([np.eye(2, dtype=np.uint8), np.zeros((2, 63), dtype=np.uint8)]) + coset_search = coset.ConnectedClusterCosetSearch( + checks, + symplectic=False, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=True, + stabilizer_overlap_cuts=True, + ) + batch = split_syndromes_into_words([1, 3], 2) + assert coset_search.get_min_weights(batch, 2, np.zeros(2, dtype=np.int64)).tolist() == [1, 2] + + @pytest.mark.parametrize("cuts", [True, False]) @pytest.mark.parametrize("restrict_viable_symbols", [True, False]) def test_connected_cluster_answers_match_exhaustive_minima( @@ -190,9 +324,9 @@ def test_connected_cluster_answers_match_exhaustive_minima( ) -> None: """Queries get the bounds that ``ConnectedClusterCosetSearch`` states, with or without cuts. - A single query searches only ``max_weight``, as does a query whose first limit is above it. A - query whose first limit is two finds the weight of the lightest words of each coset that has a - word within ``max_weight``. + A single query searches only ``max_weight``. Batch queries find the weight of the lightest + words of each coset up to ``max_weight + 1``, or a weight within its floor if it has a word + within the floor. """ # The searches of Paulis check with the stabilizers of graph states with phases, which are not # CSS, and of CSS states, with no pure-X stabilizer, only pure-X stabilizers, or both. The @@ -220,17 +354,11 @@ def test_connected_cluster_answers_match_exhaustive_minima( minima = ( get_exhaustive_minima(checks, False) if symplectic else get_binary_minima(checks) ) - for syndrome, max_weight in itertools.product( - range(1 << len(checks)), range(num_qubits + 1) - ): - minimum = minima[syndrome] - single = coset_search.get_min_weight_bound(syndrome, max_weight) - from_two, _ = coset_search._get_min_weight_bound_and_states(syndrome, max_weight, 2) - late, _ = coset_search._get_min_weight_bound_and_states( - syndrome, max_weight, max_weight + 1 - ) - assert late == single - for bound, exact in [(single, False), (from_two, True)]: + batch = split_syndromes_into_words(list(range(len(minima))), len(checks)) + for max_weight in range(num_qubits + 1): + # Single queries. + for syndrome, minimum in enumerate(minima.tolist()): + bound = coset_search.get_min_weight_bound(syndrome, max_weight) word = bound.representative if symplectic: weight = get_pauli_weight(word, num_qubits, False) @@ -243,13 +371,40 @@ def test_connected_cluster_answers_match_exhaustive_minima( if not bound.within_max_weight: expected_bound = minimum if minimum < 2 else max(2, max_weight + 1) assert bound.lower_bound == expected_bound - elif exact or minimum < 2: - # Queries from limit two, and words of weight at most one, are exact - # within max_weight. + elif minimum < 2: assert bound.lower_bound == weight == minimum else: assert bound.lower_bound == 2 and weight <= max_weight + # Batch queries, with random floors. + floors = rng.integers(max_weight + 1, size=len(batch)) + weights = coset_search.get_min_weights(batch, max_weight, floors) + within = minima <= floors + assert np.all(weights[within] <= floors[within]) + assert np.array_equal(weights[~within], np.minimum(minima, max_weight + 1)[~within]) + + +def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() -> None: + """A batch that moves to blocks answers every row of each block from the row's own floor. + + For the checks I3, a syndrome is the lightest word of its coset, so its bit count is its minimum + weight. The search of the first syndrome of the batch does the work at which the rest of the + batch moves to blocks, which up to two threads run. The second syndrome starts a block, and + its floor of zero gives its weight 2, where the floor 3 of the first or last syndrome gives 3. + """ + coset_search = coset.ConnectedClusterCosetSearch( + np.eye(3, dtype=np.uint8), + symplectic=False, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=True, + stabilizer_overlap_cuts=True, + ) + batch = split_syndromes_into_words([0b111, 0b011, 0b111], 3) + floors = np.array([3, 0, 3], dtype=np.int64) + weights = coset_search.get_min_weights(batch, 3, floors, num_threads=2, split_work=1) + assert weights[0] <= 3 and weights[1] == 2 and weights[2] <= 3 + def test_connected_cluster_batches_match_exhaustive_minima() -> None: """Batch queries by one search, or by searches of X and Z parts, agree with exhaustive minima. @@ -275,3 +430,20 @@ def test_connected_cluster_batches_match_exhaustive_minima() -> None: if bound is not None: assert not bound.within_max_weight and bound.lower_bound > max_weight assert get_syndrome(matrix, bound.representative) == index + + +#################################################################################################### +# helpers + + +def _get_batch_weights( + minima: npt.NDArray[np.int_], floors: npt.NDArray[np.int_], max_weight: int +) -> npt.NDArray[np.int_]: + """The weights that the batch loop writes for cosets of some minima (see ``_get_min_weight``). + + A minimum below two, which a lookup finds, and a minimum from the floor up give the minimum, up + to ``max_weight + 1``, and a minimum from two up to the floor gives the floor. + """ + return np.where( + minima < 2, minima, np.where(minima < floors, floors, np.minimum(minima, max_weight + 1)) + ) diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index f400f4f96..dcc01f8a9 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -354,14 +354,20 @@ The rounds need not find a lightest basis: a word of the span is a row of a redu Even a lightest basis can be heavier than the checks of a code: for the physical weight on the state `|0⟩` of an `[[n, k]]` code, the span is the stabilizer group of the state, and at most `n - k` of its independent elements are stabilizers of the code. So every basis holds at least `k` logical operators, each at least as heavy as the distance, which the greedy algorithm would have to find by exact searches. -A coset search first looks up the syndrome of a query in a table of the syndromes of the vectors of weight at most one, and searches only the syndromes that the table lacks, which have no solution of weight below two. +A coset search first finds the solutions of weight at most one, and searches only the syndromes without one, which have no solution of weight below two. +A single query looks up its syndrome in a table of the syndromes of the vectors of weight at most one. +A batch query maps its syndrome to the sparser checks, and compares it with the checks that each symbol of the first check of the syndrome flips, since a symbol with the syndrome flips that check. A search at limit `W` that finds no solution proves that every solution is heavier than `W`. -These two facts give the lower bounds of the answers, which the class docstring of `ConnectedClusterCosetSearch` states for each kind of query. +These facts give the lower bounds of the answers, which the class docstring of `ConnectedClusterCosetSearch` states for each kind of query. A query at limit `W` can wander through many heavy supports before it reaches a much lighter solution. `certify_bounded_fault_propagation` queries batches of syndromes most of which have a solution within `W`, so for such batches a coset search tries the limits 2, 3, …, `W` in turn, and stops at the first within which it finds a solution, a lightest one, at the cost of repeating the lower limits for syndromes without one. -For `estimate_residual_weight_histogram`, `CosetLeaderSearch` finds minimum weights with the same increasing limits; [problems.md](problems.md#the-coset-leader-search) gives the floor of its searches by CSS weight. +For `estimate_residual_weight_histogram`, `CosetLeaderSearch` finds minimum weights with the same increasing limits; [problems.md](problems.md#the-coset-leader-search) gives the floor of its searches by CSS weight, from which a search starts its limits. A single query, `CosetLeaderSearch.get_min_weight_bound`, searches at `W` directly, since a caller may already raise `W` one step at a time. +The queries of these batches mostly visit a few states each, so Python code around each query would take most of the time of a batch. +So the batch queries of a coset search answer each block of a batch in one call of the compiled loop `_find_min_weights` of `_connected_cluster/coset.py`, which maps, looks up, and searches each syndrome of the block, and calls `_search_supports` from compiled code. +This makes the batches of `certify_bounded_fault_propagation` about 4 to 8 times faster than answering their queries one at a time from Python. +For the first syndrome of a batch without a solution within `W`, `find_first_not_within_max_weight` returns the bound of a single query. Without reuse, a state computes the overlap and repair ([Section 3.4](#34-pruning)) of a symbol once for each unsatisfied check that it examines and the symbol flips. The checks of a syndrome query can stay dense after the rounds, so a symbol can flip many unsatisfied checks, and the query computes both at most once per symbol and state. @@ -543,7 +549,7 @@ A first limit that a `cutoff` sets above the divisor is predicted to visit `MAX_ **Syndrome queries.** A syndrome query ([Section 3.8](#38-vectors-with-a-given-syndrome)) runs on one thread. -The batch queries of `CosetLeaderSearch` instead move the rest of a costly batch to threads, by syndromes, and give the answers of one thread (section "The coset-leader search" of [problems.md](problems.md#the-coset-leader-search)). +The batch queries of `CosetLeaderSearch` instead move the rest of a costly batch to threads, in blocks of syndromes, each of which one compiled call answers, and give the answers of one thread (section "The coset-leader search" of [problems.md](problems.md#the-coset-leader-search)). The comment of `search_chunk_exponent` in `_tuning.py` says when a batch moves, and in which units its queries count their work. A coset search tabulates the overlap cuts of its queries when it is built or given words, so the threads of a batch only read the search. @@ -565,13 +571,13 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | Coset leaders of Pauli errors | `ConnectedClusterCosetSearch` in `_connected_cluster/coset.py`, `CosetLeaderSearch` in `coset_leaders.py`, and `MinWeightBound` in `min_weight_bounds.py`, the bound of one query | | Sparser checks with the same span | `get_sparser_rows` and `_sparsify` in `_connected_cluster/sparse_checks.py`, and `_get_sparser_stabilizers` of `distances.py` | | Rounds of sparsifying | `max_coset_sparsifying_rounds`, `max_distance_sparsifying_rounds`, and `sparsifying_rounds_without_improvement` of `SearchTuning` in `_tuning.py` | -| Table of light vectors, and increasing limits for batches and minimum weights | `ConnectedClusterCosetSearch` (its `_singles` and `_get_min_weight_bound_and_states`), and `_get_batch_cluster_bound` and `_get_min_cluster_weight` in `_connected_cluster/coset.py`; and `tabulate_singles` of `_cosets.py` | +| Table of light vectors, and increasing limits for batches and minimum weights | `ConnectedClusterCosetSearch` in `_connected_cluster/coset.py`, with its `_singles` for single queries, and `_get_min_weight`, which compares syndromes with the checks of symbols and tries increasing limits for batches; and `tabulate_singles` of `_cosets.py` | | Logical test | `SupportSearch._get_tests`, and `_is_outside_excluded` | | Roots, ranks, and symmetries | `SupportSearch._use_automorphisms`, and `verify_automorphisms` and `get_orbits` of `_information_sets/automorphism_families.py` | | States, branching, and undoing what a state forbade when the search leaves it | `_search_supports`, whose `levels` mark the available symbols | | Weight limits on threads: the frontier, work items, replay, claims of one item, ordered commit, and when to split | `_search_on_threads`; `_MAX_ITEMS`; `paths` and `frontier_depth` of `_search_supports`; `num_threads` and `split_minimum_states` of `SupportSearch`; the constructor of `ConnectedClusterSearch`, which computes the gate `split_minimum_states` from `search_chunk_exponent` and `connected_cluster_split_shift`; `ITEMS_PER_THREAD`, `run_work_items`, and `run_items_until_first` of `_threads.py`; and `num_threads`, `search_chunk_exponent`, and `connected_cluster_split_shift` of `SearchTuning` in `_tuning.py` | | Chunks of a weight limit, on one thread and on threads | `_search_in_chunks`, `resume`, `ends`, and `max_states` of `_search_supports`, `chunk_states` of `SupportSearch`, and `search_chunk_exponent` of `SearchTuning` in `_tuning.py` | -| Batches of syndrome queries on threads | `find_first_cluster_bound` and `get_min_cluster_weights` in `_connected_cluster/coset.py`, which `CosetLeaderSearch` calls; `ConnectedClusterCosetSearch._get_min_weight_bound_and_states`, which counts the work of a query; and `run_blocks` of `_threads.py` | +| Batches of syndrome queries on threads | `ConnectedClusterCosetSearch.find_first_not_within_max_weight` and `get_min_weights` in `_connected_cluster/coset.py`, which `CosetLeaderSearch` calls; their compiled loop `_find_min_weights`, which counts the work of each query; and `run_blocks` of `_threads.py` | | Weights, pruning, and the symbols that a state forbids for its subtree | `_get_branches`, and `restrict_viable_symbols` of `SearchTuning` in `_tuning.py`, whose `False` turns that forbidding off; the test of `b1` that skips a child is in `_search_supports` | | Overlaps with known words: loads, capacities, and the symbols that they forbid | `_get_overlap_cuts`, `_shift_cut_loads`, `SupportSearch.use_query_overlap_words`, and `stabilizer_overlap_cuts` of `SearchTuning` in `_tuning.py`, whose `False` turns the cuts off; `ConnectedClusterCosetSearch.use_query_overlap_words` and the constructor of `CosetLeaderSearch` for queries | | Sums of pairs of checks and of known words | `get_light_pair_sums` in `_connected_cluster/sparse_checks.py`, the `_summed_pairs` of `SupportSearch` and its `find_vector_with_packed_syndrome`, which maps syndromes to them, its `_known_words`, the known words of `find_witness`, and `pair_sum_checks` of `SearchTuning` in `_tuning.py`, whose `False` turns them off | @@ -587,6 +593,7 @@ Numba compiles one version of `_search_supports` for each number of 64-bit words In each fixed version, the loops over the words have a fixed length. The argument `fixed_words`, which `_get_fixed_words` makes, selects the version. Threads run `_search_supports` at once, so it is compiled with `nogil=True`, and writes only to arrays that it allocates. +So is the batch loop `_find_min_weights` of `_connected_cluster/coset.py`, which calls it through the inlined `_get_min_weight`, and which also writes the weights of its own rows. ## 5. Correctness requirements @@ -614,7 +621,7 @@ Changes to the search can use other bounds and orders, but must keep these requi The search keeps only the distinct nonzero checks, so the syndrome of the given checks must be mapped onto them, and a syndrome with a nonzero entry for a zero check, or with different entries for two equal checks, has no solution. - **Reuse an overlap or a repair only within the state that computed it**, since another state can have another syndrome or other weights. Compute a repair only after weighing all the unsatisfied checks, since it sums their weights. -- **Give coset queries only proven lower bounds**: a bound of 2 needs the syndrome to be missing from the table of the vectors of weight at most 1, and a bound above a limit needs a complete search at that limit ([Section 3.8](#38-vectors-with-a-given-syndrome)). +- **Give coset queries only proven lower bounds**: a bound of 2 needs the syndrome to have no solution of weight at most 1, which the table of these vectors or the comparison with the checks of symbols shows, and a bound above a limit needs a complete search at that limit ([Section 3.8](#38-vectors-with-a-given-syndrome)). A caller that raises its limit to each bound would silently get wrong weights from a bound above the minimum, so the tests compare the exact bounds with brute force. - **Keep the span of the checks of a coset query**, with an invertible map of the syndromes to the sparser checks, or the queries would search other cosets. - **Keep the span of the stabilizers of a subsystem code exactly** ([Section 3.9](#39-sparser-stabilizers-of-subsystem-codes)): a smaller span would admit words that anticommute with a stabilizer, and a larger one would miss dressed logical operators; redundant rows need no map. @@ -629,9 +636,9 @@ Changes to the search can use other bounds and orders, but must keep these requi A pruning rule may keep per-state data only if leaving the state undoes it, as `levels` and the loads of the overlap cuts do, and may add checks and known words only as tables built before the search, as the light sums of pairs of checks are ([Section 3.4](#34-pruning)). It must not carry memos, learned constraints, or sets of states already seen from one state or root to another, and must keep the depth-first order of the search. A change that breaks this, such as a best-first search ([Section 3.10](#310-techniques-not-used)), needs its own way to split a limit across threads. - - **Keep `_search_supports` writing only to arrays that it allocates**, and never to the tables of the search, since threads run it without the global interpreter lock. + - **Keep `_search_supports`, and the batch loop `_find_min_weights` of `_connected_cluster/coset.py`, writing only to arrays that they allocate**, and the loop also to the weights of its own rows, but never to the tables of the search, since threads run them without the global interpreter lock. `test_limits_on_threads_give_the_witnesses_and_states_of_one_thread` in `_connected_cluster/search_test.py` runs threads with every array of their search, such as its tables, read-only, and gives each call of `_search_supports` on threads read-only views of its other arrays, such as the roots and paths of work items and the paths and ends of chunks, so that numba rejects a write to one in any branch of compiled code. - `test_connected_cluster_batches_on_threads_answer_as_on_one_thread` in `coset_leaders_test.py` does the same for batches of coset queries. + `test_connected_cluster_batches_on_threads_answer_as_on_one_thread` in `coset_leaders_test.py` does the same for batches of coset queries, whose batch loop gets read-only views of every array but the weights that it writes. Both check that the arrays are unchanged. Review checks the writes that these tests miss, such as those through `.flat`, `np.ascontiguousarray`, `np.asfortranarray`, `np.nditer`, or `np.fill_diagonal`, which numba compiles anyway; those on paths that the tests do not run with the arrays read-only; and, in plain Python, those that tests do not run. - **Write shared results only in a thread's own entries, or under a lock.** diff --git a/src/qldpc/codes/distance/coset_leaders.py b/src/qldpc/codes/distance/coset_leaders.py index 6057818e0..2bcdede9f 100644 --- a/src/qldpc/codes/distance/coset_leaders.py +++ b/src/qldpc/codes/distance/coset_leaders.py @@ -34,11 +34,7 @@ get_pauli_search, ) from ._code_matrices import as_binary_matrix, as_integer, swap_pauli_halves -from ._connected_cluster.coset import ( - ConnectedClusterCosetSearch, - find_first_cluster_bound, - get_min_cluster_weights, -) +from ._connected_cluster.coset import ConnectedClusterCosetSearch from ._cosets import xor_selected, xor_selected_rows from ._tuning import get_tuning from .min_weight_bounds import MinWeightBound @@ -208,16 +204,16 @@ def __init__( # its X part (problems.md, "The coset-leader search"), and likewise for Z. x_syndrome_map = multiply_binary(z_transform, z_combinations) z_syndrome_map = multiply_binary(x_transform, x_combinations) - # Only the batch queries of the BZ searches read the packed columns of the maps. - if self._brouwer_zimmermann_searches: - self._map_columns = ( - pack_bits(np.ascontiguousarray(x_syndrome_map.T)), - pack_bits(np.ascontiguousarray(z_syndrome_map.T)), - ) + # The batch queries read the packed columns of the maps. + self._map_columns = ( + pack_bits(np.ascontiguousarray(x_syndrome_map.T)), + pack_bits(np.ascontiguousarray(z_syndrome_map.T)), + ) # Entry ``i`` of ``_joint_map_columns`` holds column ``i`` of the X map in its low # ``_num_x_syndrome_bits`` bits, and that of the Z map above them. So ``_split_syndrome`` - # maps a syndrome by XORing the entries of its set bits, which is cheap for few set bits. + # maps the syndrome of a single query by XORing the entries of its set bits, which is cheap + # for few set bits. self._num_x_syndrome_bits = len(z_rows) self._joint_map_columns = row_ints( np.ascontiguousarray(np.vstack([x_syndrome_map, z_syndrome_map]).T) @@ -288,20 +284,12 @@ def find_first_not_within_max_weight( self._check_syndromes(syndromes) max_weight = self._as_max_weight(max_weight) - # The connected-cluster searches answer one syndrome at a time. - if self._connected_cluster_searches: - return find_first_cluster_bound( - self._connected_cluster_searches, - syndromes, - max_weight, - self._split_syndrome, - self._join_part_bounds, - **self._thread_options, - ) - - # With one search, take its bound and the lightest error that it weighed. - if len(self._brouwer_zimmermann_searches) == 1: - return self._brouwer_zimmermann_searches[0].find_first_not_within_max_weight( + # With one search, take its bound. + searches: tuple[ConnectedClusterCosetSearch | BrouwerZimmermannCosetSearch, ...] = ( + self._connected_cluster_searches or self._brouwer_zimmermann_searches + ) + if len(searches) == 1: + return searches[0].find_first_not_within_max_weight( syndromes, max_weight, **self._thread_options ) @@ -310,7 +298,7 @@ def find_first_not_within_max_weight( # syndromes before the first whose X part has none, and ``get_min_weight_bound`` joins the # bounds of both parts. index = len(syndromes) - for search, map_columns in zip(self._brouwer_zimmermann_searches, self._map_columns): + for search, map_columns in zip(searches, self._map_columns): part_syndromes = _map_syndromes(syndromes[:index], map_columns) index, _ = search.find_first_not_within_max_weight( part_syndromes, max_weight, **self._thread_options @@ -342,29 +330,20 @@ def get_min_weights( self._check_syndromes(syndromes) max_weight = self._as_max_weight(max_weight) - # The connected-cluster searches answer one syndrome at a time. - if self._connected_cluster_searches: - return get_min_cluster_weights( - self._connected_cluster_searches, - syndromes, - max_weight, - self._split_syndrome, - **self._thread_options, - ) - # Every search starts from weight zero, except those of the Z parts below. floors = np.zeros(len(syndromes), dtype=np.int64) # With one search, take its weights. - if len(self._brouwer_zimmermann_searches) == 1: - return self._brouwer_zimmermann_searches[0].get_min_weights( + searches = self._connected_cluster_searches or self._brouwer_zimmermann_searches + if len(searches) == 1: + return searches[0].get_min_weights( syndromes, max_weight, floors, **self._thread_options ) # With two searches, search the Z parts only of the classes whose X parts are within # ``max_weight``, with the weight of the X part as the floor (problems.md, "The coset-leader # search"). - x_search, z_search = self._brouwer_zimmermann_searches + x_search, z_search = searches x_syndromes = _map_syndromes(syndromes, self._map_columns[0]) weights = x_search.get_min_weights(x_syndromes, max_weight, floors, **self._thread_options) rows = np.flatnonzero(weights <= max_weight) diff --git a/src/qldpc/codes/distance/coset_leaders_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index a4f2a5230..3450eae71 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -4,7 +4,6 @@ from __future__ import annotations -import inspect import itertools import threading from collections.abc import Sequence @@ -23,7 +22,6 @@ from . import _threads, coset_leaders from ._brouwer_zimmermann.coset import BrouwerZimmermannCosetSearch from ._connected_cluster import coset as cluster_coset -from ._connected_cluster import search as cluster_search from ._tuning import MAX_VALUE, use_tuning from .conftest import ( ROUTED_CSS_WEIGHT_STATE, @@ -41,7 +39,6 @@ split_syndromes_into_words, ) from .coset_leaders import CosetLeaderSearch, CosetMethod, _get_coset_search_method -from .min_weight_bounds import MinWeightBound # Four-qubit blocks: a GHZ state, which is CSS, and the same state after S on its first qubit, which # is not. By CSS weight, a search splits into X and Z parts only on the GHZ block, and by physical @@ -856,8 +853,8 @@ def test_connected_cluster_batches_on_threads_answer_as_on_one_thread( weight and by CSS weight. With chunks of one state, a batch moves to threads once its queries have visited a state for each thread. The queries run with every array of their searches read-only: the threads of a batch share them, and so do the threads of callers that share a - search. Each call of ``_search_supports`` under these read-only tables also gets read-only - views of its other arrays, such as the syndrome of its query. + search. Each call of the compiled batch loop also gets read-only views of its other arrays but + the weights that it writes: the syndromes of its block and their floors. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) cases = [(get_random_css_state(6, 3, rng), True), (get_random_css_state(6, 2, rng), False)] @@ -870,22 +867,26 @@ def run_counted(*args: Any, **kwargs: Any) -> None: thread_runs += 1 run_work_items(*args, **kwargs) - # A call whose tables are read-only gets read-only views of every array, as the calls on threads - # of distance searches do in ``_connected_cluster/search_test.py``, so that numba compiles one - # read-only version for both, and rejects a write to any array of a query. - search_supports = cluster_search._search_supports - masks_index = list(inspect.signature(search_supports).parameters).index("symbol_masks") + # Every query runs with read-only tables, so each call gets read-only views of its other arrays + # but its output too, as the calls on threads of distance searches do in + # ``_connected_cluster/search_test.py``. So numba compiles one read-only version for both, and + # rejects a write to any array of a query, including in ``_search_supports``, which the loop + # calls. + find_min_weights = cluster_coset._find_min_weights - def search_read_only(*args: Any) -> Any: - """Search with read-only views of every array argument, if the tables are read-only.""" - if not args[masks_index].flags.writeable: - args = tuple( - _get_read_only(arg) if isinstance(arg, np.ndarray) else arg for arg in args - ) - return search_supports(*args) + def search_read_only( + syndromes: npt.NDArray[np.uint64], + max_weight: int, + floors: npt.NDArray[np.int64], + *args: Any, + ) -> Any: + """Search with read-only views of the syndromes and their floors.""" + return find_min_weights( + _get_read_only(syndromes), max_weight, _get_read_only(floors), *args + ) + monkeypatch.setattr(cluster_coset, "_find_min_weights", search_read_only) monkeypatch.setattr(_threads, "run_work_items", run_counted) - monkeypatch.setattr(cluster_search, "_search_supports", search_read_only) for matrix, css_weight in cases: num_qubits = len(matrix) minima = get_exhaustive_minima(matrix, css_weight) @@ -931,7 +932,7 @@ def test_connected_cluster_batches_keep_the_least_index_whichever_block_ends_fir """ later_ran, later_started, first_ran = (threading.Event() for _ in range(3)) run_work_items = _threads.run_work_items - get_bound = cluster_coset._get_batch_cluster_bound + find_min_weights = cluster_coset._find_min_weights minima = get_exhaustive_minima(_THREADED_STATE, False) heavy = np.flatnonzero(minima > 2).tolist() syndromes = [3, heavy[0]] + [heavy[1 + row % (len(heavy) - 1)] for row in range(30)] @@ -957,19 +958,19 @@ def gated_range(start: int, end: int) -> None: run_work_items(num_items, num_threads, gated_start, **kwargs) - def gated_bound(searches: Any, syndrome: int, *args: Any) -> tuple[MinWeightBound, int]: - """Get the bound of a query; later ones wait for the first range unless ``later_first``.""" - if not later_first and syndrome not in syndromes[:2]: + def gated_search(block: npt.NDArray[np.uint64], *args: Any) -> tuple[int, bool]: + """Search a block; later ones wait for the first range unless ``later_first``.""" + if not later_first and int(block[0, 0]) not in syndromes[:2]: later_started.set() assert first_ran.wait(timeout=THREAD_TIMEOUT) - return get_bound(searches, syndrome, *args) + return find_min_weights(block, *args) batch = split_syndromes_into_words(syndromes, len(_THREADED_STATE)) with use_tuning(num_threads=1, search_chunk_exponent=0): search = CosetLeaderSearch(_THREADED_STATE, method="connected_cluster") expected = search.find_first_not_within_max_weight(batch, 2) monkeypatch.setattr(_threads, "run_work_items", gated_run) - monkeypatch.setattr(cluster_coset, "_get_batch_cluster_bound", gated_bound) + monkeypatch.setattr(cluster_coset, "_find_min_weights", gated_search) with use_tuning(num_threads=2, search_chunk_exponent=0): search = CosetLeaderSearch(_THREADED_STATE, method="connected_cluster") index, bound = search.find_first_not_within_max_weight(batch, 2) diff --git a/src/qldpc/codes/distance/problems.md b/src/qldpc/codes/distance/problems.md index ac3c8be9a..0d017ed71 100644 --- a/src/qldpc/codes/distance/problems.md +++ b/src/qldpc/codes/distance/problems.md @@ -158,10 +158,11 @@ The answers are those of one thread: the weights, and the first index without an With `method="connected_cluster"`, each `CosetLeaderSearch` builds its own coset searches, `ConnectedClusterCosetSearch` in `_connected_cluster/coset.py`, which make their checks sparser with `get_sparser_rows` and run `SupportSearch` from the syndrome of a query (Section 3.8 of `connected_cluster.md`); their checks are the stabilizers for Pauli errors, the pure-Z stabilizers for X parts, and the pure-X stabilizers for Z parts. This method weighs errors by CSS weight only on CSS states (Section 3.8 of `connected_cluster.md`). The class docstring of `ConnectedClusterCosetSearch` states the lower bounds of its answers. -`find_first_not_within_max_weight` and `get_min_weights` try increasing weight limits (`find_first_cluster_bound` and `get_min_cluster_weights` of `_connected_cluster/coset.py`), which can find light errors sooner than one search at `max_weight`. +`CosetLeaderSearch` runs the batch queries of these searches, `find_first_not_within_max_weight` and `get_min_weights` of `ConnectedClusterCosetSearch`, as it runs those of BZ searches, with the same maps of syndromes to X and Z parts and the same floors. +They try increasing weight limits, which can find light errors sooner than one search at `max_weight`, and answer each block of a batch in one compiled call (Section 3.8 of `connected_cluster.md`). They move a costly batch to threads with `run_blocks` too, by the same rule; a query that looks up its error visits no states, and so does no work. Their answers are those of one thread (Section 3.11 of `connected_cluster.md`). -For the CSS weight, the bound that `find_first_not_within_max_weight` returns holds an error for each part, and for a part within `max_weight`, that error can differ from the one that `get_min_weight_bound` gives. +`find_first_not_within_max_weight` returns the bound that `get_min_weight_bound` gives for the first syndrome without an error within `max_weight`. The table "Routes and the names that control them" of [Exact-search performance and tuning](../../../../docs/source/exact_search_tuning.rst) names the fields that configure the searches of `CosetLeaderSearch`.