-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add cirq.optimize_for_target_gateset
transformer and cirq.CompilationTargetGateset
interface
#5005
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
tanujkhattar
merged 7 commits into
quantumlib:master
from
tanujkhattar:compilation_target
Feb 18, 2022
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1027600
Add convert_to_target_gateset transformer and CompilationTargetGatese…
tanujkhattar bd39098
Address nits
tanujkhattar a6596f4
Override validation_operation to not accept intermediate results
tanujkhattar 882d0ff
Merge branch 'master' of https://github.com/quantumlib/cirq into comp…
tanujkhattar 13786d7
Rename transformers
tanujkhattar 9cf8908
Fix typo
tanujkhattar cd2a0da
Typo
tanujkhattar 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
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
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
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
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
130 changes: 130 additions & 0 deletions
130
cirq-core/cirq/transformers/convert_to_target_gateset.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,130 @@ | ||
# Copyright 2022 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. | ||
|
||
"""Transformers to rewrite a circuit using gates from a given target gateset.""" | ||
|
||
from typing import Optional, Callable, TYPE_CHECKING | ||
|
||
from cirq.protocols import decompose_protocol as dp | ||
from cirq.transformers import transformer_api, transformer_primitives | ||
|
||
if TYPE_CHECKING: | ||
import cirq | ||
|
||
|
||
def _create_on_stuck_raise_error(gateset: 'cirq.Gateset'): | ||
def _value_error_describing_bad_operation(op: 'cirq.Operation') -> ValueError: | ||
return ValueError(f"Unable to convert {op} to target gateset {gateset!r}") | ||
|
||
return _value_error_describing_bad_operation | ||
|
||
|
||
@transformer_api.transformer | ||
def decompose_operations_to_target_gateset( | ||
circuit: 'cirq.AbstractCircuit', | ||
*, | ||
context: Optional['cirq.TransformerContext'] = None, | ||
gateset: Optional['cirq.Gateset'] = None, | ||
decomposer: Callable[['cirq.Operation', int], dp.DecomposeResult] = lambda *_: NotImplemented, | ||
ignore_failures=True, | ||
tanujkhattar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> 'cirq.Circuit': | ||
"""Decomposes every operation to `gateset` using `cirq.decompose` and `decomposer`. | ||
|
||
This transformer attempts to decompose every operation `op` in the given circuit to `gateset` | ||
using `cirq.decompose` protocol with `decomposer` used as an intercepting decomposer. This | ||
ensures that `op` is recursively decomposed using implicitly defined known decompositions | ||
(eg: in `_decompose_` magic method on the gaet class) till either `decomposer` knows how to | ||
decompose the given operation or the given operation belongs to `gateset`. | ||
|
||
Args: | ||
circuit: Input circuit to transform. It will not be modified. | ||
context: `cirq.TransformerContext` storing common configurable options for transformers. | ||
gateset: Target gateset, which the decomposed operations should belong to. | ||
decomposer: A callable type which accepts an (operation, moment_index) and returns | ||
- An equivalent `cirq.OP_TREE` implementing `op` using gates from `gateset`. | ||
- `None` or `NotImplemented` if does not know how to decompose a given `op`. | ||
ignore_failures: If set, operations that fail to convert are left unchanged. If not set, | ||
conversion failures raise a TypeError. | ||
|
||
Returns: | ||
An equivalent circuit containing gates accepted by `gateset`. | ||
|
||
Raises: | ||
TypeError: If any input operation fails to convert and `ignore_failures` is False. | ||
""" | ||
|
||
def map_func(op: 'cirq.Operation', moment_index: int): | ||
return dp.decompose( | ||
op, | ||
intercepting_decomposer=lambda o: decomposer(o, moment_index), | ||
keep=gateset.validate if gateset else None, | ||
on_stuck_raise=( | ||
None | ||
if ignore_failures or gateset is None | ||
else _create_on_stuck_raise_error(gateset) | ||
), | ||
) | ||
|
||
return transformer_primitives.map_operations_and_unroll( | ||
circuit, map_func, tags_to_ignore=context.tags_to_ignore if context else () | ||
).unfreeze(copy=False) | ||
|
||
|
||
@transformer_api.transformer | ||
def convert_to_target_gateset( | ||
circuit: 'cirq.AbstractCircuit', | ||
*, | ||
context: Optional['cirq.TransformerContext'] = None, | ||
gateset: Optional['cirq.CompilationTargetGateset'] = None, | ||
ignore_failures: bool = True, | ||
) -> 'cirq.Circuit': | ||
"""Transforms the given circuit into an equivalent circuit using gates accepted by `gateset`. | ||
|
||
1. Run all `gateset.preprocess_transformers` | ||
2. Convert operations using built-in cirq decompose + `gateset.decompose_to_target_gateset`. | ||
3. Run all `gateset.postprocess_transformers` | ||
|
||
Args: | ||
circuit: Input circuit to transform. It will not be modified. | ||
context: `cirq.TransformerContext` storing common configurable options for transformers. | ||
gateset: Target gateset, which should be an instance of `cirq.CompilationTargetGateset`. | ||
ignore_failures: If set, operations that fail to convert are left unchanged. If not set, | ||
conversion failures raise a TypeError. | ||
|
||
Returns: | ||
An equivalent circuit containing gates accepted by `gateset`. | ||
|
||
Raises: | ||
TypeError: If any input operation fails to convert and `ignore_failures` is False. | ||
""" | ||
if gateset is None: | ||
return decompose_operations_to_target_gateset( | ||
circuit, context=context, ignore_failures=ignore_failures | ||
) | ||
|
||
for transformer in gateset.preprocess_transformers: | ||
circuit = transformer(circuit, context=context) | ||
|
||
circuit = decompose_operations_to_target_gateset( | ||
circuit, | ||
context=context, | ||
gateset=gateset, | ||
decomposer=gateset.decompose_to_target_gateset, | ||
ignore_failures=ignore_failures, | ||
) | ||
|
||
for transformer in gateset.postprocess_transformers: | ||
circuit = transformer(circuit, context=context) | ||
|
||
return circuit.unfreeze(copy=False) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.