Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sequence unrolling with QM #738

Merged
merged 26 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
96656f5
feat: Support sequence unrolling for QM
stavros11 Jan 8, 2024
4c169d8
fix: Recover old QMPulse to fix pulse scheduling
stavros11 Jan 9, 2024
ecd1611
refactor: Remove QMSim class
stavros11 Jan 9, 2024
b4841f7
fix: Fix simulator results
stavros11 Jan 9, 2024
b935dfb
test: Update tests
stavros11 Jan 9, 2024
7d40211
Fix bug with singleshot discrimination
stavros11 Jan 10, 2024
1889424
Merge branch 'octaves' into qmunrolling
stavros11 Jan 12, 2024
6f85966
Fix conflicts
stavros11 Jan 23, 2024
8e09cb0
Merge branch 'octaves' into qmunrolling
stavros11 Jan 31, 2024
f3aac36
refactor: Move threshold and angle to ShotsAcquisition
stavros11 Feb 5, 2024
555b12f
refactor: Drop error
stavros11 Feb 5, 2024
50af0a8
refactor: Merge acquisition measure and save
stavros11 Feb 5, 2024
77d2d71
test: remove calibration path from testing platform
stavros11 Feb 5, 2024
001f77f
Merge branch 'octaves' into qmunrolling
stavros11 Feb 15, 2024
d1c8c8a
Merge branch 'octaves' into qmunrolling
stavros11 Feb 15, 2024
7af1dee
Set batch size for unrolling
stavros11 Feb 15, 2024
4889778
Merge branch 'octaves' into qmunrolling
stavros11 Feb 16, 2024
72018be
Merge branch 'octaves' into qmunrolling
stavros11 Feb 19, 2024
ac31d56
fix: tests
stavros11 Feb 19, 2024
eb853ec
chore: naming conventions
stavros11 Feb 19, 2024
d5b8b45
refactor: simplify fetching
stavros11 Feb 19, 2024
0aaf828
refactor: simplify declare_acquisition
stavros11 Feb 19, 2024
27893f8
refactor: Lift result object creation to base Acquisition
stavros11 Feb 19, 2024
2d0420e
fix: names of result_cls
stavros11 Feb 19, 2024
5f77a71
fix: cast samples to uint32
stavros11 Feb 19, 2024
12841b3
Convert acquisitions to list
stavros11 Feb 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/qibolab/instruments/qm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
from .controller import QMController
from .devices import Octave, OPXplus
from .simulator import QMSim
162 changes: 125 additions & 37 deletions src/qibolab/instruments/qm/acquisition.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import List, Optional
stavros11 marked this conversation as resolved.
Show resolved Hide resolved

import numpy as np
from qm import qua
Expand All @@ -8,6 +9,8 @@
from qualang_tools.addons.variables import assign_variables_to_element
from qualang_tools.units import unit

from qibolab.execution_parameters import AcquisitionType, AveragingMode
from qibolab.qubits import QubitId
from qibolab.result import (
AveragedIntegratedResults,
AveragedRawWaveformResults,
Expand All @@ -27,10 +30,18 @@ class Acquisition(ABC):
variables.
"""

serial: str
"""Serial of the readout pulse that generates this acquisition."""
name: str
"""Name of the acquisition used as identifier to download results from the
instruments."""
qubit: QubitId
average: bool

keys: List[str] = field(default_factory=list)
stavros11 marked this conversation as resolved.
Show resolved Hide resolved

@property
def npulses(self):
return len(self.keys)

@abstractmethod
def assign_element(self, element):
"""Assign acquisition variables to the corresponding QM controlled.
Expand All @@ -50,10 +61,6 @@ def measure(self, operation, element):
element (str): Element (from ``config``) that the pulse will be applied on.
"""

@abstractmethod
def save(self):
"""Save acquired results from variables to streams."""

@abstractmethod
def download(self, *dimensions):
"""Save streams to prepare for fetching from host device.
Expand Down Expand Up @@ -82,28 +89,24 @@ def assign_element(self, element):
def measure(self, operation, element):
qua.measure(operation, element, self.adc_stream)

def save(self):
pass

def download(self, *dimensions):
i_stream = self.adc_stream.input1()
q_stream = self.adc_stream.input2()
if self.average:
i_stream = i_stream.average()
q_stream = q_stream.average()
i_stream.save(f"{self.serial}_I")
q_stream.save(f"{self.serial}_Q")
i_stream.save(f"{self.name}_I")
q_stream.save(f"{self.name}_Q")

def fetch(self, handles):
ires = handles.get(f"{self.serial}_I").fetch_all()
qres = handles.get(f"{self.serial}_Q").fetch_all()
ires = handles.get(f"{self.name}_I").fetch_all()
qres = handles.get(f"{self.name}_Q").fetch_all()
# convert raw ADC signal to volts
u = unit()
ires = u.raw2volts(ires)
qres = u.raw2volts(qres)
signal = u.raw2volts(ires) + 1j * u.raw2volts(qres)
if self.average:
return AveragedRawWaveformResults(ires + 1j * qres)
return RawWaveformResults(ires + 1j * qres)
return [AveragedRawWaveformResults(signal)]
return [RawWaveformResults(signal)]


@dataclass
Expand All @@ -128,30 +131,41 @@ def measure(self, operation, element):
qua.dual_demod.full("cos", "out1", "sin", "out2", self.I),
qua.dual_demod.full("minus_sin", "out1", "cos", "out2", self.Q),
)

def save(self):
qua.save(self.I, self.I_stream)
qua.save(self.Q, self.Q_stream)

def download(self, *dimensions):
Istream = self.I_stream
Qstream = self.Q_stream
if self.npulses > 1:
Istream = Istream.buffer(self.npulses)
Qstream = Qstream.buffer(self.npulses)
for dim in dimensions:
Istream = Istream.buffer(dim)
Qstream = Qstream.buffer(dim)
if self.average:
Istream = Istream.average()
Qstream = Qstream.average()
Istream.save(f"{self.serial}_I")
Qstream.save(f"{self.serial}_Q")
Istream.save(f"{self.name}_I")
Qstream.save(f"{self.name}_Q")
stavros11 marked this conversation as resolved.
Show resolved Hide resolved

def fetch(self, handles):
ires = handles.get(f"{self.serial}_I").fetch_all()
qres = handles.get(f"{self.serial}_Q").fetch_all()
if self.average:
# TODO: calculate std
return AveragedIntegratedResults(ires + 1j * qres)
return IntegratedResults(ires + 1j * qres)
ires = handles.get(f"{self.name}_I").fetch_all()
qres = handles.get(f"{self.name}_Q").fetch_all()
signal = ires + 1j * qres
if self.npulses > 1:
if self.average:
# TODO: calculate std
return [
AveragedIntegratedResults(signal[..., i])
for i in range(self.npulses)
]
return [IntegratedResults(signal[..., i]) for i in range(self.npulses)]
else:
if self.average:
# TODO: calculate std
return [AveragedIntegratedResults(signal)]
return [IntegratedResults(signal)]
stavros11 marked this conversation as resolved.
Show resolved Hide resolved


@dataclass
Expand All @@ -161,9 +175,9 @@ class ShotsAcquisition(Acquisition):
Threshold and angle must be given in order to classify shots.
"""

threshold: float
threshold: Optional[float] = None
"""Threshold to be used for classification of single shots."""
angle: float
angle: Optional[float] = None
"""Angle in the IQ plane to be used for classification of single shots."""

I: _Variable = field(default_factory=lambda: declare(fixed))
Expand Down Expand Up @@ -193,21 +207,95 @@ def measure(self, operation, element):
self.shot,
qua.Cast.to_int(self.I * self.cos - self.Q * self.sin > self.threshold),
)

def save(self):
qua.save(self.shot, self.shots)

def download(self, *dimensions):
shots = self.shots
if self.npulses > 1:
shots = shots.buffer(self.npulses)
for dim in dimensions:
shots = shots.buffer(dim)
if self.average:
shots = shots.average()
shots.save(f"{self.serial}_shots")
shots.save(f"{self.name}_shots")
alecandido marked this conversation as resolved.
Show resolved Hide resolved

def fetch(self, handles):
shots = handles.get(f"{self.serial}_shots").fetch_all()
if self.average:
# TODO: calculate std
return AveragedSampleResults(shots)
return SampleResults(shots.astype(int))
shots = handles.get(f"{self.name}_shots").fetch_all()
if self.npulses > 1:
if self.average:
# TODO: calculate std
return [
AveragedSampleResults(shots[..., i]) for i in range(self.npulses)
]
return [
SampleResults(shots[..., i].astype(int)) for i in range(self.npulses)
]
else:
if self.average:
# TODO: calculate std
return [AveragedSampleResults(shots)]
return [SampleResults(shots.astype(int))]
stavros11 marked this conversation as resolved.
Show resolved Hide resolved


ACQUISITION_TYPES = {
AcquisitionType.RAW: RawAcquisition,
AcquisitionType.INTEGRATION: IntegratedAcquisition,
AcquisitionType.DISCRIMINATION: ShotsAcquisition,
}


def declare_acquisitions(ro_pulses, qubits, options):
"""Declares variables for saving acquisition in the QUA program.

Args:
ro_pulses (list): List of readout pulses in the sequence.
qubits (dict): Dictionary containing all the :class:`qibolab.qubits.Qubit`
objects of the platform.
options (:class:`qibolab.execution_parameters.ExecutionParameters`): Execution
options containing acquisition type and averaging mode.

Returns:
Dictionary containing the different :class:`qibolab.instruments.qm.acquisition.Acquisition` objects.
"""
acquisitions = {}
for qmpulse in ro_pulses:
qubit = qmpulse.pulse.qubit
name = f"{qmpulse.operation}_{qubit}"
if name not in acquisitions:
average = options.averaging_mode is AveragingMode.CYCLIC
acquisition_cls = ACQUISITION_TYPES[options.acquisition_type]
if options.acquisition_type is AcquisitionType.DISCRIMINATION:
threshold = qubits[qubit].threshold
iq_angle = qubits[qubit].iq_angle
acquisition = acquisition_cls(
name, qubit, average, threshold=threshold, angle=iq_angle
)
else:
acquisition = acquisition_cls(name, qubit, average)
stavros11 marked this conversation as resolved.
Show resolved Hide resolved

acquisition.assign_element(qmpulse.element)
acquisitions[name] = acquisition

acquisitions[name].keys.append(qmpulse.pulse.serial)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not reviewing the whole module (maybe I should), but I wonder whether it is worth to have this nested structure (dictionary on names, and internally a list of keys), instead of unrolling to a single level.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, this depends on .fetch_all() requirements: if you have to call it on a given name, and it is much more efficient than individual .fetch() (assuming it exists), then there is no wiggle room for anything else.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the structure is single level: each readout pulse is mapped to an Acquisition object. However multiple readout pulses may be mapped to the same Acquisition.

We could implement it with a single dictionary {ro_pulse: acquisition}, I just think the current implementation which is basically the inverse of this dictionary, is more useful for the manipulations we do later on these objects. I guess it appears as nested because it is the inverse of a map that is non-invertible (in the math sense).

qmpulse.acquisition = acquisitions[name]
return acquisitions


def fetch_results(result, acquisitions):
"""Fetches results from an executed experiment.

Args:
result: Result of the executed experiment.
acquisition (dict): Dictionary containing :class:`qibolab.instruments.qm.acquisition.Acquisition` objects.

Returns:
Dictionary with the results in the format required by the platform.
"""
handles = result.result_handles
handles.wait_for_all_values() # for async replace with ``handles.is_processing()``
results = {}
for acquisition in acquisitions.values():
data = acquisition.fetch(handles)
for serial, result in zip(acquisition.keys, data):
results[acquisition.qubit] = results[serial] = result
Comment on lines +291 to +292
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aren't you overwriting results[acquisition.qubit]?

acquisition is always the same for all result (outer loop), and then acquisition.qubit as well. Isn't it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aren't you overwriting results[acquisition.qubit]?

Yes, but I think this is a more general problem with qibolab that extends beyond this driver.

Particularly, I am not sure how results[qubit] (here results is what is returned by platform.execute_pulse_sequence) is defined if the sequence contains more than one measurements on the same qubit. I had the impression that results[qubit] will only contain the last measurement and earlier measurements can only be accessed through their serial.

For now, I think I would leave it as it is here, and I will open an issue (#809) for a general solution in 0.2.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's perfectly fine. I was not aware of the problem. Thanks for the issue

return results
23 changes: 12 additions & 11 deletions src/qibolab/instruments/qm/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def register_element(self, qubit, pulse, time_of_flight=0, smearing=0):
# register flux element
self.register_flux_element(qubit, pulse.frequency)

def register_pulse(self, qubit, pulse):
def register_pulse(self, qubit, qmpulse):
"""Registers pulse, waveforms and integration weights in QM config.

Args:
Expand All @@ -243,23 +243,24 @@ def register_pulse(self, qubit, pulse):
instantiation of the Qubit objects. They are named as
"drive0", "drive1", "flux0", "readout0", ...
"""
if pulse.serial not in self.pulses:
pulse = qmpulse.pulse
if qmpulse.operation not in self.pulses:
if pulse.type is PulseType.DRIVE:
serial_i = self.register_waveform(pulse, "i")
serial_q = self.register_waveform(pulse, "q")
self.pulses[pulse.serial] = {
self.pulses[qmpulse.operation] = {
"operation": "control",
"length": pulse.duration,
"waveforms": {"I": serial_i, "Q": serial_q},
}
# register drive pulse in elements
self.elements[f"drive{qubit.name}"]["operations"][
pulse.serial
] = pulse.serial
qmpulse.operation
] = qmpulse.operation

elif pulse.type is PulseType.FLUX:
serial = self.register_waveform(pulse)
self.pulses[pulse.serial] = {
self.pulses[qmpulse.operation] = {
"operation": "control",
"length": pulse.duration,
"waveforms": {
Expand All @@ -268,14 +269,14 @@ def register_pulse(self, qubit, pulse):
}
# register flux pulse in elements
self.elements[f"flux{qubit.name}"]["operations"][
pulse.serial
] = pulse.serial
qmpulse.operation
] = qmpulse.operation

elif pulse.type is PulseType.READOUT:
serial_i = self.register_waveform(pulse, "i")
serial_q = self.register_waveform(pulse, "q")
self.register_integration_weights(qubit, pulse.duration)
self.pulses[pulse.serial] = {
self.pulses[qmpulse.operation] = {
"operation": "measurement",
"length": pulse.duration,
"waveforms": {
Expand All @@ -291,8 +292,8 @@ def register_pulse(self, qubit, pulse):
}
# register readout pulse in elements
self.elements[f"readout{qubit.name}"]["operations"][
pulse.serial
] = pulse.serial
qmpulse.operation
] = qmpulse.operation

else:
raise_error(TypeError, f"Unknown pulse type {pulse.type.name}.")
Expand Down
Loading
Loading