From c37e6c9877556efccab543f0341d552d1560698f 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: 1019783212 --- recml/core/training/keras_trainer.py | 46 +- .../training/keras_trainer_options_test.py | 202 ++++++- recml/core/training/state_folding.py | 560 ++++++++++++++++++ recml/core/training/state_folding_test.py | 532 +++++++++++++++++ 4 files changed, 1306 insertions(+), 34 deletions(-) create mode 100644 recml/core/training/state_folding.py create mode 100644 recml/core/training/state_folding_test.py diff --git a/recml/core/training/keras_trainer.py b/recml/core/training/keras_trainer.py index 08d1155..a8aefa4 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,8 @@ def __init__( skip_batch_logs: bool = False, fold_batch_leaves: bool = False, zero_copy_batches: bool = False, + fold_state_max_leaf_size: int = 0, + fold_step_logs: bool = False, ): """Initializes the instance. @@ -189,6 +192,19 @@ 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. + fold_step_logs: With `fold_state_max_leaf_size > 0`, also stack the step + logs into one 1-D array per dtype inside the jitted train step if every + log has one element, so fewer arrays come back from each step. One- + element logs then come back as scalars. Not applied in + `train_and_evaluate`. Defaults to False. resume_training_launcher: Launcher to resume training. enable_xmanager_measurements: Whether to enable XManager measurements. enable_autoxprof: Whether to enable AutoXprof. @@ -196,8 +212,9 @@ 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, if `fold_batch_leaves` is set on a backend other than JAX, or + if `fold_step_logs` is set without `fold_state_max_leaf_size`. """ if device_prefetch_depth < 0: raise ValueError( @@ -208,6 +225,13 @@ 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}." + ) + if fold_step_logs and not fold_state_max_leaf_size: + raise ValueError("fold_step_logs needs fold_state_max_leaf_size > 0.") keras.utils.set_random_seed(rng_seed) @@ -234,6 +258,8 @@ 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._fold_step_logs = fold_step_logs self._marker_path = os.path.join( model_dir, core.TRAINING_COMPLETE_MARKER_FILE ) @@ -417,6 +443,15 @@ 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 + ), + fold_logs=self._fold_step_logs, + ), device_prefetch.model_prefetch_scope( model, depth=self._device_prefetch_depth ), @@ -477,11 +512,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, fold_state_max_leaf_size and fold_step_logs 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..0b4682b 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,23 @@ 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), + dict(fold_state_max_leaf_size=64, fold_step_logs=True), + ) + 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 +285,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 +337,160 @@ 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_rejects_fold_step_logs_without_state_folding(self): + with self.assertRaisesRegex(ValueError, "fold_step_logs needs"): + _trainer(self._tmpdir, fold_step_logs=True) - 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]) + 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, + ) + + 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, + fold_step_logs=True, + 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, diff --git a/recml/core/training/state_folding.py b/recml/core/training/state_folding.py new file mode 100644 index 0000000..ca11bcb --- /dev/null +++ b/recml/core/training/state_folding.py @@ -0,0 +1,560 @@ +# Copyright 2024 RecML 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. +"""Folds small replicated leaves of the Keras JAX training state into vectors. + +The Keras JAX training loop passes every variable of the model, the optimizer, +and the metrics to the jitted train step as its own array, and receives one +array back for each, plus one array per scalar log. The host pays per-array +overhead on every step: Python argument parsing, per-chip buffer handles and +output buffer allocation, and Python array wrapper construction/destruction. +Models with hundreds of metrics pass thousands of small arrays this way. + +`model_state_folding_scope` concatenates the small fully-replicated arrays of +each of the 4 state lists into one 1-D vector per dtype. Inside the jitted train +step, the vectors are split and reshaped back before calling the model's +`train_step`, and the updated state is folded back on return. Large or sharded +arrays pass through unchanged. With `fold_logs=True`, the step logs are also +stacked into one 1-D vector per dtype, wrapped in a lazy dict, if every log has +one element; one-element logs then come back as scalars. + +Terms: + leaf: one array of a state list. + small leaf: a fully replicated leaf with at most `max_leaf_size` elements. + vector: the 1-D concatenation of the raveled small leaves of one dtype. + passthrough leaf: a leaf that is not in a vector (large, sharded, or the + only small leaf of its dtype). + folded list: the passthrough leaves in their order, then the vectors. +""" + +from collections.abc import Iterator, Sequence +import contextlib +from typing import Any + +from absl import logging +import jax +from jax import flatten_util +import jax.numpy as jnp +import keras +import numpy as np + +_STATE_KEYS = ( + "trainable_variables", + "non_trainable_variables", + "optimizer_variables", + "metrics_variables", +) + + +@contextlib.contextmanager +def _override_attribute(obj: Any, name: str, value: Any) -> Iterator[None]: + """Sets `obj.` to `value` and restores the instance attribute on exit. + + If `obj` had no instance attribute `name` before (only a class attribute or + method), the instance attribute is deleted on exit. + + Args: + obj: The object to change. + name: The attribute name. + value: The value to set while the context is active. + + Yields: + None. + """ + had_instance_attribute = name in vars(obj) + saved_value = vars(obj).get(name) + setattr(obj, name, value) + try: + yield + finally: + if had_instance_attribute: + setattr(obj, name, saved_value) + else: + delattr(obj, name) + + +def _replicated_vector_sharding( + leaf_sharding: jax.sharding.Sharding, +) -> jax.sharding.Sharding: + """Returns a replicated sharding on the devices of a small leaf.""" + if isinstance(leaf_sharding, jax.sharding.NamedSharding): + return jax.sharding.NamedSharding( + leaf_sharding.mesh, jax.sharding.PartitionSpec() + ) + return leaf_sharding + + +class _ListLayout: + """How one state list is folded. + + For example, with `max_leaf_size=2` the list + + [w: float32[2, 2], b: float32[2], c: float32[], n: int32[]] + + has small leaves b, c (float32) and n (int32). w has 4 elements, so it + passes through. n is the only small int32 leaf, so it passes through too. + The folded list is + + [w, n, float32[3] vector = concat(ravel(b), ravel(c))] + + and `passthrough_leaf_indices == [0, 3]`, `vector_leaf_indices == [[1, 2]]`. + """ + + def __init__(self, leaves: Sequence[jax.Array], max_leaf_size: int): + self.num_leaves = len(leaves) + self.leaf_shardings = [leaf.sharding for leaf in leaves] + small_leaf_indices_by_dtype: dict[np.dtype[Any], list[int]] = {} + for i, leaf in enumerate(leaves): + if leaf.size <= max_leaf_size and leaf.sharding.is_fully_replicated: + dtype = np.dtype(leaf.dtype) + small_leaf_indices_by_dtype.setdefault(dtype, []).append(i) + # For each vector, the indices of its leaves in the order of their entries. + self.vector_leaf_indices = [ + leaf_indices + for leaf_indices in small_leaf_indices_by_dtype.values() + if len(leaf_indices) > 1 + ] + leaf_indices_in_vectors = set().union(*self.vector_leaf_indices) + self.passthrough_leaf_indices = [ + i for i in range(self.num_leaves) if i not in leaf_indices_in_vectors + ] + self.vector_shardings = [ + _replicated_vector_sharding(self.leaf_shardings[leaf_indices[0]]) + for leaf_indices in self.vector_leaf_indices + ] + # `unravel` splits a vector back into its leaves with their shapes. + self._unravel_vectors = [ + flatten_util.ravel_pytree(vector_leaves)[1] + for vector_leaves in self.leaves_by_vector(leaves) + ] + + @property + def folded_list_length(self) -> int: + """Returns the length of the folded list.""" + return len(self.passthrough_leaf_indices) + len(self.vector_leaf_indices) + + def leaves_by_vector(self, leaves: Sequence[Any]) -> list[list[Any]]: + """Returns, for each vector, the entries of `leaves` that go into it.""" + return [ + [leaves[i] for i in leaf_indices] + for leaf_indices in self.vector_leaf_indices + ] + + def concat_vectors( + self, leaves_by_vector: Sequence[Sequence[jax.Array]] + ) -> list[jax.Array]: + """Returns one raveled 1-D vector per entry of `leaves_by_vector`.""" + return [ + flatten_util.ravel_pytree(list(vector_leaves))[0] + for vector_leaves in leaves_by_vector + ] + + def split_vectors( + self, vectors: Sequence[jax.Array] + ) -> list[list[jax.Array]]: + """Returns the leaves of each vector, reshaped back. Inverts the above.""" + return [ + unravel(vector) + for unravel, vector in zip(self._unravel_vectors, vectors) + ] + + def fold_list( + self, leaves: Sequence[Any], vectors: Sequence[Any] + ) -> list[Any]: + """Returns the folded list of `leaves`, given its `vectors`.""" + return [leaves[i] for i in self.passthrough_leaf_indices] + list(vectors) + + def vectors_in_folded_list(self, folded_list: Sequence[Any]) -> list[Any]: + """Returns the vectors at the end of a folded list.""" + return list(folded_list[len(self.passthrough_leaf_indices) :]) + + def unfold_list( + self, + folded_list: Sequence[Any], + leaves_by_vector: Sequence[Sequence[Any]], + ) -> list[Any]: + """Returns the unfolded leaves, given the split vectors of `folded_list`.""" + leaves = [None] * self.num_leaves + for i, leaf in zip(self.passthrough_leaf_indices, folded_list): + leaves[i] = leaf + for vector_leaves, leaf_indices in zip( + leaves_by_vector, self.vector_leaf_indices + ): + for i, leaf in zip(leaf_indices, vector_leaves): + leaves[i] = leaf + return leaves + + +class _StateLayout: + """How the 4 lists of the training state are folded.""" + + def __init__(self, state: Sequence[Sequence[jax.Array]], max_leaf_size: int): + self.list_layouts = [_ListLayout(leaves, max_leaf_size) for leaves in state] + # `fold` and `unfold` pass only the small leaves and vectors through these: + # passing the large leaves to `jit` outside a trace would copy them. + self._concat_vectors_jit = jax.jit( + self._concat_all_vectors, + out_shardings=[layout.vector_shardings for layout in self.list_layouts], + ) + self._split_vectors_jit = jax.jit( + self._split_all_vectors, + out_shardings=[ + layout.leaves_by_vector(layout.leaf_shardings) + for layout in self.list_layouts + ], + ) + logging.info( + "Folding the training state from %s to %s arrays.", + [layout.num_leaves for layout in self.list_layouts], + [layout.folded_list_length for layout in self.list_layouts], + ) + + def _concat_all_vectors( + self, leaves_by_vector_by_list: Sequence[Sequence[Sequence[jax.Array]]] + ) -> list[list[jax.Array]]: + return [ + layout.concat_vectors(leaves_by_vector) + for layout, leaves_by_vector in zip( + self.list_layouts, leaves_by_vector_by_list + ) + ] + + def _split_all_vectors( + self, vectors_by_list: Sequence[Sequence[jax.Array]] + ) -> list[list[Any]]: + return [ + layout.split_vectors(vectors) + for layout, vectors in zip(self.list_layouts, vectors_by_list) + ] + + def fold( + self, state: Sequence[Sequence[jax.Array]] + ) -> tuple[list[jax.Array], ...]: + """Returns `state` with its small replicated leaves folded into vectors.""" + leaves_by_vector_by_list = [ + layout.leaves_by_vector(leaves) + for layout, leaves in zip(self.list_layouts, state) + ] + vectors_by_list = self._concat_vectors_jit(leaves_by_vector_by_list) + return tuple( + layout.fold_list(leaves, vectors) + for layout, leaves, vectors in zip( + self.list_layouts, state, vectors_by_list + ) + ) + + def unfold( + self, folded: Sequence[Sequence[jax.Array]] + ) -> tuple[list[jax.Array], ...]: + """Returns the unfolded `state` of `folded`.""" + vectors_by_list = [ + layout.vectors_in_folded_list(folded_list) + for layout, folded_list in zip(self.list_layouts, folded) + ] + leaves_by_vector_by_list = self._split_vectors_jit(vectors_by_list) + return tuple( + layout.unfold_list(folded_list, leaves_by_vector) + for layout, folded_list, leaves_by_vector in zip( + self.list_layouts, folded, leaves_by_vector_by_list + ) + ) + + def fold_shardings( + self, shardings: Sequence[Sequence[jax.sharding.Sharding]] + ) -> tuple[list[jax.sharding.Sharding], ...]: + """Returns the shardings of the folded state.""" + return tuple( + layout.fold_list(list_shardings, layout.vector_shardings) + for layout, list_shardings in zip(self.list_layouts, shardings) + ) + + +class _FoldedLogs(dict[str, Any]): + """Step logs backed by per-dtype device vectors, unpacked on first read. + + Populates its keys upfront so key-membership checks (`keys()`, `in`, `len`) + work without transferring values from the device. Every method that reads or + changes a value reads the vectors first. + """ + + def __init__( + self, names_by_dtype: dict[str, list[str]], vectors: dict[str, jax.Array] + ): + """Initializes the logs. + + Args: + names_by_dtype: For each dtype name, the log names in the order of their + entries in the vector of that dtype. + vectors: For each dtype name, the 1-D vector of the log values. + """ + super().__init__() + for names in names_by_dtype.values(): + for name in names: + dict.__setitem__(self, name, None) + self._names_by_dtype = names_by_dtype + self._vectors: dict[str, jax.Array] | None = vectors + + def _read(self) -> None: + # Keras can read the same logs on its callback thread and on the main + # thread at once. Copy `_vectors` to a local first: the other thread can + # set it to None while this one is still reading. + vectors = self._vectors + if vectors is None: + return + for dtype, names in self._names_by_dtype.items(): + values = np.asarray(vectors[dtype]) + for name, value in zip(names, values, strict=True): + dict.__setitem__(self, name, value) + self._vectors = None + + def __getitem__(self, key: str) -> Any: + self._read() + return super().__getitem__(key) + + def __setitem__(self, key: str, value: Any) -> None: + self._read() + super().__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._read() + super().__delitem__(key) + + def __eq__(self, other: object) -> bool: + self._read() + return super().__eq__(other) + + def __ne__(self, other: object) -> bool: + self._read() + return super().__ne__(other) + + __hash__ = None # Like `dict`. + + def __iter__(self) -> Iterator[str]: # pylint: disable=useless-parent-delegation + # CPython's `dict(logs)` and `{**logs}` copy a dict subclass directly, + # without `__getitem__`, unless the subclass overrides `__iter__`. This + # override makes them call `__getitem__` (which reads the values), while + # `set(logs)` still reads only the keys. + return super().__iter__() + + def get(self, key: str, default: Any = None) -> Any: + self._read() + return super().get(key, default) + + def pop(self, key: str, *default: Any) -> Any: + self._read() + return super().pop(key, *default) + + def popitem(self) -> tuple[str, Any]: + self._read() + return super().popitem() + + def setdefault(self, key: str, default: Any = None) -> Any: + self._read() + return super().setdefault(key, default) + + def update(self, *args: Any, **kwargs: Any) -> None: + self._read() + super().update(*args, **kwargs) + + def __ior__(self, other: Any) -> "_FoldedLogs": + self._read() + return super().__ior__(other) + + def clear(self) -> None: + self._vectors = None + super().clear() + + def items(self): + self._read() + return super().items() + + def values(self): + self._read() + return super().values() + + def copy(self) -> dict[str, Any]: + return dict(self.items()) + + def __reduce__(self) -> tuple[Any, ...]: + return dict, (self.copy(),) + + def __repr__(self) -> str: + self._read() + return super().__repr__() + + +class _Folding: + """The folded train step of a model and the state conversions around it.""" + + def __init__(self, model: keras.Model, max_leaf_size: int, fold_logs: bool): + self._model = model + self._max_leaf_size = max_leaf_size + self._fold_logs_enabled = fold_logs + self._layout: _StateLayout | None = None + # Set by `folded_train_step` while it is traced, None if logs are not + # folded (log folding is off, or some log has more than one element). + self._log_names_by_dtype: dict[str, list[str]] | None = None + self.original_train_step = model.train_step + self.original_make_train_function = model.make_train_function + self.original_state_sync = model.state_sync + # pylint: disable=protected-access + self.original_get_jax_state = model._get_jax_state + self.original_get_state_sharding_spec = model._get_state_sharding_spec + # pylint: enable=protected-access + + def _get_layout(self, state: Any = None) -> _StateLayout: + """Returns the layout, built on first use from the unfolded `state`.""" + if self._layout is None: + if state is None: + state = self.original_get_jax_state( + trainable_variables=True, + non_trainable_variables=True, + optimizer_variables=True, + metrics_variables=True, + ) + self._layout = _StateLayout(state, self._max_leaf_size) + return self._layout + + def folded_train_step( + self, state: Sequence[Sequence[jax.Array]], data: Any + ) -> tuple[Any, tuple[list[jax.Array], ...]]: + layout = self._get_layout() + logs, state = self.original_train_step(layout.unfold(state), data) + if self._fold_logs_enabled: + logs = self._fold_logs(logs) + return logs, layout.fold(state) + + def _fold_logs(self, logs: dict[str, Any]) -> dict[str, Any]: + """Stacks one-element logs into one vector per dtype. + + Returns `logs` unchanged, with a warning, if any log is a nested dict or + has more than one element. + + Args: + logs: The step logs returned by the model's `train_step`. + + Returns: + The vectors by dtype name, or `logs`. + """ + named_values_by_dtype: dict[str, list[tuple[str, jax.Array]]] = {} + for name, value in logs.items(): + if isinstance(value, dict): + logging.warning("Not folding the step logs: %r is a dict.", name) + self._log_names_by_dtype = None + return logs + value = jnp.asarray(value) + if value.size != 1: + logging.warning( + "Not folding the step logs: %r has %d elements.", name, value.size + ) + self._log_names_by_dtype = None + return logs + named_values = named_values_by_dtype.setdefault(value.dtype.name, []) + named_values.append((name, value)) + self._log_names_by_dtype = { + dtype: [name for name, _ in named_values] + for dtype, named_values in named_values_by_dtype.items() + } + return { + dtype: jnp.stack([jnp.reshape(value, ()) for _, value in named_values]) + for dtype, named_values in named_values_by_dtype.items() + } + + def folded_make_train_function(self, force: bool = False) -> None: + """Builds `model.train_function` with folded state shardings and logs.""" + if self._model.train_function is not None and not force: + return + # Only the train function sees folded shardings; `evaluate` and + # `validation_data` keep the unfolded ones. + with _override_attribute( + self._model, + "_get_state_sharding_spec", + self.folded_get_state_sharding_spec, + ): + self.original_make_train_function(force=force) + train_function: Any = self._model.train_function + + def folded_train_function(state: Any, iterator: Any) -> tuple[Any, Any]: + logs, state = train_function(state, iterator) + if self._log_names_by_dtype is not None: + logs = _FoldedLogs(self._log_names_by_dtype, logs) + return logs, state + + self._model.train_function = folded_train_function + + def folded_get_jax_state(self, **kwargs: bool) -> Any: + state = self.original_get_jax_state(**kwargs) + # `fit` and `train_on_batch` ask for all 4 lists. `evaluate`, `predict` and + # the checkpoint helpers ask for fewer and keep getting unfolded state. + if not all(kwargs.get(key, False) for key in _STATE_KEYS): + return state + return self._get_layout(state).fold(state) + + def folded_get_state_sharding_spec( + self, + ) -> tuple[list[jax.sharding.Sharding], ...]: + unfolded_shardings = self.original_get_state_sharding_spec() + return self._get_layout().fold_shardings(unfolded_shardings) + + def folded_state_sync(self) -> None: + """Unfolds `_jax_state` before syncing back to the model variables.""" + model = self._model + jax_state = getattr(model, "_jax_state", None) + if ( + jax_state + and not model._jax_state_synced # pylint: disable=protected-access + and all(jax_state.get(key) is not None for key in _STATE_KEYS) + ): + state = [jax_state[key] for key in _STATE_KEYS] + unfolded = self._get_layout().unfold(state) + model._jax_state = dict( # pylint: disable=protected-access + zip(_STATE_KEYS, unfolded) + ) + self.original_state_sync() + + +@contextlib.contextmanager +def model_state_folding_scope( + model: keras.Model, max_leaf_size: int, fold_logs: bool = False +) -> Iterator[None]: + """Makes `model.fit` pass small replicated arrays of the state folded. + + Args: + model: A Keras model on the JAX backend. + max_leaf_size: Arrays with at most this many elements are folded. `0` leaves + `model` untouched. + fold_logs: Also stack the step logs into one vector per dtype if every log + has one element. One-element logs then come back as scalars. + + Yields: + None. + """ + if max_leaf_size == 0: + yield + return + folding = _Folding(model, max_leaf_size, fold_logs) + model.train_function = None + try: + with ( + _override_attribute(model, "train_step", folding.folded_train_step), + _override_attribute( + model, "make_train_function", folding.folded_make_train_function + ), + _override_attribute(model, "state_sync", folding.folded_state_sync), + _override_attribute( + model, "_get_jax_state", folding.folded_get_jax_state + ), + ): + yield + finally: + model.train_function = None diff --git a/recml/core/training/state_folding_test.py b/recml/core/training/state_folding_test.py new file mode 100644 index 0000000..809bcb3 --- /dev/null +++ b/recml/core/training/state_folding_test.py @@ -0,0 +1,532 @@ +# Copyright 2024 RecML 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 os +import pickle +import threading + +from absl.testing import absltest +import jax +import jax.numpy as jnp +import keras +from keras.src.utils import python_utils +import numpy as np +from recml.core.training import state_folding + + +def _data() -> tuple[np.ndarray, np.ndarray]: + rng = np.random.default_rng(0) + x = rng.random([32, 8]).astype(np.float32) + y = rng.random([32, 1]).astype(np.float32) + return x, y + + +class _ExtraLogModel(keras.Model): + """Adds a non-metric scalar key to `train_step` logs.""" + + def __init__(self): + super().__init__() + self._dense1 = keras.layers.Dense(4, activation="relu") + self._bn = keras.layers.BatchNormalization() + self._dense2 = keras.layers.Dense(1) + + def call(self, x, training=False): + return self._dense2(self._bn(self._dense1(x), training=training)) + + def train_step(self, state, data): + logs, state = super().train_step(state, data) + logs["extra_scalar"] = jnp.float32(7.5) + return logs, state + + +class _NonScalarLogModel(_ExtraLogModel): + """Adds a 3-element log, which turns log folding off.""" + + def train_step(self, state, data): + logs, state = super().train_step(state, data) + logs["per_class"] = jnp.arange(3, dtype=jnp.float32) + return logs, state + + +def _model( + build: bool = True, model_cls: type[keras.Model] = _ExtraLogModel +) -> keras.Model: + keras.utils.set_random_seed(0) + model = model_cls() + model.compile( + optimizer=keras.optimizers.Adam(0.01), + loss="mse", + metrics=["mae", "mse", keras.metrics.RootMeanSquaredError()], + ) + if build: + model.build((None, 8)) + return model + + +class StateFoldingTest(absltest.TestCase): + + def _require_4_devices(self) -> list[jax.Device]: + devices = jax.devices() + if len(devices) < 4 and "TEST_TARGET" not in os.environ: + self.skipTest(f"Requires 4 JAX devices, got {len(devices)}.") + self.assertLen(devices, 4) + return devices + + def _fit( + self, + max_leaf_size: int, + steps_per_execution: int = 1, + build: bool = True, + ) -> tuple[keras.Model, dict[str, list[float]], list[int]]: + x, y = _data() + model = _model(build=build) + model.steps_per_execution = steps_per_execution + num_args = [] + with state_folding.model_state_folding_scope(model, max_leaf_size): + model.make_train_function() + train_function = model.train_function + + def counting_train_function(state, iterator): + num_args.append(len(jax.tree.leaves(state))) + return train_function(state, iterator) + + model.train_function = counting_train_function + history = model.fit( + x, y, batch_size=8, epochs=3, shuffle=False, verbose=0 + ) + return model, history.history, num_args + + def _assert_same_training(self, model, history, expected, expected_history): + self.assertNotEmpty(model.get_weights()) + for actual, want in zip( + model.get_weights(), expected.get_weights(), strict=True + ): + np.testing.assert_allclose(actual, want, rtol=1e-6, atol=1e-7) + self.assertCountEqual(history, expected_history) + for key, values in expected_history.items(): + np.testing.assert_allclose(history[key], values, rtol=1e-6, err_msg=key) + + def test_same_weights_and_logs(self): + expected, expected_history, expected_args = self._fit(max_leaf_size=0) + model, history, num_args = self._fit(max_leaf_size=16) + + self.assertLess(max(num_args), min(expected_args)) + self.assertLen(num_args, len(expected_args)) + self._assert_same_training(model, history, expected, expected_history) + for actual, want in zip( + model.optimizer.variables, expected.optimizer.variables, strict=True + ): + np.testing.assert_allclose( + np.asarray(actual), np.asarray(want), rtol=1e-6, atol=1e-7 + ) + self.assertEqual(history["extra_scalar"], [7.5, 7.5, 7.5]) + + def test_same_weights_with_steps_per_execution(self): + expected, expected_history, _ = self._fit( + max_leaf_size=0, steps_per_execution=2 + ) + model, history, _ = self._fit(max_leaf_size=16, steps_per_execution=2) + + self._assert_same_training(model, history, expected, expected_history) + + def test_unbuilt_model_folds(self): + expected, expected_history, expected_args = self._fit( + max_leaf_size=0, build=False + ) + model, history, num_args = self._fit(max_leaf_size=16, build=False) + + self.assertLess(max(num_args), min(expected_args)) + self._assert_same_training(model, history, expected, expected_history) + + def test_validation_data_under_distribution_works(self): + x, y = _data() + distribution = keras.distribution.DataParallel() + with distribution.scope(): + expected = _model() + want_history = expected.fit( + x, + y, + validation_data=(x[:8], y[:8]), + batch_size=8, + epochs=2, + shuffle=False, + verbose=0, + ).history + + model = _model() + with state_folding.model_state_folding_scope(model, max_leaf_size=16): + got_history = model.fit( + x, + y, + validation_data=(x[:8], y[:8]), + batch_size=8, + epochs=2, + shuffle=False, + verbose=0, + ).history + + self.assertCountEqual(got_history, want_history) + for key, values in want_history.items(): + np.testing.assert_allclose( + got_history[key], values, rtol=1e-6, err_msg=key + ) + + def test_sharded_small_leaves_pass_through(self): + devices = self._require_4_devices() + mesh = jax.sharding.Mesh(np.array(devices), ("model",)) + sharded = jax.sharding.NamedSharding( + mesh, jax.sharding.PartitionSpec("model") + ) + replicated = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec()) + leaves = [ + jax.device_put(jnp.zeros([4], jnp.float32), sharded), + jax.device_put(jnp.zeros([4], jnp.float32), replicated), + jax.device_put(jnp.zeros([], jnp.float32), replicated), + ] + + layout = state_folding._ListLayout(leaves, max_leaf_size=16) + + # The sharded leaf is small but passes through, keeping its sharding. + self.assertEqual(layout.passthrough_leaf_indices, [0]) + self.assertEqual(layout.vector_leaf_indices, [[1, 2]]) + + def test_same_weights_under_model_parallel(self): + self._require_4_devices() + x, y = _data() + mesh = keras.distribution.DeviceMesh( + (2, 2), ["batch", "model"], devices=keras.distribution.list_devices() + ) + layout_map = keras.distribution.LayoutMap(mesh) + layout_map[".*dense/kernel"] = (None, "model") + # Small but sharded: passes through. + layout_map[".*dense/bias"] = ("model",) + distribution = keras.distribution.ModelParallel( + layout_map=layout_map, batch_dim_name="batch" + ) + results = [] + for max_leaf_size in (0, 16): + with distribution.scope(): + keras.utils.set_random_seed(0) + inputs = keras.Input((8,)) + hidden = keras.layers.Dense(4, name="dense")(inputs) + model = keras.Model(inputs, keras.layers.Dense(1)(hidden)) + model.compile(optimizer="adam", loss="mse", metrics=["mae"]) + with state_folding.model_state_folding_scope(model, max_leaf_size): + history = model.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + results.append((model, history)) + + expected, expected_history = results[0] + model, history = results[1] + self._assert_same_training(model, history, expected, expected_history) + for variable, want in zip(model.weights, expected.weights, strict=True): + self.assertEqual( + variable.value.sharding, want.value.sharding, msg=variable.path + ) + + def test_restores_the_model_on_exit(self): + model, _, _ = self._fit(max_leaf_size=16) + + for name in ( + "train_step", + "make_train_function", + "state_sync", + "_get_jax_state", + "_get_state_sharding_spec", + ): + self.assertNotIn(name, vars(model), msg=name) + x, y = _data() + model.fit(x, y, batch_size=8, epochs=1, verbose=0) + model.evaluate(x, y, batch_size=8, verbose=0) + + custom_train_step = lambda state, data: _ExtraLogModel.train_step( + model, state, data + ) + model.train_step = custom_train_step + with state_folding.model_state_folding_scope(model, max_leaf_size=16): + self.assertIsNot(model.train_step, custom_train_step) + self.assertIs(model.train_step, custom_train_step) + + def test_state_layout_preserves_replicated_named_shardings(self): + devices = self._require_4_devices() + mesh = jax.sharding.Mesh( + np.array(devices).reshape(2, 2), ("batch", "model") + ) + replicated_2d = jax.sharding.NamedSharding( + mesh, jax.sharding.PartitionSpec(None, None) + ) + replicated_0d = jax.sharding.NamedSharding( + mesh, jax.sharding.PartitionSpec() + ) + state = [[ + jax.device_put(jnp.ones([2, 2], jnp.float32), replicated_2d), + jax.device_put(jnp.array(3.0, jnp.float32), replicated_0d), + ]] + + layout = state_folding._StateLayout(state, max_leaf_size=4) + folded = layout.fold(state) + unfolded = layout.unfold(folded) + + self.assertEqual(folded[0][0].sharding, replicated_0d) + self.assertEqual(unfolded[0][0].sharding, replicated_2d) + self.assertEqual(unfolded[0][1].sharding, replicated_0d) + np.testing.assert_array_equal(unfolded[0][0], np.ones([2, 2], np.float32)) + np.testing.assert_array_equal(unfolded[0][1], 3.0) + + def test_zero_max_leaf_size_leaves_the_model_untouched(self): + model = _model() + + with state_folding.model_state_folding_scope(model, max_leaf_size=0): + self.assertNotIn("train_step", vars(model)) + + def test_list_layout_folds_small_leaves_by_dtype(self): + leaves = [ + jnp.zeros([3], jnp.int32), # 3 elements: too large, passes through. + jnp.zeros([], jnp.float32), + jnp.zeros([], jnp.int32), + jnp.zeros([1, 1], jnp.float32), + jnp.zeros([2], jnp.int32), + ] + + layout = state_folding._ListLayout(leaves, max_leaf_size=2) + + self.assertEqual(layout.passthrough_leaf_indices, [0]) + self.assertEqual(layout.vector_leaf_indices, [[1, 3], [2, 4]]) + self.assertEqual(layout.folded_list_length, 3) + float_leaves, int_leaves = layout.split_vectors([ + jnp.array([5.0, 6.0], jnp.float32), + jnp.array([7, 8, 9], jnp.int32), + ]) + np.testing.assert_array_equal(float_leaves[0], np.float32(5.0)) + np.testing.assert_array_equal(float_leaves[1], [[6.0]]) + np.testing.assert_array_equal(int_leaves[0], np.int32(7)) + np.testing.assert_array_equal(int_leaves[1], [8, 9]) + + def test_folded_logs_defers_read_until_values_accessed(self): + logs = state_folding._FoldedLogs( + {"float32": ["loss", "mae"]}, + {"float32": jnp.array([1.25, 0.5], dtype=jnp.float32)}, + ) + self.assertEqual(set(logs), {"loss", "mae"}) + self.assertIn("loss", logs) + self.assertIsNotNone(logs._vectors) + + copied = dict(logs) + self.assertIsNone(logs._vectors) + self.assertEqual(copied, {"loss": np.float32(1.25), "mae": np.float32(0.5)}) + + def test_folded_logs_survive_concurrent_reads(self): + slow = jax.jit( + lambda m: ( + jnp.stack([jnp.sum(m @ m), jnp.sum(m)]), + jnp.stack([jnp.sum(m @ m).astype(jnp.int32), jnp.int32(2)]), + ) + ) + m = jnp.ones((1024, 1024), jnp.float32) * 1e-3 + errors = [] + worker_results = [] + + def read(logs: state_folding._FoldedLogs) -> None: + try: + worker_results.append(python_utils.pythonify_logs(logs)) + except Exception as e: # pylint: disable=broad-exception-caught + errors.append(e) + + for _ in range(100): + del worker_results[:] + float_vector, int_vector = slow(m) + logs = state_folding._FoldedLogs( + {"float32": ["a", "b"], "int32": ["c", "d"]}, + {"float32": float_vector, "int32": int_vector}, + ) + worker = threading.Thread(target=read, args=(logs,)) + worker.start() + main_result = None + try: + main_result = dict(logs) # What `JAXTrainer.fit` does at epoch end. + except Exception as e: # pylint: disable=broad-exception-caught + errors.append(e) + worker.join() + self.assertIsNotNone(main_result) + self.assertLen(worker_results, 1) + for key in ("a", "b", "c", "d"): + self.assertIsNotNone(main_result[key]) + self.assertIsNotNone(worker_results[0][key]) + self.assertEqual(main_result["d"], np.int32(2)) + self.assertEqual(worker_results[0]["d"], 2) + self.assertEmpty(errors) + + def test_fold_logs_empty_and_multiple_dtypes(self): + folding = state_folding._Folding(_model(), max_leaf_size=16, fold_logs=True) + + self.assertEqual(folding._fold_logs({}), {}) + self.assertEqual(folding._log_names_by_dtype, {}) + + folded = folding._fold_logs({ + "loss": jnp.array(1.0, dtype=jnp.float32), + "mae": jnp.array(0.5, dtype=jnp.bfloat16), + "step": jnp.array(100, dtype=jnp.int32), + }) + self.assertCountEqual(folded, ["float32", "bfloat16", "int32"]) + self.assertEqual(folded["float32"].shape, (1,)) + self.assertEqual(folded["bfloat16"].shape, (1,)) + self.assertEqual(folded["int32"].shape, (1,)) + + def test_folded_logs_read_methods_read_values_first(self): + def folded_logs(): + return state_folding._FoldedLogs( + {"float32": ["loss", "mae"], "int32": ["step"]}, + { + "float32": jnp.array([1.25, 0.5], dtype=jnp.float32), + "int32": jnp.array([10], dtype=jnp.int32), + }, + ) + + self.assertEqual(folded_logs().get("loss"), np.float32(1.25)) + self.assertEqual(folded_logs().get("missing", 0.0), 0.0) + self.assertIn(("step", np.int32(10)), list(folded_logs().items())) + self.assertIn(np.float32(0.5), list(folded_logs().values())) + self.assertEqual( + folded_logs().copy(), + { + "loss": np.float32(1.25), + "mae": np.float32(0.5), + "step": np.int32(10), + }, + ) + self.assertIn("1.25", repr(folded_logs())) + + def test_non_scalar_log_disables_log_folding_with_a_warning(self): + folding = state_folding._Folding(_model(), max_leaf_size=16, fold_logs=True) + logs = {"loss": jnp.float32(1.0), "per_class": jnp.zeros([3])} + + with self.assertLogs(level="WARNING") as captured: + folded = folding._fold_logs(logs) + + self.assertIs(folded, logs) + self.assertIsNone(folding._log_names_by_dtype) + self.assertIn("per_class", captured.output[0]) + + def test_nested_dict_log_disables_log_folding_with_a_warning(self): + folding = state_folding._Folding(_model(), max_leaf_size=16, fold_logs=True) + logs = {"loss": jnp.float32(1.0), "nested": {"a": jnp.float32(2.0)}} + + with self.assertLogs(level="WARNING") as captured: + folded = folding._fold_logs(logs) + + self.assertIs(folded, logs) + self.assertIn("nested", captured.output[0]) + + def test_folded_logs_mutation_and_comparison_read_values_first(self): + def folded_logs(): + return state_folding._FoldedLogs( + {"float32": ["loss", "mae"]}, + {"float32": jnp.array([1.25, 0.5], dtype=jnp.float32)}, + ) + + self.assertEqual(folded_logs(), {"loss": 1.25, "mae": 0.5}) + self.assertNotEqual(folded_logs(), {"loss": None, "mae": None}) + self.assertEqual(folded_logs().pop("loss"), np.float32(1.25)) + self.assertEqual(folded_logs().setdefault("mae"), np.float32(0.5)) + logs = folded_logs() + logs["loss"] = 5.0 + self.assertEqual(logs["loss"], 5.0) + logs = folded_logs() + logs.update(mae=7.0) + self.assertEqual(dict(logs), {"loss": 1.25, "mae": 7.0}) + self.assertEqual(folded_logs().popitem(), ("mae", np.float32(0.5))) + logs = folded_logs() + del logs["mae"] + self.assertEqual(logs["loss"], np.float32(1.25)) + self.assertNotIn("mae", logs) + logs = folded_logs() + logs |= {"loss": 99.0} + self.assertEqual(dict(logs), {"loss": 99.0, "mae": np.float32(0.5)}) + logs = folded_logs() + logs.clear() + self.assertEqual(logs, {}) + self.assertEqual(dict(logs), {}) + expected = {"loss": np.float32(1.25), "mae": np.float32(0.5)} + unpickled = pickle.loads( # pylint: disable=g-unsafe-pickle-load + pickle.dumps(folded_logs()) + ) + self.assertEqual(unpickled, expected) + logs = folded_logs() + _ = dict(logs) + unpickled = pickle.loads( # pylint: disable=g-unsafe-pickle-load + pickle.dumps(logs) + ) + self.assertEqual(unpickled, expected) + + def test_fit_folds_the_step_logs(self): + x, y = _data() + model = _model() + log_types = [] + with state_folding.model_state_folding_scope( + model, max_leaf_size=16, fold_logs=True + ): + model.make_train_function() + train_function = model.train_function + + def recording_train_function(state, iterator): + logs, state = train_function(state, iterator) + log_types.append(type(logs)) + return logs, state + + model.train_function = recording_train_function + model.fit(x, y, batch_size=8, epochs=1, shuffle=False, verbose=0) + + self.assertEqual(set(log_types), {state_folding._FoldedLogs}) + + def test_fit_without_fold_logs_returns_plain_logs(self): + x, y = _data() + model = _model() + log_types = [] + with state_folding.model_state_folding_scope(model, max_leaf_size=16): + model.make_train_function() + train_function = model.train_function + + def recording_train_function(state, iterator): + logs, state = train_function(state, iterator) + log_types.append(type(logs)) + return logs, state + + model.train_function = recording_train_function + model.fit(x, y, batch_size=8, epochs=1, shuffle=False, verbose=0) + + self.assertNotIn(state_folding._FoldedLogs, set(log_types)) + + def test_non_scalar_log_passes_all_logs_through_fit(self): + histories = [] + for max_leaf_size in (0, 16): + x, y = _data() + model = _model(model_cls=_NonScalarLogModel) + with state_folding.model_state_folding_scope( + model, max_leaf_size, fold_logs=True + ): + histories.append( + model.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + ) + + want = histories[0] + got = histories[1] + self.assertCountEqual(got, want) + for key, values in want.items(): + np.testing.assert_allclose(got[key], values, rtol=1e-6, err_msg=key) + + +if __name__ == "__main__": + absltest.main()