benchmarks/bb144/bb144.py
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1#!/usr/bin/env python3
2"""Build the pinned [[144,12,12]] Z-check decoding problem and samples."""
3
4from __future__ import annotations
5
6import argparse
7import json
8import math
9from pathlib import Path
10
11import numpy as np
12import stim
13from bposd.css import css_code
14
15
16HERE = Path(__file__).resolve().parent
17UPSTREAM_URL = "https://github.com/sbravyi/BivariateBicycleCodes"
18UPSTREAM_COMMIT = "fa77e3333d3ec44c79d8f914dd24c040d1da471b"
19DEFAULT_P = (0.005,)
20PRIOR_BITS, PRIOR_SCALE = 4, 2
21CONTROL_MAX = 7
22LOGICAL_COUNT = 12
23
24
25def save(path: Path, value) -> None:
26 path.parent.mkdir(parents=True, exist_ok=True)
27 path.write_text(json.dumps(value, indent=2) + "\n")
28
29
30def upstream_config() -> dict:
31 """Return the circuit parameters pinned to UPSTREAM_COMMIT."""
32 return {"ell": 12, "m": 6, "a1": 3, "a2": 1, "a3": 2,
33 "b1": 3, "b2": 1, "b3": 2, "num_cycles": 12,
34 "sX": ["idle", 1, 4, 3, 5, 0, 2],
35 "sZ": [3, 5, 0, 1, 2, 4, "idle"],
36 "commit": UPSTREAM_COMMIT}
37
38
39def code_data(config: dict):
40 ell, m = config["ell"], config["m"]
41 eye_l, eye_m = np.eye(ell, dtype=np.uint8), np.eye(m, dtype=np.uint8)
42 x = [np.kron(np.roll(eye_l, i, axis=1), eye_m) for i in range(ell)]
43 y = [np.kron(eye_l, np.roll(eye_m, i, axis=1)) for i in range(m)]
44 a_parts = [x[config["a1"]], y[config["a2"]], y[config["a3"]]]
45 b_parts = [y[config["b1"]], x[config["b2"]], x[config["b3"]]]
46 a, b = np.bitwise_xor.reduce(a_parts), np.bitwise_xor.reduce(b_parts)
47 hx, hz = np.hstack((a, b)), np.hstack((b.T, a.T))
48 code = css_code(hx, hz)
49 lx = code.lx.toarray().astype(np.uint8)
50 lz = code.lz.toarray().astype(np.uint8)
51 if hx.shape != (72, 144) or hz.shape != (72, 144) or lx.shape != (12, 144):
52 raise ValueError("unexpected upstream code dimensions")
53 if np.any((hx @ hz.T) & 1) or np.any((lx @ hz.T) & 1) or np.any((lz @ hx.T) & 1):
54 raise ValueError("invalid CSS or logical matrices")
55 return a_parts, b_parts, lx, lz
56
57
58def neighbors(parts, offset: int, transpose: bool = False) -> list[list[int]]:
59 return [[offset + int(np.flatnonzero(part[:, i] if transpose else part[i])[0])
60 for part in parts] for i in range(72)]
61
62
63def circuit(config: dict, p: float, sector: str) -> stim.Circuit:
64 a_parts, b_parts, lx, lz = code_data(config)
65 xchecks, left, right, zchecks = range(72), range(72, 144), range(144, 216), range(216, 288)
66 data = list(left) + list(right)
67 nx = [a + b for a, b in zip(neighbors(a_parts, 72), neighbors(b_parts, 144))]
68 nz = [a + b for a, b in zip(neighbors(b_parts, 72, True), neighbors(a_parts, 144, True))]
69 c = stim.Circuit()
70 c.append("R" if sector == "x" else "RX", data)
71
72 def pairs(checks, table, direction, reverse=False):
73 return [q for i, check in enumerate(checks)
74 for q in ((table[i][direction], check) if reverse else (check, table[i][direction]))]
75
76 def gate(name, targets, probability, noise=None):
77 c.append(name, targets)
78 if probability and noise:
79 c.append(noise, targets, probability)
80
81 def measure(name, targets, probability, round_index, relevant):
82 c.append(name, targets, probability) if probability else c.append(name, targets)
83 if relevant:
84 for i in range(72):
85 records = [stim.target_rec(i - 72)]
86 if round_index:
87 records.append(stim.target_rec(i - 216))
88 c.append("DETECTOR", records)
89
90 for round_index in range(config["num_cycles"] + 2):
91 probability = p if round_index < config["num_cycles"] else 0.0
92 gate("RX", xchecks, probability, "Z_ERROR")
93 z0 = pairs(zchecks, nz, config["sZ"][0], True)
94 gate("CX", z0, probability, "DEPOLARIZE2")
95 gate("I", sorted(set(data) - set(z0[::2])), probability, "DEPOLARIZE1")
96 c.append("TICK")
97 for stage in range(1, 6):
98 gate("CX", pairs(xchecks, nx, config["sX"][stage]), probability, "DEPOLARIZE2")
99 gate("CX", pairs(zchecks, nz, config["sZ"][stage], True), probability, "DEPOLARIZE2")
100 c.append("TICK")
101 measure("M", zchecks, probability, round_index, sector == "x")
102 x6 = pairs(xchecks, nx, config["sX"][6])
103 gate("CX", x6, probability, "DEPOLARIZE2")
104 gate("I", sorted(set(data) - set(x6[1::2])), probability, "DEPOLARIZE1")
105 c.append("TICK")
106 gate("I", data, probability, "DEPOLARIZE1")
107 measure("MX", xchecks, probability, round_index, sector == "z")
108 gate("R", zchecks, probability, "X_ERROR")
109 c.append("TICK")
110
111 logical = lz if sector == "x" else lx
112 c.append("M" if sector == "x" else "MX", data)
113 for observable, row in enumerate(logical):
114 c.append("OBSERVABLE_INCLUDE",
115 [stim.target_rec(int(i) - 144) for i in np.flatnonzero(row)], observable)
116 return c
117
118
119def effects(dem: stim.DetectorErrorModel):
120 merged = {}
121 for instruction in dem.flattened():
122 if instruction.type in {"detector", "logical_observable"}:
123 continue
124 if instruction.type != "error":
125 raise ValueError(f"unsupported DEM instruction {instruction.type}")
126 detectors, logicals = [], []
127 for target in instruction.targets_copy():
128 if target.is_relative_detector_id():
129 detectors.append(target.val)
130 elif target.is_logical_observable_id():
131 logicals.append(target.val)
132 elif target.is_separator():
133 raise ValueError("decomposed DEM errors are not supported")
134 key = tuple(detectors), tuple(logicals)
135 probability = float(instruction.args_copy()[0])
136 old = merged.get(key, 0.0)
137 merged[key] = old * (1 - probability) + probability * (1 - old)
138 return merged
139
140
141def z_check_model(config: dict, p: float):
142 """Build the X-error component observed by Z-check measurements."""
143 built = circuit(config, p, "x")
144 model = built.detector_error_model(decompose_errors=False)
145 effective = stim.DetectorErrorModel()
146 keys, probabilities = [], []
147 for key, probability in effects(model).items():
148 detectors, logicals = key
149 targets = ([stim.target_relative_detector_id(i) for i in detectors] +
150 [stim.target_logical_observable_id(i) for i in logicals])
151 effective.append("error", probability, targets)
152 keys.append(key)
153 probabilities.append(probability)
154 return built, effective, keys, probabilities
155
156
157def sample_physical(config: dict, p: float, shots: int, seed: int):
158 """Vectorized Z-check-sector sampling of the circuit-level Pauli model."""
159 a_parts, b_parts, _, lz = code_data(config)
160 xchecks = list(range(72))
161 left, right, zchecks = list(range(72, 144)), list(range(144, 216)), list(range(216, 288))
162 data = left + right
163 nx = [a + b for a, b in zip(neighbors(a_parts, 72), neighbors(b_parts, 144))]
164 nz = [a + b for a, b in zip(neighbors(b_parts, 72, True), neighbors(a_parts, 144, True))]
165 rng = np.random.default_rng(seed)
166 x = np.zeros((shots, 288), dtype=np.bool_)
167 z = np.zeros_like(x)
168 z_check_history = []
169
170 def pair(table, direction, checks, reverse=False):
171 flat = [q for i, check in enumerate(checks)
172 for q in ((table[i][direction], check) if reverse
173 else (check, table[i][direction]))]
174 return flat[::2], flat[1::2]
175
176 def depolarize1(qubits, probability):
177 if not probability:
178 return
179 error = rng.random((shots, len(qubits))) < probability
180 pauli = rng.integers(0, 3, error.shape)
181 x[:, qubits] ^= error & (pauli != 2)
182 z[:, qubits] ^= error & (pauli != 0)
183
184 def cnot(controls, targets, probability):
185 x[:, targets] ^= x[:, controls]
186 z[:, controls] ^= z[:, targets]
187 if not probability:
188 return
189 error = rng.random((shots, len(controls))) < probability
190 pauli = rng.integers(1, 16, error.shape)
191 x[:, controls] ^= error & ((pauli & 1) != 0)
192 z[:, controls] ^= error & ((pauli & 2) != 0)
193 x[:, targets] ^= error & ((pauli & 4) != 0)
194 z[:, targets] ^= error & ((pauli & 8) != 0)
195
196 for round_index in range(config["num_cycles"] + 2):
197 probability = p if round_index < config["num_cycles"] else 0.0
198 x[:, xchecks] = False
199 z[:, xchecks] = rng.random((shots, 72)) < probability
200 controls, targets = pair(nz, config["sZ"][0], zchecks, True)
201 cnot(controls, targets, probability)
202 depolarize1(sorted(set(data) - set(controls)), probability)
203 for stage in range(1, 6):
204 cnot(*pair(nx, config["sX"][stage], xchecks), probability)
205 cnot(*pair(nz, config["sZ"][stage], zchecks, True), probability)
206 measured = x[:, zchecks].copy()
207 if probability:
208 measured ^= rng.random(measured.shape) < probability
209 z_check_history.append(measured)
210 controls, targets = pair(nx, config["sX"][6], xchecks)
211 cnot(controls, targets, probability)
212 depolarize1(sorted(set(data) - set(targets)), probability)
213 depolarize1(data, probability)
214 if probability:
215 # Preserve the full-circuit RNG schedule; this readout is outside the selected sector.
216 _ = rng.random((shots, len(xchecks)))
217 x[:, zchecks] = rng.random((shots, 72)) < probability
218 z[:, zchecks] = False
219
220 def differences(history):
221 values = np.stack(history, axis=1)
222 return np.concatenate((values[:, :1], values[:, 1:] ^ values[:, :-1]), axis=1)
223
224 detectors = differences(z_check_history).reshape(shots, -1)
225 data_x = x[:, data].astype(np.uint8)
226 observables = (data_x @ lz.T) & 1
227 return detectors.astype(np.uint8), observables.astype(np.uint8)
228
229
230def quantize(probabilities):
231 if any(not 0 < p < 0.5 for p in probabilities):
232 raise ValueError("all DEM probabilities must lie in (0, 0.5)")
233 return [min((1 << PRIOR_BITS) - 1,
234 math.floor(PRIOR_SCALE * math.log((1 - p) / p) + 0.5))
235 for p in probabilities]
236
237
238def reduce_degree_one(keys, detector_count: int, logical_count: int):
239 """Solve singleton parity checks exactly; the CNU datapath starts at degree two."""
240 raw_rows = [[] for _ in range(detector_count)]
241 raw_logicals = [[] for _ in range(logical_count)]
242 for column, (detectors, logicals) in enumerate(keys):
243 for detector in detectors:
244 raw_rows[detector].append(column)
245 for logical in logicals:
246 raw_logicals[logical].append(column)
247 fixed = {row[0]: check for check, row in enumerate(raw_rows) if len(row) == 1}
248 if len(fixed) != sum(len(row) == 1 for row in raw_rows):
249 raise ValueError("singleton checks do not fix distinct variables")
250 kept_variables = [column for column in range(len(keys)) if column not in fixed]
251 remap = {column: i for i, column in enumerate(kept_variables)}
252 kept_checks = [check for check, row in enumerate(raw_rows) if len(row) != 1]
253 rows = [[remap[column] for column in raw_rows[check] if column not in fixed]
254 for check in kept_checks]
255 logicals = [[remap[column] for column in row if column not in fixed]
256 for row in raw_logicals]
257 if any(len(row) < 2 for row in rows):
258 raise ValueError("singleton elimination exposed another low-degree check")
259 return raw_rows, raw_logicals, fixed, kept_checks, kept_variables, rows, logicals
260
261
262def reduce_sample(syndrome, observables, raw_rows, raw_logicals, fixed, kept_checks):
263 fixed_value = {column: int(syndrome[check]) for column, check in fixed.items()}
264 reduced_syndrome = [int(syndrome[check]) ^
265 (sum(fixed_value.get(column, 0) for column in raw_rows[check]) & 1)
266 for check in kept_checks]
267 reduced_observables = [int(value) ^
268 (sum(fixed_value.get(column, 0) for column in row) & 1)
269 for value, row in zip(observables, raw_logicals)]
270 return reduced_syndrome, reduced_observables
271
272
273def prepare(output: Path, p_values, shots: int, iterations: int, seed: int) -> None:
274 if shots < 1 or iterations < 1 or any(not 0 < p < 0.02 for p in p_values):
275 raise ValueError("shots and iterations must be positive; require 0 < p < 0.02")
276 config = upstream_config()
277 output.mkdir(parents=True, exist_ok=True)
278 canonical_keys, priors, dems, samples = None, [], [], []
279 for index, p in enumerate(p_values):
280 built, dem, keys, probabilities = z_check_model(config, p)
281 if canonical_keys is None:
282 canonical_keys = keys
283 (output / "z_checks.stim").write_text(str(built) + "\n")
284 elif keys != canonical_keys:
285 raise ValueError("DEM topology changed across the p sweep")
286 priors.append(quantize(probabilities))
287 dems.append(dem)
288 tag = f"p{p:.4f}".replace(".", "_")
289 (output / f"{tag}.dem").write_text(str(dem) + "\n")
290 samples.append(sample_physical(config, p, shots, seed + index))
291
292 if any(dem.num_detectors != dems[0].num_detectors for dem in dems):
293 raise ValueError("DEM detector count changed across the p sweep")
294 reduced = reduce_degree_one(canonical_keys, dems[0].num_detectors, LOGICAL_COUNT)
295 raw_rows, raw_logicals, fixed, kept_checks, kept_variables, rows, logicals = reduced
296 if any(not row for row in rows) or any(not detectors for detectors, _ in canonical_keys):
297 raise ValueError("the static decoder requires nonempty detector rows and columns")
298 priors = [[prior[column] for column in kept_variables] for prior in priors]
299 samples = [[reduce_sample(syndrome, observable, raw_rows, raw_logicals,
300 fixed, kept_checks)
301 for syndrome, observable in zip(detectors, observables)]
302 for detectors, observables in samples]
303 observed = len(rows), len(kept_variables), sum(map(len, rows)), len(logicals)
304 if observed != (936, 8784, 30672, LOGICAL_COUNT):
305 raise ValueError(f"unexpected Z-check problem dimensions {observed}")
306
307 sweep = {
308 "schema": "chipsldpc.bb144.v2",
309 "tools": {"stim": stim.__version__},
310 "upstream": {"url": UPSTREAM_URL,
311 "commit": config["commit"]},
312 "code": {"n": 144, "k": 12, "d": 12, "cycles": config["num_cycles"],
313 "ell": config["ell"], "m": config["m"],
314 "a": [config["a1"], config["a2"], config["a3"]],
315 "b": [config["b1"], config["b2"], config["b3"]]},
316 "decoder": {"iterations": iterations, "quantization_bits": PRIOR_BITS,
317 "prior_scale": PRIOR_SCALE},
318 "sampling": {"p_values": list(p_values), "shots_per_p": shots, "seed": seed,
319 "model": "Z-check sector of one circuit-level Pauli process"},
320 "dem": {"m": len(rows), "n": len(kept_variables), "e": sum(map(len, rows)),
321 "row_ones": rows, "logical_ones": logicals, "priors": priors,
322 "sector": "Z-check detectors (X-error component)",
323 "exact_preprocessing": {
324 "raw_m": dems[0].num_detectors, "raw_n": len(canonical_keys),
325 "fixed_variable_detector": [[column, check]
326 for column, check in fixed.items()]},
327 },
328 }
329 save(output / "sweep.json", sweep)
330
331 with (output / "benchmark.txt").open("w") as stream:
332 stream.write(f"{len(rows)} {len(kept_variables)} {LOGICAL_COUNT} {iterations} 12 "
333 f"{len(p_values)} {PRIOR_BITS} {CONTROL_MAX}\n")
334 for row in logicals:
335 stream.write(" ".join(map(str, (len(row), *row))) + "\n")
336 for p, prior, sample in zip(p_values, priors, samples):
337 stream.write(f"{p:.12g} {shots}\n")
338 stream.write(" ".join(map(str, prior)) + "\n")
339 for syndrome, actual in sample:
340 stream.write(" ".join(map(str, syndrome + actual)) + "\n")
341
342 verify = output / "verify"
343 for p, prior, sample in zip(p_values, priors, samples):
344 tag = f"p{p:.4f}".replace(".", "_")
345 syndrome, observables = sample[0]
346 save(verify / tag / "problem.json", {
347 "schema": 1, "n": len(kept_variables), "row_ones": rows,
348 "prior": prior, "syndrome": syndrome, "iterations": iterations,
349 })
350 save(verify / tag / "actual.json", {"p": p, "observables": observables})
351 print(f"m={len(rows)} n={len(kept_variables)} logicals={LOGICAL_COUNT} "
352 f"shots={shots * len(p_values)}")
353
354
355def main() -> None:
356 parser = argparse.ArgumentParser(description=__doc__)
357 commands = parser.add_subparsers(dest="command", required=True)
358 build = commands.add_parser("prepare")
359 build.add_argument("output", type=Path)
360 build.add_argument("--p", type=float, nargs="+", default=DEFAULT_P)
361 build.add_argument("--shots", type=int, default=1000)
362 build.add_argument("--iterations", type=int, default=30)
363 build.add_argument("--seed", type=int, default=14412)
364 args = parser.parse_args()
365 prepare(args.output, args.p, args.shots, args.iterations, args.seed)
366
367
368if __name__ == "__main__":
369 main()