From f6ce58f9fecf75b8f9f70644d2de232fd40c4988 Mon Sep 17 00:00:00 2001 From: RecML authors Date: Sun, 15 Nov 2026 20:28:39 -0800 Subject: [PATCH] Internal change PiperOrigin-RevId: 1022466707 --- recml/core/training/jax_trainer.py | 36 +++++++++++++++- recml/core/training/keras_trainer.py | 34 ++++++++++++++- .../training/keras_trainer_options_test.py | 7 ++++ recml/core/training/keras_trainer_test.py | 42 +++++++++++++++++++ 4 files changed, 116 insertions(+), 3 deletions(-) diff --git a/recml/core/training/jax_trainer.py b/recml/core/training/jax_trainer.py index 0a73141..db10096 100644 --- a/recml/core/training/jax_trainer.py +++ b/recml/core/training/jax_trainer.py @@ -19,6 +19,7 @@ import math import os import pprint +import time from typing import Any, Generic, Protocol, Self, TypeVar from absl import logging @@ -392,6 +393,7 @@ def __init__( checkpoint_interval: int | None = None, max_checkpoints_to_keep: int = 5, continuous_eval_timeout: int = 30, + continuous_eval_max_idle_secs: float | None = None, ): """Initializes the instance. @@ -425,12 +427,24 @@ def __init__( checkpoint before timing out during continuous evaluation. When a timeout happens, the job will check for a marker file on disk and if it exists, it will terminate successfully. Defaults to 30 seconds. + continuous_eval_max_idle_secs: Optional maximum seconds to wait without a + new checkpoint during `evaluate_continuously` before exiting cleanly + even if `marker.txt` has not been written. Must be > 0 when set. + Defaults to None. """ if not isinstance(steps_per_loop, int) or steps_per_loop < 1: raise ValueError( f"`steps_per_loop` ({steps_per_loop}) must be a positive integer." ) + if ( + continuous_eval_max_idle_secs is not None + and continuous_eval_max_idle_secs <= 0 + ): + raise ValueError( + "`continuous_eval_max_idle_secs` must be > 0, got" + f" {continuous_eval_max_idle_secs}." + ) self._partitioner = partitioner or partitioning.NullPartitioner() self._model_dir = model_dir or "/tmp" @@ -438,6 +452,7 @@ def __init__( self._steps_per_loop = steps_per_loop self._steps_per_eval = steps_per_eval self._continuous_eval_timeout = continuous_eval_timeout + self._continuous_eval_max_idle_secs = continuous_eval_max_idle_secs self._checkpoint_interval = checkpoint_interval or steps_per_loop self._max_checkpoints_to_keep = max_checkpoints_to_keep @@ -795,10 +810,25 @@ def evaluate_continuously(self, task: JaxTask) -> core.Logs: ) eval_summary_writers = self._create_eval_summary_writers(eval_iters) + last_checkpoint_time = time.monotonic() + def timeout_fn() -> bool: - return tf.io.gfile.exists( + if tf.io.gfile.exists( os.path.join(self._model_dir, core.TRAINING_COMPLETE_MARKER_FILE) - ) + ): + return True + if self._continuous_eval_max_idle_secs is not None: + idle_secs = time.monotonic() - last_checkpoint_time + if idle_secs >= self._continuous_eval_max_idle_secs: + logging.warning( + "Stopping continuous_eval after %.1fs with no new checkpoints in" + " %s (continuous_eval_max_idle_secs=%s).", + idle_secs, + os.path.join(self._model_dir, core.CHECKPOINT_DIR), + self._continuous_eval_max_idle_secs, + ) + return True + return False if self._steps_per_eval is not None: steps_msg = f"running {self._steps_per_eval} steps of evaluation..." @@ -833,6 +863,8 @@ def timeout_fn() -> bool: except FileNotFoundError: logging.info("Checkpoint step: %s did not finish writing...", step) + finally: + last_checkpoint_time = time.monotonic() return metrics diff --git a/recml/core/training/keras_trainer.py b/recml/core/training/keras_trainer.py index 7844ecb..dfa1924 100644 --- a/recml/core/training/keras_trainer.py +++ b/recml/core/training/keras_trainer.py @@ -121,6 +121,7 @@ def __init__( train_steps: int = 0, steps_per_eval: int | None = None, continuous_eval_timeout: int = 30, + continuous_eval_max_idle_secs: float | None = None, steps_per_loop: int = 1_000, max_checkpoints_to_keep: int = 5, checkpoint_save_interval_epochs: int = 1, @@ -142,6 +143,11 @@ def __init__( train_steps: Total number of training steps. steps_per_eval: Number of steps between evaluations. continuous_eval_timeout: Timeout for continuous evaluation. + continuous_eval_max_idle_secs: Optional maximum seconds to wait without a + new checkpoint during `evaluate_continuously` before exiting cleanly + even if `marker.txt` has not been written (for example, when the + training job aborts in a `PARTIALLY_FAILED` work unit). Must be > 0 when + set. Defaults to None (wait until `marker.txt` appears). steps_per_loop: Number of steps per training loop. max_checkpoints_to_keep: Maximum number of checkpoints to keep. checkpoint_save_interval_epochs: Interval in epochs to save checkpoints. @@ -208,6 +214,14 @@ def __init__( "fold_batch_leaves needs the JAX backend, got" f" {keras.backend.backend()!r}." ) + if ( + continuous_eval_max_idle_secs is not None + and continuous_eval_max_idle_secs <= 0 + ): + raise ValueError( + "continuous_eval_max_idle_secs must be > 0, got" + f" {continuous_eval_max_idle_secs}." + ) keras.utils.set_random_seed(rng_seed) @@ -229,6 +243,7 @@ def __init__( self._train_epochs = train_steps // steps_per_loop self._steps_per_eval = steps_per_eval self._continuous_eval_timeout = continuous_eval_timeout + self._continuous_eval_max_idle_secs = continuous_eval_max_idle_secs self._steps_per_loop = steps_per_loop self._device_prefetch_depth = device_prefetch_depth self._skip_batch_logs = skip_batch_logs @@ -528,8 +543,23 @@ def evaluate_continuously(self, task: KerasTask) -> core.Logs | None: **self._maybe_get_model_kws(task, eval_dataset), ) + last_checkpoint_time = time.monotonic() + def timeout_fn() -> bool: - return tf.io.gfile.exists(self._marker_path) + if tf.io.gfile.exists(self._marker_path): + return True + if self._continuous_eval_max_idle_secs is not None: + idle_secs = time.monotonic() - last_checkpoint_time + if idle_secs >= self._continuous_eval_max_idle_secs: + logging.warning( + "Stopping continuous_eval after %.1fs with no new checkpoints in" + " %s (continuous_eval_max_idle_secs=%s).", + idle_secs, + self._checkpoint_dir, + self._continuous_eval_max_idle_secs, + ) + return True + return False if self._steps_per_eval is not None: steps_msg = f"running {self._steps_per_eval} steps of evaluation..." @@ -612,6 +642,8 @@ def on_test_begin(self, logs: Mapping[str, Any] | None = None): ) except FileNotFoundError: logging.info("Checkpoint epoch: %s did not finish writing...", epoch) + finally: + last_checkpoint_time = time.monotonic() return history diff --git a/recml/core/training/keras_trainer_options_test.py b/recml/core/training/keras_trainer_options_test.py index 42e3eec..af5b20a 100644 --- a/recml/core/training/keras_trainer_options_test.py +++ b/recml/core/training/keras_trainer_options_test.py @@ -119,6 +119,13 @@ def test_rejects_negative_prefetch_depth(self): ): _trainer(self._tmpdir, device_prefetch_depth=-1) + def test_rejects_non_positive_continuous_eval_max_idle_secs(self): + for bad_val in (0, -5.0): + with self.assertRaisesRegex( + ValueError, "continuous_eval_max_idle_secs must be > 0" + ): + _trainer(self._tmpdir, continuous_eval_max_idle_secs=bad_val) + def test_default_leaves_the_model_unchanged(self): trainer = _trainer(self._tmpdir) model = _DummyModel() diff --git a/recml/core/training/keras_trainer_test.py b/recml/core/training/keras_trainer_test.py index 2700fc6..ae38c22 100644 --- a/recml/core/training/keras_trainer_test.py +++ b/recml/core/training/keras_trainer_test.py @@ -272,6 +272,48 @@ def test_eval_with_create_model_for_eval_override(self) -> None: self.assertEqual(experiment.task.eval_model_kwargs, {}) + def test_continuous_eval_exits_on_max_idle_secs_without_marker(self): + if keras.backend.backend() != "jax": + self.skipTest("Continuous eval is only supported on the Jax backend.") + + model_dir = self.create_tempdir().full_path + train_trainer = keras_trainer.KerasTrainer( + distribution=keras.distribution.DataParallel(), + train_steps=2, + steps_per_eval=1, + steps_per_loop=2, + model_dir=model_dir, + ) + core.run_experiment( + core.Experiment(_KerasTask(), train_trainer), core.Trainer.Mode.TRAIN + ) + # Simulate a PARTIALLY_FAILED trainer crash where marker.txt was never + # written after the last checkpoint. + marker_path = os.path.join(model_dir, core.TRAINING_COMPLETE_MARKER_FILE) + os.remove(marker_path) + self.assertFalse(os.path.exists(marker_path)) + keras.backend.clear_session() + + eval_trainer = keras_trainer.KerasTrainer( + distribution=keras.distribution.DataParallel(), + steps_per_eval=1, + steps_per_loop=2, + model_dir=model_dir, + continuous_eval_timeout=1, + continuous_eval_max_idle_secs=0.5, + ) + with self.assertLogs(level="WARNING") as log: + history = core.run_experiment( + core.Experiment(_KerasTask(), eval_trainer), + core.Trainer.Mode.CONTINUOUS_EVAL, + ) + self.assertIsNotNone(history) + self.assertIn("loss", history) + self.assertTrue( + any("continuous_eval_max_idle_secs" in entry for entry in log.output), + msg=f"Expected idle-timeout warning in logs, got {log.output}", + ) + def test_legacy_checkpoint_format_deprecated(self): model_dir = self.create_tempdir().full_path