Callbacks graph mode and export
Quick answer
Callbacks observe training events and can stop or record training. TensorFlow eager execution evaluates operations immediately; tf.function traces a graph for repeated execution. Model persistence and inference export are separate artifact types. Native TensorFlow examples are unexecuted; local Keras uses Torch. ByteMind execution is unverified.
Early stopping on a synthetic loss trace
import osos.environ["KERAS_BACKEND"]="torch"import kerasm=keras.Sequential([keras.Input((1,)),keras.layers.Dense(1)])c=keras.callbacks.EarlyStopping(monitor="val_loss",mode="min",patience=2,restore_best_weights=True)m.stop_training=False; c.set_model(m); c.on_train_begin()for epoch,v in enumerate([3.,2.,2.5,2.6]): c.on_epoch_end(epoch,{"val_loss":v}) if m.stop_training: breakc.on_train_end()print(epoch+1,c.best_epoch+1)Expected output (locally tested): 4 2. The synthetic callback trace stops after two non-improving epochs; best epoch is two (one-based).
How it works
EarlyStopping(monitor="val_loss",mode="min",patience=3,restore_best_weights=True) compares validation loss across epochs and restores the best observed model weights (not necessarily matching optimizer state). Callbacks do not make the test set a tuning set. With TensorFlow backend, tf.function traces tensor operations, can retrace for new shapes or Python values, and may execute Python print only during tracing; use tf.print for execution-time tensor diagnostics. Input signatures can limit retracing. Keras compile(run_eagerly=True) helps debugging; compiled training behavior is backend-dependent and is not automatically a TensorFlow graph on Torch. Keras 3 model.save("model.keras") stores native model configuration, weights and optimizer state when supported. keras.models.load_model restores compatible trusted artifacts; keep safe_mode=True for native format, but do not treat it as a security sandbox. For TensorFlow serving use model.export(path,format="tf_saved_model") in a supported TensorFlow lane; use tf.saved_model.load or a compatible serving interface, not Keras 3 load_model for a SavedModel directory. Export signatures, preprocessing and parity need separate tests.
Native Keras save and restore
import os,tempfile,pathlibos.environ["KERAS_BACKEND"]="torch"import keras,numpy as npfrom keras import opsm=keras.Sequential([keras.Input((1,)),keras.layers.Dense(1,kernel_initializer="ones",bias_initializer="zeros")])x=np.array([[3.]],dtype="float32")with tempfile.TemporaryDirectory() as d: p=pathlib.Path(d)/"local.keras"; m.save(p) r=keras.models.load_model(p,safe_mode=True) print(ops.convert_to_numpy(r(x)).tolist())Expected output (locally tested): [[3.0]]. Load only the locally created artifact; this is native model restoration, not SavedModel serving export.
Common mistakes
Do not pick epochs using test loss, confuse a training checkpoint with a serving export, or disable safe loading for unknown custom objects. Restoring best weights is not the same as resuming an entire optimizer trajectory.
Practice and next steps
Run the milestone with the tested Torch backend and compare evaluation metrics. The optional TensorFlow backend and export require separate verification in a compatible environment. Next: deep learning optimization and regularization.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Callbacks graph mode and export — knowledge check
Apply callbacks graph mode and export to small examples and debugging scenarios.
Which metric should drive early stopping?
What does restore_best_weights restore?
What can trigger tf.function retracing?
What is the native Keras 3 model extension?
How should a TensorFlow SavedModel be loaded for serving?