diff --git a/src/qldpc/circuits/certification/_fault_search.py b/src/qldpc/circuits/certification/_fault_search.py index cffa33604..1fb1fbe0d 100644 --- a/src/qldpc/circuits/certification/_fault_search.py +++ b/src/qldpc/circuits/certification/_fault_search.py @@ -22,12 +22,16 @@ from qldpc._binary import ( get_num_words, get_rank_packed, + multiply_binary, + pack_bits, popcount_word, trailing_zeros_word, + unpack_bits, words_to_int, ) from qldpc._compilation import always_compiled from qldpc.codes.distance import CosetLeaderSearch, CosetMethod, MinWeightBound +from qldpc.codes.distance._cosets import get_unit_syndrome_words from qldpc.codes.distance._threads import get_num_threads, iterate_in_order from qldpc.codes.distance._tuning import get_tuning @@ -134,77 +138,87 @@ def find_smallest_violation( max_fault_weight = get_rank_packed(flag_rows, min(max_weight - 1, len(flag_rows))) + 1 oracle = CosetLeaderSearch(stabilizers, css_weight=css_weight, method=method) - return _search_irreducible_faults(signatures, max_fault_weight, oracle, memory_limit) + matrix = np.asarray(stabilizers, dtype=np.uint8) + return _search_irreducible_faults(signatures, max_fault_weight, oracle, matrix, memory_limit) def _search_irreducible_faults( signatures: dict[tuple[int, int], int], max_fault_weight: int, oracle: CosetLeaderSearch, + stabilizers: npt.NDArray[np.uint8], memory_limit: int = 2**30, # 1 GiB ) -> Violation | None: """Check the irreducible accepted faults that can violate the bound, by increasing fault weight. The signatures map the (flags, syndrome) of each kept primitive fault to its DEM index, and - ``max_fault_weight`` is the largest fault weight to check. Return a violating fault of the - smallest fault weight, or None if there is none. + ``max_fault_weight`` is the largest fault weight to check. ``stabilizers`` are those of the + oracle, as a binary matrix. Return a violating fault of the smallest fault weight, or None if + there is none. """ + # Split the primitive faults into heavy and light ones by their syndromes, without the oracle, + # and give each light syndrome an error of Pauli weight at most one (see "Deciding which + # primitive faults are heavy"). + syndromes = list(dict.fromkeys(syndrome for _, syndrome in signatures)) + syndrome_rows = _hashed_rows(syndromes, get_num_words(oracle.num_qubits)) + light_errors = { + syndrome: error + for syndrome, error in zip( + syndromes, _get_light_errors(syndrome_rows, stabilizers, oracle.css_weight) + ) + if error is not None + } + # Check each primitive fault with zero flags alone (see "Listing each irreducible accepted fault - # once"), and keep the others for ``FaultLister``. + # once"), and keep the others for ``FaultLister``. At fault weight one, a fault violates the + # bound exactly if it is heavy, and the oracle gives the bound of the first such fault. flagged: list[tuple[int, int, int]] = [] for (flag, syndrome), index in signatures.items(): if flag: flagged.append((flag, syndrome, index)) - continue - failure = _check_fault((index,), syndrome, oracle) - if failure is not None: - return failure - - # Split the other primitive faults into heavy and light ones. A fault that contains no heavy - # primitive fault satisfies the bound (see "A violating fault contains a heavy primitive - # fault"), so the search stops if none is heavy. Heaviness depends only on the syndrome, and - # any error with the syndrome serves as a representative (see "Checking one fault"), so the - # search queries the oracle once for each distinct syndrome. - bounds_by_syndrome = { - distinct_syndrome: oracle.get_min_weight_bound(distinct_syndrome, 1) - for distinct_syndrome in dict.fromkeys(syndrome for _, syndrome, _ in flagged) - } - heavy: list[tuple[int, int, int, int]] = [] - light: list[tuple[int, int, int, int]] = [] - for flag, syndrome, index in flagged: - bound = bounds_by_syndrome[syndrome] - primitive = (flag, syndrome, index, bound.representative) - (light if bound.within_max_weight else heavy).append(primitive) + elif syndrome not in light_errors: + return Violation((index,), syndrome, oracle.get_min_weight_bound(syndrome, 1)) + + # A fault that contains no heavy primitive fault satisfies the bound (see "A violating fault + # contains a heavy primitive fault"), so the search stops if none is heavy. + heavy = [primitive for primitive in flagged if primitive[1] not in light_errors] + light = [primitive for primitive in flagged if primitive[1] in light_errors] if not heavy: return None # Give each primitive fault a representative of low Pauli weight, so that ``FaultLister`` skips # more faults (see "Checking one fault"). A light primitive fault's representative has Pauli # weight at most one. A heavy primitive fault whose syndrome is the sum of the syndromes of two - # light ones gets the product of their representatives. The pair depends only on the syndrome, - # so the search runs once for each distinct heavy syndrome. Compiled code does it, since its - # time is proportional to the number of distinct heavy syndromes times the number of light - # ones. Any other heavy primitive fault keeps the error that the oracle returned for it. - light_errors = {syndrome: error for _, syndrome, _, error in light} - light_syndromes = list(light_errors) - heavy_syndromes = list(dict.fromkeys(syndrome for _, syndrome, _, _ in heavy)) - num_words = _get_num_words_for_values(light_syndromes + heavy_syndromes) - pairs = _get_light_pairs( - _hashed_rows(heavy_syndromes, num_words), _hashed_rows(light_syndromes, num_words) + # light ones with nonzero flags gets the product of their representatives. The pair depends + # only on the syndrome, so the search runs once for each distinct heavy syndrome. Compiled + # code does it, since its time is proportional to the number of distinct heavy syndromes times + # the number of light ones. Any other heavy primitive fault gets a fixed error with its + # syndrome, a product of destabilizers (see "Deciding which primitive faults are heavy"). + syndrome_positions = {syndrome: position for position, syndrome in enumerate(syndromes)} + light_syndromes = list(dict.fromkeys(syndrome for _, syndrome, _ in light)) + heavy_syndromes = list(dict.fromkeys(syndrome for _, syndrome, _ in heavy)) + light_rows = syndrome_rows[[syndrome_positions[syndrome] for syndrome in light_syndromes]] + heavy_rows = syndrome_rows[[syndrome_positions[syndrome] for syndrome in heavy_syndromes]] + pairs = _get_light_pairs(heavy_rows, light_rows, light_rows) + fixed_errors = iter( + _get_fixed_errors(heavy_rows[pairs[:, 0] < 0], stabilizers, oracle.css_weight) ) - pair_errors = { - syndrome: light_errors[light_syndromes[first]] ^ light_errors[light_syndromes[second]] + heavy_errors = { + syndrome: ( + light_errors[light_syndromes[first]] ^ light_errors[light_syndromes[second]] + if first >= 0 + else next(fixed_errors) + ) for syndrome, (first, second) in zip(heavy_syndromes, pairs.tolist()) - if first >= 0 } - heavy = [ - (flag, syndrome, index, pair_errors.get(syndrome, error)) - for flag, syndrome, index, error in heavy - ] + representatives = light_errors | heavy_errors # Order the primitive faults with the heavy ones first, and each group in DEM order, so that the # faults to check are the ones that contain one of the first ``len(heavy)`` primitive faults. - primitives = heavy + light + primitives = [ + (flag, syndrome, index, representatives[syndrome]) + for flag, syndrome, index in heavy + light + ] # The oracle needs only small tables, so the lister may use the whole memory limit. It lists on # as many threads as the oracle's searches use. @@ -238,14 +252,81 @@ def find_violation(syndromes: npt.NDArray[np.uint64], max_weight: int) -> int: return None -def _check_fault( - indices: tuple[int, ...], syndrome: int, oracle: CosetLeaderSearch -) -> Violation | None: - """Return the fault with these indices and syndrome if it violates the bound.""" - bound = oracle.get_min_weight_bound(syndrome, len(indices)) - if bound.within_max_weight: - return None - return Violation(indices, syndrome, bound) +def _get_light_errors( + syndrome_rows: npt.NDArray[np.uint64], stabilizers: npt.NDArray[np.uint8], css_weight: bool +) -> list[int | None]: + """For each syndrome, an error of Pauli weight at most one with it, or None if there is none. + + Each row of ``syndrome_rows`` holds the linear hash of a syndrome of the stabilizers and then + its words, as in a table of syndromes, with a word for every 64 stabilizers. + """ + # Each error of Pauli weight at most one is the product of a first and a second error from two + # short lists (see "Deciding which primitive faults are heavy"), and ``_get_light_pairs`` finds, + # for each syndrome, the first such product with that syndrome. For the physical weight, the + # first list holds the identity alone, so each syndrome takes one lookup. + num_qubits = len(stabilizers) + x_errors = [1 << qubit for qubit in range(num_qubits)] + z_errors = [1 << (num_qubits + qubit) for qubit in range(num_qubits)] + # The syndrome of X on a qubit is the column of the Z parts of the stabilizers on that qubit, + # and that of Z is the column of their X parts. + x_words = pack_bits(np.ascontiguousarray(stabilizers[:, num_qubits:].T)) + z_words = pack_bits(np.ascontiguousarray(stabilizers[:, :num_qubits].T)) + identity_words = np.zeros((1, x_words.shape[1]), dtype=np.uint64) + if css_weight: + first_errors, first_words = [0, *x_errors], np.vstack([identity_words, x_words]) + second_errors, second_words = [0, *z_errors], np.vstack([identity_words, z_words]) + else: + first_errors, first_words = [0], identity_words + second_errors = [0] + for x_error, z_error in zip(x_errors, z_errors): + second_errors += [x_error, z_error, x_error | z_error] + single_words = np.stack([x_words, z_words, x_words ^ z_words], axis=1) + second_words = np.vstack([identity_words, single_words.reshape(-1, x_words.shape[1])]) + words = np.vstack([first_words, second_words]) + rows = np.hstack([_hash_words(words)[:, None], words]) + pairs = _get_light_pairs(syndrome_rows, rows[: len(first_words)], rows[len(first_words) :]) + return [ + first_errors[first] ^ second_errors[second] if first >= 0 else None + for first, second in pairs.tolist() + ] + + +def _get_fixed_errors( + syndrome_rows: npt.NDArray[np.uint64], stabilizers: npt.NDArray[np.uint8], css_weight: bool +) -> list[int]: + """For each syndrome, a fixed error with it, from destabilizers. + + Each row of ``syndrome_rows`` holds the linear hash of a syndrome of the stabilizers and then + its words, as in ``_get_light_errors``. For the CSS weight, the X and Z parts of the error + weigh separately, so the X part is replaced by an X error on at most one qubit with the same + syndrome, if there is one, and likewise the Z part (see "Deciding which primitive faults are + heavy"). + """ + # Multiply the syndromes by the destabilizers, the errors with unit syndromes for the matrix + # that takes errors to syndromes, which is the stabilizers with their halves swapped. + num_qubits = len(stabilizers) + checks = np.hstack([stabilizers[:, num_qubits:], stabilizers[:, :num_qubits]]) + syndromes = unpack_bits(np.ascontiguousarray(syndrome_rows[:, 1:]), num_qubits) + errors = multiply_binary(syndromes, get_unit_syndrome_words(checks)) + if not css_weight: + return _to_ints(pack_bits(errors)) + + # Look up the syndrome of each part among those of the identity and of the single-qubit errors + # of its type, each of which keeps its first qubit. + parts = [] + for columns in (slice(None, num_qubits), slice(num_qubits, None)): + singles = {0: 0} + column_words = pack_bits(np.ascontiguousarray(checks[:, columns].T)) + for qubit, syndrome in enumerate(_to_ints(column_words)): + singles.setdefault(syndrome, 1 << qubit) + part_syndromes = _to_ints( + pack_bits(multiply_binary(errors[:, columns], checks[:, columns].T)) + ) + part_errors = _to_ints(pack_bits(np.ascontiguousarray(errors[:, columns]))) + parts.append( + [singles.get(syndrome, error) for syndrome, error in zip(part_syndromes, part_errors)] + ) + return [x_part | (z_part << num_qubits) for x_part, z_part in zip(*parts)] #################################################################################################### @@ -759,6 +840,14 @@ def _to_words(values: Sequence[int], num_words: int) -> npt.NDArray[np.uint64]: return words.astype(np.uint64) +def _to_ints(words: npt.NDArray[np.uint64]) -> list[int]: + """Join each row of words into an integer, the inverse of ``_to_words``. + + Bytes join words faster than shifts do. + """ + return [int.from_bytes(row.tobytes(), "little") for row in words.astype(" npt.NDArray[np.uint64]: """For each integer, a row of its linear hash and then its words, as in a table of syndromes.""" words = _to_words(values, num_words) @@ -1397,44 +1486,50 @@ def _get_key_slots(keys: npt.NDArray[np.uint64]) -> npt.NDArray[np.int64]: @always_compiled def _get_light_pairs( - heavy_rows: npt.NDArray[np.uint64], light_rows: npt.NDArray[np.uint64] + syndrome_rows: npt.NDArray[np.uint64], + first_rows: npt.NDArray[np.uint64], + second_rows: npt.NDArray[np.uint64], ) -> npt.NDArray[np.int64]: - """For each heavy syndrome, two light syndromes that sum to it, if there are any. + """For each syndrome, a first and a second syndrome that sum to it, if there are any. - Each row holds the linear hash of a syndrome and then its words, and the light syndromes are - distinct. Row ``h`` of the result holds the first light syndrome ``i``, in order, such that the - sum of heavy syndrome ``h`` and light syndrome ``i`` is a light syndrome ``j``, and then ``j``, - or -1 twice if there is none. + Each row holds the linear hash of a syndrome and then its words. Row ``r`` of the result holds + the first row ``i`` of ``first_rows`` such that the sum of syndrome ``r`` and syndrome ``i`` is + the syndrome of a row of ``second_rows``, and then the first such row ``j``, or -1 twice if + there is none. """ - # Put the light syndromes in a hash map as in ``_find_syndrome_slot``, with at least eight times - # as many slots, so that most lookups of a sum that is not light end at once at an empty slot. - # This makes the search about five times faster than with half-full slots. + # Put the second syndromes in a hash map as in ``_find_syndrome_slot``, with at least eight + # times as many slots, so that most lookups of a sum that is not a second syndrome end at once + # at an empty slot. This makes the search about five times faster than with half-full slots. + # A syndrome that repeats keeps its first row. num_slots = 2 - while num_slots < 8 * len(light_rows): + while num_slots < 8 * len(second_rows): num_slots *= 2 slots = np.full(num_slots, -1, dtype=np.int64) - for row in range(len(light_rows)): - slots[_find_syndrome_slot(light_rows[row, 0], light_rows[row, 1:], light_rows, slots)] = row - - # Most sums are not light, so look each sum up by its hash first, as ``_find_syndrome_slot`` - # does, and compare its words only with those of a light syndrome with the same hash. The - # hashes are copied out of the rows, which are long for many qubits, so that the loop reads them - # in order. - light_hashes = light_rows[:, 0].copy() - num_words = heavy_rows.shape[1] - 1 - pairs = np.full((len(heavy_rows), 2), -1, dtype=np.int64) - for heavy in range(len(heavy_rows)): - heavy_hash = heavy_rows[heavy, 0] - for first in range(len(light_rows)): - hashed = heavy_hash ^ light_hashes[first] + for row in range(len(second_rows)): + found = _find_syndrome_slot(second_rows[row, 0], second_rows[row, 1:], second_rows, slots) + if slots[found] < 0: + slots[found] = row + + # Most sums are not second syndromes, so look each sum up by its hash first, as + # ``_find_syndrome_slot`` does, and compare its words only with those of a second syndrome with + # the same hash. The hashes are copied out of the rows, which are long for many qubits, so that + # the loop reads them in order. + first_hashes = first_rows[:, 0].copy() + second_hashes = second_rows[:, 0].copy() + num_words = syndrome_rows.shape[1] - 1 + pairs = np.full((len(syndrome_rows), 2), -1, dtype=np.int64) + for row in range(len(syndrome_rows)): + syndrome_hash = syndrome_rows[row, 0] + for first in range(len(first_rows)): + hashed = syndrome_hash ^ first_hashes[first] slot = _get_first_slot(hashed, num_slots) second = slots[slot] while second >= 0: - if light_hashes[second] == hashed: + if second_hashes[second] == hashed: equal = True for word in range(1, num_words + 1): - sum_word = heavy_rows[heavy, word] ^ light_rows[first, word] - if sum_word != light_rows[second, word]: + sum_word = syndrome_rows[row, word] ^ first_rows[first, word] + if sum_word != second_rows[second, word]: equal = False break if equal: @@ -1442,8 +1537,8 @@ def _get_light_pairs( slot = (slot + 1) & (num_slots - 1) second = slots[slot] if second >= 0: - pairs[heavy, 0] = first - pairs[heavy, 1] = second + pairs[row, 0] = first + pairs[row, 1] = second break return pairs diff --git a/src/qldpc/circuits/certification/_fault_search_test.py b/src/qldpc/circuits/certification/_fault_search_test.py index 47ad7c0a2..820c5f103 100644 --- a/src/qldpc/circuits/certification/_fault_search_test.py +++ b/src/qldpc/circuits/certification/_fault_search_test.py @@ -362,25 +362,39 @@ def test_repeated_syndromes_are_checked_once() -> None: def test_light_pairs_match_brute_force( collide: bool, pytestconfig: pytest.Config, monkeypatch: pytest.MonkeyPatch ) -> None: - """Each heavy syndrome h gets the first light syndrome i such that h + i is a light syndrome.""" - # With zero hashes, lookups must compare syndromes. Syndromes of bits 62 to 65 span two words. + """Each syndrome s gets the first syndrome i of a first list such that s + i is in a second. + + The second list can repeat a syndrome. Each list can be empty, or longer or shorter than the + others. + """ + # With zero hashes, lookups must compare syndromes. Syndromes of bits 63, 64, and 128 span + # three words, and with only eight of them, many sums are in the second list. if collide: monkeypatch.setattr( _fault_search, "_hash_words", lambda words: np.zeros(len(words), np.uint64) ) rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - for _ in range(20): - light = list(dict.fromkeys(int(ss) << 62 for ss in rng.integers(16, size=6))) - heavy = [int(ss) << 62 for ss in rng.integers(16, size=8)] - num_words = _fault_search._get_num_words_for_values(light + heavy) + + def spread(size: int) -> list[int]: + """Random syndromes of bits 63, 64, and 128.""" + values = rng.integers(8, size=size).tolist() + return [(value & 1) << 63 | (value & 2) << 63 | (value & 4) << 126 for value in values] + + for sizes in itertools.product((0, 4), (0, 6), (0, 8)): + first_list, second_list, syndromes = map(spread, sizes) + num_words = _fault_search._get_num_words_for_values(first_list + second_list + syndromes) pairs = _fault_search._get_light_pairs( - _fault_search._hashed_rows(heavy, num_words), - _fault_search._hashed_rows(light, num_words), + _fault_search._hashed_rows(syndromes, num_words), + _fault_search._hashed_rows(first_list, num_words), + _fault_search._hashed_rows(second_list, num_words), ) - for syndrome, pair in zip(heavy, pairs.tolist(), strict=True): - first = next((ii for ii, ss in enumerate(light) if syndrome ^ ss in light), -1) - expected = [first, light.index(syndrome ^ light[first])] if first >= 0 else [-1, -1] - assert pair == expected + assert pairs.shape == (len(syndromes), 2) + for syndrome, (first, second) in zip(syndromes, pairs.tolist(), strict=True): + expected = next( + (ii for ii, ss in enumerate(first_list) if syndrome ^ ss in second_list), -1 + ) + assert first == expected and (second < 0) == (first < 0) + assert first < 0 or second_list[second] == syndrome ^ first_list[first] def test_rows_hash_alike_whenever_they_are_hashed() -> None: @@ -391,59 +405,183 @@ def test_rows_hash_alike_whenever_they_are_hashed() -> None: _fault_search._hash_words(np.ones((1, num_words), dtype=np.uint64)) _fault_search._get_byte_hash_tables.cache_clear() light = _fault_search._hashed_rows([1, 2], 1) - assert _fault_search._get_light_pairs(heavy, light).tolist() == [[0, 1]] + assert _fault_search._get_light_pairs(heavy, light, light).tolist() == [[0, 1]] assert _fault_search._hashed_rows([3], 1).tolist() == heavy.tolist() -def test_heavy_primitive_faults_get_products_of_light_representatives( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A heavy primitive fault gets the product of the representatives of its first light pair. +def _random_state( + rng: np.random.Generator, num_qubits: int, clifford: bool, num_plus: int +) -> npt.NDArray[np.uint8]: + """The stabilizers, in random order, of a random state. - The pair starts with the first light syndrome, in the order of the primitive faults, whose sum - with the heavy syndrome is also light. A heavy primitive fault without a pair keeps the - oracle's representative. + The state comes from a random circuit on qubits that start in |0> or, the first ``num_plus`` of + them, in |+>. The circuit has H, S, and CX gates if ``clifford`` is true, and otherwise CX + gates alone, which make CSS states. """ - # The stabilizers ZXX, X on qubit 2, and XZX make the syndromes 1, 4, 5, and 7 light. With the - # light syndromes 5, 7, and 4 of these faults, the heavy syndrome 2, which repeats, is 5 + 7, - # the heavy syndrome 3 is 7 + 4, and the heavy syndrome 6 is no such sum. The oracle's - # representatives of 2 and 3 differ from these products. - stabilizers = np.array([[0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0]]) - syndromes = [5, 7, 4, 2, 2, 3, 6] + circuit = stim.Circuit() + circuit.append("I", range(num_qubits)) + circuit.append("H", range(num_plus)) + gates = ["H", "S", "CX"] if clifford else ["CX"] + for gate in rng.choice(gates, size=8 * num_qubits): + if gate == "CX": + circuit.append("CX", rng.permutation(num_qubits)[:2].tolist()) + else: + circuit.append(gate, [int(rng.integers(num_qubits))]) + state = stim.Tableau.from_circuit(circuit).to_stabilizers() + rows = [np.concatenate(row.to_numpy()) for row in state] + return np.array(rows, dtype=np.uint8)[rng.permutation(num_qubits)] + + +@pytest.mark.parametrize("css_weight", [False, True]) +def test_light_syndromes_match_brute_force( + css_weight: bool, pytestconfig: pytest.Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """A syndrome gets an error of Pauli weight at most one exactly if it has one, on any state. + + Every syndrome also gets a fixed error with it, whose X and Z parts are single-qubit errors + where some have their syndromes, for the CSS weight. On small states, the search matches brute + force for random flags and syndromes, and reports the first heavy primitive fault with zero + flags in DEM order if one violates the bound. The lister gets the heavy primitive faults with + nonzero flags as its start members. The representative of each primitive fault has its + syndrome, and has Pauli weight at most one if it is light, or at most two if its syndrome is + the sum of those of two light ones. + """ + # The states are random, and the syndromes of 70 qubits, and the X and Z parts of their errors, + # span two words. On |+...+>, every fixed error is a Z error that can act on every qubit. With + # both X and Z stabilizers, the Z part of a fixed error need not be the lightest. On five or + # six qubits, most syndromes are heavy, and some are not the sum of two light ones. + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + states = [ + _random_state(rng, num_qubits, clifford, num_plus) + for num_qubits, clifford, num_plus in ( + (3, True, 0), + (5, True, 0), + (6, True, 0), + (6, False, 3), + (70, True, 0), + (70, False, 70), + ) + ] lister = mock.Mock(wraps=_fault_search.FaultLister) monkeypatch.setattr(_fault_search, "FaultLister", lister) - flags = [1 << jj for jj in range(len(syndromes))] - assert _fault_search.find_smallest_violation(flags, syndromes, stabilizers, None, False) is None - _, primitive_syndromes, representatives, *_, num_starts, _ = lister.call_args.args - - def syndrome_of(pauli: int) -> int: - x = [(pauli >> qubit) & 1 for qubit in range(3)] - z = [(pauli >> (3 + qubit)) & 1 for qubit in range(3)] - return sum( - int(np.dot(x, row[3:]) + np.dot(z, row[:3])) % 2 << jj - for jj, row in enumerate(stabilizers) - ) - - for syndrome, representative in zip(primitive_syndromes, representatives, strict=True): - assert syndrome_of(representative) == syndrome - oracle = _fault_search.CosetLeaderSearch(stabilizers) + def check(stabilizers: npt.NDArray[np.uint8]) -> None: + """Check the light errors and the fixed errors of a state against brute force.""" + num_qubits = len(stabilizers) + mask = (1 << num_qubits) - 1 + x_rows = [ + sum(int(bit) << qubit for qubit, bit in enumerate(row[:num_qubits])) + for row in stabilizers + ] + z_rows = [ + sum(int(bit) << qubit for qubit, bit in enumerate(row[num_qubits:])) + for row in stabilizers + ] - def oracle_representative(syndrome: int) -> int: - return oracle.get_min_weight_bound(syndrome, 1).representative + def syndrome_of(pauli: int) -> int: + """Bit ``j`` is whether the error anticommutes with stabilizer ``j``.""" + x, z = pauli & mask, pauli >> num_qubits + return sum( + ((x & z_row ^ z & x_row).bit_count() & 1) << jj + for jj, (x_row, z_row) in enumerate(zip(x_rows, z_rows)) + ) - light = [5, 7, 4] - expected = [] - for syndrome in primitive_syndromes[:num_starts]: - first = next((ss for ss in light if syndrome ^ ss in light), None) - expected.append( - oracle_representative(syndrome) - if first is None - else oracle_representative(first) ^ oracle_representative(syndrome ^ first) + def weight_of(pauli: int) -> int: + x, z = pauli & mask, pauli >> num_qubits + return max(x.bit_count(), z.bit_count()) if css_weight else (x | z).bit_count() + + # By brute force, the errors of Pauli weight at most one: X and Z on at most one qubit each, + # on the same qubit for the physical weight. + x_singles = [0] + [1 << qubit for qubit in range(num_qubits)] + z_singles = [0] + [1 << (num_qubits + qubit) for qubit in range(num_qubits)] + light_errors = [ + x | z + for x, z in itertools.product(x_singles, z_singles) + if css_weight or not x or not z or z == x << num_qubits + ] + light_syndromes = {syndrome_of(error) for error in light_errors} + + # Query every syndrome of a small state. Of a large one, query random syndromes, and those + # of the light errors, or of 1000 of them, which keeps the test fast without compilation. + if num_qubits <= 6: + syndromes = list(range(2**num_qubits)) + else: + randoms = [int.from_bytes(rng.bytes(9), "little") & mask for _ in range(100)] + sample = sorted(light_syndromes) + if len(sample) > 1000: + sample = rng.choice(sample, 1000, replace=False).tolist() + syndromes = sample + randoms + rows = _fault_search._hashed_rows(syndromes, (num_qubits + 63) // 64) + errors = _fault_search._get_light_errors(rows, stabilizers, css_weight) + for syndrome, error in zip(syndromes, errors, strict=True): + assert (error is None) == (syndrome not in light_syndromes) + assert error is None or (syndrome_of(error) == syndrome and weight_of(error) <= 1) + fixed_errors = _fault_search._get_fixed_errors(rows, stabilizers, css_weight) + assert [syndrome_of(error) for error in fixed_errors] == syndromes + if css_weight: + # Each part is an error on at most one qubit if one has the syndrome of the part. + for singles, part_mask in ((x_singles, mask), (z_singles, mask << num_qubits)): + single_syndromes = {syndrome_of(single) for single in singles} + for error in fixed_errors: + if syndrome_of(error & part_mask) in single_syndromes: + assert error & part_mask in singles + + def check_search(stabilizers: npt.NDArray[np.uint8]) -> None: + """Check the search on a small state against brute force over all its errors.""" + # By brute force, the syndrome and the weight of each Pauli error, packed into its index. + num_qubits = len(stabilizers) + bits = (np.arange(4**num_qubits)[:, None] >> np.arange(2 * num_qubits)) & 1 + x, z = bits[:, :num_qubits], bits[:, num_qubits:] + pauli_weights = ( + np.maximum(x.sum(axis=1), z.sum(axis=1)) if css_weight else (x | z).sum(axis=1) ) - assert primitive_syndromes[:num_starts] == [2, 2, 3, 6] - assert list(representatives[:num_starts]) == expected - assert oracle_representative(2) != expected[0] and oracle_representative(3) != expected[2] + syndrome_bits = x @ stabilizers[:, num_qubits:].T + z @ stabilizers[:, :num_qubits].T + pauli_syndromes = (syndrome_bits % 2) @ (1 << np.arange(num_qubits)) + minimum = { + ss: int(pauli_weights[pauli_syndromes == ss].min()) for ss in range(2**num_qubits) + } + + for rank in [0, 1, 2, 3] * 6: + flags = list(map(int, rng.integers(min(1, rank), 1 << rank, size=8))) + syndromes = list(map(int, rng.integers(2**num_qubits, size=8))) + violation = _fault_search.find_smallest_violation( + flags, syndromes, stabilizers, None, css_weight + ) + smallest = _smallest_violation(flags, syndromes, None, minimum.__getitem__) + assert (violation is None) == (smallest is None) + if violation is not None: + indices = violation.fault_indices + assert len(indices) == smallest and _xor(flags, indices) == 0 + assert violation.syndrome == _xor(syndromes, indices) + assert not violation.bound.within_max_weight + assert smallest < violation.bound.lower_bound <= minimum[violation.syndrome] + assert pauli_syndromes[violation.bound.representative] == violation.syndrome + if smallest == 1: + first = next( + jj + for jj, (flag, syndrome) in enumerate(zip(flags, syndromes)) + if not flag and minimum[syndrome] > 1 + ) + assert indices == (first,) + + signatures = [pair for pair in dict.fromkeys(zip(flags, syndromes)) if pair[0]] + num_heavy = sum(minimum[syndrome] > 1 for _, syndrome in signatures) + for call in lister.call_args_list: + _, listed_syndromes, representatives, *_, num_starts, _ = call.args + assert num_starts == num_heavy + light = set(listed_syndromes[num_starts:]) + for syndrome, representative in zip(listed_syndromes, representatives, strict=True): + assert pauli_syndromes[representative] == syndrome + if syndrome in light: + assert pauli_weights[representative] <= 1 + elif any(syndrome ^ ss in light for ss in light): + assert pauli_weights[representative] <= 2 + lister.reset_mock() + + for stabilizers in states: + check(stabilizers) + if len(stabilizers) <= 6: + check_search(stabilizers) @pytest.mark.parametrize("css_weight", [False, True]) @@ -1293,11 +1431,18 @@ def _smallest_violation( def _certify_map( - flags: Sequence[int], syndromes: Sequence[int], max_weight: int | None, num_qubits: int + flags: Sequence[int], + syndromes: Sequence[int], + max_weight: int | None, + num_qubits: int, + css_weight: bool = False, ) -> _fault_search.Violation | None: - """Search primitive faults with these flags and syndromes on |0...0> against brute force.""" + """Search primitive faults with these flags and syndromes on |0...0> against brute force. + + On |0...0>, the lightest errors are X errors, which weigh the same by either weight. + """ violation = _fault_search.find_smallest_violation( - flags, syndromes, _z_state(num_qubits), max_weight, False + flags, syndromes, _z_state(num_qubits), max_weight, css_weight ) smallest = _smallest_violation(flags, syndromes, max_weight) assert (violation is None) == (smallest is None) @@ -1381,20 +1526,50 @@ def test_hand_derived_dependency_cases() -> None: assert (failure is None) == certified -def test_batches_have_a_word_for_every_64_output_qubits() -> None: - """On 70 qubits, syndromes below ``2**64`` have two words in batches, as the oracle needs.""" - # Together, the two primitive faults pass post-selection and leave X on three qubits. - failure = _certify_map([1, 1], [0b011, 0b100], None, 70) - assert failure is not None and failure.fault_indices == (0, 1) +def test_syndromes_have_a_word_for_every_64_output_qubits(monkeypatch: pytest.MonkeyPatch) -> None: + """Syndromes have a word for every 64 output qubits, wherever the search packs them. + + On either side of 64 qubits, by either weight, syndromes with only their first or their last + bit are light, and the representatives of light and heavy syndromes have them. On 65 qubits, + syndromes in the first word get both words, as batches and the oracle need. + """ + # On |0...0>, the X part of an error with a syndrome is the syndrome. The syndrome ``last + 3`` + # is heavy, but with 2 it forms a fault of residual weight two. + lister = mock.Mock(wraps=_fault_search.FaultLister) + monkeypatch.setattr(_fault_search, "FaultLister", lister) + for num_qubits, css_weight in itertools.product((64, 65), (False, True)): + last = 1 << (num_qubits - 1) + syndromes = [1, last, last | 3, 2] + assert _certify_map([0, 0, 1, 1], syndromes, None, num_qubits, css_weight) is None + _, listed, representatives, *_ = lister.call_args.args + assert [ + representative & (2**num_qubits - 1) for representative in representatives + ] == listed + + # Together, the primitive faults 0 and 2 pass post-selection and leave X on three qubits. + failure = _certify_map([1, 1, 1], [0b011, 0b101, 0b100], None, 65) + assert failure is not None and failure.fault_indices == (0, 2) def test_failures_report_the_smallest_faults() -> None: - """A violating fault of two primitive faults is reported before a violating fault of three.""" + """A violating fault of two primitive faults is reported before a violating fault of three. + + Of two violating faults of the smallest fault weight, the reported one is the same in every + version: here the one with the earlier heavy primitive fault in DEM order, or, if both have the + same heavy one, with the earlier light one. + """ # The primitive faults 0-2 form an accepted fault of residual weight four, and the primitive # faults 3 and 4 the only accepted fault of fault weight two, which has residual weight three. failure = _certify_map([1, 2, 3, 4, 4], [1, 2, 12, 1, 6], None, 6) assert failure is not None and set(failure.fault_indices) == {3, 4} + # On |0...0>, the primitive faults 0 and 2 are heavy, with the larger syndrome first, and 1 and + # 3 are light, and {0, 1} and {2, 3} violate the bound. Then 0 is heavy and 1 and 2 are light, + # and {0, 1} and {0, 2} violate the bound. + for flags, syndromes in (([1, 1, 2, 2], [24, 1, 3, 4]), ([1, 1, 1], [3, 4, 8])): + failure = _certify_map(flags, syndromes, None, 5) + assert failure is not None and failure.fault_indices == (0, 1) + def test_light_primitive_faults_are_never_searched(monkeypatch: pytest.MonkeyPatch) -> None: """Without a heavy primitive fault, no fault can violate the bound, so none is listed.""" diff --git a/src/qldpc/circuits/certification/fault_propagation.md b/src/qldpc/circuits/certification/fault_propagation.md index 92a929629..985dd02ce 100644 --- a/src/qldpc/circuits/certification/fault_propagation.md +++ b/src/qldpc/circuits/certification/fault_propagation.md @@ -98,7 +98,7 @@ Each column of `P` for a dropped primitive fault is zero or equals the column of ### Checking one fault The search decides exactly whether `μ(S F) ≤ |F|` for a fault `F` with a minimum-weight oracle for the Pauli errors with a given syndrome. -It uses the same oracle, with the threshold one, to decide whether a primitive fault is heavy. +Whether a primitive fault is heavy takes no search ([Deciding which primitive faults are heavy](#deciding-which-primitive-faults-are-heavy)). The oracle is `qldpc.codes.distance.CosetLeaderSearch`, named for coset leaders, the lightest errors with a given syndrome. A stabilizer state is **CSS** if its stabilizer group is generated by **pure-X stabilizers**, which have no Z part, and **pure-Z stabilizers**, which have no X part. @@ -136,6 +136,28 @@ The search skips the oracle for a fault `F` in two cases, each of which cannot h It keeps them in a table, which grows within a user-specified memory limit, up to `2^31` syndromes. A full table takes no more syndromes, so the search may check some syndromes more than once. +### Deciding which primitive faults are heavy + +A primitive fault is light exactly if its syndrome is that of an error of Pauli weight at most one. +For the physical weight, these errors are the identity and the `3n` errors X, Y, and Z on one qubit. +For the CSS weight, `max(|x|, |z|) ≤ 1` means `|x| ≤ 1` and `|z| ≤ 1`, so they are the products of an X error on at most one qubit and a Z error on at most one qubit, the same qubit or another. +This holds whether or not the state is CSS. +The syndrome of X on qubit `q` is column `q` of the Z parts of `g_1, ..., g_n`, and that of Z on qubit `q` is column `q` of their X parts. +So the search looks up each distinct syndrome of a kept primitive fault in a hash table of the syndromes of these single-qubit errors and the identity. +For the physical weight, that is one lookup. +For the CSS weight, the search looks up the sum of the syndrome and that of each of the `n + 1` choices of the X error among the syndromes of the Z errors. +A light primitive fault's representative is the error of Pauli weight at most one that the lookup finds. + +A primitive fault with zero flags violates the bound exactly if it is heavy, and the search asks the oracle, with the threshold one, only for the bound of the first such fault, which it reports. +A heavy primitive fault with nonzero flags needs only a representative. +If its syndrome is the sum of the syndromes of two light primitive faults with nonzero flags, it gets the product of their representatives, of Pauli weight at most two. +Otherwise, it gets a fixed error with its syndrome: the product of the destabilizers `d_j` for the set bits `j` of its syndrome, where `d_j` anticommutes with `g_j` alone. +The matrix `H = [W_Z | W_X]` takes an error `e = [x|z]` to its syndrome `H e`. +It has rank `n`, since `g_1, ..., g_n` are independent, so row reduction gives an invertible `T` such that `T H` is the identity on `n` pivot columns. +Then `d_j` is column `j` of `T` on the pivot columns, and zero on the others. +For the CSS weight, the X and Z parts of an error weigh separately, so the search replaces the X part of the fixed error by an X error on at most one qubit with the same syndrome, if there is one, and likewise its Z part. +The syndrome of a product is the sum of the syndromes of its factors, so the error keeps its syndrome, and its lower CSS weight lets the search skip more faults. + ### Listing each irreducible accepted fault once In this section, every fault contains only [kept primitive faults](#duplicate-and-zero-signatures-can-be-dropped).