Workaround for removal of add_loss
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
The add_loss() method in Keras allows layers and models to register auxiliary losses (like regularization penalties, KL divergence in VAEs, or custom constraints) that are automatically included in the total loss during training. While add_loss() still exists in TensorFlow/Keras, its behavior has changed across versions, and some workflows (particularly with tf.function and custom training loops) require alternative approaches. The main workarounds are computing losses directly in the training step, using the losses property, or adding losses through activity_regularizer.
How add_loss Works
During model.fit(), Keras automatically adds sum(model.losses) to the main loss.
Workaround 1: Compute Loss in Custom Training Step
The most reliable approach — compute all losses explicitly:
Workaround 2: Use model.losses in Custom Loop
Collect losses registered via add_loss() and add them manually:
Workaround 3: activity_regularizer
For regularization losses, use the activity_regularizer parameter instead of add_loss:
Workaround 4: Kernel and Bias Regularizers
For weight regularization (L1/L2), use built-in regularizer parameters:
Workaround 5: Custom Loss Function with Extra Terms
Wrap everything into a single loss function:
VAE Complete Example Without add_loss
Common Pitfalls
model.lossesis empty outside forward pass:add_loss()registers losses during the forward pass. If you accessmodel.lossesbefore callingmodel(inputs), the list is empty. Always readmodel.lossesafter the forward pass.- Double-counting losses with
model.fit(): If you useadd_loss()in a layer AND manually add the same loss in a customtrain_step, the loss is counted twice. Choose one approach, not both. tf.add_n(model.losses)fails on empty list: If no layers calladd_loss(),model.lossesis empty andtf.add_n([])raises an error. Guard withif model.losses else 0.0.- add_loss in
@tf.functiontracing: Losses added during@tf.functiontracing are captured once. If the loss depends on dynamic values, ensure the function is traced correctly or use eager mode for debugging. - Keras 3 behavior changes: In Keras 3 (TF 2.16+),
add_loss()behavior may differ from Keras 2. Check the Keras 3 migration guide if upgrading, and prefer explicit loss computation intrain_stepfor maximum compatibility.
Summary
add_loss()still works but alternative patterns are more explicit and portable across Keras versions- Compute all losses directly in a custom
train_stepfor full control and clarity - Use
model.lossesto collect auxiliary losses registered by layers after the forward pass - Use
kernel_regularizerandactivity_regularizerfor standard regularization instead of manualadd_loss - Guard
tf.add_n(model.losses)with an empty-list check to avoid runtime errors
Related reading
- Working with multiple graphs in TensorFlow
- Xavier and he_normal initialization difference
- Y label shape for time_distributed lstm
- YOLO object detection how does the algorithm predict bounding boxes larger than a grid cell?
- Working with SSIM loss function in tensorflow for RGB images
- Write tf.dataset back to TFRecord
- Working of labelEncoder in sklearn
- wrong model type for regression error in 10 fold cross validation for Naive Bayes using R
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.