From 999cc5c79e0d50675bd9164e283d7bcd79f44d2d Mon Sep 17 00:00:00 2001 From: Angel Mau Date: Wed, 2 Dec 2026 17:00:14 -0800 Subject: [PATCH] #v1 Share save and preemption telemetry between `CheckpointManager` and `training.Checkpointer`. PiperOrigin-RevId: 1034914406 --- .../save_decision_policy.py | 78 ++++++++ .../save_decision_policy_test.py | 165 ++++++++++++++++ .../_src/checkpoint_managers/telemetry.py | 177 ++++++++++++++++++ .../checkpoint_managers/telemetry_test.py | 156 +++++++++++++++ .../orbax/checkpoint/checkpoint_manager.py | 150 ++++----------- .../experimental/v1/_src/saving/execution.py | 27 ++- .../v1/_src/testing/save_load_test.py | 36 ++++ .../v1/_src/training/checkpointer.py | 58 ++---- 8 files changed, 687 insertions(+), 160 deletions(-) create mode 100644 checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry.py create mode 100644 checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry_test.py 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 4dd69b7af4..d2dc8adad1 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 a4379b73eb..834302d117 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/_src/checkpoint_managers/telemetry.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry.py new file mode 100644 index 0000000000..4e9f62570c --- /dev/null +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry.py @@ -0,0 +1,177 @@ +# Copyright 2026 The Orbax Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Save and preemption telemetry of the checkpoint managers. + +Shared by `CheckpointManager` and v1 `training.Checkpointer`, so that both +record the same metrics, with the same names and tags. +""" + +import datetime + +from absl import logging +import jax +from orbax.checkpoint._src.logging import step_statistics +from orbax.checkpoint._src.multihost import multihost + +# Waiting longer than this for previous saves logs a warning. +WAIT_FOR_PREV_SAVE_WARNING_THRESHOLD_SECS = 1.0 + + +class PreemptionSkipRecorder: + """Records the training time lost when a save is skipped on a preemption step. + + Records `/jax/checkpoint/write/preempt/duration_lost_secs` on the primary + host, at most once per step. + """ + + def __init__(self): + self._last_recorded_step: int | None = None + + def record( + self, + step: int, + current_time: datetime.datetime, + reason: str, + *, + primary_host: int | None, + latest_checkpoint_time: datetime.datetime, + continuous_checkpointing_enabled: bool, + ) -> None: + """Records that the save at `step` was skipped. + + Args: + step: The skipped step. + current_time: When the save was skipped. + reason: Why the save was skipped, recorded as the `reason` tag. + primary_host: The primary host. Other processes record nothing. + latest_checkpoint_time: When the latest checkpoint was saved. The time + lost is measured from then. + continuous_checkpointing_enabled: Recorded as the + `continuous_checkpointing_enabled` tag. + """ + if not multihost.is_primary_host(primary_host): + return + if self._last_recorded_step == step: + return + self._last_recorded_step = step + jax.monitoring.record_event_duration_secs( + '/jax/checkpoint/write/preempt/duration_lost_secs', + (current_time - latest_checkpoint_time).total_seconds(), + reason=reason, + continuous_checkpointing_enabled=int(continuous_checkpointing_enabled), + ) + + +def record_preemption_duration_saved( + checkpoint_time: datetime.datetime, + prior_checkpoint_time: datetime.datetime, + *, + continuous_checkpointing_enabled: bool, +) -> None: + """Records the training time kept by a save on a preemption step. + + Records `/jax/checkpoint/write/preempt/duration_saved_secs`: the time since + the previous checkpoint, which would otherwise have been lost. + + Args: + checkpoint_time: When the save on the preemption step started. + prior_checkpoint_time: When the previous checkpoint was saved, or when + training started if there was none. + continuous_checkpointing_enabled: Recorded as the + `continuous_checkpointing_enabled` tag. + """ + jax.monitoring.record_event_duration_secs( + '/jax/checkpoint/write/preempt/duration_saved_secs', + (checkpoint_time - prior_checkpoint_time).total_seconds(), + continuous_checkpointing_enabled=int(continuous_checkpointing_enabled), + ) + + +def record_time_between_consecutive_saves( + step_stats: step_statistics.SaveStepStatistics, + *, + last_save_time: float | None, + continuous_checkpointing_enabled: bool, +) -> None: + """Records the time from the end of the previous save to this one. + + The time is measured until `step_stats.wait_for_prev_start_time`, and also + set in `step_stats`. Nothing is recorded if there was no previous save. + + Args: + step_stats: The statistics of this save. + last_save_time: When the previous save was finalized, or None. + continuous_checkpointing_enabled: Recorded as the + `continuous_checkpointing_enabled` tag. + """ + if last_save_time is None or step_stats.wait_for_prev_start_time is None: + return + # This may be negative if we arrive at wait_until_finished() before the save + # completed. + # TODO: b/448361885 - Investigate if we can make this more robust to manual + # wait_until_finished() calls. + step_stats.time_between_consecutive_saves_sec = ( + step_stats.wait_for_prev_start_time - last_save_time + ) + jax.monitoring.record_event_duration_secs( + '/jax/orbax/checkpoint_manager/time_between_consecutive_saves_secs', + step_stats.time_between_consecutive_saves_sec, + continuous_checkpointing_enabled=int(continuous_checkpointing_enabled), + ) + + +def record_wait_for_prev_save( + step_stats: step_statistics.SaveStepStatistics, + wait_for_prev_duration_secs: float, +) -> None: + """Sets the time spent waiting for previous saves in `step_stats`. + + Logs a warning if it exceeds `WAIT_FOR_PREV_SAVE_WARNING_THRESHOLD_SECS`. + + Args: + step_stats: The statistics of this save. + wait_for_prev_duration_secs: The time spent waiting for previous saves + since the previous save started, including explicit waits. + """ + step_stats.wait_for_prev_duration_secs = wait_for_prev_duration_secs + if wait_for_prev_duration_secs > WAIT_FOR_PREV_SAVE_WARNING_THRESHOLD_SECS: + logging.warning( + 'Waiting for previous save to complete took %f seconds. If this' + ' number is high, consider checkpointing less frequently.', + wait_for_prev_duration_secs, + ) + + +def record_blocking_save_waits( + *, + start_sync_duration_secs: float, + wait_prev_duration_secs: float, +) -> None: + """Records the waits in the blocking phase of a save, once per save. + + Args: + start_sync_duration_secs: The time spent in the barrier that starts the + save. + wait_prev_duration_secs: The time this save spent waiting for the previous + save. + """ + jax.monitoring.record_event_duration_secs( + '/jax/orbax/write/checkpoint_start_sync_duration_secs', + start_sync_duration_secs, + ) + jax.monitoring.record_event_duration_secs( + '/jax/orbax/write/blocking_wait_prev_duration_secs', + wait_prev_duration_secs, + ) diff --git a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry_test.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry_test.py new file mode 100644 index 0000000000..66879cb366 --- /dev/null +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/telemetry_test.py @@ -0,0 +1,156 @@ +# Copyright 2026 The Orbax Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +import jax +from orbax.checkpoint._src.checkpoint_managers import telemetry +from orbax.checkpoint._src.logging import step_statistics +from orbax.checkpoint._src.multihost import multihost + +_TIME = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) + + +class TelemetryTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.record_duration = self.enter_context( + mock.patch.object( + jax.monitoring, 'record_event_duration_secs', autospec=True + ) + ) + + def test_preemption_skip_recorded_once_per_step(self): + recorder = telemetry.PreemptionSkipRecorder() + for step, reason in [(2, 'policy_rejected'), (2, 'save_in_progress')]: + recorder.record( + step, + _TIME + datetime.timedelta(seconds=30), + reason, + primary_host=multihost.process_index(), + latest_checkpoint_time=_TIME, + continuous_checkpointing_enabled=True, + ) + recorder.record( + 3, + _TIME + datetime.timedelta(seconds=40), + 'step_already_saved', + primary_host=None, + latest_checkpoint_time=_TIME, + continuous_checkpointing_enabled=False, + ) + self.assertSequenceEqual( + self.record_duration.call_args_list, + [ + mock.call( + '/jax/checkpoint/write/preempt/duration_lost_secs', + 30.0, + reason='policy_rejected', + continuous_checkpointing_enabled=1, + ), + mock.call( + '/jax/checkpoint/write/preempt/duration_lost_secs', + 40.0, + reason='step_already_saved', + continuous_checkpointing_enabled=0, + ), + ], + ) + + def test_preemption_skip_not_recorded_on_other_hosts(self): + telemetry.PreemptionSkipRecorder().record( + 2, + _TIME, + 'policy_rejected', + primary_host=multihost.process_index() + 1, + latest_checkpoint_time=_TIME, + continuous_checkpointing_enabled=False, + ) + self.record_duration.assert_not_called() + + def test_preemption_duration_saved(self): + telemetry.record_preemption_duration_saved( + _TIME + datetime.timedelta(seconds=20), + _TIME, + continuous_checkpointing_enabled=True, + ) + self.record_duration.assert_called_once_with( + '/jax/checkpoint/write/preempt/duration_saved_secs', + 20.0, + continuous_checkpointing_enabled=1, + ) + + @parameterized.named_parameters( + dict(testcase_name='positive', last_save_time=5.0, expected=5.0), + # The previous save may be finalized after the next save starts waiting. + dict(testcase_name='negative', last_save_time=12.0, expected=-2.0), + ) + def test_time_between_consecutive_saves(self, last_save_time, expected): + step_stats = step_statistics.SaveStepStatistics( + wait_for_prev_start_time=10.0 + ) + telemetry.record_time_between_consecutive_saves( + step_stats, + last_save_time=last_save_time, + continuous_checkpointing_enabled=False, + ) + self.assertEqual(step_stats.time_between_consecutive_saves_sec, expected) + self.record_duration.assert_called_once_with( + '/jax/orbax/checkpoint_manager/time_between_consecutive_saves_secs', + expected, + continuous_checkpointing_enabled=0, + ) + + def test_no_time_between_consecutive_saves_for_first_save(self): + step_stats = step_statistics.SaveStepStatistics( + wait_for_prev_start_time=10.0 + ) + telemetry.record_time_between_consecutive_saves( + step_stats, last_save_time=None, continuous_checkpointing_enabled=False + ) + self.assertIsNone(step_stats.time_between_consecutive_saves_sec) + self.record_duration.assert_not_called() + + @parameterized.named_parameters( + dict(testcase_name='short', duration=0.5, warns=False), + dict(testcase_name='long', duration=2.0, warns=True), + ) + def test_wait_for_prev_save(self, duration, warns): + step_stats = step_statistics.SaveStepStatistics() + with mock.patch.object(telemetry.logging, 'warning') as warning: + telemetry.record_wait_for_prev_save(step_stats, duration) + self.assertEqual(step_stats.wait_for_prev_duration_secs, duration) + self.assertEqual(warning.called, warns) + + def test_blocking_save_waits(self): + telemetry.record_blocking_save_waits( + start_sync_duration_secs=1.0, wait_prev_duration_secs=2.0 + ) + self.assertSequenceEqual( + self.record_duration.call_args_list, + [ + mock.call( + '/jax/orbax/write/checkpoint_start_sync_duration_secs', 1.0 + ), + mock.call('/jax/orbax/write/blocking_wait_prev_duration_secs', 2.0), + ], + ) + + +if __name__ == '__main__': + absltest.main() diff --git a/checkpoint/orbax/checkpoint/checkpoint_manager.py b/checkpoint/orbax/checkpoint/checkpoint_manager.py index e342b6a7a7..5c84025e6c 100644 --- a/checkpoint/orbax/checkpoint/checkpoint_manager.py +++ b/checkpoint/orbax/checkpoint/checkpoint_manager.py @@ -38,6 +38,7 @@ from orbax.checkpoint._src.checkpoint_managers import policy_checkpoint_info from orbax.checkpoint._src.checkpoint_managers import preservation_policy as preservation_policy_lib from orbax.checkpoint._src.checkpoint_managers import save_decision_policy as save_decision_policy_lib +from orbax.checkpoint._src.checkpoint_managers import telemetry from orbax.checkpoint._src.checkpointers import abstract_checkpointer from orbax.checkpoint._src.checkpointers import async_checkpointer from orbax.checkpoint._src.checkpointers import checkpointer as checkpointer_lib @@ -101,7 +102,6 @@ RESERVED_ITEM_NAMES = [] _INIT_TIME = datetime.datetime.now(tz=datetime.timezone.utc) -_WAIT_FOR_PREV_SAVE_WARNING_THRESHOLD_SECS = 1.0 def _metrics_file_exists(metrics_item_path: epath.Path) -> bool: @@ -1004,7 +1004,7 @@ def __init__( # stashed before `self._checkpoints` appends step N and prunes old steps so # `cancel()` can roll back in-memory checkpoint state. self._prior_checkpoints: list[CheckpointInfo] = list(self._checkpoints) - self._last_preemption_skip_logged_step: Optional[int] = None + self._preemption_skip_recorder = telemetry.PreemptionSkipRecorder() logging.info( '[process=%s][thread=%s] CheckpointManager created, primary_host=%s,' @@ -1301,20 +1301,15 @@ def _record_preemption_save_skipped( reason: str, ) -> None: """Records telemetry when a checkpoint save is skipped on a preemption step.""" - if not multihost.is_primary_host( - self._multiprocessing_options.primary_host - ): - return - if self._last_preemption_skip_logged_step == step: - return - self._last_preemption_skip_logged_step = step - cc_enabled = int(self._is_continuous_checkpointing_enabled()) - duration = current_time - self._latest_checkpoint_time - jax.monitoring.record_event_duration_secs( - '/jax/checkpoint/write/preempt/duration_lost_secs', - duration.total_seconds(), - reason=reason, - continuous_checkpointing_enabled=cc_enabled, + self._preemption_skip_recorder.record( + step, + current_time, + reason, + primary_host=self._multiprocessing_options.primary_host, + latest_checkpoint_time=self._latest_checkpoint_time, + continuous_checkpointing_enabled=( + self._is_continuous_checkpointing_enabled() + ), ) def _in_progress_step(self) -> int | None: @@ -1345,70 +1340,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, @@ -1611,21 +1568,13 @@ def _request_cancel(): # checkpointers are AsyncCheckpointers. # Must happen after `should_save` to avoid blocking callers. step_stats.wait_for_prev_start_time = time.time() - if self._last_save_time is not None: - # This may be negative if we arrive at - # wait_until_finished() before the save completed. - # TODO: b/448361885 - Investigate if we can make this more robust to - # manual wait_until_finished() calls. - step_stats.time_between_consecutive_saves_sec = ( - step_stats.wait_for_prev_start_time - self._last_save_time - ) - jax.monitoring.record_event_duration_secs( - '/jax/orbax/checkpoint_manager/time_between_consecutive_saves_secs', - step_stats.time_between_consecutive_saves_sec, - continuous_checkpointing_enabled=int( - self._is_continuous_checkpointing_enabled() - ), - ) + telemetry.record_time_between_consecutive_saves( + step_stats, + last_save_time=self._last_save_time, + continuous_checkpointing_enabled=( + self._is_continuous_checkpointing_enabled() + ), + ) in_save_wait_start_time = time.time() if cancel_in_progress: self.cancel() @@ -1636,17 +1585,10 @@ def _request_cancel(): # kept in step statistics but must not be attributed to this save's # blocking phase metrics. in_save_wait_duration_secs = time.time() - in_save_wait_start_time - step_stats.wait_for_prev_duration_secs = self._wait_for_prev_save_duration + telemetry.record_wait_for_prev_save( + step_stats, self._wait_for_prev_save_duration + ) self._wait_for_prev_save_duration = 0.0 - if ( - step_stats.wait_for_prev_duration_secs - > _WAIT_FOR_PREV_SAVE_WARNING_THRESHOLD_SECS - ): - logging.warning( - 'Waiting for previous save to complete took %f seconds. If this' - ' number is high, consider checkpointing less frequently.', - step_stats.wait_for_prev_duration_secs, - ) # We consider the save in progress only when we have finished waiting for # previous save to complete. self._save_progress_tracker.set(True) @@ -1737,13 +1679,9 @@ def _request_cancel(): custom_metadata=custom_metadata, force=True, ) - jax.monitoring.record_event_duration_secs( - '/jax/orbax/write/checkpoint_start_sync_duration_secs', - cm_start_sync_duration, - ) - jax.monitoring.record_event_duration_secs( - '/jax/orbax/write/blocking_wait_prev_duration_secs', - in_save_wait_duration_secs, + telemetry.record_blocking_save_waits( + start_sync_duration_secs=cm_start_sync_duration, + wait_prev_duration_secs=in_save_wait_duration_secs, ) step_stats.checkpointer_blocking_duration_secs = ( time.time() - step_stats.checkpointer_blocking_start_time @@ -1831,15 +1769,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( @@ -2453,11 +2384,10 @@ def _finalize_checkpoint(self, step: int): # since program start. if self.reached_preemption(step): assert not self._checkpoints.empty() - duration = self._checkpoints[-1].time - self._prior_checkpoint_time - jax.monitoring.record_event_duration_secs( - '/jax/checkpoint/write/preempt/duration_saved_secs', - duration.total_seconds(), - continuous_checkpointing_enabled=int( + telemetry.record_preemption_duration_saved( + self._checkpoints[-1].time, + self._prior_checkpoint_time, + continuous_checkpointing_enabled=( self._is_continuous_checkpointing_enabled() ), ) diff --git a/checkpoint/orbax/checkpoint/experimental/v1/_src/saving/execution.py b/checkpoint/orbax/checkpoint/experimental/v1/_src/saving/execution.py index 901626e69e..a19266950c 100644 --- a/checkpoint/orbax/checkpoint/experimental/v1/_src/saving/execution.py +++ b/checkpoint/orbax/checkpoint/experimental/v1/_src/saving/execution.py @@ -91,7 +91,7 @@ def add_internal_checkpointables( The updated dictionary of checkpointables. """ # Global registration ties metrics key to JsonHandler. - if metrics: + if metrics is not None: checkpointables[checkpoint_layout.METRICS_CHECKPOINTABLE_KEY] = metrics return checkpointables @@ -216,6 +216,9 @@ async def _finalize_save(self): '[process=%s] Finished writing checkpoint metadata.', multihost.process_index(), ) + callback = self._context.async_options.post_finalization_callback + if callback is not None: + callback() await atomicity.on_commit_callback( self._temporary_path.temporary_path, checkpoint_start_time=self._start_time, @@ -414,8 +417,26 @@ def save_checkpointables_impl( overwrite: bool, custom_metadata: tree_types.JsonType | None, partial_save: bool = False, + metrics: tree_types.JsonType | None = None, ) -> async_types.AsyncResponse[None]: - """See caller docstrings.""" + """Starts saving `checkpointables` to `path` and returns an `AsyncResponse`. + + Args: + path: Destination checkpoint directory. + checkpointables: Mapping from checkpointable name to object to save. + async_origin: Whether this save originates from an async API. + overwrite: Whether to overwrite an existing checkpoint at `path` instead of + raising an error. + custom_metadata: Optional user metadata to record in the step metadata. + partial_save: Whether to write only the provided checkpointables into an + unfinalized checkpoint without committing a whole checkpoint. + metrics: Metrics saved as the reserved `metrics` checkpointable. Used by + `training.Checkpointer`, not exposed by the public free functions. + + Returns: + An `AsyncResponse` whose `result()` blocks until the save completes and + returns `None`. + """ validation.validate_save_checkpointables(checkpointables) start_time = time.time() event_tracking.OperationRecorder( @@ -438,7 +459,7 @@ def save_checkpointables_impl( # Prevent internal mutation from affecting the caller. checkpointables = dict(checkpointables) checkpointables = add_internal_checkpointables( - checkpointables, context=context + checkpointables, context=context, metrics=metrics ) snapshot_type = snapshot_lib.SnapshotType.EMPTY if partial_save else None temporary_path = _TemporaryPathAwaitingCreation( diff --git a/checkpoint/orbax/checkpoint/experimental/v1/_src/testing/save_load_test.py b/checkpoint/orbax/checkpoint/experimental/v1/_src/testing/save_load_test.py index 9b9c74560e..4cb7b107ec 100644 --- a/checkpoint/orbax/checkpoint/experimental/v1/_src/testing/save_load_test.py +++ b/checkpoint/orbax/checkpoint/experimental/v1/_src/testing/save_load_test.py @@ -20,6 +20,7 @@ import asyncio import dataclasses +import json import re import threading import time @@ -47,6 +48,7 @@ from orbax.checkpoint.experimental.v1._src.layout import checkpoint_layout from orbax.checkpoint.experimental.v1._src.path import async_utils from orbax.checkpoint.experimental.v1._src.path import types as path_types +from orbax.checkpoint.experimental.v1._src.saving import execution as saving_execution from orbax.checkpoint.experimental.v1._src.synchronization import multihost from orbax.checkpoint.experimental.v1._src.synchronization import synchronization from orbax.checkpoint.experimental.v1._src.testing import array_utils as array_test_utils @@ -155,6 +157,40 @@ def test_load_default(self, use_async): loaded = self.load_and_wait(self.directory, use_async=use_async) test_utils.assert_tree_equal(self, self.pytree, loaded) + @parameterized.parameters((True,), (False,)) + def test_post_finalization_callback(self, use_async): + committed_when_called = [] + ctx = ocp.Context() + ctx.async_options.post_finalization_callback = ( + lambda: committed_when_called.append(self.directory.exists()) + ) + with ctx: + self.save_and_wait(self.directory, self.pytree, use_async=use_async) + # Like v0, runs once on the primary host, before the atomic commit. + if multihost.is_primary_host(0): + self.assertEqual(committed_when_called, [False]) + else: + self.assertEmpty(committed_when_called) + self.assertTrue(self.directory.exists()) + + @parameterized.parameters(({'loss': 0.5},), ({},)) + def test_internal_metrics_param(self, metrics): + saving_execution.save_checkpointables_impl( + self.directory, + {'state': self.numpy_pytree}, + async_origin=False, + overwrite=False, + custom_metadata=None, + metrics=metrics, + ).result() + self.assertEqual( + json.loads((self.directory / 'metrics' / 'metrics').read_text()), + metrics, + ) + self.assertSameElements( + ocp.load_checkpointables(self.directory).keys(), ['state'] + ) + def test_save_async(self): start_serialize = threading.Event() original_serialize = serialization_v0.async_serialize_from_host diff --git a/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py b/checkpoint/orbax/checkpoint/experimental/v1/_src/training/checkpointer.py index a667b22ed6..c1473d2780 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.