Skip to main content
Use W&B Keras callbacks to track experiments, log model checkpoints, and visualize model predictions during training. Use this integration to add experiment tracking and model versioning to your Keras training workflows without rewriting your training loop. Keras callbacks are available in the wandb.integration.keras module with Python SDK versions 0.13.4 and above. The W&B Keras integration provides the following callbacks:
  • 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.

Install and import Keras integration

Install the latest version of W&B.
To use the Keras integration, import required classes from wandb.integration.keras.
The following sections describe each callback in detail with code examples.

Track experiments with WandbMetricsLogger

wandb.integration.keras.WandbMetricsLogger() logs Keras’ logs dictionary that callback methods such as on_epoch_end and on_batch_end take as an argument. The following partial example shows how to use WandbMetricsLogger() in a Keras workflow. First, compile the model with the desired optimizer, loss function, and metrics. Then, initialize a W&B run using wandb.init(). Finally, pass the WandbMetricsLogger() callback to model.fit().
The previous example logs training and validation metrics such as loss, accuracy, and top@5_accuracy to W&B at the end of each epoch.

WandbMetricsLogger reference

Checkpoint a model using WandbModelCheckpoint

Use the WandbModelCheckpoint callback to periodically save the Keras model (SavedModel format) or model weights and upload them to W&B as a wandb.Artifact for model versioning. This callback subclasses tf.keras.callbacks.ModelCheckpoint(), so the parent callback handles the checkpointing logic. 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 SavedModel format or in .h5 format.
Use this callback in conjunction with 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:

Log checkpoints efficiently on a TPU architecture

While checkpointing on TPUs, you might encounter the UnimplementedError: 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. Instead, W&B uses the local path for checkpointing, which W&B then uploads as an artifact.

Visualize model predictions using WandbEvalCallback

WandbEvalCallback() is an abstract base class for building Keras callbacks, primarily for model prediction and, secondarily, dataset visualization. This abstract callback is independent of the dataset and the task. To use it, inherit from this base WandbEvalCallback() callback class and implement the add_ground_truth and add_model_prediction methods. WandbEvalCallback() is a utility class that provides methods to:
  • Create data and prediction wandb.Table() instances.
  • Log data and prediction Tables as wandb.Artifact().
  • Log the data table on_train_begin.
  • Log the prediction table on_epoch_end.
The following example uses 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.

WandbEvalCallback reference

Memory footprint details

W&B logs the data_table when invoking the on_train_begin method. After W&B uploads it as a W&B Artifact, you get a reference to this table, which you can access using the data_table_ref class variable. The data_table_ref is a 2D list that you can index like self.data_table_ref[idx][n], where idx is the row number and n is the column number. See the usage in the following example.

Customize the callback

For more control over when data and predictions are logged, you can override the default callback methods. Override the on_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 the on_train_batch_end method.
If you’re implementing a callback for model prediction visualization by inheriting WandbEvalCallback and something needs to be clarified or fixed, open an issue.

Legacy WandbCallback

WandbCallback is the legacy all-in-one callback. For new projects, use the dedicated callbacks described in the previous sections (WandbMetricsLogger, WandbModelCheckpoint, and WandbEvalCallback). Use the W&B library WandbCallback() class to save all metrics and loss values tracked in model.fit().
You can watch the short video Get Started with Keras and W&B in Less Than a Minute. For a more detailed video, watch Integrate W&B with Keras. You can review the Colab Jupyter Notebook. For additional sample scripts, see the W&B example repo, including a Fashion MNIST example and the W&B Dashboard it generates. The WandbCallback class supports logging configuration options: specifying a metric to monitor, tracking of weights and gradients, logging of predictions on training_data and validation_data, and more. See the reference documentation for keras.WandbCallback for full details. WandbCallback:
  • 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 monitor and mode attributes. This defaults to the epoch with the minimum val_loss. By default, WandbCallback saves the model associated with the best epoch.
  • Optionally logs gradient and parameter histograms.
  • Optionally saves training and validation data for wandb to visualize.

WandbCallback reference

Frequently asked questions

Use Keras multiprocessing with wandb

When you set use_multiprocessing=True, this error might occur:
To work around it:
  1. In the Sequence class construction, add: wandb.init(group='...').
  2. In main, make sure you use if __name__ == "__main__": and put the rest of your script logic inside it.