-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[cirqflow] Quantum runtime skeleton #4556
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
Closed
Closed
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6d31edd
[cirqflow] Quantum runtime skeleton
mpharrigan 424380b
[wip] tests
mpharrigan 2aeb0e3
[wip] json
mpharrigan 0cedef0
[cirqflow] Provide concrete ExecutableSpec
mpharrigan 5335074
Type annotations
mpharrigan e45545d
Merge branch '2021-10-concrete-spec' into 2021-10-execution
mpharrigan a54ee46
JSON serialization
mpharrigan ca738dd
Document KeyValueExecutableSpec args and see-also
mpharrigan fe2213a
test other datatypes
mpharrigan b20d63d
Merge remote-tracking branch 'origin/master' into 2021-10-concrete-spec
mpharrigan 6675555
Merge branch '2021-10-concrete-spec' into 2021-10-execution
mpharrigan b7dfc56
mypy
mpharrigan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
cirq-google/cirq_google/workflow/_abstract_engine_processor_shim.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Copyright 2021 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
|
||
import abc | ||
|
||
import cirq.work | ||
|
||
|
||
class AbstractEngineProcessorShim(metaclass=abc.ABCMeta): | ||
@abc.abstractmethod | ||
def get_device(self) -> cirq.Device: | ||
pass | ||
|
||
@abc.abstractmethod | ||
def get_sampler(self) -> cirq.Sampler: | ||
pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
# Copyright 2021 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
"""Infrastructure for running quantum executables.""" | ||
|
||
import os | ||
import uuid | ||
from dataclasses import dataclass | ||
from typing import List | ||
|
||
import cirq.work | ||
from cirq.protocols import dataclass_json_dict | ||
from cirq_google.workflow._abstract_engine_processor_shim import AbstractEngineProcessorShim | ||
from cirq_google.workflow.quantum_executable import ExecutableSpec, QuantumExecutableGroup, \ | ||
BitstringsMeasurement | ||
|
||
|
||
@dataclass | ||
class SharedRuntimeInfo: | ||
"""Runtime information common to all `QuantumExecutable`s in an execution of a | ||
`QuantumExecutableGroup`. | ||
|
||
There is one `SharedRuntimeInfo` per `ExecutableGroupResult`. | ||
|
||
Args: | ||
run_id: A unique `str` identifier for this run. | ||
""" | ||
run_id: str | ||
|
||
def _json_dict_(self): | ||
return dataclass_json_dict(self, namespace='cirq.google') | ||
|
||
|
||
@dataclass | ||
class RuntimeInfo: | ||
"""Runtime information relevant to a particular `QuantumExecutable`. | ||
|
||
There is one `RuntimeInfo` per `ExecutableResult` | ||
|
||
Args: | ||
execution_index: What order (in its `QuantumExecutableGroup`) this `QuantumExecutable` was | ||
executed. | ||
""" | ||
execution_index: int | ||
|
||
def _json_dict_(self): | ||
return dataclass_json_dict(self, namespace='cirq.google') | ||
|
||
|
||
@dataclass | ||
class ExecutableResult: | ||
"""Results for a `QuantumExecutable`. | ||
|
||
Args: | ||
spec: The `ExecutableSpec` typifying the `QuantumExecutable`. | ||
runtime_info: A `RuntimeInfo` dataclass containing information gathered during execution | ||
of the `QuantumExecutable`. | ||
raw_data: The `cirq.Result` containing the data from the run. | ||
""" | ||
spec: ExecutableSpec | ||
runtime_info: RuntimeInfo | ||
raw_data: cirq.Result | ||
|
||
def _json_dict_(self): | ||
return dataclass_json_dict(self, namespace='cirq.google') | ||
|
||
|
||
@dataclass | ||
class ExecutableGroupResult: | ||
"""Results for a `QuantumExecutableGroup`. | ||
|
||
Args: | ||
runtime_configuration: The `QuantumRuntimeConfiguration` describing how the | ||
`QuantumExecutableGroup` was requested to be executed. | ||
shared_runtime_info: A `SharedRuntimeInfo` dataclass containing information gathered | ||
during execution of the `QuantumExecutableGroup` which is relevant to all | ||
`executable_results`. | ||
executable_results: A list of `ExecutableResult`. Each contains results and raw data | ||
for an individual `QuantumExecutable`. | ||
""" | ||
runtime_configuration: 'QuantumRuntimeConfiguration' | ||
shared_runtime_info: SharedRuntimeInfo | ||
executable_results: List[ExecutableResult] | ||
|
||
def _json_dict_(self): | ||
return dataclass_json_dict(self, namespace='cirq.google') | ||
|
||
|
||
@dataclass | ||
class QuantumRuntimeConfiguration: | ||
"""User-requested configuration of how to execute a given `QuantumExecutableGroup`. | ||
|
||
Args: | ||
processor: The `AbstractEngineProcessor` responsible for running circuits and providing | ||
device information. | ||
run_id: A unique `str` identifier for a run. If data already exists for the specified | ||
`run_id`, an exception will be raised. If not specified, we will generate a UUID4 | ||
run identifier. | ||
""" | ||
processor: AbstractEngineProcessorShim | ||
run_id: str = None | ||
|
||
def _json_dict_(self): | ||
return dataclass_json_dict(self, namespace='cirq.google') | ||
|
||
|
||
def execute( | ||
rt_config: QuantumRuntimeConfiguration, | ||
executable_group: QuantumExecutableGroup, | ||
base_data_dir: str = ".", | ||
) -> ExecutableGroupResult: | ||
"""Execute a `QuantumExecutableGroup` according to a `QuantumRuntimeConfiguration`. | ||
|
||
Args: | ||
rt_config: The `QuantumRuntimeConfiguration` specifying how to execute `executable_group`. | ||
executable_group: The `QuantumExecutableGroup` containing the executables to execute. | ||
base_data_dir: A filesystem path to write data. We write | ||
"{base_data_dir}/{run_id}/ExecutableGroupResult.json.gz" | ||
containing the `ExecutableGroupResult` as well as one file | ||
"{base_data_dir}/{run_id}/ExecutableResult.{i}.json.gz" per `ExecutableResult` as | ||
each executable result becomes available. | ||
|
||
Returns: | ||
The `ExecutableGroupResult` containing all data and metadata for an execution. | ||
""" | ||
# run_id defaults logic. | ||
if rt_config.run_id is None: | ||
run_id = str(uuid.uuid4()) | ||
else: | ||
run_id = rt_config.run_id | ||
|
||
# base_data_dir handling. | ||
if not base_data_dir: | ||
raise ValueError("Please provide a non-empty `base_data_dir`.") | ||
|
||
os.makedirs(f'{base_data_dir}/{run_id}', exist_ok=False) | ||
|
||
# Results object that we will fill in in the main loop. | ||
exegroup_result = ExecutableGroupResult(runtime_configuration=rt_config, | ||
shared_runtime_info=SharedRuntimeInfo(run_id=run_id), | ||
executable_results=[]) | ||
cirq.to_json_gzip(exegroup_result, f'{base_data_dir}/{run_id}/ExecutableGroupResult.json.gz') | ||
|
||
# Loop over executables. | ||
sampler = rt_config.processor.get_sampler() | ||
print('# Executables:', len(executable_group), flush=True) | ||
for i, exe in enumerate(executable_group): | ||
runtime_info = RuntimeInfo( | ||
execution_index=i | ||
) | ||
|
||
if exe.params != tuple(): | ||
raise NotImplementedError("Circuit params are not yet supported.") | ||
|
||
circuit = exe.circuit | ||
|
||
if not isinstance(exe.measurement, BitstringsMeasurement): | ||
raise NotImplementedError("Only `BitstringsMeasurement` are supported.") | ||
|
||
sampler_run_result = sampler.run(circuit, repetitions=exe.measurement.n_repetitions) | ||
|
||
exe_result = ExecutableResult( | ||
spec=exe.spec, | ||
runtime_info=runtime_info, | ||
raw_data=sampler_run_result, | ||
) | ||
cirq.to_json_gzip(exe_result, f'{base_data_dir}/{run_id}/ExecutableResult.{i}.json.gz') | ||
exegroup_result.executable_results.append(exe_result) | ||
print(i, end=' ', flush=True) | ||
|
||
return exegroup_result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# Copyright 2021 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import cirq | ||
import cirq_google as cg | ||
import cirq_google.workflow as cgw | ||
from cirq_google.workflow._abstract_engine_processor_shim import AbstractEngineProcessorShim | ||
from cirq_google.workflow.quantum_executable_test import _get_quantum_executables | ||
|
||
|
||
class _MockEngineProcessor(AbstractEngineProcessorShim): | ||
|
||
def get_device(self) -> cirq.Device: | ||
return cg.Sycamore23 | ||
|
||
def get_sampler(self) -> cirq.Sampler: | ||
return cirq.ZerosSampler() | ||
|
||
def _json_dict_(self): | ||
return cirq.obj_to_dict_helper(self, attribute_names=[], namespace='cirq.google.testing') | ||
|
||
|
||
def test_execute(tmpdir): | ||
rt_config = cgw.QuantumRuntimeConfiguration( | ||
processor=_MockEngineProcessor(), | ||
run_id='unittests', | ||
) | ||
executable_group = cgw.QuantumExecutableGroup(_get_quantum_executables()) | ||
cgw.execute(rt_config=rt_config, executable_group=executable_group, base_data_dir=tmpdir) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@dstrain115
AbstractEngineProcessor
:)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@dstrain115 thoughts?