Time-Dependent and Updateable Models¶
Playground for time-dependent/updateable model work.
from collections import Counter
import loqs
from loqs.backends import PyGSTiPhysicalCircuit, PyGSTiNoiseModel, QSimQuantumState
from loqs.core import QuantumProgram, History
from loqs.core.recordables import PatchLayout
from loqs.codepacks import codepack_5_1_3_quantinuum2022 as codepack_5_1_3
Time-Independent "Standard" Workflow¶
Working with time-dependent models requires a few modifications to the normal workflow. To see the differences, first let's see the "bog standard" workflow for time-independent models.
code_5q = codepack_5_1_3.create_qec_code()
qubits = ["A0", "A1"] + [f"D{i+2}" for i in range(5)]
ideal_model = codepack_5_1_3.create_ideal_model(qubits)
# 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"),
("Non-FT Logical X Measure", "L0")
]
program = QuantumProgram(
instruction_stack=stack,
initial_history=None,
default_noise_model=ideal_model,
state_type=QSimQuantumState,
patch_types={"5Q": code_5q},
name="Time-independent program"
)
A few note-worthy things about how we constructed this program:
- We are not providing an initial
History. This has a few ramifications:- Instead, the objects like the quantum state and QEC patch are being built by the first few instructions in the
stackvariable. - We also have to tell the program what objects to use for those using
state_typeandpatch_types.
- Instead, the objects like the quantum state and QEC patch are being built by the first few instructions in the
- We are providing the noise model only with
default_noise_model. This is usually fine behavior, and is actually not a deal-breaker for time-dependent but not updateable model. If we want to update the model though, it needs to be available in each Frame instead.
results = program.run(10)
Counter(results.collect_shot_data("logical_measurement", -1))
Alternate but equivalent "standard" workflow¶
Here, we make some adjustments to run a completely equivalent program to above, but I'll show how this version will be easier to convert into a program with a calibration-capable noise model shortly.
The crux of the difference is that we want to make the model an "expiring" and "propogated" key in the Frame rather than be stored in the QuantumProgram. See the relevant documentation in the History tutorial, but the general thought process here:
- It should be "expired" because we will keep one copy of the model whose time gets updated, so previous Frames will hold a stale reference to the model that we want to highlight to the user.
- It should be propagated because we always want the current model to be in the last Frame.
While we are making a custom History with the model set up like we need, we might as well shift the other initialization steps too to the initial History as well.
code_5q = codepack_5_1_3.create_qec_code()
qubits = ["A0", "A1"] + [f"D{i+2}" for i in range(5)]
ideal_model = codepack_5_1_3.create_ideal_model(qubits)
# {"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
# NEW: Create an initial History
initial_history = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits), # Created by our first instruction above
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}), # Created by our second instruction above
"model": ideal_model # Taking the place of default_noise_model above
},
expiring_keys=["state", "model"], # Usually this is just "state"
propagating_keys=["state", "patches", "model"] # Usually this is just "state" and "patches"
)
# New stack
# Note that this is now just logical qubit operations
stack = [
("Non-FT Minus Prep", "L0"),
("Non-FT Logical X Measure", "L0")
]
# New program
# Note that all the information is now bundled into the initial history
program2 = QuantumProgram(
instruction_stack=stack,
initial_history=initial_history,
name="Time-independent program variant"
)
results2 = program2.run(10)
Counter(results2.collect_shot_data("logical_measurement", -1))
Using a time-dependent model¶
With all the LoQS basics covered for using time-dependent/updateable models, we can start to actually play with some time-dependent models.
First, let's just make our model time-dependent and set some default durations for all our gates. We would normally do this in the nosie model constructor, but we can modify one on the fly as well. Currently, only the PyGSTiNoiseModel supports time-dependent operations, so we ensure that our starting noise model uses this backend.
# PyGSTiNoiseModel is currently the default, but this future-proofs us
qubits = ["A0", "A1"] + [f"D{i+2}" for i in range(5)]
model_td1 = codepack_5_1_3.create_ideal_model(qubits, model_backend=PyGSTiNoiseModel)
# To use time-dependence with PyGSTi-based models, we need to turn on the use_time_dependence flag
model_td1.use_time_dependence = True
initial_history_td1 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td1 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
td_test_stack = [
("Non-FT Minus Prep", "L0"),
# Let's add a idle gates so we can see mess with errors on a gate later
("I", "L0"),
("Non-FT Logical X Measure", "L0")
]
# New program
# Note that all the information is now bundled into the initial history
program_td1 = QuantumProgram(
instruction_stack=td_test_stack,
initial_history=initial_history_td1,
name="Technically time-dependent (but boring) program"
)
program_td1.run(10)
Oh no! What happened?
Well, under the hood, the model is trying to compute the time of each gate/layer and update its current_time variable. However, in order to do that, it needs to know how long each gate takes. If you are using the pyGSTi circuit backend with labels that include a time entry (i.e. the label is a LabelTupWithTime), it can take the time from there. We are using the pyGSTi circuit backend, but we have not specified any times.
The fallback is to use the default_gate_durations and default_instrument_durations dictionaries to look up the durations, but we have not provided those either! Let's fix that.
# We can instead just provide defaults by name instead of (name, qubit) Label
# Let's say that all all Z gates take 0 units of time because they are done virtually,
# 1Q gates take 1 unit of time, 2Q gates take 10 units of time, and measurements take 100 units of time
model_td1.default_gate_durations = {
"Gzpi": 0,
"Gzpi2": 0,
"Gzmpi2": 0,
"Gi": 1,
"Gi1Q": 1,
'Gxpi': 1,
'Gypi': 1,
'Gh': 1,
'Gk': 1,
'Gi2Q': 10,
'Gcnot': 10,
'Gcphase': 10,
'GiMCM': 100
}
model_td1.default_instrument_durations = {
"Imrz": 100
}
# And let's try to run the program again
results_td1 = program_td1.run(10)
Counter(results_td1.collect_shot_data("logical_measurement", -1))
Ok, but how do we know whether this actually did anything different yet?
Well, internally the model has been keeping track of the time, even though none of our operations use that yet. When a time-dependent model is used, we also print the current simulation time at the end of each instruction to the Frame.
results_td1.collect_shot_data("current_model_time", "all")
How do we interpret this? Well each list is for one shot, and the entry of each list is the value of "current_model_time" at that Frame. Some of the entries are None because these do not correspond to physical circuit instructions. (It's not that important, but specifically the first entry is our initial History frame where we obviously did not set the time, the third to last entry is the Non-FT Logical X Measure instruction getting split into the decoding circuit [the second to last entry] and the parity computation for the logical measurement [last entry]).
As for the time entries, we can also double-check this. The encoding circuit is a layer of H followed by three layers of CZ gates (1 + 3*10 = 31), the I gate is a 1-qubit idle gate layer adding 1 time unit, and the non-FT logical measure is a 1Q gate layer, a layer of Z gates, a layer of H, and the measurement (1 + 0 + 1 + 100 = 102).
We can verify that this is indeed a property of programs that contain time-dependent models by checking this for one of our time-independent models.
results.collect_shot_data("current_model_time", "all")
An actual time-dependent operation¶
Now we have a "time-dependent" model, in that it is tracking the time as the simulation moves forward. But now let's actually make a model where one of the operations is affected by this.
For this dummy example, let's make it so that the 1Q gate idle on data qubit D2 flips back and forth between an I and an X every 134 time units. If we did this and ran multiple prep -> I -> meas cycles in the same program, we expect the alternate between having a correct logical outcome and a logical error.
But how do we actually define this operation? We can define our own custom PyGSTi operation. There are multiple ways to do this, but here we just extend the DenseOperator class with two key differences:
- We define a non-trivial
set_time()function that updates some internal noise parameter. - We actually use that internal noise parameter when building our operator.
(For advanced PyGSTi users, OperationFactories are also a common way to do a similar thing. The difference is that an OpFactory takes arguments from the Circuit label to generate the representation. In this case, we don't need to do that -- the model is feeding us the time via set_time() so we don't need any additional information.)
A note on constructing custom operators: Some pyGSTi versions (see pyGSTi issue #543) have a bug where wrapping a custom operator like this in an EmbeddedOp (which we do below, to place it on a specific qubit within our larger multi-qubit model) can cause pyGSTi to allocate a dense representation sized to the entire model's state space, rather than a small representation local to the embedded operator. For a model with more than a handful of qubits, this can mean allocating many GB of memory for what should be a trivial single-qubit operator! To avoid this, we construct our operator's evotype explicitly via safe_time_dependent_evotype below, rather than passing the bare string "densitymx" -- this sidesteps the bug regardless of which pyGSTi version you're using.
from copy import deepcopy
import numpy as np
import pygsti
from pygsti.baseobjs import Label
from pygsti.modelmembers.operations import DenseOperator, EmbeddedOp
from loqs.backends import safe_time_dependent_evotype
class FlippingIdle(DenseOperator):
"""An idle that gets an X(pi) rotation applied every 134 units."""
def __init__(self):
# Initialize in identity as a PTM (superoperator in Pauli Product basis)
super().__init__(np.identity(4,'d'), pygsti.BuiltinBasis("pp", 4), safe_time_dependent_evotype("densitymx"))
self.set_time(0.0)
@property
def num_params(self):
return 0
def set_time(self,t):
current_cycle = t % (2*134)
print("Setting time")
if current_cycle < 135:
# We are in the "I" part of the cycle
print("Setting I")
self._ptr[:,:] = np.eye(4)
else:
# We are in the "X" part of the cycle
print("Setting X")
self._ptr[:,:] = pygsti.unitary_to_pauligate(pygsti.sigmax)
self._ptr_has_changed()
flipping_idle = FlippingIdle()
model_td2 = deepcopy(model_td1)
# Currently, PyGSTi doesn't like qubit labels that don't start with Q so we have some minor aliasing to do
D2_qubit = model_td2.model_qubit_aliases["D2"]
model_td2.gate_dict[Label("Gi", D2_qubit)] = EmbeddedOp(model_td2.model.state_space, [D2_qubit], flipping_idle)
model_td2.current_time = 0
reps = model_td2.get_reps(PyGSTiPhysicalCircuit([("Gi", "D2")]), gatereps=[loqs.backends.QSimSuperopGateRep], instreps=[loqs.backends.ZBasisProjectionInstrumentRep])
pygsti.print_mx(reps[0].superop)
# Let's try after our supposed flip
model_td2.current_time = 135
reps = model_td2.get_reps(PyGSTiPhysicalCircuit([("Gi", "D2")]), gatereps=[loqs.backends.QSimSuperopGateRep], instreps=[loqs.backends.ZBasisProjectionInstrumentRep])
pygsti.print_mx(reps[0].superop)
# Remember to set back to 0 for simulation
model_td2.current_time = 0
initial_history_td2 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td2 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
stack_td2 = [
# Cycle 1, we expect it to be correct
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0"),
# Cycle 2, should flip
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0"),
# Cycle 3, should flip to be correct again
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0"),
# Cycle 2, should flip
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0"),
]
# New program
# Note that all the information is now bundled into the initial history
program_td2 = QuantumProgram(
instruction_stack=stack_td2,
initial_history=initial_history_td2,
name="Technically time-dependent (but boring) program"
)
results_td2 = program_td2.run(1)
results_td2.collect_shot_data("logical_measurement", "all", strip_none_entries=True)
A more interesting time-dependent operation¶
So that is working but obviously it's not a very realistic model. Let's try another model that is slightly more realistic. Let's say that the idle gate on D2 is really a slight X rotation, i.e. it has an X overrotation error. The rate won't change, but as time goes on, the gate will cycle through X(pi/2), X(pi), X(3pi/2) = X(-pi/2), and back to I. We'll actually set the period here to be 8*134 so that we can see the idle in increments of X(pi/4).
We'll also set this overrotation error rate as an internal parameter. Doing it this way means that there will be a parameter for us to tune later!
import scipy.linalg as sla
class XRotatingIdle(DenseOperator):
"""An idle that has an X overrotation."""
def __init__(self, overrot_period, overrot_shift):
# Initialize in identity as a PTM (superoperator in Pauli Product basis)
# As before, we construct the evotype via safe_time_dependent_evotype to
# avoid a pyGSTi bug when this operator is later embedded into our
# larger multi-qubit model (see the note above).
super().__init__(np.identity(4,'d'), pygsti.BuiltinBasis("pp", 4), safe_time_dependent_evotype("densitymx"))
# Initialize our parameters
self.overrot_period = overrot_period
self.overrot_shift = overrot_shift
self.set_time(0.0)
# Let's also add labels so we can tell what these are later
# The order of these should match the order returned in to_vector()
self._paramlbls = [
"Rotating idle period",
"Rotating idle shift",
]
@property
def num_params(self):
return 2 # We now have two parameters
# Now that we have a parameter, we also need to implement to/from vector
# This gives the model the handle it needs to update this parameter
def to_vector(self):
return np.array([self.overrot_period, self.overrot_shift],'d') #our parameter vector
def from_vector(self, v, close=False, dirty_value=True):
#initialize from parameter vector v
self.overrot_period = v[0]
self.overrot_shift = v[1]
self.dirty = dirty_value
def set_time(self,t):
angle = 2*(t-self.overrot_shift)/self.overrot_period
U_rot = sla.expm(-1j*np.pi*angle/2*pygsti.sigmax)
self._ptr[:, :] = pygsti.unitary_to_pauligate(U_rot)
self._ptr_has_changed()
xrot_8cycle_idle = XRotatingIdle(134*8, 31)
# At t=31, we should be an I
xrot_8cycle_idle.set_time(31)
pygsti.print_mx(xrot_8cycle_idle.to_dense())
# At t=31+134*2, we should be an X(pi/2)
xrot_8cycle_idle.set_time(31+134*2)
pygsti.print_mx(xrot_8cycle_idle.to_dense())
# This is in fact an X(pi/2) gate. Recall this is a PTM, so we leave I and X unchanged (commute with X rotation),
# but send Y to Z and Z to -Y, i.e. rotate a quarter turn clockwise around the X axis.
# At t=31+134*4, we should be an X(pi)
xrot_8cycle_idle.set_time(31+134*4)
pygsti.print_mx(xrot_8cycle_idle.to_dense())
# Again, I and X are unchanged, while Y and Z get sent to negative versions of themselves,
# i.e. a half turn around the X axis.
# At t=31+134*8, we should be an I again
xrot_8cycle_idle.set_time(31+134*8)
pygsti.print_mx(xrot_8cycle_idle.to_dense())
Ok, great! Now let's run a program and see this rotating around.
# Set up our model again, this time with the rotating idle
model_td3 = deepcopy(model_td1)
D2_qubit = model_td3.model_qubit_aliases["D2"]
model_td3.gate_dict[Label("Gi", D2_qubit)] = EmbeddedOp(model_td3.model.state_space, [D2_qubit], xrot_8cycle_idle)
initial_history_td3 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td3 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
stack_td3 = [
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0")
] * 9
program_td3 = QuantumProgram(
instruction_stack=stack_td3,
initial_history=initial_history_td3,
default_base_seed=20250126, # I'm setting the seed so outcomes stay the same later
name="Time-dependent (less boring) program"
)
results_td3 = program_td3.run(num_shots=100)
We can see this took a little longer as we ran more shots and our program is longer. Now, let's introspect this and see what our stabilizer check is picking up!
The key we are looking for in the frame is just "measurement_outcomes". This is the default key for... measurement outcomes after a physical circuit Instruction in LoQS.
It's our first time interacting with the MeasurementOutcome object directly, so we'll go through this in a few steps.
# We could grab all the measurement outcomes like we were before
# (Here I'm just using the collect_data on a single History for a shot, same syntax as collect_shot_data on the ProgramResults)
shot0_mos = results_td3.shot_histories[0].collect_data("measurement_outcomes", "all", strip_none_entries=True)
shot0_mos
# What does each of these look like? Well, they are a dict with qubit label keys and list of outcome values.
# Why a list and not a single outcome? A circuit could have multiple mid-circuit measurements on the same qubit,
# so we default to storing it as a list.
print(shot0_mos[0])
What have we actually read off here? Well, it turns out that in the 5 qubit code, you only need to read off 3 qubits to get all the logical information necessary. This needs to be done in the correct basis, which Yoder, Takagi, and Chuang :cite:yoder_universal_2016 call the "prime" basis. The codepack has done this transformation already (you will see "prime"-basis-related instructions in the Non-FT Measure instruction if you go digging), so our logical outcome is simply the parity of our three data qubit readings.
Let's compute those for each logical measurement using some list comprehensions.
# As a side note, this is basically exactly what the last instruction that populates "logical_measurement" is doing
def compute_logical_outcome(measurement_outcomes):
data_outcomes = [v[0] for v in measurement_outcomes.values()]
return sum(data_outcomes) % 2
# This is the single shot version
[compute_logical_outcome(mo) for mo in shot0_mos]
Obviously it's a little hard to tell from a single shot, but we roughly see that we are more likely to sample 1 at the start/end of the cycle and more likely to sample 0 (i.e. we've had a bitflip error and are in the |+> state) near the middle of the cycle.
Of course, I've selected a seed such that this is true for explanatory purposes here, but we can average over all the shots to see this trend is carried out.
outcomes_td3 = [
[compute_logical_outcome(mo) for mo in shot_mos]
for shot_mos in results_td3.collect_shot_data("measurement_outcomes", "all", strip_none_entries=True)
]
mean_outcomes_td3 = np.mean(outcomes_td3, axis=0)
mean_outcomes_td3
# Sweet! We start at 1, decay to 0 (hitting 50/50 along the way), and recur back to 1!
# Let's plot it against the ideal case (cos with a period of 2pi/(8*134) and a shift of 31) for funsies.
# The 0.5 and shift are to account for the fact that our outcome goes from 1->0 instead of 1->-1
import matplotlib.pyplot as plt
ts = np.linspace(31,31+8*134,9)
many_ts = np.linspace(31,31+8*134,100)
plt.plot(ts, mean_outcomes_td3, 'bo')
plt.plot(many_ts, 0.5+0.5*np.cos(np.pi*2*(many_ts-31)/(8*134)), 'b-')
plt.xlabel("Time")
plt.ylabel("Avg. Logical Outcome")
plt.show()
Real-time updating of models¶
Finally we get to the crux of the capability we want: to be able to update the model in real-time based on observed outcomes! As with everything, our example here is a little contrived, but we'll show this in two examples.
Before we dive into the examples, let's see how we can tweak the model parameters.
model_td4 = deepcopy(model_td3)
# This is a LoQS model. We can reach in to get the pyGSTi model with .model
# First let's look at the parameter vector
print(model_td4.model.to_vector())
# We can also ask for labels
# NOTE: If you are using pyGSTi pre-0.9.13, this needs to be called after model.to_vector() or model.num_params
# That should be fixed in 0.9.13, and you can ask for these parameter labels before anything else
model_td4.model.parameter_labels
# Note that the qubit label here is Q2 instead of D2 because of the qubit aliasing
# That's a pyGSTi restriction we might resolve later
# We can update the parameters by calling from_vector()
# In this case, let's half the period
model_td4.model.from_vector([1072/2, 31])
initial_history_td4 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td4 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
program_td4 = QuantumProgram(
instruction_stack=stack_td3,
initial_history=initial_history_td4,
default_base_seed=20250126, # I'm setting the seed so outcomes stay the same later
name="Time-dependent manually updated model program"
)
results_td4 = program_td4.run(100)
# Let's make an updated plot
outcomes_td4 = [
[compute_logical_outcome(mo) for mo in shot_mos]
for shot_mos in results_td4.collect_shot_data("measurement_outcomes", "all", strip_none_entries=True)
]
mean_outcomes_td4 = np.mean(outcomes_td4, axis=0)
ts = np.linspace(31,31+8*134,9)
many_ts = np.linspace(31,31+8*134,100)
plt.plot(ts, mean_outcomes_td4, 'ro')
plt.plot(many_ts, 0.5+0.5*np.cos(np.pi*2*(many_ts-31)/(8*134)), 'b-')
plt.xlabel("Time")
plt.ylabel("Avg. Logical Outcome")
plt.show()
Awesome, so we can modify our model's parameters to affect our noisy operations. But now let's see how we can do this during program execution.
Example 1: One-time update¶
First, let's say that we somehow realize partway through the program execution that this overrotation is happening. We decide that the easiest solution is just to zero out the overrotation angle so that we get perfect idles every time. We can do this by introducing an new Instruction into our quantum program.
For detailed information on building an Instruction, check out the section on Instructions and the (in progress) "Building a Complex Instruction" tutorial. However, the TL;DR of the other documentation is that an Instruction has four main parts: the apply function, data, the map qubits function, and parameter information. Let's lay out the API for our model update Instruction, and see how it lines up with what we need to define.
Apply function: What do actually need to do our operation? Let's say it needs all previous measurement outcomes so it can back out what this overrotation rate is, and it also needs the model to manipulate. As output, it will give us a Frame with a new model entry.
Data: In our current framework, we don't need to store any data. But we could store things here that would be useful for the update/calibration protocol.
One obvious thing that is missing is that we only care about certain qubits in the measurement outcomes - specifically "D0", "D2", "D4" in the codepack's template qubits. If we had any other type of measurement in our stack, or were doing this with more than one logical patch, we would almost certainly need to keep this is a list in the Instruction.data.
Map qubits function: This one is easy when you have no data - you don't need to do anything! If we were storing the data qubits we cared about, then this is where we would handle updating them. As a reminder, this is necessary so that we can define a patch once and then instantiate it multiple times on different physical qubits.
Parameter information: This is where we define things like we need "all previous" measurement outcomes or the model from the "last frame".
With all of that conceptually laid out, let's see what this Instruction actually looks like.
from loqs.core import Frame, Instruction
from loqs.core.recordables import MeasurementOutcomes
from loqs.backends import BaseNoiseModel, PyGSTiNoiseModel
def onetime_apply_fn(
all_measurement_outcomes: MeasurementOutcomes,
model: BaseNoiseModel,
) -> Frame:
# Do whatever calibration/update protocol
# In this case, let's assume we just perfectly nail it and set the model parameters
if isinstance(model, PyGSTiNoiseModel):
# We set the period here to 0.01 to avoid a divide by 0 in our noise
model.model.from_vector([0.01, 0])
else:
raise NotImplementedError("Need to code up updating non-pyGSTi model parameters")
return Frame({"model": model})
onetime_instruction = Instruction(
onetime_apply_fn,
# We can provide data and map_qubits_fn here if needed
# Next we set that we need all measurement outcomes from every history frame
param_priorities={"all_measurement_outcomes": ["history[all]"]},
# And we can also set our alias, since we called this all_measurement_outcomes in apply_fn above
param_aliases={"all_measurement_outcomes": "measurement_outcomes"},
# Finally, we have one hack because we defined our apply function in a Jupyter notebook
# This will break serialization, i.e. if you deserialize this program it won't work
# To avoid this, define all apply functions in an actual Python file and import it
serialized_apply_fn=""
)
Now we have our Instruction, but how do we use it? This is where we can use the global_instructions argument of the QuantumProgram that we have thus far been not utilizing to make our Instruction available during runtime, without having to change the codepack.
global_instructions_td5 = {
"One-time Update": onetime_instruction
}
model_td5 = deepcopy(model_td3)
initial_history_td5 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td5 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
stack_cycle = [
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0")
]
# Here we use a stack entry with None as the patch label to indicate the program should look it up in global_instructions
stack_td5 = stack_cycle*5 + [("One-time Update", None)] + stack_cycle*4
program_td5 = QuantumProgram(
instruction_stack=stack_td5,
initial_history=initial_history_td5,
default_base_seed=20250126, # I'm setting the seed so outcomes stay the same later
global_instructions=global_instructions_td5, # Make sure we add our instruction in!
name="Time-dependent + one-time model update"
)
results_td5 = program_td5.run(100)
Sweet! Our program ran. But did it do the right thing? Let's remake our plot. If we are updating the model successfully, we should see a break from our oscillatory behavior after the 5th cycle and a return back to (nearly) 1 as our logical output.
# Let's make an updated plot
outcomes_td5 = [
[compute_logical_outcome(mo) for mo in shot_mos]
for shot_mos in results_td5.collect_shot_data("measurement_outcomes", "all", strip_none_entries=True)
]
mean_outcomes_td5 = np.mean(outcomes_td5, axis=0)
ts = np.linspace(31,31+8*134,9)
many_ts = np.linspace(31,31+8*134,100)
plt.plot(ts, mean_outcomes_td5, 'ro')
plt.plot(many_ts, 0.5+0.5*np.cos(np.pi*2*(many_ts-31)/(8*134)), 'b-')
plt.xlabel("Time")
plt.ylabel("Avg. Logical Outcome")
plt.show()
Example 2: Continuous Update¶
Probably a closer to realistic option is that we are doing smaller updates all the time. Let's have our Instruction realize try to play catch up by shifting the start of the oscillation, but maybe do that imperfectly. This time, maybe we only need the last measurement outcome, so our parameter priority/aliases can be simplified a bit.
def continuous_apply_fn(
measurement_outcomes: int,
model: BaseNoiseModel,
) -> Frame:
if isinstance(model, PyGSTiNoiseModel):
period, shift = model.model.to_vector()
# Maybe we improperly guess that the phase shift needs to be updated by 128 +/- 10 instead of 134
new_shift = shift + 128 + np.random.randint(-10, 10)
model.model.from_vector([period, new_shift])
else:
raise NotImplementedError("Need to code up updating non-pyGSTi model parameters")
return Frame({"model": model})
continuous_instruction = Instruction(
continuous_apply_fn,
# We will be placing this instruction after the Non-FT Measure instruction
# However, Non-FT Measure gets split into the circuit and then the logical measure computation
# If we want access to the raw measurements, we need to go back 2 frames instead of 1
param_priorities={"measurement_outcomes": ["history[-2]"]},
# We still need this hack.
serialized_apply_fn=""
)
global_instructions_td6 = {
"Continuous Update": continuous_instruction
}
model_td6 = deepcopy(model_td3)
initial_history_td6 = History(
{
"state": QSimQuantumState(len(qubits), qubit_labels=qubits),
"patches": PatchLayout({"L0": code_5q.create_patch(qubits)}),
"model": model_td6 # Note that we are putting our new model in!
},
expiring_keys=["state", "model"],
propagating_keys=["state", "patches", "model"]
)
stack_td6 = [
("Non-FT Minus Prep", "L0"),
("I", "L0"),
("Non-FT Logical X Measure", "L0"),
# This time, we just include our global instruction as part of the cycle
("Continuous Update", None)
] * 9
program_td6 = QuantumProgram(
instruction_stack=stack_td6,
initial_history=initial_history_td6,
default_base_seed=20250126,
global_instructions=global_instructions_td6, # Make sure we add our instruction in!
name="Time-dependent + continuous model update"
)
results_td6 = program_td6.run(100)
# Let's make an updated plot
outcomes_td6 = [
[compute_logical_outcome(mo) for mo in shot_mos]
for shot_mos in results_td6.collect_shot_data("measurement_outcomes", "all", strip_none_entries=True)
]
mean_outcomes_td6 = np.mean(outcomes_td6, axis=0)
ts = np.linspace(31,31+8*134,9)
many_ts = np.linspace(31,31+8*134,100)
plt.plot(ts, mean_outcomes_td6, 'ro')
plt.plot(many_ts, 0.5+0.5*np.cos(np.pi*2*(many_ts-31)/(8*134)), 'b-')
plt.xlabel("Time")
plt.ylabel("Avg. Logical Outcome")
plt.show()