Skip to content
Merged
49 changes: 41 additions & 8 deletions src/qldpc/codes/distance/_information_sets/completion_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from __future__ import annotations

import math
import sys
from dataclasses import dataclass

import numpy as np
Expand All @@ -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

Expand All @@ -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]
Expand Down Expand Up @@ -210,14 +216,17 @@ 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]
# 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)
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
Expand Down Expand Up @@ -354,9 +363,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]
Expand Down Expand Up @@ -392,8 +409,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
from __future__ import annotations

import dataclasses
import importlib.util
import itertools
import math
import sys
import types
from typing import Any

import numpy as np
Expand Down Expand Up @@ -98,6 +101,86 @@ def test_bounds_are_exact_relaxations(pytestconfig: pytest.Config) -> None:
)


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]
# 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)
minima = np.empty((num_rows - 1, len(points)), dtype=np.int64)
# 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


class BigEndianWords:
"""The type ``np.uint64``, but whose arrays view memory in big-endian byte order."""

dtype = np.dtype(">u8")

def __call__(self, value: Any) -> np.uint64:
return np.uint64(value)


def test_tables_of_two_tiles_match_their_definition_in_either_byte_order(
pytestconfig: pytest.Config, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Every entry of tables that fill a full tile of 64 rows and then a partial one is correct.

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((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)


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, tables.block_bits, 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)
Expand Down Expand Up @@ -134,6 +217,7 @@ 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

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))
Expand Down
1 change: 1 addition & 0 deletions src/qldpc/codes/distance/brouwer_zimmermann.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down