Skip to content

[cirqflow] Add target_gateset to QuantumRuntimeConfiguration #5336

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 6 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
"random_seed": null,
"qubit_placer": {
"cirq_type": "cirq.google.NaiveQubitPlacer"
},
"target_gateset": {
"cirq_type": "CZTargetGateset",
"atol": 1e-08,
"allow_partial_czs": false
}
},
"shared_runtime_info": {
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,10 @@
"random_seed": null,
"qubit_placer": {
"cirq_type": "cirq.google.NaiveQubitPlacer"
},
"target_gateset": {
"cirq_type": "CZTargetGateset",
"atol": 1e-08,
"allow_partial_czs": false
}
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
cirq_google.QuantumRuntimeConfiguration(processor_record=cirq_google.SimulatedProcessorRecord(processor_id='rainbow', noise_strength=0), run_id='unit-test', random_seed=None, qubit_placer=cirq_google.NaiveQubitPlacer())
cirq_google.QuantumRuntimeConfiguration(processor_record=cirq_google.SimulatedProcessorRecord(processor_id='rainbow', noise_strength=0), run_id='unit-test', random_seed=None, qubit_placer=cirq_google.NaiveQubitPlacer(), target_gateset=cirq.CZTargetGateset(atol=1e-08, allow_partial_czs=False))
8 changes: 8 additions & 0 deletions cirq-google/cirq_google/workflow/quantum_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,15 @@ class QuantumRuntimeConfiguration:
qubit_placer: A `cg.QubitPlacer` implementation to map executable qubits to device qubits.
The placer is only called if a given `cg.QuantumExecutable` has a `problem_topology`.
This subroutine's runtime is keyed by "placement" in `RuntimeInfo.timings_s`.
target_gateset: If not `None`, compile all circuits to this target gateset prior to
execution.
"""

processor_record: 'cg.ProcessorRecord'
run_id: Optional[str] = None
random_seed: Optional[int] = None
qubit_placer: QubitPlacer = NaiveQubitPlacer()
target_gateset: Optional[cirq.CompilationTargetGateset] = None

@classmethod
def _json_namespace_(cls) -> str:
Expand Down Expand Up @@ -298,6 +301,11 @@ def execute(
)
runtime_info.qubit_placement = mapping

if rt_config.target_gateset is not None:
circuit = cirq.optimize_for_target_gateset(
circuit, gateset=rt_config.target_gateset
).freeze()
Comment on lines +305 to +307
Copy link
Collaborator

Choose a reason for hiding this comment

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

It would be nice if we can also allow plumbing a transformer context here, which can be used to control many useful compilation behaviors like context.tags_to_ignore or context.deep (to compile sub-circuits recursively instead of treating them as standalone operations).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

That sounds reasonable.

Now that I'm looking at TransformerContext it would be really nice if I could offer a transformer logger that logs into the cg.RuntimeInfo for each executable.

Designing the API to enable this may be weird: because the TransformerLogger in the TransformerContext will need a reference to the RuntimeInfo which doesn't exist when the user is setting up their QuantumRuntimeConfiguration.

I could do something gross like define a subclass WorkflowTransformerLogger and do an isinstance check during the execution loop. If it's an instance of this special class, call a method to plumb in the RuntimeInfo object.

Any other ideas?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

TransformerContext isn't json serializable, which blocks its use in QuantumRuntimeConfiguration. We can plumb it through when that's done

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ah, it's a dataclass but not a json_serializable_dataclass. Okay, let's open a new issue to track the change.

Also; for google devices (i.e. devices with GridDeviceMetadata), it should be possible to get the target gateset from processor_record.device.metadata.compilation_target_gatesets[0] -- but I think it's better to explicitly require a target_gateset here and the user can pick it from the device instead of creating a new instance if they want to.


with _time_into_runtime_info(runtime_info, 'run'):
sampler_run_result = sampler.run(circuit, repetitions=exe.measurement.n_repetitions)

Expand Down
67 changes: 51 additions & 16 deletions cirq-google/cirq_google/workflow/quantum_runtime_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,63 @@ def _assert_json_roundtrip(o, tmpdir):
assert o == o2


def test_quantum_runtime_configuration():
rt_config = cg.QuantumRuntimeConfiguration(
processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), run_id='unit-test'
)
@pytest.fixture(params=['minimal', 'full'])
def rt_config(request):
if request.param == 'minimal':
return cg.QuantumRuntimeConfiguration(
processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow')
)

elif request.param == 'full':
return cg.QuantumRuntimeConfiguration(
processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'),
run_id='unit-test',
random_seed=52,
qubit_placer=cg.RandomDevicePlacer(),
target_gateset=cirq.CZTargetGateset(),
)

raise ValueError(f"Unknown flavor {request}")


def test_quantum_runtime_configuration_sampler(rt_config):
sampler = rt_config.processor_record.get_sampler()
result = sampler.run(cirq.Circuit(cirq.measure(cirq.GridQubit(5, 3), key='z')))
assert isinstance(result, cirq.Result)


def test_quantum_runtime_configuration_device(rt_config):
assert isinstance(rt_config.processor_record.get_device(), cirq.Device)


def test_quantum_runtime_configuration_serialization(tmpdir):
rt_config = cg.QuantumRuntimeConfiguration(
processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'), run_id='unit-test'
def test_quantum_runtime_configuration_run_id(rt_config):
if rt_config.run_id is not None:
assert isinstance(rt_config.run_id, str)


def test_quantum_runtime_configuration_qubit_placer(rt_config):
device = rt_config.processor_record.get_device()
c, _ = rt_config.qubit_placer.place_circuit(
cirq.Circuit(cirq.measure(cirq.LineQubit(0), cirq.LineQubit(1), key='z')),
problem_topology=cirq.LineTopology(n_nodes=2),
shared_rt_info=cg.SharedRuntimeInfo(run_id=rt_config.run_id, device=device),
rs=np.random.RandomState(rt_config.random_seed),
)
if isinstance(rt_config.qubit_placer, cg.NaiveQubitPlacer):
assert all(isinstance(q, cirq.LineQubit) for q in c.all_qubits())
else:
assert all(isinstance(q, cirq.GridQubit) for q in c.all_qubits())


def test_quantum_runtime_configuration_target_gateset(rt_config):
c = cirq.Circuit(cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1)))
if rt_config.target_gateset is not None:
# CNOT = H CZ H
c = cirq.optimize_for_target_gateset(c, gateset=rt_config.target_gateset)
assert len(c) == 3


def test_quantum_runtime_configuration_serialization(tmpdir, rt_config):
cg_assert_equivalent_repr(rt_config)
_assert_json_roundtrip(rt_config, tmpdir)

Expand Down Expand Up @@ -135,20 +176,14 @@ def _load_result_by_hand(tmpdir: str, run_id: str) -> cg.ExecutableGroupResult:
)


@pytest.mark.parametrize('run_id_in', ['unit_test_runid', None])
def test_execute(tmpdir, run_id_in):
rt_config = cg.QuantumRuntimeConfiguration(
processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'),
run_id=run_id_in,
qubit_placer=cg.NaiveQubitPlacer(),
)
def test_execute(tmpdir, rt_config):
executable_group = cg.QuantumExecutableGroup(_get_quantum_executables())
returned_exegroup_result = cg.execute(
rt_config=rt_config, executable_group=executable_group, base_data_dir=tmpdir
)
run_id = returned_exegroup_result.shared_runtime_info.run_id
if run_id_in is not None:
assert run_id_in == run_id
if rt_config.run_id is not None:
assert run_id == 'unit-test'
else:
assert isinstance(uuid.UUID(run_id), uuid.UUID)

Expand Down