From 969f6c20c73fc39af0e550c69ba7f8afae443617 Mon Sep 17 00:00:00 2001 From: RecML authors Date: Tue, 24 Nov 2026 18:19:55 -0800 Subject: [PATCH] Internal change PiperOrigin-RevId: 1029491645 --- recml/core/training/keras_trainer.py | 17 +- .../training/keras_trainer_options_test.py | 60 +++ recml/core/training/state_folding.py | 192 +++++++++- recml/core/training/state_folding_test.py | 361 +++++++++++++++++- 4 files changed, 619 insertions(+), 11 deletions(-) diff --git a/recml/core/training/keras_trainer.py b/recml/core/training/keras_trainer.py index e7d8582..a8aefa4 100644 --- a/recml/core/training/keras_trainer.py +++ b/recml/core/training/keras_trainer.py @@ -135,6 +135,7 @@ def __init__( 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. @@ -199,6 +200,11 @@ def __init__( 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. @@ -207,7 +213,8 @@ def __init__( Raises: 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. + 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( @@ -223,6 +230,8 @@ def __init__( "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) @@ -250,6 +259,7 @@ def __init__( 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 ) @@ -440,6 +450,7 @@ def train(self, task: KerasTask) -> core.Logs: if keras.backend.backend() == "jax" else 0 ), + fold_logs=self._fold_step_logs, ), device_prefetch.model_prefetch_scope( model, depth=self._device_prefetch_depth @@ -505,8 +516,8 @@ def train_and_evaluate(self, task: KerasTask) -> core.Logs: ): logging.warning( "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`." + " 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 8a088e9..3575fed 100644 --- a/recml/core/training/keras_trainer_options_test.py +++ b/recml/core/training/keras_trainer_options_test.py @@ -191,6 +191,7 @@ def test_prefetch_skips_export_on_non_chief_hosts(self): 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) @@ -336,6 +337,10 @@ def test_zero_copy_batches_with_fold_batch_leaves(self): value, features[key][2 * step : 2 * step + 2] ) + 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_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) @@ -467,6 +472,7 @@ def make_dataset(): 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( @@ -486,6 +492,60 @@ def make_dataset(): opt_history.history[key], values, rtol=1e-6, err_msg=key ) + # Exercise `_FoldedLogs._read()` through `KerasTrainer.train` with + # `skip_batch_logs=False` and a per-batch callback. + want_batch_logs = [] + ref_cb_dir = os.path.join(self._tmpdir, "ref_batch_logs") + os.makedirs(ref_cb_dir) + _trainer( + ref_cb_dir, + train_steps=4, + steps_per_loop=2, + train_callbacks=[ + keras.callbacks.LambdaCallback( + on_train_batch_end=lambda _, logs: want_batch_logs.append( + dict(logs) + ) + ) + ], + distribution=keras.distribution.DataParallel(), + ).train( + types.SimpleNamespace( + create_dataset=lambda training: make_dataset(), + create_model=build_model, + export_model=lambda m, model_dir: None, + ) + ) + got_batch_logs = [] + opt_cb_dir = os.path.join(self._tmpdir, "opt_batch_logs") + os.makedirs(opt_cb_dir) + _trainer( + opt_cb_dir, + train_steps=4, + steps_per_loop=2, + fold_state_max_leaf_size=64, + fold_step_logs=True, + train_callbacks=[ + keras.callbacks.LambdaCallback( + on_train_batch_end=lambda _, logs: got_batch_logs.append( + dict(logs) + ) + ) + ], + distribution=keras.distribution.DataParallel(), + ).train( + types.SimpleNamespace( + create_dataset=lambda training: make_dataset(), + create_model=build_model, + export_model=lambda m, model_dir: None, + ) + ) + self.assertLen(got_batch_logs, 4) + for got, want in zip(got_batch_logs, want_batch_logs, strict=True): + self.assertCountEqual(got, want) + for key, value in want.items(): + np.testing.assert_allclose(got[key], value, 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 index aa999f1..b4cb73e 100644 --- a/recml/core/training/state_folding.py +++ b/recml/core/training/state_folding.py @@ -15,7 +15,7 @@ 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. The host pays per-array +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. @@ -24,7 +24,10 @@ each of the 4 state lists into one 1-D vector per dtype and replicated sharding. 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. +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. @@ -44,6 +47,7 @@ from absl import logging import jax from jax import flatten_util +import jax.numpy as jnp import keras import numpy as np @@ -53,6 +57,7 @@ "optimizer_variables", "metrics_variables", ) +_FOLDED_LOGS_KEY = "__state_folding_packed_logs__" @contextlib.contextmanager @@ -319,12 +324,128 @@ def fold_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`. + + # pylint: disable-next=useless-parent-delegation + def __iter__(self) -> Iterator[str]: + # 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): + 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 self.original_train_step = model.train_step self.original_make_train_function = model.make_train_function @@ -352,10 +473,53 @@ def folded_train_step( ) -> 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) + @staticmethod + def _fold_logs(logs: dict[str, Any]) -> dict[str, Any]: + """Stacks one-element logs into one vector per dtype. + + Returns `logs` unchanged (with a warning for nested dicts or multi-element + logs) when logs are empty or cannot be stacked. Log names are carried as + static PyTree metadata in the returned dict keys so XLA cache hits across + multiple batch shapes stay stateless. + + Args: + logs: The step logs returned by the model's `train_step`. + + Returns: + A single-entry dict carrying the stacked vectors and log names, or `logs`. + """ + if not logs: + return 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) + return logs + value = jnp.asarray(value) + if value.size != 1: + logging.warning( + "Not folding the step logs: %r has %d elements.", name, value.size + ) + return logs + named_values = named_values_by_dtype.setdefault(value.dtype.name, []) + named_values.append((name, value)) + return { + _FOLDED_LOGS_KEY: { + (dtype, tuple(name for name, _ in named_values)): 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.""" + """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( @@ -364,6 +528,20 @@ def folded_make_train_function(self, force: bool = False) -> None: self.folded_get_state_sharding_spec, ): self.original_make_train_function(force=force) + if not self._fold_logs_enabled: + return + 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 isinstance(logs, dict) and _FOLDED_LOGS_KEY in logs: + packed = logs[_FOLDED_LOGS_KEY] + names_by_dtype = {dtype: list(names) for dtype, names in packed} + vectors = {dtype: vec for (dtype, _), vec in packed.items()} + logs = _FoldedLogs(names_by_dtype, vectors) + 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) @@ -398,7 +576,7 @@ def folded_state_sync(self) -> None: @contextlib.contextmanager def model_state_folding_scope( - model: keras.Model, max_leaf_size: int + model: keras.Model, max_leaf_size: int, fold_logs: bool = False ) -> Iterator[None]: """Makes `model.fit` pass small replicated arrays of the state folded. @@ -406,6 +584,8 @@ def model_state_folding_scope( 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. @@ -413,7 +593,7 @@ def model_state_folding_scope( if max_leaf_size == 0: yield return - folding = _Folding(model, max_leaf_size) + folding = _Folding(model, max_leaf_size, fold_logs) model.train_function = None try: with ( diff --git a/recml/core/training/state_folding_test.py b/recml/core/training/state_folding_test.py index 445ab4d..0c60231 100644 --- a/recml/core/training/state_folding_test.py +++ b/recml/core/training/state_folding_test.py @@ -12,11 +12,14 @@ # 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 @@ -46,9 +49,30 @@ def train_step(self, state, data): return logs, state -def _model(build: bool = True) -> keras.Model: +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 + + +class _BatchShapedLogModel(_ExtraLogModel): + """Adds a `(batch_size,)` log: folds only on size-1 remainder batches.""" + + def train_step(self, state, data): + logs, state = super().train_step(state, data) + _, y = data[:2] + logs["per_row"] = y[:, 0] + return logs, state + + +def _model( + build: bool = True, model_cls: type[keras.Model] = _ExtraLogModel +) -> keras.Model: keras.utils.set_random_seed(0) - model = _ExtraLogModel() + model = model_cls() model.compile( optimizer=keras.optimizers.Adam(0.01), loss="mse", @@ -370,6 +394,339 @@ def test_list_layout_rejects_mismatched_lengths(self): with self.assertRaises(ValueError): layout.split_vectors([]) + 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({}), {}) + + folded = folding._fold_logs({ + "loss": jnp.array(1.0, dtype=jnp.float32), + "extra": jnp.array(2.5, dtype=jnp.float32), + "mae": jnp.array(0.5, dtype=jnp.bfloat16), + "step": jnp.array(100, dtype=jnp.int32), + }) + packed = folded[state_folding._FOLDED_LOGS_KEY] + self.assertCountEqual( + packed, + [ + ("float32", ("loss", "extra")), + ("bfloat16", ("mae",)), + ("int32", ("step",)), + ], + ) + np.testing.assert_array_equal( + packed[("float32", ("loss", "extra"))], + np.array([1.0, 2.5], dtype=np.float32), + ) + np.testing.assert_array_equal( + packed[("bfloat16", ("mae",))].astype(jnp.float32), + np.array([0.5], dtype=np.float32), + ) + np.testing.assert_array_equal( + packed[("int32", ("step",))], np.array([100], dtype=np.int32) + ) + + 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.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() + want_batch_logs, got_batch_logs = [], [] + expected = _model() + want_history = expected.fit( + x, + y, + batch_size=8, + epochs=2, + shuffle=False, + verbose=0, + callbacks=[ + keras.callbacks.LambdaCallback( + on_train_batch_end=lambda _, logs: want_batch_logs.append( + dict(logs) + ) + ) + ], + ).history + 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 + got_history = model.fit( + x, + y, + batch_size=8, + epochs=2, + shuffle=False, + verbose=0, + callbacks=[ + keras.callbacks.LambdaCallback( + on_train_batch_end=lambda _, logs: got_batch_logs.append( + dict(logs) + ) + ) + ], + ).history + + self.assertEqual(set(log_types), {state_folding._FoldedLogs}) + self._assert_same_training(model, got_history, expected, want_history) + for got, want in zip(got_batch_logs, want_batch_logs, strict=True): + self.assertCountEqual(got, want) + for key, value in want.items(): + np.testing.assert_allclose(got[key], value, rtol=1e-6, err_msg=key) + + def test_fit_folds_step_logs_with_steps_per_execution(self): + x, y = _data() + expected = _model() + expected.steps_per_execution = 2 + want_history = expected.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + model = _model() + model.steps_per_execution = 2 + 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 + got_history = model.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + + self.assertEqual(set(log_types), {state_folding._FoldedLogs}) + self._assert_same_training(model, got_history, expected, want_history) + + def test_mixed_batch_shapes_fold_and_pass_through_across_epochs(self): + x, y = _data() + x, y = x[:9], y[:9] # Batch 0 has size 8 (raw), batch 1 has size 1 (fold). + expected = _model(model_cls=_BatchShapedLogModel) + want_history = expected.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + + model = _model(model_cls=_BatchShapedLogModel) + 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 + got_history = model.fit( + x, y, batch_size=8, epochs=2, shuffle=False, verbose=0 + ).history + + # Epoch 2 step 0 hits the B=8 XLA cache and stays raw (not _FoldedLogs). + self.assertEqual( + log_types, + [dict, state_folding._FoldedLogs, dict, state_folding._FoldedLogs], + ) + # On the B=1 remainder batch, the (1,) log folds and returns as a scalar. + np.testing.assert_allclose( + got_history.pop("per_row"), + np.squeeze(want_history.pop("per_row"), axis=-1), + rtol=1e-6, + ) + self._assert_same_training(model, got_history, expected, want_history) + + 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()