From d924b426548c6d7fd99f32753b79cafc4f60cb29 Mon Sep 17 00:00:00 2001 From: RecML authors Date: Wed, 11 Nov 2026 22:08:32 -0800 Subject: [PATCH] Internal change PiperOrigin-RevId: 1019783214 --- recml/core/training/keras_trainer.py | 35 +++- .../training/keras_trainer_options_test.py | 196 +++++++++++++++--- 2 files changed, 197 insertions(+), 34 deletions(-) diff --git a/recml/core/training/keras_trainer.py b/recml/core/training/keras_trainer.py index 08d1155..e7d8582 100644 --- a/recml/core/training/keras_trainer.py +++ b/recml/core/training/keras_trainer.py @@ -34,6 +34,7 @@ from recml.core.training import batch_folding from recml.core.training import core from recml.core.training import device_prefetch +from recml.core.training import state_folding from recml.core.utils import py_utils import tensorflow as tf @@ -133,6 +134,7 @@ def __init__( skip_batch_logs: bool = False, fold_batch_leaves: bool = False, zero_copy_batches: bool = False, + fold_state_max_leaf_size: int = 0, ): """Initializes the instance. @@ -189,6 +191,14 @@ def __init__( bfloat16 and complex tensors, are still converted (and copied) as Keras converts them. Requires a `tf.data.Dataset`. Not applied in `train_and_evaluate`. Defaults to False. + fold_state_max_leaf_size: During `train` on the JAX backend, concatenate + the fully replicated variables with at most this many elements into one + 1-D array per dtype in each of the 4 state lists (trainable, + non-trainable, optimizer and metrics variables), and split them back + inside the jitted train step (see `state_folding`). Fewer arrays then + pass in and out of each step, which reduces the host time per step for + models with many small variables, such as metrics. `0` disables state + folding. Not applied in `train_and_evaluate`. Defaults to 0. resume_training_launcher: Launcher to resume training. enable_xmanager_measurements: Whether to enable XManager measurements. enable_autoxprof: Whether to enable AutoXprof. @@ -196,8 +206,8 @@ def __init__( s2_logging_settings: Settings for S2 logging. Raises: - ValueError: If `device_prefetch_depth` is negative, or if - `fold_batch_leaves` is set on a backend other than JAX. + ValueError: If `device_prefetch_depth` or `fold_state_max_leaf_size` is + negative, or if `fold_batch_leaves` is set on a backend other than JAX. """ if device_prefetch_depth < 0: raise ValueError( @@ -208,6 +218,11 @@ def __init__( "fold_batch_leaves needs the JAX backend, got" f" {keras.backend.backend()!r}." ) + if fold_state_max_leaf_size < 0: + raise ValueError( + "fold_state_max_leaf_size must be >= 0, got" + f" {fold_state_max_leaf_size}." + ) keras.utils.set_random_seed(rng_seed) @@ -234,6 +249,7 @@ def __init__( self._skip_batch_logs = skip_batch_logs self._fold_batch_leaves = fold_batch_leaves self._zero_copy_batches = zero_copy_batches + self._fold_state_max_leaf_size = fold_state_max_leaf_size self._marker_path = os.path.join( model_dir, core.TRAINING_COMPLETE_MARKER_FILE ) @@ -417,6 +433,14 @@ def train(self, task: KerasTask) -> core.Logs: fit_data = zero_copy_batches_lib.zero_copy_adapter(dataset) with ( batch_folding.model_unfold_scope(model, unfold), + state_folding.model_state_folding_scope( + model, + max_leaf_size=( + self._fold_state_max_leaf_size + if keras.backend.backend() == "jax" + else 0 + ), + ), device_prefetch.model_prefetch_scope( model, depth=self._device_prefetch_depth ), @@ -477,11 +501,12 @@ def train_and_evaluate(self, task: KerasTask) -> core.Logs: or self._skip_batch_logs or self._fold_batch_leaves or self._zero_copy_batches + or self._fold_state_max_leaf_size ): logging.warning( - "device_prefetch_depth, skip_batch_logs, fold_batch_leaves and" - " zero_copy_batches only apply to `train`; ignoring them in" - " `train_and_evaluate`." + "device_prefetch_depth, skip_batch_logs, fold_batch_leaves," + " zero_copy_batches and fold_state_max_leaf_size only apply to" + " `train`; ignoring them in `train_and_evaluate`." ) train_dataset = task.create_dataset( training=True, **self._maybe_get_dataset_kws(task) diff --git a/recml/core/training/keras_trainer_options_test.py b/recml/core/training/keras_trainer_options_test.py index e75c23e..8a088e9 100644 --- a/recml/core/training/keras_trainer_options_test.py +++ b/recml/core/training/keras_trainer_options_test.py @@ -18,6 +18,7 @@ from unittest import mock from absl.testing import absltest +from absl.testing import parameterized import jax import keras from keras.src.utils import python_utils @@ -116,7 +117,7 @@ def _task(model, exported): ) -class KerasTrainerOptionsTest(absltest.TestCase): +class KerasTrainerOptionsTest(parameterized.TestCase): def setUp(self): super().setUp() @@ -128,6 +129,12 @@ def test_rejects_negative_prefetch_depth(self): ): _trainer(self._tmpdir, device_prefetch_depth=-1) + def test_rejects_negative_fold_state_max_leaf_size(self): + with self.assertRaisesRegex( + ValueError, "fold_state_max_leaf_size must be >= 0" + ): + _trainer(self._tmpdir, fold_state_max_leaf_size=-1) + def test_default_leaves_the_model_unchanged(self): trainer = _trainer(self._tmpdir) model = _DummyModel() @@ -178,14 +185,22 @@ def test_prefetch_skips_export_on_non_chief_hosts(self): self.assertLen(model.seen_in_fit, 1) self.assertEmpty(exported) - def test_train_and_evaluate_warns_that_prefetch_is_not_applied(self): - trainer = _trainer(self._tmpdir, device_prefetch_depth=2) + @parameterized.parameters( + dict(device_prefetch_depth=2), + dict(skip_batch_logs=True), + dict(fold_batch_leaves=True), + dict(zero_copy_batches=True), + dict(fold_state_max_leaf_size=64), + ) + def test_train_and_evaluate_warns_that_option_is_not_applied(self, **options): + trainer = _trainer(self._tmpdir, **options) task = mock.Mock() task.create_dataset.side_effect = RuntimeError("stop") with self.assertLogs(level="WARNING") as logs: with self.assertRaisesRegex(RuntimeError, "stop"): trainer.train_and_evaluate(task) - self.assertIn("device_prefetch_depth", logs.output[0]) + for name in options: + self.assertIn(name, logs.output[0]) def test_fold_batch_leaves_folds_the_dataset_and_unfolds_in_the_step(self): features = { @@ -269,15 +284,6 @@ def train(model_dir, **options): for key, values in want_history.items(): np.testing.assert_allclose(history[key], values, rtol=1e-6, err_msg=key) - def test_train_and_evaluate_warns_that_folding_is_not_applied(self): - trainer = _trainer(self._tmpdir, fold_batch_leaves=True) - task = mock.Mock() - task.create_dataset.side_effect = RuntimeError("stop") - with self.assertLogs(level="WARNING") as logs: - with self.assertRaisesRegex(RuntimeError, "stop"): - trainer.train_and_evaluate(task) - self.assertIn("fold_batch_leaves", logs.output[0]) - def test_zero_copy_batches_wraps_the_dataset_in_a_zero_copy_adapter(self): features = np.arange(20, dtype=np.float32).reshape([10, 2]) dataset = tf.data.Dataset.from_tensor_slices(features).batch( @@ -330,23 +336,155 @@ def test_zero_copy_batches_with_fold_batch_leaves(self): value, features[key][2 * step : 2 * step + 2] ) - def test_train_and_evaluate_warns_that_zero_copy_batches_is_not_applied(self): - trainer = _trainer(self._tmpdir, zero_copy_batches=True) - task = mock.Mock() - task.create_dataset.side_effect = RuntimeError("stop") - with self.assertLogs(level="WARNING") as logs: - with self.assertRaisesRegex(RuntimeError, "stop"): - trainer.train_and_evaluate(task) - self.assertIn("zero_copy_batches", logs.output[0]) + def test_fold_state_max_leaf_size_folds_the_state_during_train(self): + rng = np.random.default_rng(0) + x = rng.random((8, 4)).astype(np.float32) + y = rng.random((8, 1)).astype(np.float32) + inputs = keras.Input(shape=(4,), dtype="float32") + model = keras.Model(inputs, keras.layers.Dense(1)(inputs)) + model.compile(optimizer="sgd", loss="mse") + task = types.SimpleNamespace( + create_dataset=lambda training: tf.data.Dataset.from_tensor_slices( + (x, y) + ) + .batch(2, drop_remainder=True) + .repeat(), + create_model=lambda: model, + export_model=lambda m, model_dir: None, + ) - def test_train_and_evaluate_warns_that_skip_batch_logs_is_not_applied(self): - trainer = _trainer(self._tmpdir, skip_batch_logs=True) - task = mock.Mock() - task.create_dataset.side_effect = RuntimeError("stop") - with self.assertLogs(level="WARNING") as logs: - with self.assertRaisesRegex(RuntimeError, "stop"): - trainer.train_and_evaluate(task) - self.assertIn("skip_batch_logs", logs.output[0]) + with self.assertLogs(level="INFO") as logs: + _trainer( + self._tmpdir, + train_steps=2, + steps_per_loop=1, + fold_state_max_leaf_size=64, + ).train(task) + + self.assertTrue( + any("Folding the training state" in line for line in logs.output) + ) + + def test_fold_state_max_leaf_size_checkpoints_resume(self): + rng = np.random.default_rng(0) + x = rng.random((40, 4)).astype(np.float32) + y = rng.random((40, 1)).astype(np.float32) + + def train(model_dir, train_steps, fold_state_max_leaf_size): + keras.utils.set_random_seed(0) + inputs = keras.Input(shape=(4,), dtype="float32") + model = keras.Model(inputs, keras.layers.Dense(1)(inputs)) + model.compile(optimizer=keras.optimizers.Adam(0.01), loss="mse") + os.makedirs(model_dir, exist_ok=True) + dataset = ( + tf.data.Dataset.from_tensor_slices((x, y)) + .batch(2, drop_remainder=True) + .repeat() + ) + history = _trainer( + model_dir, + train_steps=train_steps, + steps_per_loop=5, + fold_state_max_leaf_size=fold_state_max_leaf_size, + distribution=keras.distribution.DataParallel(), + ).train( + types.SimpleNamespace( + create_dataset=lambda training: dataset, + create_model=lambda: model, + export_model=lambda m, model_dir: None, + ) + ) + variables = model.weights + model.optimizer.variables + return [v.numpy() for v in variables], history.history + + plain_dir = os.path.join(self._tmpdir, "plain") + train(plain_dir, train_steps=10, fold_state_max_leaf_size=0) + want, _ = train(plain_dir, train_steps=20, fold_state_max_leaf_size=0) + for resume_max_leaf_size in (0, 64): + with self.subTest(resume_max_leaf_size=resume_max_leaf_size): + model_dir = os.path.join(self._tmpdir, f"folded_{resume_max_leaf_size}") + # Writes the epoch 0-2 checkpoints with folding, then resumes from the + # epoch 2 checkpoint. + train(model_dir, train_steps=10, fold_state_max_leaf_size=64) + got, history = train( + model_dir, + train_steps=20, + fold_state_max_leaf_size=resume_max_leaf_size, + ) + self.assertLen(history["loss"], 2) # Only epochs 3 and 4 ran. + for actual, expected in zip(got, want, strict=True): + np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-7) + + def test_all_host_speed_options_end_to_end_real_keras_model(self): + rng = np.random.default_rng(0) + x = rng.random((40, 4)).astype(np.float32) + y = rng.random((40, 1)).astype(np.float32) + + def build_model(): + keras.utils.set_random_seed(0) + inp = keras.Input(shape=(4,), dtype="float32") + out = keras.layers.Dense(1)(keras.layers.Dense(4, activation="relu")(inp)) + model = keras.Model(inputs=inp, outputs=out) + model.compile( + optimizer=keras.optimizers.Adam(0.01), + loss=keras.losses.MeanSquaredError(), + metrics=["mae", "mse"], + ) + return model + + def make_dataset(): + return ( + tf.data.Dataset.from_tensor_slices((x, y)) + .batch(2, drop_remainder=True) + .repeat() + ) + + ref_model = build_model() + ref_dir = os.path.join(self._tmpdir, "ref") + os.makedirs(ref_dir) + ref_history = _trainer( + ref_dir, + train_steps=10, + steps_per_loop=5, + distribution=keras.distribution.DataParallel(), + ).train( + types.SimpleNamespace( + create_dataset=lambda training: make_dataset(), + create_model=lambda: ref_model, + export_model=lambda m, model_dir: None, + ) + ) + + opt_model = build_model() + opt_dir = os.path.join(self._tmpdir, "opt") + os.makedirs(opt_dir) + opt_history = _trainer( + opt_dir, + train_steps=10, + steps_per_loop=5, + device_prefetch_depth=1, + skip_batch_logs=True, + fold_batch_leaves=True, + zero_copy_batches=True, + fold_state_max_leaf_size=64, + distribution=keras.distribution.DataParallel(), + ).train( + types.SimpleNamespace( + create_dataset=lambda training: make_dataset(), + create_model=lambda: opt_model, + export_model=lambda m, model_dir: None, + ) + ) + + for actual, want in zip( + opt_model.get_weights(), ref_model.get_weights(), strict=True + ): + np.testing.assert_allclose(actual, want, rtol=1e-6, atol=1e-7) + self.assertCountEqual(opt_history.history, ref_history.history) + for key, values in ref_history.history.items(): + np.testing.assert_allclose( + opt_history.history[key], values, rtol=1e-6, err_msg=key + ) def test_train_and_evaluate_skips_train_throughput_callback_with_warning( self,