|
| 1 | +# Copyright 2023–2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Utility functions for Elastic Training.""" |
| 16 | + |
| 17 | +import functools |
| 18 | +import jax |
| 19 | +from maxtext.utils import gcs_utils |
| 20 | +from maxtext.utils import max_logging |
| 21 | +import pathwaysutils |
| 22 | +from pathwaysutils.elastic import manager |
| 23 | + |
| 24 | + |
| 25 | +elastic_manager: manager.Manager | None = None |
| 26 | + |
| 27 | + |
| 28 | +def elastic_enabled(config) -> bool: |
| 29 | + """Returns whether elastic mode is enabled.""" |
| 30 | + return pathwaysutils.is_pathways_backend_used() and config.elastic_enabled |
| 31 | + |
| 32 | + |
| 33 | +def clean_up_checkpoints(checkpoint_dir: str): |
| 34 | + """Cleans up incomplete checkpoints after an elastic event.""" |
| 35 | + max_logging.log("Elastic utils: Checking for incomplete checkpoint after an elastic event...") |
| 36 | + checkpoint_dir = gcs_utils.add_trailing_slash(checkpoint_dir) |
| 37 | + |
| 38 | + # 1. List the "directories" (steps) |
| 39 | + checkpoints = gcs_utils.gcs_list_directories(checkpoint_dir) |
| 40 | + |
| 41 | + # 2. Filter for directories that are numbers |
| 42 | + checkpoints = [cp for cp in checkpoints if cp.isdigit()] |
| 43 | + |
| 44 | + if not checkpoints: |
| 45 | + max_logging.log("Found no existing checkpoints. Continuing") |
| 46 | + return |
| 47 | + |
| 48 | + # Sort naturally (numerical sort) and get the last one |
| 49 | + checkpoints.sort(key=int) |
| 50 | + latest_checkpoint_name = checkpoints[-1] |
| 51 | + latest_checkpoint_path = f"{checkpoint_dir}{latest_checkpoint_name}/" |
| 52 | + |
| 53 | + max_logging.log(f"Checking latest checkpoint: {latest_checkpoint_path}") |
| 54 | + |
| 55 | + # 3. Check for commit_success file |
| 56 | + success_markers = gcs_utils.gcs_glob_pattern(f"{latest_checkpoint_path}commit_success*") |
| 57 | + |
| 58 | + if not success_markers: |
| 59 | + max_logging.log(f"No commit_success file found. Deleting {latest_checkpoint_path}...") |
| 60 | + gcs_utils.gcs_delete_directory(latest_checkpoint_path) |
| 61 | + else: |
| 62 | + max_logging.log(f"Found commit_success file. Keeping {latest_checkpoint_path}.") |
| 63 | + |
| 64 | + |
| 65 | +def live_devices(): |
| 66 | + """Returns the list of live devices.""" |
| 67 | + global elastic_manager |
| 68 | + # If pathways is not used or elastic_manager is not initialized, return all devices |
| 69 | + if pathwaysutils.is_pathways_backend_used(): |
| 70 | + if elastic_manager is None: |
| 71 | + elastic_manager = manager.Manager() |
| 72 | + # Filter devices that are in active slices |
| 73 | + return [d for d in jax.devices() if d.slice_index in elastic_manager.active_slice_indices] |
| 74 | + return jax.devices() |
| 75 | + |
| 76 | + |
| 77 | +def chain_callbacks(*funcs): |
| 78 | + """Helper function to chain callbacks.""" |
| 79 | + |
| 80 | + def wrapper(): |
| 81 | + for func in funcs: |
| 82 | + func() |
| 83 | + |
| 84 | + return wrapper |
| 85 | + |
| 86 | + |
| 87 | +def elastic_retry(config, callback_fn=None): |
| 88 | + """Decorator for elastic retry. |
| 89 | +
|
| 90 | + If an elastic event occurs, the decorator will retry the decorated function |
| 91 | + up to `config.elastic_max_retries` times. |
| 92 | + Before each retry, it cleans up partial checkpoints by calling |
| 93 | + `clean_up_checkpoints`. If `callback_fn` is provided, it is |
| 94 | + called after `clean_up_checkpoints`. |
| 95 | +
|
| 96 | + Args: |
| 97 | + config: Config object. |
| 98 | + callback_fn: Optional callback function to be called after |
| 99 | + `clean_up_checkpoints` on an elastic event. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + A decorator for elastic retry. |
| 103 | + """ |
| 104 | + global elastic_manager |
| 105 | + if not elastic_enabled(config): |
| 106 | + msg = ( |
| 107 | + "Elastic training requires the Pathways backend, and elastic_enabled" |
| 108 | + " must be set to True: current config.elastic_enabled:" |
| 109 | + f" {config.elastic_enabled}, pathways backend used:" |
| 110 | + f" {pathwaysutils.is_pathways_backend_used()}" |
| 111 | + ) |
| 112 | + raise ValueError(msg) |
| 113 | + |
| 114 | + max_logging.log("Elastic Retry Enabled") |
| 115 | + if elastic_manager is None: |
| 116 | + elastic_manager = manager.Manager() |
| 117 | + |
| 118 | + cleanup_partial = functools.partial(clean_up_checkpoints, config.checkpoint_dir) |
| 119 | + |
| 120 | + if callback_fn is None: |
| 121 | + effective_callback = cleanup_partial |
| 122 | + else: |
| 123 | + effective_callback = chain_callbacks(cleanup_partial, callback_fn) |
| 124 | + |
| 125 | + return elastic_manager.elastic_retry( |
| 126 | + max_retries=config.elastic_max_retries, |
| 127 | + timeout=config.elastic_timeout_seconds, |
| 128 | + on_elastic_event_callback=effective_callback, |
| 129 | + ) |
0 commit comments