Skip to content

Commit c2b5a32

Browse files
authored
[JAX] Add MXFP8 token dispatch to the MoE block (#3818)
* [JAX] Add MXFP8 token dispatch to the MoE block Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com> --------- Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
1 parent 857df10 commit c2b5a32

12 files changed

Lines changed: 649 additions & 79 deletions

File tree

‎tests/jax/moe/test_moe_fsdp_layout.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,10 +305,12 @@ def forward(weight, quant_before_fsdp_ag):
305305
jnp.asarray([1]),
306306
weight,
307307
wo,
308+
None, # No dispatched MXFP8 scales
308309
None,
309310
None,
310311
None,
311312
(quantizers, quantizers),
313+
compute_dtype=x.dtype,
312314
num_local_experts=1,
313315
activation_type="silu",
314316
apply_topk_weights_early=False,

‎tests/jax/moe/test_moe_resource_api.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,11 @@ def bind(*args, **kwargs):
8383
monkeypatch.setattr(ep.EpPrepareAndDispatchPrimitive.outer_primitive, "bind", bind)
8484
cfg = SimpleNamespace(top_k=1, dispatch_output_per_expert_alignment=256, topk_idx_dtype=0)
8585
with global_shard_guard(MeshResource(dp_resource="dp", fsdp_resource="fsdp", ep_resource="ep")):
86-
inspect.unwrap(ep._ep_fused_prepare_and_dispatch_fwd)(cfg, None, None, None, 256)
86+
inspect.unwrap(ep._ep_fused_prepare_and_dispatch_fwd)(cfg, None, None, None, None, 256)
8787

8888
mesh = Mesh(np.asarray(jax.devices()[:1]).reshape(1, 1, 1), ("dp", "fsdp", "ep"))
8989
sharding = NamedSharding(mesh, P(("dp", "fsdp", "ep"), None, None))
90-
args = [SimpleNamespace(sharding=sharding)] * 3
90+
args = [SimpleNamespace(sharding=sharding)] * 4
9191
_, _, outputs, _ = ep.EpPrepareAndDispatchPrimitive.partition(
9292
captured["top_k"],
9393
captured["dispatch_output_per_expert_alignment"],

‎tests/jax/test_custom_call_compute.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,25 @@ def test_quantize_bitwise_jitted(
851851
)
852852

853853

854+
@pytest_parametrize_wrapper("in_dtype", [jnp.bfloat16, jnp.float32])
855+
@pytest_parametrize_wrapper("input_shape", [(2, 16, 512), (8, 16, 256)])
856+
def test_mxfp8_rowwise_quantize_short_sequence(in_dtype, input_shape):
857+
"""Rowwise-only MXFP8 quantize must not require the colwise axis to be a multiple of 32."""
858+
if not is_mxfp8_supported:
859+
pytest.skip(mxfp8_unsupported_reason)
860+
861+
key = jax.random.PRNGKey(0)
862+
x = jax.random.uniform(key, input_shape, in_dtype)
863+
quantizer = QuantizerFactory.create(
864+
scaling_mode=ScalingMode.MXFP8_1D_SCALING,
865+
q_dtype=jnp.float8_e4m3fn,
866+
q_layout=QuantizeLayout.ROWWISE,
867+
)
868+
out = tex.quantize(x, quantizer=quantizer)
869+
assert isinstance(out, ScaledTensor1x) and not out.is_colwise
870+
assert_dequantized_scaled_tensor(out, x)
871+
872+
854873
@pytest_parametrize_wrapper("in_dtype", [jnp.bfloat16])
855874
@pytest_parametrize_wrapper("q_dtype", [jnp.float4_e2m1fn])
856875
@pytest_parametrize_wrapper("input_shape,flatten_axis", ALL_QUANTIZE_TEST_SHAPES_AND_FLATTEN_AXES)
@@ -2469,6 +2488,7 @@ def reorder(tensor, *, interleave):
24692488
wi=jnp.ones((1, combined, 128) if native_layout else (1, 128, combined), jnp.bfloat16),
24702489
wo=jnp.ones((1, 128, 128), jnp.bfloat16),
24712490
quantizer_sets=(quantizers, quantizers),
2491+
compute_dtype=jnp.bfloat16,
24722492
num_local_experts=1,
24732493
use_cudnn_jax_fusion=True,
24742494
cudnn_native_weight_layout=native_layout,

‎tests/jax/test_te_ep_moe.py‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def _read_mp_options():
159159
DTYPE = jnp.bfloat16
160160
BATCH = EP_SIZE * FSDP_SIZE * 2 # 8 on 4-GPU, 16 on 8-GPU
161161
SEQ = 32
162-
HIDDEN = 128
162+
HIDDEN = 512 # multiple of 512 so MXFP8 dispatch scale rows are 16-byte aligned
163163
INTER = 128
164164
NUM_EXPERTS = 8
165165
TOPK = 2
@@ -168,7 +168,7 @@ def _read_mp_options():
168168
# These bounds are rounded slightly above the worst error observed across
169169
# the forward and backward configuration matrix.
170170
FWD_TOLERANCE = {
171-
"bf16": {"atol": 5e-4, "rtol": 5e-4},
171+
"bf16": {"atol": 1e-3, "rtol": 1e-3},
172172
"mxfp8": {"atol": 7e-3, "rtol": 7e-3},
173173
}
174174
GRAD_FFN_TOLERANCE = {
@@ -177,7 +177,7 @@ def _read_mp_options():
177177
}
178178
GRAD_GATE_TOLERANCE = {
179179
"bf16": {"atol": 7e-8, "rtol": 7e-8},
180-
"mxfp8": {"atol": 8e-7, "rtol": 8e-7},
180+
"mxfp8": {"atol": 1e-6, "rtol": 1e-6},
181181
}
182182

183183
# Aux loss is computed in float32 from the SAME logits as the routing
@@ -401,6 +401,7 @@ def _make_block(
401401
dispatch_checkpoint_name=None,
402402
quant_before_fsdp_ag=False,
403403
mesh_resource=None,
404+
dispatch_quantization_recipe=None,
404405
use_cudnn_fusion,
405406
):
406407
kwargs = dict(
@@ -419,6 +420,7 @@ def _make_block(
419420
dispatch_checkpoint_name=dispatch_checkpoint_name,
420421
quant_before_fsdp_ag=quant_before_fsdp_ag,
421422
use_cudnn_fusion=use_cudnn_fusion,
423+
dispatch_quantization_recipe=dispatch_quantization_recipe,
422424
)
423425
# Custom expert_bias_init lets tests inject a non-zero expert_bias without
424426
# poking variables['params'] post-init.
@@ -1043,6 +1045,42 @@ def test_routing_map_shape_validation(self):
10431045
)
10441046

10451047

1048+
@pytest.mark.skipif(get_device_compute_capability(0) < 100, reason="MXFP8 dispatch requires SM100+")
1049+
class TestTeEpMoeDispatchMxfp8:
1050+
"""MXFP8 dispatch matches the high-precision dispatch under the same MXFP8 recipe."""
1051+
1052+
@pytest.mark.parametrize("config", _CONFIGS)
1053+
def test_forward_and_backward(self, mesh, config, make_block):
1054+
recipe = MXFP8BlockScaling()
1055+
ref_block = make_block(**config, quantization_recipe=recipe)
1056+
block = make_block(
1057+
**config,
1058+
quantization_recipe=recipe,
1059+
dispatch_quantization_recipe=recipe,
1060+
)
1061+
x = _make_inputs(jax.random.PRNGKey(4))
1062+
variables, out_ref, _, _ = _init_apply(ref_block, mesh, x, jax.random.PRNGKey(5))
1063+
_, out, _, _ = _init_apply(block, mesh, x, jax.random.PRNGKey(5))
1064+
out_np = _to_global_numpy(out, mesh).astype(np.float32)
1065+
out_ref_np = _to_global_numpy(out_ref, mesh).astype(np.float32)
1066+
assert np.all(np.isfinite(out_np)), "output has NaN/Inf"
1067+
np.testing.assert_allclose(out_np, out_ref_np, **FWD_TOLERANCE["mxfp8"])
1068+
1069+
grads, grad_x = _grad_step(block, variables, mesh, x)
1070+
grads_ref, grad_x_ref = _grad_step(ref_block, variables, mesh, x)
1071+
for name in ("gate_kernel", "wi", "wo"):
1072+
g = _to_global_numpy(_unwrap(grads["params"][name]), mesh).astype(np.float32)
1073+
g_ref = _to_global_numpy(_unwrap(grads_ref["params"][name]), mesh).astype(np.float32)
1074+
assert np.all(np.isfinite(g)) and np.any(g != 0.0), f"{name} grad invalid"
1075+
rel = np.linalg.norm(g - g_ref) / np.linalg.norm(g_ref)
1076+
assert rel < 0.1, f"{name} grad relative L2 error {rel:.3%} >= 10%"
1077+
dx = _to_global_numpy(grad_x, mesh).astype(np.float32)
1078+
dx_ref = _to_global_numpy(grad_x_ref, mesh).astype(np.float32)
1079+
assert np.all(np.isfinite(dx)) and np.any(dx != 0.0), "d_x invalid"
1080+
rel = np.linalg.norm(dx - dx_ref) / np.linalg.norm(dx_ref)
1081+
assert rel < 0.1, f"d_x relative L2 error {rel:.3%} >= 10%"
1082+
1083+
10461084
class TestTeEpMoeBackward:
10471085
"""Per-config backward correctness in a single run: per-tensor
10481086
grads finite, non-zero AND parity vs the pure-JAX reference."""

0 commit comments

Comments
 (0)