TerminateOnNaN classkeras.callbacks.TerminateOnNaN(raise_error: bool = False)
Callback that terminates training when a NaN loss is encountered.
This callback monitors the loss value during training
and terminates training when a NaN or Inf loss is detected.
By default, training is stopped gracefully
by setting model.stop_training = True, which triggers all callback cleanup
methods including on_train_end().
Alternatively, you can use raise_error=True to immediately raise a
RuntimeError when NaN/Inf is detected. This raise_error termination
prevents on_train_end() from being called on other callbacks, which
is useful for preserving backup states or preventing unintended cleanup
when training fails.
Arguments
model.stop_training = True. If True, immediately raises
RuntimeError on NaN/Inf loss, bypassing callback cleanup methods.Example
# Graceful termination (default)
callback = keras.callbacks.TerminateOnNaN()
model.fit(x, y, callbacks=[callback])
# raise_error termination (strict failure)
callback = keras.callbacks.TerminateOnNaN(raise_error=True)
model.fit(x, y, callbacks=[callback])