From eeddbd9e45dc10cb5dbcf7677def065c687eb6d1 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 11:07:27 -0500 Subject: [PATCH 01/16] Answer connected-cluster coset batches in one compiled call per block ConnectedClusterCosetSearch gets the batch queries find_first_not_within_max_weight and get_min_weights of BrouwerZimmermannCosetSearch, with the same signatures, floors, and thread options. Each block of a batch runs in one nogil compiled call, _find_first_not_within_max_weight or _find_min_weights, which maps each syndrome to the sparser checks, finds its words of weight at most one by comparing it with the checks of the symbols of its first check, and tries increasing weight limits with _search_supports. CosetLeaderSearch drives these searches as it drives BZ searches, so the Python batch loops of _connected_cluster/coset.py are gone. Single queries keep their Python path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset.py | 516 ++++++++++++------ .../distance/_connected_cluster/coset_test.py | 103 +++- src/qldpc/codes/distance/connected_cluster.md | 25 +- src/qldpc/codes/distance/coset_leaders.py | 59 +- .../codes/distance/coset_leaders_test.py | 57 +- src/qldpc/codes/distance/problems.md | 5 +- 6 files changed, 499 insertions(+), 266 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset.py b/src/qldpc/codes/distance/_connected_cluster/coset.py index 1e0aa3d05..5fbea1ac5 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset.py @@ -2,34 +2,36 @@ """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 +from typing import Any 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, _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] - #################################################################################################### # coset searches @@ -40,20 +42,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 +95,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 +143,127 @@ 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. + """ + syndromes = np.ascontiguousarray(syndromes) + tables = self._get_batch_tables() + + def search_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: + """Search rows in order, up to the first without a light enough word.""" + index, ends = _find_first_not_within_max_weight( + syndromes[start:end], max_weight, max_work, *tables + ) + return start + index + int(ends), bool(ends) + + index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) + 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``. + """ + 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.""" + num_done = _find_min_weights( + syndromes[start:end], + max_weight, + floors[start:end], + max_work, + weights[start:end], + *tables, + ) + return start + num_done, False + + _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) + return weights + + def _get_batch_tables(self) -> tuple[Any, ...]: + """The arguments of the compiled batch queries from ``map_columns`` on. + + 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 +282,232 @@ 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_first_not_within_max_weight( 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 + max_work: int, + map_columns: npt.NDArray[np.uint64], + check_starts: npt.NDArray[np.int64], + check_symbols: npt.NDArray[np.int64], + symbol_masks: npt.NDArray[np.uint64], + test_columns: npt.NDArray[np.uint64], + ranks: npt.NDArray[np.int64], + inverse_overlaps: npt.NDArray[np.int64], + fixed_words: tuple[int, ...], + restrict_viable_symbols: bool, + cut_symbol_starts: npt.NDArray[np.int64], + cut_symbol_entries: npt.NDArray[np.int64], + cut_starts: npt.NDArray[np.int64], + cut_entries: npt.NDArray[np.int64], + cut_capacities: npt.NDArray[np.int64], + cut_blocked_symbols: npt.NDArray[np.int64], +) -> tuple[int, bool]: + """Search the coset of each syndrome in turn with ``_get_min_weight``, within a budget of work. + + The arguments from ``map_columns`` on are those of ``_get_min_weight``. The work of a query is + the number of states that its searches visit. The search stops at the first syndrome whose + coset has no word within ``max_weight``, or once the work of this call reaches ``max_work``, or + after the last syndrome. Threads run it at once, so it writes only to arrays that it allocates. - index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: run_rows) - return index, found.get(index) + Returns: + If the search found 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. + """ + mapped = np.empty(symbol_masks.shape[1], dtype=np.uint64) + work = 0 + for index in range(len(syndromes)): + weight, num_states = _get_min_weight( + syndromes[index], + max_weight, + 2, + mapped, + map_columns, + check_starts, + check_symbols, + symbol_masks, + test_columns, + ranks, + inverse_overlaps, + fixed_words, + restrict_viable_symbols, + cut_symbol_starts, + cut_symbol_entries, + cut_starts, + cut_entries, + cut_capacities, + cut_blocked_symbols, + ) + if weight > max_weight: + return index, True + work += num_states + if work >= max_work: + return index + 1, False + return len(syndromes), False -def get_min_cluster_weights( - searches: tuple[ConnectedClusterCosetSearch, ...], +@always_compiled(nogil=True) +def _find_min_weights( 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. - """ - 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 + floors: npt.NDArray[np.int64], + max_work: int, + weights: npt.NDArray[np.int64], + map_columns: npt.NDArray[np.uint64], + check_starts: npt.NDArray[np.int64], + check_symbols: npt.NDArray[np.int64], + symbol_masks: npt.NDArray[np.uint64], + test_columns: npt.NDArray[np.uint64], + ranks: npt.NDArray[np.int64], + inverse_overlaps: npt.NDArray[np.int64], + fixed_words: tuple[int, ...], + restrict_viable_symbols: bool, + cut_symbol_starts: npt.NDArray[np.int64], + cut_symbol_entries: npt.NDArray[np.int64], + cut_starts: npt.NDArray[np.int64], + cut_entries: npt.NDArray[np.int64], + cut_capacities: npt.NDArray[np.int64], + cut_blocked_symbols: npt.NDArray[np.int64], +) -> int: + """Search the coset of each syndrome in turn with ``_get_min_weight``, from its floor. + + The arguments are those of ``_find_first_not_within_max_weight``, with the floor of each + syndrome in ``floors``, and with ``weights``, into whose entry ``i`` the search writes the + weight of syndrome ``i``. It writes only ``weights`` and arrays that it allocates, so calls + that run at once may share every argument but ``weights``. - _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: run_rows) - return weights + Returns: + The number of syndromes searched: all of them, or those up to the first at which the work of + this call reaches ``max_work``. + """ + mapped = np.empty(symbol_masks.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, + map_columns, + check_starts, + check_symbols, + symbol_masks, + test_columns, + ranks, + inverse_overlaps, + fixed_words, + restrict_viable_symbols, + cut_symbol_starts, + cut_symbol_entries, + cut_starts, + cut_entries, + cut_capacities, + cut_blocked_symbols, + ) + weights[index] = weight + work += num_states + if work >= max_work: + return index + 1 + return len(syndromes) -def _get_min_cluster_weight( - searches: tuple[ConnectedClusterCosetSearch, ...], - syndrome: int, +@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], + map_columns: npt.NDArray[np.uint64], + check_starts: npt.NDArray[np.int64], + check_symbols: npt.NDArray[np.int64], + symbol_masks: npt.NDArray[np.uint64], + test_columns: npt.NDArray[np.uint64], + ranks: npt.NDArray[np.int64], + inverse_overlaps: npt.NDArray[np.int64], + fixed_words: tuple[int, ...], + restrict_viable_symbols: bool, + cut_symbol_starts: npt.NDArray[np.int64], + cut_symbol_entries: npt.NDArray[np.int64], + cut_starts: npt.NDArray[np.int64], + cut_entries: npt.NDArray[np.int64], + cut_capacities: npt.NDArray[np.int64], + cut_blocked_symbols: npt.NDArray[np.int64], ) -> 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`` 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 arguments from ``check_starts`` on + 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 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): + 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_viable_symbols, + cut_symbol_starts, + cut_symbol_entries, + cut_starts, + cut_entries, + cut_capacities, + cut_blocked_symbols, + ) + 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..59ab7228a 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -59,9 +59,10 @@ def test_connected_cluster_queries_add_no_pair_sums(monkeypatch: pytest.MonkeyPa """The coset searches of ``CosetLeaderSearch`` search their sparser checks without pair sums. The checks of a repetition code have light sums of pairs, which distance searches would add, - but queries search only the checks themselves (Sections 3.4 and 3.8 of + but queries, single or in batches, search only the checks themselves (Sections 3.4 and 3.8 of ``connected_cluster.md``). """ + batch_check_starts = _record_batch_argument(monkeypatch, "check_starts") num_checks: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -86,13 +87,15 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: # The syndrome of the first and last checks has no word of weight one, so the query searches. assert coset_search.get_min_weight_bound(0b101, 2).within_max_weight assert num_checks == [len(coset_search.checks)] + _run_batches(coset_search, [0b101], 2) + assert [len(starts) - 1 for starts in batch_check_starts] == [len(coset_search.checks)] * 2 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 +121,7 @@ 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 + _run_batches(coset_search, [0b101, 0b111, 0b100], 2) assert len(tabulated) == num_tabulated @@ -125,7 +129,8 @@ 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 and batch queries.""" + batch_settings = _record_batch_argument(monkeypatch, "restrict_viable_symbols") settings: list[bool] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -150,13 +155,19 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: ) assert coset_search.get_min_weight_bound(syndrome, 2).within_max_weight assert settings and set(settings) == {restrict_viable_symbols} + _run_batches(coset_search, [syndrome], 2) + assert batch_settings == [restrict_viable_symbols] * 2 @pytest.mark.parametrize("cuts", [True, False]) 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 queries exactly when its switch is on. + + This holds for single queries and for batches. + """ + batch_capacities = _record_batch_argument(monkeypatch, "cut_capacities") num_cuts_per_query: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -177,10 +188,14 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: coset_search.use_query_overlap_words(coset_search.checks) # Every syndrome that the table of light words lacks starts a query. - for syndrome in range(1, 2 ** len(coset_search.checks)): + syndromes = range(1, 2 ** len(coset_search.checks)) + for syndrome in syndromes: coset_search.get_min_weight_bound(syndrome, 3) assert num_cuts_per_query assert all(bool(num_cuts) == cuts for num_cuts in num_cuts_per_query) + _run_batches(coset_search, list(syndromes), 3) + assert len(batch_capacities) == 2 + assert all(bool(len(capacities)) == cuts for capacities in batch_capacities) @pytest.mark.parametrize("cuts", [True, False]) @@ -190,9 +205,10 @@ 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``. The batch queries find the first coset without a + word within ``max_weight``, with the bound of a single query, and 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 +236,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 +253,32 @@ 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 floors of zero and random floors. + capped = np.minimum(minima, max_weight + 1) + zeros = np.zeros(len(batch), dtype=np.int64) + assert np.array_equal( + coset_search.get_min_weights(batch, max_weight, zeros), capped + ) + 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], capped[~within]) + above = np.flatnonzero(minima > max_weight).tolist() + index, first_bound = coset_search.find_first_not_within_max_weight( + batch, max_weight + ) + assert index == (above[0] if above else len(batch)) + if above: + assert first_bound == coset_search.get_min_weight_bound(index, max_weight) + else: + assert first_bound is None + 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 +304,31 @@ 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 _record_batch_argument(monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: + """Record an argument of each call of the compiled batch queries of ``coset``, and run them.""" + values: list[Any] = [] + for entry_name in ("_find_first_not_within_max_weight", "_find_min_weights"): + entry = getattr(coset, entry_name) + + def record(*args: Any, entry: Any = entry) -> Any: + """Record the argument of a call, and run it.""" + values.append(inspect.signature(entry).bind(*args).arguments[name]) + return entry(*args) + + monkeypatch.setattr(coset, entry_name, record) + return values + + +def _run_batches( + coset_search: coset.ConnectedClusterCosetSearch, syndromes: list[int], max_weight: int +) -> None: + """Run both batch queries of a coset search on a batch of syndromes, from floors of zero.""" + batch = split_syndromes_into_words(syndromes, len(coset_search.checks)) + coset_search.find_first_not_within_max_weight(batch, max_weight) + coset_search.get_min_weights(batch, max_weight, np.zeros(len(batch), dtype=np.int64)) diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index f400f4f96..973d889d1 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 compiled call, `_find_first_not_within_max_weight` or `_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 loops `_find_first_not_within_max_weight` and `_find_min_weights`, which count 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 are the batch loops `_find_first_not_within_max_weight` and `_find_min_weights` of `_connected_cluster/coset.py`, which call it through the inlined `_get_min_weight`, and which also write the weights of their 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 loops `_find_first_not_within_max_weight` and `_find_min_weights` of `_connected_cluster/coset.py`, writing only to arrays that they allocate**, and the loops also to the weights of their 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 loops get read-only views of every array but the weights that they write. 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..7f9ce66ae 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -23,7 +23,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 +40,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 +854,9 @@ 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 a compiled batch loop under these read-only tables also gets read-only + views of its other arrays, such as the syndromes of its block, apart from the weights that it + writes. """ 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 +869,32 @@ 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") - - 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) + # A call whose tables are read-only gets read-only views of every array but its output, 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, + # including in ``_search_supports``, which the loops call. + for name in ("_find_first_not_within_max_weight", "_find_min_weights"): + batch_loop = getattr(cluster_coset, name) + parameters = list(inspect.signature(batch_loop).parameters) + + def search_read_only( + *args: Any, + batch_loop: Any = batch_loop, + masks_index: int = parameters.index("symbol_masks"), + output_index: int = parameters.index("weights") if "weights" in parameters else -1, + ) -> Any: + """Search with read-only views of the array arguments, if the tables are read-only.""" + if not args[masks_index].flags.writeable: + args = tuple( + _get_read_only(arg) + if isinstance(arg, np.ndarray) and index != output_index + else arg + for index, arg in enumerate(args) + ) + return batch_loop(*args) + monkeypatch.setattr(cluster_coset, name, 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 +940,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_first = cluster_coset._find_first_not_within_max_weight 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 +966,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_find_first(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_first(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_first_not_within_max_weight", gated_find_first) 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`. From 6280e3385e9e1a53a68c7fda2688355cfffcbfce Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 11:24:11 -0500 Subject: [PATCH 02/16] Check that connected-cluster batches search with the restriction and cuts of single queries A test counts the states that a batch query visits, through the work that its compiled loop counts, and compares them with those of single queries at the same limits, on a case where restrict_viable_symbols and the overlap cuts each change that number. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 98 ++++++++++++++++--- 1 file changed, 87 insertions(+), 11 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 59ab7228a..8367a001c 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -12,8 +12,9 @@ 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 .._cosets import xor_selected from .._tuning import use_tuning from ..conftest import ( get_binary_minima, @@ -129,8 +130,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 single and batch queries.""" - batch_settings = _record_batch_argument(monkeypatch, "restrict_viable_symbols") + """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) @@ -155,19 +158,16 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: ) assert coset_search.get_min_weight_bound(syndrome, 2).within_max_weight assert settings and set(settings) == {restrict_viable_symbols} - _run_batches(coset_search, [syndrome], 2) - assert batch_settings == [restrict_viable_symbols] * 2 @pytest.mark.parametrize("cuts", [True, False]) 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. - This holds for single queries and for batches. + ``test_connected_cluster_batches_search_as_single_queries`` checks its batch queries. """ - batch_capacities = _record_batch_argument(monkeypatch, "cut_capacities") num_cuts_per_query: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -193,9 +193,37 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: coset_search.get_min_weight_bound(syndrome, 3) assert num_cuts_per_query assert all(bool(num_cuts) == cuts for num_cuts in num_cuts_per_query) - _run_batches(coset_search, list(syndromes), 3) - assert len(batch_capacities) == 2 - assert all(bool(len(capacities)) == cuts for capacities in batch_capacities) + + +@pytest.mark.parametrize("switch", ["restrict_viable_symbols", "cuts"]) +def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None: + """Batch queries visit the states of single queries at their limits, with a switch on and off. + + So they search with the restriction and the overlap cuts of the coset search. 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 each switch, which is otherwise on. + """ + 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], len(matrix)) + counts = [] + for setting in (True, False): + options = {"restrict_viable_symbols": True, "cuts": True, switch: setting} + coset_search = coset.ConnectedClusterCosetSearch( + matrix, + symplectic=True, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=options["restrict_viable_symbols"], + stabilizer_overlap_cuts=options["cuts"], + ) + coset_search.use_query_overlap_words(coset_search.checks) + assert coset_search.get_min_weights(batch, 2, np.zeros(1, dtype=np.int64)).tolist() == [2] + num_states = _count_batch_states(coset_search, syndrome, 2) + assert num_states == _count_single_states(coset_search, syndrome, 2) + counts.append(num_states) + assert counts[0] != counts[1] @pytest.mark.parametrize("cuts", [True, False]) @@ -332,3 +360,51 @@ def _run_batches( batch = split_syndromes_into_words(syndromes, len(coset_search.checks)) coset_search.find_first_not_within_max_weight(batch, max_weight) coset_search.get_min_weights(batch, max_weight, np.zeros(len(batch), dtype=np.int64)) + + +def _count_batch_states( + coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int +) -> int: + """The number of states that a batch query visits, as the compiled loop counts its work. + + ``_find_min_weights`` stops after a query once its work reaches ``max_work``, so of two copies + of a syndrome that is not looked up, it searches only the first exactly if the first visits at + least ``max_work`` states. A search for the largest such ``max_work`` finds that number. + """ + batch = split_syndromes_into_words([syndrome, syndrome], len(coset_search.checks)) + floors = np.zeros(2, dtype=np.int64) + weights = np.empty(2, dtype=np.int64) + tables = coset_search._get_batch_tables() + + def searches_one(max_work: int) -> bool: + """Whether the batch stops after the first copy within ``max_work``.""" + num_done = coset._find_min_weights(batch, max_weight, floors, max_work, weights, *tables) + return bool(num_done == 1) + + low, high = 0, 1 + while searches_one(high): + low, high = high, 2 * high + while high - low > 1: + middle = (low + high) // 2 + low, high = (middle, high) if searches_one(middle) else (low, middle) + return low + + +def _count_single_states( + coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int +) -> int: + """The number of states that single queries visit at the limits 2, 3, ... up to a vector. + + The syndrome must have no vector of weight at most one. + """ + mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) + packed_syndrome = int_to_words(mapped, get_num_words(len(coset_search.checks))) + num_states = 0 + for limit in range(2, max_weight + 1): + symbols, states = coset_search._search.find_vector_with_packed_syndrome( + packed_syndrome, limit + ) + num_states += states + if symbols is not None: + break + return num_states From 5404e8f1d3b88bad3ada7ba1c3e8ba4f8f998e76 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 11:32:36 -0500 Subject: [PATCH 03/16] Check the states of both connected-cluster batch loops against single queries The test of the restriction and the overlap cuts of batch queries counts the states that _find_first_not_within_max_weight visits too, as it does for _find_min_weights. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 8367a001c..8aa67a8d2 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -197,7 +197,7 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: @pytest.mark.parametrize("switch", ["restrict_viable_symbols", "cuts"]) def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None: - """Batch queries visit the states of single queries at their limits, with a switch on and off. + """Both batch queries visit the states of single queries, with a switch on and off. So they search with the restriction and the overlap cuts of the coset search. On this CSS state, the lightest errors with the syndrome 57 weigh two, and the number of states that its @@ -220,8 +220,10 @@ def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None ) coset_search.use_query_overlap_words(coset_search.checks) assert coset_search.get_min_weights(batch, 2, np.zeros(1, dtype=np.int64)).tolist() == [2] - num_states = _count_batch_states(coset_search, syndrome, 2) - assert num_states == _count_single_states(coset_search, syndrome, 2) + assert coset_search.find_first_not_within_max_weight(batch, 2) == (1, None) + num_states = _count_single_states(coset_search, syndrome, 2) + assert _count_batch_states(coset_search, syndrome, 2, first=True) == num_states + assert _count_batch_states(coset_search, syndrome, 2, first=False) == num_states counts.append(num_states) assert counts[0] != counts[1] @@ -363,13 +365,15 @@ def _run_batches( def _count_batch_states( - coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int + coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int, *, first: bool ) -> int: - """The number of states that a batch query visits, as the compiled loop counts its work. + """The number of states that a batch query visits, as its compiled loop counts its work. - ``_find_min_weights`` stops after a query once its work reaches ``max_work``, so of two copies - of a syndrome that is not looked up, it searches only the first exactly if the first visits at - least ``max_work`` states. A search for the largest such ``max_work`` finds that number. + The loop is ``_find_first_not_within_max_weight`` if ``first``, and otherwise + ``_find_min_weights``. Each stops after a query once its work reaches ``max_work``, so of two + copies of a syndrome that is not looked up and has a vector within ``max_weight``, it searches + only the first exactly if the first visits at least ``max_work`` states. A search for the + largest such ``max_work`` finds that number. """ batch = split_syndromes_into_words([syndrome, syndrome], len(coset_search.checks)) floors = np.zeros(2, dtype=np.int64) @@ -378,7 +382,14 @@ def _count_batch_states( def searches_one(max_work: int) -> bool: """Whether the batch stops after the first copy within ``max_work``.""" - num_done = coset._find_min_weights(batch, max_weight, floors, max_work, weights, *tables) + if first: + num_done, _ = coset._find_first_not_within_max_weight( + batch, max_weight, max_work, *tables + ) + else: + num_done = coset._find_min_weights( + batch, max_weight, floors, max_work, weights, *tables + ) return bool(num_done == 1) low, high = 0, 1 From df9766dcc8ed639e59070d5a415c562a40ff2dd4 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:06:36 -0500 Subject: [PATCH 04/16] Answer both connected-cluster batch queries with one compiled loop over a tuple of tables The batch queries find_first_not_within_max_weight and get_min_weights of ConnectedClusterCosetSearch now run one compiled loop, _find_min_weights, through one helper, _search_batch. The loop writes the weight of each syndrome, and stops at the first above max_weight only when find_first_not_within_max_weight asks it to, so both queries keep their results and their requirements on threads, and numba compiles one version for both. The loop and _get_min_weight take the tables of the search of the sparser checks as one plain tuple, _BatchTables, as the BZ coset searches take their tails, instead of fifteen separate arguments. _get_min_weight unpacks it once per query, and names each table in its call of _search_supports, since star-unpacking the tuples there made the queries a few percent slower. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset.py | 244 ++++++------------ .../distance/_connected_cluster/coset_test.py | 17 +- src/qldpc/codes/distance/connected_cluster.md | 10 +- .../codes/distance/coset_leaders_test.py | 56 ++-- 4 files changed, 118 insertions(+), 209 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset.py b/src/qldpc/codes/distance/_connected_cluster/coset.py index 5fbea1ac5..6a7b1b752 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset.py @@ -9,8 +9,6 @@ from __future__ import annotations -from typing import Any - import numpy as np import numpy.typing as npt @@ -29,9 +27,25 @@ 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, _get_fixed_words, _search_supports +from .search import SupportSearch, _CutTables, _get_fixed_words, _search_supports from .sparse_checks import get_sparser_rows +# 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 @@ -189,17 +203,8 @@ def find_first_not_within_max_weight( ``get_min_weight_bound`` gives for it; or the number of syndromes and None if there is none. """ - syndromes = np.ascontiguousarray(syndromes) - tables = self._get_batch_tables() - - def search_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: - """Search rows in order, up to the first without a light enough word.""" - index, ends = _find_first_not_within_max_weight( - syndromes[start:end], max_weight, max_work, *tables - ) - return start + index + int(ends), bool(ends) - - index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) + 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) @@ -227,6 +232,22 @@ def get_min_weights( 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) @@ -234,21 +255,22 @@ def get_min_weights( def search_rows(start: int, end: int, max_work: int) -> tuple[int, bool]: """Search rows in order, and write their weights.""" - num_done = _find_min_weights( + index, ends = _find_min_weights( syndromes[start:end], max_weight, floors[start:end], max_work, + stop_above_max_weight, weights[start:end], - *tables, + tables, ) - return start + num_done, False + return start + index + int(ends), bool(ends) - _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) - return weights + index = _threads.run_blocks(len(syndromes), num_threads, split_work, lambda: search_rows) + return index, weights - def _get_batch_tables(self) -> tuple[Any, ...]: - """The arguments of the compiled batch queries from ``map_columns`` on. + 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``). @@ -257,12 +279,12 @@ def _get_batch_tables(self) -> tuple[Any, ...]: assert search._query_cuts is not None return ( self._packed_map_columns, - *search._check_tables, + 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, + search._query_cuts, ) def _get_word(self, symbols: npt.NDArray[np.int64]) -> int: @@ -286,62 +308,37 @@ def _get_word(self, symbols: npt.NDArray[np.int64]) -> int: @always_compiled(nogil=True) -def _find_first_not_within_max_weight( +def _find_min_weights( syndromes: npt.NDArray[np.uint64], max_weight: int, + floors: npt.NDArray[np.int64], max_work: int, - map_columns: npt.NDArray[np.uint64], - check_starts: npt.NDArray[np.int64], - check_symbols: npt.NDArray[np.int64], - symbol_masks: npt.NDArray[np.uint64], - test_columns: npt.NDArray[np.uint64], - ranks: npt.NDArray[np.int64], - inverse_overlaps: npt.NDArray[np.int64], - fixed_words: tuple[int, ...], - restrict_viable_symbols: bool, - cut_symbol_starts: npt.NDArray[np.int64], - cut_symbol_entries: npt.NDArray[np.int64], - cut_starts: npt.NDArray[np.int64], - cut_entries: npt.NDArray[np.int64], - cut_capacities: npt.NDArray[np.int64], - cut_blocked_symbols: npt.NDArray[np.int64], + 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 arguments from ``map_columns`` on are those of ``_get_min_weight``. The work of a query is - the number of states that its searches visit. The search stops at the first syndrome whose - coset has no word within ``max_weight``, or once the work of this call reaches ``max_work``, or - after the last syndrome. Threads run it at once, so it writes only to arrays that it allocates. + 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``. Returns: - If the search found 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. + 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. """ - mapped = np.empty(symbol_masks.shape[1], dtype=np.uint64) + # 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, - 2, - mapped, - map_columns, - check_starts, - check_symbols, - symbol_masks, - test_columns, - ranks, - inverse_overlaps, - fixed_words, - restrict_viable_symbols, - cut_symbol_starts, - cut_symbol_entries, - cut_starts, - cut_entries, - cut_capacities, - cut_blocked_symbols, + syndromes[index], max_weight, floors[index], mapped, tables ) - if weight > max_weight: + weights[index] = weight + if stop_above_max_weight and weight > max_weight: return index, True work += num_states if work >= max_work: @@ -349,110 +346,34 @@ def _find_first_not_within_max_weight( return len(syndromes), False -@always_compiled(nogil=True) -def _find_min_weights( - syndromes: npt.NDArray[np.uint64], - max_weight: int, - floors: npt.NDArray[np.int64], - max_work: int, - weights: npt.NDArray[np.int64], - map_columns: npt.NDArray[np.uint64], - check_starts: npt.NDArray[np.int64], - check_symbols: npt.NDArray[np.int64], - symbol_masks: npt.NDArray[np.uint64], - test_columns: npt.NDArray[np.uint64], - ranks: npt.NDArray[np.int64], - inverse_overlaps: npt.NDArray[np.int64], - fixed_words: tuple[int, ...], - restrict_viable_symbols: bool, - cut_symbol_starts: npt.NDArray[np.int64], - cut_symbol_entries: npt.NDArray[np.int64], - cut_starts: npt.NDArray[np.int64], - cut_entries: npt.NDArray[np.int64], - cut_capacities: npt.NDArray[np.int64], - cut_blocked_symbols: npt.NDArray[np.int64], -) -> int: - """Search the coset of each syndrome in turn with ``_get_min_weight``, from its floor. - - The arguments are those of ``_find_first_not_within_max_weight``, with the floor of each - syndrome in ``floors``, and with ``weights``, into whose entry ``i`` the search writes the - weight of syndrome ``i``. It writes only ``weights`` and arrays that it allocates, so calls - that run at once may share every argument but ``weights``. - - Returns: - The number of syndromes searched: all of them, or those up to the first at which the work of - this call reaches ``max_work``. - """ - mapped = np.empty(symbol_masks.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, - map_columns, - check_starts, - check_symbols, - symbol_masks, - test_columns, - ranks, - inverse_overlaps, - fixed_words, - restrict_viable_symbols, - cut_symbol_starts, - cut_symbol_entries, - cut_starts, - cut_entries, - cut_capacities, - cut_blocked_symbols, - ) - weights[index] = weight - work += num_states - if work >= max_work: - return index + 1 - return len(syndromes) - - @always_compiled(inline=True) def _get_min_weight( syndrome: npt.NDArray[np.uint64], max_weight: int, first_limit: int, mapped: npt.NDArray[np.uint64], - map_columns: npt.NDArray[np.uint64], - check_starts: npt.NDArray[np.int64], - check_symbols: npt.NDArray[np.int64], - symbol_masks: npt.NDArray[np.uint64], - test_columns: npt.NDArray[np.uint64], - ranks: npt.NDArray[np.int64], - inverse_overlaps: npt.NDArray[np.int64], - fixed_words: tuple[int, ...], - restrict_viable_symbols: bool, - cut_symbol_starts: npt.NDArray[np.int64], - cut_symbol_entries: npt.NDArray[np.int64], - cut_starts: npt.NDArray[np.int64], - cut_entries: npt.NDArray[np.int64], - cut_capacities: npt.NDArray[np.int64], - cut_blocked_symbols: npt.NDArray[np.int64], + tables: _BatchTables, ) -> tuple[int, int]: """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`` 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 + ``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 arguments from ``check_starts`` on - are those of ``_search_supports``, from the search of the sparser checks. + 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: 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``. """ + 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 @@ -482,6 +403,7 @@ def _get_min_weight( 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, @@ -499,13 +421,13 @@ def _get_min_weight( mapped, fixed_words, True, - restrict_viable_symbols, - cut_symbol_starts, - cut_symbol_entries, - cut_starts, - cut_entries, - cut_capacities, - cut_blocked_symbols, + restrict, + cuts[0], + cuts[1], + cuts[2], + cuts[3], + cuts[4], + cuts[5], ) num_states += item_states[0] if len(support): diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 8aa67a8d2..6ec02597b 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -63,7 +63,7 @@ def test_connected_cluster_queries_add_no_pair_sums(monkeypatch: pytest.MonkeyPa but queries, single or in batches, search only the checks themselves (Sections 3.4 and 3.8 of ``connected_cluster.md``). """ - batch_check_starts = _record_batch_argument(monkeypatch, "check_starts") + batch_tables = _record_batch_argument(monkeypatch, "tables") num_checks: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -89,7 +89,7 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: assert coset_search.get_min_weight_bound(0b101, 2).within_max_weight assert num_checks == [len(coset_search.checks)] _run_batches(coset_search, [0b101], 2) - assert [len(starts) - 1 for starts in batch_check_starts] == [len(coset_search.checks)] * 2 + assert [len(tables[1][0]) - 1 for tables in batch_tables] == [len(coset_search.checks)] * 2 def test_connected_cluster_queries_only_read_their_search(monkeypatch: pytest.MonkeyPatch) -> None: @@ -343,7 +343,7 @@ def test_connected_cluster_batches_match_exhaustive_minima() -> None: def _record_batch_argument(monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: """Record an argument of each call of the compiled batch queries of ``coset``, and run them.""" values: list[Any] = [] - for entry_name in ("_find_first_not_within_max_weight", "_find_min_weights"): + for entry_name in ("_find_min_weights",): entry = getattr(coset, entry_name) def record(*args: Any, entry: Any = entry) -> Any: @@ -382,14 +382,9 @@ def _count_batch_states( def searches_one(max_work: int) -> bool: """Whether the batch stops after the first copy within ``max_work``.""" - if first: - num_done, _ = coset._find_first_not_within_max_weight( - batch, max_weight, max_work, *tables - ) - else: - num_done = coset._find_min_weights( - batch, max_weight, floors, max_work, weights, *tables - ) + num_done, _ = coset._find_min_weights( + batch, max_weight, floors, max_work, first, weights, tables + ) return bool(num_done == 1) low, high = 0, 1 diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index 973d889d1..dcc01f8a9 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -365,7 +365,7 @@ A query at limit `W` can wander through many heavy supports before it reaches a 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 compiled call, `_find_first_not_within_max_weight` or `_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. +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. @@ -577,7 +577,7 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | 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 | `ConnectedClusterCosetSearch.find_first_not_within_max_weight` and `get_min_weights` in `_connected_cluster/coset.py`, which `CosetLeaderSearch` calls; their compiled loops `_find_first_not_within_max_weight` and `_find_min_weights`, which count the work of each 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 | @@ -593,7 +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 are the batch loops `_find_first_not_within_max_weight` and `_find_min_weights` of `_connected_cluster/coset.py`, which call it through the inlined `_get_min_weight`, and which also write the weights of their own rows. +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 @@ -636,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`, and the batch loops `_find_first_not_within_max_weight` and `_find_min_weights` of `_connected_cluster/coset.py`, writing only to arrays that they allocate**, and the loops also to the weights of their own rows, but never to the tables of the search, since threads run them 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, whose batch loops get read-only views of every array but the weights that they write. + `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_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index 7f9ce66ae..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 @@ -854,9 +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 a compiled batch loop under these read-only tables also gets read-only - views of its other arrays, such as the syndromes of its block, apart from the weights that it - writes. + 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)] @@ -869,31 +867,25 @@ 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 but its output, 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, - # including in ``_search_supports``, which the loops call. - for name in ("_find_first_not_within_max_weight", "_find_min_weights"): - batch_loop = getattr(cluster_coset, name) - parameters = list(inspect.signature(batch_loop).parameters) - - def search_read_only( - *args: Any, - batch_loop: Any = batch_loop, - masks_index: int = parameters.index("symbol_masks"), - output_index: int = parameters.index("weights") if "weights" in parameters else -1, - ) -> Any: - """Search with read-only views of the array arguments, if the tables are read-only.""" - if not args[masks_index].flags.writeable: - args = tuple( - _get_read_only(arg) - if isinstance(arg, np.ndarray) and index != output_index - else arg - for index, arg in enumerate(args) - ) - return batch_loop(*args) + # 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( + 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, name, search_read_only) + monkeypatch.setattr(cluster_coset, "_find_min_weights", search_read_only) monkeypatch.setattr(_threads, "run_work_items", run_counted) for matrix, css_weight in cases: num_qubits = len(matrix) @@ -940,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 - find_first = cluster_coset._find_first_not_within_max_weight + 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)] @@ -966,19 +958,19 @@ def gated_range(start: int, end: int) -> None: run_work_items(num_items, num_threads, gated_start, **kwargs) - def gated_find_first(block: npt.NDArray[np.uint64], *args: Any) -> tuple[int, bool]: + 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 find_first(block, *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, "_find_first_not_within_max_weight", gated_find_first) + 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) From 5f5aa952daa26699c6b27724fa64def9d19453ea Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:06:48 -0500 Subject: [PATCH 05/16] Keep only the connected-cluster coset tests that can catch a bug no other case catches - The test of pair sums checks single queries only: the batch queries read the same check tables, and the tests that compare them with exhaustive minima and with the states of single queries catch batch tables with pair sums. - The test that batches search with the restriction and cuts of single queries counts the states of the one batch loop once, and leaves their answers to the test of exhaustive minima. - The test of exhaustive minima checks get_min_weights with random floors only, which are zero at max_weight zero; a separate run with floors of zero caught no further mutation of the loop. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 92 ++++--------------- 1 file changed, 19 insertions(+), 73 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 6ec02597b..4fbc62e1e 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -12,7 +12,7 @@ import numpy.typing as npt import pytest -from qldpc._binary import get_kernel, get_num_words, int_to_words +from qldpc._binary import get_kernel, int_to_words from .._cosets import xor_selected from .._tuning import use_tuning @@ -60,10 +60,9 @@ def test_connected_cluster_queries_add_no_pair_sums(monkeypatch: pytest.MonkeyPa """The coset searches of ``CosetLeaderSearch`` search their sparser checks without pair sums. The checks of a repetition code have light sums of pairs, which distance searches would add, - but queries, single or in batches, search only the checks themselves (Sections 3.4 and 3.8 of + but queries search only the checks themselves (Sections 3.4 and 3.8 of ``connected_cluster.md``). """ - batch_tables = _record_batch_argument(monkeypatch, "tables") num_checks: list[int] = [] search_supports = search._search_supports signature = inspect.signature(search_supports) @@ -88,8 +87,6 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: # The syndrome of the first and last checks has no word of weight one, so the query searches. assert coset_search.get_min_weight_bound(0b101, 2).within_max_weight assert num_checks == [len(coset_search.checks)] - _run_batches(coset_search, [0b101], 2) - assert [len(tables[1][0]) - 1 for tables in batch_tables] == [len(coset_search.checks)] * 2 def test_connected_cluster_queries_only_read_their_search(monkeypatch: pytest.MonkeyPatch) -> None: @@ -122,7 +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 - _run_batches(coset_search, [0b101, 0b111, 0b100], 2) + 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 @@ -188,8 +187,7 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: coset_search.use_query_overlap_words(coset_search.checks) # Every syndrome that the table of light words lacks starts a query. - syndromes = range(1, 2 ** len(coset_search.checks)) - for syndrome in syndromes: + for syndrome in range(1, 2 ** len(coset_search.checks)): coset_search.get_min_weight_bound(syndrome, 3) assert num_cuts_per_query assert all(bool(num_cuts) == cuts for num_cuts in num_cuts_per_query) @@ -197,7 +195,7 @@ def record(*args: Any, **kwargs: Any) -> tuple[npt.NDArray[np.int64], ...]: @pytest.mark.parametrize("switch", ["restrict_viable_symbols", "cuts"]) def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None: - """Both batch queries visit the states of single queries, with a switch on and off. + """Batch queries visit the states of single queries, with a switch on and off. So they search with the restriction and the overlap cuts of the coset search. On this CSS state, the lightest errors with the syndrome 57 weigh two, and the number of states that its @@ -206,7 +204,6 @@ def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None 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], len(matrix)) counts = [] for setting in (True, False): options = {"restrict_viable_symbols": True, "cuts": True, switch: setting} @@ -219,11 +216,10 @@ def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None stabilizer_overlap_cuts=options["cuts"], ) coset_search.use_query_overlap_words(coset_search.checks) - assert coset_search.get_min_weights(batch, 2, np.zeros(1, dtype=np.int64)).tolist() == [2] - assert coset_search.find_first_not_within_max_weight(batch, 2) == (1, None) - num_states = _count_single_states(coset_search, syndrome, 2) - assert _count_batch_states(coset_search, syndrome, 2, first=True) == num_states - assert _count_batch_states(coset_search, syndrome, 2, first=False) == num_states + mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) + packed_syndrome = int_to_words(mapped, 1) + _, num_states = coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, 2) + assert _count_batch_states(coset_search, syndrome, 2) == num_states counts.append(num_states) assert counts[0] != counts[1] @@ -288,17 +284,12 @@ def test_connected_cluster_answers_match_exhaustive_minima( else: assert bound.lower_bound == 2 and weight <= max_weight - # Batch queries, with floors of zero and random floors. - capped = np.minimum(minima, max_weight + 1) - zeros = np.zeros(len(batch), dtype=np.int64) - assert np.array_equal( - coset_search.get_min_weights(batch, max_weight, zeros), capped - ) + # 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], capped[~within]) + assert np.array_equal(weights[~within], np.minimum(minima, max_weight + 1)[~within]) above = np.flatnonzero(minima > max_weight).tolist() index, first_bound = coset_search.find_first_not_within_max_weight( batch, max_weight @@ -340,40 +331,15 @@ def test_connected_cluster_batches_match_exhaustive_minima() -> None: # helpers -def _record_batch_argument(monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: - """Record an argument of each call of the compiled batch queries of ``coset``, and run them.""" - values: list[Any] = [] - for entry_name in ("_find_min_weights",): - entry = getattr(coset, entry_name) - - def record(*args: Any, entry: Any = entry) -> Any: - """Record the argument of a call, and run it.""" - values.append(inspect.signature(entry).bind(*args).arguments[name]) - return entry(*args) - - monkeypatch.setattr(coset, entry_name, record) - return values - - -def _run_batches( - coset_search: coset.ConnectedClusterCosetSearch, syndromes: list[int], max_weight: int -) -> None: - """Run both batch queries of a coset search on a batch of syndromes, from floors of zero.""" - batch = split_syndromes_into_words(syndromes, len(coset_search.checks)) - coset_search.find_first_not_within_max_weight(batch, max_weight) - coset_search.get_min_weights(batch, max_weight, np.zeros(len(batch), dtype=np.int64)) - - def _count_batch_states( - coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int, *, first: bool + coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int ) -> int: """The number of states that a batch query visits, as its compiled loop counts its work. - The loop is ``_find_first_not_within_max_weight`` if ``first``, and otherwise - ``_find_min_weights``. Each stops after a query once its work reaches ``max_work``, so of two - copies of a syndrome that is not looked up and has a vector within ``max_weight``, it searches - only the first exactly if the first visits at least ``max_work`` states. A search for the - largest such ``max_work`` finds that number. + The loop, ``_find_min_weights``, stops after a query once its work reaches ``max_work``, so of + two copies of a syndrome that is not looked up and has a vector within ``max_weight``, it + searches only the first exactly if the first visits at least ``max_work`` states. A search for + the largest such ``max_work`` finds that number. """ batch = split_syndromes_into_words([syndrome, syndrome], len(coset_search.checks)) floors = np.zeros(2, dtype=np.int64) @@ -383,7 +349,7 @@ def _count_batch_states( def searches_one(max_work: int) -> bool: """Whether the batch stops after the first copy within ``max_work``.""" num_done, _ = coset._find_min_weights( - batch, max_weight, floors, max_work, first, weights, tables + batch, max_weight, floors, max_work, False, weights, tables ) return bool(num_done == 1) @@ -394,23 +360,3 @@ def searches_one(max_work: int) -> bool: middle = (low + high) // 2 low, high = (middle, high) if searches_one(middle) else (low, middle) return low - - -def _count_single_states( - coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int -) -> int: - """The number of states that single queries visit at the limits 2, 3, ... up to a vector. - - The syndrome must have no vector of weight at most one. - """ - mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) - packed_syndrome = int_to_words(mapped, get_num_words(len(coset_search.checks))) - num_states = 0 - for limit in range(2, max_weight + 1): - symbols, states = coset_search._search.find_vector_with_packed_syndrome( - packed_syndrome, limit - ) - num_states += states - if symbols is not None: - break - return num_states From 19ce4ac0512301b4d5f57f2c452ecf8767d35ebd Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:38:30 -0500 Subject: [PATCH 06/16] Check that connected-cluster batch blocks take their own floors and count unsuccessful work - A batch of the checks I3, whose minimum weights are the bit counts of the syndromes, moves to two threads after its first query, so a block starts at its second row; that row must start its search from its own floor of zero, not from the floor 3 of the first row. - A batch of 32 copies of a syndrome of minimum weight 3 on a five-qubit graph state, whose searches at the limit 2 visit states without finding an error, must move to threads, so the work of unsuccessful searches counts toward split_work. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 22 +++++++++++++++++++ .../codes/distance/coset_leaders_test.py | 13 ++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 4fbc62e1e..e21120599 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -301,6 +301,28 @@ def test_connected_cluster_answers_match_exhaustive_minima( assert first_bound is None +def test_connected_cluster_batches_on_threads_start_from_the_floors_of_their_rows() -> None: + """A block of a batch on threads starts the search of each syndrome from its own floor. + + For the checks I3, a syndrome is the lightest word of its coset, so its bit count is the minimum + weight. The search of the first syndrome does the work at which the batch moves to two + threads, so a block starts at the second syndrome, whose floor of zero gives its weight 2, and + the floor 3 of the first syndrome would give 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], 3) + floors = np.array([3, 0], 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 + + 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. diff --git a/src/qldpc/codes/distance/coset_leaders_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index 3450eae71..6c4e9cde0 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -986,7 +986,8 @@ def test_connected_cluster_batches_run_on_the_threads_of_their_search( With chunks of one state, a batch whose queries visit states moves to threads, and with the default chunks, this small batch stays on the calling thread. So does a batch of syndromes of - errors of weight at most one, whose queries look up their errors and visit no states. + errors of weight at most one, whose queries look up their errors and visit no states. The + states that a search visits without finding an error count too. """ calls: list[int] = [] run_work_items = _threads.run_work_items @@ -1022,6 +1023,16 @@ def record(num_items: int, num_threads: int, *args: Any, **kwargs: Any) -> None: search.get_min_weights(batch, 1) assert not calls + # On this graph state, the class of the syndrome 14 has minimum weight 3, and its search at the + # limit 2 visits states without finding an error. + graph_state = get_graph_state(5, [(0, 1), (1, 3), (3, 4)], phase=True) + assert get_exhaustive_minima(graph_state, False)[14] == 3 + batch = split_syndromes_into_words([14] * 32, len(graph_state)) + with use_tuning(num_threads=3, search_chunk_exponent=0): + search = CosetLeaderSearch(graph_state, method="connected_cluster") + assert np.all(search.get_min_weights(batch, 2) == 3) + assert calls and set(calls) == {3} + def test_connected_cluster_batches_by_css_weight_count_the_work_of_z_parts( monkeypatch: pytest.MonkeyPatch, From d28a906dde27ff1466fc2d6af252a744ab07a56b Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 18:55:48 -0500 Subject: [PATCH 07/16] Check that connected-cluster batches answer every row of multi-row blocks The test of floors in blocks now also runs a batch of 34 syndromes of the checks I3 on two threads, long enough for blocks of several rows with differing floors, whose syndromes of weight 2 each do work, and whose first syndrome of weight 3 follows such a syndrome in its block. The expected weights are the bit counts of the syndromes, and the first index without a word within max_weight is that of the syndrome of weight 3. The docstring says that the rest of a batch moves to blocks, which up to two threads run, rather than that the batch runs on two threads. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index e21120599..aba994536 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -301,13 +301,16 @@ def test_connected_cluster_answers_match_exhaustive_minima( assert first_bound is None -def test_connected_cluster_batches_on_threads_start_from_the_floors_of_their_rows() -> None: - """A block of a batch on threads starts the search of each syndrome from its own floor. - - For the checks I3, a syndrome is the lightest word of its coset, so its bit count is the minimum - weight. The search of the first syndrome does the work at which the batch moves to two - threads, so a block starts at the second syndrome, whose floor of zero gives its weight 2, and - the floor 3 of the first syndrome would give 3. +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 a batch does the work at which the rest of the + batch moves to blocks, which up to two threads run. In the first batch, the second syndrome + starts a block, and its floor of zero gives its weight 2, where the floor 3 of the first + syndrome would give 3. The second batch is long enough for blocks of several rows, with + differing floors, whose syndromes of weight 2 each do work. Its first syndrome without a word + within ``max_weight`` follows such a syndrome in its block. """ coset_search = coset.ConnectedClusterCosetSearch( np.eye(3, dtype=np.uint8), @@ -322,6 +325,20 @@ def test_connected_cluster_batches_on_threads_start_from_the_floors_of_their_row weights = coset_search.get_min_weights(batch, 3, floors, num_threads=2, split_work=1) assert weights[0] <= 3 and weights[1] == 2 + syndromes = [(0b011, 0b101, 0b110)[row % 3] for row in range(34)] + syndromes[2] = 0b111 + batch = split_syndromes_into_words(syndromes, 3) + floors = np.arange(len(syndromes)) % 3 + weights = coset_search.get_min_weights(batch, 2, floors, num_threads=2, split_work=1) + minima = np.array([syndrome.bit_count() for syndrome in syndromes]) + within = minima <= floors + assert np.all(weights[within] <= floors[within]) + assert np.array_equal(weights[~within], np.minimum(minima, 3)[~within]) + index, bound = coset_search.find_first_not_within_max_weight( + batch, 2, num_threads=2, split_work=1 + ) + assert index == 2 and bound is not None and bound.lower_bound == 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. From 5577785d990bd1365fb7fb5703e7e79cf215fe76 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 19:09:35 -0500 Subject: [PATCH 08/16] Check that a batch block takes the floors of its own rows, not of the end of the batch The first batch of the test of floors in blocks now has a third syndrome with the floor 3, so that taking a block's floors from the end of the batch, like taking them from its start, gives the second syndrome a weight above its minimum. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../codes/distance/_connected_cluster/coset_test.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index aba994536..66de116e1 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -307,8 +307,8 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_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 a batch does the work at which the rest of the batch moves to blocks, which up to two threads run. In the first batch, the second syndrome - starts a block, and its floor of zero gives its weight 2, where the floor 3 of the first - syndrome would give 3. The second batch is long enough for blocks of several rows, with + starts a block, and its floor of zero gives its weight 2, where the floor 3 of the first or the + last syndrome would give 3. The second batch is long enough for blocks of several rows, with differing floors, whose syndromes of weight 2 each do work. Its first syndrome without a word within ``max_weight`` follows such a syndrome in its block. """ @@ -320,10 +320,10 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - restrict_viable_symbols=True, stabilizer_overlap_cuts=True, ) - batch = split_syndromes_into_words([0b111, 0b011], 3) - floors = np.array([3, 0], dtype=np.int64) + 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 + assert weights[0] <= 3 and weights[1] == 2 and weights[2] <= 3 syndromes = [(0b011, 0b101, 0b110)[row % 3] for row in range(34)] syndromes[2] = 0b111 From 5e4e1ca04ac506e2d2202241f31a1ad31844aa9c Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 19:35:13 -0500 Subject: [PATCH 09/16] Give the rows of multi-row batch blocks floors that change their answers The long batch of the test of floors in blocks now has the floors 0 to 3 at max_weight 3, so that a block that read the floors of its rows in another order would answer some syndrome of weight 2 from a floor of 3. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/qldpc/codes/distance/_connected_cluster/coset_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 66de116e1..599fb1b0c 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -328,12 +328,12 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - syndromes = [(0b011, 0b101, 0b110)[row % 3] for row in range(34)] syndromes[2] = 0b111 batch = split_syndromes_into_words(syndromes, 3) - floors = np.arange(len(syndromes)) % 3 - weights = coset_search.get_min_weights(batch, 2, floors, num_threads=2, split_work=1) + floors = np.arange(len(syndromes)) % 4 + weights = coset_search.get_min_weights(batch, 3, floors, num_threads=2, split_work=1) minima = np.array([syndrome.bit_count() for syndrome in syndromes]) within = minima <= floors assert np.all(weights[within] <= floors[within]) - assert np.array_equal(weights[~within], np.minimum(minima, 3)[~within]) + assert np.array_equal(weights[~within], minima[~within]) index, bound = coset_search.find_first_not_within_max_weight( batch, 2, num_threads=2, split_work=1 ) From 8a36bdbbb9384b88fa6d211f0c88c58fb6d5a5da Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 19:50:08 -0500 Subject: [PATCH 10/16] Give the long batch of the test of floors in blocks floors without a pattern Fixed pseudorandom floors from 0 to 3 make a block that took the floors of other rows, in any order or offset, answer some row wrongly, which a regular pattern of floors could hide. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../codes/distance/_connected_cluster/coset_test.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 599fb1b0c..e44f724cb 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -308,9 +308,10 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - weight. The search of the first syndrome of a batch does the work at which the rest of the batch moves to blocks, which up to two threads run. In the first batch, the second syndrome starts a block, and its floor of zero gives its weight 2, where the floor 3 of the first or the - last syndrome would give 3. The second batch is long enough for blocks of several rows, with - differing floors, whose syndromes of weight 2 each do work. Its first syndrome without a word - within ``max_weight`` follows such a syndrome in its block. + last syndrome would give 3. The second batch is long enough for blocks of several rows, whose + syndromes of weight 2 each do work. Its floors, from 0 to 3, follow no pattern, so that a block + that took the floors of other rows would answer some row wrongly. Its first syndrome without a + word within ``max_weight`` follows a syndrome of weight 2 in its block. """ coset_search = coset.ConnectedClusterCosetSearch( np.eye(3, dtype=np.uint8), @@ -328,7 +329,7 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - syndromes = [(0b011, 0b101, 0b110)[row % 3] for row in range(34)] syndromes[2] = 0b111 batch = split_syndromes_into_words(syndromes, 3) - floors = np.arange(len(syndromes)) % 4 + floors = np.random.default_rng(1).integers(0, 4, size=len(syndromes)) weights = coset_search.get_min_weights(batch, 3, floors, num_threads=2, split_work=1) minima = np.array([syndrome.bit_count() for syndrome in syndromes]) within = minima <= floors From 87562eca390aa1f96fb3bd5e9d85662a987a631c Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 00:01:05 -0500 Subject: [PATCH 11/16] Check connected-cluster batches of syndromes of two words against block minima A new test runs the batch queries of a coset search on more than 64 checks, copies of a block, by Pauli and by binary checks, against the sums of the minima of the blocks and against single queries, on one to three threads with random split work and floors. Its syndromes of the last copy reach the second word alone, so that a search that misread the words of a mapped syndrome would misweigh a coset. The test of batch states now also checks a class of minimum weight three, whose batch query counts the states of both limits that it tries, and the test of floors in blocks checks that a batch whose first query ends it ends there, even with no split work. The cut switch of the test of batch states, the long batch of the test of floors in blocks, and the graph-state batch of the test of threads go, since the other cases catch every bug that they catch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 138 +++++++++++++----- .../codes/distance/coset_leaders_test.py | 13 +- 2 files changed, 106 insertions(+), 45 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index e44f724cb..74248b01c 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -165,7 +165,8 @@ def test_connected_cluster_queries_cut_by_their_overlap_words_if_switched_on( ) -> None: """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 its batch queries. + ``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 @@ -193,35 +194,35 @@ 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) -@pytest.mark.parametrize("switch", ["restrict_viable_symbols", "cuts"]) -def test_connected_cluster_batches_search_as_single_queries(switch: str) -> None: - """Batch queries visit the states of single queries, with a switch on and off. +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. 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 each switch, which is otherwise on. + 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. Those with the syndrome 21 weigh + three, so its batch query visits the states of single queries at the limits two and three. """ matrix = get_random_css_state(6, 3, np.random.default_rng(0)) syndrome = 57 - assert get_exhaustive_minima(matrix, False)[syndrome] == 2 + minima = get_exhaustive_minima(matrix, False) + assert minima[syndrome] == 2 and minima[21] == 3 counts = [] - for setting in (True, False): - options = {"restrict_viable_symbols": True, "cuts": True, switch: setting} + for restrict_viable_symbols in (True, False): coset_search = coset.ConnectedClusterCosetSearch( matrix, symplectic=True, max_rounds=0, rounds_without_improvement=1, - restrict_viable_symbols=options["restrict_viable_symbols"], - stabilizer_overlap_cuts=options["cuts"], + 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, 1) - _, num_states = coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, 2) + num_states = _count_single_states(coset_search, syndrome, range(2, 3)) assert _count_batch_states(coset_search, syndrome, 2) == num_states counts.append(num_states) assert counts[0] != counts[1] + num_states = _count_single_states(coset_search, 21, range(2, 4)) + assert _count_batch_states(coset_search, 21, 3) == num_states @pytest.mark.parametrize("cuts", [True, False]) @@ -305,13 +306,11 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - """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 a batch does the work at which the rest of the - batch moves to blocks, which up to two threads run. In the first batch, the second syndrome - starts a block, and its floor of zero gives its weight 2, where the floor 3 of the first or the - last syndrome would give 3. The second batch is long enough for blocks of several rows, whose - syndromes of weight 2 each do work. Its floors, from 0 to 3, follow no pattern, so that a block - that took the floors of other rows would answer some row wrongly. Its first syndrome without a - word within ``max_weight`` follows a syndrome of weight 2 in its block. + 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 the last syndrome would give + 3. With no split work, the rest of a batch moves to blocks after its first query, unless that + query ends the batch, as that of the first syndrome does at ``max_weight`` two. """ coset_search = coset.ConnectedClusterCosetSearch( np.eye(3, dtype=np.uint8), @@ -326,19 +325,77 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - 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 - syndromes = [(0b011, 0b101, 0b110)[row % 3] for row in range(34)] - syndromes[2] = 0b111 - batch = split_syndromes_into_words(syndromes, 3) - floors = np.random.default_rng(1).integers(0, 4, size=len(syndromes)) - weights = coset_search.get_min_weights(batch, 3, floors, num_threads=2, split_work=1) - minima = np.array([syndrome.bit_count() for syndrome in syndromes]) - within = minima <= floors - assert np.all(weights[within] <= floors[within]) - assert np.array_equal(weights[~within], minima[~within]) index, bound = coset_search.find_first_not_within_max_weight( - batch, 2, num_threads=2, split_work=1 + batch, 2, num_threads=2, split_work=0 + ) + assert index == 0 and bound is not None and bound.lower_bound == 3 + + +@pytest.mark.parametrize("symplectic", [True, False]) +def test_connected_cluster_batches_of_two_words_match_block_minima( + pytestconfig: pytest.Config, symplectic: bool +) -> None: + """Batch queries of syndromes of two words agree with block minima and with single queries. + + The checks are copies of a block on their own variables, so the minimum weight of a coset is + the sum of the minima of the syndromes of its copies. The searches of Paulis check with 17 + copies of a random graph state with phases, whose last copy has its four checks in the second + 64-bit word. The searches of X or Z parts check with 22 copies of the checks of a repetition + code of length four, whose last copy has its first check in the first word and the other two in + the second. Without rounds of sparsifying, each sparser check acts only on the variables of + the copy at its position. The batch starts with each nonzero syndrome of the last copy alone, + those of weight one first, so that at ``max_weight`` one the first syndrome without a word + within it has weight two, and goes on with random syndromes of two copies. The batches run on + one to three threads in turn, with random split work and floors, and the first syndrome without + a word within ``max_weight`` gets the bound of a single query. + """ + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + if symplectic: + edges = [pair for pair in itertools.combinations(range(4), 2) if rng.integers(2)] + block = get_graph_state(4, edges, phase=True) + block_minima = get_exhaustive_minima(block, False) + else: + block = np.array([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1]], dtype=np.uint8) + block_minima = get_binary_minima(block) + halves = np.split(block, 2 if symplectic else 1, axis=1) + num_copies = 64 // len(block) + 1 + checks = np.hstack([np.kron(np.eye(num_copies, dtype=np.uint8), half) for half in halves]) + coset_search = coset.ConnectedClusterCosetSearch( + checks, + symplectic=symplectic, + max_rounds=0, + rounds_without_improvement=1, + restrict_viable_symbols=True, + stabilizer_overlap_cuts=True, ) - assert index == 2 and bound is not None and bound.lower_bound == 3 + copy_of_columns = np.tile(np.repeat(np.arange(num_copies), 4), len(halves)) + rows, columns = np.nonzero(coset_search.checks) + assert np.array_equal(rows // len(block), copy_of_columns[columns]) + + # Each query is a list of pairs of a copy and its syndrome. + num_syndromes = 1 << len(block) + by_weight = sorted(range(1, num_syndromes), key=lambda local: block_minima[local]) + queries = [[(num_copies - 1, local)] for local in by_weight] + for _ in range(10): + copies = rng.choice(num_copies, size=2, replace=False).tolist() + queries.append(list(zip(copies, rng.integers(1, num_syndromes, size=2).tolist()))) + syndromes = [sum(local << (len(block) * copy) for copy, local in query) for query in queries] + minima = np.array([sum(block_minima[local] for _, local in query) for query in queries]) + batch = split_syndromes_into_words(syndromes, len(checks)) + for max_weight in range(5): + options = {"num_threads": 1 + max_weight % 3, "split_work": int(rng.integers(3))} + floors = rng.integers(max_weight + 1, size=len(batch)) + weights = coset_search.get_min_weights(batch, max_weight, floors, **options) + within = minima <= floors + assert np.all(weights[within] <= floors[within]) + assert np.array_equal(weights[~within], np.minimum(minima, max_weight + 1)[~within]) + above = np.flatnonzero(minima > max_weight).tolist() + index, bound = coset_search.find_first_not_within_max_weight(batch, max_weight, **options) + assert index == (above[0] if above else len(batch)) + if above: + assert bound == coset_search.get_min_weight_bound(syndromes[index], max_weight) + else: + assert bound is None def test_connected_cluster_batches_match_exhaustive_minima() -> None: @@ -371,6 +428,21 @@ def test_connected_cluster_batches_match_exhaustive_minima() -> None: # helpers +def _count_single_states( + coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, limits: range +) -> int: + """The number of states that single searches of a syndrome visit at some weight limits. + + The syndrome must fit in one word, and its coset must have no word of weight at most one. + """ + mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) + packed_syndrome = int_to_words(mapped, 1) + return sum( + coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, limit)[1] + for limit in limits + ) + + def _count_batch_states( coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int ) -> int: diff --git a/src/qldpc/codes/distance/coset_leaders_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index 6c4e9cde0..3450eae71 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -986,8 +986,7 @@ def test_connected_cluster_batches_run_on_the_threads_of_their_search( With chunks of one state, a batch whose queries visit states moves to threads, and with the default chunks, this small batch stays on the calling thread. So does a batch of syndromes of - errors of weight at most one, whose queries look up their errors and visit no states. The - states that a search visits without finding an error count too. + errors of weight at most one, whose queries look up their errors and visit no states. """ calls: list[int] = [] run_work_items = _threads.run_work_items @@ -1023,16 +1022,6 @@ def record(num_items: int, num_threads: int, *args: Any, **kwargs: Any) -> None: search.get_min_weights(batch, 1) assert not calls - # On this graph state, the class of the syndrome 14 has minimum weight 3, and its search at the - # limit 2 visits states without finding an error. - graph_state = get_graph_state(5, [(0, 1), (1, 3), (3, 4)], phase=True) - assert get_exhaustive_minima(graph_state, False)[14] == 3 - batch = split_syndromes_into_words([14] * 32, len(graph_state)) - with use_tuning(num_threads=3, search_chunk_exponent=0): - search = CosetLeaderSearch(graph_state, method="connected_cluster") - assert np.all(search.get_min_weights(batch, 2) == 3) - assert calls and set(calls) == {3} - def test_connected_cluster_batches_by_css_weight_count_the_work_of_z_parts( monkeypatch: pytest.MonkeyPatch, From ed0454d0b6dbf5ed313d91aa557ad0bcf0b8e74a Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 01:12:58 -0500 Subject: [PATCH 12/16] Check the compiled batch loop with general word tables and within its work A new test calls the batch loop of connected-cluster coset searches directly on the checks I64, whose syndromes fill exactly one word, with its tables and again with an empty fixed_words, which selects the version of the search for any number of words. Its batch repeats a syndrome of one bit and has syndromes of two bits, so the loop must size, clear and compare the mapped syndrome by the words of the map, not by fixed_words. Three queries whose states fill the work budget after two must stop there and leave the third weight unwritten, so the loop must add up the work of its queries. The test of batches of syndromes of two words keeps only its Pauli checks, since its binary checks caught no bug that another case misses. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 84 +++++++++++++------ 1 file changed, 59 insertions(+), 25 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 74248b01c..7844d5169 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -15,7 +15,7 @@ from qldpc._binary import get_kernel, int_to_words from .._cosets import xor_selected -from .._tuning import use_tuning +from .._tuning import MAX_VALUE, use_tuning from ..conftest import ( get_binary_minima, get_binary_syndrome, @@ -225,6 +225,48 @@ def test_connected_cluster_batches_search_as_single_queries() -> None: assert _count_batch_states(coset_search, 21, 3) == num_states +def test_connected_cluster_batch_loop_answers_by_general_tables_within_its_work() -> None: + """The compiled batch loop weighs cosets by fixed or general word tables, within its work. + + For the checks I64, a syndrome is the lightest word of its coset, so its bit count is its + minimum weight, and a packed syndrome fills exactly one word. An empty ``fixed_words`` selects + the version of ``_search_supports`` for any number of words, which wider checks need, and the + loop must not take its number of words from it. The batch repeats a syndrome of one bit, so + that each query must clear the mapped syndrome of the last. The loop stops once its work + reaches ``max_work``: three queries of the syndrome 3 that visit ``n`` states each stop after + two at the work ``2 n``, and leave the weight of the third unwritten. + """ + coset_search = coset.ConnectedClusterCosetSearch( + np.eye(64, 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() + syndromes = [1, 1, 3, 1 << 63, (1 << 63) | 1, 0, 7] + batch = split_syndromes_into_words(syndromes, 64) + floors = np.zeros(len(batch), dtype=np.int64) + minima = np.array([syndrome.bit_count() for syndrome in syndromes]) + for batch_tables in (tables, tables[:4] + ((),) + tables[5:]): + for max_weight in (1, 2): + 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, np.minimum(minima, max_weight + 1)) + + num_states = _count_single_states(coset_search, 3, range(2, 3)) + assert num_states + batch = split_syndromes_into_words([3, 3, 3], 64) + weights = np.full(3, -1, dtype=np.int64) + assert coset._find_min_weights( + batch, 2, floors[:3], 2 * num_states, False, weights, tables + ) == (2, False) + assert weights.tolist() == [2, 2, -1] + + @pytest.mark.parametrize("cuts", [True, False]) @pytest.mark.parametrize("restrict_viable_symbols", [True, False]) def test_connected_cluster_answers_match_exhaustive_minima( @@ -331,44 +373,36 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - assert index == 0 and bound is not None and bound.lower_bound == 3 -@pytest.mark.parametrize("symplectic", [True, False]) def test_connected_cluster_batches_of_two_words_match_block_minima( - pytestconfig: pytest.Config, symplectic: bool + pytestconfig: pytest.Config, ) -> None: """Batch queries of syndromes of two words agree with block minima and with single queries. - The checks are copies of a block on their own variables, so the minimum weight of a coset is - the sum of the minima of the syndromes of its copies. The searches of Paulis check with 17 - copies of a random graph state with phases, whose last copy has its four checks in the second - 64-bit word. The searches of X or Z parts check with 22 copies of the checks of a repetition - code of length four, whose last copy has its first check in the first word and the other two in - the second. Without rounds of sparsifying, each sparser check acts only on the variables of - the copy at its position. The batch starts with each nonzero syndrome of the last copy alone, - those of weight one first, so that at ``max_weight`` one the first syndrome without a word - within it has weight two, and goes on with random syndromes of two copies. The batches run on - one to three threads in turn, with random split work and floors, and the first syndrome without - a word within ``max_weight`` gets the bound of a single query. + The checks are 17 copies of a random graph state with phases on their own qubits, so the + minimum weight of a coset is the sum of the minima of the syndromes of its copies, and the last + copy has its four checks in the second 64-bit word. Without rounds of sparsifying, each sparser + check acts only on the qubits of the copy at its position. The batch starts with each nonzero + syndrome of the last copy alone, those of weight one first, so that at ``max_weight`` one the + first syndrome without a word within it has weight two, and goes on with random syndromes of two + copies. The batches run on one to three threads in turn, with random split work and floors, and + the first syndrome without a word within ``max_weight`` gets the bound of a single query. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - if symplectic: - edges = [pair for pair in itertools.combinations(range(4), 2) if rng.integers(2)] - block = get_graph_state(4, edges, phase=True) - block_minima = get_exhaustive_minima(block, False) - else: - block = np.array([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1]], dtype=np.uint8) - block_minima = get_binary_minima(block) - halves = np.split(block, 2 if symplectic else 1, axis=1) + edges = [pair for pair in itertools.combinations(range(4), 2) if rng.integers(2)] + block = get_graph_state(4, edges, phase=True) + block_minima = get_exhaustive_minima(block, False) num_copies = 64 // len(block) + 1 - checks = np.hstack([np.kron(np.eye(num_copies, dtype=np.uint8), half) for half in halves]) + eye = np.eye(num_copies, dtype=np.uint8) + checks = np.hstack([np.kron(eye, half) for half in np.split(block, 2, axis=1)]) coset_search = coset.ConnectedClusterCosetSearch( checks, - symplectic=symplectic, + symplectic=True, max_rounds=0, rounds_without_improvement=1, restrict_viable_symbols=True, stabilizer_overlap_cuts=True, ) - copy_of_columns = np.tile(np.repeat(np.arange(num_copies), 4), len(halves)) + copy_of_columns = np.tile(np.repeat(np.arange(num_copies), 4), 2) rows, columns = np.nonzero(coset_search.checks) assert np.array_equal(rows // len(block), copy_of_columns[columns]) From 5c663f13b1700f6b1a4dcbbc187cf51017bd5d30 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 02:29:06 -0500 Subject: [PATCH 13/16] Check the batch loop's budget from positive floors and its words on rectangular checks The test of the compiled batch loop now checks its budget from the floors 0, 2, and 2, where every query searches from limit two and must count its states, and with no work allowed after a first query that looks up its word and visits no states. It weighs its batch at max_weight 2 only, since max_weight 1 caught no bug that another case misses. A new test runs batch queries on the checks [I2 | 0], whose syndromes fill one 64-bit word while their 65 variables fill two, so that batches must size the syndromes of their searches by the checks. The test of batches of syndromes of two words compares the bound of its first rejected syndrome in one assertion, which every seed reaches, now that its Pauli checks alone can leave classes above the largest max_weight that it tries. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 72 +++++++++++++------ 1 file changed, 52 insertions(+), 20 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 7844d5169..d3aaba617 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -232,9 +232,13 @@ def test_connected_cluster_batch_loop_answers_by_general_tables_within_its_work( minimum weight, and a packed syndrome fills exactly one word. An empty ``fixed_words`` selects the version of ``_search_supports`` for any number of words, which wider checks need, and the loop must not take its number of words from it. The batch repeats a syndrome of one bit, so - that each query must clear the mapped syndrome of the last. The loop stops once its work - reaches ``max_work``: three queries of the syndrome 3 that visit ``n`` states each stop after - two at the work ``2 n``, and leave the weight of the third unwritten. + that each query must clear the mapped syndrome of the last. + + The loop stops once its work reaches ``max_work``. Three queries of the syndrome 3, from the + floors 0, 2, and 2, each visit the ``n`` states of a single search at limit two, so they stop + after two at the work ``2 n``. With no work allowed, the loop stops after its first query, + though that query looks up its word and visits no states. Either way, the weights of the + queries after the stop stay unwritten. """ coset_search = coset.ConnectedClusterCosetSearch( np.eye(64, dtype=np.uint8), @@ -247,24 +251,54 @@ def test_connected_cluster_batch_loop_answers_by_general_tables_within_its_work( tables = coset_search._get_batch_tables() syndromes = [1, 1, 3, 1 << 63, (1 << 63) | 1, 0, 7] batch = split_syndromes_into_words(syndromes, 64) - floors = np.zeros(len(batch), dtype=np.int64) minima = np.array([syndrome.bit_count() for syndrome in syndromes]) for batch_tables in (tables, tables[:4] + ((),) + tables[5:]): - for max_weight in (1, 2): - 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, np.minimum(minima, max_weight + 1)) + weights = np.full(len(batch), -1, dtype=np.int64) + zeros = np.zeros(len(batch), dtype=np.int64) + assert coset._find_min_weights( + batch, 2, zeros, MAX_VALUE, False, weights, batch_tables + ) == (len(batch), False) + assert np.array_equal(weights, np.minimum(minima, 3)) num_states = _count_single_states(coset_search, 3, range(2, 3)) assert num_states - batch = split_syndromes_into_words([3, 3, 3], 64) - weights = np.full(3, -1, dtype=np.int64) - assert coset._find_min_weights( - batch, 2, floors[:3], 2 * num_states, False, weights, tables - ) == (2, False) - assert weights.tolist() == [2, 2, -1] + for syndromes, floors, max_work, expected in [ + ([3, 3, 3], [0, 2, 2], 2 * num_states, [2, 2, -1]), + ([0, 1, 3], [0, 0, 0], 0, [0, -1, -1]), + ]: + weights = np.full(3, -1, dtype=np.int64) + num_searched = len(expected) - expected.count(-1) + assert coset._find_min_weights( + split_syndromes_into_words(syndromes, 64), + 2, + np.array(floors, dtype=np.int64), + max_work, + False, + weights, + tables, + ) == (num_searched, False) + assert weights.tolist() == expected + + +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] + index, bound = coset_search.find_first_not_within_max_weight(batch, 1) + assert index == 1 and bound is not None and not bound.within_max_weight @pytest.mark.parametrize("cuts", [True, False]) @@ -426,10 +460,8 @@ def test_connected_cluster_batches_of_two_words_match_block_minima( above = np.flatnonzero(minima > max_weight).tolist() index, bound = coset_search.find_first_not_within_max_weight(batch, max_weight, **options) assert index == (above[0] if above else len(batch)) - if above: - assert bound == coset_search.get_min_weight_bound(syndromes[index], max_weight) - else: - assert bound is None + single = coset_search.get_min_weight_bound(syndromes[index], max_weight) if above else None + assert bound == single def test_connected_cluster_batches_match_exhaustive_minima() -> None: From e715eb3a100a0caa6bd7b62ae193a86d71d11273 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 04:18:44 -0500 Subject: [PATCH 14/16] Check the compiled batch loop against bit counts on random identity checks A seeded test runs the batch loop of connected-cluster coset searches on identity checks of 3, 4, 63, 64, 65, and 129 rows, whose syndromes have their bit counts as minimum weights. Its batches have syndromes of random bits in each word alone, across the first and last words, and anywhere, and start with one that the loop looks up. At each max_weight up to five, with random floors, the loop must give the weights that _get_min_weight states, with the tables of the search and with an empty fixed_words; the first syndrome without a word within max_weight must get the bound of a single query; and a budget of the states that the single searches of any number of leading rows visit must stop the loop at the row that reaches it and leave the later weights unwritten. The fixed test of the batch loop on I64 and the test of batches of syndromes of two words on graph states go, since the new test and the others catch every bug that they catch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 198 ++++++++---------- 1 file changed, 87 insertions(+), 111 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index d3aaba617..508bf745a 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -12,7 +12,7 @@ import numpy.typing as npt import pytest -from qldpc._binary import get_kernel, int_to_words +from qldpc._binary import get_kernel, get_num_words, int_to_words from .._cosets import xor_selected from .._tuning import MAX_VALUE, use_tuning @@ -225,59 +225,92 @@ def test_connected_cluster_batches_search_as_single_queries() -> None: assert _count_batch_states(coset_search, 21, 3) == num_states -def test_connected_cluster_batch_loop_answers_by_general_tables_within_its_work() -> None: - """The compiled batch loop weighs cosets by fixed or general word tables, within its work. +def test_connected_cluster_batch_loop_matches_bit_counts_on_identity_checks( + pytestconfig: pytest.Config, +) -> None: + """The compiled batch loop agrees with the bit counts of syndromes of identity checks. + + For identity checks, a syndrome is the lightest word of its coset, so its bit count is its + minimum weight. The numbers of checks straddle the boundaries of 64-bit words. Each batch + starts with a syndrome of at most one bit, which the loop looks up without a search, and goes + on, in random order, with a syndrome of random bits of each word alone, one with a bit of the + first word and bits of the last, and syndromes of random bits. Bit counts up to five let some + searches start from floors above two and below their minima. At each ``max_weight`` up to five, + with random floors, the loop runs with the tables of the search and with an empty + ``fixed_words``, which selects the version of ``_search_supports`` for any number of words, and + gives the weights that ``_get_min_weight`` states. The first syndrome without a word within + ``max_weight`` gets the bound of a single query. At ``max_weight`` five, for each number of + leading rows, a budget of the states that their single searches visit stops the loop at the + first row at which its work reaches the budget, even the first row with no budget, and leaves + the later weights unwritten. + """ + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - For the checks I64, a syndrome is the lightest word of its coset, so its bit count is its - minimum weight, and a packed syndrome fills exactly one word. An empty ``fixed_words`` selects - the version of ``_search_supports`` for any number of words, which wider checks need, and the - loop must not take its number of words from it. The batch repeats a syndrome of one bit, so - that each query must clear the mapped syndrome of the last. + 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()) - The loop stops once its work reaches ``max_work``. Three queries of the syndrome 3, from the - floors 0, 2, and 2, each visit the ``n`` states of a single search at limit two, so they stop - after two at the work ``2 n``. With no work allowed, the loop stops after its first query, - though that query looks up its word and visits no states. Either way, the weights of the - queries after the stop stay unwritten. - """ - coset_search = coset.ConnectedClusterCosetSearch( - np.eye(64, 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() - syndromes = [1, 1, 3, 1 << 63, (1 << 63) | 1, 0, 7] - batch = split_syndromes_into_words(syndromes, 64) - minima = np.array([syndrome.bit_count() for syndrome in syndromes]) - for batch_tables in (tables, tables[:4] + ((),) + tables[5:]): - weights = np.full(len(batch), -1, dtype=np.int64) - zeros = np.zeros(len(batch), dtype=np.int64) - assert coset._find_min_weights( - batch, 2, zeros, MAX_VALUE, False, weights, batch_tables - ) == (len(batch), False) - assert np.array_equal(weights, np.minimum(minima, 3)) - - num_states = _count_single_states(coset_search, 3, range(2, 3)) - assert num_states - for syndromes, floors, max_work, expected in [ - ([3, 3, 3], [0, 2, 2], 2 * num_states, [2, 2, -1]), - ([0, 1, 3], [0, 0, 0], 0, [0, -1, -1]), - ]: - weights = np.full(3, -1, dtype=np.int64) - num_searched = len(expected) - expected.count(-1) - assert coset._find_min_weights( - split_syndromes_into_words(syndromes, 64), - 2, - np.array(floors, dtype=np.int64), - max_work, - False, - weights, - tables, - ) == (num_searched, False) - assert weights.tolist() == expected + for num_checks in (3, 4, 63, 64, 65, 129): + num_words = get_num_words(num_checks) + 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() + words = [range(64 * word, min(64 * word + 64, num_checks)) for word in range(num_words)] + bit_sets = [get_bits(checks, int(rng.integers(1, 6))) for 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) + syndromes.insert( + 0, sum(1 << bit for bit in get_bits(range(num_checks), int(rng.integers(2)))) + ) + 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 = np.where( + minima < 2, + minima, + np.where(minima < floors, floors, np.minimum(minima, max_weight + 1)), + ) + 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)) + single = ( + coset_search.get_min_weight_bound(syndromes[index], max_weight) if above else None + ) + assert bound == single + + # The single searches of a row try the limits from the larger of two and its floor, up to + # its minimum or max_weight, unless the row looks up a word of weight at most one. + num_states = [0] + for syndrome, minimum, floor in zip(syndromes, minima.tolist(), floors.tolist()): + first = max(2, floor) + limits = range(first, min(max(minimum, first), max_weight) + 1 if minimum > 1 else 0) + num_states.append(num_states[-1] + _count_single_states(coset_search, syndrome, limits)) + for max_work in num_states: + num_searched = next( + (rows for rows in range(1, len(batch)) if num_states[rows] >= max_work), len(batch) + ) + weights = np.full(len(batch), -1, dtype=np.int64) + assert coset._find_min_weights( + batch, max_weight, floors, max_work, False, weights, tables + ) == (num_searched, False) + assert np.array_equal(weights[:num_searched], expected[:num_searched]) + assert np.all(weights[num_searched:] == -1) def test_connected_cluster_batches_count_words_of_checks_not_of_variables() -> None: @@ -407,63 +440,6 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - assert index == 0 and bound is not None and bound.lower_bound == 3 -def test_connected_cluster_batches_of_two_words_match_block_minima( - pytestconfig: pytest.Config, -) -> None: - """Batch queries of syndromes of two words agree with block minima and with single queries. - - The checks are 17 copies of a random graph state with phases on their own qubits, so the - minimum weight of a coset is the sum of the minima of the syndromes of its copies, and the last - copy has its four checks in the second 64-bit word. Without rounds of sparsifying, each sparser - check acts only on the qubits of the copy at its position. The batch starts with each nonzero - syndrome of the last copy alone, those of weight one first, so that at ``max_weight`` one the - first syndrome without a word within it has weight two, and goes on with random syndromes of two - copies. The batches run on one to three threads in turn, with random split work and floors, and - the first syndrome without a word within ``max_weight`` gets the bound of a single query. - """ - rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - edges = [pair for pair in itertools.combinations(range(4), 2) if rng.integers(2)] - block = get_graph_state(4, edges, phase=True) - block_minima = get_exhaustive_minima(block, False) - num_copies = 64 // len(block) + 1 - eye = np.eye(num_copies, dtype=np.uint8) - checks = np.hstack([np.kron(eye, half) for half in np.split(block, 2, axis=1)]) - coset_search = coset.ConnectedClusterCosetSearch( - checks, - symplectic=True, - max_rounds=0, - rounds_without_improvement=1, - restrict_viable_symbols=True, - stabilizer_overlap_cuts=True, - ) - copy_of_columns = np.tile(np.repeat(np.arange(num_copies), 4), 2) - rows, columns = np.nonzero(coset_search.checks) - assert np.array_equal(rows // len(block), copy_of_columns[columns]) - - # Each query is a list of pairs of a copy and its syndrome. - num_syndromes = 1 << len(block) - by_weight = sorted(range(1, num_syndromes), key=lambda local: block_minima[local]) - queries = [[(num_copies - 1, local)] for local in by_weight] - for _ in range(10): - copies = rng.choice(num_copies, size=2, replace=False).tolist() - queries.append(list(zip(copies, rng.integers(1, num_syndromes, size=2).tolist()))) - syndromes = [sum(local << (len(block) * copy) for copy, local in query) for query in queries] - minima = np.array([sum(block_minima[local] for _, local in query) for query in queries]) - batch = split_syndromes_into_words(syndromes, len(checks)) - for max_weight in range(5): - options = {"num_threads": 1 + max_weight % 3, "split_work": int(rng.integers(3))} - floors = rng.integers(max_weight + 1, size=len(batch)) - weights = coset_search.get_min_weights(batch, max_weight, floors, **options) - within = minima <= floors - assert np.all(weights[within] <= floors[within]) - assert np.array_equal(weights[~within], np.minimum(minima, max_weight + 1)[~within]) - above = np.flatnonzero(minima > max_weight).tolist() - index, bound = coset_search.find_first_not_within_max_weight(batch, max_weight, **options) - assert index == (above[0] if above else len(batch)) - single = coset_search.get_min_weight_bound(syndromes[index], max_weight) if above else None - assert bound == single - - 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. @@ -499,10 +475,10 @@ def _count_single_states( ) -> int: """The number of states that single searches of a syndrome visit at some weight limits. - The syndrome must fit in one word, and its coset must have no word of weight at most one. + The coset of the syndrome must have no word of weight at most one. """ mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) - packed_syndrome = int_to_words(mapped, 1) + packed_syndrome = int_to_words(mapped, get_num_words(len(coset_search.checks))) return sum( coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, limit)[1] for limit in limits From 8dad5d5fb8e098ff6c2ececdc2d1918ac2dfcb13 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 05:30:34 -0500 Subject: [PATCH 15/16] Check batch loops on rectangular checks, nine-word tables, and rejected rows The randomized test of the compiled batch loop now also runs on three checks of six variables with exhaustive minima, where floors above the number of checks must search up to the number of variables, and checks its budgets with floors at max_weight too. A loop that stops at the first syndrome without a word within max_weight must write that syndrome's weight and no later one. A new test answers a batch with tables of identity checks of eight and nine 64-bit words, the largest that the fixed versions of the search take and the smallest that they do not. Its searches are assembled directly, since building them takes seconds as plain Python. Two older gaps close too. A single query on checks [I2 | 0] must size its syndrome by the checks, not by the 65 variables. Batches of minimum weights by CSS weight on |0>^65 and |+>^65 must read both words of the syndromes of their X and Z parts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 178 +++++++++++++----- .../codes/distance/coset_leaders_test.py | 19 ++ 2 files changed, 153 insertions(+), 44 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 508bf745a..9610fcac8 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -30,6 +30,13 @@ from ..coset_leaders import CosetLeaderSearch from . import coset, search, sparse_checks +# Three checks on six variables, more than the checks. The coset of the syndrome 4 has words of +# weight 2, but from a floor of 4 the search visits states at the limit 4 that it does not visit at +# the limit 3. +_RECTANGULAR_CHECKS = np.array( + [[1, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0]], dtype=np.uint8 +) + def test_connected_cluster_coset_searches_make_checks_sparser_with_their_rounds( monkeypatch: pytest.MonkeyPatch, @@ -225,24 +232,28 @@ def test_connected_cluster_batches_search_as_single_queries() -> None: assert _count_batch_states(coset_search, 21, 3) == num_states -def test_connected_cluster_batch_loop_matches_bit_counts_on_identity_checks( +def test_connected_cluster_batch_loop_matches_the_minima_of_random_cosets( pytestconfig: pytest.Config, ) -> None: - """The compiled batch loop agrees with the bit counts of syndromes of identity checks. + """The compiled batch loop agrees with the minima of the cosets of random syndromes. For identity checks, a syndrome is the lightest word of its coset, so its bit count is its minimum weight. The numbers of checks straddle the boundaries of 64-bit words. Each batch starts with a syndrome of at most one bit, which the loop looks up without a search, and goes on, in random order, with a syndrome of random bits of each word alone, one with a bit of the first word and bits of the last, and syndromes of random bits. Bit counts up to five let some - searches start from floors above two and below their minima. At each ``max_weight`` up to five, - with random floors, the loop runs with the tables of the search and with an empty - ``fixed_words``, which selects the version of ``_search_supports`` for any number of words, and - gives the weights that ``_get_min_weight`` states. The first syndrome without a word within - ``max_weight`` gets the bound of a single query. At ``max_weight`` five, for each number of - leading rows, a budget of the states that their single searches visit stops the loop at the - first row at which its work reaches the budget, even the first row with no budget, and leaves - the later weights unwritten. + searches start from floors above two and below their minima. The three checks on six + variables of ``_RECTANGULAR_CHECKS`` get every syndrome, in random order, and exhaustive minima. + + At each ``max_weight`` up to five, with random floors, the loop runs with the tables of the + search and with an empty ``fixed_words``, which selects the version of ``_search_supports`` for + any number of words, and gives the weights that ``_get_min_weight`` states. The first syndrome + without a word within ``max_weight`` gets the bound of a single query, and a loop that stops + there writes its weight and no later one. At ``max_weight`` five, with the random floors and + with floors of five, above the number of rectangular checks, for each number of leading rows, + a budget of the states that their single searches visit stops the loop at the first row at + which its work reaches the budget, even the first row with no budget, and leaves the later + weights unwritten. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) @@ -250,10 +261,11 @@ 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 (3, 4, 63, 64, 65, 129): - num_words = get_num_words(num_checks) + identities = [np.eye(num_checks, dtype=np.uint8) for num_checks in (3, 4, 63, 64, 65, 129)] + for checks in [*identities, _RECTANGULAR_CHECKS]: + num_checks = len(checks) coset_search = coset.ConnectedClusterCosetSearch( - np.eye(num_checks, dtype=np.uint8), + checks, symplectic=False, max_rounds=0, rounds_without_improvement=1, @@ -261,25 +273,25 @@ def get_bits(checks: range, num_bits: int) -> set[int]: stabilizer_overlap_cuts=True, ) tables = coset_search._get_batch_tables() - words = [range(64 * word, min(64 * word + 64, num_checks)) for word in range(num_words)] - bit_sets = [get_bits(checks, int(rng.integers(1, 6))) for 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) - syndromes.insert( - 0, sum(1 << bit for bit in get_bits(range(num_checks), int(rng.integers(2)))) - ) - minima = np.array([syndrome.bit_count() for syndrome in syndromes]) + if checks is _RECTANGULAR_CHECKS: + syndromes = rng.permutation(1 << num_checks).tolist() + minima = get_binary_minima(checks)[syndromes] + else: + 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 = np.where( - minima < 2, - minima, - np.where(minima < floors, floors, np.minimum(minima, max_weight + 1)), - ) + 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( @@ -293,31 +305,93 @@ def get_bits(checks: range, num_bits: int) -> set[int]: coset_search.get_min_weight_bound(syndromes[index], max_weight) if above else None ) assert bound == single + 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]) + assert np.all(weights[num_written:] == -1) # The single searches of a row try the limits from the larger of two and its floor, up to # its minimum or max_weight, unless the row looks up a word of weight at most one. - num_states = [0] - for syndrome, minimum, floor in zip(syndromes, minima.tolist(), floors.tolist()): - first = max(2, floor) - limits = range(first, min(max(minimum, first), max_weight) + 1 if minimum > 1 else 0) - num_states.append(num_states[-1] + _count_single_states(coset_search, syndrome, limits)) - for max_work in num_states: - num_searched = next( - (rows for rows in range(1, len(batch)) if num_states[rows] >= max_work), len(batch) - ) - weights = np.full(len(batch), -1, dtype=np.int64) - assert coset._find_min_weights( - batch, max_weight, floors, max_work, False, weights, tables - ) == (num_searched, False) - assert np.array_equal(weights[:num_searched], expected[:num_searched]) - assert np.all(weights[num_searched:] == -1) + for budget_floors in (floors, np.full(len(batch), max_weight)): + expected = _get_batch_weights(minima, budget_floors, max_weight) + num_states = [0] + for syndrome, minimum, floor in zip(syndromes, minima.tolist(), budget_floors.tolist()): + first = max(2, floor) + limits = range( + first, min(max(minimum, first), max_weight) + 1 if minimum > 1 else 0 + ) + num_states.append( + num_states[-1] + _count_single_states(coset_search, syndrome, limits) + ) + for max_work in num_states: + num_searched = next( + (rows for rows in range(1, len(batch)) if num_states[rows] >= max_work), + len(batch), + ) + weights = np.full(len(batch), -1, dtype=np.int64) + assert coset._find_min_weights( + batch, max_weight, budget_floors, max_work, False, weights, tables + ) == (num_searched, False) + assert np.array_equal(weights[:num_searched], expected[:num_searched]) + assert np.all(weights[num_searched:] == -1) + + +def test_connected_cluster_batches_of_nine_words_take_the_search_for_any_number_of_words() -> None: + """Batch queries on checks of more than eight 64-bit words answer as on eight. + + ``_search_supports`` has fixed versions only for syndromes of up to eight words, so the tables + of checks of nine words select its version for any number of words. The identity checks I512 + and I513 fill eight and nine words. Their searches are assembled directly, as + ``SupportSearch`` builds them for identity checks, since building them takes seconds as plain + Python. A syndrome of the first and last checks has a lightest word of weight 2. + """ + for num_checks in (512, 513): + num_words = get_num_words(num_checks) + columns = np.zeros((num_checks, num_words), dtype=np.uint64) + columns[np.arange(num_checks), np.arange(num_checks) // 64] = np.left_shift( + np.uint64(1), (np.arange(num_checks) % 64).astype(np.uint64) + ) + ranks = np.arange(num_checks, dtype=np.int64) + support_search = search.SupportSearch.__new__(search.SupportSearch) + support_search._check_tables = search._CheckTables( + np.arange(num_checks + 1, dtype=np.int64), + np.arange(num_checks, dtype=np.int64), + columns, + np.zeros((num_checks, 0), dtype=np.uint64), + ) + support_search._ranks = ranks + support_search._inverse_overlaps = np.array([0, 1], dtype=np.int64) + support_search._restrict_viable_symbols = True + support_search._query_cuts = search._get_overlap_cuts( + np.zeros((0, num_checks), dtype=np.uint8), ranks, False + ) + coset_search = coset.ConnectedClusterCosetSearch.__new__(coset.ConnectedClusterCosetSearch) + coset_search._packed_map_columns = columns + coset_search._search = support_search + + batch = split_syndromes_into_words([1 | (1 << (num_checks - 1))], num_checks) + weights = np.full(1, -1, dtype=np.int64) + assert coset._find_min_weights( + batch, + 2, + np.zeros(1, dtype=np.int64), + MAX_VALUE, + False, + weights, + coset_search._get_batch_tables(), + ) == (1, False) + assert weights.tolist() == [2] 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. + """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. + Batch queries and a single query that searches all size them so. """ checks = np.hstack([np.eye(2, dtype=np.uint8), np.zeros((2, 63), dtype=np.uint8)]) coset_search = coset.ConnectedClusterCosetSearch( @@ -332,6 +406,9 @@ def test_connected_cluster_batches_count_words_of_checks_not_of_variables() -> N assert coset_search.get_min_weights(batch, 2, np.zeros(2, dtype=np.int64)).tolist() == [1, 2] index, bound = coset_search.find_first_not_within_max_weight(batch, 1) assert index == 1 and bound is not None and not bound.within_max_weight + bound = coset_search.get_min_weight_bound(3, 2) + word = bound.representative + assert bound.within_max_weight and word.bit_count() <= 2 and word & 3 == 3 @pytest.mark.parametrize("cuts", [True, False]) @@ -470,6 +547,19 @@ def test_connected_cluster_batches_match_exhaustive_minima() -> None: # 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)) + ) + + def _count_single_states( coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, limits: range ) -> int: diff --git a/src/qldpc/codes/distance/coset_leaders_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index 3450eae71..1a895c171 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -184,6 +184,25 @@ def test_x_and_z_syndromes_span_several_words(pytestconfig: pytest.Config) -> No assert found == np.flatnonzero(np.array(minima) > max_weight).tolist() +def test_min_weights_by_css_weight_read_parts_of_several_words() -> None: + """By CSS weight, batches of minimum weights read syndromes of X and Z parts of two words. + + On |0>^65, the pure-Z stabilizers check the X parts, and on |+>^65 the pure-X stabilizers + check the Z parts. Either way, the bit count of a syndrome is its minimum weight, and the + syndromes of the searched part fill two 64-bit words. Both methods map the syndromes of a + batch to those of its parts in the same code. + """ + num_qubits = 65 + identity = np.eye(num_qubits, dtype=np.uint8) + zeros = np.zeros_like(identity) + syndromes = [1 << 64, 1 | (1 << 64), 0, 1] + batch = split_syndromes_into_words(syndromes, num_qubits) + for matrix in (np.hstack([zeros, identity]), np.hstack([identity, zeros])): + search = CosetLeaderSearch(matrix, css_weight=True) + weights = search.get_min_weights(batch, 2) + assert weights.tolist() == [syndrome.bit_count() for syndrome in syndromes] + + def test_css_weight_counts_the_larger_sector() -> None: """X0 Z1 on |0+> has CSS weight one but physical weight two.""" matrix = np.array([[0, 0, 1, 0], [0, 1, 0, 0]], dtype=np.uint8) From 62a34a93edc901ae65a523960f24a9c3f08997b6 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 11:05:20 -0500 Subject: [PATCH 16/16] Trim tests to the behavior this change introduces Drop the test of nine-word batch tables, the budget sweep with its rectangular checks, the identity checks other than I64 and I65, and the checks that repeat other cases, and count the states of a batch query with two calls of the loop. Drop the tests of single-query sizing and of CSS-weight batches over several words, whose behavior this change leaves as it was. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/coset_test.py | 243 ++++-------------- .../codes/distance/coset_leaders_test.py | 19 -- 2 files changed, 43 insertions(+), 219 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/coset_test.py b/src/qldpc/codes/distance/_connected_cluster/coset_test.py index 9610fcac8..3722cc287 100644 --- a/src/qldpc/codes/distance/_connected_cluster/coset_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/coset_test.py @@ -30,13 +30,6 @@ from ..coset_leaders import CosetLeaderSearch from . import coset, search, sparse_checks -# Three checks on six variables, more than the checks. The coset of the syndrome 4 has words of -# weight 2, but from a floor of 4 the search visits states at the limit 4 that it does not visit at -# the limit 3. -_RECTANGULAR_CHECKS = np.array( - [[1, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0]], dtype=np.uint8 -) - def test_connected_cluster_coset_searches_make_checks_sparser_with_their_rounds( monkeypatch: pytest.MonkeyPatch, @@ -206,13 +199,15 @@ def test_connected_cluster_batches_search_as_single_queries() -> None: 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. Those with the syndrome 21 weigh - three, so its batch query visits the states of single queries at the limits two and three. + 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 - minima = get_exhaustive_minima(matrix, False) - assert minima[syndrome] == 2 and minima[21] == 3 + 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( @@ -224,12 +219,15 @@ def test_connected_cluster_batches_search_as_single_queries() -> None: stabilizer_overlap_cuts=True, ) coset_search.use_query_overlap_words(coset_search.checks) - num_states = _count_single_states(coset_search, syndrome, range(2, 3)) - assert _count_batch_states(coset_search, syndrome, 2) == num_states + 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] - num_states = _count_single_states(coset_search, 21, range(2, 4)) - assert _count_batch_states(coset_search, 21, 3) == num_states def test_connected_cluster_batch_loop_matches_the_minima_of_random_cosets( @@ -237,23 +235,18 @@ def test_connected_cluster_batch_loop_matches_the_minima_of_random_cosets( ) -> None: """The compiled batch loop agrees with the minima of the cosets of random syndromes. - For identity checks, a syndrome is the lightest word of its coset, so its bit count is its - minimum weight. The numbers of checks straddle the boundaries of 64-bit words. Each batch - starts with a syndrome of at most one bit, which the loop looks up without a search, and goes - on, in random order, with a syndrome of random bits of each word alone, one with a bit of the - first word and bits of the last, and syndromes of random bits. Bit counts up to five let some - searches start from floors above two and below their minima. The three checks on six - variables of ``_RECTANGULAR_CHECKS`` get every syndrome, in random order, and exhaustive minima. - - At each ``max_weight`` up to five, with random floors, the loop runs with the tables of the - search and with an empty ``fixed_words``, which selects the version of ``_search_supports`` for - any number of words, and gives the weights that ``_get_min_weight`` states. The first syndrome - without a word within ``max_weight`` gets the bound of a single query, and a loop that stops - there writes its weight and no later one. At ``max_weight`` five, with the random floors and - with floors of five, above the number of rectangular checks, for each number of leading rows, - a budget of the states that their single searches visit stops the loop at the first row at - which its work reaches the budget, even the first row with no budget, and leaves the later - weights unwritten. + 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")) @@ -261,11 +254,9 @@ 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()) - identities = [np.eye(num_checks, dtype=np.uint8) for num_checks in (3, 4, 63, 64, 65, 129)] - for checks in [*identities, _RECTANGULAR_CHECKS]: - num_checks = len(checks) + for num_checks in (64, 65): coset_search = coset.ConnectedClusterCosetSearch( - checks, + np.eye(num_checks, dtype=np.uint8), symplectic=False, max_rounds=0, rounds_without_improvement=1, @@ -273,20 +264,16 @@ def get_bits(checks: range, num_bits: int) -> set[int]: stabilizer_overlap_cuts=True, ) tables = coset_search._get_batch_tables() - if checks is _RECTANGULAR_CHECKS: - syndromes = rng.permutation(1 << num_checks).tolist() - minima = get_binary_minima(checks)[syndromes] - else: - 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]) + 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): @@ -301,97 +288,21 @@ def get_bits(checks: range, num_bits: int) -> set[int]: 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)) - single = ( - coset_search.get_min_weight_bound(syndromes[index], max_weight) if above else None - ) - assert bound == single + 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]) - assert np.all(weights[num_written:] == -1) - - # The single searches of a row try the limits from the larger of two and its floor, up to - # its minimum or max_weight, unless the row looks up a word of weight at most one. - for budget_floors in (floors, np.full(len(batch), max_weight)): - expected = _get_batch_weights(minima, budget_floors, max_weight) - num_states = [0] - for syndrome, minimum, floor in zip(syndromes, minima.tolist(), budget_floors.tolist()): - first = max(2, floor) - limits = range( - first, min(max(minimum, first), max_weight) + 1 if minimum > 1 else 0 - ) - num_states.append( - num_states[-1] + _count_single_states(coset_search, syndrome, limits) - ) - for max_work in num_states: - num_searched = next( - (rows for rows in range(1, len(batch)) if num_states[rows] >= max_work), - len(batch), - ) - weights = np.full(len(batch), -1, dtype=np.int64) - assert coset._find_min_weights( - batch, max_weight, budget_floors, max_work, False, weights, tables - ) == (num_searched, False) - assert np.array_equal(weights[:num_searched], expected[:num_searched]) - assert np.all(weights[num_searched:] == -1) - - -def test_connected_cluster_batches_of_nine_words_take_the_search_for_any_number_of_words() -> None: - """Batch queries on checks of more than eight 64-bit words answer as on eight. - - ``_search_supports`` has fixed versions only for syndromes of up to eight words, so the tables - of checks of nine words select its version for any number of words. The identity checks I512 - and I513 fill eight and nine words. Their searches are assembled directly, as - ``SupportSearch`` builds them for identity checks, since building them takes seconds as plain - Python. A syndrome of the first and last checks has a lightest word of weight 2. - """ - for num_checks in (512, 513): - num_words = get_num_words(num_checks) - columns = np.zeros((num_checks, num_words), dtype=np.uint64) - columns[np.arange(num_checks), np.arange(num_checks) // 64] = np.left_shift( - np.uint64(1), (np.arange(num_checks) % 64).astype(np.uint64) - ) - ranks = np.arange(num_checks, dtype=np.int64) - support_search = search.SupportSearch.__new__(search.SupportSearch) - support_search._check_tables = search._CheckTables( - np.arange(num_checks + 1, dtype=np.int64), - np.arange(num_checks, dtype=np.int64), - columns, - np.zeros((num_checks, 0), dtype=np.uint64), - ) - support_search._ranks = ranks - support_search._inverse_overlaps = np.array([0, 1], dtype=np.int64) - support_search._restrict_viable_symbols = True - support_search._query_cuts = search._get_overlap_cuts( - np.zeros((0, num_checks), dtype=np.uint8), ranks, False - ) - coset_search = coset.ConnectedClusterCosetSearch.__new__(coset.ConnectedClusterCosetSearch) - coset_search._packed_map_columns = columns - coset_search._search = support_search - - batch = split_syndromes_into_words([1 | (1 << (num_checks - 1))], num_checks) - weights = np.full(1, -1, dtype=np.int64) - assert coset._find_min_weights( - batch, - 2, - np.zeros(1, dtype=np.int64), - MAX_VALUE, - False, - weights, - coset_search._get_batch_tables(), - ) == (1, False) - assert weights.tolist() == [2] def test_connected_cluster_batches_count_words_of_checks_not_of_variables() -> None: - """Queries size the syndromes of their searches by the checks, not by the variables. + """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. - Batch queries and a single query that searches all size them so. """ checks = np.hstack([np.eye(2, dtype=np.uint8), np.zeros((2, 63), dtype=np.uint8)]) coset_search = coset.ConnectedClusterCosetSearch( @@ -404,11 +315,6 @@ def test_connected_cluster_batches_count_words_of_checks_not_of_variables() -> N ) 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] - index, bound = coset_search.find_first_not_within_max_weight(batch, 1) - assert index == 1 and bound is not None and not bound.within_max_weight - bound = coset_search.get_min_weight_bound(3, 2) - word = bound.representative - assert bound.within_max_weight and word.bit_count() <= 2 and word & 3 == 3 @pytest.mark.parametrize("cuts", [True, False]) @@ -418,8 +324,7 @@ 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``. The batch queries find the first coset without a - word within ``max_weight``, with the bound of a single query, and the weight of the lightest + 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. """ @@ -477,15 +382,6 @@ def test_connected_cluster_answers_match_exhaustive_minima( within = minima <= floors assert np.all(weights[within] <= floors[within]) assert np.array_equal(weights[~within], np.minimum(minima, max_weight + 1)[~within]) - above = np.flatnonzero(minima > max_weight).tolist() - index, first_bound = coset_search.find_first_not_within_max_weight( - batch, max_weight - ) - assert index == (above[0] if above else len(batch)) - if above: - assert first_bound == coset_search.get_min_weight_bound(index, max_weight) - else: - assert first_bound is None def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() -> None: @@ -493,10 +389,8 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_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 the last syndrome would give - 3. With no split work, the rest of a batch moves to blocks after its first query, unless that - query ends the batch, as that of the first syndrome does at ``max_weight`` two. + 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), @@ -511,11 +405,6 @@ def test_connected_cluster_batches_in_blocks_answer_every_row_from_its_floor() - 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 - index, bound = coset_search.find_first_not_within_max_weight( - batch, 2, num_threads=2, split_work=0 - ) - assert index == 0 and bound is not None and bound.lower_bound == 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. @@ -558,49 +447,3 @@ def _get_batch_weights( return np.where( minima < 2, minima, np.where(minima < floors, floors, np.minimum(minima, max_weight + 1)) ) - - -def _count_single_states( - coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, limits: range -) -> int: - """The number of states that single searches of a syndrome visit at some weight limits. - - The coset of the syndrome must have no word of weight at most one. - """ - mapped = xor_selected(coset_search._syndrome_map_columns, syndrome) - packed_syndrome = int_to_words(mapped, get_num_words(len(coset_search.checks))) - return sum( - coset_search._search.find_vector_with_packed_syndrome(packed_syndrome, limit)[1] - for limit in limits - ) - - -def _count_batch_states( - coset_search: coset.ConnectedClusterCosetSearch, syndrome: int, max_weight: int -) -> int: - """The number of states that a batch query visits, as its compiled loop counts its work. - - The loop, ``_find_min_weights``, stops after a query once its work reaches ``max_work``, so of - two copies of a syndrome that is not looked up and has a vector within ``max_weight``, it - searches only the first exactly if the first visits at least ``max_work`` states. A search for - the largest such ``max_work`` finds that number. - """ - batch = split_syndromes_into_words([syndrome, syndrome], len(coset_search.checks)) - floors = np.zeros(2, dtype=np.int64) - weights = np.empty(2, dtype=np.int64) - tables = coset_search._get_batch_tables() - - def searches_one(max_work: int) -> bool: - """Whether the batch stops after the first copy within ``max_work``.""" - num_done, _ = coset._find_min_weights( - batch, max_weight, floors, max_work, False, weights, tables - ) - return bool(num_done == 1) - - low, high = 0, 1 - while searches_one(high): - low, high = high, 2 * high - while high - low > 1: - middle = (low + high) // 2 - low, high = (middle, high) if searches_one(middle) else (low, middle) - return low diff --git a/src/qldpc/codes/distance/coset_leaders_test.py b/src/qldpc/codes/distance/coset_leaders_test.py index 1a895c171..3450eae71 100644 --- a/src/qldpc/codes/distance/coset_leaders_test.py +++ b/src/qldpc/codes/distance/coset_leaders_test.py @@ -184,25 +184,6 @@ def test_x_and_z_syndromes_span_several_words(pytestconfig: pytest.Config) -> No assert found == np.flatnonzero(np.array(minima) > max_weight).tolist() -def test_min_weights_by_css_weight_read_parts_of_several_words() -> None: - """By CSS weight, batches of minimum weights read syndromes of X and Z parts of two words. - - On |0>^65, the pure-Z stabilizers check the X parts, and on |+>^65 the pure-X stabilizers - check the Z parts. Either way, the bit count of a syndrome is its minimum weight, and the - syndromes of the searched part fill two 64-bit words. Both methods map the syndromes of a - batch to those of its parts in the same code. - """ - num_qubits = 65 - identity = np.eye(num_qubits, dtype=np.uint8) - zeros = np.zeros_like(identity) - syndromes = [1 << 64, 1 | (1 << 64), 0, 1] - batch = split_syndromes_into_words(syndromes, num_qubits) - for matrix in (np.hstack([zeros, identity]), np.hstack([identity, zeros])): - search = CosetLeaderSearch(matrix, css_weight=True) - weights = search.get_min_weights(batch, 2) - assert weights.tolist() == [syndrome.bit_count() for syndrome in syndromes] - - def test_css_weight_counts_the_larger_sector() -> None: """X0 Z1 on |0+> has CSS weight one but physical weight two.""" matrix = np.array([[0, 0, 1, 0], [0, 1, 0, 0]], dtype=np.uint8)