Every circuit in this primer so far was a memory experiment: prepare a logical qubit, measure its
checks for a while, read it out. A quantum algorithm also needs logical operations:
measurements of
Riverlane’s deltakit-compile (version 0.1.0, Apache-2.0,
repository) is such a compiler. It takes a
logical assembly program and lowers it, through a stack of intermediate languages built with
the xDSL framework, to Stim text. This lecture explains the ideas it is built on, then runs it.
Version 0.1.0 is an early release: it builds programs for most of its instruction set, but
compiles only the simplest ones to Stim. The lecture says exactly which, because the probes in
this primer found the boundary the hard way.
Notebook and field map
Notebook 8: Logical assembly compiles a repetition-code program and a surface-code patch, watches the IR change pass by pass, repairs the exported circuit and compares it with Deltakit’s hand-built memory circuit. Field map: deltakit-compile and logical assembly, Lattice surgery, xDSL dialects in deltakit-compile, Detectors and observables, The memory-experiment pipeline.
From logical programs to circuits
Definition 8.1 (Patch and logical program).A patch is a region of the chip that holds one surface-code logical qubit, described by its size and position. A logical program is a sequence of instructions on patches: prepare in a basis, idle while measuring stabilizers for some rounds, measure a logical Pauli operator, measure a product of logical Paulis across several patches, apply a transversal gate, move or grow a patch. Instructions return classical results, and later instructions may depend on them.
Turning one instruction of Definition 8.1 into gates is mechanical: Lecture 3 did it for “measure stabilizers”. The hard part is the detectors. A detector (Lecture 2) is a set of measurements whose parity is fixed when there is no noise. When patches merge, split and move, which parities are fixed changes from round to round. The compiler finds them by tracking how Pauli operators move through the circuit.
Definition 8.2 (Stabilizer flow).A Clifford circuit
with measurements has the flow through a set of its measurements if, for every input that is a eigenstate of the Pauli , the output is an eigenstate of the Pauli whose eigenvalue is to the parity of the outcomes in . A reset in the basis has the flow with no measurements; a measurement has through itself.
Flows compose: if one piece of a circuit has
Remark 8.1 (The logical outcome is also a flow).In a memory experiment you reset the data qubits, which prepares
, and finally measure them, which reads . The logical outcome is therefore also deterministic without noise: at the start, at the end, so it is an flow like any detector. A detector finder that knows nothing else will declare it a detector. Only the program knows that this parity is the protected quantity, an observable, rather than a check. If the logical outcome is listed as a detector, the decoder is told the answer.
Lattice surgery
Surface-code patches cannot easily apply a two-qubit logical gate to each other. Lattice surgery replaces the gate by a joint measurement, using only operations the code already does: preparing qubits, measuring checks, measuring qubits.
Definition 8.3 (Lattice-surgery merge and split).Place two patches side by side with a column of bridge qubits between them. To measure
, prepare the bridge in , then measure the stabilizers of the single merged patch for rounds. The product of the new -type checks along the seam is the outcome of . To split, measure the bridge qubits in the basis; the two patches are separate again.
The figure shows why the product in Definition 8.3 works, for a seam of height 3. Each new
A single merged measurement is not trustworthy: any check can be misread. So the merged patch is
measured for multi_pauli_measure is the
central instruction of logical assembly.
The compiler as a stack of dialects
A compiler rarely jumps from source to machine code in one step. It rewrites the program through several intermediate representations (IRs), each closer to the hardware than the last.
Definition 8.4 (Dialect, pass and lowering).In the MLIR style of compiler, an IR program is a list of operations such as
%q1 = log_asm.prepare<Z> (%q0). Every value (here%q1) is defined exactly once, so data flow is explicit. A dialect is a named family of operations and types at one level of abstraction (log_asmfor patches,qreffor physical gates,stimfor Stim instructions), and one program may mix several. A pass rewrites the program; a lowering is a pass that replaces operations of a higher dialect by operations of a lower one.
deltakit-compile uses xDSL, a Python framework that implements MLIR’s ideas,
and defines its own dialects. Qubits are values passed from operation to operation, so the
compiler sees which instructions depend on which. The figure shows the stages of the pipeline
with Stim export (Definition 8.4), with the dialects each one introduces.
- Logical assembly. Inline every
CircuitBuildercircuit you called, remove duplicated work, and lower the builder-only operations (log_asm_api,tensor,arith) to physical registers and gates (qcore,qref,qstruct). Patch instructions are already in thelog_asmdialect, written there byLogAsmBuilder, and pass through unchanged. - Patch lowering. Turn each patch instruction into plaquettes (the checks of a rotated
surface code at given positions), schedule their two-qubit gates, and emit physical gates in
qref. Observables are placed here (sobs). Only rotated planar patches are supported. - Stabilizer flows. Convert the physical circuit into the
stabdialect, which records the flows of Definition 8.2, merge them across the whole program, and emitqec.detectoroperations for everyflow, with coordinates inferred from the qubits involved. - Stim export. Name gates, insert
TICKs, flatten qubit registers to integers, lower to thestimdialect and print.
With Stim export the pipeline runs 45 passes (35 without it), many of them small clean-ups. Notebook 8 runs them one at a time on a three-round patch memory and counts the operations of each dialect in between.
In Deltakit
The entry points are LogAsmBuilder and RotatedPlanarPatch in
deltakit_compile.frontend.logasm, CircuitBuilder and QubitReg in
deltakit_compile.frontend.common, and LogicalAssembler with LogicalAssemblerConfig.
Passing export_config=StimExportPipelineConfig() asks for Stim text; the default prints the
final physical IR instead. Here is what 0.1.0 does with each instruction (all probed):
| instruction | builds a program | compiles to Stim |
|---|---|---|
CircuitBuilder circuits via call_circuit | yes | yes |
patch prepare, measure_stabilisers(1), measure | yes | yes, but see Remark 8.1 |
measure_stabilisers(min_rounds), | yes | ValueError in a flow pass |
multi_pauli_measure | yes | NotImplementedError |
transversal, move, grow, rotate, step | yes | NotImplementedError |
for_, if_, while_, CircuitBuilder.repeat | NotImplementedError |
Start at the bottom of the stack with a circuit you write gate by gate: a three-qubit repetition
code with data on qubits 0, 2, 4 and ancillas on 1 and 3. Three small circuits (prepare, one
round of declare_observable().include(...).
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)
from deltakit_compile.passes.stim.stim_export.pipeline import (
StimExportPipelineConfig)
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(3):
builder.call_circuit(check(reg))
builder.add_return(builder.call_circuit(readout(reg)))
config = LogicalAssemblerConfig(export_config=StimExportPipelineConfig(),
verify_between_passes=True)
assembler = LogicalAssembler(config)
rep_text = assembler.compile(builder.build_program()).program
print("\n".join(rep_text.splitlines()[-6:]))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]The compiler found the detectors by itself: two after the first round (an ancilla that starts in
DETECTOR rec[-1], is qubit 4 alone. It is
deterministic because the data started in
import deltakit_stim as stim
from deltakit.circuit import Circuit
from deltakit.decode import PyMatchingDecoder
from deltakit.decode.analysis import StimDecoderManager
from deltakit.explorer.qpu import QPU, SI1000Noise
SEED = 2026
def failures(circ, p, shots=100_000):
"""SI1000 noise, PyMatching, seeded sampling: logical failures."""
dk = Circuit.from_stim_circuit(circ)
qpu = QPU(qubits=dk.qubits, noise_model=SI1000Noise(p=p))
noisy = qpu.compile_and_add_noise_to_circuit(dk)
dec, dec_circ = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
manager = StimDecoderManager(dec_circ, dec, seed=SEED, batch_size=shots)
return manager.run_batch_shots(shots)[1]
def last_detector(circ):
return max(i for i, ins in enumerate(circ) if ins.name == "DETECTOR")
rep = stim.Circuit(rep_text)
trimmed = stim.Circuit()
for i, ins in enumerate(rep):
if i != last_detector(rep):
trimmed.append(ins)
print("as compiled: ", failures(rep, 0.01), "fails in 100000")
print("without last detector:", failures(trimmed, 0.01), "fails in 100000")as compiled: 0 fails in 100000
without last detector: 4397 fails in 100000Zero failures at shortest_graphlike_error() on the noisy circuit), it
finds three in the trimmed circuit and raises “Failed to find any graphlike logical errors” on
the compiled one (Notebook 8 shows the same for the surface-code patch below).
Now a real patch. RotatedPlanarPatch(3, 3) is a distance-3 rotated surface code; three calls of
measure_stabilisers(1) give three rounds, the form that 0.1.0 compiles.
lb = LogAsmBuilder()
patch = lb.declare_patch(RotatedPlanarPatch(3, 3, location=(0, 0)))
patch.prepare("Z")
for _ in range(3):
patch.measure_stabilisers(1)
lb.add_return(patch.measure("Z"))
patch_circ = stim.Circuit(assembler.compile(lb.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 patch measure produced no OBSERVABLE_INCLUDE, and the last detector is OBSERVABLE_INCLUDE
is marked as an expected failure, so this is the current state of 0.1.0 rather than a misuse.
The repair is one line of intent: that detector is the observable.
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("p = 1e-3:", failures(fixed, 1e-3), "fails in 100000")24 detectors, 1 observable
p = 1e-3: 405 fails in 100000The same experiment built by hand in Lecture 0 (css_code_memory_circuit, 3 rounds, same noise,
seed and decoder) failed 344 times. The two circuits have the same qubits, gates, measurements
and detectors, but not the same schedule. The visible difference is at the end: the compiled
circuit measures the last ancillas and the data in two separate layers, so each group waits
while the other is measured, and SI1000 charges every such wait with a
Lattice surgery builds but does not compile. multi_pauli_measure chooses a bridge patch of
width 1 between two aligned patches and records the merge for log_asm.multi_pauli_meas<3, (Z, Z)>). Lowering it raises
NotImplementedError: MultiPauliMeasOp is not yet supported.
lb = LogAsmBuilder()
p1 = lb.declare_patch(RotatedPlanarPatch(3, 3, location=(0, 0)))
p2 = lb.declare_patch(RotatedPlanarPatch(3, 3, location=(4, 0)))
p1.prepare("Z")
p2.prepare("Z")
lb.add_return(lb.multi_pauli_measure([p1, p2], pauli_bases=["Z", "Z"]))
assembler.compile(lb.build_program())Compile time also grows fast with patch size: the three-round
Try this
- Change the repetition program to declare no observable (
readout.add_return(m)). How many detectors and observables does the compiled circuit have? - In the patch program, prepare and measure in the
basis. Which detector is now the logical one, and what are its coordinates? - Call
patch.measure_stabilisers(3)once instead of three times, and read the error. - Print
lb.build_program()for the lattice-surgery program and find the bridge patch: its size, location and preparation basis.
Readings
- C. Horsman, A. G. Fowler, S. Devitt and R. Van Meter, Surface code quantum computing by lattice surgery, New J. Phys. 14, 123011 (2012). Merge, split and the logical CNOT.
- D. Litinski, A game of surface codes: large-scale quantum computing with lattice surgery, Quantum 3, 128 (2019). Computation as Pauli-product measurements.
- C. Lattner et al., MLIR: scaling compiler infrastructure for domain specific computation, CGO 2021. Dialects, passes and lowering.
- xDSL, the Python framework
deltakit-compileis built on, and the deltakit-compile repository, whose tests are the best documentation of the API.