Skip to content

Commit 636e9c2

Browse files
edlopertensorflower-gardener
authored andcommitted
Add SavedModel support for tf.Struct.
PiperOrigin-RevId: 370447441 Change-Id: I583ce72dd399c21066cfb847ee818c74650063b9
1 parent 559047c commit 636e9c2

2 files changed

Lines changed: 48 additions & 11 deletions

File tree

‎tensorflow/python/framework/tensor_struct.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,8 +274,9 @@ class StructSpec(type_spec.TypeSpec):
274274
"""Base class for tf.Struct TypeSpec."""
275275

276276
def _serialize(self): # TypeSpec API.
277-
# TODO(b/184565242) Preserve the order of the fields in the TypeSpec?
278-
return _change_nested_mappings_to(self.__dict__, dict)
277+
return tuple(
278+
(f.name, _change_nested_mappings_to(self.__dict__[f.name], dict))
279+
for f in self._tf_struct_fields())
279280

280281
@classmethod
281282
def _deserialize(cls, state): # TypeSpec API.
@@ -487,3 +488,8 @@ def _add_type_spec(cls):
487488
_build_spec_constructor(spec)
488489

489490
cls.__abstractmethods__ -= {'_type_spec'}
491+
492+
# If the user included an explicit `__name__` attribute, then use that to
493+
# register the TypeSpec (so it can be used in SavedModel signatures).
494+
if '__name__' in cls.__dict__:
495+
type_spec.register(cls.__dict__['__name__'] + '.Spec')(spec)

‎tensorflow/python/framework/tensor_struct_test.py‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""Tests for tf.framework.tensor_struct."""
1616

1717
import contextlib
18+
import tempfile
1819
import typing
1920

2021
from absl.testing import parameterized
@@ -29,12 +30,16 @@
2930
from tensorflow.python.framework import tensor_spec
3031
from tensorflow.python.framework import tensor_struct
3132
from tensorflow.python.framework import test_util
33+
from tensorflow.python.module import module
3234
from tensorflow.python.ops import array_ops
3335
from tensorflow.python.ops import control_flow_ops
3436
from tensorflow.python.ops import math_ops
3537
from tensorflow.python.ops.ragged import ragged_factory_ops
3638
from tensorflow.python.ops.ragged import ragged_tensor
3739
from tensorflow.python.platform import googletest
40+
from tensorflow.python.platform import test
41+
from tensorflow.python.saved_model import load
42+
from tensorflow.python.saved_model import save
3843
from tensorflow.python.util import dispatch
3944
from tensorflow.python.util import nest
4045
from tensorflow.python.util import tf_inspect
@@ -694,6 +699,33 @@ def testStructBaseConstructorRaisesException(self):
694699
'Struct is an abstract base class.'):
695700
tensor_struct.Struct()
696701

702+
class StructWithName(tensor_struct.Struct):
703+
__name__ = 'tf.__test__.StructWithName' # For SavedModel serialization
704+
x: typing.Tuple[ops.Tensor, int]
705+
y: ops.Tensor
706+
707+
def testSavedModelSupport(self):
708+
709+
class TestModule(module.Module):
710+
711+
@def_function.function
712+
def f(self, s):
713+
return s.x[0] + s.x[1] + s.y
714+
715+
s1 = self.StructWithName((1, 2), 3)
716+
s2 = self.StructWithName((1.0, 2), [3.0, 4.0])
717+
718+
m = TestModule()
719+
m.f.get_concrete_function(s1)
720+
m.f.get_concrete_function(s2)
721+
722+
path = tempfile.mkdtemp(prefix=test.get_temp_dir())
723+
save.save(m, path)
724+
loaded = load.load(path)
725+
726+
self.assertAllEqual(loaded.f(s1), 6)
727+
self.assertAllEqual(loaded.f(s2), [6.0, 7.0])
728+
697729

698730
@test_util.run_all_in_graph_and_eager_modes
699731
class StructSpecTest(test_util.TensorFlowTestCase, parameterized.TestCase):
@@ -768,20 +800,19 @@ class Zoo(tensor_struct.Struct):
768800
})
769801

770802
serialized = zoo_spec._serialize()
771-
self.assertEqual(
772-
serialized,
773-
dict(
774-
zookeepers=('Zoey', 'Zack'),
775-
animals={
776-
'tiger': featurespec,
777-
'elephant': featurespec
778-
}))
803+
self.assertEqual(serialized,
804+
(('zookeepers', ('Zoey', 'Zack')), ('animals', {
805+
'tiger': featurespec,
806+
'elephant': featurespec
807+
})))
779808
restored = Zoo.Spec._deserialize(serialized)
780809
self.assertEqual(zoo_spec, restored)
781810

782811
# ImmutableDict is used for the field, but dict for the serialization:
783812
self.assertIsInstance(zoo_spec.animals, immutable_dict.ImmutableDict)
784-
self.assertIsInstance(serialized['animals'], dict)
813+
serialized_field_name, serialized_field_value = serialized[1]
814+
self.assertEqual(serialized_field_name, 'animals')
815+
self.assertIsInstance(serialized_field_value, dict)
785816

786817
def testSpecComponents(self):
787818

0 commit comments

Comments
 (0)