About this notebook

Companion to Lecture 8: Fault-tolerant compilation with deltakit-compile. Every cell below was executed headless with the course’s pinned Deltakit (deltakit 0.10.2, deltakit-stim 0.2.7, pymatching 2.4.0, Python 3.12.12); each output is exactly what the code printed. Download the notebook (.ipynb)

Lecture 8 described deltakit-compile as a stack of intermediate languages (dialects) that a logical program falls through on its way to Stim. Here you run it and look inside.

  1. Count the passes of the default pipeline, stage by stage.
  2. Compile a repetition-code program written gate by gate, and read the Stim it produces.
  3. Lower a distance-3 surface-code patch one pass at a time and watch the dialects change.
  4. Find the patch circuit’s missing observable, prove it is missing, and repair it.
  5. Compare the repaired circuit with the one Deltakit builds by hand (Lecture 0).
  6. Build a lattice-surgery program, and see where version 0.1.0 stops.

Everything here uses version 0.1.0 of deltakit-compile, an early release; Lecture 8 lists what it can and cannot compile.

import collections
import importlib.metadata
import re
 
import deltakit
import deltakit_stim as stim
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import SVG
from matplotlib.colors import LogNorm
from matplotlib_inline.backend_inline import set_matplotlib_formats
 
from deltakit.circuit import Circuit
from deltakit.circuit.gates import PauliBasis
from deltakit.decode import PyMatchingDecoder
from deltakit.decode.analysis import StimDecoderManager
from deltakit.explorer.analysis import calculate_lep_and_lep_stddev
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
from deltakit_compile.frontend.common import CircuitBuilder, QubitReg
from deltakit_compile.frontend.logasm import LogAsmBuilder, RotatedPlanarPatch
from deltakit_compile.frontend.logical_assembler import (
    LogicalAssembler,
    LogicalAssemblerConfig,
    LogicalAssemblerFromApiPipeline,
)
from deltakit_compile.passes.log_asm_api.pipeline import LogAsmApiToLogAsmPipeline
from deltakit_compile.passes.patch_lowering.rotated_surface.pipeline import (
    RotatedSurfacePatchLoweringPipeline,
)
from deltakit_compile.passes.stabiliser.pipeline import StabiliserFlowPipeline
from deltakit_compile.passes.stim.stim_export.pipeline import (
    StimExportPipeline,
    StimExportPipelineConfig,
)
 
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)
print("deltakit-compile", importlib.metadata.version("deltakit-compile"))
deltakit 0.10.2
deltakit-compile 0.1.0

1. The pipeline, stage by stage

LogicalAssembler.compile runs one long list of passes. That list is made of four sub-pipelines, the four stages of Lecture 8, glued together with canonicalize passes (a standard xDSL clean-up that folds constants and deletes unused operations):

  your program  (LogAsmBuilder: log_asm; CircuitBuilder: log_asm_api, tensor, arith)
       |
       |  canonicalize
       v
  stage 1  LogAsmApiToLogAsmPipeline            inline, cse, ... -> qcore/qref/qstruct
                                                 (log_asm patch ops pass through)
       |  canonicalize
       v
  stage 2  RotatedSurfacePatchLoweringPipeline  patches -> plaquettes -> qref gates
       v
  stage 3  StabiliserFlowPipeline               flows -> qec.detector   (+ canonicalize)
       v
  stage 4  StimExportPipeline                   named gates, TICKs -> stim (+ canonicalize)
       |
       v
  Stim text   (CompilationResult.program)

The pipeline object knows its sub-pipelines’ settings, so we can count each stage.

config = LogicalAssemblerConfig(export_config=StimExportPipelineConfig(),
                                verify_between_passes=True)
pipeline = LogicalAssemblerFromApiPipeline.from_configuration(config)
passes = pipeline.get_passes()
stages = {
    "1 logical assembly": LogAsmApiToLogAsmPipeline.from_configuration(
        pipeline.api_to_logasm_config).get_passes(),
    "2 patch lowering": RotatedSurfacePatchLoweringPipeline.from_configuration(
        pipeline.patch_lowering_config).get_passes(),
    "3 stabilizer flows": StabiliserFlowPipeline.from_configuration(
        pipeline.stabiliser_flow_config).get_passes(),
    "4 Stim export": StimExportPipeline.from_configuration(
        pipeline.export_config).get_passes(),
}
for name, stage in stages.items():
    print(f"{name:20s} {len(stage):2d} passes: {', '.join(p.name for p in stage[:4])}, ...")
print(f"total {len(passes)} passes, of which "
      f"{sum(p.name == 'canonicalize' for p in passes)} are canonicalize")
1 logical assembly    7 passes: canonicalize, cse, lockstep-parallels, inline-circuits-and-subroutines, ...
2 patch lowering     12 passes: backpropagate-observables, lower-patch-declaration, place-observables, patch-to-plaquettes, ...
3 stabilizer flows   13 passes: split-gate-like-broadcast-ops, qstruct-circuit-to-stab, canonicalize, lower-concrete-flows, ...
4 Stim export         9 passes: unitaries-to-named-gates, convert-parallels-to-lockstep, merge-gate-like-broadcast-ops, combine-detector-rounds, ...
total 45 passes, of which 9 are canonicalize

2. A program written gate by gate

CircuitBuilder writes small physical circuits on a register of qubits; LogAsmBuilder calls them. This is the three-qubit repetition code from Lecture 8: data on qubits 0, 2, 4, ancillas on 1 and 3, three rounds of and checks, and a readout that declares the observable .

def repetition_program(rounds=3):
    prep = CircuitBuilder()
    q = prep.add_arg(QubitReg(5))
    prep.gate("RZ", q)
    prep = prep.build("prep")
 
    check = CircuitBuilder()
    q = check.add_arg(QubitReg(5))
    check.gate("RZ", (q[1], q[3]))
    for ctrl, targ in ((0, 1), (2, 1), (2, 3), (4, 3)):
        check.gate("CX", (q[ctrl], q[targ]))
    check.add_return(check.measure("Z", (q[1], q[3])))
    check = check.build("zz_round")
 
    readout = CircuitBuilder()
    q = readout.add_arg(QubitReg(5))
    m = readout.measure("Z", (q[0], q[2], q[4]))
    obs = readout.declare_observable()
    obs.include([m[0]])
    readout.add_return(obs.get_corrected())
    readout = readout.build("readout")
 
    builder = LogAsmBuilder()
    reg = builder.declare_patch(QubitReg(5))
    builder.call_circuit(prep(reg))
    for _ in range(rounds):
        builder.call_circuit(check(reg))
    builder.add_return(builder.call_circuit(readout(reg)))
    return builder.build_program()
 
 
SHORT_TYPES = [
    (r"!log_asm\.patch\.rot_planar<size=(\([^)]*\)), location=(\([^)]*\)), orient=\w+>",
     r"patch<\1 at \2>"),
    (r"tensor<(\d+)x!qcore\.qubit>", r"qubits[\1]"),
    (r"tensor<(\d+)xi1>", r"bits[\1]"),
    (r"!qcore\.qubit_reg<(\d+)>", r"reg[\1]"),
]
 
 
def top_level(program):
    """The program's main body, with long type names abbreviated."""
    lines = str(program).splitlines()[1:]
    end = next(i for i, ln in enumerate(lines)
               if "circuit_dec" in ln or ln.startswith("})"))
    text = "\n".join(ln[2:] for ln in lines[:end])
    for pattern, short in SHORT_TYPES:
        text = re.sub(pattern, short, text)
    return text
 
 
rep_program = repetition_program()
print(top_level(rep_program))
%0 = qcore.alloc_qubit -> reg[5]
%qreg = log_asm_api.cast(%0 : reg[5]) -> qubits[5]
%qreg_1 = log_asm_api.call @prep(%qreg) : (qubits[5]) -> qubits[5]
%meas, %qreg_2 = log_asm_api.call @zz_round(%qreg_1) : (qubits[5]) -> (bits[2], qubits[5])
%meas_1, %qreg_3 = log_asm_api.call @zz_round(%qreg_2) : (qubits[5]) -> (bits[2], qubits[5])
%meas_2, %qreg_4 = log_asm_api.call @zz_round(%qreg_3) : (qubits[5]) -> (bits[2], qubits[5])
%cexpr, %qreg_5 = log_asm_api.call @readout(%qreg_4) : (qubits[5]) -> (i1, qubits[5])
qstruct.output(%cexpr : i1)

(Type names are abbreviated: qubits[5] is a tensor of five qubits, bits[2] two measurement results.) Every line defines new values (%qreg_2, %meas_1, …) exactly once, and the qubit register is passed from call to call: the IR spells out that round 2 needs the qubits round 1 left behind. The three circuits themselves are separate circuit_dec blocks further down; stage 1 inlines them. Compile:

assembler = LogicalAssembler(config)
rep_circ = stim.Circuit(assembler.compile(repetition_program()).program)
print(rep_circ)
R 0 1 2 3 4
TICK
R 1 3
TICK
CX 0 1
TICK
CX 2 1
TICK
CX 2 3
TICK
CX 4 3
TICK
M 1 3
TICK
DETECTOR rec[-2]
DETECTOR rec[-1]
R 1 3
TICK
CX 0 1
TICK
CX 2 1
TICK
CX 2 3
TICK
CX 4 3
TICK
M 1 3
TICK
DETECTOR rec[-4] rec[-2]
DETECTOR rec[-3] rec[-1]
R 1 3
TICK
CX 0 1
TICK
CX 2 1
TICK
CX 2 3
TICK
CX 4 3
TICK
M 1 3
TICK
DETECTOR rec[-4] rec[-2]
DETECTOR rec[-3] rec[-1]
M 0 2 4
TICK
OBSERVABLE_INCLUDE(0) rec[-3]
DETECTOR rec[-5] rec[-3] rec[-2]
DETECTOR rec[-4] rec[-1] rec[-2]
DETECTOR rec[-1]

Compare the text with what you wrote. RZ became R; each CX got a layer of its own (TICK), because each one shares a qubit with the next and the compiler keeps your order; and every DETECTOR was found by the compiler. The last one, DETECTOR rec[-1], is the data qubit 4 on its own; Section 4 explains why that is a problem. Stim can draw the circuit as a timeline (time runs left to right, one line per qubit):

SVG(str(rep_circ.diagram("timeline-svg")))
Timeline of the compiled repetition-code circuit, drawn by Stim. Resets, CX layers and measurements of the three rounds, then the readout of qubits 0, 2 and 4; detectors and the observable are attached to the measurements they compare.

Timeline of the compiled repetition-code circuit, drawn by Stim. Resets, CX layers and measurements of the three rounds, then the readout of qubits 0, 2 and 4; detectors and the observable are attached to the measurements they compare.

3. A surface-code patch, one pass at a time

Now a program at the level of patches: one distance-3 rotated surface code, prepared in , three rounds of stabilizer measurement (three calls of measure_stabilisers(1), the form 0.1.0 compiles), and a readout. to_ascii prints the patch with its qubit numbers.

def patch_memory(rounds=3, d=3):
    builder = LogAsmBuilder()
    patch = builder.declare_patch(RotatedPlanarPatch(d, d, location=(0, 0)))
    patch.prepare("Z")
    for _ in range(rounds):
        patch.measure_stabilisers(1)
    builder.add_return(patch.measure("Z"))
    return builder, patch
 
 
builder, patch = patch_memory()
print(patch.to_ascii())
patch_program = builder.build_program()
print(top_level(patch_program))
3 |         13
  |      2-------5-------8
2 |      |  10   |  12   |  14
  |      1-------4-------7
1 | 16   |   9   |  11   |
  |      0-------3-------6
0 |                 15
  +---------------------------
     0       1       2       3
%qreg = log_asm.patch_dec -> patch<(3, 3) at (0.0, 0.0)>
%qreg_1 = log_asm.prepare<Z> (%qreg : patch<(3, 3) at (0.0, 0.0)>)
%qreg_2 = log_asm.meas_stab<1> (%qreg_1 : patch<(3, 3) at (0.0, 0.0)>)
%qreg_3 = log_asm.meas_stab<1> (%qreg_2 : patch<(3, 3) at (0.0, 0.0)>)
%qreg_4 = log_asm.meas_stab<1> (%qreg_3 : patch<(3, 3) at (0.0, 0.0)>)
%cexpr = log_asm.measure<Z> (%qreg_4 : patch<(3, 3) at (0.0, 0.0)>) -> i1
qstruct.output(%cexpr : i1)

Six log_asm operations: declare, prepare, three rounds, measure. Instead of calling compile, apply the 45 passes ourselves to the program’s xDSL module, and after each pass count the operations of each dialect. (compile does exactly this, plus checks between passes.)

def op_counts(module):
    """Operation names in the module, without xDSL's own builtin dialect."""
    return collections.Counter(op.name for op in module.walk()
                               if not op.name.startswith("builtin."))
 
 
module = patch_program.module
context = LogicalAssembler.make_context()
history = [op_counts(module)]
for p in passes:
    p.apply(context, module)
    history.append(op_counts(module))
 
order = ["log_asm", "sobs", "plaquette", "qcore", "qref", "qstruct", "stab", "qec", "stim"]
table = np.zeros((len(order), len(history)))
for j, names in enumerate(history):
    for name, count in names.items():
        table[order.index(name.split(".")[0]), j] += count
print("dialects seen:", sorted({n.split(".")[0] for h in history for n in h}))
print("final operations:", dict(history[-1]))
dialects seen: ['log_asm', 'plaquette', 'qcore', 'qec', 'qref', 'qstruct', 'sobs', 'stab', 'stim']
final operations: {'stim.qubit_alloc': 17, 'stim.assign_qubit_coord': 17, 'stim.reset': 4, 'stim.tick': 20, 'stim.clifford': 24, 'stim.measure': 4, 'stim.detector': 25}
fig, ax = plt.subplots(figsize=(6.4, 3.8))
masked = np.ma.masked_equal(table, 0)
im = ax.imshow(masked, aspect="auto", cmap="Blues", interpolation="nearest",
               norm=LogNorm(vmin=1, vmax=table.max()))
ax.set_yticks(range(len(order)), order)
ax.set_xlabel("after pass number")
# the full list is: canonicalize, stage 1, canonicalize, stage 2, stage 3, canonicalize,
# stage 4, canonicalize
n1, n2, n3, n4 = (len(stage) for stage in stages.values())
edges = [0, n1 + 2, n1 + 2 + n2, n1 + n2 + n3 + 3, n1 + n2 + n3 + n4 + 4]
assert edges[-1] == len(passes)
for e in edges[1:-1]:
    ax.axvline(e + 0.5, color="#81796f", linestyle=":", linewidth=1.2)
for k, (lo, hi) in enumerate(zip(edges[:-1], edges[1:])):
    ax.text((lo + hi) / 2 + 0.5, -0.8, f"stage {k + 1}", ha="center", va="bottom",
            fontsize=9, color="#81796f")
ax.grid(False)
fig.colorbar(im, ax=ax, label="operations", pad=0.02)
plt.show()
Operations of each dialect in the patch-memory program after each of the 45 passes (column 0 is the program as built; white means none). Dialects are ordered from the logical level (top) to Stim (bottom); dotted lines separate the four stages.

Operations of each dialect in the patch-memory program after each of the 45 passes (column 0 is the program as built; white means none). Dialects are ordered from the logical level (top) to Stim (bottom); dotted lines separate the four stages.

Read the picture from top to bottom.

  • Stage 1 changes nothing here. The program was already written in log_asm; stage 1 matters for CircuitBuilder programs like Section 2’s.
  • Stage 2 explodes the patch. patch-to-plaquettes rewrites the patch operations in terms of the code’s plaquettes (its checks, in the plaquette dialect), and plaquette-to-circuit writes out the gates of each plaquette in qref.
  • Stage 3 finds the detectors. The circuit is re-expressed as stab blocks with known flows, and merge-circuits adds qec operations. Which ones?
merge = next(i for i, p in enumerate(passes) if p.name == "merge-circuits") + 1
print({name: n for name, n in history[merge].items() if name.startswith("qec.")})
{'qec.dec_observable': 1, 'qec.detector': 25, 'qec.get_corrected': 1}

Twenty-five qec.detector operations, one per DETECTOR line of the output. The patch measure did create an observable (dec_observable, get_corrected), but nothing ever includes a measurement in it: Section 2’s program had a qec.observable_include here, this one has none. Section 4 shows the consequence.

  • Stage 4 prints. Everything collapses into the stim dialect, whose operations map almost one to one onto lines of Stim text (QUBIT_COORDS, R, TICK, CX, M, DETECTOR).

4. The missing observable

Compile the same patch program normally and look at the counts and the last detector.

def last_detector(circ):
    return max(i for i, ins in enumerate(circ) if ins.name == "DETECTOR")
 
 
builder, patch = patch_memory()
patch_circ = stim.Circuit(assembler.compile(builder.build_program()).program)
print(patch_circ.num_qubits, "qubits,", patch_circ.num_measurements, "measurements,",
      patch_circ.num_detectors, "detectors,", patch_circ.num_observables, "observables")
print(patch_circ[last_detector(patch_circ)])
17 qubits, 33 measurements, 25 detectors, 0 observables
DETECTOR(2.5, 1.5) rec[-3] rec[-2] rec[-1]

The last detector compares the final measurements of data qubits 6, 7 and 8, the column at in the drawing above: a string from one boundary to the other, which is a representative of . Without noise it is deterministic (we prepared ), so the flow analysis lists it as a detector, and the patch measure produced no observable.

What if you simply add the observable on the same qubits and keep the detector? Then the observable is a detector, and no error can flip it without being seen. Stim’s search for the smallest undetectable logical error finds none:

def noisy(circ, p):
    """The circuit with SI1000 noise, via Deltakit (CZ becomes H-CX-H, MX becomes H-M)."""
    dk = Circuit.from_stim_circuit(circ)
    qpu = QPU(qubits=dk.qubits, noise_model=SI1000Noise(p=p))
    return qpu.compile_and_add_noise_to_circuit(dk)
 
 
doubled = patch_circ.copy()
logical = patch_circ[last_detector(patch_circ)].targets_copy()
doubled.append("OBSERVABLE_INCLUDE", logical, 0)
noisy(doubled, 1e-3).as_stim_circuit().shortest_graphlike_error()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 1
----> 1 noisy(doubled, 1e-3).as_stim_circuit().shortest_graphlike_error()
ValueError: Failed to find any graphlike logical errors.

The repair is to say what we mean: that parity is the observable, not a check. Replace the detector by OBSERVABLE_INCLUDE(0) with the same measurement targets.

fixed = stim.Circuit()
for i, ins in enumerate(patch_circ):
    if i == last_detector(patch_circ):
        fixed.append("OBSERVABLE_INCLUDE", ins.targets_copy(), 0)
    else:
        fixed.append(ins)
print(fixed.num_detectors, "detectors,", fixed.num_observables, "observable")
print("smallest undetectable logical error:",
      len(noisy(fixed, 1e-3).as_stim_circuit().shortest_graphlike_error()), "faults")
24 detectors, 1 observable
smallest undetectable logical error: 3 faults

Three faults, the distance of the code. The circuit is now a proper memory experiment.

Check every exported circuit

A compiler that finds detectors automatically will also find your logical outcome, unless the program marks it as an observable. A logical error rate of exactly zero, or a shortest_graphlike_error that finds nothing, means the observable is hidden among the detectors.

5. Compiled versus hand-built

Lecture 0 built the same experiment with css_code_memory_circuit. Both circuits have 17 qubits, 33 measurements and 24 detectors. Run both through the same noise, decoder and seed.

def failures(noisy_circuit, shots=100_000):
    dec, dec_circ = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy_circuit)
    manager = StimDecoderManager(dec_circ, dec, seed=SEED, batch_size=shots)
    return int(manager.run_batch_shots(shots)[1])
 
 
code = RotatedPlanarCode(width=3, height=3)
by_hand = css_code_memory_circuit(code, num_rounds=3, logical_basis=PauliBasis.Z)
ps = [5e-4, 1e-3, 2e-3, 4e-3]
shots = 100_000
fails = {"compiled (repaired)": [], "css_code_memory_circuit": []}
for p in ps:
    fails["compiled (repaired)"].append(failures(noisy(fixed, p)))
    qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=p))
    fails["css_code_memory_circuit"].append(
        failures(qpu.compile_and_add_noise_to_circuit(by_hand)))
print("p        compiled   by hand   (fails in 100000)")
for i, p in enumerate(ps):
    print(f"{p:<8g} {fails['compiled (repaired)'][i]:8d} "
          f"{fails['css_code_memory_circuit'][i]:9d}")
p        compiled   by hand   (fails in 100000)
0.0005         97       109
0.001         405       344
0.002        1550      1262
0.004        5248      4795
fig, ax = plt.subplots()
for name, f in fails.items():
    lep, err = calculate_lep_and_lep_stddev(fails=f, shots=[shots] * len(ps))
    ax.errorbar(ps, lep, yerr=err, marker="o", capsize=3, label=name)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("physical error rate p (SI1000)")
ax.set_ylabel("logical error probability (3 rounds)")
ax.legend()
plt.show()
Logical error probability of the 3-round, distance-3 memory experiment against SI1000 noise strength p, 100,000 shots per point, PyMatching: the circuit compiled by deltakit-compile (after the repair) and the one built by css_code_memory_circuit. Error bars are one standard deviation.

Logical error probability of the 3-round, distance-3 memory experiment against SI1000 noise strength p, 100,000 shots per point, PyMatching: the circuit compiled by deltakit-compile (after the repair) and the one built by css_code_memory_circuit. Error bars are one standard deviation.

Close, but the compiled circuit fails more often at . Same code, same number of rounds, same detectors. Count what the noisy circuits contain, including the idling errors: SI1000 gives a qubit that waits while others are measured or reset a depolarizing error of strength .

def census(noisy_circuit, p):
    """H and CX gates, layers, and qubits hit by idle depolarizing noise of strength 2p."""
    c = collections.Counter()
    for ins in noisy_circuit.as_stim_circuit().flattened():
        n = len(ins.targets_copy())
        if ins.name in ("H", "CX"):
            c[ins.name] += n // (2 if ins.name == "CX" else 1)
        elif ins.name == "TICK":
            c["layers"] += 1
        elif ins.name == "DEPOLARIZE1" and abs(ins.gate_args_copy()[0] - 2 * p) < 1e-12:
            c["idle at 2p"] += n
    return {k: c[k] for k in ("H", "CX", "layers", "idle at 2p")}
 
 
print("compiled:", census(noisy(fixed, 1e-3), 1e-3))
qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))
print("by hand: ", census(qpu.compile_and_add_noise_to_circuit(by_hand), 1e-3))
lines = str(fixed).splitlines()
start = max(i for i, ln in enumerate(lines) if ln.startswith("MX"))
print("\n".join(ln for ln in lines[start:] if not ln.startswith("DETECTOR")))
compiled: {'H': 32, 'CX': 72, 'layers': 24, 'idle at 2p': 53}
by hand:  {'H': 32, 'CX': 72, 'layers': 24, 'idle at 2p': 36}
MX 9 11 10 12 13 15 16 14
TICK
M 0 1 2 3 4 5 6 7 8
TICK
OBSERVABLE_INCLUDE(0) rec[-3] rec[-2] rec[-1]

The same gates in the same numbers (after the QPU model rewrites CZ as H-CX-H and MX as H-M in both), and the same number of layers. The difference is 17 extra idling errors in the compiled circuit, and the tail of its Stim text shows where they come from: it measures the last ancillas (MX) and the data (M) in two separate layers. The nine data qubits wait through the first, picking up a error just before they are read out, and the eight ancillas wait through the second. css_code_memory_circuit measures all seventeen in one layer. The two circuits also order the gates inside each round differently, so this is the most visible difference, not necessarily the only one.

Both circuits are correct; the hand-built one is better scheduled for this noise model. A production compiler would schedule with the target hardware in mind; the 0.1.0 source has a placeholder for that step (a commented-out “QPU specialisation” pipeline).

6. Lattice surgery: built, not yet compiled

multi_pauli_measure is the lattice-surgery instruction. Build a measurement between two patches side by side and read the IR.

builder = LogAsmBuilder()
left = builder.declare_patch(RotatedPlanarPatch(3, 3, location=(0, 0)))
right = builder.declare_patch(RotatedPlanarPatch(3, 3, location=(4, 0)))
left.prepare("Z")
right.prepare("Z")
builder.add_return(builder.multi_pauli_measure([left, right], pauli_bases=["Z", "Z"]))
surgery = builder.build_program()
print(top_level(surgery))
%qreg = log_asm.patch_dec -> patch<(3, 3) at (0.0, 0.0)>
%qreg_1 = log_asm.patch_dec -> patch<(3, 3) at (4.0, 0.0)>
%qreg_2 = log_asm.prepare<Z> (%qreg : patch<(3, 3) at (0.0, 0.0)>)
%qreg_3 = log_asm.prepare<Z> (%qreg_1 : patch<(3, 3) at (4.0, 0.0)>)
%qreg_4 = log_asm.patch_dec -> patch<(1, 3) at (3.0, 0.0)>
%qreg_5 = log_asm.prepare<X> (%qreg_4 : patch<(1, 3) at (3.0, 0.0)>)
%cexpr, %qreg_6, %qreg_7 = log_asm.multi_pauli_meas<3, (Z, Z)> (%qreg_2, %qreg_3 : patch<(3, 3) at (0.0, 0.0)>, patch<(3, 3) at (4.0, 0.0)>) (%qreg_5 : patch<(1, 3) at (3.0, 0.0)>) -> i1
%0 = log_asm.measure<X> (%qreg_5 : patch<(1, 3) at (3.0, 0.0)>) -> i1
qstruct.output(%cexpr : i1)

The builder added a third patch, of size at : the bridge between the two, prepared in (prepare<X>), exactly as in Lecture 8’s figure. The joint measurement multi_pauli_meas<3, (Z, Z)> asks for 3 rounds (its rounds property; the default is the distance), and afterwards the bridge is measured in the basis (measure<X>): the split. multi_pauli_measure also accepts your own bridges and rounds. Patch lowering does not handle the operation yet:

assembler.compile(surgery)
… (traceback shortened)
NotImplementedError: MultiPauliMeasOp is not yet supported.
"builtin.module"() ({
  %0 = "sobs.dec_unplaced_observable"() : () -> !sobs.unplaced_observable
  %qreg, %qreg_1, %qreg_2 = "qstruct.parallel"() <{alignment = #qstruct.align<BOTTOM>}> ({
    %qreg_3 = "log_asm.patch_dec"() : () -> !log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>
    %qreg_4 = "log_asm.prepare"(%qreg_3) <{basis = #qcore.pauli<Z>}> : (!log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>) -> !log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>
    "qstruct.yield"(%qreg_4) : (!log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>) -> ()
  }, {
    %qreg_5 = "log_asm.patch_dec"() : () -> !log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>
    %qreg_6 = "log_asm.prepare"(%qreg_5) <{basis = #qcore.pauli<Z>}> : (!log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>) -> !log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>
    "qstruct.yield"(%qreg_6) : (!log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>) -> ()
  }, {
    %qreg_7 = "log_asm.patch_dec"() : () -> !log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>
    %qreg_8 = "log_asm.prepare"(%qreg_7) <{basis = #qcore.pauli<X>}> : (!log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>) -> !log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>
    "qstruct.yield"(%qreg_8) : (!log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>) -> ()
  }) : () -> (!log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>, !log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>, !log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>)
  %cexpr, %qreg_9, %qreg_10 = "log_asm.multi_pauli_meas"(%qreg, %qreg_1, %qreg_2) <{rounds = #builtin.int<3>, basis = [#qcore.pauli<Z>, #qcore.pauli<Z>], operandSegmentSizes = array<i32: 2, 1>}> : (!log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>, !log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>, !log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>) -> (i1, !log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>, !log_asm.patch.rot_planar<size=(3, 3), location=(4.0, 0.0), orient=v_z>)
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----------------
  | Error while applying pattern: MultiPauliMeasOp is not yet supported.
  ----------------------------------------------------------------------
  %1 = "sobs.locate_unplaced_observable"(%0, %qreg_2) <{bases = [#qcore.pauli<X>]}> : (!sobs.unplaced_observable, !log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>) -> !sobs.unplaced_observable
  %2 = "log_asm.measure"(%qreg_2) <{basis = #qcore.pauli<X>}> : (!log_asm.patch.rot_planar<size=(1, 3), location=(3.0, 0.0), orient=v_z>) -> i1
  "qstruct.output"(%cexpr) : (i1) -> ()
}) : () -> ()

Try this

  1. In repetition_program, return the raw measurements (readout.add_return(m)) instead of the observable. How many detectors and observables does the compiled circuit have now?
  2. Prepare and measure the patch in the basis (patch.prepare("X"), patch.measure("X")). Which detector is the logical one now, and which data qubits does it cover?
  3. Compile a 5-round patch (patch_memory(rounds=5)) and repeat the repair. Does the gap to css_code_memory_circuit(code, num_rounds=5, ...) grow or shrink?
  4. Repeat Section 3 for repetition_program() and see stage 1 do the work: which dialects does the program start in?