Skip to content

Example Workflow

Binder

Here we provide an example of a general workflow where we define a QuantumProgram based on a "codepack" (i.e. prebuilt QECCode object) and an ideal noise model.

QECCode from a Codepack

As always, we begin with our imports. In this example, we are using pyGSTi for our circuits and noise model, and quantumsim for our quantum states, so we import the relevant backends. We also import the relevant codepack, in this case a [[5,1,3]] (a.k.a. 5-qubit) code.

from loqs.backends import QSimQuantumState, PyGSTiNoiseModel, PyGSTiPhysicalCircuit
from loqs.core import QuantumProgram
from loqs.codepacks import codepack_5_1_3_quantinuum2022 as codepack_5_1_3

Creating the QECCode from the codepack is as simple as calling the create_qec_code() function. More complex codepacks could take additional arguments here to customize the resulting QECCode; for example, options could include auxiliary qubit reuse (e.g. Surface-13 vs Surface-17), different syndrome extraction schedules, etc.

In this case, we call the default configuration of the 5-qubit code. Note that there is a single argument called circuit_backend- this determines what circuit backend is used for any physical circuits that are needed. Currently, the default (and only allowed option) is PyGSTiPhysicalCircuit.

code_5q = codepack_5_1_3.create_qec_code(circuit_backend=PyGSTiPhysicalCircuit)

One of the main features of a QECCode is the list of Instruction objects that are available. We can print those out for the 5-qubit codepack and see that we have things like both fault-tolerant (FT) and non-fault-tolerant (non-FT) state preparation, logical gates, and stages for an adaptive measurement scheme. More details on the exact Instruction implementations can be found in the codepack.

list(code_5q.instructions.keys())

Defining a Noise Model

In order to do simulation, we will also need a noise model. For convenience, the codepack also provides an ideal (i.e. noiseless) model with all the operations needed to run the physical circuits in code_5q created above. Users will almost certainly want to provide their own (noisy) models, but this ideal model can serve as a good starting point to check what connectivity/gate set is needed.

Note that as with the create_qec_code() function above, we take a model_backend parameter that in the future will allow users to quickly change out the model backend. Currently, the default (and only allowed option) is PyGSTiNoiseModel.

# Define the physical qubit labels for our system here
qubits = ["A0", "A1"] + [f"D{i+2}" for i in range(5)]

ideal_model = codepack_5_1_3.create_ideal_model(qubits, model_backend=PyGSTiNoiseModel)

Creating an InstructionStack

With our noise model and QEC code specified, we can finally start to create a QuantumProgram.

First, we create a list that will become our InstructionStack. The entries are InstructionLabels, which are really just dicts with the following keys:

  1. "instruction": Either a key into QuantumProgram.global_instructions or a QECCode.instructions (discussed more below) or an actual Instruction object
  2. "patch_label": A patch label
  3. Any other keyword arguments to pass into the Instruction.apply_fn (discussed in the Instruction tutorial)

You'll notice that all of the instruction keys below are strings rather than an Instruction. These are converted into the proper instructions by the QuantumProgram by first looking into QuantumProgram.global_instructions and then in all QECCode.instructions for the given patch (if a patch label is provided).

Three types of instructions are automatically generated in the QuantumProgram.global_instructions based on the state_type and patch_types arguments in QuantumProgram.__init__:

  1. An "Init State" that a state backend object based on the value of state_type
  2. One "Init Patch {patch_key}" for each patch_key in patch_types that can create QECCodePatch objects
  3. An "Remove Patch" instruction that can delete QECCodePatch objects

We use the first two of these autogenerated global instructions to initialize the physical quantum state and a 5Q code patch. The next two instructions act on the patch we have created, and (non-fault-tolerantly) create a logical \(\ket{-}\) state and subsequently measure it in the logical \(X\) basis.

state_type = QSimQuantumState
patch_types = {"5Q": code_5q}

# Stack
# The "Init *" instructions will be generated by the QuantumProgram based on the values
# of state_type and patch_types below
stack = [
    {"instruction": "Init State", "state": len(qubits), "qubit_labels": qubits}, # Autogenerated from state_type
    {"instruction": "Init Patch 5Q", "new_patch_label": "L0", "qubits": qubits}, # Autogenerated from patch_types. Note that 5Q here must be a key into the patch_types dict below
    ("Non-FT Minus Prep", "L0"), # (instruction, patch_label) 2-tuple shorthand for {"instruction": ..., "patch_label": ...} when there are no other kwargs
    ("Non-FT Logical X Measure", "L0")
]

Creating a QuantumProgram

Finally, we can combine our stack, noise model, and state/patch types. We also give the program a name for better logging.

program = QuantumProgram(
    stack,
    default_noise_model=ideal_model,
    state_type=state_type,
    patch_types=patch_types,
    name="Prep minus, measure X"
)

Running a QuantumProgram

We execute the program by calling the run() function. In this case, let's run it more than once - we can run it 20 times by specifying num_shots=20 to the run() function.

run() returns a ProgramResults object, so we need to capture that return value to look at what happened during execution.

# And now we can run it for real!
results = program.run(num_shots=20)

The individual History objects are now available in the results.shot_histories member variable, a dict keyed by (non-negative) shot index -- so unlike a list, negative indices like -1 aren't supported.

Wall-clock timing information for each shot is also available in results.shot_wall_clock_times, which maps shot index to execution duration in seconds.

# Show the wall-clock timing for each shot
results.shot_wall_clock_times

For example, we could print out the History corresponding to the last shot just to get a sense for what this object looks like.

last_shot = max(results.shot_histories)
print(results.shot_histories[last_shot])

This is a bit unwieldy to parse all the text, so we can instead ask LoQS to display the object in an interactive viewer.

results.shot_histories[last_shot].display()

While this is handy for looking at the details of a specific shot, we are often more interested in some collective result. In this case, we may be interested in the "logical_measurement" element of the final Frame.

We can collect these using the collect_shot_data() function on our results, where we specify a Frame key and a set of indices into the History for which frames to target (in this case, we are only interested in the final frame so use -1.)

This will return a list of 20 entries (one per shot), so we instead use a Counter collection to look at how many of these are 0 or 1.

from collections import Counter

# collect_shot_data lets us pull out keys from the histories of every shot
# In this case, we pull logical_measurement from the last frame (-1) of each shot
# We pass it into Counter to get more convenient 0/1 counts
Counter(results.collect_shot_data("logical_measurement", -1))

# Because we prepped logical minus and did a logical X measurement, we expect to get all 1s here

As expected, because we performed a logical \(\ket{-}\) measurement and then measured in the \(X\) basis, we are determinstically in the -1 eigenstate of the \(X\) basis (as indicated by a measurement outcome of 1).

Running with a new InstructionStack

We may commonly want to use the same QuantumProgram, but run on a new InstructionStack.

The QuantumProgram.from_quantum_program() class method is designed for this purpose, where we want to copy a QuantumProgram but swap out some of the components. In this case we are only replacing the stack and name, but you can also change the underlying state or patch types, noise model, RNG seed, etc.

# Make a version that goes to logical 0 and measures in Z
stack = [
    {"instruction": "Init State", "state": len(qubits), "qubit_labels": qubits}, # Autogenerated from state_type
    {"instruction": "Init Patch 5Q", "new_patch_label": "L0", "qubits": qubits}, # Autogenerated from patch_types. Note that 5Q here must be a key
    ("Non-FT Minus Prep", "L0"),
    ("H", "L0"), # Rotate to logical Z basis
    ("X", "L0"), # Flip from -1 eigenstate to +1 eigenstate
    ("Non-FT Logical Z Measure", "L0")
]

# We want to use the same program settings, just swap out the stack and name
program2 = QuantumProgram.from_quantum_program(program, stack, name="Prep 0, measure Z")

results2 = program2.run(num_shots=20)

Counter(results2.collect_shot_data("logical_measurement", -1))

Seeding RNG for Undeterminate Measurement Outcomes

The previous programs were all determinate outcome circuits; however, it is more often the case that any measurements will probabilistically return 0 or 1. In this case, it is often a good practice to seed the random number generation (RNG) for these operations such that programs can be done reproducibly.

We show one such usage here.

# Now let's stay in minus but measure in Z
stack = [
    {"instruction": "Init State", "state": len(qubits), "qubit_labels": qubits}, # Autogenerated from state_type
    {"instruction": "Init Patch 5Q", "new_patch_label": "L0", "qubits": qubits}, # Autogenerated from patch_types. Note that 5Q here must be a key
    ("Non-FT Minus Prep", "L0"),
    ("Non-FT Logical Z Measure", "L0")
]

# This one will be non-determinate outcome. Let's seed the RNG
program3 = QuantumProgram.from_quantum_program(program, stack, default_base_seed=20240702, name="Prep -, measure Z")

results3 = program3.run(num_shots=150) # Let's also collect more statistics!

Counter(results3.collect_shot_data("logical_measurement", -1))

And now we create a copy of this program (i.e. it has the same base seed since we are not updating it) to demonstrate that we get the exact same counts out.

# And now we can show that it's deterministic counts with the same RNG seed
program4 = QuantumProgram.from_quantum_program(program3, name="Prep -, measure Z... again")

results4 = program4.run(num_shots=150) # Let's also collect more statistics!

Counter(results4.collect_shot_data("logical_measurement", -1))

Saving a QuantumProgram and its ProgramResults

Any object that is derived from loqs.internal.Serializable can be easily serialized with the following API:

  • to_serialization: This usually returns a dict that is JSON-able.
  • dumps: Similar to json.dumps, it is a string version of the output of to_serializable.
  • dump: Similar to json.dump, this writes the output of to_serializable to a file pointer.
  • write: Similar to dump, but it takes a filename/path instead. This is likely to be the most commonly used serialization function.

Deserialization is just as simple, and follows a similar API with reverse functions: from_serialization creates the object from a JSON-able dict, loads creates the object from the string version of the dict, load creates the object from a file pointer, and read creates the object from a filename/path.

Note that a QuantumProgram and its ProgramResults (the object returned by run()) are serialized independently of one another: a QuantumProgram only stores the definition of the program (its instruction stack, noise model, RNG seed, etc.), not any shot data, while a ProgramResults only stores the shot histories (plus a reference back to the program that produced them). So if you want to persist both the program and its results, you need to save both objects.

# Note that this can take some time (~10 seconds)
# Currently 14 MB uncompressed
program4.write('test.json')
program5 = QuantumProgram.read('test.json')

Because program4 was created with a fixed default_base_seed, re-running the deserialized program5 reproduces exactly the same shot outcomes, demonstrating that the program definition round-tripped correctly through serialization.

results5 = program5.run(num_shots=150)

# Same counts as results4 above, since program5 has the same instruction stack, noise model, and RNG seed
Counter(results5.collect_shot_data("logical_measurement", -1))

If instead you want to persist the results themselves (so you don't have to re-run the program to get the same shot data back), serialize the ProgramResults object directly.

results4.write('test-results.json')
from loqs.core import ProgramResults

reloaded_results4 = ProgramResults.read('test-results.json')

# And we still have all our original shot histories, with no need to re-run anything
Counter(reloaded_results4.collect_shot_data("logical_measurement", -1))

Checkpointing QuantumProgram execution

We can also checkpoint the execution of a QuantumProgram as it runs, writing completed shots to disk in batches. This is done by passing checkpoint=True to run(), along with checkpoint_batch_size (how many shots to accumulate before writing a checkpoint file) and checkpoint_dir (where to write them) -- checkpoint_batch_size/checkpoint_dir alone do not enable checkpointing without checkpoint=True.

Note that enabling checkpointing will add some file I/O overhead to every checkpointed batch. For the small jobs being run here, it is noticeable; for larger jobs where you would like to checkpoint, it should be less of a factor.

program6 = QuantumProgram.from_quantum_program(program3, name="Prep -, measure Z... again")

# Checkpoint every 30 shots to the given directory
results6 = program6.run(num_shots=150, checkpoint=True, checkpoint_batch_size=30, checkpoint_dir="test-checkpoint")

If a run is interrupted partway through (e.g. a crash, or a manual Ctrl-C), the shots that were already checkpointed to disk are not lost. We can recover them by constructing a fresh ProgramResults and pointing load_checkpoint() at the checkpoint directory.

recovered_results6 = ProgramResults()
recovered_results6.load_checkpoint(checkpoint_dir="test-checkpoint")

len(recovered_results6.shot_histories)

A shot checkpoint keeps every key of every frame except the quantum state, which reads back as "NOT SERIALIZED". A dense state is most of a checkpoint file, so by default a QuantumProgram built without a History leaves it out. To keep the final state, pass an initial History, which is used as given and saves everything.

from loqs.core import History

# A History is used as given, so this one saves every key, the state included
program7 = QuantumProgram(
    stack,
    initial_history=History([]),
    default_noise_model=ideal_model,
    state_type=state_type,
    patch_types=patch_types,
    name="Prep -, measure Z... keeping state"
)

A checkpointed run whose History keeps the state warns that every shot checkpoint will hold it. To silence the warning on purpose, use warnings.filterwarnings("ignore", message=".*no_serialize_keys.*").

Note

run() also supports genuine resume: calling it again with checkpoint=True, resume=True against the same checkpoint_dir picks up right where an interrupted run left off, computing only the shots not yet checkpointed rather than starting over from 0 (pass force_resume=True if the resuming call's own num_shots/max_frame_limit/RNG seed intentionally differ from the original -- otherwise a mismatch raises ValueError). Checkpointing is also useful even without resuming, for (a) not losing already-completed shots if a long run is interrupted, and (b) collecting results from multiple parallel workers (see the worker_id argument of ProgramResults.checkpoint).