From 1014dca285ab4abe1fca92ff822bb743ead327cd Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 14:54:47 -0500 Subject: [PATCH 1/4] Weigh connected-cluster states with fewer mispredicted branches A state of the connected-cluster search that forbids variables that are not viable summed the weights of the unsatisfied checks of each available symbol in turn, in loops whose branches the processor often mispredicted. It now adds the weight of each unsatisfied check to the repair of each of its symbols, and allows the viable symbols by selects. A state whose unsatisfied checks have more entries than there are symbols also takes the overlaps of all symbols at once, and clears all repairs at once. The searches visit the same states and find the same witnesses. On one thread, distance searches of a quantum Tanner code and of the [[276, 98, 14]] pair-partition code take about 1.2 to 1.3 times less time, and those of the [[71, 1, 11]] quadratic-residue code and of the [63, 30, 13] BCH code about 1.45 times less. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/search.py | 140 ++++++++++++------ .../_connected_cluster/search_test.py | 32 ++++ src/qldpc/codes/distance/connected_cluster.md | 10 +- 3 files changed, 138 insertions(+), 44 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/search.py b/src/qldpc/codes/distance/_connected_cluster/search.py index c68a12fc9..2c31b49ae 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search.py +++ b/src/qldpc/codes/distance/_connected_cluster/search.py @@ -1125,7 +1125,7 @@ def _search_supports( fixed_words: Empty, or an entry for each 64-bit word of a row of ``symbol_masks``, as ``_get_fixed_words`` makes it. Numba compiles a version for each length of ``fixed_words`` (see ``_MAX_FIXED_WORDS``). - memoize: Whether each state computes the overlap and repair of each symbol at most once. + memoize: Whether each state computes the overlap of each symbol at most once. restrict_viable_symbols: As for ``_get_branches``. cut_symbol_starts: Where the entries of each symbol start in ``cut_symbol_entries``. cut_symbol_entries: For each symbol in turn, ``_LOAD_BASE c + l`` for each overlap cut @@ -1185,7 +1185,9 @@ def _search_supports( # The state at each depth has a syndrome, branches, and the cursor of its next branch. A state # that restricts its subtree sets restricts[depth], since it may allow no symbols, and allows # allowances[allowance_starts[depth] : allowance_starts[depth + 1]]. Room for every state to - # allow every symbol would be large under a large cutoff, so allowances grows as needed. + # allow every symbol would be large under a large cutoff, so allowances grows as needed. A + # state also writes one entry past the symbols that it allows (see _get_branches), so + # allowances keeps room for one more. syndromes = np.zeros((max_weight + 1, num_words), dtype=np.uint64) support = np.empty(max_weight + 1, dtype=np.int64) branches = np.empty((max_weight + 1, max_branches), dtype=np.int64) @@ -1193,13 +1195,15 @@ def _search_supports( cursors = np.zeros(max_weight + 1, dtype=np.int64) restricts = np.zeros(max_weight + 1, dtype=np.bool_) allowance_starts = np.zeros(max_weight + 2, dtype=np.int64) - allowances = np.empty(num_symbols, dtype=np.int64) + allowances = np.empty(num_symbols + 1, dtype=np.int64) # Scratch space for _get_branches, whose docstring describes ``memos``. Each call gets its own # stamp, the number of calls so far, including itself, so the zeros of ``memos`` match none. check_weights = np.zeros(len(check_starts) - 1, dtype=np.int64) branch_repairs = np.empty(max_branches, dtype=np.int64) - memos = np.zeros((4, num_symbols if memoize else 0), dtype=np.int64) + symbol_overlaps = np.zeros(num_symbols, dtype=np.int64) + symbol_repairs = np.zeros(num_symbols, dtype=np.int64) + memos = np.zeros((2, num_symbols if memoize else 0), dtype=np.int64) stamp = 0 # The path of the current item, and the branch before which the state at each depth leaves; the @@ -1251,6 +1255,8 @@ def _search_supports( inverse_overlaps, check_weights, branch_repairs, + symbol_overlaps, + symbol_repairs, memos, stamp, restrict_viable_symbols, @@ -1378,10 +1384,10 @@ def _search_supports( ) continue - # Make room for the symbols that this state may allow, each at most once, and choose its - # branches. - if allowance_starts[depth] + num_symbols > len(allowances): - grown = np.empty(2 * len(allowances) + num_symbols, dtype=np.int64) + # Make room for the symbols that this state may allow, each at most once, and the entry + # past them, and choose its branches. + if allowance_starts[depth] + num_symbols + 1 > len(allowances): + grown = np.empty(2 * len(allowances) + num_symbols + 1, dtype=np.int64) grown[: allowance_starts[depth]] = allowances[: allowance_starts[depth]] allowances = grown stamp += 1 @@ -1402,6 +1408,8 @@ def _search_supports( inverse_overlaps, check_weights, branch_repairs, + symbol_overlaps, + symbol_repairs, memos, stamp, restrict_viable_symbols, @@ -1443,6 +1451,8 @@ def _get_branches( inverse_overlaps: npt.NDArray[np.int64], check_weights: npt.NDArray[np.int64], branch_repairs: npt.NDArray[np.int64], + symbol_overlaps: npt.NDArray[np.int64], + symbol_repairs: npt.NDArray[np.int64], memos: npt.NDArray[np.int64], stamp: int, restrict_viable_symbols: bool, @@ -1452,9 +1462,17 @@ def _get_branches( Section 3.4 of ``connected_cluster.md`` says when the state is pruned, and when it allows only viable symbols in its subtree. A state that restricts its subtree raises the levels of the symbols that it allows, lists them in ``allowances`` from ``allowance_starts[depth]``, and sets - ``restricts[depth]``. The branches are the available symbols of the unsatisfied check with the - fewest available symbols, after any restriction. They go to ``branches[depth]``, most repairing - first. + ``restricts[depth]``. It also writes the entry of ``allowances`` after the last symbol that it + allows. The branches are the available symbols of the unsatisfied check with the fewest + available symbols, after any restriction. They go to ``branches[depth]``, most repairing first. + + A state visits each entry of its unsatisfied checks in passes that select rather than branch + where they can, since the processor would often mispredict a branch on whether a symbol is + available or viable. If the unsatisfied checks have more entries than there are symbols, it + takes the overlaps of all symbols first, in one pass over the rows of ``symbol_masks``. A state + that restricts its subtree adds the weight of each unsatisfied check to the repair of each of + its symbols, rather than summing the weights of the unsatisfied checks of each available symbol + in turn. Args: check_starts: As for ``_search_supports``. @@ -1475,10 +1493,11 @@ def _get_branches( in units of ``1 / inverse_overlaps[1]``. check_weights: Scratch space for the weights of the checks. branch_repairs: Scratch space for the repairs of the branches. - memos: An array of four rows: with no columns, to turn memoization off, or with a column + symbol_overlaps: Scratch space for the overlap of each symbol. + symbol_repairs: Scratch space for the repair of each symbol. + memos: An array of two rows: with no columns, to turn memoization off, or with a column for each symbol. For each symbol, row 0 holds the stamp of the call that last - computed its overlap, and row 1 that overlap. Rows 2 and 3 hold the same for its - repair. + computed its overlap, and row 1 that overlap. stamp: The stamp of this call, which no other call uses. restrict_viable_symbols: Whether a state may allow only viable symbols in its subtree. @@ -1486,12 +1505,26 @@ def _get_branches( The number of branches, which is zero if the state is pruned. """ scale = inverse_overlaps[1] + num_symbols = len(symbol_overlaps) memoize = memos.shape[1] > 0 - overlap_stamps, overlaps, repair_stamps, repairs = memos[0], memos[1], memos[2], memos[3] + overlap_stamps, overlaps = memos[0], memos[1] + + # Take the overlaps of all symbols at once if the unsatisfied checks have more entries, on + # average, than there are symbols. + num_unsatisfied = 0 + for word in range(num_words): + num_unsatisfied += int(popcount_word(syndromes[depth, word])) + take_all_overlaps = num_symbols * (len(check_starts) - 1) < num_unsatisfied * check_starts[-1] + if take_all_overlaps: + for symbol in range(num_symbols): + symbol_overlaps[symbol] = _get_overlap( + syndromes, num_words, depth, symbol_masks, symbol + ) # Weigh each unsatisfied check, and choose the one with the fewest available symbols, starting - # from a count above any possible count. + # from a count above any possible count. Count the entries of the checks weighed. total_weight = 0 + num_entries = 0 branch_check = -1 fewest = check_starts[-1] + 1 for word in range(num_words): @@ -1501,7 +1534,14 @@ def _get_branches( bits &= bits - np.uint64(1) largest_overlap = 0 count = 0 - if memoize: + if take_all_overlaps: + for position in range(check_starts[check], check_starts[check + 1]): + symbol = check_symbols[position] + available = levels[symbol] == available_level + overlap = symbol_overlaps[symbol] + largest_overlap = max(largest_overlap, overlap if available else 0) + count += available + elif memoize: for position in range(check_starts[check], check_starts[check + 1]): symbol = check_symbols[position] if levels[symbol] == available_level: @@ -1517,7 +1557,7 @@ def _get_branches( count += 1 else: # Without memos, take the overlap of every symbol, and count only the available - # ones by a select rather than a branch, which the processor would often mispredict. + # ones by a select rather than a branch. for position in range(check_starts[check], check_starts[check + 1]): symbol = check_symbols[position] available = levels[symbol] == available_level @@ -1526,6 +1566,7 @@ def _get_branches( count += available if count == 0: return 0 + num_entries += check_starts[check + 1] - check_starts[check] check_weights[check] = inverse_overlaps[largest_overlap] total_weight += check_weights[check] # The total weight only grows, so prune the state as soon as it exceeds the slack. @@ -1537,8 +1578,36 @@ def _get_branches( # Symbols that flip no unsatisfied check repair nothing, so they are viable exactly when every # symbol is. If they are not, and restrict_viable_symbols is set, allow only the viable symbols # of the unsatisfied checks, and count them in each check. - if restrict_viable_symbols and total_weight > (slack - 1) * scale: + restricted = restrict_viable_symbols and total_weight > (slack - 1) * scale + if restricted: restricts[depth] = True + + # The repair of a symbol is the total weight of the unsatisfied checks that hold it, so + # clear the repairs of the symbols of these checks, or of all symbols if there are fewer, + # and add the weight of each check to each of its symbols. + if num_symbols <= num_entries: + symbol_repairs[:] = 0 + else: + for word in range(num_words): + bits = syndromes[depth, word] + while bits: + check = 64 * word + int(trailing_zeros_word(bits)) + bits &= bits - np.uint64(1) + for position in range(check_starts[check], check_starts[check + 1]): + symbol_repairs[check_symbols[position]] = 0 + for word in range(num_words): + bits = syndromes[depth, word] + while bits: + check = 64 * word + int(trailing_zeros_word(bits)) + bits &= bits - np.uint64(1) + weight = check_weights[check] + for position in range(check_starts[check], check_starts[check + 1]): + symbol_repairs[check_symbols[position]] += weight + + # A symbol is viable if its repair is at least least_repair. Allow each available viable + # symbol, once, by writing every symbol to the next entry of allowances and keeping only + # those allowed. + least_repair = total_weight - (slack - 1) * scale allowance_end = allowance_starts[depth] branch_check = -1 fewest = check_starts[-1] + 1 @@ -1550,23 +1619,12 @@ def _get_branches( count = 0 for position in range(check_starts[check], check_starts[check + 1]): symbol = check_symbols[position] - if levels[symbol] == available_level: - if not memoize: - repair = _get_repair( - syndromes, num_words, depth, symbol_masks, symbol, check_weights - ) - elif repair_stamps[symbol] != stamp: - repair = _get_repair( - syndromes, num_words, depth, symbol_masks, symbol, check_weights - ) - repair_stamps[symbol] = stamp - repairs[symbol] = repair - else: - repair = repairs[symbol] - if total_weight - repair <= (slack - 1) * scale: - levels[symbol] += 1 - allowances[allowance_end] = symbol - allowance_end += 1 + allow = (levels[symbol] == available_level) & ( + symbol_repairs[symbol] >= least_repair + ) + levels[symbol] += allow + allowances[allowance_end] = symbol + allowance_end += allow count += levels[symbol] == available_level + 1 if count == 0: allowance_starts[depth + 1] = allowance_end @@ -1584,14 +1642,10 @@ def _get_branches( symbol = check_symbols[position] if levels[symbol] != available_level: continue - if not memoize: - repair = _get_repair(syndromes, num_words, depth, symbol_masks, symbol, check_weights) - elif repair_stamps[symbol] != stamp: - repair = _get_repair(syndromes, num_words, depth, symbol_masks, symbol, check_weights) - repair_stamps[symbol] = stamp - repairs[symbol] = repair + if restricted: + repair = symbol_repairs[symbol] else: - repair = repairs[symbol] + repair = _get_repair(syndromes, num_words, depth, symbol_masks, symbol, check_weights) index = num_branches while index > 0 and branch_repairs[index - 1] < repair: branches[depth, index] = branches[depth, index - 1] diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index c55f9e3d2..c2f29a756 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -856,6 +856,38 @@ def test_the_restriction_to_viable_symbols_can_be_switched_off() -> None: assert num_states[False] == num_states[True] + 1 +def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state() -> None: + """Variables in no check change only how the states take overlaps and clear repairs. + + A state takes the overlaps of all symbols at once, and clears the repairs of all symbols, if its + unsatisfied checks have more entries than there are symbols, as ``_get_branches`` counts them. + The states of the Golay problem often do, and those of the problem padded with as many + variables in no check as the checks have entries never do. The padded variables are excluded, + and come last, so each adds a root whose one state has an empty syndrome and no witness, and + changes nothing else. + """ + checks, excluded = get_golay_problem() + num_padded = int(np.count_nonzero(checks)) + padded_checks = np.hstack([checks, np.zeros((len(checks), num_padded), dtype=np.uint8)]) + padded_excluded = np.block( + [ + [excluded, np.zeros((len(excluded), num_padded), dtype=np.uint8)], + [np.zeros((num_padded, checks.shape[1]), dtype=np.uint8), np.eye(num_padded)], + ] + ).astype(np.uint8) + search = get_search(checks, excluded, pair_sum_checks=False) + padded = get_search(padded_checks, padded_excluded, pair_sum_checks=False) + for max_weight in range(1, 8): + num_states = search.num_states, padded.num_states + witness, padded_witness = search.find_witness(max_weight), padded.find_witness(max_weight) + added_states = padded.num_states - num_states[1] - (search.num_states - num_states[0]) + if witness is None or padded_witness is None: + assert witness is None and padded_witness is None and added_states == num_padded + else: + assert witness.tolist() == padded_witness.tolist() and added_states == 0 + assert witness is not None and len(witness) == 7 + + @pytest.mark.parametrize( "switch", ["restrict_viable_symbols", "stabilizer_overlap_cuts", "pair_sum_checks"] ) diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index c52c76794..11450e58e 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -29,6 +29,13 @@ The cost thus grows with the weight of the checks, with `W`, and with the number The search raises `W` until it finds a nontrivial word ([Section 3.6](#36-from-a-search-to-the-distance)), each limit costing roughly a constant factor more than the last, so dense checks, whose factor is large, make the search slow unless the distance is small. Checks much lighter than the distance, as in surface codes, also slow the search: a support can leave few checks unsatisfied yet need many more variables, so the bounds of Section 3.4 prune little. +Each state costs time in proportion to the entries of its unsatisfied checks, which it visits in a few passes. +The first weighs each unsatisfied check by the overlaps of its available variables ([Section 3.4](#34-pruning)), and about half to two thirds of the states end in it, pruned. +An overlap counts the set bits of one 64-bit word for each 64 checks, so if the unsatisfied checks have more entries than there are variables, as with dense checks, the state first takes the overlaps of all variables at once. +A state that forbids the variables that are not viable then adds the weight of each unsatisfied check to the repair of each of its variables, and allows the viable ones in another pass. +The passes choose by selects rather than branches where they can, since the processor would often mispredict whether a variable is available or viable. +So a state of a code with heavy checks, many unsatisfied checks, or many checks costs more. + The stabilizers that `get_distance_css` and `get_distance_pauli` derive for a subsystem code can be much heavier than its lightest stabilizer generators ([Section 3.9](#39-sparser-stabilizers-of-subsystem-codes)). A caller who knows sparse stabilizer generators can search them as given with `get_distance_from_checks`, whose docstring says which matrices to pass. @@ -585,7 +592,8 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | Distance of a vector `v` from a classical code with generator matrix `G_C` | `_get_coset_weight` of `distances.py`, which `ClassicalCode.get_distance_exact(vector=v)` calls, and which, by the connected-cluster method, searches `([H \| Hv], [G_C \| 0])` and subtracts one ([Section 3.8](#38-vectors-with-a-given-syndrome)) | | Search through a weight limit `W` | `SupportSearch.find_witness` | | Syndrome query | `SupportSearch.find_vector_with_syndrome`, which coset searches skip for `SupportSearch.find_vector_with_packed_syndrome`, and the sentinel root `-1` of `_search_supports` | -| Overlaps and repairs that a syndrome query reuses within a state | `memoize` of `_search_supports`, and `memos` and `stamp` of `_get_branches` | +| Overlaps that a syndrome query reuses within a state | `memoize` of `_search_supports`, and `memos` and `stamp` of `_get_branches` | +| Overlaps of all symbols at once, and repairs summed check by check | `symbol_overlaps` and `symbol_repairs` of `_get_branches` | | 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` | From c8e51c4d2598db55ea30e57f17d68e2079cb5662 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 15:29:42 -0500 Subject: [PATCH 2/4] Describe overlap-only memos, and test both overlap routes of queries Memos of a connected-cluster state now hold overlaps only: a state that restricts its subtree sums the repairs of all its symbols check by check, in distance searches and syndrome queries alike, and its branches reuse them. The guide and the docstrings now say so, and state the rule by which a state takes the overlaps of all symbols in one pass: its number of unsatisfied checks times the average number of entries of a check exceeds the number of symbols. A new test pads binary and symplectic syndrome queries with variables in no check, which makes every state compute the overlap of each entry, and checks that the returned symbols and counts of states match those of the one-pass route, with and without memos. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_connected_cluster/search.py | 33 ++++++----- .../_connected_cluster/search_test.py | 58 +++++++++++++++++-- src/qldpc/codes/distance/connected_cluster.md | 16 ++--- 3 files changed, 81 insertions(+), 26 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/search.py b/src/qldpc/codes/distance/_connected_cluster/search.py index 2c31b49ae..fa3a5c0f4 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search.py +++ b/src/qldpc/codes/distance/_connected_cluster/search.py @@ -1125,7 +1125,9 @@ def _search_supports( fixed_words: Empty, or an entry for each 64-bit word of a row of ``symbol_masks``, as ``_get_fixed_words`` makes it. Numba compiles a version for each length of ``fixed_words`` (see ``_MAX_FIXED_WORDS``). - memoize: Whether each state computes the overlap of each symbol at most once. + memoize: Whether a state that does not take the overlaps of all symbols in one pass + memoizes the overlap of each symbol, so that it computes it at most once. Repairs are + never memoized (see ``_get_branches``). restrict_viable_symbols: As for ``_get_branches``. cut_symbol_starts: Where the entries of each symbol start in ``cut_symbol_entries``. cut_symbol_entries: For each symbol in turn, ``_LOAD_BASE c + l`` for each overlap cut @@ -1468,11 +1470,14 @@ def _get_branches( A state visits each entry of its unsatisfied checks in passes that select rather than branch where they can, since the processor would often mispredict a branch on whether a symbol is - available or viable. If the unsatisfied checks have more entries than there are symbols, it - takes the overlaps of all symbols first, in one pass over the rows of ``symbol_masks``. A state - that restricts its subtree adds the weight of each unsatisfied check to the repair of each of - its symbols, rather than summing the weights of the unsatisfied checks of each available symbol - in turn. + available or viable. The state estimates the entries of its unsatisfied checks as their number + times the average number of entries of a check. If the estimate exceeds the number of symbols, + it first takes the overlaps of all symbols in one pass over the rows of ``symbol_masks``, and + otherwise computes the overlap of each entry, once per symbol if it memoizes. A state that + restricts its subtree clears the repairs of the symbols of its unsatisfied checks, or of all + symbols if these checks have at least as many entries as there are symbols, and adds the weight + of each unsatisfied check to the repair of each of its symbols. Its branches reuse these + repairs, and the branches of a state that does not restrict its subtree compute their own. Args: check_starts: As for ``_search_supports``. @@ -1493,11 +1498,13 @@ def _get_branches( in units of ``1 / inverse_overlaps[1]``. check_weights: Scratch space for the weights of the checks. branch_repairs: Scratch space for the repairs of the branches. - symbol_overlaps: Scratch space for the overlap of each symbol. - symbol_repairs: Scratch space for the repair of each symbol. - memos: An array of two rows: with no columns, to turn memoization off, or with a column - for each symbol. For each symbol, row 0 holds the stamp of the call that last - computed its overlap, and row 1 that overlap. + symbol_overlaps: Scratch space for the overlap of each symbol, which a state that takes + all overlaps in one pass writes and reads. + symbol_repairs: Scratch space for the repair of each symbol, which a state that restricts + its subtree writes and reads. + memos: The memos of overlaps, an array of two rows: with no columns, to turn memoization + off, or with a column for each symbol. For each symbol, row 0 holds the stamp of the + call that last computed its overlap, and row 1 that overlap. Repairs have no memos. stamp: The stamp of this call, which no other call uses. restrict_viable_symbols: Whether a state may allow only viable symbols in its subtree. @@ -1509,8 +1516,8 @@ def _get_branches( memoize = memos.shape[1] > 0 overlap_stamps, overlaps = memos[0], memos[1] - # Take the overlaps of all symbols at once if the unsatisfied checks have more entries, on - # average, than there are symbols. + # Take the overlaps of all symbols in one pass if the unsatisfied checks, estimated to have the + # average number of entries of a check each, have more entries than there are symbols. num_unsatisfied = 0 for word in range(num_words): num_unsatisfied += int(popcount_word(syndromes[depth, word])) diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index c2f29a756..573ac6a30 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -859,12 +859,13 @@ def test_the_restriction_to_viable_symbols_can_be_switched_off() -> None: def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state() -> None: """Variables in no check change only how the states take overlaps and clear repairs. - A state takes the overlaps of all symbols at once, and clears the repairs of all symbols, if its - unsatisfied checks have more entries than there are symbols, as ``_get_branches`` counts them. - The states of the Golay problem often do, and those of the problem padded with as many - variables in no check as the checks have entries never do. The padded variables are excluded, - and come last, so each adds a root whose one state has an empty syndrome and no witness, and - changes nothing else. + A state takes the overlaps of all symbols in one pass if its number of unsatisfied checks times + the average number of entries of a check exceeds the number of symbols, and clears the repairs + of all symbols if its unsatisfied checks have at least as many entries as there are symbols + (see ``_get_branches``). The states of the Golay problem often do both, and those of the + problem padded with as many variables in no check as the checks have entries never do. The + padded variables are excluded, and come last, so each adds a root whose one state has an empty + syndrome and no witness, and changes nothing else. """ checks, excluded = get_golay_problem() num_padded = int(np.count_nonzero(checks)) @@ -1446,6 +1447,9 @@ def get_vector( "zero-checks": (np.zeros((2, 3)), False), # The syndrome 11 needs every variable, so a query reaches the limit of their number. "identity": (np.eye(2), False), + # The syndrome 111 has two lightest vectors, {0, 2} and {1, 3}, and its query without sums of + # pairs of checks takes the overlaps of all symbols in one pass. + "dense-queries": (np.array([[0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1]]), False), } @@ -2445,3 +2449,45 @@ def test_memoizing_changes_no_result_or_count_of_states(name: str) -> None: # Stale memos, such as those of a search from root 0, would likely change the count. assert results[0][0].tolist() == results[1][0].tolist() assert np.array_equal(results[0][1], results[1][1]) + + +@pytest.mark.parametrize("name", ["dense-queries", "nested-restrictions", "five-qubit-state"]) +def test_queries_take_the_same_states_by_either_route_to_overlaps(name: str) -> None: + """Variables in no check, and memos, change no vector that a query returns or count of states. + + The variables in no check, as many as the checks have entries, make every state of a query + compute the overlap of each entry, rather than of all symbols in one pass, and clear only the + repairs of the symbols of its unsatisfied checks (see + ``test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state``). No unsatisfied check + holds them, so they change nothing else. + """ + checks, symplectic = SYNDROME_PROBLEMS[name] + checks = np.asarray(checks, dtype=np.uint8) + num_variables = checks.shape[1] // 2 if symplectic else checks.shape[1] + num_padded = int(np.count_nonzero(checks)) + blocks = np.split(checks, 2, axis=1) if symplectic else [checks] + padding = np.zeros((len(checks), num_padded), dtype=np.uint8) + padded_checks = np.hstack([part for block in blocks for part in (block, padding)]) + searches = [ + get_search( + problem, np.zeros((0, problem.shape[1])), symplectic=symplectic, pair_sum_checks=False + ) + for problem in (checks, padded_checks) + ] + for bits in itertools.product([0, 1], repeat=len(searches[0]._checks)): + if not any(bits): + continue + packed = pack_bits(np.array([bits], dtype=np.uint8))[0] + for max_weight in range(1, num_variables + 1): + results = set() + for search, memoize in itertools.product(searches, (False, True)): + support, item_states, *_ = run_search_supports( + search, [-1], max_weight, packed, memoize=memoize + ) + # Map the symbol of each value of a variable to its symbol without padding. + width = search.num_variables + symbols = sorted( + num_variables * (symbol // width) + symbol % width for symbol in support + ) + results.add((tuple(symbols), tuple(item_states))) + assert len(results) == 1 diff --git a/src/qldpc/codes/distance/connected_cluster.md b/src/qldpc/codes/distance/connected_cluster.md index 11450e58e..29029a1b8 100644 --- a/src/qldpc/codes/distance/connected_cluster.md +++ b/src/qldpc/codes/distance/connected_cluster.md @@ -31,8 +31,9 @@ Checks much lighter than the distance, as in surface codes, also slow the search Each state costs time in proportion to the entries of its unsatisfied checks, which it visits in a few passes. The first weighs each unsatisfied check by the overlaps of its available variables ([Section 3.4](#34-pruning)), and about half to two thirds of the states end in it, pruned. -An overlap counts the set bits of one 64-bit word for each 64 checks, so if the unsatisfied checks have more entries than there are variables, as with dense checks, the state first takes the overlaps of all variables at once. -A state that forbids the variables that are not viable then adds the weight of each unsatisfied check to the repair of each of its variables, and allows the viable ones in another pass. +An overlap counts the set bits of one 64-bit word for each 64 checks. +A state estimates the entries of its unsatisfied checks as their number times the average number of entries of a check, and if the estimate exceeds the number of symbols, as with dense checks, it first takes the overlaps of all symbols in one pass over their columns, and reads them in the first pass. +A state that forbids the variables that are not viable then adds the weight of each unsatisfied check to the repair of each of its symbols, and allows the viable ones in another pass; its branches reuse these repairs. The passes choose by selects rather than branches where they can, since the processor would often mispredict whether a variable is available or viable. So a state of a code with heavy checks, many unsatisfied checks, or many checks costs more. @@ -370,9 +371,10 @@ 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. A single query, `CosetLeaderSearch.get_min_weight_bound`, searches at `W` directly, since a caller may already raise `W` one step at a time. -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. -A distance search, whose checks are usually sparse, recomputes both, since the bookkeeping would cost more than it saves. +Unless it takes the overlaps of all symbols in one pass ([Section 2](#2-what-the-cost-of-the-search-depends-on)), a state computes the overlap ([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 then memoizes the overlap of each symbol within the state. +A distance search, whose checks are usually sparse, recomputes the overlaps, since the bookkeeping would cost more than it saves. +Neither memoizes repairs: in both, a state that forbids the variables that are not viable sums the repairs of all its symbols at once, by adding the weight of each unsatisfied check to each of its symbols, and its branches reuse them. **The distance of a vector from a classical code.** The vectors with a given syndrome form a coset, whose least weight can also come from a distance search rather than a syndrome query. @@ -592,8 +594,8 @@ The names below are in `_connected_cluster/search.py`, unless the table says oth | Distance of a vector `v` from a classical code with generator matrix `G_C` | `_get_coset_weight` of `distances.py`, which `ClassicalCode.get_distance_exact(vector=v)` calls, and which, by the connected-cluster method, searches `([H \| Hv], [G_C \| 0])` and subtracts one ([Section 3.8](#38-vectors-with-a-given-syndrome)) | | Search through a weight limit `W` | `SupportSearch.find_witness` | | Syndrome query | `SupportSearch.find_vector_with_syndrome`, which coset searches skip for `SupportSearch.find_vector_with_packed_syndrome`, and the sentinel root `-1` of `_search_supports` | -| Overlaps that a syndrome query reuses within a state | `memoize` of `_search_supports`, and `memos` and `stamp` of `_get_branches` | -| Overlaps of all symbols at once, and repairs summed check by check | `symbol_overlaps` and `symbol_repairs` of `_get_branches` | +| Overlaps that a syndrome query memoizes within a state | `memoize` of `_search_supports`, and `memos` and `stamp` of `_get_branches` | +| Overlaps of all symbols in one pass, and repairs summed check by check, in distance searches and syndrome queries | `symbol_overlaps` and `symbol_repairs` of `_get_branches` | | 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` | From cf09bcbdb24db45abbc0671d49000746838ba1fd Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 11:01:40 -0500 Subject: [PATCH 3/4] Trim tests to the behavior this change introduces Keep one Golay search per route to overlaps, and check through a wrapper that only the dense one takes the overlaps of variables in no check. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../_connected_cluster/search_test.py | 96 ++++++------------- 1 file changed, 27 insertions(+), 69 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index 573ac6a30..5f84bf8da 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -18,7 +18,7 @@ import pytest from sympy.abc import x, y -from qldpc import codes +from qldpc import _compilation, codes from qldpc._binary import get_independent_rows, get_kernel, pack_bits from qldpc.objects import PAULIS_XZ, Pauli @@ -856,37 +856,40 @@ def test_the_restriction_to_viable_symbols_can_be_switched_off() -> None: assert num_states[False] == num_states[True] + 1 -def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state() -> None: +def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state( + monkeypatch: pytest.MonkeyPatch, +) -> None: """Variables in no check change only how the states take overlaps and clear repairs. A state takes the overlaps of all symbols in one pass if its number of unsatisfied checks times the average number of entries of a check exceeds the number of symbols, and clears the repairs of all symbols if its unsatisfied checks have at least as many entries as there are symbols - (see ``_get_branches``). The states of the Golay problem often do both, and those of the - problem padded with as many variables in no check as the checks have entries never do. The - padded variables are excluded, and come last, so each adds a root whose one state has an empty + (see ``_get_branches``). The states of the Golay problem padded with one variable in no check + often do both, and those of the problem padded with as many such variables as the checks have + entries never do, as only the former take the overlaps of padded variables. The padded + variables are excluded, and come last, so each adds a root whose one state has an empty syndrome and no witness, and changes nothing else. """ checks, excluded = get_golay_problem() - num_padded = int(np.count_nonzero(checks)) - padded_checks = np.hstack([checks, np.zeros((len(checks), num_padded), dtype=np.uint8)]) - padded_excluded = np.block( - [ - [excluded, np.zeros((len(excluded), num_padded), dtype=np.uint8)], - [np.zeros((num_padded, checks.shape[1]), dtype=np.uint8), np.eye(num_padded)], - ] - ).astype(np.uint8) - search = get_search(checks, excluded, pair_sum_checks=False) - padded = get_search(padded_checks, padded_excluded, pair_sum_checks=False) - for max_weight in range(1, 8): - num_states = search.num_states, padded.num_states - witness, padded_witness = search.find_witness(max_weight), padded.find_witness(max_weight) - added_states = padded.num_states - num_states[1] - (search.num_states - num_states[0]) - if witness is None or padded_witness is None: - assert witness is None and padded_witness is None and added_states == num_padded - else: - assert witness.tolist() == padded_witness.tolist() and added_states == 0 - assert witness is not None and len(witness) == 7 + get_overlap = unittest.mock.Mock(wraps=cs._get_overlap) + monkeypatch.setattr(cs, "_get_overlap", get_overlap) + symbols, num_states = [], [] + for num_padded in (1, int(np.count_nonzero(checks))): + padded_checks = np.hstack([checks, np.zeros((len(checks), num_padded), dtype=np.uint8)]) + padded_excluded = np.block( + [ + [excluded, np.zeros((len(excluded), num_padded), dtype=np.uint8)], + [np.zeros((num_padded, checks.shape[1]), dtype=np.uint8), np.eye(num_padded)], + ] + ).astype(np.uint8) + search = get_search(padded_checks, padded_excluded, pair_sum_checks=False) + get_overlap.reset_mock() + assert search.find_witness(6) is None + symbols.append({call.args[-1] for call in get_overlap.call_args_list}) + num_states.append(search.num_states - num_padded) + assert num_states[0] == num_states[1] + # Compiled code calls the compiled function rather than the wrapper. + assert not _compilation.is_compilation_disabled() or max(symbols[0]) >= 23 > max(symbols[1]) @pytest.mark.parametrize( @@ -1447,9 +1450,6 @@ def get_vector( "zero-checks": (np.zeros((2, 3)), False), # The syndrome 11 needs every variable, so a query reaches the limit of their number. "identity": (np.eye(2), False), - # The syndrome 111 has two lightest vectors, {0, 2} and {1, 3}, and its query without sums of - # pairs of checks takes the overlaps of all symbols in one pass. - "dense-queries": (np.array([[0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1]]), False), } @@ -2449,45 +2449,3 @@ def test_memoizing_changes_no_result_or_count_of_states(name: str) -> None: # Stale memos, such as those of a search from root 0, would likely change the count. assert results[0][0].tolist() == results[1][0].tolist() assert np.array_equal(results[0][1], results[1][1]) - - -@pytest.mark.parametrize("name", ["dense-queries", "nested-restrictions", "five-qubit-state"]) -def test_queries_take_the_same_states_by_either_route_to_overlaps(name: str) -> None: - """Variables in no check, and memos, change no vector that a query returns or count of states. - - The variables in no check, as many as the checks have entries, make every state of a query - compute the overlap of each entry, rather than of all symbols in one pass, and clear only the - repairs of the symbols of its unsatisfied checks (see - ``test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state``). No unsatisfied check - holds them, so they change nothing else. - """ - checks, symplectic = SYNDROME_PROBLEMS[name] - checks = np.asarray(checks, dtype=np.uint8) - num_variables = checks.shape[1] // 2 if symplectic else checks.shape[1] - num_padded = int(np.count_nonzero(checks)) - blocks = np.split(checks, 2, axis=1) if symplectic else [checks] - padding = np.zeros((len(checks), num_padded), dtype=np.uint8) - padded_checks = np.hstack([part for block in blocks for part in (block, padding)]) - searches = [ - get_search( - problem, np.zeros((0, problem.shape[1])), symplectic=symplectic, pair_sum_checks=False - ) - for problem in (checks, padded_checks) - ] - for bits in itertools.product([0, 1], repeat=len(searches[0]._checks)): - if not any(bits): - continue - packed = pack_bits(np.array([bits], dtype=np.uint8))[0] - for max_weight in range(1, num_variables + 1): - results = set() - for search, memoize in itertools.product(searches, (False, True)): - support, item_states, *_ = run_search_supports( - search, [-1], max_weight, packed, memoize=memoize - ) - # Map the symbol of each value of a variable to its symbol without padding. - width = search.num_variables - symbols = sorted( - num_variables * (symbol // width) + symbol % width for symbol in support - ) - results.add((tuple(symbols), tuple(item_states))) - assert len(results) == 1 From d041b4858ea0600a0e65555792d87ca8b429d246 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 11:06:30 -0500 Subject: [PATCH 4/4] Wrap overlaps only when the tests run as plain Python Compiled code cannot inline a wrapper, so installing it failed when no compiled code was cached. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../codes/distance/_connected_cluster/search_test.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/qldpc/codes/distance/_connected_cluster/search_test.py b/src/qldpc/codes/distance/_connected_cluster/search_test.py index 5f84bf8da..afcd4193b 100644 --- a/src/qldpc/codes/distance/_connected_cluster/search_test.py +++ b/src/qldpc/codes/distance/_connected_cluster/search_test.py @@ -871,8 +871,11 @@ def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state( syndrome and no witness, and changes nothing else. """ checks, excluded = get_golay_problem() + # Compiled code cannot call a wrapper, so only plain Python checks which route each state takes. + check_routes = _compilation.is_compilation_disabled() get_overlap = unittest.mock.Mock(wraps=cs._get_overlap) - monkeypatch.setattr(cs, "_get_overlap", get_overlap) + if check_routes: + monkeypatch.setattr(cs, "_get_overlap", get_overlap) symbols, num_states = [], [] for num_padded in (1, int(np.count_nonzero(checks))): padded_checks = np.hstack([checks, np.zeros((len(checks), num_padded), dtype=np.uint8)]) @@ -888,8 +891,7 @@ def test_taking_the_overlaps_of_all_symbols_at_once_changes_no_state( symbols.append({call.args[-1] for call in get_overlap.call_args_list}) num_states.append(search.num_states - num_padded) assert num_states[0] == num_states[1] - # Compiled code calls the compiled function rather than the wrapper. - assert not _compilation.is_compilation_disabled() or max(symbols[0]) >= 23 > max(symbols[1]) + assert not check_routes or max(symbols[0]) >= 23 > max(symbols[1]) @pytest.mark.parametrize(