Skip to content

Tools to disable op validation #5530

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 8 commits into from
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 42 additions & 0 deletions cirq-core/cirq/contrib/hacks/disable_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# 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.

"""Tools for disabling validation in circuit construction."""

import contextlib


@contextlib.contextmanager
def disable_op_validation(*, accept_debug_responsibility: bool = False):
if not accept_debug_responsibility:
raise ValueError(
"WARNING! Using disable_op_validation with invalid ops can cause "
"mysterious and terrible things to happen. cirq-maintainers will "
"not help you debug beyond this point!\n"
"If you still wish to continue, call this method with "
"accept_debug_responsibility=True."
)

from cirq.ops import raw_types

temp = raw_types._validate_qid_shape
raw_types._validate_qid_shape = lambda *args: None
Copy link
Contributor

Choose a reason for hiding this comment

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

We might consider using contextvars instead:

# raw_types.py
validate_qids: contextvars.ContextVar[bool] = contextvars.ContextVar('validate_qids', default=True)

def _validate_qid_shape(...) -> None:
    if validate_qids.get():
        return
    ...

# here
def disable_op_validation(...):
    ...
    token = raw_types.validate_qids.set(False)
    try:
        yield
    finally:
        raw_types.validate_qids.reset(token)

This would be more scoped than modifying global state, which could otherwise cause hard-to-debug issues with threads or asynchrony.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done. My only misgiving with this is that it exposes the hack in raw_types.py, which could lead to users applying it in ill-advised ways. Left a comment to mitigate this somewhat.

Copy link
Contributor

Choose a reason for hiding this comment

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

After thinking about it, I think I agree with you that it's better to keep the hack itself contained and not modify raw_types.py. If this turns out to be useful and we can't otherwise optimize the qid validation then we could migrate it into raw_types in the future. So feel free to ignore my suggestions and revert to your original version.

try:
yield None
# ...run context...
except:
raw_types._validate_qid_shape = temp
raise
finally:
raw_types._validate_qid_shape = temp
Copy link
Contributor

Choose a reason for hiding this comment

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

Only need the finally clause here. It'll run on failure too.

44 changes: 44 additions & 0 deletions cirq-core/cirq/contrib/hacks/disable_validation_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# 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.

import pytest

import cirq
from cirq.contrib.hacks.disable_validation import disable_op_validation


def test_disable_op_validation():
q0, q1 = cirq.LineQubit.range(2)

# Fails normally.
with pytest.raises(ValueError, match='Wrong number'):
_ = cirq.H(q0, q1)

# Fails if responsibility is not accepted.
with pytest.raises(ValueError, match='mysterious and terrible'):
with disable_op_validation():
_ = cirq.H(q0, q1)

# Passes, skipping validation.
with disable_op_validation(accept_debug_responsibility=True):
op = cirq.H(q0, q1)
assert op.qubits == (q0, q1)

# Validation is restored even on error.
with pytest.raises(AssertionError):
assert False
# Future developer: DO NOT REMOVE. This is NOT a duplicate!
# It only LOOKS like a duplicate because this is a gross hack :D
with pytest.raises(ValueError, match='Wrong number'):
_ = cirq.H(q0, q1)