Extended stabilizer beyond a statevector

Real quantum hardware errors are typically mostly stochastic Pauli noise with a smaller coherent over-rotation component. Statevectors stop around ~30 qubits, and 2D matrix product states (MPS) need bond dimensions that grow exponentially with code width.

Maestro’s ExtendedStabilizer (with extended_stabilizer_amplitude_tolerance, available in Maestro 0.3.16+) represents the state as a Clifford operator acting on a sparse sum of stabilizer components—letting small coherent errors run on codes far past statevector or MPS limits.

At a glance

  • Guides: Simulation types · Extended stabilizer benchmarks

  • Key APIs: MaestroBackend(simulation_type=ExtendedStabilizer, extended_stabilizer_amplitude_tolerance=...), twirled_circuit()

  • Simulators used: Statevector (exact d=3 reference), ExtendedStabilizer (d=3 and 49-qubit d=5), Stabilizer (Pauli twirl)

  • Run locally: python examples/example_extended_stabilizer.py (~45 s)

Setup: d=3 and d=5 rotated surface codes

We build d=3 (17 qubits) and d=5 (49 qubits) 3-round Z-basis memory circuits under Deltakit’s SI1000Noise(p=0.002).

def build_surface_code(distance: int, rounds: int = ROUNDS, p: float = P) -> stim.Circuit:
    """Build a Deltakit rotated surface code Z-memory circuit with SI1000(p) noise."""
    code = RotatedPlanarCode(width=distance, height=distance)
    circuit = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=PauliBasis.Z)
    qpu = QPU(circuit.qubits, noise_model=SI1000Noise(p=p))
    return to_stim(qpu.compile_and_add_noise_to_circuit(circuit))


Step 1: Checking amplitude tolerance against exact Statevector

Under noise_type="coherent" at p = 0.002, each coherent over-rotation adds a branch of amplitude sin(ε/2) = √p ≈ 0.045. Setting extended_stabilizer_amplitude_tolerance=0.05 exceeds that single-error amplitude and prunes coherent error branches almost completely, sharply undercounting detection events. Tightening the tolerance to 1e-3 and 3e-4 keeps the contributing branches and converges to Maestro’s exact Statevector.

for idx, tol in enumerate(TOLERANCES, start=1):
    ext = MaestroBackend(
        simulation_type=EXTENDED,
        extended_stabilizer_amplitude_tolerance=tol,
    )
    t0 = time.perf_counter()
    sampler = ext.compile_sampler(circuit, noise_type="coherent", decoder=None, seed=SEED + idx)
    dets, obs = sampler.sample_detection_events(SHOTS_D3)
    ms = (time.perf_counter() - t0) / SHOTS_D3 * 1e3
    rate = detection_rate(dets)
    lep = decode_lep(dem, dets, obs)
    z = z_score(rate, sv_rate)
    print(
        f"  {f'Extended, tol={tol:g}':<22} │ "
        f"{rate[0]:.5f} ± {rate[1]:.5f} │ {z:>+7.1f} │ "
        f"{lep[0]:.4f} ± {lep[1]:.4f} │ {ms:>7.2f}"
    )


Output:

  simulator              │         det. rate │ z vs SV │             LEP │ ms/shot

Step 2: Past statevector scale on a 49-qubit d=5 surface code

A 49-qubit statevector would require 8 PiB of RAM. With realistic mixed noise (SI1000(p=0.002) plus noise_type="full", coherent=5e-4, a quarter of the two-qubit gate Pauli error), ExtendedStabilizer samples the d=5 surface code directly. Both runs are decoded with PyMatching using the matched Pauli-twirl DEM (twirl_sampler.task.detector_error_model), and checked at a tighter tolerance (3e-4):

for idx, (tol, shots) in enumerate(((1e-3, SHOTS_D5), (3e-4, SHOTS_D5_CHECK)), start=1):
    ext = MaestroBackend(
        simulation_type=EXTENDED,
        extended_stabilizer_amplitude_tolerance=tol,
    )
    t0 = time.perf_counter()
    sampler = ext.compile_sampler(
        circuit, noise_type="full", coherent=COHERENT, decoder=None, seed=SEED + idx
    )
    assert sampler.task.detector_error_model == dem
    dets, obs = sampler.sample_detection_events(shots)
    ms = (time.perf_counter() - t0) / shots * 1e3
    rate = detection_rate(dets)
    lep = decode_lep(dem, dets, obs)
    ratio = rate[0] / twirl_rate[0]
    print(
        f"  {f'Extended, tol={tol:g}':<24} │ {shots:>7,} │ "
        f"{rate[0]:.5f} ± {rate[1]:.5f} │ {ratio:>7.3f}× │ "
        f"{lep[0]:.4f} ± {lep[1]:.4f} │ {ms:>7.1f}"
    )


Output:

  run                      │   shots │         det. rate │ vs twirl │             LEP │ ms/shot
  ──────────────────────────────────────────────────────────────────────────────────────────
  Pauli twirl (Stabilizer) │ 100,000 │ 0.06145 ± 0.00013 │   1.000× │ 0.0056 ± 0.0002 │   <0.01
  Extended, tol=0.001      │     600 │ 0.06380 ± 0.00168 │   1.038× │ 0.0033 ± 0.0024 │    36.4
  Extended, tol=0.0003     │      80 │ 0.06146 ± 0.00441 │   1.000× │ 0.0125 ± 0.0124 │   364.2

Key takeaways

  • Pruning biases results downward toward the Pauli twirl whenever the tolerance is too loose; validate on a smaller code against Statevector and spot-check at a tighter tolerance on larger codes.

  • ExtendedStabilizer is fastest when the coherent component is smaller than the stochastic Pauli error rate (see Extended stabilizer benchmarks for high-shot studies up to d=7 (97 qubits) and [[72,12,6]] (144 qubits)).

  • Next: Coherent noise on a repetition code switches to Maestro’s MPS simulator for strong coherent errors on 1D chains.


Full script and complete output

View full script (examples/example_extended_stabilizer.py)
"""
Extended Stabilizer — Small Coherent Errors Beyond a Statevector
================================================================

Real hardware noise is usually dominated by stochastic Pauli errors with a
smaller coherent over-rotation component. A statevector stops around ~30 qubits,
and a 2D matrix product state (MPS) needs a bond dimension that grows
exponentially with code width.

Maestro's ``ExtendedStabilizer`` represents the state as a Clifford operator
acting on a sparse sum of stabilizer components: Clifford gates and Pauli errors
add no components, small coherent over-rotations branch new ones, and syndrome
measurements collapse them. Setting ``extended_stabilizer_amplitude_tolerance``
prunes small-amplitude branches, letting coherent noise run on codes far past
statevector or MPS limits (up to d=7 surface codes and 144-qubit qLDPC codes in
the Benchmarks).

Because pruning drops error branches, too loose a tolerance undercounts coherent
errors and biases results toward the Pauli twirl. Always validate the tolerance
on a smaller code or against a tighter tolerance.

Demonstrates:
    1. Validating ``extended_stabilizer_amplitude_tolerance`` against Maestro's
       exact ``Statevector`` on the 17-qubit d=3 rotated surface code.
    2. Simulating Pauli + weak coherent noise (``noise_type='full'``) on the
       49-qubit d=5 rotated surface code—well beyond statevector memory—and
       comparing against its matched Pauli twirl, both decoded with PyMatching.

Usage:
    pip install -e ".[examples]"    # from project root (deltakit-maestro/)
    python examples/example_extended_stabilizer.py
"""

# Deltakit must be imported before pymatching: with pymatching 2.4 loaded
# first, Deltakit's circuit builders fail with "Caught an unknown exception!".
from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise

# isort: split
import time

import maestro
import numpy as np
import pymatching
import stim

from deltakit_maestro import MaestroBackend, to_stim

EXTENDED = maestro.SimulationType.ExtendedStabilizer
STATEVECTOR = maestro.SimulationType.Statevector

# =============================================================================
# EXPERIMENT CONFIGURATION
# =============================================================================

P = 0.002  # SI1000 physical error rate
COHERENT = 5e-4  # Small coherent over-rotation (p / 4) for d=5 mixed noise
ROUNDS = 3
TOLERANCES = [5e-2, 1e-2, 1e-3, 3e-4]
SHOTS_D3 = 1_200
SHOTS_D5 = 600
SHOTS_D5_CHECK = 80
SHOTS_TWIRL = 100_000
SEED = 1


# =============================================================================
# CIRCUIT BUILDER & STATISTICS HELPERS
# =============================================================================


def build_surface_code(distance: int, rounds: int = ROUNDS, p: float = P) -> stim.Circuit:
    """Build a Deltakit rotated surface code Z-memory circuit with SI1000(p) noise."""
    code = RotatedPlanarCode(width=distance, height=distance)
    circuit = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=PauliBasis.Z)
    qpu = QPU(circuit.qubits, noise_model=SI1000Noise(p=p))
    return to_stim(qpu.compile_and_add_noise_to_circuit(circuit))


def detection_rate(dets: np.ndarray) -> tuple[float, float]:
    """Mean detection-event rate and its standard error across shots."""
    per_shot = dets.mean(axis=1)
    return float(per_shot.mean()), float(per_shot.std(ddof=1) / np.sqrt(len(per_shot)))


def decode_lep(
    dem: stim.DetectorErrorModel,
    dets: np.ndarray,
    obs: np.ndarray,
) -> tuple[float, float]:
    """Decode detection events with PyMatching and return (lep, standard_error)."""
    matcher = pymatching.Matching.from_detector_error_model(dem)
    fails = np.any(matcher.decode_batch(dets) != obs, axis=1)
    lep = float(fails.mean())
    err = float(np.sqrt(lep * (1 - lep) / len(fails)))
    return lep, err


def z_score(a: tuple[float, float], b: tuple[float, float]) -> float:
    """Difference in units of combined standard error."""
    se = float(np.hypot(a[1], b[1]))
    return (a[0] - b[0]) / se if se > 0 else 0.0


# =============================================================================
# STEP DEMONSTRATIONS
# =============================================================================


def step_1_validate_tolerance_on_d3(circuit: stim.Circuit):
    """Compare pruned ExtendedStabilizer against exact Statevector on d=3."""
    print(f"\n{'─' * 78}")
    print("  1. Checking amplitude tolerance against exact Statevector (rotated d=3)")
    print(f"{'─' * 78}")
    print(
        f"  Full coherent gate noise (noise_type='coherent', p={P}, sin(ε/2) ≈ {np.sqrt(P):.3f})\n"
        f"  stresses pruning hardest. At tol=0.05 (> sin(ε/2)), even single-error branches\n"
        f"  are pruned; tightening the tolerance converges to exact Statevector ({SHOTS_D3:,} shots).\n"
    )

    sv_backend = MaestroBackend(simulation_type=STATEVECTOR)
    t0 = time.perf_counter()
    sv_sampler = sv_backend.compile_sampler(circuit, noise_type="coherent", decoder=None, seed=SEED)
    sv_dets, sv_obs = sv_sampler.sample_detection_events(SHOTS_D3)
    sv_ms = (time.perf_counter() - t0) / SHOTS_D3 * 1e3

    dem = sv_sampler.task.detector_error_model
    sv_rate = detection_rate(sv_dets)
    sv_lep = decode_lep(dem, sv_dets, sv_obs)

    print(
        f"  {'simulator':<22} │ {'det. rate':>17} │ {'z vs SV':>7} │ {'LEP':>15} │ {'ms/shot':>7}"
    )
    print(f"  {'─' * 76}")
    print(
        f"  {'Statevector (exact)':<22} │ "
        f"{sv_rate[0]:.5f} ± {sv_rate[1]:.5f} │ {'—':>7} │ "
        f"{sv_lep[0]:.4f} ± {sv_lep[1]:.4f} │ {sv_ms:>7.2f}"
    )

    for idx, tol in enumerate(TOLERANCES, start=1):
        ext = MaestroBackend(
            simulation_type=EXTENDED,
            extended_stabilizer_amplitude_tolerance=tol,
        )
        t0 = time.perf_counter()
        sampler = ext.compile_sampler(circuit, noise_type="coherent", decoder=None, seed=SEED + idx)
        dets, obs = sampler.sample_detection_events(SHOTS_D3)
        ms = (time.perf_counter() - t0) / SHOTS_D3 * 1e3
        rate = detection_rate(dets)
        lep = decode_lep(dem, dets, obs)
        z = z_score(rate, sv_rate)
        print(
            f"  {f'Extended, tol={tol:g}':<22} │ "
            f"{rate[0]:.5f} ± {rate[1]:.5f} │ {z:>+7.1f} │ "
            f"{lep[0]:.4f} ± {lep[1]:.4f} │ {ms:>7.2f}"
        )


def step_2_beyond_statevector_on_d5(circuit: stim.Circuit):
    """Run Pauli + weak coherent noise on a 49-qubit d=5 surface code."""
    print(f"\n{'─' * 78}")
    print("  2. Past statevector scale: rotated d=5 surface code (49 qubits)")
    print(f"{'─' * 78}")
    print(
        f"  A 49-qubit statevector needs 8 PiB of RAM. With SI1000(p={P}) plus a small\n"
        f"  coherent over-rotation (coherent={COHERENT:g}, i.e. p/4), ExtendedStabilizer\n"
        f"  samples the code directly and compares against its Pauli twirl, both decoded\n"
        f"  by PyMatching with the twirl's DEM.\n"
    )

    twirl_backend = MaestroBackend()
    twirl_circuit = twirl_backend.twirled_circuit(circuit, noise_type="full", coherent=COHERENT)
    twirl_sampler = twirl_backend.compile_sampler(twirl_circuit, decoder=None, seed=SEED)
    twirl_dets, twirl_obs = twirl_sampler.sample_detection_events(SHOTS_TWIRL)
    dem = twirl_sampler.task.detector_error_model
    twirl_rate = detection_rate(twirl_dets)
    twirl_lep = decode_lep(dem, twirl_dets, twirl_obs)

    print(
        f"  {'run':<24} │ {'shots':>7} │ {'det. rate':>17} │ {'vs twirl':>8} │ {'LEP':>15} │ {'ms/shot':>7}"
    )
    print(f"  {'─' * 90}")
    print(
        f"  {'Pauli twirl (Stabilizer)':<24} │ {SHOTS_TWIRL:>7,} │ "
        f"{twirl_rate[0]:.5f} ± {twirl_rate[1]:.5f} │ {'1.000×':>8} │ "
        f"{twirl_lep[0]:.4f} ± {twirl_lep[1]:.4f} │ {'<0.01':>7}"
    )

    for idx, (tol, shots) in enumerate(((1e-3, SHOTS_D5), (3e-4, SHOTS_D5_CHECK)), start=1):
        ext = MaestroBackend(
            simulation_type=EXTENDED,
            extended_stabilizer_amplitude_tolerance=tol,
        )
        t0 = time.perf_counter()
        sampler = ext.compile_sampler(
            circuit, noise_type="full", coherent=COHERENT, decoder=None, seed=SEED + idx
        )
        assert sampler.task.detector_error_model == dem
        dets, obs = sampler.sample_detection_events(shots)
        ms = (time.perf_counter() - t0) / shots * 1e3
        rate = detection_rate(dets)
        lep = decode_lep(dem, dets, obs)
        ratio = rate[0] / twirl_rate[0]
        print(
            f"  {f'Extended, tol={tol:g}':<24} │ {shots:>7,} │ "
            f"{rate[0]:.5f} ± {rate[1]:.5f} │ {ratio:>7.3f}× │ "
            f"{lep[0]:.4f} ± {lep[1]:.4f} │ {ms:>7.1f}"
        )


# =============================================================================
# MAIN ENTRYPOINT
# =============================================================================


def main():
    d3_circuit = build_surface_code(distance=3, rounds=ROUNDS)
    d5_circuit = build_surface_code(distance=5, rounds=ROUNDS)

    print("=" * 78)
    print("  Extended Stabilizer — small coherent errors beyond a statevector")
    print("=" * 78)
    print(
        f"  d=3 circuit: {d3_circuit.num_qubits} qubits, {ROUNDS} rounds, "
        f"{d3_circuit.num_detectors} detectors"
    )
    print(
        f"  d=5 circuit: {d5_circuit.num_qubits} qubits, {ROUNDS} rounds, "
        f"{d5_circuit.num_detectors} detectors"
    )

    step_1_validate_tolerance_on_d3(d3_circuit)
    step_2_beyond_statevector_on_d5(d5_circuit)

    print(f"\n{'=' * 78}")
    print("  Notes:")
    print("    - Tightening extended_stabilizer_amplitude_tolerance keeps more coherent")
    print("      error branches: always verify convergence at a tighter tolerance.")
    print("    - See the Extended stabilizer benchmark page for high-shot studies up to")
    print("      d=7 (97 qubits) and the [[72,12,6]] bivariate bicycle code (144 qubits).")
    print("=" * 78)


if __name__ == "__main__":
    main()
View complete output
==============================================================================
  Extended Stabilizer — small coherent errors beyond a statevector
==============================================================================
  d=3 circuit: 17 qubits, 3 rounds, 24 detectors
  d=5 circuit: 49 qubits, 3 rounds, 72 detectors

──────────────────────────────────────────────────────────────────────────────
  1. Checking amplitude tolerance against exact Statevector (rotated d=3)
──────────────────────────────────────────────────────────────────────────────
  Full coherent gate noise (noise_type='coherent', p=0.002, sin(ε/2) ≈ 0.045)
  stresses pruning hardest. At tol=0.05 (> sin(ε/2)), even single-error branches
  are pruned; tightening the tolerance converges to exact Statevector (1,200 shots).

  simulator              │         det. rate │ z vs SV │             LEP │ ms/shot
  ────────────────────────────────────────────────────────────────────────────
  Statevector (exact)    │ 0.06972 ± 0.00196 │       — │ 0.0233 ± 0.0044 │    8.05
  Extended, tol=0.05     │ 0.04069 ± 0.00154 │   -11.7 │ 0.0117 ± 0.0031 │    0.33
  Extended, tol=0.01     │ 0.07167 ± 0.00192 │    +0.7 │ 0.0175 ± 0.0038 │    1.47
  Extended, tol=0.001    │ 0.07170 ± 0.00194 │    +0.7 │ 0.0258 ± 0.0046 │    9.68
  Extended, tol=0.0003   │ 0.07410 ± 0.00200 │    +1.6 │ 0.0275 ± 0.0047 │   25.64

──────────────────────────────────────────────────────────────────────────────
  2. Past statevector scale: rotated d=5 surface code (49 qubits)
──────────────────────────────────────────────────────────────────────────────
  A 49-qubit statevector needs 8 PiB of RAM. With SI1000(p=0.002) plus a small
  coherent over-rotation (coherent=0.0005, i.e. p/4), ExtendedStabilizer
  samples the code directly and compares against its Pauli twirl, both decoded
  by PyMatching with the twirl's DEM.

  run                      │   shots │         det. rate │ vs twirl │             LEP │ ms/shot
  ──────────────────────────────────────────────────────────────────────────────────────────
  Pauli twirl (Stabilizer) │ 100,000 │ 0.06145 ± 0.00013 │   1.000× │ 0.0056 ± 0.0002 │   <0.01
  Extended, tol=0.001      │     600 │ 0.06380 ± 0.00168 │   1.038× │ 0.0033 ± 0.0024 │    36.4
  Extended, tol=0.0003     │      80 │ 0.06146 ± 0.00441 │   1.000× │ 0.0125 ± 0.0124 │   364.2

==============================================================================
  Notes:
    - Tightening extended_stabilizer_amplitude_tolerance keeps more coherent
      error branches: always verify convergence at a tighter tolerance.
    - See the Extended stabilizer benchmark page for high-shot studies up to
      d=7 (97 qubits) and the [[72,12,6]] bivariate bicycle code (144 qubits).
==============================================================================