The Keras training infrastructure in TensorFlow provides a high-level API for orchestrating machine learning workflows. It centers around the Model.fit execution loop, which abstracts data ingestion via adapters, loss and metric computation, and a sophisticated callback system for monitoring and side-effect management.
Model.fit)The Model.fit method in tensorflow/python/keras/engine/training.py is the entry point for supervised training. It handles the transition from raw input data to executed gradient updates.
Before training begins, the DataAdapter system converts various input types (NumPy arrays, tf.data.Dataset, Python generators) into a unified tf.data.Dataset format tensorflow/python/keras/engine/data_adapter.py55-80
| Adapter Class | Input Type Handled | Source |
|---|---|---|
TensorDataAdapter | Eager Tensors | tensorflow/python/keras/engine/data_adapter.py293 |
NumpyArrayDataAdapter | NumPy Arrays | tensorflow/python/keras/engine/data_adapter.py195 |
DatasetAdapter | tf.data.Dataset | tensorflow/python/keras/engine/data_adapter.py535 |
GeneratorDataAdapter | Python Generators | tensorflow/python/keras/engine/data_adapter.py787 |
The training loop utilizes train_function, which is a compiled tf.function that wraps a single step of training tensorflow/python/keras/engine/training.py821-840
Model Training Data Flow
Sources: tensorflow/python/keras/engine/training.py759-800 tensorflow/python/keras/engine/data_adapter.py55-138
Callbacks are objects that can perform actions at various stages of training (e.g., at the start/end of epochs or batches). The CallbackList class acts as a container and dispatcher for these events tensorflow/python/keras/callbacks.py195-200
on_train_begin / on_train_end: Called at the start and end of fit.on_epoch_begin / on_epoch_end: Called at the start and end of every epoch.on_train_batch_begin / on_train_batch_end: Called before and after every batch update.ModelCheckpoint: Periodically saves the Keras model or weights to a given path tensorflow/python/keras/callbacks.py1218-1250EarlyStopping: Monitors a specific metric and stops training when improvement ceases tensorflow/python/keras/callbacks.py1655-1680TensorBoard: Writes logs for visualization in the TensorBoard dashboard tensorflow/python/keras/callbacks.py2058-2100History: Automatically applied to all models to record metrics for each epoch tensorflow/python/keras/callbacks.py1100-1110Sources: tensorflow/python/keras/callbacks.py17-133
Metrics and losses are specialized Layer subclasses that track state across batches.
The Metric base class requires subclasses to implement update_state(), result(), and reset_state() tensorflow/python/keras/metrics.py74-144
update_state: Logic for accumulating statistics (e.g., sum of squares, true positive counts) tensorflow/python/keras/metrics.py129-140result: Logic for computing the final metric value from accumulated state tensorflow/python/keras/metrics.py141-142The Loss base class handles the reduction of per-sample losses into a scalar value tensorflow/python/keras/losses.py48-84 It supports different Reduction types: AUTO, SUM_OVER_BATCH_SIZE, SUM, and NONE tensorflow/python/keras/losses.py86-103
Metric State Management
Sources: tensorflow/python/keras/metrics.py74-144 tensorflow/python/keras/losses.py48-157
Keras supports mixed precision training, where most operations use float16 for speed, while certain variables (like weights) remain in float32 for numerical stability.
Policy: Controls the compute_dtype and variable_dtype for layers tensorflow/python/keras/mixed_precision/policy.py30-60LossScaleOptimizer: Wraps a standard optimizer to scale the loss. This prevents "gradient underflow" where small gradients vanish when converted to float16 tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py54-100Layer class automatically casts inputs to the policy's compute_dtype during the call() method tensorflow/python/keras/engine/base_layer.py930-950Mixed Precision Entity Mapping
| Code Entity | Responsibility | Source |
|---|---|---|
Policy | Defines dtype pairs (e.g., "mixed_float16") | tensorflow/python/keras/mixed_precision/policy.py30 |
LossScaleOptimizer | Scales loss before backprop, unscales gradients after | tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py54 |
autocast_variable | Ensures variables are read in the correct dtype | tensorflow/python/keras/engine/base_layer.py53 |
Sources: tensorflow/python/keras/mixed_precision/policy.py30-60 tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py54-150 tensorflow/python/keras/engine/base_layer.py97-150