CheckpointManager#

class braintools.trainer.CheckpointManager(dirpath, max_to_keep=5, filename_template=None, save_best_only=False, monitor=None, mode='min', verbose=True)#

Manager for saving and loading checkpoints.

Provides functionality for: - Saving checkpoints with automatic naming - Tracking and keeping only the best N checkpoints - Loading checkpoints by epoch, step, or best metric - Automatic cleanup of old checkpoints

Parameters:
  • dirpath (str) – Directory to save checkpoints.

  • max_to_keep (int) – Maximum number of checkpoints to keep. Set to -1 to keep all.

  • filename_template (str | None) – Template for checkpoint filenames. Available variables: {epoch}, {step}, {metric}, {timestamp}

  • save_best_only (bool) – Only save when the monitored metric improves.

  • monitor (str | None) – Metric to monitor for best checkpoint selection.

  • mode (str) – One of ‘min’ or ‘max’. In ‘min’ mode, lower is better.

  • verbose (bool) – Whether to print checkpoint operations.

Examples

Keep the two most recent checkpoints and track the best val_loss:

>>> import os, shutil, tempfile
>>> import brainstate
>>> import braintools
>>> brainstate.random.seed(0)
>>> model = brainstate.nn.Linear(3, 2)
>>> tmp = tempfile.mkdtemp()
>>> manager = braintools.trainer.CheckpointManager(
...     tmp, max_to_keep=2, monitor='val_loss', mode='min', verbose=False)
>>> for epoch, loss in enumerate([0.9, 0.5, 0.7, 0.8]):
...     _ = manager.save(model, epoch=epoch, metrics={'val_loss': loss})
>>> [os.path.basename(c['path']) for c in manager.checkpoints]
['checkpoint-epoch=0001.ckpt', 'checkpoint-epoch=0003.ckpt']
>>> manager.best_score
0.5
>>> state = manager.load_best()
>>> state['epoch'], state['metrics']
(1, {'val_loss': 0.5})
>>> shutil.rmtree(tmp)
property best: str | None#

Path to the best checkpoint.

property best_score: float | None#

Best score achieved.

property checkpoints: List[Dict[str, Any]]#

List of tracked checkpoints.

clear()[source]#

Remove all checkpoints.

property latest: str | None#

Path to the latest checkpoint.

load(filepath=None, model=None, optimizer=None)[source]#

Load a checkpoint.

Parameters:
  • filepath (str | None) – Path to checkpoint. If None, loads the latest.

  • model (Any | None) – Model to load state into.

  • optimizer (Any | None) – Optimizer to load state into.

Returns:

Loaded checkpoint state.

Return type:

Dict[str, Any]

Examples

Restore saved parameters into a fresh model:

>>> import shutil, tempfile
>>> import jax.numpy as jnp
>>> import brainstate
>>> import braintools
>>> brainstate.random.seed(0)
>>> model = brainstate.nn.Linear(3, 2)
>>> tmp = tempfile.mkdtemp()
>>> manager = braintools.trainer.CheckpointManager(tmp, verbose=False)
>>> path = manager.save(model, epoch=3)
>>> fresh = brainstate.nn.Linear(3, 2)
>>> state = manager.load(path, model=fresh)
>>> state['epoch']
3
>>> bool(jnp.allclose(fresh.weight.value['weight'], model.weight.value['weight']))
True
>>> shutil.rmtree(tmp)
load_best(model=None, optimizer=None)[source]#

Load the best checkpoint based on monitored metric.

Parameters:
  • model (Any | None) – Model to load state into.

  • optimizer (Any | None) – Optimizer to load state into.

Returns:

Loaded checkpoint state.

Return type:

Dict[str, Any]

load_latest(model=None, optimizer=None)[source]#

Load the most recent checkpoint.

Parameters:
  • model (Any | None) – Model to load state into.

  • optimizer (Any | None) – Optimizer to load state into.

Returns:

Loaded checkpoint state.

Return type:

Dict[str, Any]

save(model, optimizer=None, epoch=0, step=None, metrics=None, extra_state=None)[source]#

Save a checkpoint.

Parameters:
  • model (Any) – Model to save.

  • optimizer (Any | None) – Optimizer to save.

  • epoch (int) – Current epoch.

  • step (int | None) – Current step.

  • metrics (Dict[str, float] | None) – Current metrics.

  • extra_state (Dict[str, Any] | None) – Additional state to save.

Returns:

Path to saved checkpoint, or None if not saved (save_best_only).

Return type:

str | None

Examples

>>> import os, shutil, tempfile
>>> import brainstate
>>> import braintools
>>> model = brainstate.nn.Linear(3, 2)
>>> tmp = tempfile.mkdtemp()
>>> manager = braintools.trainer.CheckpointManager(tmp, verbose=False)
>>> path = manager.save(model, epoch=10, step=200)
>>> os.path.basename(path)
'checkpoint-epoch=0010.ckpt'
>>> shutil.rmtree(tmp)
save_best_as(filepath)[source]#

Copy the best checkpoint to a new location.

Parameters:

filepath (str) – Destination path.