Repository navigation
Description
Hi, and thanks for PyMatching and for adding correlated matching.
Summary. On Stim's generated rotated surface code memories, with the model decomposed by decompose_errors=True (as in the README and the getting-started notebook), correlated matching decodes some single faults of the d = 3 circuit wrongly and ends up with more logical errors than plain matching. Re-decomposing every error into exactly one X-type part and one Z-type part before building the Matching removes those failures and turns the loss into a gain; at d = 5 it roughly doubles the gain.
Results (script below, uniform circuit-level noise p = 0.001, d rounds, 10^6 shots, same shots for every decoder):
pymatching 2.4.0, stim 1.16.0, p = 0.001
d=3 decompose_errors=True plain 783 / 1000000 correlated 1122 / 1000000 single faults decoded wrongly (of 286): plain 0, correlated 6
d=3 X/Z split plain 766 / 1000000 correlated 666 / 1000000 single faults decoded wrongly (of 286): plain 0, correlated 0
d=5 decompose_errors=True plain 138 / 1000000 correlated 120 / 1000000
d=5 X/Z split plain 130 / 1000000 correlated 90 / 1000000
What goes wrong. In all 6 failing single faults, Stim splits the error into three pieces, two of them halves of the same X-type pair sent to the boundary, for example D5 D16 ^ D9 ^ D12 (D5, D16 are Z-type detectors, D9, D12 X-type), although D9 D12 occurs on its own elsewhere in the model. The reweighting rules derived from those pieces then make boundary edges cheap that no physical Y error makes likely, and the second pass picks a correction through the boundary. On the d = 5 model, Stim splits about 400 errors into several pieces of the same type. Split as D5 D16 ^ D9 D12, every rule pairs the X part with the Z part of a real error.
Suggestion. At least a note in the docs that correlated matching works best when each error is decomposed into one X part and one Z part, and possibly a helper or an option (for instance a detector-to-basis map) to do that split. The note in the code of Hernando de la Fuente et al. (arXiv:2610.26785), whose default is the coordinate-based split from the Tesseract decoder, says the same: it gives lower logical error rates than Stim's decomposer for both plain and correlated matching.
I ran into this while adding correlated decoding to an open-source Union-Find decoder, where the same thing happens: https://github.com/jcedrik/backlog (decompose_by_basis, and more numbers in the README). Happy to help with a docs PR if that is useful.
Reproduction script (stim + pymatching + numpy, about 10 s)
import numpy as np
import pymatching
import stim
def memory(d: int, p: float) -> stim.Circuit:
return stim.Circuit.generated(
"surface_code:rotated_memory_z", distance=d, rounds=d,
after_clifford_depolarization=p, before_round_data_depolarization=p,
before_measure_flip_probability=p, after_reset_flip_probability=p)
def decompose_by_basis(dem: stim.DetectorErrorModel) -> stim.DetectorErrorModel:
"""Split every error into exactly its X-type part and its Z-type part.
Stabilizer type from the detector coordinates of Stim's rotated surface
code; each part keeps the observables it has when it occurs on its own.
"""
dem = dem.flattened()
coords = dem.get_detector_coordinates()
basis = {d: (int(c[0]) // 2 + int(c[1]) // 2) % 2 for d, c in coords.items()}
def symptom(inst):
dets, obs = set(), 0
for t in inst.targets_copy():
if t.is_relative_detector_id():
dets ^= {t.val}
elif t.is_logical_observable_id():
obs ^= 1 << t.val
return tuple(sorted(dets)), obs
errors = [(inst.args_copy(), *symptom(inst)) for inst in dem if inst.type == "error"]
alone = {}
for _, dets, obs in errors:
if len({basis[d] for d in dets}) <= 1:
alone.setdefault(dets, set()).add(obs)
out = stim.DetectorErrorModel()
for inst in dem:
if inst.type != "error":
out.append(inst)
for args, dets, obs in errors:
groups = {}
for d in dets:
groups.setdefault(basis[d], []).append(d)
pieces = [(dets, obs)]
if len(groups) == 2:
a, b = (tuple(g) for g in groups.values())
oa = next(o for o in sorted(alone.get(a, ())) if o ^ obs in alone.get(b, ()))
pieces = [(a, oa), (b, oa ^ obs)]
targets = []
for i, (ds, o) in enumerate(pieces):
if i:
targets.append(stim.target_separator())
targets += [stim.target_relative_detector_id(d) for d in ds]
targets += [stim.target_logical_observable_id(k) for k in range(64) if o >> k & 1]
out.append("error", args, targets)
return out
def single_faults(dem: stim.DetectorErrorModel):
"""Syndrome and logical flip of every error of the model, alone."""
rows, flips = [], []
for inst in dem.flattened():
if inst.type != "error":
continue
row = np.zeros(dem.num_detectors, dtype=bool)
flip = False
for t in inst.targets_copy():
if t.is_relative_detector_id():
row[t.val] ^= True
elif t.is_logical_observable_id():
flip ^= True
rows.append(row)
flips.append(flip)
return np.array(rows), np.array(flips)
p = 1e-3
print(f"pymatching {pymatching.__version__}, stim {stim.__version__}, p = {p}")
for d, shots in ((3, 1_000_000), (5, 1_000_000)):
c = memory(d, p)
stim_dem = c.detector_error_model(decompose_errors=True)
dets, obs = c.compile_detector_sampler(seed=1).sample(shots, separate_observables=True)
for name, dem in (("decompose_errors=True", stim_dem), ("X/Z split", decompose_by_basis(stim_dem))):
m = pymatching.Matching.from_detector_error_model(dem, enable_correlations=True)
line = f"d={d} {name:22s}"
for corr in (False, True):
errors = np.sum(np.any(m.decode_batch(dets, enable_correlations=corr) != obs, axis=1))
line += f" {'correlated' if corr else 'plain':10s} {errors:5d} / {shots}"
if d == 3:
syn, flip = single_faults(dem)
wrong = [int(np.sum(m.decode_batch(syn, enable_correlations=corr)[:, 0] != flip))
for corr in (False, True)]
line += f" single faults decoded wrongly (of {len(flip)}): plain {wrong[0]}, correlated {wrong[1]}"
print(line, flush=True)
Activity
Prepare the first PyPI release
haonanren888 commentedon Nov 19, 2026
Some additional data that may help scope this. On d = 5 the single faults are all fine, as reported above, but effective distance is still not preserved in this example: exhaustively decoding all 1,906,128 pairs of faults (XOR of two DEM error mechanisms) in the d=5 rotated memory-Z circuit, plain matching fails on 0 pairs and correlated matching fails on 1,173.
One failing pair consists of two 2-piece errors,
error(6.66978e-05) D4 D24 ^ D15anderror(6.66978e-05) D5 D24 ^ D30. So it's not only the 3-piece decompositions from the d = 3 case.I also tried the X/Z re-decomposition suggested above: each error is rewritten into exactly one X-type piece and one Z-type piece, with detector type taken from the measured check. It removes the d = 3 single-fault failures (6 → 0 for memory Z, 4 → 0 for memory X). On d = 5 it reduces the double-fault failures but doesn't eliminate them: 1,173 → 206 pairs (memory Z) and 1,208 → 321 (memory X), out of ~1.9M. So part of the distance loss seems to come from the reweighting itself, not only from Stim's choice of decomposition.
Looking at those remaining failures (X/Z-split DEMs, d = 5): in all 206 (Z) and 321 (X) failing pairs the first pass, plain matching, is already correct. The second pass then follows companion edges whose weights were lowered to a median of ~0.25 of the original, with some lowered to 0. I re-implemented the reweighting as conditional probabilities q = min(1/2, p_joint/p_marginal), taking the lowest weight when several rules hit the same edge; this matches PyMatching's correlated predictions on 200/200 sampled shots per basis. With that re-implementation, flooring each reweighted edge at half its original weight leaves 55 (Z) / 74 (X) failing pairs. Of the floor values tested, only 1.0 (no lowering) removes all of these failures. That may be useful input for the regularized-reweighting idea in #188.
The observed ordering in these particular samples reverses at low p. With 2×10^6 shots, at p = 0.001 plain gives 77 failures and correlated gives 68; at p = 3×10^-4, plain gives 1 and correlated gives 5 (too few failures to establish a crossover). On d = 3, the low-p scaling of the correlated decoder is ~linear in p: 610 → 144 → 46 failures per 10^6 shots at p = 10^-3, 3×10^-4, 10^-4, versus 208 → 24 → 2 for plain matching.
(pymatching 2.4.0, stim 1.17.dev1793242987.)
Disclosure: found with AI-assisted exhaustive testing, directed by the account owner, who authorized this comment; the reported counts were independently re-run with AI assistance.