Skip to content

Commit

Permalink
Adding default values to op serializers and deserializers (#3280)
Browse files Browse the repository at this point in the history
- This will allow us to have more efficient passing of values over
the wire for common or missing values.
- This will also allow tokens for focused calibrations (see PR #3269)
to not add a token arg for every gate.
- This will also add defaults for deserialization only.

Note: a second PR will later be needed to add the defaults for
serializers.  This is done in two steps for backwards compatibility.
We need the ability to correct for defaults in deserialization on
all servers before we can add support for defaults in serialization.
  • Loading branch information
dstrain115 committed Sep 25, 2020
1 parent fa433c3 commit 730cc24
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 19 deletions.
30 changes: 23 additions & 7 deletions cirq/google/common_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,12 @@ def _convert_physical_z(op: ops.Operation, proto: v2.program_pb2.Operation):
op_deserializer.DeserializingArg(
serialized_name='axis_half_turns',
constructor_arg_name='phase_exponent',
default=0.0,
),
op_deserializer.DeserializingArg(
serialized_name='half_turns',
constructor_arg_name='exponent',
default=1.0,
),
],
),
Expand All @@ -189,6 +191,7 @@ def _convert_physical_z(op: ops.Operation, proto: v2.program_pb2.Operation):
op_deserializer.DeserializingArg(
serialized_name='half_turns',
constructor_arg_name='exponent',
default=1.0,
),
],
op_wrapper=lambda op, proto: _convert_physical_z(op, proto)),
Expand All @@ -199,14 +202,17 @@ def _convert_physical_z(op: ops.Operation, proto: v2.program_pb2.Operation):
op_deserializer.DeserializingArg(
serialized_name='x_exponent',
constructor_arg_name='x_exponent',
default=0.0,
),
op_deserializer.DeserializingArg(
serialized_name='z_exponent',
constructor_arg_name='z_exponent',
default=0.0,
),
op_deserializer.DeserializingArg(
serialized_name='axis_phase_exponent',
constructor_arg_name='axis_phase_exponent',
default=0.0,
),
],
),
Expand Down Expand Up @@ -322,7 +328,8 @@ def _convert_physical_z(op: ops.Operation, proto: v2.program_pb2.Operation):
args=[
op_deserializer.DeserializingArg(
serialized_name='axis_half_turns',
constructor_arg_name='phase_exponent'),
constructor_arg_name='phase_exponent',
),
op_deserializer.DeserializingArg(serialized_name='axis_half_turns',
constructor_arg_name='exponent',
value_func=lambda _: 1),
Expand Down Expand Up @@ -376,8 +383,11 @@ def _convert_physical_z(op: ops.Operation, proto: v2.program_pb2.Operation):
serialized_gate_id='cz',
gate_constructor=ops.CZPowGate,
args=[
op_deserializer.DeserializingArg(serialized_name='half_turns',
constructor_arg_name='exponent')
op_deserializer.DeserializingArg(
serialized_name='half_turns',
constructor_arg_name='exponent',
default=1.0,
)
])

#
Expand Down Expand Up @@ -539,10 +549,16 @@ def _can_serialize_limited_iswap(exponent: float):
serialized_gate_id='fsim',
gate_constructor=ops.FSimGate,
args=[
op_deserializer.DeserializingArg(serialized_name='theta',
constructor_arg_name='theta'),
op_deserializer.DeserializingArg(serialized_name='phi',
constructor_arg_name='phi'),
op_deserializer.DeserializingArg(
serialized_name='theta',
constructor_arg_name='theta',
default=0.0,
),
op_deserializer.DeserializingArg(
serialized_name='phi',
constructor_arg_name='phi',
default=0.0,
),
])


Expand Down
15 changes: 11 additions & 4 deletions cirq/google/op_deserializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@ class DeserializingArg:
None.
required: Whether a value must be specified when constructing the
deserialized gate. Defaults to True.
default: default value to set if the value is not present in the
arg. If set, required is ignored.
"""
serialized_name: str
constructor_arg_name: str
value_func: Optional[Callable[[arg_func_langs.ARG_LIKE], Any]] = None
required: bool = True
default: Any = None


class GateOpDeserializer:
Expand Down Expand Up @@ -107,10 +110,14 @@ def _args_from_proto(self, proto: v2.program_pb2.Operation, *,
) -> Dict[str, arg_func_langs.ARG_LIKE]:
return_args = {}
for arg in self.args:
if arg.serialized_name not in proto.args and arg.required:
raise ValueError(
'Argument {} not in deserializing args, but is required.'.
format(arg.serialized_name))
if arg.serialized_name not in proto.args:
if arg.default:
return_args[arg.constructor_arg_name] = arg.default
continue
elif arg.required:
raise ValueError(
f'Argument {arg.serialized_name} '
'not in deserializing args, but is required.')

value = arg_func_langs._arg_from_proto(
proto.args[arg.serialized_name],
Expand Down
27 changes: 27 additions & 0 deletions cirq/google/op_deserializer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,30 @@ def test_from_proto_required_arg_not_assigned():
})
with pytest.raises(ValueError):
deserializer.from_proto(serialized)


def test_defaults():
deserializer = cg.GateOpDeserializer(
serialized_gate_id='my_gate',
gate_constructor=GateWithAttribute,
args=[
cg.DeserializingArg(serialized_name='my_val',
constructor_arg_name='val',
default=1.0),
cg.DeserializingArg(serialized_name='not_req',
constructor_arg_name='not_req',
default='hello',
required=False)
])
serialized = op_proto({
'gate': {
'id': 'my_gate'
},
'args': {},
'qubits': [{
'id': '1_2'
}]
})
g = GateWithAttribute(1.0)
g.not_req = 'hello'
assert deserializer.from_proto(serialized) == g(cirq.GridQubit(1, 2))
19 changes: 11 additions & 8 deletions cirq/google/op_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

from dataclasses import dataclass
from typing import (Callable, List, Optional, Type, TypeVar, Union,
from typing import (Any, Callable, List, Optional, Type, TypeVar, Union,
TYPE_CHECKING)

import numpy as np
Expand Down Expand Up @@ -44,11 +44,14 @@ class SerializingArg:
returns this value (i.e. `lambda x: default_value`)
required: Whether this argument is a required argument for the
serialized form.
default: default value. avoid serializing if this is the value.
Note that the DeserializingArg must also have this as default.
"""
serialized_name: str
serialized_type: Type[arg_func_langs.ARG_LIKE]
op_getter: Union[str, Callable[['cirq.Operation'], arg_func_langs.ARG_LIKE]]
required: bool = True
default: Any = None


class GateOpSerializer:
Expand Down Expand Up @@ -121,7 +124,7 @@ def to_proto(
msg.qubits.add().id = v2.qubit_to_proto_id(qubit)
for arg in self.args:
value = self._value_from_gate(op, arg)
if value is not None:
if value is not None and (not arg.default or value != arg.default):
_arg_to_proto(value,
out=msg.args[arg.serialized_name],
arg_function_language=arg_function_language)
Expand Down Expand Up @@ -156,16 +159,16 @@ def _value_from_gate(self, op: 'cirq.Operation', arg: SerializingArg

def _check_type(self, value: arg_func_langs.ARG_LIKE,
arg: SerializingArg) -> None:
if arg.serialized_type == List[bool]:
if (not isinstance(value, (list, tuple, np.ndarray)) or
not all(isinstance(x, (bool, np.bool_)) for x in value)):
raise ValueError('Expected type List[bool] but was {}'.format(
type(value)))
elif arg.serialized_type == float:
if arg.serialized_type == float:
if not isinstance(value, (float, int)):
raise ValueError(
'Expected type convertible to float but was {}'.format(
type(value)))
elif arg.serialized_type == List[bool]:
if (not isinstance(value, (list, tuple, np.ndarray)) or
not all(isinstance(x, (bool, np.bool_)) for x in value)):
raise ValueError('Expected type List[bool] but was {}'.format(
type(value)))
elif value is not None and not isinstance(value, arg.serialized_type):
raise ValueError(
'Argument {} had type {} but gate returned type {}'.format(
Expand Down
38 changes: 38 additions & 0 deletions cirq/google/op_serializer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,41 @@ def test_can_serialize_operation_subclass():
q = cirq.GridQubit(1, 1)
assert serializer.can_serialize_operation(SubclassGate(1)(q))
assert not serializer.can_serialize_operation(SubclassGate(0)(q))


def test_defaults_not_serialized():
serializer = cg.GateOpSerializer(gate_type=GateWithAttribute,
serialized_gate_id='my_gate',
args=[
cg.SerializingArg(
serialized_name='my_val',
serialized_type=float,
default=1.0,
op_getter='val')
])
q = cirq.GridQubit(1, 2)
no_default = op_proto({
'gate': {
'id': 'my_gate'
},
'args': {
'my_val': {
'arg_value': {
'float_value': 0.125
}
}
},
'qubits': [{
'id': '1_2'
}]
})
assert no_default == serializer.to_proto(GateWithAttribute(0.125)(q))
with_default = op_proto({
'gate': {
'id': 'my_gate'
},
'qubits': [{
'id': '1_2'
}]
})
assert with_default == serializer.to_proto(GateWithAttribute(1.0)(q))

0 comments on commit 730cc24

Please sign in to comment.