keras-team/keras · error · ValueError

`add_loss()` can only be called from inside `build()` or `ca

Error message

`add_loss()` can only be called from inside `build()` or `call()`, on a tensor input. Received invalid value: {x}

What it means

add_loss() accepts only backend tensors. It is meant to be called inside build() or call(); passing Python numbers, NumPy arrays, or anything that is not a backend tensor raises this eager-mode validation error.

Source

Thrown at keras/src/layers/layer.py:1292

    def add_loss(self, loss):
        """Can be called inside of the `call()` method to add a scalar loss.

        Example:

        ```python
        class MyLayer(Layer):
            ...
            def call(self, x):
                self.add_loss(ops.sum(x))
                return x
        ```
        """
        # Eager only.
        losses = tree.flatten(loss)
        for x in losses:
            if not backend.is_tensor(x):
                raise ValueError(
                    "`add_loss()` can only be called from inside `build()` or "
                    f"`call()`, on a tensor input. Received invalid value: {x}"
                )
        if backend.in_stateless_scope():
            scope = backend.get_stateless_scope()
            if scope.collect_losses:
                for x in losses:
                    scope.add_loss(x)
                    self._loss_ids.add(id(x))
        else:
            self._losses.extend(losses)

    def _get_own_losses(self):
        if backend.in_stateless_scope():
            losses = []
            scope = backend.get_stateless_scope()
            for loss in scope.losses:
                if id(loss) in self._loss_ids:

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Wrap values with keras.ops.convert_to_tensor (or use keras.ops operations throughout) before add_loss
  2. Compute losses from layer tensors/variables so the result stays a backend tensor

Example fix

# before
self.add_loss(1e-4 * np.sum(w))
# after
import keras
self.add_loss(1e-4 * keras.ops.sum(keras.ops.convert_to_tensor(w)))
Defensive patterns

Strategy: validation

Validate before calling

import keras
losses = [keras.ops.convert_to_tensor(l) for l in losses]
layer.add_loss(losses)

Prevention

When it happens

Trigger: self.add_loss(0.01 * self.l2) where the value is a Python float/np.ndarray; add_loss(np.array(...)); calling add_loss outside call/build with computed Python scalars.

Common situations: Regularization losses computed with NumPy instead of keras.ops; porting TF1/TF2 code that added float losses; debug code adding constants.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/b74d4616380cdbd9. Report an issue: GitHub.