Training Checkpoints

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A checkpoint stores the values of variables, and nothing else: no architecture and no computation. Its job is to let a long training run survive a crash or preemption, to keep the best weights, and to move values between programs. Whole-model artifacts are on Saving Keras Models and SavedModel & Signatures. This page covers the TensorFlow Core API (tf.train.Checkpoint, CheckpointManager), the Keras callbacks (ModelCheckpoint and the Keras 3 OrbaxCheckpoint), and how they fit into the loops of A Training Loop with TF Core, Writing a Training Loop from Scratch and Callbacks. Sharded multi-host checkpoints are touched on in Distributed Training, and the PyTorch analogue is Distributed Checkpoint.

It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming) and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. Snippets that continue an earlier example, or use names such as model and train_ds defined elsewhere, were run with small synthetic stand-ins.

Object-based checkpoints

TensorFlow 2 checkpoints are object-based: a variable is saved and restored by its path through a graph of Python objects (net, then l1, then kernel), not by a variable name. Trackable objects are tf.train.Checkpoint, tf.Module and its subclasses (including Keras layers and models), and the containers dict, list and tuple (including named tuples). defaultdict and set are not supported, and plain int, str and float attributes are ignored, so keep counters in a tf.Variable. The older TF1 name-based style (tf.compat.v1.train.Saver, which keyed on variable names and depended on graph construction order) is legacy; new code does not use it.

import tensorflow as tf
import keras

net = keras.Sequential(
    [keras.Input(shape=(4,)), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(1)]
)
opt = keras.optimizers.Adam(1e-3)
step = tf.Variable(0, dtype=tf.int64)

ckpt = tf.train.Checkpoint(step=step, optimizer=opt, net=net)
manager = tf.train.CheckpointManager(ckpt, directory="./tf_ckpts", max_to_keep=3)

# Resume if something is there
status = ckpt.restore(manager.latest_checkpoint)
print("resumed" if manager.latest_checkpoint else "fresh start")

x = tf.random.normal([32, 4])
y = tf.random.normal([32, 1])

for _ in range(30):
    with tf.GradientTape() as tape:
        loss = tf.reduce_mean(tf.square(net(x) - y))
    grads = tape.gradient(loss, net.trainable_variables)
    opt.apply_gradients(zip(grads, net.trainable_variables))
    step.assign_add(1)
    if int(step) % 10 == 0:
        path = manager.save()                        # ./tf_ckpts/ckpt-1, ckpt-2, ...
        print(f"step {int(step)} loss {float(loss):.4f} saved {path}")

Notes:

  • The keyword names you give Checkpoint(...) become path components. Renaming net= to model= later makes old checkpoints unmatched, so choose names you will keep.

  • CheckpointManager(ckpt, directory, max_to_keep=N) numbers checkpoints, deletes the oldest beyond N, and exposes latest_checkpoint and checkpoints. tf.train.latest_checkpoint(dir) does the same lookup without a manager.

  • A checkpoint path such as ./tf_ckpts/ckpt-3 is a prefix, not a file: on disk it is an .index file plus one or more .data-xxxxx-of-yyyyy files, and a small checkpoint file records the manager state.

  • Keras 3 optimizers are tracked, so the Adam moments and step count are saved. Save the optimizer if you intend to resume rather than fine-tune.

  • Include everything that defines training progress: the step or epoch, the optimizer, the model, and for input pipelines a tf.data iterator (iterator=iter(dataset)), so that data position can be restored too.

Restoring, assertions and deferred restoration

restore returns a status object, and it is the way to learn whether the restore actually matched anything.

new_net = keras.Sequential(
    [keras.Input(shape=(4,)), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(1)]
)
new_ckpt = tf.train.Checkpoint(net=new_net)           # note: no optimizer, no step
status = new_ckpt.restore(tf.train.latest_checkpoint("./tf_ckpts"))

status.assert_existing_objects_matched()              # every object in new_ckpt found its values
# status.assert_consumed()                            # raises AssertionError: the checkpoint also has optimizer, step
status.expect_partial()                               # silence warnings about unused checkpoint values
  • assert_existing_objects_matched() passes when every object in your new Checkpoint received values. Use it for inference or partial restores.

  • assert_consumed() is the strict check: it passes only if the checkpoint and the program match exactly, so it fails when the file contains values (for example optimizer slot variables) with no counterpart in your program. Use it in tests to prove a save/restore round trip is complete.

  • expect_partial() marks a partial restore as intentional and silences the warnings TensorFlow prints at exit for unrestored checkpoint values (described in the tf.train.Checkpoint API reference rather than the guide).

  • Deferred restoration: if a checkpoint holds a value for an object that does not exist yet, for example a layer whose variables are created on first call, the restore is queued and runs as soon as a matching variable is attached. Variables of an unbuilt Keras model therefore get their values when the model is built, so verify with the assertions after the first forward pass rather than immediately.

  • Partial restore of a subset works by rebuilding only the path to the variable you need (Checkpoint(net=Checkpoint(l1=Checkpoint(bias=var)))), which is a good way to lift one layer out of a large checkpoint.

Inspecting a checkpoint

reader = tf.train.load_checkpoint("./tf_ckpts")
for key, shape in reader.get_variable_to_shape_map().items():
    print(key, shape)                                 # e.g. optimizer/_trainable_variables/0/.ATTRIBUTES/VARIABLE_VALUE [4, 8]

print(tf.train.list_variables("./tf_ckpts"))          # list of (name, shape) pairs
value = reader.get_tensor(next(iter(reader.get_variable_to_shape_map())))

The keys are object paths ending in .ATTRIBUTES/VARIABLE_VALUE; the checkpoint has no concept of layers or models. Each variable is stored once, under one path that reaches it: in the example above the model’s kernels appear as optimizer/_trainable_variables/N/... rather than under net/, because the optimizer also tracks them, yet restoring Checkpoint(net=...) still finds them through the saved object graph. CheckpointReader also offers get_variable_to_dtype_map for dtypes, and tf.train.list_variables returns the same keys as sorted (name, shape) pairs.

Keras ModelCheckpoint

In fit, keras.callbacks.ModelCheckpoint saves the model at epoch ends (or every N batches). In Keras 3 its file path must end in .keras for a full model, or .weights.h5 when save_weights_only=True; the old TF-format and .h5 conventions from Keras 2 no longer apply. The formats are explained on Saving Keras Models.

callbacks = [
    keras.callbacks.ModelCheckpoint(
        filepath="runs/best.keras",
        monitor="val_loss",
        mode="min",
        save_best_only=True,
    ),
    keras.callbacks.ModelCheckpoint(
        filepath="runs/epoch-{epoch:02d}.weights.h5",
        save_weights_only=True,
        save_freq="epoch",
    ),
]
model = net
model.compile(optimizer="adam", loss="mse")
model.fit(x, y, validation_split=0.25, epochs=5, callbacks=callbacks, verbose=0)

best = keras.saving.load_model("runs/best.keras")

Practical points: the filename accepts formatting fields such as {epoch:02d} and any logged metric; save_best_only=True with a metric needs monitor and a sensible mode; save_freq is "epoch" or an integer number of batches. Saving a full model every epoch is slow and large for big models, so prefer save_weights_only=True with periodic saves plus a best-model file. A .keras save does not keep Python callbacks or the data pipeline, so the position in the data is not restored when you resume: pass initial_epoch to fit to continue the epoch numbering and learning-rate schedules.

Orbax checkpoints in Keras 3

Keras 3.14 added keras.callbacks.OrbaxCheckpoint, a drop-in analogue of ModelCheckpoint built on Orbax, the checkpointing library of the JAX ecosystem. The Keras guide is written for the JAX backend; the example below also runs unchanged with KERAS_BACKEND="tensorflow" (saving, load_model, load_weights and resuming). Install the library with pip install -U orbax-checkpoint (without it, creating the callback raises ImportError). Orbax needs an absolute directory: a relative path such as "runs/orbax" fails at the first save with ValueError: Checkpoint path should be absolute.

import os
os.environ["KERAS_BACKEND"] = "jax"                  # the guide uses the JAX backend
import keras

ckpt_dir = os.path.abspath("runs/orbax")            # Orbax requires an absolute path

ckpt_cb = keras.callbacks.OrbaxCheckpoint(
    directory=ckpt_dir,
    monitor="val_loss",
    mode="min",
    save_best_only=False,
    save_freq="epoch",
    max_to_keep=3,
    save_on_background=True,                           # asynchronous writes
)
model.fit(x, y, validation_split=0.25, epochs=4, callbacks=[ckpt_cb])

restored = keras.saving.load_model(ckpt_dir)        # config, weights and optimizer state
fresh = build_model()
fresh.load_weights(ckpt_dir)                        # weights only into an existing model

# Resume: same directory, continue the step numbering
restored.fit(x, y, epochs=8, initial_epoch=4,
             callbacks=[keras.callbacks.OrbaxCheckpoint(directory=ckpt_dir, max_to_keep=5)])

The documented parameters are directory, monitor (default "val_loss"), mode, save_best_only, save_freq ("epoch" or a batch count), max_to_keep (default 1), save_on_background (default true), save_weights_only, initial_value_threshold and verbose. Each save is a numbered step directory. The notable benefit is distributed use: with the Keras Distribution API (DeviceMesh, LayoutMap, ModelParallel) the checkpoint stores the sharded state, and a checkpoint written under one layout can be loaded under another, with Orbax resharding the data on load; multi-host JAX runs are coordinated automatically. keras.saving.load_model accepts an Orbax directory.

Choosing a mechanism

Mechanism Strength Limit

tf.train.Checkpoint + CheckpointManager

Full control in custom loops; any trackable state, including the data iterator.

You write the loop and restore logic; weights only, no architecture.

ModelCheckpoint

One line in fit; best-model selection.

Whole-model saves are slow for big models; no data-position restore.

OrbaxCheckpoint

Async, sharded, reshard-on-load, JAX-oriented.

Newer (Keras 3.14+); needs orbax-checkpoint and an absolute path.

model.save_weights

Simple weights file.

No optimizer, no progress counters.

Common mistakes

  • Checkpointing only the model, then resuming with a fresh optimizer: the moments and step count restart, and the loss spikes.

  • Changing the keyword names or the attribute structure between save and restore, which silently leaves variables unrestored; always check the status object (or use assert_consumed in a test).

  • Asserting before deferred variables exist (before the model has been built), or ignoring the unrestored-values warning.

  • Saving int Python counters, which are not tracked; keep the step in a tf.Variable.

  • Forgetting that max_to_keep deletes old files, including the best checkpoint, if best-model saving is mixed into the same manager. Use a separate directory for the best model.

  • Using Keras 2 file names (weights.{epoch}.h5, SavedModel directories) with Keras 3 callbacks.

  • Copying a checkpoint prefix by hand: copy the .index and all .data-* files together.

  • Using checkpoints to ship a model for inference; use SavedModel or model.export.