Measuring Streaming Interleaved Feed-forward Latency (SIFL)

This experiment shows how waiting for a decoder’s correction can increase the work in the next shot. Two decoder instances alternate surface-code memory shots. While one shot is being decoded, the next collects measurement rounds until the previous correction arrives or a round cap is reached. The script varies the interval between rounds and reports the resulting shot lengths and decoding response times.

Use it to investigate the connection between measurement cadence, feedback waiting, and decoder backlog. A longer wait can produce a larger shot, which can take longer to decode in turn. Increasing the interval between rounds gives the decoder more time to finish before further measurements arrive. The default configuration uses PyMatching on the CPU, with measurements generated by Stim and sent by the Playback Emulator.

Prerequisites

  • A CUDA-Q QEC installation built with CUDA-Q realtime support, including the Python playback interface (cudaq_qec.playback), development headers, libcudaq-qec-decoders, and the PyMatching decoder plugin.

  • python3 with cudaq_qec, numpy, and stim importable, plus g++ with C++17 support and Bash to build and run the example plugin.

  • A writable example directory. The runner creates libper_round_decoder.so beside the source files and removes that generated plugin when it exits.

The default PyMatching experiment runs in process and needs no decoding server, GPU, QPU, or FPGA. The 0.9.0 pip wheels do not include the Python playback interface. Use a realtime-enabled installation and ensure its headers and libraries match; see Building CUDA-Q QEC from Source if you need to prepare that environment.

Run the Experiment

Use the directory docs/sphinx/examples/qec/sifl_demo/ in your CUDA-Q QEC checkout, or download these three files into one directory:

File

Purpose

run_sifl_demo.sh

Builds the plugin and runs the experiment with the supplied options.

sifl_demo.py

Prepares detector error models, runs the playback schedules, and prints results.

per_round_decoder.cpp

Buffers each shot and selects a sub-decoder for its final round count.

With the installation’s Python and library environment set up, start with a small run from that directory:

bash run_sifl_demo.sh --distance 3 --shots 6 \
    --init-rounds 3 --max-rounds 12 --cadences 2 20 100

This runs six shots at each of three requested round periods: 2, 20, and 100 microseconds. Expect one result line per period, each with six shot lengths. The first shot has three rounds; subsequent shots have between one and nine rounds, where nine is max-rounds - init-rounds.

For the default experiment, run:

bash run_sifl_demo.sh

The defaults are distance 5, physical error probability 0.01, 30 shots per cadence, ten rounds in the first shot, and round periods of 2, 5, 10, 20, and 50 microseconds. --max-rounds defaults to 60, giving subsequent shots a cap of 50 rounds. bash run_sifl_demo.sh --help lists the options; --decoder selects the sub-decoder, with pymatching as the default.

How the Example Runs

The Python script generates a detector error model for each possible shot length. The C++ plugin prepares a sub-decoder from each detector error model and warms it up before the timed runs. For an incoming shot, it buffers the measurement rounds, then selects the matching sub-decoder when the final data readout arrives. Decoding happens at that point, rather than incrementally as each round is enqueued.

The playback schedule sends one stabilizer round every requested \(T\) microseconds. After the first shot, a completion signal from the previous shot’s correction ends the current stream, subject to the minimum of one round and the configured cap. The two decoder instances exchange roles on each shot. This models a timing dependency; the returned correction bits do not change the next circuit’s operations.

Reading the Output

The script prints two quantities for each cadence:

  • Decode time per round: Sum the intervals from dispatching each shot’s final data readout to receiving its correction, then divide by the total stabilizer rounds streamed. The intervals include decoder and request-handling time, but exclude preparation of the final readout and the earlier streaming of measurement rounds. This is a normalized response time, not the total experiment runtime divided by its rounds.

  • Rounds streamed per shot: The length of each shot in stabilizer rounds, excluding its final data readout. Read the sequence to see whether shots become longer, remain short, or repeatedly reach the cap.

The following illustrative output uses the default first-shot length and round cap; the lists are shortened for display. Timings and shot lengths vary with the decoder, host, workload, and scheduling:

Decode time per round and rounds streamed per shot (stream cap 50):
  T =    2 us  decode time per round  7.17 us  [10, 50, 50, 50, 50, 50, 50, ...]
  T =   10 us  decode time per round  9.87 us  [10, 16, 13, 12, 18, 12, 16, ...]
  T =   50 us  decode time per round 12.84 us  [10, 3, 2, 2, 2, 1, 2, ...]

Here, the 2-microsecond cadence repeatedly reaches the cap, while the 50-microsecond cadence leaves more time for corrections to return between measurement rounds. A cap of 50 limits what can be observed: reaching it is not evidence of an unlimited shot length. Likewise, a short run with small shots does not establish a latency guarantee.

Host scheduling, measurement generation, and decoding all affect the results. The requested round cadence does not guarantee that the emulator dispatches each round on time. Consider the shot-length sequence alongside the reported average when comparing configurations under the same conditions.

The script checks that correction requests complete, but supplies no expected logical values and does not measure logical error rate. For timing details behind the averages, the Python playback result contains per-request dispatch and reply timestamps; see the Playback Emulator output format.

The Example Source

"""Streaming Interleaved Feed-forward Latency (SIFL) on the playback emulator.

Usage: ./run_sifl_demo.sh [options]
"""
import argparse, ctypes, os, tempfile
import numpy as np
import stim
import cudaq_qec as qec

parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--distance", type=int, default=5, help="code distance")
parser.add_argument("--p", type=float, default=0.01, help="physical error rate")
parser.add_argument(
    "--max-rounds",
    type=int,
    default=60,
    help="longest shot, in stabilizer rounds, the decoder accepts")
parser.add_argument("--shots", type=int, default=30, help="shots per cadence")
parser.add_argument("--init-rounds",
                    type=int,
                    default=10,
                    help="stabilizer rounds in the first shot")
parser.add_argument("--cadences",
                    type=float,
                    nargs="+",
                    default=[2, 5, 10, 20, 50],
                    help="round periods T to run, in us")
parser.add_argument("--seed", type=int, default=1, help="syndrome source seed")
parser.add_argument("--decoder",
                    default="pymatching",
                    help="decoder used for each round count")
args = parser.parse_args()
if not 0 < args.init_rounds < args.max_rounds:
    parser.error("--init-rounds must be between 1 and --max-rounds - 1")
STREAM_CAP = args.max_rounds - args.init_rounds
# Longest shot the schedule can produce.
MAX_SHOT = max(args.init_rounds, STREAM_CAP)

# Loading the plugin registers `per_round_decoder` with CUDA-Q QEC.
ctypes.CDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "libper_round_decoder.so"),
            mode=ctypes.RTLD_GLOBAL)


def circuit(rounds):
    return stim.Circuit.generated("surface_code:rotated_memory_z",
                                  rounds=rounds,
                                  distance=args.distance,
                                  before_measure_flip_probability=args.p,
                                  after_clifford_depolarization=args.p)


round_width = circuit(2).num_measurements - circuit(1).num_measurements
terminal_width = circuit(1).num_measurements - round_width


def write_dem(rounds, path):
    """Writes the full DEM of an r-round circuit as H, O, D and rates lines."""
    c = circuit(rounds)
    text = str(c.detector_error_model(decompose_errors=True))
    dem = qec.dem_from_stim_text(text, use_decomp_suggestions=True)
    dem.canonicalize_for_rounds(round_width, remove_zero_syndrome_errors=True)
    # D: flipping measurement i alone fires exactly the detectors in column i.
    flips = np.eye(c.num_measurements, dtype=np.bool_)
    D = c.compile_m2d_converter().convert(measurements=flips,
                                          append_observables=False).T
    lines = [
        qec.pcm_to_sparse_vec(np.ascontiguousarray(M, dtype=np.uint8))
        for M in (dem.detector_error_matrix, dem.observables_flips_matrix, D)
    ] + [dem.error_rates]
    with open(path, "w") as f:
        f.write("\n".join(" ".join(map(str, line)) for line in lines) + "\n")


def ring(decoder_id, dem_dir):
    config = qec.decoder_config()
    config.id, config.type = decoder_id, "per_round_decoder"
    # Placeholders: the decoder builds its sub-decoders from dem_dir. The large
    # D_sparse index lets a shot carry any number of measurements.
    config.block_size, config.syndrome_size = 1, 1
    config.H_sparse, config.O_sparse = [0, -1], [0, -1]
    config.D_sparse = [9_999_999, -1]
    config.decoder_custom_args = dict(dem_dir=dem_dir,
                                      round_width=round_width,
                                      terminal_width=terminal_width,
                                      max_rounds=MAX_SHOT,
                                      delegate_type=args.decoder)
    return config


# Shot i streams to ring i % 2 until shot i-1's correction lands.
lines = [
    f"0 stream source=0 rounds={args.init_rounds}", "- enqueue_data source=0",
    "- get_corrections return_size=1 signal=shot0"
]
for i in range(1, args.shots):
    lines += [
        f"- stream session={i % 2} source=0 every=1 min_rounds=1 "
        f"max_rounds={STREAM_CAP} until=shot{i - 1}",
        f"- enqueue_data session={i % 2} source=0",
        f"- get_corrections session={i % 2} return_size=1 signal=shot{i}"
    ]
schedule = "\n".join(lines) + "\n"
source = dict(type="stim_memory",
              seed=args.seed,
              code="surface_code",
              task="rotated_memory_z",
              distance=args.distance,
              rounds=10_000,
              before_measure_flip_probability=args.p,
              after_clifford_depolarization=args.p)

with tempfile.TemporaryDirectory() as dem_dir:
    for r in range(1, MAX_SHOT + 1):
        write_dem(r, f"{dem_dir}/r{r}.txt")
    decoders = qec.multi_decoder_config()
    decoders.decoders = [ring(0, dem_dir), ring(1, dem_dir)]

    pb = qec.playback
    print(f"Decode time per round and rounds streamed per shot "
          f"(stream cap {STREAM_CAP}):")
    for period_us in args.cadences:
        result = pb.run(schedule,
                        tick_ns=round(period_us * 1000),
                        decoders=decoders,
                        sources={0: source})
        rounds = [
            r["rounds_streamed"] for r in result.records if r["op"] == "stream"
        ]
        readouts = [r for r in result.records if r["op"] == "enqueue_data"]
        reads = [r for r in result.records if r["op"] == "get_corrections"]
        assert all(r["read_completed"] for r in reads)
        # Decode time runs from dispatching a shot's data readout to its
        # correction, excluding the source's time preparing the readout.
        decode_us = sum((g["return_ns"] - e["request_dispatch_ns"][0]) / 1e3
                        for e, g in zip(readouts, reads))
        print(f"  T = {period_us:>4g} us  decode time per round "
              f"{decode_us / sum(rounds):5.2f} us  {rounds}")

See Also