Skip to content

Conversation

@dstrain115
Copy link
Collaborator

  • This adds custom tag serializers for serializing tags.
  • This allows greater flexibility and a much easier way to specify a serializer to serialize and deserialize internal tags.

- This adds custom tag serializers for serializing tags.
- This allows greater flexibility and a much easier way to
specify a serializer to serialize and deserialize internal tags.
@dstrain115 dstrain115 requested review from a team, verult, vtomole and wcourtney as code owners March 20, 2025 17:21
@codecov
Copy link

codecov bot commented Mar 20, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.13%. Comparing base (8cde2ba) to head (24b8253).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7169      +/-   ##
==========================================
- Coverage   98.13%   98.13%   -0.01%     
==========================================
  Files        1093     1095       +2     
  Lines       95579    95649      +70     
==========================================
+ Hits        93797    93864      +67     
- Misses       1782     1785       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dstrain115 dstrain115 requested a review from senecameeks March 20, 2025 19:29
Copy link
Collaborator

@pavoljuhas pavoljuhas left a comment

Choose a reason for hiding this comment

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

LGTM with some small tweaks, please see inline.

self.discount = discount

def __eq__(self, other):
if isinstance(other, DiscountTag) and self.discount == other.discount:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit - __eq__ should return NotImplemented for unhandled types (I realize this is a test class). Consider using attrs instead which define __eq__ and __hash__ with less code

@attrs.frozen
class DiscountTag:
    discount: float

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good idea. Done.

),
constants=[v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='1_1'))],
)
expected_circuit_no_tag = cirq.Circuit(
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit - the _no_tag suffix is a bit confusing, because there is a tagged operation.
How about plain expected_circuit?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Changed.

Comment on lines 333 to 334
constant = v2.program_pb2.Constant()
tag_index = len(constants)
Copy link
Collaborator

Choose a reason for hiding this comment

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

We can use constant in both if-branches. It is also safer to get tag_index after the tag_serializer.to_proto() call in case it changes the constants list:

diff --git a/cirq-google/cirq_google/serialization/circuit_serializer.py b/cirq-google/cirq_google/serialization/circuit_serializer.py
index b76b23f7..ae940471 100644
--- a/cirq-google/cirq_google/serialization/circuit_serializer.py
+++ b/cirq-google/cirq_google/serialization/circuit_serializer.py
@@ -331,17 +331,17 @@ class CircuitSerializer(serializer.Serializer):
                     tag.to_proto(msg=msg.tags.add())
                 if (tag_index := raw_constants.get(tag, None)) is None:
                     constant = v2.program_pb2.Constant()
-                    tag_index = len(constants)
                     if self.tag_serializer and self.tag_serializer.can_serialize_tag(tag):
-                        tag_proto = self.tag_serializer.to_proto(
-                            tag, constants=constants, raw_constants=raw_constants
+                        self.tag_serializer.to_proto(
+                            tag,
+                            msg=constant.tag_value,
+                            constants=constants,
+                            raw_constants=raw_constants,
                         )
-                        constants.append(v2.program_pb2.Constant(tag_value=tag_proto))
-                        if raw_constants is not None:
-                            raw_constants[tag] = tag_index
-                        msg.tag_indices.append(tag_index)
                     elif getattr(tag, 'to_proto', None) is not None:
                         tag.to_proto(constant.tag_value)  # type: ignore
+                    if constant.WhichOneof('const_value'):
+                        tag_index = len(constants)
                         constants.append(constant)
                         if raw_constants is not None:
                             raw_constants[tag] = tag_index

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Changed.

Comment on lines 1052 to 1056
msg: Optional[v2.program_pb2.CircuitOperation] = None,
*,
constants: List[v2.program_pb2.Constant],
raw_constants: Dict[Any, int],
) -> v2.program_pb2.CircuitOperation:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Typo in annotation -

Suggested change
msg: Optional[v2.program_pb2.CircuitOperation] = None,
*,
constants: List[v2.program_pb2.Constant],
raw_constants: Dict[Any, int],
) -> v2.program_pb2.CircuitOperation:
msg: Optional[v2.program_pb2.Tag] = None,
*,
constants: List[v2.program_pb2.Constant],
raw_constants: Dict[Any, int],
) -> v2.program_pb2.Tag:

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.

Copy link
Collaborator Author

@dstrain115 dstrain115 left a comment

Choose a reason for hiding this comment

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

Thanks for the quick review!

Comment on lines 1052 to 1056
msg: Optional[v2.program_pb2.CircuitOperation] = None,
*,
constants: List[v2.program_pb2.Constant],
raw_constants: Dict[Any, int],
) -> v2.program_pb2.CircuitOperation:
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.

),
constants=[v2.program_pb2.Constant(qubit=v2.program_pb2.Qubit(id='1_1'))],
)
expected_circuit_no_tag = cirq.Circuit(
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Changed.

Comment on lines 333 to 334
constant = v2.program_pb2.Constant()
tag_index = len(constants)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Changed.

self.discount = discount

def __eq__(self, other):
if isinstance(other, DiscountTag) and self.discount == other.discount:
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good idea. Done.

@dstrain115 dstrain115 requested a review from pavoljuhas March 20, 2025 20:20
if constant.WhichOneof('const_value'):
constants.append(constant)
if raw_constants is not None:
raw_constants[tag] = tag_index
Copy link
Collaborator

Choose a reason for hiding this comment

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

tag_index is unassigned here. nice catch by mypy.

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.

Copy link
Collaborator

@pavoljuhas pavoljuhas left a comment

Choose a reason for hiding this comment

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

LGTM modulo the tag_index typo

@dstrain115 dstrain115 added this pull request to the merge queue Mar 20, 2025
Merged via the queue into quantumlib:main with commit 43d033b Mar 20, 2025
38 checks passed
@dstrain115 dstrain115 deleted the custom_tag_serializers branch March 20, 2025 21:52
BichengYing pushed a commit to BichengYing/Cirq that referenced this pull request Jun 20, 2025
* Add ability to add custom tag (de)serializers

- This adds custom tag serializers for serializing tags.
- This allows greater flexibility and a much easier way to
specify a serializer to serialize and deserialize internal tags.

* Fix types.

* Fix coverage

* Address comments.

* Fix unassigned variable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants