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/save_finalization.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_finalization.py new file mode 100644 index 0000000000..d004a2a7e2 --- /dev/null +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_finalization.py @@ -0,0 +1,378 @@ +# 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. + +"""Background finalization of saves in the checkpoint managers. + +Shared by `CheckpointManager` and v1 `training.Checkpointer`. After the +blocking phase of a save, a `FinalizeThread` waits for the save to finish, then +deletes the checkpoints that the preservation policy no longer keeps. Each +checkpoint manager keeps its own state, such as its `FinalizeThread`, and passes +it to these functions. +""" + +from __future__ import annotations + +import threading +import time +from typing import Any, Callable, Sequence + +from absl import logging +import jax +from orbax.checkpoint._src import threading as threading_lib +from orbax.checkpoint._src.futures import signaling_client +from orbax.checkpoint._src.futures import synchronization +from orbax.checkpoint._src.multihost import multihost +from orbax.checkpoint._src.path import deleter + +_THREAD_NAME = 'save_finalize' + + +class FinalizeThread(threading.Thread): + """Thread wrapper that raises an exception if encountered.""" + + exception = None + + def __init__( + self, + step: int, + target: Callable[..., object], + name: str, + args=(), + kwargs=None, + *, + daemon=None, + ): + super().__init__( + target=target, + name=name, + args=args, + kwargs=kwargs, + daemon=daemon, + ) + self._step = step + self._lock = threading.Lock() + self._cancelled = False + self._finalizing = False + self._cancel_handled = False + self._thread_local = threading.local() + + def step(self) -> int: + return self._step + + def try_cancel(self) -> bool: + """Marks the thread as cancelled if finalization has not yet begun.""" + with self._lock: + if self._cancelled or self._finalizing: + return False + self._cancelled = True + return True + + def try_begin_finalize(self) -> bool: + """Marks finalization as begun if the thread has not been cancelled.""" + with self._lock: + if self._cancelled: + return False + self._finalizing = True + return True + + def cancel(self) -> None: + with self._lock: + self._cancelled = True + + def is_cancelled(self) -> bool: + with self._lock: + return self._cancelled + + def is_cancel_handled(self) -> bool: + return self._cancel_handled + + def mark_cancel_handled(self) -> None: + self._cancel_handled = True + + def run(self): + try: + super().run() + except BaseException as e: # pylint:disable=broad-exception-caught + self.exception = e + + def join(self, *args, **kwargs): + super().join(*args, **kwargs) + + # Keep track of whether the calling thread should raise the exception. + if not hasattr(self._thread_local, 'should_raise'): + self._thread_local.should_raise = True + if self.exception and self._thread_local.should_raise: + # Each thread should only raise once. + self._thread_local.should_raise = False + raise self.exception + + +def in_progress_step(finalize_thread: FinalizeThread | None) -> int | None: + """Returns the step that `finalize_thread` finalizes, if not cancelled.""" + if finalize_thread is None or finalize_thread.is_cancel_handled(): + return None + return finalize_thread.step() + + +def start( + finalize_thread: threading_lib.OptionalRef[FinalizeThread], + *, + step: int, + target: Callable[..., object], + args: tuple[Any, ...], +) -> None: + """Starts finalizing `step` by running `target(*args)` in a new thread. + + Args: + finalize_thread: Set to the new thread. The previous one must be done. + step: The step to finalize. + target: Finalizes `step`, typically by calling `finalize()`. + args: The arguments of `target`. + """ + + def launch() -> FinalizeThread: + is_finalize_in_progress = finalize_thread.map( + lambda t: t is not None and t.is_alive() + ) + assert not is_finalize_in_progress, ( + 'Save finalization already in progress for' + f' step={finalize_thread.get_not_none().step()}' + ) + logging.info( + '[process=%s][thread=%s][step=%s] Starting Save Finalize thread=%s', + multihost.process_index(), + threading.current_thread().name, + step, + _THREAD_NAME, + ) + thread = FinalizeThread( + step=step, name=_THREAD_NAME, target=target, args=args + ) + thread.start() + return thread + + finalize_thread.set_from(launch) + + +def wait( + finalize_thread: threading_lib.OptionalRef[FinalizeThread], + *, + on_failure: Callable[[], None], +) -> None: + """Blocks until `finalize_thread`, if any, is done. + + Args: + finalize_thread: The finalization to wait for. + on_failure: Called if the finalization failed, before its error is raised. + Typically rolls back the checkpoints that the failed save added. + + Raises: + BaseException: The error of the finalization, if it failed. Each waiting + thread raises it once. + """ + process_index = multihost.process_index() + current_thread = threading.current_thread() + thread_name = None + step = None + try: + if finalize_thread.map( + lambda t: t is None or (not t.is_alive() and t.exception is None) + ): + logging.info( + '[process=%s][thread=%s][wait_until_finished] No Save Finalize' + ' thread to wait for. Returning.', + process_index, + current_thread.name, + ) + return + thread = finalize_thread.get_not_none() + step = thread.step() + thread_name = thread.name + logging.info( + '[process=%s][thread=%s][step=%s][wait_until_finished] Waiting for' + ' Save Finalize thread (%s) to complete.', + process_index, + current_thread.name, + step, + thread_name, + ) + # Don't join while holding a lock, so that waiting threads are not + # serialized. + thread.join() + logging.info( + '[process=%s][thread=%s][step=%s][wait_until_finished] Done' + ' waiting for Save Finalize thread (%s) running at step=%d.', + process_index, + current_thread.name, + step, + thread_name, + step, + ) + except BaseException: # pylint:disable=broad-exception-caught + logging.exception( + '[process=%s][thread=%s][step=%s][wait_until_finished] Save' + ' Finalize thread (%s) failed.', + process_index, + current_thread.name, + step, + thread_name, + ) + on_failure() + raise + + +def record_wait_duration(start_time: float, *, manual: bool) -> float: + """Records the time spent waiting for a finalization since `start_time`. + + Only waits on the main thread are recorded, as + `/jax/checkpoint/write/wait_for_prev_duration_secs`, and also as + `/jax/orbax/write/manual_wait_until_finished_duration_secs` if `manual`. + + Args: + start_time: When the wait started. + manual: Whether the user asked to wait, as opposed to the automatic wait at + the start of a save or when closing. + + Returns: + The recorded duration, or 0 if nothing was recorded. + """ + duration = time.time() - start_time + if duration <= 0 or threading.current_thread() is not threading.main_thread(): + return 0.0 + jax.monitoring.record_event_duration_secs( + '/jax/checkpoint/write/wait_for_prev_duration_secs', + duration, + ) + if manual: + jax.monitoring.record_event_duration_secs( + '/jax/orbax/write/manual_wait_until_finished_duration_secs', + duration, + ) + return duration + + +def agree_to_cancel( + finalize_thread: FinalizeThread, + *, + primary_host: int | None, + active_processes: set[int] | None, + signals_namespace: str, +) -> bool: + """Returns whether the save that `finalize_thread` finalizes is cancelled. + + The primary host cancels it unless its finalization has already begun, then + shares the decision, which all processes return. + + Args: + finalize_thread: Finalizes the save to cancel. + primary_host: The primary host, which decides. + active_processes: The processes that follow the decision. + signals_namespace: Namespace of the key that shares the decision. + """ + in_flight_step = finalize_thread.step() + is_primary_host = multihost.is_primary_host(primary_host) + was_cancelled = False + if is_primary_host: + was_cancelled = finalize_thread.try_cancel() + if ( + not multihost.should_skip_process_sync(active_processes) + and primary_host is not None + ): + client = signaling_client.get_signaling_client() + operation_id = synchronization.OperationIdGenerator.next_operation_id() + cancel_barrier_key = ( + f'{signals_namespace}_checkpoint_manager_cancel_' + f'{operation_id}_{in_flight_step}/' + ) + if is_primary_host: + client.key_value_set( + cancel_barrier_key, + str(int(was_cancelled)), + allow_overwrite=True, + ) + was_cancelled = bool( + int( + client.blocking_key_value_get( + cancel_barrier_key, + timeout_secs=multihost.coordination_timeout(), + ) + ) + ) + return was_cancelled + + +def finalize( + step: int, + steps_to_remove: Sequence[int], + *, + finalize_thread: threading_lib.OptionalRef[FinalizeThread], + wait_for_save: Callable[[], None], + finalize_checkpoint: Callable[[int], None], + checkpoint_deleter: deleter.CheckpointDeleter, + save_progress_tracker: synchronization.MultihostSynchronizedValue[bool], +) -> None: + """Finalizes the save of `step`, unless it was cancelled. + + Waits for the save, then calls `finalize_checkpoint(step)` and deletes + `steps_to_remove`. Whether or not this succeeds, the save is then no longer + in progress, which syncs the processes. + + Args: + step: The saved step. + steps_to_remove: The steps that the preservation policy no longer keeps. + finalize_thread: The thread that finalizes the save, if any. Its + cancellation is checked once the save is done. + wait_for_save: Blocks until the save is done, raising if it failed. + finalize_checkpoint: Runs final actions for the saved step. + checkpoint_deleter: Deletes `steps_to_remove`. + save_progress_tracker: Whether a save is in progress. + """ + process_index = multihost.process_index() + current_thread = threading.current_thread() + try: + wait_for_save() + thread = finalize_thread.get() + if thread is not None and not thread.try_begin_finalize(): + logging.info( + '[process=%s][thread=%s][step=%s] Checkpoint save was cancelled;' + ' skipping finalization and garbage collection.', + process_index, + current_thread.name, + step, + ) + return + # If the save failed, `wait_for_save` raised, so this is not reached. + finalize_checkpoint(step) + remove_steps_start_time = time.time() + checkpoint_deleter.delete_steps(steps_to_remove) + jax.monitoring.record_event_duration_secs( + '/jax/checkpoint/write/remove_steps_duration_secs', + time.time() - remove_steps_start_time, + ) + finally: + logging.info( + '[process=%s][thread=%s][step=%s] Save Finalize is syncing with' + ' other hosts...', + process_index, + current_thread.name, + step, + ) + # Setting the tracker syncs hosts, so no barrier is needed here. + save_progress_tracker.set(False) + logging.info( + '[process=%s][thread=%s][step=%s] Save Finalize is done on all hosts.', + process_index, + current_thread.name, + step, + ) diff --git a/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_finalization_test.py b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_finalization_test.py new file mode 100644 index 0000000000..17b10b7b75 --- /dev/null +++ b/checkpoint/orbax/checkpoint/_src/checkpoint_managers/save_finalization_test.py @@ -0,0 +1,240 @@ +# 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 threading +import time +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +import jax +from orbax.checkpoint._src import threading as threading_lib +from orbax.checkpoint._src.checkpoint_managers import save_finalization +from orbax.checkpoint._src.multihost import multihost + + +def _finished_thread( + step: int, target=lambda: None +) -> save_finalization.FinalizeThread: + thread = save_finalization.FinalizeThread( + step=step, target=target, name='save_finalize' + ) + thread.start() + thread.join() + return thread + + +class FinalizeThreadTest(absltest.TestCase): + + def test_raises_exception_once_per_joining_thread(self): + def fail(): + raise ValueError('failed') + + thread = save_finalization.FinalizeThread( + step=1, target=fail, name='save_finalize' + ) + thread.start() + with self.assertRaisesRegex(ValueError, 'failed'): + thread.join() + thread.join() # Does not raise again in this thread. + + errors = [] + + def join_in_other_thread(): + try: + thread.join() + except ValueError as e: + errors.append(e) + + other = threading.Thread(target=join_in_other_thread) + other.start() + other.join() + self.assertLen(errors, 1) + + def test_cancel_before_finalize(self): + thread = save_finalization.FinalizeThread( + step=1, target=lambda: None, name='save_finalize' + ) + self.assertTrue(thread.try_cancel()) + self.assertTrue(thread.is_cancelled()) + self.assertFalse(thread.try_cancel()) + self.assertFalse(thread.try_begin_finalize()) + + def test_cannot_cancel_once_finalizing(self): + thread = save_finalization.FinalizeThread( + step=1, target=lambda: None, name='save_finalize' + ) + self.assertTrue(thread.try_begin_finalize()) + self.assertFalse(thread.try_cancel()) + self.assertFalse(thread.is_cancelled()) + + +class SaveFinalizationTest(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_in_progress_step(self): + self.assertIsNone(save_finalization.in_progress_step(None)) + thread = _finished_thread(3) + self.assertEqual(save_finalization.in_progress_step(thread), 3) + thread.mark_cancel_handled() + self.assertIsNone(save_finalization.in_progress_step(thread)) + + def test_start(self): + ref = threading_lib.OptionalRef[save_finalization.FinalizeThread]() + done = [] + save_finalization.start(ref, step=2, target=done.append, args=(2,)) + ref.get_not_none().join() + self.assertEqual(ref.get_not_none().step(), 2) + self.assertEqual(done, [2]) + + def test_start_while_finalizing_raises(self): + release = threading.Event() + ref = threading_lib.OptionalRef[save_finalization.FinalizeThread]() + save_finalization.start(ref, step=1, target=release.wait, args=()) + try: + with self.assertRaisesRegex(AssertionError, 'already in progress'): + save_finalization.start(ref, step=2, target=lambda: None, args=()) + finally: + release.set() + ref.get_not_none().join() + + def test_wait_without_thread(self): + on_failure = mock.Mock() + save_finalization.wait( + threading_lib.OptionalRef[save_finalization.FinalizeThread](), + on_failure=on_failure, + ) + on_failure.assert_not_called() + + def test_wait_for_failed_finalization(self): + def fail(): + raise ValueError('failed') + + ref = threading_lib.OptionalRef[save_finalization.FinalizeThread]() + save_finalization.start(ref, step=1, target=fail, args=()) + on_failure = mock.Mock() + with self.assertRaisesRegex(ValueError, 'failed'): + save_finalization.wait(ref, on_failure=on_failure) + on_failure.assert_called_once() + + @parameterized.parameters(True, False) + def test_record_wait_duration(self, manual): + with mock.patch.object(time, 'time', return_value=12.0): + duration = save_finalization.record_wait_duration(10.0, manual=manual) + self.assertEqual(duration, 2.0) + expected = [ + mock.call('/jax/checkpoint/write/wait_for_prev_duration_secs', 2.0) + ] + if manual: + expected.append( + mock.call( + '/jax/orbax/write/manual_wait_until_finished_duration_secs', 2.0 + ) + ) + self.assertSequenceEqual(self.record_duration.call_args_list, expected) + + def test_record_wait_duration_ignores_background_threads(self): + durations = [] + thread = threading.Thread( + target=lambda: durations.append( + save_finalization.record_wait_duration( + time.time() - 1, manual=True + ) + ) + ) + thread.start() + thread.join() + self.assertEqual(durations, [0.0]) + self.record_duration.assert_not_called() + + def test_agree_to_cancel_on_single_process(self): + thread = save_finalization.FinalizeThread( + step=1, target=lambda: None, name='save_finalize' + ) + agree = lambda: save_finalization.agree_to_cancel( + thread, + primary_host=multihost.process_index(), + active_processes=None, + signals_namespace='test', + ) + self.assertTrue(agree()) + # Already cancelled. + self.assertFalse(agree()) + + def test_agree_not_to_cancel_once_finalizing(self): + thread = save_finalization.FinalizeThread( + step=1, target=lambda: None, name='save_finalize' + ) + thread.try_begin_finalize() + self.assertFalse( + save_finalization.agree_to_cancel( + thread, + primary_host=multihost.process_index(), + active_processes=None, + signals_namespace='test', + ) + ) + + def finalize(self, *, finalize_thread=None, wait_for_save=lambda: None): + ref = threading_lib.OptionalRef[save_finalization.FinalizeThread]( + finalize_thread + ) + finalize_checkpoint = mock.Mock() + deleter = mock.Mock() + tracker = mock.Mock() + try: + save_finalization.finalize( + 3, + [1, 2], + finalize_thread=ref, + wait_for_save=wait_for_save, + finalize_checkpoint=finalize_checkpoint, + checkpoint_deleter=deleter, + save_progress_tracker=tracker, + ) + finally: + tracker.set.assert_called_once_with(False) + return finalize_checkpoint, deleter + + def test_finalize(self): + finalize_checkpoint, deleter = self.finalize( + finalize_thread=_finished_thread(3) + ) + finalize_checkpoint.assert_called_once_with(3) + deleter.delete_steps.assert_called_once_with([1, 2]) + + def test_finalize_cancelled_save(self): + thread = _finished_thread(3) + thread.cancel() + finalize_checkpoint, deleter = self.finalize(finalize_thread=thread) + finalize_checkpoint.assert_not_called() + deleter.delete_steps.assert_not_called() + + def test_finalize_failed_save(self): + def fail(): + raise ValueError('failed') + + with self.assertRaisesRegex(ValueError, 'failed'): + self.finalize(wait_for_save=fail) + + +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..b090164ad5 100644 --- a/checkpoint/orbax/checkpoint/checkpoint_manager.py +++ b/checkpoint/orbax/checkpoint/checkpoint_manager.py @@ -38,11 +38,12 @@ 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 save_finalization +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 from orbax.checkpoint._src.futures import future -from orbax.checkpoint._src.futures import signaling_client from orbax.checkpoint._src.futures import synchronization from orbax.checkpoint._src.handlers import checkpoint_handler from orbax.checkpoint._src.handlers import composite_checkpoint_handler @@ -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: @@ -118,86 +118,6 @@ class StepAlreadyExistsError(ValueError): pass -class _FinalizeThread(threading.Thread): - """Thread wrapper that raises an exception if encountered.""" - - exception = None - - def __init__( - self, - step: int, - target: Callable[..., object], - name: str, - args=(), - kwargs=None, - *, - daemon=None, - ): - super().__init__( - target=target, - name=name, - args=args, - kwargs=kwargs, - daemon=daemon, - ) - self._step = step - self._lock = threading.Lock() - self._cancelled = False - self._finalizing = False - self._cancel_handled = False - self._thread_local = threading.local() - - def step(self) -> int: - return self._step - - def try_cancel(self) -> bool: - """Marks the thread as cancelled if finalization has not yet begun.""" - with self._lock: - if self._cancelled or self._finalizing: - return False - self._cancelled = True - return True - - def try_begin_finalize(self) -> bool: - """Marks finalization as begun if the thread has not been cancelled.""" - with self._lock: - if self._cancelled: - return False - self._finalizing = True - return True - - def cancel(self) -> None: - with self._lock: - self._cancelled = True - - def is_cancelled(self) -> bool: - with self._lock: - return self._cancelled - - def is_cancel_handled(self) -> bool: - return self._cancel_handled - - def mark_cancel_handled(self) -> None: - self._cancel_handled = True - - def run(self): - try: - super().run() - except BaseException as e: # pylint:disable=broad-exception-caught - self.exception = e - - def join(self, *args, **kwargs): - super().join(*args, **kwargs) - - # Keep track of whether the calling thread should raise the exception. - if not hasattr(self._thread_local, 'should_raise'): - self._thread_local.should_raise = True - if self.exception and self._thread_local.should_raise: - # Each thread should only raise once. - self._thread_local.should_raise = False - raise self.exception - - @dataclasses.dataclass class _ShouldSaveFnPolicy(save_decision_policy_lib.SaveDecisionPolicy): """A policy that uses a user-provided should_save_fn.""" @@ -969,8 +889,9 @@ def __init__( self._maybe_save_root_metadata(metadata) - # TODO: b/359854428 - Move Finalize biz logic to a separate class/module. - self._finalize_thread = threading_lib.OptionalRef[_FinalizeThread]() + self._finalize_thread = threading_lib.OptionalRef[ + save_finalization.FinalizeThread + ]() self._checkpoint_deleter: deleter.CheckpointDeleter = ( deleter.create_checkpoint_deleter( @@ -1004,7 +925,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,27 +1222,19 @@ 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: - finalize_thread = self._finalize_thread.get() - if finalize_thread is None or finalize_thread.is_cancel_handled(): - return None - return finalize_thread.step() + return save_finalization.in_progress_step(self._finalize_thread.get()) def should_save(self, step: int) -> bool: """Returns True if a checkpoint should be saved for the current step. @@ -1345,70 +1258,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 +1486,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 +1503,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 +1597,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 @@ -1782,43 +1638,19 @@ def _request_cancel(): processes=self._multiprocessing_options.active_processes, ) - current_thread = threading.current_thread() if is_async_checkpointer(self._checkpointer): - - def launch_finalize_thread() -> _FinalizeThread: - is_finalize_in_progress = self._finalize_thread.map( - lambda t: t is not None and t.is_alive() - ) - assert not is_finalize_in_progress, ( - 'Save finalization already in progress for' - f' step={self._finalize_thread.get_not_none().step()}' - ) - finalize_thread_name = 'save_finalize' - logging.info( - '[process=%s][thread=%s][step=%s] Starting CheckpointManager Save' - ' Finalize thread=%s', - process_index, - current_thread.name, - step, - finalize_thread_name, - ) - finalize_thread = _FinalizeThread( - step=step, - name=finalize_thread_name, - target=self._finalize, - args=(step, steps_to_remove), - ) - finalize_thread.start() - return finalize_thread - - self._finalize_thread.set_from(launch_finalize_thread) - + save_finalization.start( + self._finalize_thread, + step=step, + target=self._finalize, + args=(step, steps_to_remove), + ) else: self._finalize(step, steps_to_remove) logging.info( '[process=%s][thread=%s][step=%s] Finished synchronous save.', process_index, - current_thread.name, + threading.current_thread().name, step, ) @@ -1831,15 +1663,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( @@ -2266,78 +2091,27 @@ def _wait_until_finished_impl(self, *, manual: bool): as opposed to the automatic wait inside `save()` or `close()`. """ start_time = time.time() - process_index = multihost.process_index() - current_thread = threading.current_thread() - finalize_thread_name = None - step = None - try: - if self._finalize_thread.map( - lambda t: t is None or (not t.is_alive() and t.exception is None) - ): - logging.info( - '[process=%s][thread=%s][wait_until_finished] No Save Finalize' - ' thread to wait for. Returning.', - process_index, - current_thread.name, - ) - return - - step = self._finalize_thread.get_not_none().step() - finalize_thread_name = self._finalize_thread.get_not_none().name - - logging.info( - '[process=%s][thread=%s][step=%s][wait_until_finished] Waiting for' - ' Save Finalize thread (%s) to complete.', - process_index, - current_thread.name, - step, - finalize_thread_name, - ) - # Let all threads join and wait for the finalize thread to complete. - # Don't call join() with a lock otherwise we will end up serializing the - # access to the finalize thread. - self._finalize_thread.get_not_none().join() - logging.info( - '[process=%s][thread=%s][step=%s][wait_until_finished] Done' - ' waiting for Save Finalize thread (%s) running at step=%d.', - process_index, - current_thread.name, - step, - finalize_thread_name, - step, - ) - except BaseException: # pylint:disable=broad-exception-caught - logging.exception( - '[process=%s][thread=%s][step=%s][wait_until_finished] Save' - ' Finalize thread (%s) failed.', - process_index, - current_thread.name, - step, - finalize_thread_name, - ) # `save()` already added the failed step and pruned old steps from the # in-memory view, but old steps are only deleted from disk after a - # successful finalize. Restore the view from before the failed save. - self._checkpoints.set(self._prior_checkpoints) - self._latest_checkpoint_time = self._prior_checkpoint_time - raise + # successful finalize. If it failed, restore the view from before the + # failed save. + save_finalization.wait( + self._finalize_thread, on_failure=self._restore_prior_checkpoints + ) finally: - duration = time.time() - start_time - if duration > 0 and current_thread is threading.main_thread(): - jax.monitoring.record_event_duration_secs( - '/jax/checkpoint/write/wait_for_prev_duration_secs', - duration, - ) - self._wait_for_prev_save_duration += duration - if manual: - # Explicit user call (e.g. before eval or restore), as opposed to the - # automatic wait inside `save()` (recorded as - # /jax/orbax/write/blocking_wait_prev_duration_secs) or `close()`. - jax.monitoring.record_event_duration_secs( - '/jax/orbax/write/manual_wait_until_finished_duration_secs', - duration, - ) + # An explicit user call (`manual`), e.g. before eval or restore, is also + # recorded as /jax/orbax/write/manual_wait_until_finished_duration_secs, + # unlike the automatic wait inside `save()` (recorded as + # /jax/orbax/write/blocking_wait_prev_duration_secs) or `close()`. + self._wait_for_prev_save_duration += ( + save_finalization.record_wait_duration(start_time, manual=manual) + ) + + def _restore_prior_checkpoints(self) -> None: + """Restores the checkpoints from before the latest save.""" + self._checkpoints.set(self._prior_checkpoints) + self._latest_checkpoint_time = self._prior_checkpoint_time def is_saving_in_progress(self) -> bool: """Returns whether a checkpoint save is in progress.""" @@ -2373,39 +2147,12 @@ def cancel(self) -> None: return finalize_thread.mark_cancel_handled() in_flight_step = finalize_thread.step() - is_primary_host = multihost.is_primary_host( - self._multiprocessing_options.primary_host - ) - was_cancelled = False - if is_primary_host: - was_cancelled = finalize_thread.try_cancel() - if ( - not multihost.should_skip_process_sync( - self._multiprocessing_options.active_processes - ) - and self._multiprocessing_options.primary_host is not None + if not save_finalization.agree_to_cancel( + finalize_thread, + primary_host=self._multiprocessing_options.primary_host, + active_processes=self._multiprocessing_options.active_processes, + signals_namespace=self._signals_namespace, ): - client = signaling_client.get_signaling_client() - operation_id = synchronization.OperationIdGenerator.next_operation_id() - cancel_barrier_key = ( - f'{self._signals_namespace}_checkpoint_manager_cancel_' - f'{operation_id}_{in_flight_step}/' - ) - if is_primary_host: - client.key_value_set( - cancel_barrier_key, - str(int(was_cancelled)), - allow_overwrite=True, - ) - was_cancelled = bool( - int( - client.blocking_key_value_get( - cancel_barrier_key, - timeout_secs=multihost.coordination_timeout(), - ) - ) - ) - if not was_cancelled: self._wait_until_finished() logging.info( '[process=%s] CheckpointManager.cancel() called with no save in' @@ -2423,8 +2170,7 @@ def cancel(self) -> None: self._checkpointer.cancel() self._wait_until_finished() self._checkpoint_deleter.delete(in_flight_step) - self._checkpoints.set(self._prior_checkpoints) - self._latest_checkpoint_time = self._prior_checkpoint_time + self._restore_prior_checkpoints() def _finalize_checkpoint(self, step: int): """Executes final actions just before the checkpoint write completes. @@ -2453,61 +2199,32 @@ 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() ), ) def _finalize(self, step: int, steps_to_remove: List[int]): """Finalizes individual items and starts garbage collection.""" - process_index = multihost.process_index() - current_thread = threading.current_thread() - try: + + def wait_for_save(): self._non_blocking_metadata_store.wait_until_finished() self._wait_for_checkpointers() - finalize_thread = self._finalize_thread.get() - if ( - finalize_thread is not None - and not finalize_thread.try_begin_finalize() - ): - logging.info( - '[process=%s][thread=%s][step=%s] Checkpoint save was cancelled;' - ' skipping finalization and garbage collection.', - process_index, - current_thread.name, - step, - ) - return - # If an error is encountered while waiting for commit futures to complete, - # we will not proceed past this point. - self._finalize_checkpoint(step) - remove_steps_start_time = time.time() - self._checkpoint_deleter.delete_steps(steps_to_remove) - jax.monitoring.record_event_duration_secs( - '/jax/checkpoint/write/remove_steps_duration_secs', - time.time() - remove_steps_start_time, - ) - finally: - logging.info( - '[process=%s][thread=%s][step=%s] CheckpointManager Save Finalize is' - ' syncing with other hosts...', - process_index, - current_thread.name, - step, - ) - # Set save in progress does a barrier sync so we don't need to do it here. - self._save_progress_tracker.set(False) - logging.info( - '[process=%s][thread=%s][step=%s] CheckpointManager Save Finalize is' - ' done on all hosts.', - process_index, - current_thread.name, + + try: + save_finalization.finalize( step, + steps_to_remove, + finalize_thread=self._finalize_thread, + wait_for_save=wait_for_save, + finalize_checkpoint=self._finalize_checkpoint, + checkpoint_deleter=self._checkpoint_deleter, + save_progress_tracker=self._save_progress_tracker, ) + finally: # This time is tracked for metric purposes only. self._last_save_time = time.time() 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.