Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cloning with compiled sequential model #20888

Merged
merged 4 commits into from
Feb 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions keras/src/models/cloning.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,15 @@ def _clone_sequential_model(model, clone_function, input_tensors=None):
name=input_name,
)
new_layers = [inputs] + new_layers
return Sequential(new_layers, name=model.name, trainable=model.trainable)
cloned_model = Sequential(
new_layers, name=model.name, trainable=model.trainable
)

# If model compiled already then set same to cloned model
if model.compiled:
compiled_config = model.get_compile_config()
cloned_model.compile_from_config(compiled_config)
return cloned_model


def _clone_functional_model(
Expand Down Expand Up @@ -405,5 +413,7 @@ def operation_fn(layer):
# class than the original. However various existing models rely
# on this behavior, so we keep it.
new_model = Functional(input_tensors, output_tensors, name=model.name)

if model.compiled:
compiled_config = model.get_compile_config()
new_model.compile_from_config(compiled_config)
return new_model
9 changes: 9 additions & 0 deletions keras/src/models/cloning_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,12 @@ def clone_function(layer):
if isinstance(l2, layers.Dense):
self.assertFalse(hasattr(l1, "flag"))
self.assertTrue(hasattr(l2, "flag"))

def test_compiled_model_cloning(self):
model = models.Sequential()
model.add(layers.Input((3,)))
model.add(layers.Dense(5, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(optimizer="adam", loss="binary_crossentropy")
cloned_model = clone_model(model)
self.assertEqual(model.compiled, cloned_model.compiled)