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 the issue when using Model.compile multiple times #20602

Merged
merged 1 commit into from
Dec 6, 2024
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
16 changes: 0 additions & 16 deletions keras/src/trainers/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ def compile(
wrapped in a `LossScaleOptimizer`, which will dynamically
scale the loss to prevent underflow.
"""
self._clear_previous_trainer_metrics()
optimizer = optimizers.get(optimizer)
self.optimizer = optimizer
if (
Expand Down Expand Up @@ -287,21 +286,6 @@ def _get_own_metrics(self):
metrics.extend(self._metrics)
return metrics

def _clear_previous_trainer_metrics(self):
for layer in self._flatten_layers(include_self=False):
if not isinstance(layer, Trainer):
continue
# A sublayer might be a Trainer. In that case, we need to clear
# the Trainer-related metrics, as they are not usable when a
# new Trainer is instantiated.
for m in self._get_own_metrics():
layer._tracker.untrack(m)
layer._loss_tracker = None
layer._compile_metrics = None
if layer._compile_loss is not None:
layer._compile_loss._metrics.clear()
layer._metrics.clear()

def compute_loss(
self,
x=None,
Expand Down
32 changes: 32 additions & 0 deletions keras/src/trainers/trainer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,38 @@ def test_nested_trainer_metrics_without_compile(self):
self.assertEqual(new_model.metrics[0], new_model._loss_tracker)
self.assertEqual(new_model.metrics[1], new_model._compile_metrics)

def test_multiple_compiles(self):
# https://github.com/keras-team/keras/issues/20474
model1 = ExampleModel(units=3)
model2 = ExampleModel(units=3)
model1.compile(
optimizer=optimizers.SGD(),
loss=losses.MeanSquaredError(),
metrics=[metrics.MeanSquaredError()],
)

# Combine these 2 models into `combined`.
inputs = keras.Input(shape=(4,))
x = model1(inputs)
outputs = model2(x)
combined = models.Model(inputs, outputs)
combined.compile(
optimizer=optimizers.SGD(),
loss=losses.MeanSquaredError(),
metrics=[metrics.MeanSquaredError()],
)

self.assertLen(model1.metrics, 2)
self.assertIsNotNone(model1._loss_tracker)
self.assertEqual(model1.metrics[0], model1._loss_tracker)
self.assertEqual(model1.metrics[1], model1._compile_metrics)

# `combined.metrics` will not include `model1.metrics`.
self.assertLen(combined.metrics, 2)
self.assertIsNotNone(combined._loss_tracker)
self.assertEqual(combined.metrics[0], combined._loss_tracker)
self.assertEqual(combined.metrics[1], combined._compile_metrics)

@pytest.mark.skipif(
backend.backend() != "torch",
reason="torch backend runs in eager mode for jit_compile='auto'",
Expand Down
Loading