See also

A Jupyter notebook version of this tutorial can be downloaded here.

Randomized benchmarking#

This application example is qubit type agnostic, i.e. it can be applied for any type of qubit (e.g. transmon, spin, etc.).

For demonstration, we will assume that the qubit type is flux-tunable transmon.

The experiments can also be executed using a dummy Qblox device that is created via an instance of the Cluster class, and is initialized with a dummy configuration. However, when using a dummy device, the analysis will not work because the experiments will return np.nan values.

Hardware setup#

In this section we configure the hardware configuration which specifies the connectivity of our system.

Configuration file#

We will load a template hardware configuration file for a 2-qubit system (we name the qubits q0 and q1), with dedicated flux-control lines.

The hardware connectivity is as follows, by cluster slot:

  • QCM (Slot 2)

    • \(\text{O}^{1}\): Flux line for q0.

    • \(\text{O}^{2}\): Flux line for q1.

  • QCM-RF (Slot 6)

    • \(\text{O}^{1}\): Drive line for q0 using fixed 80 MHz IF.

    • \(\text{O}^{2}\): Drive line for q1 using fixed 80 MHz IF.

  • QRM-RF (Slot 8)

    • \(\text{O}^{1}\) and \(\text{I}^{1}\): Shared readout line for q0/q1 using a fixed LO set at 7.5 GHz.

Note that in the hardware configuration below the mixers are uncorrected, but for high fidelity experiments this should also be done for all the RF modules.

[1]:
from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
from pycqed_randomized_benchmarking.randomized_benchmarking import randomized_benchmarking_sequence
from pycqed_randomized_benchmarking.two_qubit_clifford_group import (
    SingleQubitClifford,
    TwoQubitClifford,
    common_cliffords,
)
from qcodes import ManualParameter

from quantify_scheduler import Schedule, ScheduleGettable
from quantify_scheduler.backends.qblox.constants import MIN_TIME_BETWEEN_OPERATIONS
from quantify_scheduler.operations import CZ, X90, Y90, Measure, Reset, Rxy, X, Y

if TYPE_CHECKING:
    from collections.abc import Iterable
import json

import rich  # noqa:F401

import quantify_core.data.handling as dh
from quantify_scheduler import QuantumDevice

from utils import initialize_hardware, run  # noqa:F401
Generating Clifford hash tables.
Successfully generated Clifford hash tables.
[2]:
hw_config_path = "configs/tuning_transmon_coupled_pair_hardware_config.json"
device_path = "devices/transmon_device_2q.json"
[3]:
with open(hw_config_path) as hw_cfg_json_file:
    hardware_cfg = json.load(hw_cfg_json_file)

# Enter your own dataset directory here!
dh.set_datadir(dh.default_datadir())
Data will be saved in:
/root/quantify-data
[4]:
quantum_device = QuantumDevice.from_json_file(device_path)
qubit = quantum_device.get_element("q0")
quantum_device.hardware_config(hardware_cfg)
meas_ctrl, _, cluster = initialize_hardware(quantum_device, ip=None)

Setup#

In this section we configure the hardware configuration which specifies the connectivity of our system.

The experiments of this tutorial are meant to be executed with a Qblox Cluster controlling a transmon system. The experiments can also be executed using a dummy Qblox device that is created via an instance of the Cluster class, and is initialized with a dummy configuration. When using a dummy device, the analysis will not work because the experiments will return np.nan values.

Configuration file#

This is a template hardware configuration file for a 2-qubit system with a flux-control line which can be used to tune the qubit frequency. We will only work with qubit 0.

The hardware connectivity is as follows, by cluster slot:

  • QCM (Slot 2)

    • \(\text{O}^{1}\): Flux line for q0.

    • \(\text{O}^{2}\): Flux line for q1.

  • QCM-RF (Slot 6)

    • \(\text{O}^{1}\): Drive line for q0 using fixed 80 MHz IF.

    • \(\text{O}^{2}\): Drive line for q1 using fixed 80 MHz IF.

  • QRM-RF (Slot 8)

    • \(\text{O}^{1}\) and \(\text{I}^{1}\): Shared readout line for q0/q1 using a fixed LO set at 7.5 GHz.

Note that in the hardware configuration below the mixers are uncorrected, but for high fidelity experiments this should also be done for all the modules.

Quantum device settings#

Here we initialize our QuantumDevice and our qubit parameters, checkout this tutorial for further details.

In short, a QuantumDevice contains device elements where we save our found parameters. Here we are loading a template for 2 qubits, but we will only use qubit 0.

[5]:
q0 = quantum_device.get_element("q0")
q1 = quantum_device.get_element("q1")

Configure external flux control#

We need to have some way of controlling the external flux.

This can be done by setting an output bias on a module of the cluster which is then connected to the flux-control line.

Here we are nullifying the external flux on both qubits.

[6]:
flux_settables = {q0.name: cluster.module2.out0_offset, q1.name: cluster.module2.out1_offset}

for flux_settable in flux_settables.values():
    flux_settable.inter_delay = 100e-9  # Delay time in seconds between consecutive set operations.
    flux_settable.step = 0.3e-3  # Stepsize in V that this Parameter uses during set operation.
    flux_settable()  # Get before setting to avoid jumps.
    flux_settable(0.0)
[7]:
flux_settables[q0.name](0.0)  # enter your own value here for qubit 0
flux_settables[q1.name](0.0)  # enter your own value here for qubit 1

Experiment#

[8]:
def randomized_benchmarking_schedule(
    qubit_specifier: str | Iterable[str],
    lengths: Iterable[int],
    desired_net_clifford_index: int | None = common_cliffords["I"],
    seed: int | None = None,
    repetitions: int = 1,
) -> Schedule:
    """
    Generate a randomized benchmarking schedule.

    All Clifford gates in the schedule are decomposed into products
    of the following unitary operations:

        {'CZ', 'I', 'Rx(pi)', 'Rx(pi/2)', 'Ry(pi)', 'Ry(pi/2)', 'Rx(-pi/2)', 'Ry(-pi/2)'}

    Parameters
    ----------
    qubit_specifier
        String or iterable of strings specifying which qubits to conduct the
        experiment on. If one name is specified, then single qubit randomized
        benchmarking is performed. If two names are specified, then two-qubit
        randomized benchmarking is performed.
    lengths
        Array of non-negative integers specifying how many Cliffords
        to apply before each recovery and measurement. If lengths is of size M
        then there will be M recoveries and M measurements in the schedule.
    desired_net_clifford_index
        Optional index specifying what the net Clifford gate should be. If None
        is specified, then no recovery Clifford is calculated. The default index
        is 0, which corresponds to the identity gate. For a map of common Clifford
        gates to Clifford indices, please see: two_qubit_clifford_group.common_cliffords
    seed
        Optional random seed to use for all lengths m. If the seed is None,
        then a new seed will be used for each length m.
    repetitions
        Optional positive integer specifying the amount of times the
        Schedule will be repeated. This corresponds to the number of averages
        for each measurement.

    """
    # ---- Error handling and argument parsing ----#
    lengths = np.asarray(lengths, dtype=int)

    if isinstance(qubit_specifier, str):
        qubit_names = [qubit_specifier]
    else:
        qubit_names = [q for q in qubit_specifier]

    n = len(qubit_names)
    if n not in (1, 2):
        raise ValueError("Only single and two-qubit randomized benchmarking supported.")
    if len(set(qubit_names)) != n:
        raise ValueError("Two-qubit randomized benchmarking on the same qubit is ill-defined.")

    # ---- PycQED mappings ----#
    pycqed_qubit_map = {f"q{idx}": name for idx, name in enumerate(qubit_names)}
    pycqed_operation_map = {
        "X180": lambda q: X(pycqed_qubit_map[q]),
        "X90": lambda q: X90(pycqed_qubit_map[q]),
        "Y180": lambda q: Y(pycqed_qubit_map[q]),
        "Y90": lambda q: Y90(pycqed_qubit_map[q]),
        "mX90": lambda q: Rxy(qubit=pycqed_qubit_map[q], phi=0.0, theta=-90.0),
        "mY90": lambda q: Rxy(qubit=pycqed_qubit_map[q], phi=90.0, theta=-90.0),
        "CZ": lambda q: CZ(qC=pycqed_qubit_map[q[0]], qT=pycqed_qubit_map[q[1]]),
    }

    # ---- Build RB schedule ----#
    sched = Schedule(
        "Randomized benchmarking on " + " and ".join(qubit_names), repetitions=repetitions
    )
    clifford_class = [SingleQubitClifford, TwoQubitClifford][n - 1]

    # two-qubit RB needs buffer time for phase corrections on drive lines
    operation_buffer_time = [0.0, MIN_TIME_BETWEEN_OPERATIONS * 4e-9][n - 1]

    for idx, m in enumerate(lengths):
        sched.add(Reset(*qubit_names))
        if m > 0:
            # m-sized random sample of representatives in the quotient group C_n / U(1)
            # where C_n is the n-qubit Clifford group and U(1) is the circle group
            rb_sequence_m: list[int] = randomized_benchmarking_sequence(
                m, number_of_qubits=n, seed=seed, desired_net_cl=desired_net_clifford_index
            )

            for clifford_gate_idx in rb_sequence_m:
                cl_decomp = clifford_class(clifford_gate_idx).gate_decomposition

                operations = [
                    pycqed_operation_map[gate](q) for (gate, q) in cl_decomp if gate != "I"
                ]

                for op in operations:
                    sched.add(op, rel_time=operation_buffer_time)

        sched.add(Measure(*qubit_names, acq_index=idx))

    return sched

Single qubit RB example#

[9]:
length = ManualParameter(name="length", unit="#", label="Number of Clifford gates")
length.batched = True
length.batch_size = 10

rb_sched_kwargs = {"qubit_specifier": q0.name, "lengths": length}

gettable = ScheduleGettable(
    quantum_device,
    schedule_function=randomized_benchmarking_schedule,
    schedule_kwargs=rb_sched_kwargs,
    real_imag=False,
    batched=True,
    num_channels=1,
)
meas_ctrl.gettables(gettable)
[10]:
length_setpoints = np.arange(0, 100, 2)

meas_ctrl.settables(length)
meas_ctrl.setpoints(length_setpoints)

quantum_device.cfg_sched_repetitions(200)
rb_ds = meas_ctrl.run("Randomized benchmarking on " + rb_sched_kwargs["qubit_specifier"])
rb_ds
Starting batched measurement...
Iterative settable(s) [outer loop(s)]:
         --- (None) ---
Batched settable(s):
         length
Batch size limit: 10

[10]:
<xarray.Dataset> Size: 1kB
Dimensions:  (dim_0: 50)
Coordinates:
    x0       (dim_0) int64 400B 0 2 4 6 8 10 12 14 ... 84 86 88 90 92 94 96 98
Dimensions without coordinates: dim_0
Data variables:
    y0       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
    y1       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
Attributes:
    tuid:                             20250114-023609-474-c8c2f2
    name:                             Randomized benchmarking on q0
    grid_2d:                          False
    grid_2d_uniformly_spaced:         False
    1d_2_settables_uniformly_spaced:  False

Two qubit RB example#

[11]:
length = ManualParameter(name="length", unit="#", label="Number of Clifford gates")
length.batched = True
length.batch_size = 10

rb_sched_kwargs = {"qubit_specifier": [q0.name, q1.name], "lengths": length}

gettable = ScheduleGettable(
    quantum_device,
    schedule_function=randomized_benchmarking_schedule,
    schedule_kwargs=rb_sched_kwargs,
    real_imag=False,
    batched=True,
    num_channels=2,
)
meas_ctrl.gettables(gettable)
[12]:
length_setpoints = np.arange(0, 100, 2)

meas_ctrl.settables(length)
meas_ctrl.setpoints(length_setpoints)

quantum_device.cfg_sched_repetitions(200)
rb_ds = meas_ctrl.run(
    "Randomized benchmarking on " + " and ".join(rb_sched_kwargs["qubit_specifier"])
)
rb_ds
Starting batched measurement...
Iterative settable(s) [outer loop(s)]:
         --- (None) ---
Batched settable(s):
         length
Batch size limit: 10

[12]:
<xarray.Dataset> Size: 2kB
Dimensions:  (dim_0: 50)
Coordinates:
    x0       (dim_0) int64 400B 0 2 4 6 8 10 12 14 ... 84 86 88 90 92 94 96 98
Dimensions without coordinates: dim_0
Data variables:
    y0       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
    y1       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
    y2       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
    y3       (dim_0) float64 400B nan nan nan nan nan ... nan nan nan nan nan
Attributes:
    tuid:                             20250114-023611-485-12b2ac
    name:                             Randomized benchmarking on q0 and q1
    grid_2d:                          False
    grid_2d_uniformly_spaced:         False
    1d_2_settables_uniformly_spaced:  False
[13]:
rich.print(quantum_device.hardware_config())
{
    'config_type': 'quantify_scheduler.backends.qblox_backend.QbloxHardwareCompilationConfig',
    'hardware_description': {
        'cluster0': {
            'instrument_type': 'Cluster',
            'modules': {
                '6': {'instrument_type': 'QCM_RF'},
                '2': {'instrument_type': 'QCM'},
                '8': {'instrument_type': 'QRM_RF'}
            },
            'sequence_to_file': False,
            'ref': 'internal'
        }
    },
    'hardware_options': {
        'output_att': {'q0:mw-q0.01': 10, 'q1:mw-q1.01': 10, 'q0:res-q0.ro': 60, 'q1:res-q1.ro': 60},
        'mixer_corrections': {
            'q0:mw-q0.01': {
                'auto_lo_cal': 'on_lo_interm_freq_change',
                'auto_sideband_cal': 'on_interm_freq_change'
            },
            'q1:mw-q1.01': {
                'auto_lo_cal': 'on_lo_interm_freq_change',
                'auto_sideband_cal': 'on_interm_freq_change'
            },
            'q0:res-q0.ro': {
                'auto_lo_cal': 'on_lo_interm_freq_change',
                'auto_sideband_cal': 'on_interm_freq_change'
            },
            'q1:res-q1.ro': {
                'auto_lo_cal': 'on_lo_interm_freq_change',
                'auto_sideband_cal': 'on_interm_freq_change'
            }
        },
        'modulation_frequencies': {
            'q0:mw-q0.01': {'interm_freq': 80000000.0},
            'q1:mw-q1.01': {'interm_freq': 80000000.0},
            'q0:res-q0.ro': {'lo_freq': 7500000000.0},
            'q1:res-q1.ro': {'lo_freq': 7500000000.0}
        }
    },
    'connectivity': {
        'graph': [
            ['cluster0.module6.complex_output_0', 'q0:mw'],
            ['cluster0.module6.complex_output_1', 'q1:mw'],
            ['cluster0.module2.real_output_0', 'q0:fl'],
            ['cluster0.module2.real_output_1', 'q1:fl'],
            ['cluster0.module8.complex_output_0', 'q0:res'],
            ['cluster0.module8.complex_output_0', 'q1:res']
        ]
    }
}
[14]:
quantum_device.to_json_file("devices/")
[14]:
'devices/device_2q_2025-01-14_02-36-19_UTC.json'