Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions src/jaxpot/training/checkpointing.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@

from jaxpot.agents import BaseTrainingAgent
from jaxpot.league import LeagueManager
from jaxpot.utils.checkpoints import (
BestCheckpointManager,
BestCheckpointSelection,
CheckpointManager,
)
from jaxpot.utils.best_checkpoints import BestCheckpointManager, BestCheckpointSelection
from jaxpot.utils.checkpoints import CheckpointManager


def save_checkpoint_now(
Expand Down
6 changes: 3 additions & 3 deletions src/jaxpot/training/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@
from jaxpot.rollout.advantage_gatherers import AdvantageGatherer
from jaxpot.rollout.aux_target_hooks import AuxTargetHook
from jaxpot.rollout.buffer import RolloutAuxTransform
from jaxpot.utils.checkpoints import (
from jaxpot.utils.best_checkpoints import (
BestCheckpointSelection,
Checkpoint,
configure_best_checkpoint_selection,
create_lr_schedule,
)
from jaxpot.utils.checkpoints import Checkpoint
from jaxpot.utils.logging import JsonLinesLogger, TrainingProgress
from jaxpot.utils.lr_schedule import create_lr_schedule
from jaxpot.utils.sharding import get_replicated_sharding
from jaxpot.utils.target_network import TargetNetwork

Expand Down
225 changes: 225 additions & 0 deletions src/jaxpot/utils/best_checkpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
"""Metric-based top-k best-checkpoint tracker.

Lives separately from ``utils.checkpoints`` so the main ``CheckpointManager``
(atomic publish, resume, league dump) doesn't carry the unrelated
manifest-based top-k retention logic.
"""

from __future__ import annotations

import json
import shutil
import traceback
from dataclasses import dataclass
from pathlib import Path

from loguru import logger
from omegaconf import DictConfig


@dataclass
class BestCheckpointEntry:
iteration: int
score: float
checkpoint_dir: str


@dataclass
class BestCheckpointSelection:
enabled: bool
metric: str | None
mode: str


def configure_best_checkpoint_selection(
cfg: DictConfig, evaluator_eval_every_by_name: dict[str, int]
) -> BestCheckpointSelection:
best_checkpoint_metric = cfg.get("best_checkpoint_metric")
best_checkpoint_mode = str(cfg.get("best_checkpoint_mode", "max")).lower()
best_checkpoint_enabled = False
if best_checkpoint_metric:
if best_checkpoint_mode not in {"max", "min"}:
raise ValueError(
f"Invalid best_checkpoint_mode='{best_checkpoint_mode}', expected one of ['max', 'min']"
)
best_checkpoint_metric = str(best_checkpoint_metric)
best_checkpoint_metric_prefix = best_checkpoint_metric.split("/", 1)[0]
metric_eval_every = evaluator_eval_every_by_name.get(best_checkpoint_metric_prefix)
if metric_eval_every is None:
raise ValueError(
"No evaluator found with name "
f"'{best_checkpoint_metric_prefix}' for metric '{best_checkpoint_metric}'. Can't save best checkpoints."
)
save_every = int(cfg.save_every)
if save_every <= 0:
logger.warning(
"Disabling best checkpoint selection: save_every <= 0, regular checkpoints are off."
)
else:
if metric_eval_every > 0 and save_every % metric_eval_every != 0:
raise ValueError(
"best_checkpoint metric cadence may miss save iterations: "
f"save_every={save_every}, evaluator='{best_checkpoint_metric_prefix}', "
f"eval_every={metric_eval_every}."
)
best_checkpoint_enabled = True
return BestCheckpointSelection(
enabled=best_checkpoint_enabled,
metric=best_checkpoint_metric,
mode=best_checkpoint_mode,
)


class BestCheckpointManager:
"""
Manages top-k best checkpoints according to evaluation scores.

Checkpoints are stored in a separate directory and tracked via a JSON manifest.
Only the top k checkpoints by score are retained.
"""

MANIFEST_FILE = "best_checkpoints.json"

def __init__(self, path: str | Path, keep_top_k: int = 5):
"""
Parameters
----------
path : str | Path
Directory where best checkpoints will be stored.
keep_top_k : int
Number of top checkpoints to retain.
"""
self.path = Path(path).resolve()
self.keep_top_k = keep_top_k
self.path.mkdir(parents=True, exist_ok=True)
self._entries: list[BestCheckpointEntry] = self._load_manifest()

def _manifest_path(self) -> Path:
return self.path / self.MANIFEST_FILE

def _load_manifest(self) -> list[BestCheckpointEntry]:
manifest_path = self._manifest_path()
if not manifest_path.exists():
return []
try:
with open(manifest_path) as f:
data = json.load(f)
return [
BestCheckpointEntry(
iteration=e["iteration"],
score=e["score"],
checkpoint_dir=e["checkpoint_dir"],
)
for e in data
]
except Exception:
traceback.print_exc()
return []

def _save_manifest(self) -> None:
manifest_path = self._manifest_path()
data = [
{
"iteration": e.iteration,
"score": e.score,
"checkpoint_dir": e.checkpoint_dir,
}
for e in self._entries
]
with open(manifest_path, "w") as f:
json.dump(data, f, indent=2)

def _is_better_than_worst(self, score: float) -> bool:
if len(self._entries) < self.keep_top_k:
return True
worst_score = min(e.score for e in self._entries)
return score > worst_score

def maybe_save(
self,
source_checkpoint_path: str | Path,
iteration: int,
score: float,
) -> str | None:
"""
Save checkpoint if score qualifies for top-k.

Parameters
----------
source_checkpoint_path : str | Path
Path to the source checkpoint directory to copy.
iteration : int
Training iteration number.
score : float
Evaluation score.

Returns
-------
str | None
Path to saved best checkpoint, or None if not saved.
"""
if not self._is_better_than_worst(score):
logger.debug(
f"Score {score:.4f} at iter {iteration} not in top {self.keep_top_k}, skipping"
)
return None
logger.info(f"Saving best checkpoint: iter={iteration}, score={score:.4f}")
source_path = Path(source_checkpoint_path).resolve()
if not source_path.exists():
logger.warning(f"Source checkpoint {source_path} does not exist")
return None

dest_name = f"{iteration:06d}_score_{score:.4f}"
dest_path = self.path / dest_name

try:
if dest_path.exists():
shutil.rmtree(dest_path)
shutil.copytree(source_path, dest_path)

new_entry = BestCheckpointEntry(
iteration=iteration,
score=score,
checkpoint_dir=str(dest_path),
)
self._entries.append(new_entry)
self._prune_worst()
self._save_manifest()

logger.info(
f"Saved best checkpoint: iter={iteration}, score={score:.4f}, path={dest_path}"
)
return str(dest_path)

except Exception:
traceback.print_exc()
return None

def _prune_worst(self) -> None:
if len(self._entries) <= self.keep_top_k:
return

self._entries.sort(key=lambda e: e.score, reverse=True)
to_remove = self._entries[self.keep_top_k :]
self._entries = self._entries[: self.keep_top_k]

for entry in to_remove:
try:
ckpt_path = Path(entry.checkpoint_dir)
if ckpt_path.exists():
shutil.rmtree(ckpt_path)
logger.debug(
f"Removed checkpoint: iter={entry.iteration}, score={entry.score:.4f}"
)
except Exception:
traceback.print_exc()

def get_best(self) -> BestCheckpointEntry | None:
"""Return the entry with the highest score."""
if not self._entries:
return None
return max(self._entries, key=lambda e: e.score)

def get_all_entries(self) -> list[BestCheckpointEntry]:
"""Return all tracked entries sorted by score (descending)."""
return sorted(self._entries, key=lambda e: e.score, reverse=True)
Loading
Loading