Skip to content

Commit a78fb81

Browse files
Merge pull request AI-Hypercomputer#4179 from ROCm:fix-moe-expert-parallel-sharding
PiperOrigin-RevId: 936344159
2 parents 6bc5f8a + ea41360 commit a78fb81

5 files changed

Lines changed: 146 additions & 13 deletions

File tree

src/maxtext/configs/base.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ load_balance_loss_weight: 0.0 # weight for the load balance loss
218218
use_random_routing: false # whether to use random routing for debug/test purpose
219219
use_custom_sort_vjp: true # whether to use a custom VJP sort for efficient backward pass processing in sparse matmul
220220
use_ring_of_experts: false # whether to use ring of experts for sparse matmul expert parallelism
221+
# If true, peel the 'expert' mesh axis off the MoE dispatch/MLP batch dim so the expert GEMM
222+
# stays expert-parallel (AllToAll); false keeps 'expert' on the batch dim (activation_batch_moe).
223+
# Only affects the dense (dense_matmul) MoE path; the sparse (shard_map) path is unaffected.
224+
moe_dispatch_no_expert_sharding: false
221225
use_ragged_sort: false # whether to use the Pallas ragged-sort kernels in the MoE permute path; valid both with and
222226
# without `use_ring_of_experts` (with EP > 1). When `use_ring_of_experts=True` the kernels run
223227
# inside `permute`/`unpermute`; otherwise they run inside `local_permute`/local-unpermute.

src/maxtext/configs/types.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -743,6 +743,13 @@ class MoEGeneral(BaseModel):
743743
False,
744744
description="Whether to use Ring of Experts for sparse matmul expert parallelism.",
745745
)
746+
moe_dispatch_no_expert_sharding: bool = Field(
747+
False,
748+
description=(
749+
"If true, shard the MoE dispatch/MLP batch dim without 'expert' so the expert GEMM "
750+
"stays expert-parallel (AllToAll); false keeps 'expert' on it (activation_batch_moe)."
751+
),
752+
)
746753
use_ragged_sort: bool = Field(
747754
False, description="Whether to use ragged kernel for sorting, improve performance when EP is enabled."
748755
)

src/maxtext/layers/moe.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
from maxtext.utils import max_utils
4444
from maxtext.utils import maxtext_utils
4545
from maxtext.utils.sharding import create_sharding, maybe_shard_with_logical, maybe_shard_with_pspec
46-
from maxtext.utils.sharding import logical_to_mesh_axes
46+
from maxtext.utils.sharding import logical_to_mesh_axes, remove_expert_from_partition_spec
4747
import numpy as np
4848
import qwix
4949
from qwix.contrib.sparsity import sparsity_module
@@ -631,6 +631,18 @@ def _maybe_shard_with_pspec(self, inputs, pspec: jax.sharding.PartitionSpec | No
631631
extra_stack_level=1,
632632
)
633633

634+
def _maybe_shard_moe_dispatch(self, inputs, logical_axis, peel_expert):
635+
"""Shard a MoE dispatch/MLP activation. When `peel_expert` is set, drop the 'expert'
636+
mesh axis from the batch dim (index 1) so the GEMM stays expert-parallel (AllToAll)
637+
instead of double-mapping E and B onto 'expert'. Each logical dim is resolved
638+
independently so the shared 'expert' axis is not deduped off the expert dim before
639+
the peel."""
640+
if not peel_expert:
641+
return self._maybe_shard_with_logical(inputs, logical_axis)
642+
spec = [None if name is None else self._logical_to_mesh_axes((name,))[0] for name in logical_axis]
643+
pspec = remove_expert_from_partition_spec(jax.sharding.PartitionSpec(*spec), dims_to_peel=(1,))
644+
return self._maybe_shard_with_pspec(inputs, pspec)
645+
634646
def get_expert_parallelism_size(self):
635647
# When expert parallelism has more than one physical axes, take product of their shapes
636648
if isinstance(self._expert_parallelism_name, tuple):
@@ -2203,12 +2215,18 @@ def dense_matmul(
22032215

22042216
if self.config.capacity_factor > 0:
22052217
# token dropping if needed
2218+
moe_peel_expert = False # only the training dispatch/MLP path peels 'expert' from the batch dim
22062219
if self.config.model_call_mode != "inference":
22072220
# TODO(b/425930949): remove this pylint by refactoring the logic here.
22082221
dispatch_mask, combine_mask = self.generate_masks(
22092222
top_k_indices, weights # pylint: disable=undefined-variable,possibly-used-before-assignment
22102223
)
22112224
mask_axes = ("activation_batch_moe", "activation_norm_length_moe", None, None)
2225+
# Dispatch/MLP are already expert-sharded via "activation_exp". With
2226+
# moe_dispatch_no_expert_sharding we peel 'expert' off the batch dim of these specs
2227+
# (see _maybe_shard_moe_dispatch) so the GEMM stays expert-parallel (AllToAll) instead
2228+
# of double-mapping E and B onto 'expert' (FSDP-style fallback).
2229+
moe_peel_expert = self.config.moe_dispatch_no_expert_sharding
22122230
dispatch_axis = (
22132231
"activation_exp",
22142232
"activation_batch_moe",
@@ -2313,10 +2331,7 @@ def dense_matmul(
23132331
"activation_embed_moe",
23142332
),
23152333
)
2316-
dispatch = self._maybe_shard_with_logical(
2317-
dispatch,
2318-
dispatch_axis,
2319-
)
2334+
dispatch = self._maybe_shard_moe_dispatch(dispatch, dispatch_axis, moe_peel_expert)
23202335
with jax.named_scope("wi_0"):
23212336
w0_kernel_axes = ("exp", None, "mlp")
23222337
w0_kernel = self.maybe_all_gather_kernel_weight_in_expert_parallelism(w0_kernel, w0_kernel_axes)
@@ -2329,10 +2344,7 @@ def dense_matmul(
23292344

23302345
if self.config.activations_in_float32:
23312346
layer_w0 = layer_w0.astype(jnp.float32)
2332-
layer_w0 = self._maybe_shard_with_logical(
2333-
layer_w0,
2334-
mlp_axis,
2335-
)
2347+
layer_w0 = self._maybe_shard_moe_dispatch(layer_w0, mlp_axis, moe_peel_expert)
23362348
layer_w0 = adc.checkpoint_name(adc.checkpoint_name(layer_w0, "mlpwi_0"), "moe_mlpwi_0")
23372349
with jax.named_scope("wi_1"):
23382350
w1_kernel_axes = ("exp", None, "mlp")
@@ -2345,10 +2357,7 @@ def dense_matmul(
23452357
layer_w1 = layer_w1 + w1_bias
23462358
if self.config.activations_in_float32:
23472359
layer_w1 = layer_w1.astype(jnp.float32)
2348-
layer_w1 = self._maybe_shard_with_logical(
2349-
layer_w1,
2350-
mlp_axis,
2351-
)
2360+
layer_w1 = self._maybe_shard_moe_dispatch(layer_w1, mlp_axis, moe_peel_expert)
23522361
layer_w1 = adc.checkpoint_name(adc.checkpoint_name(layer_w1, "mlpwi_1"), "moe_mlpwi_1")
23532362
layer_multiply = self.apply_ffn_activation(layer_w0, layer_w1)
23542363
with jax.named_scope("wo"):

src/maxtext/utils/sharding.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,32 @@ def _remove_fsdp_from_partition_spec(named_sharding):
732732
return jax.tree.map(_remove_fsdp_from_partition_spec, sharding_tree)
733733

734734

735+
def remove_expert_from_partition_spec(pspec, dims_to_peel):
736+
"""Return `pspec` with the 'expert' mesh axis removed from the given dim indices.
737+
738+
Used by the MoE dispatch/MLP sharding: the expert dim is already sharded over the
739+
'expert' mesh axis via the `activation_exp` rule, so the batch dim must not also map
740+
to 'expert' (that double-maps two tensor dims onto one mesh axis and makes GSPMD fall
741+
back to FSDP-style AllGather+ReduceScatter instead of expert-parallel AllToAll). Only
742+
the dims listed in `dims_to_peel` (the batch dim) are modified; the expert dim is left
743+
untouched. Avoids needing a separate `activation_batch_no_exp` logical rule that every
744+
`custom_mesh_and_rule` set would have to redefine.
745+
"""
746+
new_spec = list(pspec)
747+
for i in dims_to_peel:
748+
axis = new_spec[i]
749+
if axis is None:
750+
continue
751+
if isinstance(axis, str):
752+
new_spec[i] = None if axis == "expert" else axis
753+
elif isinstance(axis, (list, tuple)):
754+
filtered = tuple(a for a in axis if a != "expert")
755+
new_spec[i] = filtered or None
756+
else:
757+
raise ValueError(f"Unsupported axis type: {type(axis)}")
758+
return jax.sharding.PartitionSpec(*new_spec)
759+
760+
735761
def get_physical_spec_no_fsdp(full_logical, mesh, logical_axis_rules):
736762
"""
737763
Generates a physical sharding spec for fully replicated weights.

tests/unit/moe_test.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from maxtext.layers.initializers import NdInitializer, nd_dense_init, variable_to_logically_partitioned
3131
from maxtext.layers.quantizations import Fp8Quantization
3232
from maxtext.utils import maxtext_utils
33+
from maxtext.utils.sharding import remove_expert_from_partition_spec
3334
from tests.utils.test_helpers import get_test_config_path
3435
import pytest
3536

@@ -1556,5 +1557,91 @@ def test_prefused_vs_sparse_softmax(self):
15561557
self.assertIsNone(bias_updates)
15571558

15581559

1560+
@pytest.mark.parametrize(
1561+
"model_name,flag",
1562+
[
1563+
("mixtral-8x7b", True), # flag on: expert stays on E, peeled off the batch dim
1564+
("mixtral-8x22b", True), # flag on
1565+
("mixtral-8x7b", False), # flag off (default): batch dim keeps 'expert'
1566+
],
1567+
)
1568+
def test_moe_dispatch_keeps_expert_on_expert_dim(model_name, flag):
1569+
"""Regression guard for the MoE dispatch/MLP expert-parallel sharding.
1570+
1571+
The expert (E) dim is always sharded by the 'expert' mesh axis (via activation_exp).
1572+
With moe_dispatch_no_expert_sharding the batch (B) dim must NOT also take 'expert'
1573+
(which would double-map two tensor dims onto one mesh axis and force an FSDP-style
1574+
fallback instead of expert-parallel AllToAll); with the flag off, the default keeps
1575+
'expert' on the batch dim. Mirrors dense_matmul's axis selection.
1576+
"""
1577+
cfg = pyconfig.initialize(
1578+
[None, get_test_config_path()],
1579+
run_name=f"moe_shard_{model_name}_{flag}",
1580+
enable_checkpointing=False,
1581+
model_name=model_name,
1582+
moe_dispatch_no_expert_sharding=flag,
1583+
)
1584+
rules = cfg.logical_axis_rules
1585+
1586+
def _as_set(entry):
1587+
if entry is None:
1588+
return set()
1589+
return {entry} if isinstance(entry, str) else set(entry)
1590+
1591+
# Mirror _maybe_shard_moe_dispatch: resolve E and batch dims independently (so the shared
1592+
# 'expert' axis isn't deduped off E), then peel 'expert' from the batch dim when the flag is set.
1593+
e_spec = nn_partitioning.logical_to_mesh_axes(("activation_exp",), rules=rules)
1594+
b_spec = nn_partitioning.logical_to_mesh_axes(("activation_batch_moe",), rules=rules)
1595+
if cfg.moe_dispatch_no_expert_sharding:
1596+
b_spec = remove_expert_from_partition_spec(b_spec, dims_to_peel=(0,))
1597+
1598+
e_axes, b_axes = _as_set(e_spec[0]), _as_set(b_spec[0])
1599+
assert "expert" in e_axes, "expert dim must be sharded by the 'expert' mesh axis"
1600+
if cfg.moe_dispatch_no_expert_sharding:
1601+
assert "expert" not in b_axes, "flag on: the batch dim must not take 'expert'"
1602+
else:
1603+
assert "expert" in b_axes, "flag off (default): the batch dim keeps 'expert' (activation_batch_moe)"
1604+
1605+
1606+
def test_remove_expert_from_partition_spec():
1607+
"""remove_expert_from_partition_spec peels 'expert' only from the requested dims."""
1608+
spec = jax.sharding.PartitionSpec
1609+
assert remove_expert_from_partition_spec(spec("expert", ("data", "fsdp", "expert"), None), dims_to_peel=(1,)) == spec(
1610+
"expert", ("data", "fsdp"), None
1611+
)
1612+
assert remove_expert_from_partition_spec(spec("expert", "expert", None), dims_to_peel=(1,)) == spec(
1613+
"expert", None, None
1614+
)
1615+
assert remove_expert_from_partition_spec(spec(("expert",), None), dims_to_peel=(0, 1)) == spec(None, None)
1616+
1617+
1618+
def test_moe_dispatch_no_expert_sharding_dense_forward():
1619+
"""The moe_dispatch_no_expert_sharding peel path runs in dense_matmul (capacity_factor>0)."""
1620+
cfg = pyconfig.initialize(
1621+
[None, get_test_config_path()],
1622+
run_name="moe_dense_no_exp_fwd",
1623+
enable_checkpointing=False,
1624+
model_name="mixtral-8x7b",
1625+
dtype="bfloat16",
1626+
megablox=False,
1627+
sparse_matmul=False,
1628+
capacity_factor=1.0,
1629+
moe_dispatch_no_expert_sharding=True,
1630+
per_device_batch_size=1,
1631+
max_target_length=16,
1632+
)
1633+
devices = maxtext_utils.create_device_mesh(cfg)
1634+
mesh = Mesh(devices, cfg.mesh_axes)
1635+
model = make_moe(cfg, mesh)
1636+
inputs = jax.random.normal(
1637+
jax.random.PRNGKey(0),
1638+
(int(cfg.per_device_batch_size) * jax.device_count(), cfg.max_target_length, cfg.base_emb_dim),
1639+
dtype=jnp.bfloat16,
1640+
)
1641+
with mesh:
1642+
out, _, _ = model(inputs)
1643+
assert out.shape == inputs.shape
1644+
1645+
15591646
if __name__ == "__main__":
15601647
unittest.main()

0 commit comments

Comments
 (0)