Keras callbacks
W&B has three callbacks for Keras, available fromwandb v0.13.4. For the legacy WandbCallback scroll down.
-
WandbMetricsLogger: Use this callback for Experiment Tracking. It logs your training and validation metrics along with system metrics to W&B. -
WandbModelCheckpoint: Use this callback to log your model checkpoints to W&B Artifacts. -
WandbEvalCallback: This base callback logs model predictions to W&B Tables for interactive visualization.
- Adhere to Keras design philosophy.
- Reduce the cognitive load of using a single callback (
WandbCallback) for everything. - Make it easy for Keras users to modify the callback by subclassing it to support their niche use case.
Track experiments with WandbMetricsLogger
WandbMetricsLogger automatically logs Keras’ logs dictionary that callback methods such as on_epoch_end, on_batch_end etc, take as an argument.
This tracks:
- Training and validation metrics defined in
model.compile. - System (CPU/GPU/TPU) metrics.
- Learning rate (both for a fixed value or a learning rate scheduler.
WandbMetricsLogger reference
Checkpoint a model using WandbModelCheckpoint
Use WandbModelCheckpoint callback to save the Keras model (SavedModel format) or model weights periodically and uploads them to W&B as a wandb.Artifact for model versioning.
This callback is subclassed from tf.keras.callbacks.ModelCheckpoint ,thus the checkpointing logic is taken care of by the parent callback.
This callback saves:
- The model that has achieved best performance based on the monitor.
- The model at the end of every epoch regardless of the performance.
- The model at the end of the epoch or after a fixed number of training batches.
- Only model weights or the whole model.
- The model either in
SavedModelformat or in.h5format.
WandbMetricsLogger.
WandbModelCheckpoint reference
Log checkpoints after N epochs
By default (save_freq="epoch"), the callback creates a checkpoint and uploads it as an artifact after each epoch. To create a checkpoint after a specific number of batches, set save_freq to an integer. To checkpoint after N epochs, compute the cardinality of the train dataloader and pass it to save_freq:
Efficiently log checkpoints on a TPU architecture
While checkpointing on TPUs you might encounterUnimplementedError: File system scheme '[local]' not implemented error message. This happens because the model directory (filepath) must use a cloud storage bucket path (gs://bucket-name/...), and this bucket must be accessible from the TPU server. We can however, use the local path for checkpointing which in turn is uploaded as an Artifacts.
Visualize model predictions using WandbEvalCallback
The WandbEvalCallback is an abstract base class to build Keras callbacks primarily for model prediction and, secondarily, dataset visualization.
This abstract callback is agnostic with respect to the dataset and the task. To use this, inherit from this base WandbEvalCallback callback class and implement the add_ground_truth and add_model_prediction methods.
The WandbEvalCallback is a utility class that provides methods to:
- Create data and prediction
wandb.Tableinstances. - Log data and prediction Tables as
wandb.Artifact. - Log the data table
on_train_begin. - log the prediction table
on_epoch_end.
WandbClfEvalCallback for an image classification task. This example callback logs the validation data (data_table) to W&B, performs inference, and logs the prediction (pred_table) to W&B at the end of every epoch.
The W&B Artifact page includes Table logs by default, rather than the Workspace page.
WandbEvalCallback reference
Memory footprint details
We log thedata_table to W&B when the on_train_begin method is invoked. Once it’s uploaded as a W&B Artifact, we get a reference to this table which can be accessed using data_table_ref class variable. The data_table_ref is a 2D list that can be indexed like self.data_table_ref[idx][n], where idx is the row number while n is the column number. Let’s see the usage in the example below.
Customize the callback
You can override theon_train_begin or on_epoch_end methods to have more fine-grained control. If you want to log the samples after N batches, you can implement on_train_batch_end method.
If you are implementing a callback for model prediction visualization by inheriting
WandbEvalCallback and something needs to be clarified or fixed, let us know by opening an issue.WandbCallback [legacy]
Use the W&B library WandbCallback Class to automatically save all the metrics and the loss values tracked in model.fit.
See our example repo for scripts, including a Fashion MNIST example and the W&B Dashboard it generates.
WandbCallback class supports a wide variety of logging configuration options: specifying a metric to monitor, tracking of weights and gradients, logging of predictions on training_data and validation_data, and more.
Check out the reference documentation for the keras.WandbCallback for full details.
The WandbCallback
- Automatically logs history data from any metrics collected by Keras: loss and anything passed into
keras_model.compile(). - Sets summary metrics for the run associated with the “best” training step, as defined by the
monitorandmodeattributes. This defaults to the epoch with the minimumval_loss.WandbCallbackby default saves the model associated with the bestepoch. - Optionally logs gradient and parameter histogram.
- Optionally saves training and validation data for wandb to visualize.
WandbCallback reference
Frequently Asked Questions
How do I use Keras multiprocessing with wandb?
When setting use_multiprocessing=True, this error may occur:
- In the
Sequenceclass construction, add:wandb.init(group='...'). - In
main, make sure you’re usingif __name__ == "__main__":and put the rest of your script logic inside it.