qldpc.circuits.benchmarking

Methods for benchmarking circuits.

Functions

get_logical_error_and_discard_rate(, ...)

Compute a logical error rate and discard rate from samples of the provided circuit.

get_state_prep_diagnostic_circuit(...)

Annotate a logical state prep circuit with diagnostics for computing logical error rates.

get_state_prep_diagnostic_tasks(, qubit_ids, ...)

Helper method to build sinter Tasks for benchmarking a logical state preparation circuit.

Module Contents

qldpc.circuits.benchmarking.get_logical_error_and_discard_rate(circuit_or_dem: stim.Circuit | stim.DetectorErrorModel, sinter_decoder: sinter.Decoder, num_samples: int, *, post_select: collections.abc.Collection[int] = (), post_select_observables: collections.abc.Collection[int] = (), dem_to_decode: stim.DetectorErrorModel | None = None) → tuple[float, float][source]

Compute a logical error rate and discard rate from samples of the provided circuit.

Each logical error rate is a fraction of the (possibly post-selected) shots in which observable flips are predicted incorrectly by the provided decoder.

This method is provided for convenience, but if you are doing heavy numerics you should probably build a sinter.Task and call sinter.collect. In this case, circuit_or_dem should just be a circuit, and the sinter.Task would be built as follows:

postselection_mask = np.zeros(circuit.num_detectors, dtype=int)
postselection_mask[post_select] = 1
task = sinter.Task(
    circuit=circuit,
    detector_error_model=dem_to_decode,
    postselection_mask=np.packbits(postselection_mask, bitorder="little"),
)

Sampling data would then be collected with:

stats = sinter.collect(
    tasks=[task],  # or more maybe more tasks
    decoders=["custom"],
    custom_decoders={"custom": sinter_decoder},
    num_shots=num_samples,
    # other options such as num_workers=os.cpu_count() or max_errors=100
)
Parameters:
  • circuit_or_dem – The circuit or detector error model we wish to sample.

  • sinter_decoder – The circuit-level decoder used to predict observable flips.

  • num_samples – The number of times to sample the circuit_or_dem.

Keyword Arguments:
  • post_select – The detectors in circuit_or_dem to post-select on.

  • post_select_observables – The observables to post-select on. Any time the decoder’s prediction for these observable flips do not agree with the actual observable flips, the shot is discarded rather than counting as an error.

  • dem_to_decode – The detector error model to decode. This DEM should include _all_ detectors, including any that are post-selected on: the decoder receives every detector bit, for consistency with how sinter works. If dem_to_decode is None, this method decodes with the (simplified) DEM sampled from circuit_or_dem.

Returns:

A fraction of the retained samples in which at least one observable was decoded incorrectly. A fraction of samples that were discarded, either by post-selection or at the request of the decoder, which signals that a shot should be discarded by predicting observable flips in one more byte than the observables of the sampled circuit require. These are point estimates. Use sinter.collect when counts or confidence intervals are needed.

qldpc.circuits.benchmarking.get_state_prep_diagnostic_circuit(code: qldpc.codes.QuditCode, state_prep_circuit: stim.Circuit, *, add_flags: bool = False, qubit_ids: qldpc.circuits.bookkeeping.QubitIDs | None = None, observables: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | collections.abc.Sequence[stim.PauliString] | None = None, skip_validation: bool = False) → tuple[stim.Circuit, qldpc.circuits.bookkeeping.DetectorRecord][source]

Annotate a logical state prep circuit with diagnostics for computing logical error rates.

More specifically, this method returns a diagnostic circuit that appends the following to the provided circuit:

  • If ‘add_flags is True’, a detector for each measurement that is not addressed by an existing

    detector in the provided circuit. The added detectors are called “flag detectors”.

  • Noiseless measurements of all stabilizers of the code.

  • A detector for each of the noiseless stabilizer measurements.

  • Noiseless measurements of observables that stabilize the state prepared by state_prep_circuit.

  • Annotations of the measured observables (with OBSERVABLE_INCLUDE).

The logical error rate of the diagnostic circuit is nominally the probability with which any of the annotated observables are flipped after decoding flag and stabilizer measurement outcomes. However, the details of decoding and the option to post-select on some detectors are left up to the user.

The second returned value is a DetectorRecord whose get_events method maps keys to detector indices:

  • get_events(“prep”) returns the indices of detectors already present in the provided

    state_prep_circuit.

  • get_events(“flags”) returns the indices of the flag detectors.

  • get_events(stab_index)[0] is the index of the detector for the stabilizer

    code.get_stabilizer_ops()[stab_index].

Parameters:
  • code – The code whose logical state is prepared by the provided state_prep_circuit.

  • state_prep_circuit – A circuit that prepares a logical state of the provided code.

Keyword Arguments:
  • add_flags – Whether to add a flag detector for each unaddressed measurement in the circuit.

  • qubit_ids – A QubitIDs object specifying the indices of the data qubits of the code. If None, the data qubits of the code are assumed to be range(len(code)).

  • observables – The observables that should stabilize the prepared state, or (by default) None. If not None, the observables should be either a matrix of symplectic row vectors, with shape (num_observables, 2 * len(code)), or a sequence of Pauli strings supported on the data qubits of the code. If None, observables are determined automatically by finding all logical Pauli operators of the code that stabilize the state prepared by state_prep_circuit.

  • skip_validation – If True, skip the check to assert that the provided circuit prepares a logical state of the provided code.

Returns:

An annotated circuit for stim/sinter simulations of logical error rates. circuits.DetectorRecord: A record of the circuit’s detectors (keys described above).

Return type:

stim.Circuit

qldpc.circuits.benchmarking.get_state_prep_diagnostic_tasks(code: qldpc.codes.QuditCode, state_prep_circuit: stim.Circuit, error_rates: collections.abc.Sequence[float] | numpy.typing.NDArray[numpy.floating], noise_model_family: collections.abc.Callable[[float], qldpc.circuits.noise_model.NoiseModel] = DepolarizingNoiseModel, *, post_select: bool | collections.abc.Collection[int] = False, post_select_observables: collections.abc.Collection[int] = (), qubit_ids: qldpc.circuits.bookkeeping.QubitIDs | None = None, observables: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | collections.abc.Sequence[stim.PauliString] | None = None, skip_validation: bool = False, metadata: dict[str, collections.abc.Hashable] | None = None) → list[sinter.Task][source]

Helper method to build sinter Tasks for benchmarking a logical state preparation circuit.

This method is essentially a wrapper for get_state_prep_diagnostic_circuit. See help(get_state_prep_diagnostic_circuit) for additional information.

As an example, if:

tasks = get_state_prep_diagnostic_tasks(...)
decoder = qldpc.decoders.SinterDecoder(...)

then we can collect statistics with:

stats = sinter.collect(
    tasks=tasks,
    decoders=["custom"],
    custom_decoders={"custom": decoder},
    num_workers=os.cpu_count(),
    max_shots=10**5,
    max_errors=100,
)

and plot the results with:

import matplotlib.pyplot as plt

figure, axis = plt.subplots(figsize=(5, 4))
sinter.plot_error_rate(
    ax=axis,
    stats=stats,
    x_func=lambda stats: stats.json_metadata["p"],
)
axis.axline(
    (0, 0),
    slope=1,
    color="k",
    linestyle=":",
    label=r"$p_{\mathrm{log}}=p_{\mathrm{phys}}$",
)
axis.set_ylabel("logical error rate")
axis.set_xlabel("physical error rate")
axis.loglog()
axis.grid(which="both")
figure.tight_layout()
plt.show()
Parameters:
  • code – The code whose logical state is prepared by the provided state_prep_circuit.

  • state_prep_circuit – A circuit that prepares a logical state of the provided code.

  • error_rates – The error rates at which to evaluate the provided family of noise models.

  • noise_model_family – A single-parameter family of noise models for adding noise to circuits.

Keyword Arguments:
  • post_select – If True, add a flag detector for each unused measurement in the provided circuit and post-select on those detectors. If provided a collection of integers, post-select on corresponding detectors that are already present in the provided circuit.

  • post_select_observables – The observables to post-select on. Any time the decoder’s prediction for these observable flips do not agree with the actual observable flips, the shot is discarded rather than counting as an error.

  • qubit_ids – A QubitIDs object specifying the indices of the data qubits of the code. If None, the data qubits of the code are assumed to be range(len(code)).

  • observables – The observables that should stabilize the prepared state, or (by default) None. If not None, the observables should be either a matrix of symplectic row vectors, with shape (num_observables, 2 * len(code)), or a sequence of Pauli strings supported on the data qubits of the code. If None, observables are determined automatically by finding all logical Pauli operators of the code that stabilize the state prepared by state_prep_circuit.

  • skip_validation – If True, skip the check to assert that the provided circuit prepares a logical state of the provided code.

  • metadata – Extra key-value pairs to attach to the json_metadata of every returned task (merged with the per-task error rate “p”).

Returns:

A list of sinter Tasks, one-to-one with the provided error_rates. The error rate of an

individual task is task.json_metadata[“p”].