Skip to content

Commit c512b1a

Browse files
Preserve tuples in TypeSpecs.
PiperOrigin-RevId: 690793837
1 parent f7b9120 commit c512b1a

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

tf_keras/saving/legacy/saved_model/json_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def get_json_type(obj):
210210
return {
211211
"class_name": "TypeSpec",
212212
"type_spec": type_spec_name,
213-
"serialized": obj._serialize(),
213+
"serialized": _encode_tuple(obj._serialize()),
214214
}
215215
except ValueError:
216216
raise ValueError(

tf_keras/saving/legacy/saved_model/json_utils_test.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"""Tests the JSON encoder and decoder."""
1717

1818
import enum
19+
from typing import Mapping
1920

2021
import tensorflow.compat.v2 as tf
2122

@@ -24,6 +25,16 @@
2425
from tf_keras.testing_infra import test_utils
2526

2627

28+
class _ExtensionType(tf.experimental.ExtensionType):
29+
"""An ExtensionType with multiple tuples and mappings."""
30+
31+
__name__ = "tf_keras.json_utils.test._ExtensionType"
32+
33+
x: tf.Tensor
34+
xy: tuple[tf.Tensor, tf.Tensor]
35+
kv: Mapping[str, tf.Tensor]
36+
37+
2738
class JsonUtilsTest(test_combinations.TestCase):
2839
def test_encode_decode_tensor_shape(self):
2940
metadata = {
@@ -64,6 +75,17 @@ def test_encode_decode_type_spec(self):
6475
):
6576
loaded = json_utils.decode(string)
6677

78+
def test_encode_decode_extensiontype_spec(self):
79+
instance = _ExtensionType(
80+
x=tf.constant(1),
81+
xy=(tf.constant(2), tf.constant(True)),
82+
kv={"a": tf.constant("foo"), "b": tf.constant("bar")},
83+
)
84+
spec = tf.type_spec_from_value(instance)
85+
string = json_utils.Encoder().encode(spec)
86+
loaded = json_utils.decode(string)
87+
self.assertEqual(spec, loaded)
88+
6789
def test_encode_decode_enum(self):
6890
class Enum(enum.Enum):
6991
CLASS_A = "a"

0 commit comments

Comments
 (0)