diff --git a/recml/core/ops/binary_cross_entropy_ops.py b/recml/core/ops/binary_cross_entropy_ops.py index eb12af0..a5753f8 100644 --- a/recml/core/ops/binary_cross_entropy_ops.py +++ b/recml/core/ops/binary_cross_entropy_ops.py @@ -158,12 +158,38 @@ def _get_sharding(x: jt.ArrayLike) -> jax.sharding.Sharding | None: return None +def _check_not_partially_manual( + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh, +) -> None: + """Raises if `mesh` mixes manual and non-manual axes.""" + if 0 < len(mesh.manual_axes) < len(mesh.axis_names): + raise NotImplementedError( + "Partially-manual shard_map meshes mixing manual and non-manual axes" + f" are not supported; got {mesh}." + ) + + +def _has_non_manual_axes( + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh, +) -> bool: + """Returns whether the active mesh has non-manual axes.""" + ctx_mesh = jax.sharding.get_abstract_mesh() + effective = ctx_mesh if not ctx_mesh.empty else mesh + _check_not_partially_manual(effective) + if effective is not mesh: + _check_not_partially_manual(mesh) + return not effective.empty and not effective.manual_axes + + def _token_shard_count( x: jt.Float[jt.Array, "... D"], mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh | None = None, spec: jax.sharding.PartitionSpec | None = None, ) -> int | None: """Returns how many ways the token axes of `x` are sharded, or None.""" + ctx_mesh = jax.sharding.get_abstract_mesh() + if not ctx_mesh.empty and not _has_non_manual_axes(ctx_mesh): + return 1 if mesh is None or spec is None: sharding = _get_sharding(x) if not isinstance(sharding, jax.sharding.NamedSharding): @@ -171,6 +197,8 @@ def _token_shard_count( mesh, spec = sharding.mesh, sharding.spec if mesh.empty: return None + if not _has_non_manual_axes(mesh): + return 1 # A PartitionSpec may be shorter than `x.ndim`; trailing axes are unsharded. factor = 1 @@ -207,7 +235,7 @@ def _replicate_hidden_dim( sharding = _get_sharding(x) if isinstance(sharding, jax.sharding.NamedSharding): mesh = sharding.mesh - if not mesh.empty: + if _has_non_manual_axes(mesh): spec = sharding.spec new_spec_list = list(spec) + [None] * (x.ndim - len(spec)) if new_spec_list: @@ -633,6 +661,10 @@ def cut_binary_cross_entropy( and above raise a `ValueError`. Reshape or vmap over the extra leading axes before calling this op. + When called inside an outer ``jax.shard_map`` with ``use_pallas=True``, the + outer ``shard_map`` must set ``check_vma=False`` because the backward Pallas + kernel declares ``ShapeDtypeStruct`` outputs without ``manual_axis_type``. + Args: activations: Hidden-state outputs of shape ``[B, N, D]``, or ``[X, B, N, D]`` with a single extra leading axis. @@ -679,6 +711,8 @@ def cut_binary_cross_entropy( Raises: ValueError: If ``activations`` has rank 5 or above, or if ``weights`` does not exactly match the per-position loss shape. + NotImplementedError: If ``embeddings`` are sharded along hidden dim ``D``, + or if the active mesh mixes manual and non-manual axes. """ # `_bce_fwd_local` operates on a single `[B, N, D]` array and the forward # pass only vmaps over one extra leading axis, so ranks >= 5 are unsupported. @@ -703,13 +737,14 @@ def cut_binary_cross_entropy( f" {tuple(weights.shape)}." ) + _check_not_partially_manual(jax.sharding.get_abstract_mesh()) + # Prevent collective communications inside the loop by forcing replication of # weights. sharding = _get_sharding(embeddings) - if ( - isinstance(sharding, jax.sharding.NamedSharding) - and not sharding.mesh.empty - ): + if isinstance( + sharding, jax.sharding.NamedSharding + ) and _has_non_manual_axes(sharding.mesh): replicated_sharding = jax.sharding.NamedSharding( sharding.mesh, jax.sharding.PartitionSpec() ) @@ -1580,6 +1615,7 @@ def _bce_bwd_sharded( jt.Float[jt.Array, "V D"], ]: """Sharding-aware dispatcher for BCE backward.""" + _check_not_partially_manual(jax.sharding.get_abstract_mesh()) mesh = None act_spec = None emb_spec = None @@ -1589,13 +1625,13 @@ def _bce_bwd_sharded( act_spec = config.act_spec emb_spec = config.emb_spec or jax.sharding.PartitionSpec() act_sharding = jax.sharding.NamedSharding(mesh, act_spec) - is_sharded = True + is_sharded = _has_non_manual_axes(mesh) else: act_sharding = _get_sharding(activations) emb_sharding = _get_sharding(embeddings) is_sharded = ( isinstance(act_sharding, jax.sharding.NamedSharding) - and not act_sharding.mesh.empty + and _has_non_manual_axes(act_sharding.mesh) and isinstance(emb_sharding, jax.sharding.NamedSharding) ) if is_sharded: diff --git a/recml/core/ops/binary_cross_entropy_ops_test.py b/recml/core/ops/binary_cross_entropy_ops_test.py index 8e735aa..6f490ad 100644 --- a/recml/core/ops/binary_cross_entropy_ops_test.py +++ b/recml/core/ops/binary_cross_entropy_ops_test.py @@ -264,6 +264,45 @@ def test_local_tokens_with_real_mesh(self): binary_cross_entropy_ops._local_tokens(activations), 8 * 64 ) + def test_local_tokens_inside_shard_map(self): + num_devices = jax.device_count() + mesh = jax.sharding.Mesh(np.array(jax.devices()), ('batch',)) + local_counts = [] + explicit_counts = [] + eager_counts = [] + + def per_shard_eager(local_x): + eager_counts.append(binary_cross_entropy_ops._local_tokens(local_x)) + return local_x + + jax.shard_map( + per_shard_eager, mesh=mesh, in_specs=P('batch'), out_specs=P('batch') + )(jnp.ones((2 * num_devices, 64, 32))) + self.assertEqual(eager_counts[-1], 2 * 64) + + @jax.jit + def f(x): + def per_shard(local_x): + local_counts.append(binary_cross_entropy_ops._local_tokens(local_x)) + explicit_counts.append( + binary_cross_entropy_ops._local_tokens( + local_x, mesh, P('batch', None, None) + ) + ) + return local_x + + return jax.shard_map( + per_shard, mesh=mesh, in_specs=P('batch'), out_specs=P('batch') + )(x) + + x_sharded = jax.device_put( + jnp.ones((2 * num_devices, 64, 32)), + jax.sharding.NamedSharding(mesh, P('batch', None, None)), + ) + f(x_sharded) + self.assertEqual(local_counts[-1], 2 * 64) + self.assertEqual(explicit_counts[-1], 2 * 64) + # --- `block_v` selection: the memory budget itself. ------------------------ def test_auto_block_v_is_clamped_to_vocab_size(self): @@ -1210,6 +1249,149 @@ def loss_fn(act, emb, force_bwd): g_emb_forced, g_emb_clamped, atol=1e-5, rtol=1e-5 ) + @parameterized.named_parameters( + ('pure_jax_tiled', False, False), + ('pallas_tiled', True, False), + ('pure_jax_explicit_mesh', False, True), + ('pallas_explicit_mesh', True, True), + ) + def test_cut_bce_inside_shard_map_jit_grad( + self, use_pallas, explicit_mesh_and_closed_emb + ): + num_devices = jax.device_count() + batch, seq_len, hidden_dim = 2 * num_devices, 16, 128 + vocab_size, num_labels = 256, 3 + key_act, key_emb, key_tgt = jax.random.split(jax.random.PRNGKey(17), 3) + mesh = jax.sharding.Mesh(np.array(jax.devices()), ('batch',)) + batch_sharding = jax.sharding.NamedSharding(mesh, P('batch', None, None)) + replicated_sharding = jax.sharding.NamedSharding(mesh, P()) + activations = jax.device_put( + jax.random.normal(key_act, (batch, seq_len, hidden_dim)), + batch_sharding, + ) + embeddings = jax.device_put( + jax.random.normal(key_emb, (vocab_size, hidden_dim)), + replicated_sharding, + ) + targets = jax.device_put( + jax.random.randint( + key_tgt, (batch, seq_len, num_labels), 0, vocab_size + ), + batch_sharding, + ) + + def sharded_loss_and_metrics(act, emb): + if explicit_mesh_and_closed_emb: + + def per_shard_closed(local_act, local_tgt): + _, per_pos, tp, fp, fn, tn = ( + binary_cross_entropy_ops.cut_binary_cross_entropy( + local_act, + emb, + local_tgt, + block_v=None, + mesh=mesh, + act_spec=P('batch', None, None), + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + return_per_target_metrics=True, + ) + ) + return per_pos, tp, fp, fn, tn + + losses, tp, fp, fn, tn = jax.shard_map( + per_shard_closed, + mesh=mesh, + in_specs=(P('batch'), P('batch')), + out_specs=(P('batch'),) * 5, + check_vma=False, + )(act, targets) + else: + tiled_emb = jnp.tile(emb, (num_devices, 1)) + + def per_shard_tiled(local_act, local_emb, local_tgt): + _, per_pos, tp, fp, fn, tn = ( + binary_cross_entropy_ops.cut_binary_cross_entropy( + local_act, + local_emb, + local_tgt, + block_v=None, + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + return_per_target_metrics=True, + ) + ) + return per_pos, tp, fp, fn, tn + + losses, tp, fp, fn, tn = jax.shard_map( + per_shard_tiled, + mesh=mesh, + in_specs=(P('batch'), P('batch'), P('batch')), + out_specs=(P('batch'),) * 5, + check_vma=False, + )(act, tiled_emb, targets) + + metrics = (jnp.sum(tp), jnp.sum(fp), jnp.sum(fn), jnp.sum(tn)) + return jnp.mean(losses), metrics + + def ref_loss_and_metrics(act, emb): + _, per_pos, tp, fp, fn, tn = ( + binary_cross_entropy_ops.cut_binary_cross_entropy( + act, + emb, + targets, + block_v=None, + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + ) + ) + return jnp.mean(per_pos), (tp, fp, fn, tn) + + (loss_got, metrics_got), (g_act_got, g_emb_got) = jax.jit( + jax.value_and_grad( + sharded_loss_and_metrics, argnums=(0, 1), has_aux=True + ) + )(activations, embeddings) + (loss_ref, metrics_ref), (g_act_ref, g_emb_ref) = jax.jit( + jax.value_and_grad(ref_loss_and_metrics, argnums=(0, 1), has_aux=True) + )(activations, embeddings) + np.testing.assert_allclose(loss_got, loss_ref, atol=1e-5, rtol=1e-5) + for got_metric, ref_metric in zip(metrics_got, metrics_ref, strict=True): + np.testing.assert_allclose(got_metric, ref_metric, atol=1e-5, rtol=1e-5) + np.testing.assert_allclose(g_act_got, g_act_ref, atol=1e-5, rtol=1e-5) + np.testing.assert_allclose(g_emb_got, g_emb_ref, atol=1e-5, rtol=1e-5) + + def test_partially_manual_shard_map_raises(self): + num_devices = jax.device_count() + mesh = jax.sharding.Mesh( + np.array(jax.devices()).reshape(num_devices, 1), ('dp', 'tp') + ) + activations = jnp.ones((num_devices, 8, 128)) + embeddings = jnp.ones((128, 128)) + targets = jnp.zeros((num_devices, 8, 2), dtype=jnp.int32) + + def per_dp_shard(local_act, local_tgt): + return binary_cross_entropy_ops.cut_binary_cross_entropy( + local_act, + embeddings, + local_tgt, + use_pallas=False, + return_per_target_losses=True, + )[1] + + with self.assertRaisesRegex(NotImplementedError, 'Partially-manual'): + jax.shard_map( + per_dp_shard, + mesh=mesh, + axis_names={'dp'}, + in_specs=(P('dp'), P('dp')), + out_specs=P('dp'), + check_vma=False, + )(activations, targets) + if __name__ == '__main__': absltest.main() diff --git a/recml/core/ops/binary_focal_cross_entropy_ops.py b/recml/core/ops/binary_focal_cross_entropy_ops.py index 311af8e..e35d7f2 100644 --- a/recml/core/ops/binary_focal_cross_entropy_ops.py +++ b/recml/core/ops/binary_focal_cross_entropy_ops.py @@ -36,6 +36,9 @@ bce_ops._bce_bwd_scan_groups # pylint: disable=protected-access ) _local_tokens = bce_ops._local_tokens # pylint: disable=protected-access +_check_not_partially_manual = ( + bce_ops._check_not_partially_manual # pylint: disable=protected-access +) _check_vocab_replicated_in_d = ( bce_ops._check_vocab_replicated_in_d # pylint: disable=protected-access ) @@ -43,6 +46,9 @@ bce_ops._effective_block_v # pylint: disable=protected-access ) _get_sharding = bce_ops._get_sharding # pylint: disable=protected-access +_has_non_manual_axes = ( + bce_ops._has_non_manual_axes # pylint: disable=protected-access +) _max_safe_block_v = bce_ops._max_safe_block_v # pylint: disable=protected-access _max_safe_chunk_n = bce_ops._max_safe_chunk_n # pylint: disable=protected-access _pallas_interpret = bce_ops._pallas_interpret # pylint: disable=protected-access @@ -447,6 +453,10 @@ def cut_binary_focal_cross_entropy( and above raise a `ValueError`. Reshape or vmap over the extra leading axes before calling this op. + When called inside an outer ``jax.shard_map`` with ``use_pallas=True``, the + outer ``shard_map`` must set ``check_vma=False`` because the backward Pallas + kernel declares ``ShapeDtypeStruct`` outputs without ``manual_axis_type``. + Args: activations: Hidden-state outputs of shape ``[B, N, D]``, or ``[X, B, N, D]`` with a single extra leading axis. @@ -496,6 +506,8 @@ def cut_binary_focal_cross_entropy( Raises: ValueError: If ``activations`` has rank 5 or above, or if ``weights`` does not exactly match the per-position loss shape. + NotImplementedError: If ``embeddings`` are sharded along hidden dim ``D``, + or if the active mesh mixes manual and non-manual axes. """ # `_focal_bce_fwd_local` operates on a single `[B, N, D]` array and the # forward pass only vmaps over one extra leading axis, so ranks >= 5 are @@ -521,11 +533,12 @@ def cut_binary_focal_cross_entropy( f" {tuple(weights.shape)}." ) + _check_not_partially_manual(jax.sharding.get_abstract_mesh()) + sharding = _get_sharding(embeddings) - if ( - isinstance(sharding, jax.sharding.NamedSharding) - and not sharding.mesh.empty - ): + if isinstance( + sharding, jax.sharding.NamedSharding + ) and _has_non_manual_axes(sharding.mesh): replicated_sharding = jax.sharding.NamedSharding( sharding.mesh, jax.sharding.PartitionSpec() ) @@ -1149,6 +1162,7 @@ def _focal_bce_bwd_sharded( jt.Float[jt.Array, "V D"], ]: """Sharding-aware dispatcher for Focal BCE backward.""" + _check_not_partially_manual(jax.sharding.get_abstract_mesh()) mesh = None act_spec = None emb_spec = None @@ -1158,13 +1172,13 @@ def _focal_bce_bwd_sharded( act_spec = config.act_spec emb_spec = config.emb_spec or jax.sharding.PartitionSpec() act_sharding = jax.sharding.NamedSharding(mesh, act_spec) - is_sharded = True + is_sharded = _has_non_manual_axes(mesh) else: act_sharding = _get_sharding(activations) emb_sharding = _get_sharding(embeddings) is_sharded = ( isinstance(act_sharding, jax.sharding.NamedSharding) - and not act_sharding.mesh.empty + and _has_non_manual_axes(act_sharding.mesh) and isinstance(emb_sharding, jax.sharding.NamedSharding) ) if is_sharded: diff --git a/recml/core/ops/binary_focal_cross_entropy_ops_test.py b/recml/core/ops/binary_focal_cross_entropy_ops_test.py index b04a9a8..b15bb64 100644 --- a/recml/core/ops/binary_focal_cross_entropy_ops_test.py +++ b/recml/core/ops/binary_focal_cross_entropy_ops_test.py @@ -1160,6 +1160,149 @@ def loss_fn(act, emb, force_bwd): g_emb_forced, g_emb_clamped, atol=1e-4, rtol=1e-4 ) + @parameterized.named_parameters( + ('pure_jax_tiled', False, False), + ('pallas_tiled', True, False), + ('pure_jax_explicit_mesh', False, True), + ('pallas_explicit_mesh', True, True), + ) + def test_cut_focal_bce_inside_shard_map_jit_grad( + self, use_pallas, explicit_mesh_and_closed_emb + ): + num_devices = jax.device_count() + batch, seq_len, hidden_dim = 2 * num_devices, 16, 128 + vocab_size, num_labels = 256, 3 + key_act, key_emb, key_tgt = jax.random.split(jax.random.PRNGKey(17), 3) + mesh = jax.sharding.Mesh(np.array(jax.devices()), ('batch',)) + batch_sharding = jax.sharding.NamedSharding(mesh, P('batch', None, None)) + replicated_sharding = jax.sharding.NamedSharding(mesh, P()) + activations = jax.device_put( + jax.random.normal(key_act, (batch, seq_len, hidden_dim)), + batch_sharding, + ) + embeddings = jax.device_put( + jax.random.normal(key_emb, (vocab_size, hidden_dim)), + replicated_sharding, + ) + targets = jax.device_put( + jax.random.randint( + key_tgt, (batch, seq_len, num_labels), 0, vocab_size + ), + batch_sharding, + ) + + def sharded_loss_and_metrics(act, emb): + if explicit_mesh_and_closed_emb: + + def per_shard_closed(local_act, local_tgt): + _, per_pos, tp, fp, fn, tn = ( + binary_focal_cross_entropy_ops.cut_binary_focal_cross_entropy( + local_act, + emb, + local_tgt, + block_v=None, + mesh=mesh, + act_spec=P('batch', None, None), + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + return_per_target_metrics=True, + ) + ) + return per_pos, tp, fp, fn, tn + + losses, tp, fp, fn, tn = jax.shard_map( + per_shard_closed, + mesh=mesh, + in_specs=(P('batch'), P('batch')), + out_specs=(P('batch'),) * 5, + check_vma=False, + )(act, targets) + else: + tiled_emb = jnp.tile(emb, (num_devices, 1)) + + def per_shard_tiled(local_act, local_emb, local_tgt): + _, per_pos, tp, fp, fn, tn = ( + binary_focal_cross_entropy_ops.cut_binary_focal_cross_entropy( + local_act, + local_emb, + local_tgt, + block_v=None, + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + return_per_target_metrics=True, + ) + ) + return per_pos, tp, fp, fn, tn + + losses, tp, fp, fn, tn = jax.shard_map( + per_shard_tiled, + mesh=mesh, + in_specs=(P('batch'), P('batch'), P('batch')), + out_specs=(P('batch'),) * 5, + check_vma=False, + )(act, tiled_emb, targets) + + metrics = (jnp.sum(tp), jnp.sum(fp), jnp.sum(fn), jnp.sum(tn)) + return jnp.mean(losses), metrics + + def ref_loss_and_metrics(act, emb): + _, per_pos, tp, fp, fn, tn = ( + binary_focal_cross_entropy_ops.cut_binary_focal_cross_entropy( + act, + emb, + targets, + block_v=None, + use_pallas=use_pallas, + return_per_target_losses=True, + return_metrics=True, + ) + ) + return jnp.mean(per_pos), (tp, fp, fn, tn) + + (loss_got, metrics_got), (g_act_got, g_emb_got) = jax.jit( + jax.value_and_grad( + sharded_loss_and_metrics, argnums=(0, 1), has_aux=True + ) + )(activations, embeddings) + (loss_ref, metrics_ref), (g_act_ref, g_emb_ref) = jax.jit( + jax.value_and_grad(ref_loss_and_metrics, argnums=(0, 1), has_aux=True) + )(activations, embeddings) + np.testing.assert_allclose(loss_got, loss_ref, atol=1e-5, rtol=1e-5) + for got_metric, ref_metric in zip(metrics_got, metrics_ref, strict=True): + np.testing.assert_allclose(got_metric, ref_metric, atol=1e-5, rtol=1e-5) + np.testing.assert_allclose(g_act_got, g_act_ref, atol=1e-5, rtol=1e-5) + np.testing.assert_allclose(g_emb_got, g_emb_ref, atol=1e-5, rtol=1e-5) + + def test_partially_manual_shard_map_raises(self): + num_devices = jax.device_count() + mesh = jax.sharding.Mesh( + np.array(jax.devices()).reshape(num_devices, 1), ('dp', 'tp') + ) + activations = jnp.ones((num_devices, 8, 128)) + embeddings = jnp.ones((128, 128)) + targets = jnp.zeros((num_devices, 8, 2), dtype=jnp.int32) + + def per_dp_shard(local_act, local_tgt): + return binary_focal_cross_entropy_ops.cut_binary_focal_cross_entropy( + local_act, + embeddings, + local_tgt, + use_pallas=False, + return_per_target_losses=True, + )[1] + + with self.assertRaisesRegex(NotImplementedError, 'Partially-manual'): + jax.shard_map( + per_dp_shard, + mesh=mesh, + axis_names={'dp'}, + in_specs=(P('dp'), P('dp')), + out_specs=P('dp'), + check_vma=False, + )(activations, targets) + if __name__ == '__main__': absltest.main() diff --git a/recml/core/utils/distribution_utils.py b/recml/core/utils/distribution_utils.py index e079588..5de27a9 100644 --- a/recml/core/utils/distribution_utils.py +++ b/recml/core/utils/distribution_utils.py @@ -13,8 +13,17 @@ # limitations under the License. """Utilities for inspecting the active JAX/Keras distribution mesh.""" +from collections.abc import Callable +import functools +import math +from typing import Any +import weakref + import jax +from jax import lax +import jax.numpy as jnp import keras +from keras.src.backend.common import variables as keras_variables # Conventional name of the mesh axis used for model/tensor parallelism. Any # other axis of the mesh is assumed to shard the batch. @@ -120,3 +129,278 @@ def resolve_batch_axis( # somewhere; fall back to the full set of axis names. batch_axes = tuple(abstract_mesh.axis_names) return normalize_axis(batch_axes) + + +def fuse_table_grads_enabled() -> bool: + """Returns whether the active distribution fuses table gradients. + + A distribution opts in by setting a truthy `fuse_table_grads` attribute. + Layers that read a large table with a batch (embedding lookups, tied output + projections) then run that read through `fused_table_grad_call`. + + Returns: + True if a distribution is active and its `fuse_table_grads` is truthy. + """ + return bool( + getattr(keras.distribution.distribution(), 'fuse_table_grads', False) + ) + + +def bf16_table_allreduce_enabled() -> bool: + """Returns whether fused table gradients use bfloat16 cross-device all-reduce. + + When enabled, per-device local gradient accumulation across all readers of a + shared table still runs in the table's variable dtype (typically `float32`), + and only the cross-device `psum` collective casts to `bfloat16` before casting + back to the variable dtype for the optimizer update. + + Returns: + True if a distribution is active and its `bf16_table_allreduce` is truthy. + """ + return bool( + getattr(keras.distribution.distribution(), 'bf16_table_allreduce', False) + ) + + +class FusedTableGradDataParallel(keras.distribution.DataParallel): + """`DataParallel` that fuses gradients across reads of each replicated table. + + Under plain `DataParallel`, XLA partitions every embedding lookup's gradient + (a scatter-add into a replicated table) as a local scatter plus an + all-reduce, and it seeds the next scatter of the same table with that + all-reduce's result. A table read by N lookups then pays a chain of up to N + table-sized all-reduces per step. With this distribution, every read of a + table runs under `jax.shard_map` on a shared per-device copy of the table. + Each device adds up its reads' table gradients locally, and one all-reduce + per table sums the result across devices. The forward computation is + unchanged; only the order in which the table gradient is summed changes. + + Attributes: + fuse_table_grads: Whether this distribution opts in to fused table + gradients. Always True. + bf16_table_allreduce: If True, cast the locally accumulated per-device table + gradient to `bfloat16` for the cross-device all-reduce, then cast back to + the variable dtype (`float32`) for the optimizer update. + """ + + fuse_table_grads = True + + def __init__( + self, + *args, + bf16_table_allreduce: bool = False, + **kwargs, + ): + super().__init__(*args, **kwargs) + self.bf16_table_allreduce = bf16_table_allreduce + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(1, 2, 3, 4)) +def _tile_with_collective_dtype( + table_value: jax.Array, + num_copies: int, + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh, + batch_axis: str | tuple[str, ...], + allreduce_dtype: Any, +) -> jax.Array: + """Tiles a replicated table into per-device copies with custom collective dtype.""" + del mesh, batch_axis, allreduce_dtype + return jnp.tile(table_value, (num_copies,) + (1,) * (table_value.ndim - 1)) + + +def _tile_with_collective_dtype_fwd( + table_value: jax.Array, + num_copies: int, + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh, + batch_axis: str | tuple[str, ...], + allreduce_dtype: Any, +) -> tuple[jax.Array, None]: + del mesh, batch_axis, allreduce_dtype + copies = jnp.tile(table_value, (num_copies,) + (1,) * (table_value.ndim - 1)) + return copies, None + + +def _tile_with_collective_dtype_bwd( + num_copies: int, + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh, + batch_axis: str | tuple[str, ...], + allreduce_dtype: Any, + res: None, + g_copies: jax.Array, +) -> tuple[jax.Array]: + del res + table_shape = (g_copies.shape[0] // num_copies, *g_copies.shape[1:]) + table_dtype = g_copies.dtype + if allreduce_dtype is not None and table_dtype != allreduce_dtype: + def _reduce_local(local_g: jax.Array) -> jax.Array: + return lax.psum( + local_g.astype(allreduce_dtype), axis_name=batch_axis + ).astype(table_dtype) + + g_reduced = jax.shard_map( + _reduce_local, + mesh=mesh, + in_specs=jax.P(batch_axis), + out_specs=jax.P(), + check_vma=False, + )(g_copies) + else: + g_reduced = g_copies.reshape((num_copies, *table_shape)).sum(axis=0) + return (g_reduced,) + + +_tile_with_collective_dtype.defvjp( + _tile_with_collective_dtype_fwd, _tile_with_collective_dtype_bwd +) + + +# Shared per-device copies of replicated tables. Maps id(table) to a weak +# reference to the table, the table's value in the trace that read it last, and +# the copies of that value. See `_shared_table_copies`. +_shared_table_copies_cache: dict[ + int, tuple[weakref.ref[keras.Variable], jax.Array, jax.Array] +] = {} + + +def _shared_table_copies( + table: keras.Variable, + table_value: jax.Array, + num_copies: int, + mesh: jax.sharding.Mesh | jax.sharding.AbstractMesh | None = None, + batch_axis: AxisSpec = None, + allreduce_dtype: Any = None, +) -> jax.Array: + """Returns `num_copies` copies of `table_value` stacked on dim 0. + + Every call on `table` with the same traced `table_value` gets the same + copies. JAX then adds up the table gradients of all those calls on each + device before it reaches the transpose of the tile, which sums the copies + across devices once. + + The copies are a tracer, so all calls on a table must run at the same trace + level. If the first call runs inside a nested transformation such as + `jax.checkpoint` and a later one outside it, JAX raises an escaped-tracer + error. + + Args: + table: The table variable. + table_value: The table's value in the current trace. + num_copies: The number of devices that share the table. + mesh: Active mesh for custom-dtype collective reduction. + batch_axis: Batch mesh axis or axes for custom-dtype collective reduction. + allreduce_dtype: Optional collective dtype (e.g. `jnp.bfloat16`) used only + for the cross-device all-reduce after local accumulation completes. + + Returns: + An array of shape `(num_copies * table.shape[0], *table.shape[1:])`. + """ + key = id(table) + cached = _shared_table_copies_cache.get(key) + if cached is not None and cached[0]() is table and cached[1] is table_value: + return cached[2] + if allreduce_dtype is not None and mesh is not None and batch_axis is not None: + copies = _tile_with_collective_dtype( + table_value, num_copies, mesh, batch_axis, allreduce_dtype + ) + else: + copies = jnp.tile(table_value, (num_copies,) + (1,) * (table_value.ndim - 1)) + _shared_table_copies_cache[key] = ( + # Drops the entry, and the tracers in it, when the table goes away. + weakref.ref(table, lambda _: _shared_table_copies_cache.pop(key, None)), + table_value, + copies, + ) + return copies + + +def fused_table_grad_call( + fn: Callable[..., Any], + table: keras.Variable, + *batch_args: Any, +) -> Any: + """Calls `fn(table, *batch_args)` on each device and fuses table gradients. + + The table must be replicated. Each device gets its own copy, and all calls on + the table in the same trace share that copy. So each device adds up the table + gradients of all calls, and one all-reduce per table sums them across + devices. All calls on a table must run at the same trace level (see + `_shared_table_copies`). + + Under a Keras autocast scope, `fn` gets the table in the scope's dtype, but + the gradient is still all-reduced in the variable dtype. + + Args: + fn: A function of the full table and the local batch shards. Each output row + must depend only on the same row of the batch args. + table: A replicated table variable. + *batch_args: Arrays whose dim 0 is the global batch. + + Returns: + The output of `fn`, sharded on dim 0 over the batch axes. + + Raises: + ValueError: If no Keras distribution is active or the batch axis cannot be + determined. + NotImplementedError: If the active distribution shards the table. + """ + distribution = keras.distribution.distribution() + if distribution is None: + raise ValueError( + 'fused_table_grad_call requires an active Keras distribution.' + ) + # TODO(jinchi): Support sharded (FSDP) tables. + if any(distribution.get_variable_layout(table).axes): + raise NotImplementedError( + 'fused_table_grad_call supports only replicated tables.' + ) + abstract_mesh = get_abstract_mesh() + batch_axis = resolve_batch_axis(abstract_mesh) + if batch_axis is None: + raise ValueError( + 'Could not determine batch axis for fused_table_grad_call.' + ) + + # Read the table in its variable dtype and cast inside `fn`, so the gradient + # is all-reduced in that dtype rather than in bf16. + autocast_scope = keras_variables.get_autocast_scope() + with keras_variables.AutocastScope(None): + table_value = keras.ops.convert_to_tensor(table) + + if abstract_mesh is not None and isinstance(table_value, jax.core.Tracer): + mesh = abstract_mesh + batch_axes = batch_axis if isinstance(batch_axis, tuple) else (batch_axis,) + axis_sizes = dict( + zip(abstract_mesh.axis_names, abstract_mesh.axis_sizes, strict=True) + ) + allreduce_dtype = ( + jnp.bfloat16 if bf16_table_allreduce_enabled() else None + ) + table_value = _shared_table_copies( + table, + table_value, + math.prod(axis_sizes[axis] for axis in batch_axes), + mesh=mesh, + batch_axis=batch_axis, + allreduce_dtype=allreduce_dtype, + ) + table_spec = jax.P(batch_axis) + else: + # Eager `shard_map` on an `AbstractMesh` rejects inputs without a + # `NamedSharding`, so eager calls use the concrete mesh and one table. + mesh = distribution.device_mesh.backend_mesh + table_spec = jax.P() + + def local_fn(full_table, *local_batch_args): + if autocast_scope is not None: + full_table = autocast_scope.maybe_cast(full_table) + return fn(full_table, *local_batch_args) + + # The transpose of the tile sums the copies' gradients across devices. + return jax.shard_map( + local_fn, + mesh=mesh, + in_specs=(table_spec,) + (jax.P(batch_axis),) * len(batch_args), + out_specs=jax.P(batch_axis), + # NOMUTANTS -- Pallas kernels inside fn (e.g. CutBCE) lack VMA rules. + check_vma=False, + )(table_value, *batch_args) diff --git a/recml/core/utils/distribution_utils_test.py b/recml/core/utils/distribution_utils_test.py index ce622a5..417fb4b 100644 --- a/recml/core/utils/distribution_utils_test.py +++ b/recml/core/utils/distribution_utils_test.py @@ -13,20 +13,27 @@ # limitations under the License. """Tests mesh and batch-axis resolution in distribution_utils.""" +import re + from absl.testing import absltest from absl.testing import parameterized import jax +import jax.numpy as jnp import keras -from keras.src.distribution import distribution_lib +import numpy as np from recml.core.utils import distribution_utils -_DEVICES = [f'cpu:{i}' for i in range(8)] +# Virtual CPU devices for the test meshes. Must be even for the 2D meshes. +_NUM_DEVICES = 8 +# Must run before JAX starts. +jax.config.update('jax_num_cpu_devices', _NUM_DEVICES) +_DEVICES = [f'cpu:{i}' for i in range(_NUM_DEVICES)] class _StubDistribution: """Minimal stand-in for a Keras distribution. - Real hybrid-FSDP distributions live outside this package, so the two + Real hybrid-FSDP distributions live outside this package, so the methods and attributes `distribution_utils` reads are stubbed here instead. """ @@ -34,6 +41,11 @@ def __init__(self, device_mesh, batch_dim_name): self.device_mesh = device_mesh self.batch_dim_name = batch_dim_name + def get_variable_layout(self, variable): + return keras.distribution.TensorLayout( + (None,) * len(variable.shape), self.device_mesh + ) + def _abstract_mesh( axis_names: tuple[str, ...], axis_sizes: tuple[int, ...] @@ -45,6 +57,16 @@ def _abstract_mesh( ) +def _all_reduced_elements(hlo_text: str, shape: str) -> int: + """Counts all-reduced arrays of `shape` (e.g. 'f32[24,8]') in HLO text.""" + count = 0 + for line in hlo_text.splitlines(): + match = re.search(r'=\s*(.*?)\s+all-reduce(?:-start)?\(', line) + if match: + count += match.group(1).count(shape) + return count + + class DistributionUtilsTest(parameterized.TestCase): def setUp(self): @@ -82,8 +104,8 @@ def test_resolve_batch_axis_without_mesh_or_distribution(self): self.assertIsNone(distribution_utils.resolve_batch_axis(None)) def test_resolve_batch_axis_prefers_distribution_over_mesh(self): - device_mesh = distribution_lib.DeviceMesh( - (2, 4), ('replica', 'fsdp'), _DEVICES + device_mesh = keras.distribution.DeviceMesh( + (2, _NUM_DEVICES // 2), ('replica', 'fsdp'), _DEVICES ) keras.distribution.set_distribution( _StubDistribution(device_mesh, ('replica', 'fsdp')) @@ -95,7 +117,9 @@ def test_resolve_batch_axis_prefers_distribution_over_mesh(self): ) def test_resolve_batch_axis_from_data_parallel_distribution(self): - device_mesh = distribution_lib.DeviceMesh((8,), ('batch',), _DEVICES) + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) keras.distribution.set_distribution( keras.distribution.DataParallel(device_mesh=device_mesh) ) @@ -115,8 +139,8 @@ def test_get_abstract_mesh_from_global_jax_mesh(self): self.assertEqual(abstract_mesh.axis_names, ('data',)) def test_get_abstract_mesh_from_distribution(self): - device_mesh = distribution_lib.DeviceMesh( - (2, 4), ('replica', 'fsdp'), _DEVICES + device_mesh = keras.distribution.DeviceMesh( + (2, _NUM_DEVICES // 2), ('replica', 'fsdp'), _DEVICES ) keras.distribution.set_distribution(_StubDistribution(device_mesh, None)) @@ -124,7 +148,7 @@ def test_get_abstract_mesh_from_distribution(self): self.assertIsNotNone(mesh) self.assertEqual(mesh.axis_names, ('replica', 'fsdp')) - self.assertEqual(mesh.axis_sizes, (2, 4)) + self.assertEqual(mesh.axis_sizes, (2, _NUM_DEVICES // 2)) # Regression: `axis_types` must have one entry per axis. Passing a bare # `AxisType` raises `ValueError` on a mesh with more than one axis. self.assertEqual( @@ -133,5 +157,379 @@ def test_get_abstract_mesh_from_distribution(self): ) +# TODO(jinchi): Add sharded-table (FSDP) tests once fused table gradients +# support FSDP. +class FusedTableGradTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + keras.distribution.set_distribution(None) + self.addCleanup(keras.distribution.set_distribution, None) + + def test_fuse_table_grads_disabled_without_distribution(self): + self.assertFalse(distribution_utils.fuse_table_grads_enabled()) + + def test_fused_table_grad_data_parallel_opts_in(self): + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + self.assertTrue(distribution_utils.fuse_table_grads_enabled()) + + def test_fused_table_grad_call_under_data_parallel(self): + """Several reads of one replicated table, as in GUM.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + vocab, dim, batch, tokens = 16, 8, _NUM_DEVICES, 3 + rng = np.random.default_rng(0) + table = keras.Variable( + rng.normal(size=(vocab, dim)).astype(np.float32), name='table' + ) + ids = [ + rng.integers(0, vocab, size=(batch, tokens), dtype=np.int32) + for _ in range(3) + ] + h = rng.normal(size=(batch, dim)).astype(np.float32) + out_weights = rng.normal(size=(batch, 3 * dim + vocab)).astype(np.float32) + + def lookup(full_table, ids): + return jnp.take(full_table, ids, axis=0).sum(axis=1) + + def tied_logits(full_table, h): + return h @ full_table.T + + def loss_fn(table_value, h, fuse_grads): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + outs = [] + for token_ids in ids: + if fuse_grads: + outs.append( + distribution_utils.fused_table_grad_call( + lookup, table, token_ids + ) + ) + else: + outs.append(lookup(keras.ops.convert_to_tensor(table), token_ids)) + if fuse_grads: + outs.append( + distribution_utils.fused_table_grad_call(tied_logits, table, h) + ) + else: + outs.append(tied_logits(keras.ops.convert_to_tensor(table), h)) + return jnp.sum(jnp.concatenate(outs, axis=-1) * out_weights) + + grad_fn = jax.jit( + jax.value_and_grad(loss_fn, argnums=(0, 1)), static_argnums=2 + ) + expected_loss, expected_grads = grad_fn(table.value, h, False) + loss, grads = grad_fn(table.value, h, True) + + np.testing.assert_allclose(loss, expected_loss, rtol=1e-5) + for grad, expected_grad in zip(grads, expected_grads, strict=True): + np.testing.assert_allclose(grad, expected_grad, rtol=1e-5, atol=1e-5) + + def test_fused_table_grad_call_reduces_replicated_table_once(self): + """All reads of a replicated table share one gradient all-reduce.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + vocab, dim, batch, tokens = 24, 8, _NUM_DEVICES, 3 + rng = np.random.default_rng(0) + table = keras.Variable( + rng.normal(size=(vocab, dim)).astype(np.float32), name='table' + ) + ids = [ + rng.integers(0, vocab, size=(batch, tokens), dtype=np.int32) + for _ in range(3) + ] + h = rng.normal(size=(batch, dim)).astype(np.float32) + + def lookup(full_table, ids): + return jnp.take(full_table, ids, axis=0).sum(axis=1) + + def tied_logits(full_table, h): + return h @ full_table.T + + def loss_fn(table_value, h): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + outs = [ + distribution_utils.fused_table_grad_call(lookup, table, token_ids) + for token_ids in ids + ] + outs.append( + distribution_utils.fused_table_grad_call(tied_logits, table, h) + ) + return sum(jnp.sum(out) for out in outs) + + hlo = ( + jax.jit(jax.grad(loss_fn, argnums=(0, 1))) + .lower(table.value, h) + .compile() + .as_text() + ) + + # 4 calls read the table, but its gradient is all-reduced once. + self.assertEqual(_all_reduced_elements(hlo, f'f32[{vocab},{dim}]'), 1) + + def test_fused_table_grad_call_in_separate_traces(self): + """Each trace makes its own table copies.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + vocab, dim, batch = 16, 8, _NUM_DEVICES + rng = np.random.default_rng(0) + table = keras.Variable( + rng.normal(size=(vocab, dim)).astype(np.float32), name='table' + ) + h = rng.normal(size=(batch, dim)).astype(np.float32) + + def tied_logits(full_table, h): + return h @ full_table.T + + def loss_fn(table_value, h): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + logits = distribution_utils.fused_table_grad_call(tied_logits, table, h) + return jnp.sum(jnp.square(logits)) + + # Reusing the first trace's copies would raise an escaped-tracer error. + loss = jax.jit(loss_fn)(table.value, h) + table_grad, _ = jax.jit(jax.grad(loss_fn, argnums=(0, 1)))(table.value, h) + + logits = h @ np.asarray(table.value).T + np.testing.assert_allclose(loss, np.sum(np.square(logits)), rtol=1e-5) + np.testing.assert_allclose( + table_grad, 2 * logits.T @ h, rtol=1e-4, atol=1e-4 + ) + + @parameterized.named_parameters(('off', False), ('on', True)) + def test_fuse_table_grads_reads_distribution(self, value): + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + distribution = keras.distribution.DataParallel(device_mesh=device_mesh) + distribution.fuse_table_grads = value + keras.distribution.set_distribution(distribution) + self.assertEqual(distribution_utils.fuse_table_grads_enabled(), value) + + def test_fused_table_grad_call_raises_without_distribution(self): + table = keras.Variable(np.ones((4, 2), dtype=np.float32), name='table') + inputs = jnp.ones((_NUM_DEVICES, 2), dtype=jnp.float32) + with self.assertRaisesRegex(ValueError, 'active Keras distribution'): + distribution_utils.fused_table_grad_call( + lambda full_table, local_inputs: local_inputs @ full_table.T, + table, + inputs, + ) + + def test_fused_table_grad_call_raises_without_batch_axis(self): + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution(_StubDistribution(device_mesh, ())) + table = keras.Variable(np.ones((4, 2), dtype=np.float32), name='table') + inputs = jnp.ones((_NUM_DEVICES, 2), dtype=jnp.float32) + with self.assertRaisesRegex(ValueError, 'Could not determine batch axis'): + distribution_utils.fused_table_grad_call( + lambda full_table, local_inputs: local_inputs @ full_table.T, + table, + inputs, + ) + + def test_fused_table_grad_call_eager_and_mixed_precision(self): + """Covers eager calls and bf16 autocast with fp32 table gradients.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + vocab, dim = 8, 4 + rng = np.random.default_rng(1) + table = keras.Variable( + rng.normal(size=(vocab, dim)).astype(np.float32), name='table' + ) + batch_sharding = jax.sharding.NamedSharding( + device_mesh.backend_mesh, jax.P('batch') + ) + inputs = jax.device_put( + rng.normal(size=(_NUM_DEVICES, dim)).astype(np.float32), + batch_sharding, + ) + + eager_logits = distribution_utils.fused_table_grad_call( + lambda full_table, local_inputs: local_inputs @ full_table.T, + table, + inputs, + ) + np.testing.assert_allclose( + eager_logits, + np.asarray(inputs) @ np.asarray(table.value).T, + rtol=1e-5, + ) + + seen_dtypes = [] + + class _MixedPrecisionLayer(keras.Layer): + + def call(self, batch_inputs): + def proj(full_table, local_inputs): + seen_dtypes.append(full_table.dtype) + return local_inputs.astype(full_table.dtype) @ full_table.T + + return distribution_utils.fused_table_grad_call( + proj, table, batch_inputs + ) + + layer = _MixedPrecisionLayer(dtype='mixed_bfloat16') + + def loss_fn(table_value, batch_inputs): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + logits = layer(batch_inputs) + return jnp.sum(logits.astype(jnp.float32)) + + table_grad = jax.jit(jax.grad(loss_fn))(table.value, inputs) + self.assertEqual(seen_dtypes, [jnp.bfloat16]) + self.assertEqual(table_grad.dtype, jnp.float32) + + def test_bf16_table_allreduce_flag(self): + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel(device_mesh=device_mesh) + ) + self.assertFalse(distribution_utils.bf16_table_allreduce_enabled()) + + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel( + device_mesh=device_mesh, bf16_table_allreduce=True + ) + ) + self.assertTrue(distribution_utils.bf16_table_allreduce_enabled()) + + def test_fused_table_grad_call_bf16_allreduce_hlo(self): + """bf16_table_allreduce emits one bf16 all-reduce and returns fp32 grad.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel( + device_mesh=device_mesh, bf16_table_allreduce=True + ) + ) + vocab, dim, batch, tokens = 24, 8, _NUM_DEVICES, 3 + rng = np.random.default_rng(0) + table = keras.Variable( + rng.normal(size=(vocab, dim)).astype(np.float32), name='table' + ) + ids = [ + rng.integers(0, vocab, size=(batch, tokens), dtype=np.int32) + for _ in range(3) + ] + h = rng.normal(size=(batch, dim)).astype(np.float32) + + def lookup(full_table, ids): + return jnp.take(full_table, ids, axis=0).sum(axis=1) + + def tied_logits(full_table, h): + return h @ full_table.T + + def loss_fn(table_value, h): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + outs = [ + distribution_utils.fused_table_grad_call(lookup, table, token_ids) + for token_ids in ids + ] + outs.append( + distribution_utils.fused_table_grad_call(tied_logits, table, h) + ) + return sum(jnp.sum(out) for out in outs) + + grad_fn = jax.jit(jax.grad(loss_fn, argnums=(0, 1))) + # Check StableHLO (works on both CPU and TPU backends; XLA:CPU upcasts bf16 + # all-reduce during CPU codegen while XLA:TPU keeps it in bf16). + stablehlo = grad_fn.lower(table.value, h).as_text() + self.assertIn(f'tensor<{vocab}x{dim}xbf16>', stablehlo) + self.assertIn('stablehlo.all_reduce', stablehlo) + self.assertRegex( + stablehlo, + rf'(?s)stablehlo\.all_reduce.*?:\s*\(tensor<{vocab}x{dim}xbf16>\)', + ) + + table_grad, _ = grad_fn(table.value, h) + self.assertEqual(table_grad.dtype, jnp.float32) + + def test_fused_table_grad_call_bf16_allreduce_8192_repeat_parity(self): + """Local 8192-repeat accumulation stays in fp32 before bf16 all-reduce.""" + device_mesh = keras.distribution.DeviceMesh( + (_NUM_DEVICES,), ('batch',), _DEVICES + ) + vocab, dim = 64, 8 + repeats_per_dev = 8192 + batch = _NUM_DEVICES * repeats_per_dev + rng = np.random.default_rng(42) + table_init = rng.normal(size=(vocab, dim)).astype(np.float32) * 0.05 + idx_np = rng.integers(0, vocab, size=(batch,), dtype=np.int32) + idx_np[::2] = 0 + coeff_np = np.full((batch, dim), 1e-4, dtype=np.float32) + + def run_with_bf16(bf16_allreduce: bool) -> jax.Array: + keras.distribution.set_distribution( + distribution_utils.FusedTableGradDataParallel( + device_mesh=device_mesh, + bf16_table_allreduce=bf16_allreduce, + ) + ) + table = keras.Variable(table_init, name='table') + batch_sharding = jax.sharding.NamedSharding( + device_mesh.backend_mesh, jax.P('batch') + ) + idx = jax.device_put(idx_np, batch_sharding) + coeff = jax.device_put(coeff_np, batch_sharding) + + def loss_fn(table_value, i_in, c_in): + with keras.StatelessScope(state_mapping=[(table, table_value)]): + y1 = distribution_utils.fused_table_grad_call( + lambda t, i, c: jnp.sum(t[i] * c, axis=-1), table, i_in, c_in + ) + y2 = distribution_utils.fused_table_grad_call( + lambda t, i, c: jnp.sum(t[i] * c, axis=-1), table, i_in, c_in + ) + return jnp.sum(y1) + jnp.sum(y2) + + return jax.jit(jax.grad(loss_fn))(table.value, idx, coeff) + + g_f32 = run_with_bf16(False) + g_bf16 = run_with_bf16(True) + + self.assertEqual(g_bf16.dtype, jnp.float32) + self.assertTrue(bool(jnp.all(jnp.isfinite(g_bf16)))) + hot_rel_err = float( + np.max( + np.abs(np.asarray(g_bf16)[0] - np.asarray(g_f32)[0]) + / np.maximum(np.abs(np.asarray(g_f32)[0]), 1e-6) + ) + ) + self.assertLess(hot_rel_err, 0.02) + np.testing.assert_allclose(g_bf16, g_f32, rtol=2e-2, atol=1e-4) + + # Exact bit-for-bit replica agreement across all devices. + shards = [np.asarray(s.data) for s in g_bf16.addressable_shards] + for dev_i in range(1, len(shards)): + np.testing.assert_array_equal(shards[0], shards[dev_i]) + + if __name__ == '__main__': absltest.main()