Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions recml/core/ops/binary_cross_entropy_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,19 +158,47 @@ 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):
return None
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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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()
)
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
182 changes: 182 additions & 0 deletions recml/core/ops/binary_cross_entropy_ops_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()
26 changes: 20 additions & 6 deletions recml/core/ops/binary_focal_cross_entropy_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,19 @@
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
)
_effective_block_v = (
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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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()
)
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
Loading
Loading