Skip to content

Commit

Permalink
Fix export_lib.make_tensor_spec (#19915)
Browse files Browse the repository at this point in the history
* Fix `export_lib.make_tensor_spec`

* Add test

* chore(format)
  • Loading branch information
Grvzard authored Jun 25, 2024
1 parent b038ce2 commit 558d38c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
11 changes: 8 additions & 3 deletions keras/src/export/export_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,13 +654,18 @@ def make_tensor_spec(structure):
# into plain Python structures because they don't work with jax2tf/JAX.
if isinstance(structure, dict):
return {k: make_tensor_spec(v) for k, v in structure.items()}
if isinstance(structure, (list, tuple)):
elif isinstance(structure, tuple):
if all(isinstance(d, (int, type(None))) for d in structure):
return tf.TensorSpec(
shape=(None,) + structure[1:], dtype=model.input_dtype
)
result = [make_tensor_spec(v) for v in structure]
return tuple(result) if isinstance(structure, tuple) else result
return tuple(make_tensor_spec(v) for v in structure)
elif isinstance(structure, list):
if all(isinstance(d, (int, type(None))) for d in structure):
return tf.TensorSpec(
shape=[None] + structure[1:], dtype=model.input_dtype
)
return [make_tensor_spec(v) for v in structure]
else:
raise ValueError(
f"Unsupported type {type(structure)} for {structure}"
Expand Down
16 changes: 16 additions & 0 deletions keras/src/export/export_lib_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,22 @@ def call(self, inputs):
)
revived_model.serve(bigger_input)

# Test with keras.saving_lib
temp_filepath = os.path.join(
self.get_temp_dir(), "exported_model.keras"
)
saving_lib.save_model(model, temp_filepath)
revived_model = saving_lib.load_model(
temp_filepath,
{
"TupleModel": TupleModel,
"ArrayModel": ArrayModel,
"DictModel": DictModel,
},
)
self.assertAllClose(ref_output, revived_model(ref_input))
export_lib.export_model(revived_model, self.get_temp_dir())

def test_model_with_multiple_inputs(self):

class TwoInputsModel(models.Model):
Expand Down

0 comments on commit 558d38c

Please sign in to comment.