Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions recml/core/training/jax_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import math
import os
import pprint
import time
from typing import Any, Generic, Protocol, Self, TypeVar

from absl import logging
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -425,19 +427,32 @@ 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"
self._train_steps = train_steps
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

Expand Down Expand Up @@ -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..."
Expand Down Expand Up @@ -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

Expand Down
34 changes: 33 additions & 1 deletion recml/core/training/keras_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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)

Expand All @@ -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
Expand Down Expand Up @@ -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..."
Expand Down Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions recml/core/training/keras_trainer_options_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
42 changes: 42 additions & 0 deletions recml/core/training/keras_trainer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading