Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,4 @@ cython_debug/
marimo/_static/
marimo/_lsp/
__marimo__/
!test/data/**/*.stim
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
The fault distance of d=5 T-state cultivation (3, as found by
[Chan et al.](https://arxiv.org/abs/2609.17706)) takes under a second, and
that of its Z-flagged version (4) takes 5 s.
- **Determined measurements of non-Clifford circuits (experimental).**
`tsim.experimental.count_determined_measurements` and `missing_detectors`
work like Stim's methods of those names for circuits with T gates, either
exactly or from `shots` noiseless samples. `nondeterministic_detectors` lists
the declared detectors and observables that are random without noise, and
`missing_detectors` returns the parities of random detectors that stay
determined first, which repairs a circuit whose S gates became T gates. On
the d=5 cultivation circuits of [Chan et al.](https://arxiv.org/abs/2609.17706),
they find the 4 random detectors of the uncorrected circuit and none in the
corrected ones.

### Changed
- The stabilizer-rank strategies compile components of the same shape once, and
Expand Down
429 changes: 429 additions & 0 deletions src/tsim/determined.py

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions src/tsim/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,17 @@
- `shortest_errors` finds a circuit's fault distance: every smallest set of
faults that flips an observable without flipping a detector, as `LogicalError`s
of `Fault`s.
- `count_determined_measurements`, `missing_detectors` and
`nondeterministic_detectors` find the parities of measurements that every
noiseless shot gives the same value, as Stim's methods of those names do for
Clifford circuits, and the declared detectors that are random.
"""

from tsim.determined import (
count_determined_measurements as count_determined_measurements,
missing_detectors as missing_detectors,
nondeterministic_detectors as nondeterministic_detectors,
)
from tsim.noise.faults import (
Fault as Fault,
LogicalError as LogicalError,
Expand All @@ -29,5 +38,8 @@
"Fault",
"LogicalError",
"SteaneEncoder",
"count_determined_measurements",
"missing_detectors",
"nondeterministic_detectors",
"shortest_errors",
]
96 changes: 73 additions & 23 deletions src/tsim/statevector/branches.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"""Most measurement branches that one row of f-bits may have."""

IMPOSSIBLE = 1e-12
"""Weight below which a measurement outcome cannot happen."""
"""Probability below which a measurement outcome cannot happen."""

_I_POWERS = (1, 1j, -1, -1j)

Expand Down Expand Up @@ -66,6 +66,9 @@ class Branches:
sign_rows: The component f-bits that each rotation's sign reads.
output_rows: The component f-bits that each output slot reads.
observable: Whether each output slot is an observable.
coin_rows: The output slots that each fair coin flips, for the coins
that ``support`` fixes at 0: dormant measurements that no
rotation reads.

"""

Expand All @@ -88,6 +91,13 @@ def __init__(self, component: StatevectorComponent, num_detectors: int) -> None:
self._outputs = np.asarray(component.output_indices, dtype=np.int64)
self._num_detectors = num_detectors
self.observable = self._outputs >= num_detectors
# NOTE: a dormant measurement leaves the amplitudes alone; if no rotation
# reads it either, it only flips outputs, independently of the rest.
dormant = np.flatnonzero(tape.kind == MEASURE_DORMANT)
unread = ~np.asarray(self._sign_b.any(axis=0))[self._branch[dormant]]
self._coins = np.zeros(len(tape.kind), dtype=bool)
self._coins[dormant[unread]] = True
self.coin_rows = self._out_b[:, self._branch[dormant[unread]]].T

@cached_property
def reference(self) -> np.ndarray:
Expand Down Expand Up @@ -136,39 +146,72 @@ def outcomes(self, f: np.ndarray) -> list[tuple[np.ndarray, np.ndarray]]:
"""
f = np.asarray(f, dtype=np.uint8)
flips = gf2_product(f, self.output_rows) ^ self.reference
rows, weights, deviations = [], [], []
row, weight, outputs = self._collect(f, skip_coins=False)
deviation = outputs ^ flips[row]
bounds = np.searchsorted(row, np.arange(len(f) + 1))
result = []
for r in range(len(f)):
mine = slice(bounds[r], bounds[r + 1])
values, group = np.unique(deviation[mine], axis=0, return_inverse=True)
probability = np.zeros(len(values))
np.add.at(probability, group.ravel(), weight[mine])
result.append((values, probability))
return result

def support(self, f: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Return the output values that each row of f-bits can give.

The walk fixes the coins of ``coin_rows`` at 0: each of them flips the
outputs by its row of ``coin_rows`` with probability 1/2, whatever
else happens.

Args:
f: The component's f-bits, shape ``(rows, len(f_selection))``.

Returns:
The row of ``f`` of each possible outcome, in increasing order,
and its output values, shape ``(outcomes, output slots)``.

Raises:
ValueError: If the walk has more than ``MAX_BRANCHES`` branches
per row.

"""
row, _, outputs = self._collect(np.asarray(f, dtype=np.uint8), skip_coins=True)
return row, outputs

def _collect(
self, f: np.ndarray, *, skip_coins: bool
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return every branch's row, probability and outputs, sorted by row."""
rows, weights, outputs = [], [], []
leaves = 0
for row, weight, outputs in self._leaves(f):
for row, weight, out in self._leaves(f, skip_coins=skip_coins):
rows.append(row)
weights.append(weight)
outputs.append(out)
leaves += len(row)
if leaves > MAX_BRANCHES * len(f):
raise ValueError(
f"the tape has more than {MAX_BRANCHES} measurement branches"
)
rows.append(row)
weights.append(weight)
deviations.append(outputs ^ flips[row])
row = np.concatenate(rows)
weight = np.concatenate(weights)
deviation = np.concatenate(deviations)
order = np.argsort(row, kind="stable")
bounds = np.searchsorted(row[order], np.arange(len(f) + 1))
result = []
for r in range(len(f)):
mine = order[bounds[r] : bounds[r + 1]]
values, group = np.unique(deviation[mine], axis=0, return_inverse=True)
probability = np.zeros(len(values))
np.add.at(probability, group.ravel(), weight[mine])
result.append((values, probability))
return result
return (
row[order],
np.concatenate(weights)[order],
np.concatenate(outputs)[order],
)

def _leaves(
self, f: np.ndarray
self, f: np.ndarray, *, skip_coins: bool = False
) -> Iterator[tuple[np.ndarray, np.ndarray, np.ndarray]]:
"""Yield the branches that reach the end of the tape, in batches.

A batch is the row of ``f`` of each branch, its probability and its
output values.
output values. With ``skip_coins``, the coins of ``coin_rows`` land 0.
"""
skip = self._coins if skip_coins else np.zeros_like(self._coins)
tape = self._tape
sign = np.zeros((len(f), len(tape.kind)), dtype=np.uint8)
sign[:, self._rotations] = gf2_product(f, self.sign_rows)
Expand All @@ -180,7 +223,7 @@ def _leaves(
amps = np.zeros((len(row), self._size), dtype=np.complex128)
amps[:, 0] = 1.0
bits = np.zeros((len(row), self._out_b.shape[1]), dtype=np.uint8)
yield from self._walk(0, amps, row, bits, sign, out)
yield from self._walk(0, amps, row, bits, sign, out, skip)

def _walk(
self,
Expand All @@ -190,16 +233,19 @@ def _walk(
bits: np.ndarray,
sign: np.ndarray,
out: np.ndarray,
skip: np.ndarray,
) -> Iterator[tuple[np.ndarray, np.ndarray, np.ndarray]]:
"""Run the actions from ``start`` on lanes and yield those that finish.

Lane ``i`` has amplitudes ``amps[i]``, whose squared norm is its
probability, belongs to row ``row[i]`` and has branch bits ``bits[i]``.
``sign`` and ``out`` hold the rows' f-bit parts of the action signs and
of the outputs.
of the outputs. The actions of ``skip`` do not run.
"""
tape = self._tape
for a in range(start, len(tape.kind)):
if skip[a]:
continue
x, z = int(tape.x_mask[a]), int(tape.z_mask[a])
# NOTE: the Pauli P = i^|x&z| X^x Z^z takes amplitudes ``amps`` to
# ``amps[:, source] * phase``.
Expand All @@ -213,13 +259,17 @@ def _walk(
)
continue
children = []
weight = _weights(amps)
for outcome in (0, 1):
if tape.kind[a] == MEASURE_DORMANT:
kept, child = np.arange(len(row)), amps * np.sqrt(0.5)
else:
moved = amps[:, source] * phase
projected = (amps - moved if outcome else amps + moved) / 2
kept = np.flatnonzero(_weights(projected) > IMPOSSIBLE)
# NOTE: an outcome is impossible given the lane, whatever
# the lane's own weight.
possible = _weights(projected) > IMPOSSIBLE * weight
kept = np.flatnonzero(possible)
projected = projected[kept]
# NOTE: the planner moved the measured Pauli onto the pivot,
# which ends in |0>, as in ``shared._project_range``.
Expand All @@ -240,7 +290,7 @@ def _walk(
half = len(row) // 2
for part in (slice(0, half), slice(half, None)):
yield from self._walk(
a + 1, amps[part], row[part], bits[part], sign, out
a + 1, amps[part], row[part], bits[part], sign, out, skip
)
return
yield row, _weights(amps), out[row] ^ _bit_parity(bits, self._out_b)
149 changes: 149 additions & 0 deletions src/tsim/utils/gf2_span.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""A growing span of GF(2) vectors, packed into 64-bit words.

``Span`` keeps one basis vector per pivot, the lowest set bit of that vector,
so inserting a vector reduces it by at most one basis vector per pivot, as
``linalg.find_basis`` does with Python integers. Its annihilator, the vectors
orthogonal to the whole span, then has one basis vector per column that is no
pivot: that column plus the pivots before it.
"""

from __future__ import annotations

import numba
import numpy as np


def num_words(width: int) -> int:
"""Return the 64-bit words of a packed vector of ``width`` bits."""
return max(1, -(-width // 64))


def pack(bits: np.ndarray) -> np.ndarray:
"""Return rows of 0/1 entries as rows of little-endian 64-bit words."""
bits = np.asarray(bits, dtype=np.uint8)
rows, width = bits.shape
padded = np.zeros((rows, num_words(width) * 64), dtype=np.uint8)
padded[:, :width] = bits
packed = np.packbits(padded, axis=1, bitorder="little")
return packed.view("<u8").reshape(rows, num_words(width))


def pack_bytes(rows: np.ndarray, width: int) -> np.ndarray:
"""Return little-endian bit-packed bytes, ``width`` bits a row, as 64-bit words."""
padded = np.zeros((len(rows), num_words(width) * 8), dtype=np.uint8)
padded[:, : rows.shape[1]] = rows
return padded.view("<u8").reshape(len(rows), num_words(width))


def unpack(words: np.ndarray, width: int) -> np.ndarray:
"""Return rows of 64-bit words as rows of ``width`` 0/1 entries."""
as_bytes = np.ascontiguousarray(words).view(np.uint8)
return np.unpackbits(as_bytes, axis=1, bitorder="little")[:, :width]


@numba.njit(cache=True)
def _lowest(row: np.ndarray) -> int:
for w in range(len(row)):
word = row[w]
if word:
bit = 0
while not (word >> np.uint64(bit)) & np.uint64(1):
bit += 1
return 64 * w + bit
return -1


@numba.njit(cache=True)
def _has_bit(row: np.ndarray, column: int) -> bool:
return bool((row[column // 64] >> np.uint64(column % 64)) & np.uint64(1))


@numba.njit(cache=True)
def _insert(basis: np.ndarray, has: np.ndarray, rows: np.ndarray) -> np.ndarray:
"""Insert ``rows`` and return, for each, whether it grew the span."""
grew = np.zeros(len(rows), dtype=np.bool_)
v = np.empty(basis.shape[1], dtype=np.uint64)
for i in range(len(rows)):
v[:] = rows[i]
while True:
p = _lowest(v)
if p < 0:
break
if has[p]:
v ^= basis[p]
else:
basis[p] = v
has[p] = True
grew[i] = True
break
return grew


@numba.njit(cache=True)
def _annihilator(basis: np.ndarray, has: np.ndarray) -> np.ndarray:
"""Return, per column j that is no pivot, e_j plus the pivots before it, packed."""
width = len(has)
reduced = basis.copy()
# NOTE: clearing each pivot column from the other basis vectors, from the
# last pivot down, leaves each with its pivot and columns that are none.
for p in range(width - 1, -1, -1):
if has[p]:
for q in range(p):
if has[q] and _has_bit(reduced[q], p):
reduced[q] ^= reduced[p]
slot = np.full(width, -1, dtype=np.int64)
count = 0
for j in range(width):
if not has[j]:
slot[j] = count
count += 1
result = np.zeros((count, basis.shape[1]), dtype=np.uint64)
for j in range(width):
if slot[j] >= 0:
result[slot[j], j // 64] |= np.uint64(1) << np.uint64(j % 64)
for p in range(width):
if has[p]:
for j in range(p + 1, width):
if slot[j] >= 0 and _has_bit(reduced[p], j):
result[slot[j], p // 64] |= np.uint64(1) << np.uint64(p % 64)
return result


class Span:
"""The span of the vectors inserted so far, in ``GF(2)^width``."""

def __init__(self, width: int) -> None:
"""Start with the zero span."""
self.width = width
self._basis = np.zeros((width, num_words(width)), dtype=np.uint64)
self._has = np.zeros(width, dtype=np.bool_)

@property
def rank(self) -> int:
"""Return the dimension of the span."""
return int(self._has.sum())

def basis(self) -> np.ndarray:
"""Return a basis of the span, packed."""
return self._basis[self._has]

def insert(self, words: np.ndarray) -> np.ndarray:
"""Insert packed vectors and return, for each, whether it grew the span."""
return _insert(self._basis, self._has, self._rows(words))

def insert_bits(self, bits: np.ndarray) -> np.ndarray:
"""Insert vectors of 0/1 entries; see ``insert``."""
bits = np.asarray(bits, dtype=np.uint8)
return self.insert(pack(bits[None] if bits.ndim == 1 else bits))

def annihilator(self) -> np.ndarray:
"""Return a basis of the vectors orthogonal to the span, packed.

Row ``i`` is a column ``j`` that is no pivot plus pivots before ``j``,
so the rows end at distinct columns, in increasing order.
"""
return _annihilator(self._basis, self._has)

def _rows(self, words: np.ndarray) -> np.ndarray:
words = np.ascontiguousarray(words, dtype=np.uint64)
return words.reshape(-1, num_words(self.width))
9 changes: 9 additions & 0 deletions test/data/determined/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# A cultivation circuit with T gates

`chan_d5a19_uncorrected_T.stim`, for
`test/integration/test_determined_literature.py`, is a noiseless d=5 magic
state cultivation circuit from Chan, Strikis, Sun, Cai, arXiv:2609.17706,
[timchan0/cliffordea](https://github.com/timchan0/cliffordea)
`sim/stim_files/` at `27385c6` (MIT): an S proxy with S/S_DAG swapped for
T/T_DAG as in `circuit_text.swap_t_and_s_gates`, before the paper's d=5
correction (`sim/d5-correction.md`).
Loading
Loading