From 996add69585a74fea5e424df93b326408a528b3a Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 14:56:17 -0500 Subject: [PATCH 1/9] Store completion tables with the rows innermost A scan looks up the completion bounds of one prefix for consecutive rows s, with the same values on each block. With each row's tables contiguous, these lookups were offsets[-1] bytes apart and each missed the caches. Index the tables as (offsets[b] + x) * (num_rows - 1) + s instead, so that they share cache lines. The stored bounds, the decisions made from them, and the cost model are unchanged. The fill collects the tables of up to 64 rows in a tile and transposes it into place, reading the tile a word at a time. A test checks the bounds of a basis of more rows than one tile holds against their definition. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../_information_sets/completion_bounds.py | 46 +++++++++++++++---- .../completion_bounds_test.py | 12 +++++ .../codes/distance/brouwer_zimmermann.md | 1 + 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds.py b/src/qldpc/codes/distance/_information_sets/completion_bounds.py index 247463fc0..553697b06 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds.py @@ -18,6 +18,7 @@ from __future__ import annotations import math +import sys from dataclasses import dataclass import numpy as np @@ -29,6 +30,10 @@ from .._tuning import SearchTuning from . import certificates +# The shifts that take byte ``i`` of a word of packed bytes to its lowest byte are +# ``_FIRST_BYTE_SHIFT + _BYTE_SHIFT_STEP * i``. +_FIRST_BYTE_SHIFT, _BYTE_SHIFT_STEP = (0, 8) if sys.byteorder == "little" else (56, -8) + #################################################################################################### # completion tables @@ -40,9 +45,10 @@ class CompletionTables: The tables belong to the packed tails of one systematic basis, with its rows in the order in which a search sums them (Section 3.9). Block ``b`` covers the tail columns from ``b * block_bits`` up to, but not including, ``(b + 1) * block_bits``, and the last block may be - narrower. Viewed with shape ``(num_rows - 1, offsets[-1])``, entry ``offsets[b] + x`` of row - ``s`` of ``tables`` is the least weight of ``x + P_i + P_j`` on block ``b`` over the pairs - ``s <= i < j``, where ``x`` is the value of a tail on the block. + narrower. Viewed with shape ``(offsets[-1], num_rows - 1)``, entry ``s`` of row + ``offsets[b] + x`` of ``tables`` is the least weight of ``x + P_i + P_j`` on block ``b`` over + the pairs ``s <= i < j``, where ``x`` is the value of a tail on the block. Section 3.9 says why + the rows ``s`` are innermost. """ tables: npt.NDArray[np.uint8] @@ -210,14 +216,14 @@ def get_completion_bound( ``tables``, ``offsets``, and ``block_bits`` are those of ``CompletionTables``. The sum stops once it reaches ``limit``, so the result is the bound or a lower value of at least ``limit``. """ - base = first * offsets[-1] + num_table_rows = len(tables) // offsets[-1] # Bytes from the tables add up in int64, which no number of blocks can overflow. bound = np.int64(0) for block in range(len(offsets) - 1): # Take each value within the size of its own table, so that ones of the prefix past the last # tail column with a one never index another table. value = _get_block_value(prefix, block * block_bits, offsets[block + 1] - offsets[block]) - bound += np.int64(tables[base + offsets[block] + np.int64(value)]) + bound += np.int64(tables[(offsets[block] + np.int64(value)) * num_table_rows + first]) if bound >= limit: break return bound @@ -354,9 +360,17 @@ def _fill_tables( On each block, the table of row ``s`` holds the distance from each value to the nearest sum of a pair of rows from ``s`` on. A breadth-first search computes it from the table of row ``s + 1``. + The tables of up to 64 rows collect in a tile, whose transpose then fills ``tables``. Reading + the tile a word at a time, rather than a byte at a time, makes this transpose about a third + cheaper. """ num_rows = rows.shape[0] - row_bytes = offsets[-1] + num_table_rows = num_rows - 1 + tile_rows, tile_words = 64, 4 + # The first block, if any, is the widest. A row of the tile holds at least one word. + widest = offsets[1] if len(offsets) > 1 else 0 + tile = np.empty((min(tile_rows, num_table_rows), max(widest, 8)), dtype=np.uint8) + words = tile.view(np.uint64) for block in range(len(offsets) - 1): start = block * block_bits size = offsets[block + 1] - offsets[block] @@ -392,8 +406,24 @@ def _fill_tables( distances[neighbor] = distance queue[tail] = neighbor tail += 1 - begin = first * row_bytes + offsets[block] - tables[begin : begin + size] = distances + low = first - first % tile_rows + tile[first - low, :size] = distances + + # Once the tile's first row is stored, copy the tile into the tables of the block, a + # few words of each row at a time, so that the words stay in the caches. + if first == low: + num_words = -(-size // 8) + block_start = offsets[block] * num_table_rows + for begin in range(0, num_words, tile_words): + for row in range(low, min(low + tile_rows, num_table_rows)): + for word in range(begin, min(begin + tile_words, num_words)): + entries = words[row - low, word] + entry = block_start + 8 * word * num_table_rows + row + for point in range(8): + if point < size: + shift = np.uint64(_FIRST_BYTE_SHIFT + _BYTE_SHIFT_STEP * point) + byte = np.uint8((entries >> shift) & np.uint64(255)) + tables[entry + point * num_table_rows] = byte @always_compiled diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index fd2bc0024..494633a0d 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -98,6 +98,18 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None: ) +def test_bounds_of_a_basis_of_many_rows_match_their_definition(pytestconfig: pytest.Config) -> None: + """Bounds from the tables of a basis of many rows, from every row on, match their definition.""" + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + tails = get_random_tails(rng, 67, 6) + tables = cb.CompletionTables.build(pack_bits(tails), 4) + for first in range(len(tails) - 1): + prefix = rng.integers(0, 2, (1, tails.shape[1]), dtype=np.uint8) + packed = pack_bits(prefix)[0] + bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, first, packed, 10**9) + assert bound == get_bound_oracle(tails, prefix[0], first, 4) + + def test_bounds_ignore_ones_past_the_tails() -> None: """A prefix with ones past the last tail column with a one reads only its own tables.""" tails = np.eye(3, dtype=np.uint8) diff --git a/src/qldpc/codes/distance/brouwer_zimmermann.md b/src/qldpc/codes/distance/brouwer_zimmermann.md index 01a2fd0c7..04346705c 100644 --- a/src/qldpc/codes/distance/brouwer_zimmermann.md +++ b/src/qldpc/codes/distance/brouwer_zimmermann.md @@ -457,6 +457,7 @@ The breadth-first search halts at each value whose distance it does not lower, s With blocks of `β` columns, the tables take `(r - 1) Σ_b 2^|J_b|` bytes, and building them costs about `2^β β^2` steps for each block, plus a step for each pair of rows on each block, and writing each table. A lookup reads one entry per block. The scan looks up the bound each time it tries a new first row `s` for the pair that completes a prefix, and if `w + B ≥ U`, skips every completion of the prefix from row `s` on. +Until it skips, the scan looks up the bounds of one prefix for consecutive `s`, so the tables store the entries of every `s` for one value on a block next to each other, where these lookups share cache lines. A bound for a larger `s` is stronger, so a support is skipped exactly if the bound of its own `s` reaches `U - w`. The threads of a split layer ([Section 4.5](brouwer_zimmermann_code.md#45-behavior-spanning-files)), and coset queries that run at once, each read shared tables, so a table must be complete before any scan reads it, and unchanged while scans do ([Section 5](brouwer_zimmermann_code.md#5-correctness-requirements)). Heuristic search in artificial intelligence calls such tables additive pattern databases: their entries for disjoint parts of a problem add up to a lower bound. From 155c5ce1242eeccd801659233fff379d75c06d3a Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 15:27:10 -0500 Subject: [PATCH 2/9] Bound nothing with completion tables that have no blocks Tables without blocks, such as NO_TABLES and the tables of tails without ones, have offsets[-1] == 0, so counting their rows divided by zero. Return the bound zero for them before counting, as the lookup did before the rows moved innermost. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../distance/_information_sets/completion_bounds.py | 3 +++ .../distance/_information_sets/completion_bounds_test.py | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds.py b/src/qldpc/codes/distance/_information_sets/completion_bounds.py index 553697b06..db4faeb94 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds.py @@ -216,6 +216,9 @@ def get_completion_bound( ``tables``, ``offsets``, and ``block_bits`` are those of ``CompletionTables``. The sum stops once it reaches ``limit``, so the result is the bound or a lower value of at least ``limit``. """ + # Tables without blocks, such as ``NO_TABLES``, have no rows to count and bound nothing. + if len(offsets) == 1: + return np.int64(0) num_table_rows = len(tables) // offsets[-1] # Bytes from the tables add up in int64, which no number of blocks can overflow. bound = np.int64(0) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 494633a0d..94eecbb80 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -110,6 +110,15 @@ def test_bounds_of_a_basis_of_many_rows_match_their_definition(pytestconfig: pyt assert bound == get_bound_oracle(tails, prefix[0], first, 4) +def test_tables_without_blocks_bound_nothing() -> None: + """Tables of tails without ones, and ``NO_TABLES``, give the bound zero.""" + rows = np.zeros((2, 1), dtype=np.uint64) + prefix = np.zeros(1, dtype=np.uint64) + for tables in (cb.CompletionTables.build(rows, 4), cb.NO_TABLES): + bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, 0, prefix, 10**9) + assert bound == 0 + + def test_bounds_ignore_ones_past_the_tails() -> None: """A prefix with ones past the last tail column with a one reads only its own tables.""" tails = np.eye(3, dtype=np.uint8) From 6b7b2a971484b4696c447e20aa37d8def2d386f9 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 21:20:36 -0500 Subject: [PATCH 3/9] Check every entry of completion tables against its definition The test of a basis of many rows checked one random bound from each row of its tables, on blocks of four columns. Check instead every entry of the tables against the least weight of each value plus two rows, found by enumerating the pairs on each block. The tails cover the cases of the transposing fill: fewer and more rows of tables than the 64 that it transposes at once, blocks of fewer than eight values and of 256 values, and narrower last blocks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 56 ++++++++++++++++--- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 94eecbb80..3ea217695 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -98,16 +98,54 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None: ) -def test_bounds_of_a_basis_of_many_rows_match_their_definition(pytestconfig: pytest.Config) -> None: - """Bounds from the tables of a basis of many rows, from every row on, match their definition.""" +def get_value(bits: npt.NDArray[np.uint8]) -> int: + """The value of a block of columns, with its first column in the lowest bit.""" + return int(bits.astype(np.int64) @ (1 << np.arange(len(bits)))) + + +def get_block_minima( + tails: npt.NDArray[np.uint8], start: int, block_bits: int +) -> npt.NDArray[np.int64]: + """The least weights on a block of its values plus two rows from each row on, by enumeration. + + The block has the columns from ``start`` on, at most ``block_bits`` of them. Entry ``[s, x]`` + is the least weight on the block of ``x`` plus two rows from row ``s`` on. + """ + block = tails[:, start : start + block_bits] + values = np.array([get_value(row) for row in block]) + points = np.arange(1 << block.shape[1]) + weights = np.array([point.bit_count() for point in range(len(points))]) + num_rows = len(tails) + minima = np.empty((num_rows - 1, len(points)), dtype=np.int64) + for first in range(num_rows - 1): + sums = (values[:, None] ^ values[None, :])[first:, first:] + pairs = np.unique(sums[np.triu_indices(num_rows - first, 1)]) + minima[first] = weights[points[:, None] ^ pairs[None, :]].min(axis=1) + return minima + + +def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.Config) -> None: + """Every entry of the tables of random tails matches its definition. + + The fill transposes the tables of 64 rows at once, four words of each at a time. The first + tails have fewer rows of tables, on blocks of fewer than eight values. The second have more, on + blocks of 256 values. Where blocks have more than one column, the last block is narrower. + """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - tails = get_random_tails(rng, 67, 6) - tables = cb.CompletionTables.build(pack_bits(tails), 4) - for first in range(len(tails) - 1): - prefix = rng.integers(0, 2, (1, tails.shape[1]), dtype=np.uint8) - packed = pack_bits(prefix)[0] - bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, first, packed, 10**9) - assert bound == get_bound_oracle(tails, prefix[0], first, 4) + for num_rows, block_bits in [(63, int(rng.choice([1, 2]))), (66, 8)]: + last_bits = int(rng.integers(1, block_bits)) if block_bits > 1 else 1 + num_columns = block_bits * int(rng.integers(1, 3)) + last_bits + tails = get_random_tails(rng, num_rows, num_columns) + # A one in the last column keeps the last block as wide as the columns make it. + tails[rng.integers(num_rows), -1] = 1 + tables = cb.CompletionTables.build(pack_bits(tails), block_bits) + offsets = tables.offsets + entries = tables.tables.reshape(offsets[-1], num_rows - 1) + for block, start in enumerate(range(0, num_columns, block_bits)): + block_entries = entries[offsets[block] : offsets[block + 1]] + np.testing.assert_array_equal( + block_entries.T, get_block_minima(tails, start, block_bits) + ) def test_tables_without_blocks_bound_nothing() -> None: From 064f1091753d29c86c72abb54f109741427806d2 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Wed, 25 Nov 2026 23:39:00 -0500 Subject: [PATCH 4/9] Check the bounds and storage of completion tables of three tiles of rows Check the bounds that completion tables give from every row, not only their entries, against the least weights found by enumerating pairs. Replace the tails of fewer rows of tables than one tile with tails of three tiles, so that rows past the first 128 are stored and looked up, and add tails with an entry of 16, the largest distance. Fill storage that starts with a value that no entry takes, so that entries left unwritten show, and fill a strided view, so that the tables fill the storage given and leave the bytes between them unchanged. Drop the tails of 66 rows, whose cases the others cover. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 63 +++++++++++++------ 1 file changed, 45 insertions(+), 18 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 3ea217695..4a4f9ba53 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -125,27 +125,47 @@ def get_block_minima( def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.Config) -> None: - """Every entry of the tables of random tails matches its definition. + """Every entry of the tables of tails, and the bounds that they give, match their definitions. - The fill transposes the tables of 64 rows at once, four words of each at a time. The first - tails have fewer rows of tables, on blocks of fewer than eight values. The second have more, on - blocks of 256 values. Where blocks have more than one column, the last block is narrower. + The fill transposes the tables of 64 rows at once, four words of each at a time. The random + tails have three tiles of rows of tables, on blocks of fewer than eight values, and where blocks + have two columns, the last has one. The other tails have one row of tables, on a block of + sixteen columns, and an entry of 16, the largest distance. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - for num_rows, block_bits in [(63, int(rng.choice([1, 2]))), (66, 8)]: - last_bits = int(rng.integers(1, block_bits)) if block_bits > 1 else 1 - num_columns = block_bits * int(rng.integers(1, 3)) + last_bits - tails = get_random_tails(rng, num_rows, num_columns) - # A one in the last column keeps the last block as wide as the columns make it. - tails[rng.integers(num_rows), -1] = 1 - tables = cb.CompletionTables.build(pack_bits(tails), block_bits) - offsets = tables.offsets - entries = tables.tables.reshape(offsets[-1], num_rows - 1) - for block, start in enumerate(range(0, num_columns, block_bits)): - block_entries = entries[offsets[block] : offsets[block + 1]] - np.testing.assert_array_equal( - block_entries.T, get_block_minima(tails, start, block_bits) - ) + block_bits = int(rng.choice([1, 2])) + tails = get_random_tails(rng, 130, block_bits * int(rng.integers(1, 3)) + 1) + # A one in the last column keeps the last block as wide as the columns make it. + tails[rng.integers(130), -1] = 1 + # The only sum of two equal rows of ones is zero, at distance 16 from the value with all ones. + cases = [ + (tails, block_bits, range(1 << block_bits)), + (np.ones((2, 16), dtype=np.uint8), 16, [2**16 - 1]), + ] + + for tails, block_bits, values in cases: + num_rows, num_columns = tails.shape + minima = [ + get_block_minima(tails, start, block_bits) + for start in range(0, num_columns, block_bits) + ] + sizes = [block_minima.shape[1] for block_minima in minima] + # Fill storage of a value that no entry takes, so that every entry left unwritten shows. + out = np.full((num_rows - 1) * sum(sizes), 255, dtype=np.uint8) + tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) + entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) + for block_entries, block_minima in zip(entries, minima, strict=True): + np.testing.assert_array_equal(block_entries.T, block_minima) + + # Bound, from every row, prefixes that take the same value on every block. + for value in values: + prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 + packed = pack_bits(prefix[None].astype(np.uint8))[0] + for first in range(num_rows - 1): + bound = cb.get_completion_bound( + tables.tables, tables.offsets, block_bits, first, packed, 10**9 + ) + assert bound == sum(m[first, value % m.shape[1]] for m in minima) def test_tables_without_blocks_bound_nothing() -> None: @@ -193,6 +213,13 @@ def test_tables_within_a_limit_fit_only_if_they_skip_something_and_build_in_plac cb.CompletionTables.build(rows, 8, out=array[1:-1]) np.testing.assert_array_equal(array[1:-1], tables.tables) assert array[0] == array[-1] == 255 + + # Strided storage, whose bytes between those of the tables stay unchanged. + tails = np.array([[0], [1]], dtype=np.uint8) + storage = np.full(4, 255, dtype=np.uint8) + cb.CompletionTables.build(pack_bits(tails), 1, out=storage[::2]) + np.testing.assert_array_equal(storage[::2], get_block_minima(tails, 0, 1)[0]) + assert np.all(storage[1::2] == 255) for size in (num_bytes - 1, num_bytes + 1): with pytest.raises(AssertionError): cb.CompletionTables.build(rows, 8, out=np.empty(size, dtype=np.uint8)) From 9a90f850d52e813e57a5083f9c7d8ee1cbc89d4e Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 00:52:35 -0500 Subject: [PATCH 5/9] Check completion tables over a matrix of rows, blocks and storage Check every entry and every bound of completion tables for each combination of 130 or 258 rows, which cross tiles of rows and row 256, and blocks of 1, 2 or 8 columns, so that rows of tables of several words cross tiles too. Fill both contiguous storage and every other byte of storage, check that the bytes between entries stay unchanged, and look the bounds up in the strided tables. This covers the case of strided storage of the test of building in place, which is dropped. Compute the least weights from each row by adding the pairs of that row to those from the next row, so that 258 rows stay quick as plain Python. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 79 ++++++++++--------- 1 file changed, 40 insertions(+), 39 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 4a4f9ba53..a352edba3 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -117,10 +117,12 @@ def get_block_minima( weights = np.array([point.bit_count() for point in range(len(points))]) num_rows = len(tails) minima = np.empty((num_rows - 1, len(points)), dtype=np.int64) - for first in range(num_rows - 1): - sums = (values[:, None] ^ values[None, :])[first:, first:] - pairs = np.unique(sums[np.triu_indices(num_rows - first, 1)]) - minima[first] = weights[points[:, None] ^ pairs[None, :]].min(axis=1) + # The pairs from row s on are those from row s + 1 on and those of row s with a later row. + least = np.full(len(points), block.shape[1] + 1) + for first in range(num_rows - 2, -1, -1): + sums = np.unique(values[first] ^ values[first + 1 :]) + least = np.minimum(least, weights[points[:, None] ^ sums[None, :]].min(axis=1)) + minima[first] = least return minima @@ -128,44 +130,50 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C """Every entry of the tables of tails, and the bounds that they give, match their definitions. The fill transposes the tables of 64 rows at once, four words of each at a time. The random - tails have three tiles of rows of tables, on blocks of fewer than eight values, and where blocks - have two columns, the last has one. The other tails have one row of tables, on a block of - sixteen columns, and an entry of 16, the largest distance. + tails have three or five tiles of rows of tables, the last with one row, on two blocks of two to + 256 values, where the last block may be narrower. The other tails have one row of tables, on a + block of sixteen columns, and an entry of 16, the largest distance. The tables fill contiguous + storage, and every other byte of storage, whose bytes between them stay unchanged. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - block_bits = int(rng.choice([1, 2])) - tails = get_random_tails(rng, 130, block_bits * int(rng.integers(1, 3)) + 1) - # A one in the last column keeps the last block as wide as the columns make it. - tails[rng.integers(130), -1] = 1 + cases = [] + for num_rows, block_bits in itertools.product([130, 258], [1, 2, 8]): + tails = get_random_tails(rng, num_rows, block_bits + int(rng.integers(1, block_bits + 1))) + # A one in the last column keeps the last block as wide as the columns make it. + tails[rng.integers(num_rows), -1] = 1 + cases.append((tails, block_bits)) # The only sum of two equal rows of ones is zero, at distance 16 from the value with all ones. - cases = [ - (tails, block_bits, range(1 << block_bits)), - (np.ones((2, 16), dtype=np.uint8), 16, [2**16 - 1]), - ] + cases.append((np.ones((2, 16), dtype=np.uint8), 16)) - for tails, block_bits, values in cases: + for tails, block_bits in cases: num_rows, num_columns = tails.shape minima = [ get_block_minima(tails, start, block_bits) for start in range(0, num_columns, block_bits) ] sizes = [block_minima.shape[1] for block_minima in minima] - # Fill storage of a value that no entry takes, so that every entry left unwritten shows. - out = np.full((num_rows - 1) * sum(sizes), 255, dtype=np.uint8) - tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) - entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) - for block_entries, block_minima in zip(entries, minima, strict=True): - np.testing.assert_array_equal(block_entries.T, block_minima) - - # Bound, from every row, prefixes that take the same value on every block. - for value in values: - prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 - packed = pack_bits(prefix[None].astype(np.uint8))[0] - for first in range(num_rows - 1): - bound = cb.get_completion_bound( - tables.tables, tables.offsets, block_bits, first, packed, 10**9 - ) - assert bound == sum(m[first, value % m.shape[1]] for m in minima) + num_bytes = (num_rows - 1) * sum(sizes) + # Every value of blocks of up to four values, and otherwise a few, including all ones. + values = {(1 << block_bits) - 1, *rng.permutation(1 << block_bits)[:4].tolist()} + for step in [1, 2]: + # Fill storage of a value that no entry takes, so that every entry left unwritten and + # every byte written between entries shows. + storage = np.full(step * num_bytes, 255, dtype=np.uint8) + tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=storage[::step]) + assert np.all(storage.reshape(-1, step)[:, 1:] == 255) + entries = np.split(storage[::step].reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) + for block_entries, block_minima in zip(entries, minima, strict=True): + np.testing.assert_array_equal(block_entries.T, block_minima) + + # Bound, from every row, prefixes that take the same value on every block. + for value in values: + prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 + packed = pack_bits(prefix[None].astype(np.uint8))[0] + for first in range(num_rows - 1): + bound = cb.get_completion_bound( + tables.tables, tables.offsets, block_bits, first, packed, 10**9 + ) + assert bound == sum(m[first, value % m.shape[1]] for m in minima) def test_tables_without_blocks_bound_nothing() -> None: @@ -213,13 +221,6 @@ def test_tables_within_a_limit_fit_only_if_they_skip_something_and_build_in_plac cb.CompletionTables.build(rows, 8, out=array[1:-1]) np.testing.assert_array_equal(array[1:-1], tables.tables) assert array[0] == array[-1] == 255 - - # Strided storage, whose bytes between those of the tables stay unchanged. - tails = np.array([[0], [1]], dtype=np.uint8) - storage = np.full(4, 255, dtype=np.uint8) - cb.CompletionTables.build(pack_bits(tails), 1, out=storage[::2]) - np.testing.assert_array_equal(storage[::2], get_block_minima(tails, 0, 1)[0]) - assert np.all(storage[1::2] == 255) for size in (num_bytes - 1, num_bytes + 1): with pytest.raises(AssertionError): cb.CompletionTables.build(rows, 8, out=np.empty(size, dtype=np.uint8)) From 2ad1976ba909d169b9b9ad070b558b20a7de96b4 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 02:29:03 -0500 Subject: [PATCH 6/9] Check completion tables of a full last tile and in reversed storage Add tails of 65 rows on blocks of one column, whose 64 rows of tables fill exactly one tile, to the cases whose every entry and bound are checked, and keep of the larger tails only those of 258 rows. Fill every other byte of storage backward instead of forward, so that the tables and their bounds are also checked with a negative stride. Bound the tables without blocks with their own block width, which is zero for NO_TABLES. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index a352edba3..ede0c1100 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -130,18 +130,20 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C """Every entry of the tables of tails, and the bounds that they give, match their definitions. The fill transposes the tables of 64 rows at once, four words of each at a time. The random - tails have three or five tiles of rows of tables, the last with one row, on two blocks of two to - 256 values, where the last block may be narrower. The other tails have one row of tables, on a - block of sixteen columns, and an entry of 16, the largest distance. The tables fill contiguous - storage, and every other byte of storage, whose bytes between them stay unchanged. + tails have five tiles of rows of tables, the last with one row, on two blocks of four or 256 + values, where the last block may be narrower. The tails of 65 rows have one full tile. The + tails of two rows have one row of tables, on a block of sixteen columns, and an entry of 16, the + largest distance. The tables fill contiguous storage, and every other byte of storage backward, + whose bytes between them stay unchanged. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) cases = [] - for num_rows, block_bits in itertools.product([130, 258], [1, 2, 8]): - tails = get_random_tails(rng, num_rows, block_bits + int(rng.integers(1, block_bits + 1))) + for block_bits in [2, 8]: + tails = get_random_tails(rng, 258, block_bits + int(rng.integers(1, block_bits + 1))) # A one in the last column keeps the last block as wide as the columns make it. - tails[rng.integers(num_rows), -1] = 1 + tails[rng.integers(258), -1] = 1 cases.append((tails, block_bits)) + cases.append((get_random_tails(rng, 65, 1), 1)) # The only sum of two equal rows of ones is zero, at distance 16 from the value with all ones. cases.append((np.ones((2, 16), dtype=np.uint8), 16)) @@ -155,13 +157,16 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C num_bytes = (num_rows - 1) * sum(sizes) # Every value of blocks of up to four values, and otherwise a few, including all ones. values = {(1 << block_bits) - 1, *rng.permutation(1 << block_bits)[:4].tolist()} - for step in [1, 2]: + for step in [1, -2]: # Fill storage of a value that no entry takes, so that every entry left unwritten and # every byte written between entries shows. - storage = np.full(step * num_bytes, 255, dtype=np.uint8) - tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=storage[::step]) - assert np.all(storage.reshape(-1, step)[:, 1:] == 255) - entries = np.split(storage[::step].reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) + storage = np.full(abs(step) * num_bytes, 255, dtype=np.uint8) + out = storage[::step] + tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) + gaps = np.ones(len(storage), dtype=bool) + gaps[np.arange(len(storage))[::step]] = False + assert np.all(storage[gaps] == 255) + entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) for block_entries, block_minima in zip(entries, minima, strict=True): np.testing.assert_array_equal(block_entries.T, block_minima) @@ -181,7 +186,9 @@ def test_tables_without_blocks_bound_nothing() -> None: rows = np.zeros((2, 1), dtype=np.uint64) prefix = np.zeros(1, dtype=np.uint64) for tables in (cb.CompletionTables.build(rows, 4), cb.NO_TABLES): - bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, 0, prefix, 10**9) + bound = cb.get_completion_bound( + tables.tables, tables.offsets, tables.block_bits, 0, prefix, 10**9 + ) assert bound == 0 From b68eb779ebe0afc4adace8aa5577dfa7e2575fc4 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 04:18:22 -0500 Subject: [PATCH 7/9] Check completion tables of random shapes, in either byte order Draw the cases whose every entry and bound are checked at random: row counts that straddle the tiles of 64 rows of tables, column counts that straddle the words of 64 columns, blocks of 1, 2 or 8 columns, and sparse tails, so that rows differ and single ones fall in late rows and columns. Each seed has a full last tile, a later partial tile of several rows, more than 256 rows, and later tiles of blocks past the first word or of more than four words, and fills contiguous and reversed storage. These replace the fixed cases of 258 and 65 rows. Check that the byte shifts take each byte of a word to its lowest byte on machines of either byte order, from copies of the module imported as if on each. Check also that a bound stopped early at a limit is at most the bound and at least the smaller of the bound and the limit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 113 ++++++++++++------ 1 file changed, 77 insertions(+), 36 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index ede0c1100..17b665c03 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -5,9 +5,11 @@ from __future__ import annotations import dataclasses +import importlib.util import itertools import math -from typing import Any +import sys +from typing import Any, Literal import numpy as np import numpy.typing as npt @@ -93,6 +95,7 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None: for limit in range(bound + 2): stopped = get_bound(tables.tables, tables.offsets, bits, first, packed, limit) assert (stopped >= limit) == (bound >= limit) + assert min(int(bound), limit) <= stopped <= bound assert all( bounds[narrow] <= bounds[wide] for narrow, wide in itertools.pairwise(widths) ) @@ -129,56 +132,94 @@ def get_block_minima( def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.Config) -> None: """Every entry of the tables of tails, and the bounds that they give, match their definitions. - The fill transposes the tables of 64 rows at once, four words of each at a time. The random - tails have five tiles of rows of tables, the last with one row, on two blocks of four or 256 - values, where the last block may be narrower. The tails of 65 rows have one full tile. The - tails of two rows have one row of tables, on a block of sixteen columns, and an entry of 16, the - largest distance. The tables fill contiguous storage, and every other byte of storage backward, - whose bytes between them stay unchanged. + The fill transposes the tables of 64 rows at once, four words of each at a time. Each random + case draws its rows, columns, and block width from counts that straddle the tiles of 64 rows of + tables and the words of 64 columns. The cases include a full last tile, a later partial tile of + several rows, more than 256 rows, and later tiles of blocks past the first word or of more than + four words. The tails of two rows of sixteen ones have an entry of 16, the largest distance. + The tables fill contiguous storage, or every other byte of storage backward, whose bytes between + them stay unchanged. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + tiled, columns = [66, 67, 127, 128, 129, 130], [1, 7, 63, 64, 65, 70] + choices = [ + ([65, 129], [1, 2, 8], columns), + ([67, 127, 128], [1, 2, 8], columns), + ([258], [1, 2, 8], columns), + (tiled, [1], [65, 70]), + (tiled, [8], columns[1:]), + ] cases = [] - for block_bits in [2, 8]: - tails = get_random_tails(rng, 258, block_bits + int(rng.integers(1, block_bits + 1))) + for row_counts, widths, column_counts in choices: + while True: + num_rows, block_bits, num_columns = ( + int(rng.choice(counts)) for counts in (row_counts, widths, column_counts) + ) + # Redraw tails whose tables take too long to build and check as plain Python. + num_blocks = -(-num_columns // block_bits) + if num_rows * num_blocks * (num_rows + 2**block_bits) <= 2**19: + break + tails = (rng.random((num_rows, num_columns)) < rng.uniform(0.01, 0.2)).astype(np.uint8) # A one in the last column keeps the last block as wide as the columns make it. - tails[rng.integers(258), -1] = 1 + tails[rng.integers(num_rows), -1] = 1 cases.append((tails, block_bits)) - cases.append((get_random_tails(rng, 65, 1), 1)) # The only sum of two equal rows of ones is zero, at distance 16 from the value with all ones. cases.append((np.ones((2, 16), dtype=np.uint8), 16)) - for tails, block_bits in cases: + steps = rng.permutation(np.resize([1, -2], len(cases))) + for (tails, block_bits), step in zip(cases, steps, strict=True): num_rows, num_columns = tails.shape minima = [ get_block_minima(tails, start, block_bits) for start in range(0, num_columns, block_bits) ] sizes = [block_minima.shape[1] for block_minima in minima] - num_bytes = (num_rows - 1) * sum(sizes) - # Every value of blocks of up to four values, and otherwise a few, including all ones. + # Fill storage of a value that no entry takes, so that every entry left unwritten and every + # byte written between entries shows. + storage = np.full(abs(step) * (num_rows - 1) * sum(sizes), 255, dtype=np.uint8) + out = storage[::step] + tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) + gaps = np.ones(len(storage), dtype=bool) + gaps[np.arange(len(storage))[::step]] = False + assert np.all(storage[gaps] == 255) + entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) + for block_entries, block_minima in zip(entries, minima, strict=True): + np.testing.assert_array_equal(block_entries.T, block_minima) + + # Bound, from every row, prefixes that take the same value on every block: every value of + # blocks of up to four values, and otherwise a few, including the one with all ones. values = {(1 << block_bits) - 1, *rng.permutation(1 << block_bits)[:4].tolist()} - for step in [1, -2]: - # Fill storage of a value that no entry takes, so that every entry left unwritten and - # every byte written between entries shows. - storage = np.full(abs(step) * num_bytes, 255, dtype=np.uint8) - out = storage[::step] - tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) - gaps = np.ones(len(storage), dtype=bool) - gaps[np.arange(len(storage))[::step]] = False - assert np.all(storage[gaps] == 255) - entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) - for block_entries, block_minima in zip(entries, minima, strict=True): - np.testing.assert_array_equal(block_entries.T, block_minima) - - # Bound, from every row, prefixes that take the same value on every block. - for value in values: - prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 - packed = pack_bits(prefix[None].astype(np.uint8))[0] - for first in range(num_rows - 1): - bound = cb.get_completion_bound( - tables.tables, tables.offsets, block_bits, first, packed, 10**9 - ) - assert bound == sum(m[first, value % m.shape[1]] for m in minima) + for value in values: + prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 + packed = pack_bits(prefix[None].astype(np.uint8))[0] + for first in range(num_rows - 1): + bound = cb.get_completion_bound( + tables.tables, tables.offsets, block_bits, first, packed, 10**9 + ) + assert bound == sum(m[first, value % m.shape[1]] for m in minima) + + +def test_byte_shifts_take_each_byte_of_a_word_on_either_byte_order( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """On a machine of either byte order, the byte shifts take each byte of a word to its lowest. + + The fill reads its tiles a word at a time, so its shifts depend on the byte order. A copy of + the module, imported as if on a machine of each order, gives the shifts of that order. + """ + memory = bytes(range(1, 9)) + byteorders: list[Literal["little", "big"]] = ["little", "big"] + for byteorder in byteorders: + monkeypatch.setattr(sys, "byteorder", byteorder) + name = f"{cb.__name__}_on_{byteorder}_endian" + spec = importlib.util.spec_from_file_location(name, cb.__file__) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + spec.loader.exec_module(module) + word = int.from_bytes(memory, byteorder) + shifts = [module._FIRST_BYTE_SHIFT + module._BYTE_SHIFT_STEP * i for i in range(8)] + assert bytes(word >> shift & 255 for shift in shifts) == memory def test_tables_without_blocks_bound_nothing() -> None: From ab5233aa947632447ea643d094ef6e8d453ea0c2 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 05:55:58 -0500 Subject: [PATCH 8/9] Check completion tables of wide blocks, both byte orders, and strides Add later tiles of blocks of sixteen columns, whose tile rows hold more than 64 words, to the random cases whose every entry and bound are checked. Fill tables as plain Python from copies of the module imported as if on machines of either byte order, with words that view memory in that order, and check their entries and bounds, instead of checking only the byte shifts. Fill every other byte of storage forward through the build, and check the bytes between entries and the bounds from every row. Check also the bounds of two equal rows of 260 ones, which pass the largest byte, with the contract of early stops at every limit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 98 +++++++++++++++---- 1 file changed, 80 insertions(+), 18 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 17b665c03..4983d892c 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -9,6 +9,7 @@ import itertools import math import sys +import types from typing import Any, Literal import numpy as np @@ -92,14 +93,31 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None: assert bound == get_bound_oracle(tails, prefix, first, bits) <= minimum bounds[bits] = bound - for limit in range(bound + 2): - stopped = get_bound(tables.tables, tables.offsets, bits, first, packed, limit) - assert (stopped >= limit) == (bound >= limit) - assert min(int(bound), limit) <= stopped <= bound + check_early_stops(tables, first, packed, int(bound)) assert all( bounds[narrow] <= bounds[wide] for narrow, wide in itertools.pairwise(widths) ) + # Bounds past the largest byte, from two equal rows of ones and the prefix of ones. + tails = np.ones((2, 260), dtype=np.uint8) + tables = cb.CompletionTables.build(pack_bits(tails), 8) + packed = pack_bits(tails[:1])[0] + bound = get_bound(tables.tables, tables.offsets, 8, 0, packed, 10**9) + assert bound == get_bound_oracle(tails, tails[0], 0, 8) == 260 + check_early_stops(tables, 0, packed, int(bound)) + + +def check_early_stops( + tables: cb.CompletionTables, first: int, prefix: npt.NDArray[np.uint64], bound: int +) -> None: + """Bounds stopped at each limit up to past ``bound`` stop as their contract says.""" + for limit in range(bound + 2): + stopped = cb.get_completion_bound( + tables.tables, tables.offsets, tables.block_bits, first, prefix, limit + ) + assert (stopped >= limit) == (bound >= limit) + assert min(bound, limit) <= stopped <= bound + def get_value(bits: npt.NDArray[np.uint8]) -> int: """The value of a block of columns, with its first column in the lowest bit.""" @@ -135,10 +153,10 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C The fill transposes the tables of 64 rows at once, four words of each at a time. Each random case draws its rows, columns, and block width from counts that straddle the tiles of 64 rows of tables and the words of 64 columns. The cases include a full last tile, a later partial tile of - several rows, more than 256 rows, and later tiles of blocks past the first word or of more than - four words. The tails of two rows of sixteen ones have an entry of 16, the largest distance. - The tables fill contiguous storage, or every other byte of storage backward, whose bytes between - them stay unchanged. + several rows, more than 256 rows, and later tiles of blocks past the first word, of more than + four words, or of more than 64 words. The tails of two rows of sixteen ones have an entry of + 16, the largest distance. The tables fill contiguous storage, or every other byte of storage + backward, whose bytes between them stay unchanged. """ rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) tiled, columns = [66, 67, 127, 128, 129, 130], [1, 7, 63, 64, 65, 70] @@ -148,6 +166,7 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C ([258], [1, 2, 8], columns), (tiled, [1], [65, 70]), (tiled, [8], columns[1:]), + (tiled, [16], [10]), ] cases = [] for row_counts, widths, column_counts in choices: @@ -157,7 +176,11 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C ) # Redraw tails whose tables take too long to build and check as plain Python. num_blocks = -(-num_columns // block_bits) - if num_rows * num_blocks * (num_rows + 2**block_bits) <= 2**19: + num_values = sum( + 2 ** min(block_bits, num_columns - start) + for start in range(0, num_columns, block_bits) + ) + if num_rows * (num_blocks * num_rows + num_values) <= 2**19: break tails = (rng.random((num_rows, num_columns)) < rng.uniform(0.01, 0.2)).astype(np.uint8) # A one in the last column keeps the last block as wide as the columns make it. @@ -199,15 +222,30 @@ def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.C assert bound == sum(m[first, value % m.shape[1]] for m in minima) -def test_byte_shifts_take_each_byte_of_a_word_on_either_byte_order( - monkeypatch: pytest.MonkeyPatch, +class WordsOfByteOrder: + """The type ``np.uint64``, but whose arrays view memory in a given byte order.""" + + def __init__(self, byteorder: Literal["little", "big"]) -> None: + self.dtype = np.dtype("u8") + + def __call__(self, value: Any) -> np.uint64: + return np.uint64(value) + + +def test_tables_fill_alike_on_either_byte_order( + pytestconfig: pytest.Config, monkeypatch: pytest.MonkeyPatch ) -> None: - """On a machine of either byte order, the byte shifts take each byte of a word to its lowest. + """Tables filled as on a machine of either byte order match their definition. - The fill reads its tiles a word at a time, so its shifts depend on the byte order. A copy of - the module, imported as if on a machine of each order, gives the shifts of that order. + The fill reads its tiles a word at a time, so the bytes that it takes from a word depend on the + byte order. A copy of the module, imported as if on a machine of each order, fills tables as + plain Python, with words that view memory in that order. """ - memory = bytes(range(1, 9)) + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) + tails = (rng.random((6, 13)) < 0.3).astype(np.uint8) + tails[rng.integers(6), -1] = 1 + minima = [get_block_minima(tails, start, 4) for start in range(0, 13, 4)] + sizes = [block_minima.shape[1] for block_minima in minima] byteorders: list[Literal["little", "big"]] = ["little", "big"] for byteorder in byteorders: monkeypatch.setattr(sys, "byteorder", byteorder) @@ -217,9 +255,21 @@ def test_byte_shifts_take_each_byte_of_a_word_on_either_byte_order( module = importlib.util.module_from_spec(spec) monkeypatch.setitem(sys.modules, name, module) spec.loader.exec_module(module) - word = int.from_bytes(memory, byteorder) - shifts = [module._FIRST_BYTE_SHIFT + module._BYTE_SHIFT_STEP * i for i in range(8)] - assert bytes(word >> shift & 255 for shift in shifts) == memory + numpy = types.SimpleNamespace(**vars(np)) + numpy.uint64 = WordsOfByteOrder(byteorder) + monkeypatch.setattr(module, "np", numpy) + for function in ["_fill_tables", "_get_block_value"]: + compiled = getattr(module, function) + monkeypatch.setattr(module, function, getattr(compiled, "py_func", compiled)) + + tables = module.CompletionTables.build(pack_bits(tails), 4) + entries = np.split(tables.tables.reshape(-1, 5), np.cumsum(sizes)[:-1]) + for block_entries, block_minima in zip(entries, minima, strict=True): + np.testing.assert_array_equal(block_entries.T, block_minima) + for first, value in itertools.product(range(5), range(16)): + prefix = pack_bits(((value >> (np.arange(13) % 4)) & 1)[None].astype(np.uint8))[0] + bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, first, prefix, 10**9) + assert bound == sum(m[first, value % m.shape[1]] for m in minima) def test_tables_without_blocks_bound_nothing() -> None: @@ -269,6 +319,18 @@ def test_tables_within_a_limit_fit_only_if_they_skip_something_and_build_in_plac cb.CompletionTables.build(rows, 8, out=array[1:-1]) np.testing.assert_array_equal(array[1:-1], tables.tables) assert array[0] == array[-1] == 255 + + # Every other byte of storage, whose bytes between those of the tables stay unchanged. + tails = np.array([[1], [1], [0]], dtype=np.uint8) + minima = get_block_minima(tails, 0, 1) + storage = np.full(8, 255, dtype=np.uint8) + tables = cb.CompletionTables.build(pack_bits(tails), 1, out=storage[::2]) + np.testing.assert_array_equal(storage[::2].reshape(2, 2).T, minima) + assert np.all(storage[1::2] == 255) + for first, value in itertools.product(range(2), range(2)): + prefix = np.array([value], dtype=np.uint64) + bound = cb.get_completion_bound(tables.tables, tables.offsets, 1, first, prefix, 10**9) + assert bound == minima[first, value] for size in (num_bytes - 1, num_bytes + 1): with pytest.raises(AssertionError): cb.CompletionTables.build(rows, 8, out=np.empty(size, dtype=np.uint8)) From 2da499f85d472378b67abe64b2534d56dd102574 Mon Sep 17 00:00:00 2001 From: "Michael A. Perlin" Date: Thu, 26 Nov 2026 11:00:05 -0500 Subject: [PATCH 9/9] Trim the completion-table tests to the layout this change introduces Check one fixed case of a full and a partial tile of 64 rows, natively and as on a big-endian machine, and drop the cases that the existing tests already guard or that test behavior this change leaves unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../completion_bounds_test.py | 187 ++++-------------- 1 file changed, 37 insertions(+), 150 deletions(-) diff --git a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py index 4983d892c..812a0658d 100644 --- a/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py +++ b/src/qldpc/codes/distance/_information_sets/completion_bounds_test.py @@ -10,7 +10,7 @@ import math import sys import types -from typing import Any, Literal +from typing import Any import numpy as np import numpy.typing as npt @@ -93,36 +93,13 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None: assert bound == get_bound_oracle(tails, prefix, first, bits) <= minimum bounds[bits] = bound - check_early_stops(tables, first, packed, int(bound)) + for limit in range(bound + 2): + stopped = get_bound(tables.tables, tables.offsets, bits, first, packed, limit) + assert (stopped >= limit) == (bound >= limit) assert all( bounds[narrow] <= bounds[wide] for narrow, wide in itertools.pairwise(widths) ) - # Bounds past the largest byte, from two equal rows of ones and the prefix of ones. - tails = np.ones((2, 260), dtype=np.uint8) - tables = cb.CompletionTables.build(pack_bits(tails), 8) - packed = pack_bits(tails[:1])[0] - bound = get_bound(tables.tables, tables.offsets, 8, 0, packed, 10**9) - assert bound == get_bound_oracle(tails, tails[0], 0, 8) == 260 - check_early_stops(tables, 0, packed, int(bound)) - - -def check_early_stops( - tables: cb.CompletionTables, first: int, prefix: npt.NDArray[np.uint64], bound: int -) -> None: - """Bounds stopped at each limit up to past ``bound`` stop as their contract says.""" - for limit in range(bound + 2): - stopped = cb.get_completion_bound( - tables.tables, tables.offsets, tables.block_bits, first, prefix, limit - ) - assert (stopped >= limit) == (bound >= limit) - assert min(bound, limit) <= stopped <= bound - - -def get_value(bits: npt.NDArray[np.uint8]) -> int: - """The value of a block of columns, with its first column in the lowest bit.""" - return int(bits.astype(np.int64) @ (1 << np.arange(len(bits)))) - def get_block_minima( tails: npt.NDArray[np.uint8], start: int, block_bits: int @@ -133,7 +110,8 @@ def get_block_minima( is the least weight on the block of ``x`` plus two rows from row ``s`` on. """ block = tails[:, start : start + block_bits] - values = np.array([get_value(row) for row in block]) + # The value of each row on the block, with its first column in the lowest bit. + values = block.astype(np.int64) @ (1 << np.arange(block.shape[1])) points = np.arange(1 << block.shape[1]) weights = np.array([point.bit_count() for point in range(len(points))]) num_rows = len(tails) @@ -147,129 +125,49 @@ def get_block_minima( return minima -def test_every_entry_of_the_tables_matches_its_definition(pytestconfig: pytest.Config) -> None: - """Every entry of the tables of tails, and the bounds that they give, match their definitions. +class BigEndianWords: + """The type ``np.uint64``, but whose arrays view memory in big-endian byte order.""" - The fill transposes the tables of 64 rows at once, four words of each at a time. Each random - case draws its rows, columns, and block width from counts that straddle the tiles of 64 rows of - tables and the words of 64 columns. The cases include a full last tile, a later partial tile of - several rows, more than 256 rows, and later tiles of blocks past the first word, of more than - four words, or of more than 64 words. The tails of two rows of sixteen ones have an entry of - 16, the largest distance. The tables fill contiguous storage, or every other byte of storage - backward, whose bytes between them stay unchanged. - """ - rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - tiled, columns = [66, 67, 127, 128, 129, 130], [1, 7, 63, 64, 65, 70] - choices = [ - ([65, 129], [1, 2, 8], columns), - ([67, 127, 128], [1, 2, 8], columns), - ([258], [1, 2, 8], columns), - (tiled, [1], [65, 70]), - (tiled, [8], columns[1:]), - (tiled, [16], [10]), - ] - cases = [] - for row_counts, widths, column_counts in choices: - while True: - num_rows, block_bits, num_columns = ( - int(rng.choice(counts)) for counts in (row_counts, widths, column_counts) - ) - # Redraw tails whose tables take too long to build and check as plain Python. - num_blocks = -(-num_columns // block_bits) - num_values = sum( - 2 ** min(block_bits, num_columns - start) - for start in range(0, num_columns, block_bits) - ) - if num_rows * (num_blocks * num_rows + num_values) <= 2**19: - break - tails = (rng.random((num_rows, num_columns)) < rng.uniform(0.01, 0.2)).astype(np.uint8) - # A one in the last column keeps the last block as wide as the columns make it. - tails[rng.integers(num_rows), -1] = 1 - cases.append((tails, block_bits)) - # The only sum of two equal rows of ones is zero, at distance 16 from the value with all ones. - cases.append((np.ones((2, 16), dtype=np.uint8), 16)) - - steps = rng.permutation(np.resize([1, -2], len(cases))) - for (tails, block_bits), step in zip(cases, steps, strict=True): - num_rows, num_columns = tails.shape - minima = [ - get_block_minima(tails, start, block_bits) - for start in range(0, num_columns, block_bits) - ] - sizes = [block_minima.shape[1] for block_minima in minima] - # Fill storage of a value that no entry takes, so that every entry left unwritten and every - # byte written between entries shows. - storage = np.full(abs(step) * (num_rows - 1) * sum(sizes), 255, dtype=np.uint8) - out = storage[::step] - tables = cb.CompletionTables.build(pack_bits(tails), block_bits, out=out) - gaps = np.ones(len(storage), dtype=bool) - gaps[np.arange(len(storage))[::step]] = False - assert np.all(storage[gaps] == 255) - entries = np.split(out.reshape(-1, num_rows - 1), np.cumsum(sizes)[:-1]) - for block_entries, block_minima in zip(entries, minima, strict=True): - np.testing.assert_array_equal(block_entries.T, block_minima) - - # Bound, from every row, prefixes that take the same value on every block: every value of - # blocks of up to four values, and otherwise a few, including the one with all ones. - values = {(1 << block_bits) - 1, *rng.permutation(1 << block_bits)[:4].tolist()} - for value in values: - prefix = (value >> (np.arange(num_columns) % block_bits)) & 1 - packed = pack_bits(prefix[None].astype(np.uint8))[0] - for first in range(num_rows - 1): - bound = cb.get_completion_bound( - tables.tables, tables.offsets, block_bits, first, packed, 10**9 - ) - assert bound == sum(m[first, value % m.shape[1]] for m in minima) - - -class WordsOfByteOrder: - """The type ``np.uint64``, but whose arrays view memory in a given byte order.""" - - def __init__(self, byteorder: Literal["little", "big"]) -> None: - self.dtype = np.dtype("u8") + dtype = np.dtype(">u8") def __call__(self, value: Any) -> np.uint64: return np.uint64(value) -def test_tables_fill_alike_on_either_byte_order( +def test_tables_of_two_tiles_match_their_definition_in_either_byte_order( pytestconfig: pytest.Config, monkeypatch: pytest.MonkeyPatch ) -> None: - """Tables filled as on a machine of either byte order match their definition. + """Every entry of tables that fill a full tile of 64 rows and then a partial one is correct. - The fill reads its tiles a word at a time, so the bytes that it takes from a word depend on the - byte order. A copy of the module, imported as if on a machine of each order, fills tables as - plain Python, with words that view memory in that order. + The tables have eight blocks of 32 words and a last block narrower than a word, and fill storage + of a value that no entry takes. The bytes that the fill takes from each word of a tile depend + on the byte order, so a copy of the module, imported as if on a big-endian machine, also fills + them as plain Python, with words that view memory in that order. """ + monkeypatch.setattr(sys, "byteorder", "big") + name = f"{cb.__name__}_on_big_endian" + spec = importlib.util.spec_from_file_location(name, cb.__file__) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + spec.loader.exec_module(module) + numpy = types.SimpleNamespace(**vars(np)) + numpy.uint64 = BigEndianWords() + monkeypatch.setattr(module, "np", numpy) + for function in ["_fill_tables", "_get_block_value"]: + compiled = getattr(module, function) + monkeypatch.setattr(module, function, getattr(compiled, "py_func", compiled)) + rng = np.random.default_rng(pytestconfig.getoption("randomly_seed")) - tails = (rng.random((6, 13)) < 0.3).astype(np.uint8) - tails[rng.integers(6), -1] = 1 - minima = [get_block_minima(tails, start, 4) for start in range(0, 13, 4)] - sizes = [block_minima.shape[1] for block_minima in minima] - byteorders: list[Literal["little", "big"]] = ["little", "big"] - for byteorder in byteorders: - monkeypatch.setattr(sys, "byteorder", byteorder) - name = f"{cb.__name__}_on_{byteorder}_endian" - spec = importlib.util.spec_from_file_location(name, cb.__file__) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - monkeypatch.setitem(sys.modules, name, module) - spec.loader.exec_module(module) - numpy = types.SimpleNamespace(**vars(np)) - numpy.uint64 = WordsOfByteOrder(byteorder) - monkeypatch.setattr(module, "np", numpy) - for function in ["_fill_tables", "_get_block_value"]: - compiled = getattr(module, function) - monkeypatch.setattr(module, function, getattr(compiled, "py_func", compiled)) - - tables = module.CompletionTables.build(pack_bits(tails), 4) - entries = np.split(tables.tables.reshape(-1, 5), np.cumsum(sizes)[:-1]) - for block_entries, block_minima in zip(entries, minima, strict=True): + tails = (rng.random((67, 66)) < 0.1).astype(np.uint8) + tails[rng.integers(67), -1] = 1 + minima = [get_block_minima(tails, start, 8) for start in range(0, 66, 8)] + for build in [cb.CompletionTables.build, module.CompletionTables.build]: + out = np.full(66 * (8 * 2**8 + 2**2), 255, dtype=np.uint8) + build(pack_bits(tails), 8, out=out) + blocks = np.split(out.reshape(-1, 66), range(2**8, 8 * 2**8 + 1, 2**8)) + for block_entries, block_minima in zip(blocks, minima, strict=True): np.testing.assert_array_equal(block_entries.T, block_minima) - for first, value in itertools.product(range(5), range(16)): - prefix = pack_bits(((value >> (np.arange(13) % 4)) & 1)[None].astype(np.uint8))[0] - bound = cb.get_completion_bound(tables.tables, tables.offsets, 4, first, prefix, 10**9) - assert bound == sum(m[first, value % m.shape[1]] for m in minima) def test_tables_without_blocks_bound_nothing() -> None: @@ -320,17 +218,6 @@ def test_tables_within_a_limit_fit_only_if_they_skip_something_and_build_in_plac np.testing.assert_array_equal(array[1:-1], tables.tables) assert array[0] == array[-1] == 255 - # Every other byte of storage, whose bytes between those of the tables stay unchanged. - tails = np.array([[1], [1], [0]], dtype=np.uint8) - minima = get_block_minima(tails, 0, 1) - storage = np.full(8, 255, dtype=np.uint8) - tables = cb.CompletionTables.build(pack_bits(tails), 1, out=storage[::2]) - np.testing.assert_array_equal(storage[::2].reshape(2, 2).T, minima) - assert np.all(storage[1::2] == 255) - for first, value in itertools.product(range(2), range(2)): - prefix = np.array([value], dtype=np.uint64) - bound = cb.get_completion_bound(tables.tables, tables.offsets, 1, first, prefix, 10**9) - assert bound == minima[first, value] for size in (num_bytes - 1, num_bytes + 1): with pytest.raises(AssertionError): cb.CompletionTables.build(rows, 8, out=np.empty(size, dtype=np.uint8))