Skip to content

Modify run_batch_async #6387

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

Merged
merged 16 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
16 changes: 12 additions & 4 deletions cirq-core/cirq/work/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ def run_batch(
ValueError: If length of `programs` is not equal to the length
of `params_list` or the length of `repetitions`.
"""
print("um")
params_list, repetitions = self._normalize_batch_args(programs, params_list, repetitions)
return [
self.run_sweep(circuit, params=params, repetitions=repetitions)
Expand All @@ -293,11 +294,18 @@ async def run_batch_async(

See docs for `cirq.Sampler.run_batch`.
"""
print("finally")
params_list, repetitions = self._normalize_batch_args(programs, params_list, repetitions)
return [
await self.run_sweep_async(circuit, params=params, repetitions=repetitions)
for circuit, params, repetitions in zip(programs, params_list, repetitions)
]
Comment on lines -297 to -300
Copy link
Contributor

Choose a reason for hiding this comment

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

You probably want to use a variant of duet.pmap ("parallel map") to make multiple calls in parallel. In this case, the zip produces tuples of args and we want to call the underlying function like self.run_sweep_async(*args), so we need a "starmap", something like:

return await duet.pstarmap_async(self.run_sweep_async, zip(programs, params_list, repetitions))

Copy link
Contributor

Choose a reason for hiding this comment

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

For reference, here's the definition of duet.pstarmap_async: https://github.com/google/duet/blob/main/duet/api.py#L171

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thank you for the code pointer!

results = []
for circuit, params, repetitions in zip(programs, params_list, repetitions):
results.append(duet.run(self.run_sweep_async, circuit, params, repetitions))

return results

# return [
# await self.run_sweep_async(circuit, params=params, repetitions=repetitions)
# for circuit, params, repetitions in zip(programs, params_list, repetitions)
# ]

def _normalize_batch_args(
self,
Expand Down
6 changes: 6 additions & 0 deletions cirq-google/cirq_google/engine/processor_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,16 @@

import cirq
import duet
import concurrent.futures
from typing import TypeVar, Generic

if TYPE_CHECKING:
import cirq_google as cg


T = TypeVar("T")


class ProcessorSampler(cirq.Sampler):
"""A wrapper around AbstractProcessor to implement the cirq.Sampler interface."""

Expand Down Expand Up @@ -76,6 +81,7 @@ async def run_batch_async(
params_list: Optional[Sequence[cirq.Sweepable]] = None,
repetitions: Union[int, Sequence[int]] = 1,
) -> Sequence[Sequence['cg.EngineResult']]:
print("outer")
return cast(
Sequence[Sequence['cg.EngineResult']],
await super().run_batch_async(programs, params_list, repetitions),
Expand Down
21 changes: 17 additions & 4 deletions docs/tutorials/google/start.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,25 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 9,
"metadata": {
"cellView": "both",
"id": "EQoTYZIEPa9S"
},
"outputs": [],
"id": "EQoTYZIEPa9S",
"outputId": "43c72568-3bc8-4b44-871b-b9db19c9e672",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Circuit:\n",
"(0, 0): ───X───M('result')───\n"
]
}
],
"source": [
"# Define a qubit at an arbitrary grid location.\n",
"qubit = cirq.GridQubit(0, 0)\n",
Expand Down
121 changes: 121 additions & 0 deletions hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import cirq
from typing import Sequence
import numpy as np
from cirq.experiments.qubit_characterizations import (
RandomizedBenchMarkResult,
_random_single_q_clifford,
_single_qubit_cliffords,
_gate_seq_to_mats,
)
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import datetime


def _create_rb_circuit(
qubits: tuple[cirq.GridQubit], num_cfds: int, c1: list, cfd_mats: np.array
) -> cirq.Circuit:
circuits_to_zip = [_random_single_q_clifford(qubit, num_cfds, c1, cfd_mats) for qubit in qubits]
circuit = cirq.Circuit.zip(*circuits_to_zip)
measure_moment = cirq.Moment(
cirq.measure_each(*qubits, key_func=lambda q: 'q{}_{}'.format(q.row, q.col))
)
circuit_with_meas = cirq.Circuit.from_moments(*(circuit.moments + [measure_moment]))
return circuit_with_meas


def single_qubit_randomized_benchmarking(
sampler: cirq.Sampler,
use_xy_basis: bool = True,
*,
qubits: tuple[cirq.GridQubit] | None = None,
num_clifford_range: Sequence[int] = [5, 18, 70, 265, 1000],
num_circuits: int = 10,
repetitions: int = 600,
) -> list[RandomizedBenchMarkResult]:
if qubits is None:
device = sampler.processor.get_device()
qubits = tuple(sorted(list(device.metadata.qubit_set)))

cliffords = _single_qubit_cliffords()
c1 = cliffords.c1_in_xy if use_xy_basis else cliffords.c1_in_xz
cfd_mats = np.array([_gate_seq_to_mats(gates) for gates in c1])

# create circuits
circuits = []
for num_cfds in num_clifford_range:
for _ in range(num_circuits):
circuits.append(_create_rb_circuit(qubits, num_cfds, c1, cfd_mats))

# run circuits
results_all = sampler.run_batch(circuits, repetitions=repetitions)
gnd_probs = {q: [] for q in qubits}
idx = 0
for num_cfds in num_clifford_range:
excited_probs_l = {q: [] for q in qubits}
for _ in range(num_circuits):
results = results_all[idx][0]
for qubit in qubits:
excited_probs_l[qubit].append(
np.mean(results.measurements['q{}_{}'.format(qubit.row, qubit.col)])
)
idx += 1
for qubit in qubits:
gnd_probs[qubit].append(1.0 - np.mean(excited_probs_l[qubit]))
return {q: RandomizedBenchMarkResult(num_clifford_range, gnd_probs[q]) for q in qubits}


def compute_pauli_errors(rb_result: dict) -> dict:
exp_fit = lambda x, A, B, p: A * p**x + B
rb_errors = {}
d = 2
for qubit in rb_result:
data = np.array(result[qubit].data)
x = data[:, 0]
y = data[:, 1]
fit = curve_fit(exp_fit, x, y)
p = fit[0][2]
pauli_error = (1.0 - 1.0 / (d * d)) * (1.0 - p)
rb_errors[qubit] = pauli_error
return rb_errors


def plot_error_rates(rb_result: dict, ax: plt.Axes | None = None) -> plt.Axes:
errors = compute_pauli_errors(rb_result)
heatmap = cirq.Heatmap(errors)
if ax is None:
_, ax = plt.subplots(figsize=(8, 8))
_ = heatmap.plot(ax, vmin=0, vmax=0.01)
return ax


if __name__ == "__main__":
# The Google Cloud Project id to use.
project_id = "i-dont-have-experimental" # @param {type:"string"}

from cirq_google.engine.qcs_notebook import get_qcs_objects_for_notebook

# For real engine instances, delete 'virtual=True' below.
qcs_objects = get_qcs_objects_for_notebook(project_id)

project_id = qcs_objects.project_id
engine = qcs_objects.engine
if not qcs_objects.signed_in:
print(
"ERROR: Please setup project_id in this cell or set the `GOOGLE_CLOUD_PROJECT` env var to your project id."
)
print("Using noisy simulator instead.")

processor_id = "bodega_sim_gmon18" # @param {type:"string"}
processor = engine.get_processor(processor_id)

sampler = processor.get_sampler(
# run_name =
# device_config_name =
)
start = datetime.datetime.now().timestamp()
result = single_qubit_randomized_benchmarking(sampler)
end = datetime.datetime.now().timestamp()
print(end - start)

plot_error_rates(result)