From e8c8746d6d437124c86a5e5f8620091368b7fadf Mon Sep 17 00:00:00 2001 From: RecML authors Date: Tue, 24 Nov 2026 15:21:17 -0800 Subject: [PATCH] Internal change PiperOrigin-RevId: 1029382863 --- recml/core/training/state_folding.py | 431 ++++++++++++++++++++++ recml/core/training/state_folding_test.py | 375 +++++++++++++++++++ 2 files changed, 806 insertions(+) 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/state_folding.py b/recml/core/training/state_folding.py new file mode 100644 index 0000000..aa999f1 --- /dev/null +++ b/recml/core/training/state_folding.py @@ -0,0 +1,431 @@ +# 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. 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 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. + +Terms: + leaf: one array of a state list. + small leaf: a fully replicated leaf with no sharded axes and at most + `max_leaf_size` elements. + vector: the 1-D concatenation of the raveled small leaves with the same dtype + and replicated sharding. + passthrough leaf: a leaf that is not in a vector (large, sharded, or the + only small leaf in its dtype and sharding group). + 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 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(), + memory_kind=leaf_sharding.memory_kind, + ) + return leaf_sharding + + +def _is_foldable_leaf(leaf: jax.Array, max_leaf_size: int) -> bool: + """Returns whether `leaf` can be folded into a replicated 1-D vector.""" + if leaf.size > max_leaf_size or not leaf.sharding.is_fully_replicated: + return False + if isinstance(leaf.sharding, jax.sharding.NamedSharding): + return all(axis is None for axis in leaf.sharding.spec) + return True + + +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_group: dict[ + tuple[np.dtype[Any], jax.sharding.Sharding], list[int] + ] = {} + for i, leaf in enumerate(leaves): + if _is_foldable_leaf(leaf, max_leaf_size): + group = ( + np.dtype(leaf.dtype), + _replicated_vector_sharding(leaf.sharding), + ) + small_leaf_indices_by_group.setdefault(group, []).append(i) + # For each vector, the indices of its leaves in the order of their entries. + vector_groups = [ + (sharding, leaf_indices) + for (_, sharding), leaf_indices in small_leaf_indices_by_group.items() + if len(leaf_indices) > 1 + ] + self.vector_leaf_indices = [indices for _, indices in vector_groups] + 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 = [sharding for sharding, _ in vector_groups] + # `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.""" + if len(leaves) != self.num_leaves: + raise ValueError( + f"Expected {self.num_leaves} state leaves, got {len(leaves)}." + ) + 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, strict=True) + ] + + def fold_list( + self, leaves: Sequence[Any], vectors: Sequence[Any] + ) -> list[Any]: + """Returns the folded list of `leaves`, given its `vectors`.""" + if len(leaves) != self.num_leaves: + raise ValueError( + f"Expected {self.num_leaves} state leaves, got {len(leaves)}." + ) + if len(vectors) != len(self.vector_leaf_indices): + raise ValueError( + f"Expected {len(self.vector_leaf_indices)} vectors, got" + f" {len(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.""" + if len(folded_list) != self.folded_list_length: + raise ValueError( + f"Expected {self.folded_list_length} folded entries, got" + f" {len(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`.""" + if len(folded_list) != self.folded_list_length: + raise ValueError( + f"Expected {self.folded_list_length} folded entries, got" + f" {len(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, strict=True + ): + for i, leaf in zip(leaf_indices, vector_leaves, strict=True): + 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, strict=True + ) + ] + + 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, strict=True + ) + ] + + 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, strict=True) + ] + 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, strict=True + ) + ) + + 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, strict=True) + ] + 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, strict=True + ) + ) + + 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, strict=True + ) + ) + + +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): + self._model = model + self._max_leaf_size = max_leaf_size + self._layout: _StateLayout | 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) + return logs, layout.fold(state) + + def folded_make_train_function(self, force: bool = False) -> None: + """Builds `model.train_function` with folded state shardings.""" + # 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) + + 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, strict=True) + ) + self.original_state_sync() + + +@contextlib.contextmanager +def model_state_folding_scope( + model: keras.Model, max_leaf_size: int +) -> 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. + + Yields: + None. + """ + if max_leaf_size == 0: + yield + return + folding = _Folding(model, max_leaf_size) + 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..445ab4d --- /dev/null +++ b/recml/core/training/state_folding_test.py @@ -0,0 +1,375 @@ +# 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 + +from absl.testing import absltest +import jax +import jax.numpy as jnp +import keras +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 + + +def _model(build: bool = True) -> keras.Model: + keras.utils.set_random_seed(0) + model = _ExtraLogModel() + 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_single_device_named_sharding_with_axis_passes_through(self): + mesh = jax.sharding.Mesh(np.array([jax.devices()[0]]), ("sparsecore",)) + sharded = jax.sharding.NamedSharding( + mesh, jax.sharding.PartitionSpec("sparsecore") + ) + 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), + ] + self.assertTrue(leaves[0].sharding.is_fully_replicated) + + layout = state_folding._ListLayout(leaves, max_leaf_size=16) + + self.assertEqual(layout.passthrough_leaf_indices, [0]) + self.assertEqual(layout.vector_leaf_indices, [[1, 2]]) + + def test_list_layout_groups_by_sharding_and_preserves_memory_kind(self): + devices = self._require_4_devices() + mesh_a = jax.sharding.Mesh(np.array(devices[:2]), ("a",)) + mesh_b = jax.sharding.Mesh(np.array(devices[2:]), ("b",)) + sharding_a = jax.sharding.NamedSharding( + mesh_a, jax.sharding.PartitionSpec() + ) + sharding_b = jax.sharding.NamedSharding( + mesh_b, jax.sharding.PartitionSpec() + ) + pinned = jax.sharding.NamedSharding( + mesh_a, jax.sharding.PartitionSpec(None), memory_kind="pinned_host" + ) + self.assertEqual( + state_folding._replicated_vector_sharding(pinned), + jax.sharding.NamedSharding( + mesh_a, jax.sharding.PartitionSpec(), memory_kind="pinned_host" + ), + ) + leaves = [ + jax.device_put(jnp.zeros([2], jnp.float32), sharding_a), + jax.device_put(jnp.zeros([2], jnp.float32), sharding_b), + jax.device_put(jnp.zeros([], jnp.float32), sharding_a), + jax.device_put(jnp.zeros([], jnp.float32), sharding_b), + ] + + layout = state_folding._ListLayout(leaves, max_leaf_size=16) + + self.assertEmpty(layout.passthrough_leaf_indices) + self.assertEqual(layout.vector_leaf_indices, [[0, 2], [1, 3]]) + self.assertEqual(layout.vector_shardings, [sharding_a, sharding_b]) + + def test_list_layout_rejects_mismatched_lengths(self): + leaves = [ + jnp.zeros([3], jnp.int32), + jnp.zeros([], jnp.float32), + jnp.zeros([1], jnp.float32), + ] + layout = state_folding._ListLayout(leaves, max_leaf_size=2) + + with self.assertRaisesRegex(ValueError, "Expected 3 state leaves, got 4"): + layout.leaves_by_vector(leaves + [jnp.zeros([], jnp.float32)]) + with self.assertRaisesRegex(ValueError, "Expected 3 state leaves, got 2"): + layout.fold_list(leaves[:2], [jnp.zeros([2], jnp.float32)]) + with self.assertRaisesRegex(ValueError, "Expected 1 vectors, got 0"): + layout.fold_list(leaves, []) + with self.assertRaisesRegex(ValueError, "Expected 2 folded entries, got 3"): + layout.vectors_in_folded_list([0, 1, 2]) + with self.assertRaisesRegex(ValueError, "Expected 2 folded entries, got 1"): + layout.unfold_list([0], [[jnp.zeros([]), jnp.zeros([1])]]) + with self.assertRaises(ValueError): + layout.split_vectors([]) + + +if __name__ == "__main__": + absltest.main()