Skip to content

Commit

Permalink
Fixed layer.losses such that it recurses into sublayer losses (#18828)
Browse files Browse the repository at this point in the history
* Fixed layer.losses such that it recurses into sublayer losses

* moved recursion into sub function

* moved recursion to losses property
  • Loading branch information
jackd authored Nov 26, 2023
1 parent 9620d23 commit 0b20c8d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions keras/layers/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1073,9 +1073,9 @@ def _get_own_losses(self):

@property
def losses(self):
"""List of scalar losses added via `add_loss()` during layer call."""
"""List of scalar losses from `add_loss`, regularizers and sublayers."""
losses = self._get_own_losses()
for layer in self._layers:
for layer in self._flatten_layers(include_self=False):
losses.extend(layer._get_own_losses())
weight_regularization_losses = []
for v in self.trainable_weights:
Expand Down
6 changes: 6 additions & 0 deletions keras/layers/layer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,12 @@ def call(self, x):
self.assertLen(model.losses, 1)
self.assertAllClose(model.losses[0], 1.0)

# It works recursively in nested models
model = models.Sequential([model])
model(np.ones((1,)))
self.assertLen(model.losses, 1)
self.assertAllClose(model.losses[0], 1.0)

def test_training_arg_value_resolution(self):
# Check that even if `training` is not passed
# to an inner layer, the outer value gets propagated
Expand Down

0 comments on commit 0b20c8d

Please sign in to comment.