diff --git a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy.py index 4dd69b7af..d2dc8adad 100644 --- a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy.py +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy.py @@ -18,6 +18,7 @@ import dataclasses import datetime import enum +import os import statistics import typing from typing import Callable, Container, Protocol, Sequence @@ -27,6 +28,7 @@ from orbax.checkpoint._src.checkpoint_managers import policy_checkpoint_info from orbax.checkpoint._src.futures import signaling_client from orbax.checkpoint._src.futures import synchronization +from orbax.checkpoint._src.metadata import checkpoint_info from orbax.checkpoint._src.multihost import multihost @@ -645,3 +647,79 @@ def should_save( policy.should_save(step, previous_steps=previous_steps, context=context) for policy in self.policies ) + + +def is_continuous_checkpointing_enabled( + policy: SaveDecisionPolicy | None, +) -> bool: + """Returns whether `policy` is or contains a `ContinuousCheckpointingPolicy`.""" + policies = policy.policies if isinstance(policy, AnySavePolicy) else [policy] + return any(isinstance(p, ContinuousCheckpointingPolicy) for p in policies) + + +def should_save( + step: int, + *, + policy: SaveDecisionPolicy, + previous_steps: Sequence[PolicyCheckpointInfo], + latest_step: int | None, + context: DecisionContext, + directory: str | os.PathLike[str], + record_preemption_save_skipped: Callable[ + [int, datetime.datetime, str], None + ], +) -> bool: + """Returns whether `policy` allows saving at `step`. + + Shared by `CheckpointManager` and `training.Checkpointer`. Steps are expected + to increase, so this never saves at or before `latest_step`. When a save is + skipped on a preemption step, `record_preemption_save_skipped` is called with + the reason. + + Args: + step: The step to evaluate. + policy: The save decision policy. + previous_steps: The saved steps, passed to `policy`. + latest_step: The latest saved step, or None if no step is saved. + context: The context passed to `policy`. + directory: The root directory, used in log messages. + record_preemption_save_skipped: Records telemetry for a save skipped on a + preemption step, given the step, current time and reason. + """ + current_time = datetime.datetime.now(tz=datetime.timezone.utc) + if latest_step is not None and latest_step >= step: + if latest_step > step: + logging.log_first_n( + logging.WARNING, + "Skipping save at step %d because a newer checkpoint at step %d" + " already exists in %s. Until a step greater than %d is saved, a" + " restart restoring the latest step will resume step %d. To roll" + " back, start a new checkpoint directory or delete checkpoints" + " newer than the restored step before continuing training.", + 1, + step, + latest_step, + directory, + latest_step, + latest_step, + ) + if context.reached_preemption: + record_preemption_save_skipped(step, current_time, "step_already_saved") + return False + current_step = checkpoint_info.CheckpointInfo( + step=step, time=current_time, metrics=None + ) + result = policy.should_save( + current_step, previous_steps=previous_steps, context=context # pyrefly: ignore[bad-argument-type] + ) + if not result and context.reached_preemption: + if context.is_saving_in_progress: + reason = SKIP_REASON_SAVE_IN_PROGRESS + elif context.skip_reason is not None: + reason = context.skip_reason + elif is_continuous_checkpointing_enabled(policy): + reason = SKIP_REASON_MINIMUM_INTERVAL_NOT_MET + else: + reason = "policy_rejected" + record_preemption_save_skipped(step, current_time, reason) + return result diff --git a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy_test.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy_test.py index a4379b73e..834302d11 100644 --- a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy_test.py +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_decision_policy_test.py @@ -597,5 +597,170 @@ def record_cancel(): self.assertEqual(cancel_calls, 1) +class _FakePolicy(save_decision_policy_lib.SaveDecisionPolicy): + """Returns `result`, optionally setting `context.skip_reason`.""" + + def __init__(self, result: bool, skip_reason: str | None = None): + self.result = result + self.skip_reason = skip_reason + self.steps: list[int] = [] + + def should_save( + self, + step: save_decision_policy_lib.PolicyCheckpointInfo, + previous_steps: Sequence[save_decision_policy_lib.PolicyCheckpointInfo], + *, + context: DecisionContext, + ) -> bool: + del previous_steps + self.steps.append(step.step) + if self.skip_reason is not None: + context.skip_reason = self.skip_reason + return self.result + + +class ShouldSaveTest(parameterized.TestCase): + + def should_save( + self, + step: int, + policy: save_decision_policy_lib.SaveDecisionPolicy, + *, + latest_step: int | None = None, + reached_preemption: bool = False, + is_saving_in_progress: bool = False, + previous_steps: Sequence[CheckpointInfo] = (), + ) -> tuple[bool, list[str]]: + """Returns the decision and the recorded preemption skip reasons.""" + reasons: list[str] = [] + context = DecisionContext( + is_saving_in_progress=is_saving_in_progress, + in_progress_step=None, + reached_preemption=reached_preemption, + multiprocessing_options=options_lib.MultiprocessingOptions(), + cancel_in_progress_save=lambda: None, + ) + result = save_decision_policy_lib.should_save( + step, + policy=policy, + previous_steps=previous_steps, + latest_step=latest_step, + context=context, + directory="/root", + record_preemption_save_skipped=lambda s, t, r: reasons.append(r), + ) + return result, reasons + + @parameterized.parameters(True, False) + def test_returns_policy_decision(self, policy_result): + policy = _FakePolicy(policy_result) + self.assertEqual( + self.should_save(5, policy, latest_step=4), (policy_result, []) + ) + self.assertEqual(policy.steps, [5]) + + @parameterized.parameters(4, 5) + def test_skips_at_or_before_latest_step(self, step): + policy = _FakePolicy(True) + self.assertEqual(self.should_save(step, policy, latest_step=5), (False, [])) + self.assertEmpty(policy.steps) + + def test_records_step_already_saved_on_preemption(self): + self.assertEqual( + self.should_save( + 5, _FakePolicy(True), latest_step=5, reached_preemption=True + ), + (False, ["step_already_saved"]), + ) + + def test_records_nothing_when_saving_on_preemption(self): + self.assertEqual( + self.should_save(5, _FakePolicy(True), reached_preemption=True), + (True, []), + ) + + @parameterized.named_parameters( + dict( + testcase_name="save_in_progress", + policy=_FakePolicy(False), + is_saving_in_progress=True, + previous_steps=(), + expected_reason="save_in_progress", + ), + dict( + testcase_name="minimum_interval_not_met", + policy=save_decision_policy_lib.AnySavePolicy([ + _FakePolicy(False), + ContinuousCheckpointingPolicy(minimum_interval_secs=3600), + ]), + is_saving_in_progress=False, + # Saved just now, so the minimum interval is not met. + previous_steps=( + CheckpointInfo( + step=4, + time=datetime.datetime.now(tz=datetime.timezone.utc), + metrics=None, + ), + ), + expected_reason="minimum_interval_not_met", + ), + dict( + testcase_name="reason_from_policy", + policy=_FakePolicy(False, skip_reason="deferred_for_target_step"), + is_saving_in_progress=False, + previous_steps=(), + expected_reason="deferred_for_target_step", + ), + dict( + testcase_name="policy_rejected", + policy=_FakePolicy(False), + is_saving_in_progress=False, + previous_steps=(), + expected_reason="policy_rejected", + ), + ) + def test_records_reason_when_rejected_on_preemption( + self, policy, is_saving_in_progress, previous_steps, expected_reason + ): + self.assertEqual( + self.should_save( + 5, + policy, + latest_step=4, + reached_preemption=True, + is_saving_in_progress=is_saving_in_progress, + previous_steps=previous_steps, + ), + (False, [expected_reason]), + ) + + @parameterized.named_parameters( + dict(testcase_name="none", policy=None, expected=False), + dict( + testcase_name="fixed_interval", + policy=save_decision_policy_lib.FixedIntervalPolicy(1), + expected=False, + ), + dict( + testcase_name="continuous", + policy=ContinuousCheckpointingPolicy(), + expected=True, + ), + dict( + testcase_name="any_with_continuous", + policy=save_decision_policy_lib.AnySavePolicy([ + save_decision_policy_lib.FixedIntervalPolicy(1), + ContinuousCheckpointingPolicy(), + ]), + expected=True, + ), + ) + def test_is_continuous_checkpointing_enabled(self, policy, expected): + self.assertEqual( + save_decision_policy_lib.is_continuous_checkpointing_enabled(policy), + expected, + ) + + if __name__ == "__main__": absltest.main() diff --git a/checkpoint/orbax/checkpoint/checkpoint_manager.py b/checkpoint/orbax/checkpoint/checkpoint_manager.py index e342b6a7a..352d9b86a 100644 --- a/checkpoint/orbax/checkpoint/checkpoint_manager.py +++ b/checkpoint/orbax/checkpoint/checkpoint_manager.py @@ -1345,70 +1345,32 @@ def _should_save( cancel_in_progress_save: Callable[[], None] = lambda: None, ) -> bool: """Evaluates whether `step` should be saved, optionally recording cancel intent.""" - current_time = datetime.datetime.now(tz=datetime.timezone.utc) if self._options.read_only: logging.warning('%s is read only, save will be skipped', self.directory) if self.reached_preemption(step): + current_time = datetime.datetime.now(tz=datetime.timezone.utc) self._record_preemption_save_skipped(step, current_time, 'read_only') return False - last_checkpoint_step = self.latest_step() - # Ensure current step is between the last step and next step (accounting for - # save interval). - if last_checkpoint_step is not None and last_checkpoint_step >= step: - if last_checkpoint_step > step: - logging.log_first_n( - logging.WARNING, - 'Skipping save at step %d because a newer checkpoint at step %d' - ' already exists in %s. Until a step greater than %d is saved, a' - ' restart restoring the latest step will resume step %d. To roll' - ' back, start a new checkpoint directory or delete checkpoints' - ' newer than the restored step before continuing training.', - 1, - step, - last_checkpoint_step, - self.directory, - last_checkpoint_step, - last_checkpoint_step, - ) - if self.reached_preemption(step): - self._record_preemption_save_skipped( - step, current_time, 'step_already_saved' - ) - return False - if self._options.enable_should_save_is_saving_in_progress_check: is_saving_in_progress = self.is_saving_in_progress() else: is_saving_in_progress = False - reached_preemption = self.reached_preemption(step) - current_step_info = checkpoint_info.CheckpointInfo( - step=step, - time=current_time, - metrics=None, - ) context = save_decision_policy_lib.DecisionContext( is_saving_in_progress=is_saving_in_progress, in_progress_step=self._in_progress_step(), - reached_preemption=reached_preemption, + reached_preemption=self.reached_preemption(step), multiprocessing_options=self._multiprocessing_options, cancel_in_progress_save=cancel_in_progress_save, ) - should_save_result = self._save_decision_policy.should_save( - current_step_info, previous_steps=self._checkpoints, context=context # pyrefly: ignore[bad-argument-type] + return save_decision_policy_lib.should_save( + step, + policy=self._save_decision_policy, + previous_steps=self._checkpoints, # pyrefly: ignore[bad-argument-type] + latest_step=self.latest_step(), + context=context, + directory=self.directory, + record_preemption_save_skipped=self._record_preemption_save_skipped, ) - if not should_save_result and reached_preemption: - if is_saving_in_progress: - skip_reason = 'save_in_progress' - elif context.skip_reason is not None: - skip_reason = context.skip_reason - elif self._is_continuous_checkpointing_enabled(): - skip_reason = ( - save_decision_policy_lib.SKIP_REASON_MINIMUM_INTERVAL_NOT_MET - ) - else: - skip_reason = 'policy_rejected' - self._record_preemption_save_skipped(step, current_time, skip_reason) - return should_save_result def _get_save_directory( self, @@ -1831,15 +1793,8 @@ def launch_finalize_thread() -> _FinalizeThread: def _is_continuous_checkpointing_enabled(self) -> bool: """Returns True if continuous checkpointing is enabled.""" - decision_policy = self._options.save_decision_policy - policies = ( - decision_policy.policies - if isinstance(decision_policy, save_decision_policy_lib.AnySavePolicy) - else [decision_policy] - ) - return any( - isinstance(p, save_decision_policy_lib.ContinuousCheckpointingPolicy) - for p in policies + return save_decision_policy_lib.is_continuous_checkpointing_enabled( + self._options.save_decision_policy ) def _maybe_get_default_item( diff --git a/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py b/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py index a667b22ed..c1473d278 100644 --- a/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py +++ b/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py @@ -26,10 +26,10 @@ from absl import logging from etils import epy from orbax.checkpoint import checkpoint_manager +from orbax.checkpoint._src.checkpoint_managers import save_decision_policy as save_decision_policy_lib from orbax.checkpoint._src.logging import abstract_logger from orbax.checkpoint._src.logging import standard_logger from orbax.checkpoint._src.logging import step_statistics -from orbax.checkpoint._src.metadata import checkpoint_info from orbax.checkpoint.experimental.v1._src.context import context as context_lib from orbax.checkpoint.experimental.v1._src.deletion import execution as deletion_execution from orbax.checkpoint.experimental.v1._src.deletion import validation as deletion_validation @@ -392,63 +392,27 @@ def _should_save( cancel_in_progress_save: Callback invoked by the policy when an in-progress background save should be cancelled. """ - current_time = datetime.datetime.now(tz=datetime.timezone.utc) previous_steps = [ info for info in self._manager._checkpoints # pylint: disable=protected-access if not (replacing and info.step == step) ] - # Steps are expected to increase; never save at or before the latest step. - if previous_steps and previous_steps[-1].step >= step: - latest_step = previous_steps[-1].step - if latest_step > step: - logging.log_first_n( - logging.WARNING, - 'Skipping save at step %d because a newer checkpoint at step %d' - ' already exists in %s. Until a step greater than %d is saved, a' - ' restart restoring the latest step will resume step %d. To roll' - ' back, start a new checkpoint directory or delete checkpoints' - ' newer than the restored step before continuing training.', - 1, - step, - latest_step, - self.directory, - latest_step, - latest_step, - ) - if self._manager.reached_preemption(step): - self._record_preemption_save_skipped( - step, current_time, 'step_already_saved' - ) - return False - is_saving_in_progress = self._manager.is_saving_in_progress() - reached_preemption = self._manager.reached_preemption(step) context = save_decision_policies.DecisionContext( - is_saving_in_progress=is_saving_in_progress, + is_saving_in_progress=self._manager.is_saving_in_progress(), in_progress_step=self._manager._in_progress_step(), # pylint: disable=protected-access - reached_preemption=reached_preemption, + reached_preemption=self._manager.reached_preemption(step), multiprocessing_options=self._context.multiprocessing_options.v0(), cancel_in_progress_save=cancel_in_progress_save, ) - current_step = checkpoint_info.CheckpointInfo( - step=step, - time=current_time, - metrics=None, - ) - should_save = self._save_decision_policy.should_save( - current_step, previous_steps=previous_steps, context=context # pyrefly: ignore[bad-argument-type] + return save_decision_policy_lib.should_save( + step, + policy=self._save_decision_policy, # pyrefly: ignore[bad-argument-type] + previous_steps=previous_steps, + latest_step=previous_steps[-1].step if previous_steps else None, + context=context, + directory=self.directory, + record_preemption_save_skipped=self._record_preemption_save_skipped, ) - if not should_save and reached_preemption: - if is_saving_in_progress: - reason = 'save_in_progress' - elif context.skip_reason is not None: - reason = context.skip_reason - elif self._manager._is_continuous_checkpointing_enabled(): # pylint: disable=protected-access - reason = 'minimum_interval_not_met' - else: - reason = 'policy_rejected' - self._record_preemption_save_skipped(step, current_time, reason) - return should_save def should_save(self, step: int) -> bool: """Returns whether a checkpoint should be saved at the given step.