Skip to content

Commit 023680c

Browse files
committed
[JAX] EP overlap: support TE checkpoint (remat) names
The overlap path no longer rejects TE checkpoint names. The forward tags the residuals of the fused dispatch+FC1 call (routing state, received tokens and their MXFP8 scales, received routing weights, per-expert counts, the FC1 output and, for BF16, the SwiGLU output) with checkpoint_name; the wo name tags nothing because the overlap backward does not read FC2's output. Under a names-based remat policy JAX rebuilds unsaved residuals by re-running only the fused dispatch+FC1 call; FC2+combine is never re-run (no separate recompute path). A re-run dispatch can place the received rows in a different order, so mixing saved and rebuilt residuals corrupts the gate and input gradients (measured: relative error ~1). Every fused-call residual therefore carries all given names (dispatch, wi_0, wi_1), nested, and is saved when the policy saves any of them: a mixed policy saves all of them, otherwise all are rebuilt. _MoEBlock gains wi_0/wi_1/wo_checkpoint_name (forwarded to moe()). Tests (tests/jax/test_te_ep_moe.py, 4x GB300, EP2xFSDP2, unfused mode): test_ep_remat_policy over BF16/MXFP8 x policies {wo saved (MaxText custom remat), nothing saved, dispatch+wo, wi+wo}: overlap loss and gradients match the un-rematerialized flag-off step; compiled HLO has 2x te_ep_dispatch_gemm_fwd_ffi when no fused-call name is saved (1x otherwise) and 1x each other overlap call. The flag-off path is checked only with everything rematerialized: with saved residuals and a re-run dispatch it shows the same row-order mismatch (pre-existing, not changed here). `-k "overlap or remat or checkpoint"`: 63 passed, 29 skipped. DeepSeek-V3 MaxText proxy (4x GB300, EP4, 1 dense + 4 MoE layers, FP8 dense + MXFP8 MoE, pdb 6 x seq 4096, GA 2, custom remat: dispatch and moe_mlpwi remat, moe_mlpwo saved): the compiled train step has te_ep_dispatch_gemm_fwd_ffi x16, te_ep_combine_gemm_fwd_ffi x8 and each backward call x8 (4 layers x 2 microbatches: dispatch+FC1 re-run once per layer, FC2+combine not re-run). With the overlap on (+ native layouts) vs off: step 0.991 vs 1.090 s (-9.0%), LHS estimate 98.2 vs 107.7 GiB, peak 159.5 vs 169.7 GiB, losses within 0.004 over 24 steps. Depends on upstream PR NVIDIA#3906. Signed-off-by: Deep Patel <deepatel@nvidia.com>
1 parent 6cce050 commit 023680c

3 files changed

Lines changed: 130 additions & 13 deletions

File tree

‎tests/jax/test_te_ep_moe.py‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,13 +430,17 @@ def _make_block(
430430
dispatch_quantization_recipe=None,
431431
enable_ep_overlap=False,
432432
intermediate_size=INTER,
433+
ffn_checkpoint_names=(None, None, None),
433434
use_cudnn_fusion,
434435
):
435436
kwargs = dict(
436437
num_experts=NUM_EXPERTS,
437438
num_experts_per_tok=TOPK,
438439
intermediate_size=intermediate_size,
439440
enable_ep_overlap=enable_ep_overlap,
441+
wi_0_checkpoint_name=ffn_checkpoint_names[0],
442+
wi_1_checkpoint_name=ffn_checkpoint_names[1],
443+
wo_checkpoint_name=ffn_checkpoint_names[2],
440444
mesh_resource=mesh_resource,
441445
apply_topk_weights_early=apply_topk_weights_early,
442446
aux_loss_coeff=aux_loss_coeff,
@@ -1279,7 +1283,6 @@ def recorded_checkpoint_name(value, name):
12791283
@pytest.mark.parametrize(
12801284
"block_kwargs, env, match",
12811285
[
1282-
pytest.param(dict(dispatch_checkpoint_name="moe_dispatch"), {}, "checkpoint", id="ckpt"),
12831286
pytest.param(dict(quantization="mxfp8", intermediate_size=INTER), {}, "of 256", id="ffn"),
12841287
pytest.param(dict(quant_before_fsdp_ag=True), {}, "MXFP8 recipe", id="qbfag_bf16"),
12851288
pytest.param({}, {"NCCL_EP_COMM_SMS": "8"}, "NCCL_EP_COMM_SMS", id="nccl_ep_sms"),
@@ -1303,6 +1306,87 @@ def test_ep_overlap_unmet_requirement_raises(
13031306
)
13041307

13051308

1309+
@pytest.mark.parametrize(
1310+
"saved",
1311+
[
1312+
("moe_mlpwo",),
1313+
(),
1314+
("moe_dispatch", "moe_mlpwo"),
1315+
("moe_mlpwi_0", "moe_mlpwi_1", "moe_mlpwo"),
1316+
],
1317+
ids=["wo", "none", "dispatch_wo", "wi_wo"],
1318+
)
1319+
@pytest.mark.parametrize("quantization", _QUANTIZATION_CASES)
1320+
def test_ep_remat_policy(mesh, make_block, use_cudnn_fusion, quantization, saved):
1321+
"""Names-based remat policies (``saved`` names are kept, the rest rematerialized; "wo" is
1322+
MaxText's custom remat: dispatch and FC1 remat, FC2 saved). With the overlap, the loss and
1323+
gradients match the un-rematerialized flag-off step, and the backward re-runs only the fused
1324+
dispatch+FC1 call when none of its names is saved (two in the step), never FC2+combine.
1325+
1326+
The flag-off path is checked only when every name is rematerialized: when some of its
1327+
residuals are saved and the dispatch is re-run, the re-run's received-row order can differ
1328+
from the saved residuals', which corrupts the gate and input gradients (known defect of the
1329+
regular path, measured relative error ~1)."""
1330+
_skip_unless_overlap_available(True, use_cudnn_fusion)
1331+
names = dict(
1332+
dispatch_checkpoint_name="moe_dispatch",
1333+
ffn_checkpoint_names=("moe_mlpwi_0", "moe_mlpwi_1", "moe_mlpwo"),
1334+
)
1335+
policy = jax.checkpoint_policies.save_only_these_names(*saved)
1336+
x = _make_inputs(jax.random.PRNGKey(42))
1337+
common = dict(
1338+
quantization_recipe=_quantization_recipe(quantization),
1339+
intermediate_size=OVERLAP_INTER,
1340+
**names,
1341+
)
1342+
variables, _, _, _ = _init_apply(make_block(**common), mesh, x, jax.random.PRNGKey(43))
1343+
results = {}
1344+
with _ctx(mesh):
1345+
x_sh = _shard_inputs(x, mesh)
1346+
for overlap in (False, True):
1347+
block = make_block(enable_ep_overlap=overlap, **common)
1348+
for remat in (False, True):
1349+
1350+
def loss_fn(v, x, block=block, remat=remat):
1351+
apply = lambda v, x: block.apply(v, x)[0]
1352+
if remat:
1353+
apply = jax.checkpoint(apply, policy=policy)
1354+
return jnp.mean(apply(v, x).astype(jnp.float32) ** 2)
1355+
1356+
step = jax.jit(jax.value_and_grad(loss_fn, argnums=(0, 1)))
1357+
hlo = step.lower(variables, x_sh).compile().as_text()
1358+
loss, (grads, grad_x) = step(variables, x_sh)
1359+
counts = {
1360+
t: len(re.findall(rf'custom_call_target="{t}"', hlo)) for t in OVERLAP_TARGETS
1361+
}
1362+
results[overlap, remat] = (loss, grads, grad_x, counts)
1363+
for remat in (False, True):
1364+
assert set(results[False, remat][3].values()) == {0}
1365+
on, on_remat = results[True, False][3], results[True, True][3]
1366+
assert on == dict.fromkeys(OVERLAP_TARGETS, 1), on
1367+
rerun = not {"moe_dispatch", "moe_mlpwi_0", "moe_mlpwi_1"} & set(saved)
1368+
assert on_remat == dict(on, te_ep_dispatch_gemm_fwd_ffi=1 + rerun), on_remat
1369+
if saved:
1370+
del results[False, True]
1371+
tol = OVERLAP_GRAD_TOLERANCE[quantization]
1372+
ref_loss, ref_grads, ref_grad_x, _ = results[False, False]
1373+
1374+
def tensors(grads, grad_x):
1375+
named = {k: _unwrap(grads["params"][k]) for k in ("gate_kernel", "wi", "wo")}
1376+
named["x"] = grad_x
1377+
return {k: _to_global_numpy(v, mesh).astype(np.float32) for k, v in named.items()}
1378+
1379+
ref = tensors(ref_grads, ref_grad_x)
1380+
failures = []
1381+
for (overlap, remat), (loss, grads, grad_x, _) in results.items():
1382+
np.testing.assert_allclose(float(loss), float(ref_loss), rtol=tol["rtol"])
1383+
for name, value in tensors(grads, grad_x).items():
1384+
if not np.allclose(value, ref[name], **tol):
1385+
rel = np.max(np.abs(value - ref[name])) / max(np.max(np.abs(ref[name])), 1e-30)
1386+
failures.append((overlap, remat, name, float(rel)))
1387+
assert not failures, failures
1388+
1389+
13061390
def test_ep_overlap_no_kernel_compile_at_execution(mesh, make_block, use_cudnn_fusion):
13071391
"""The CuTeDSL GEMMs compile while jit traces (nvte_ep_overlap_compile); executing the
13081392
compiled step, first and later, never re-enters the Python compile/register entry points."""

‎transformer_engine/jax/flax/moe.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ class _MoEBlock(TransformerEngineBase):
116116
dispatch_checkpoint_name : Optional[str]
117117
JAX rematerialization checkpoint name for the EP dispatch outputs.
118118
``None`` leaves them unnamed.
119+
wi_0_checkpoint_name, wi_1_checkpoint_name, wo_checkpoint_name : Optional[str]
120+
JAX rematerialization checkpoint names for the FC1 (gate, up) and FC2 outputs, forwarded
121+
to :func:`moe`. ``None`` leaves them unnamed.
119122
dispatch_quantization_recipe : Optional[Recipe]
120123
Recipe used to quantize tokens before EP dispatch so that the dispatch moves quantized
121124
data plus compact scales instead of high-precision activations. Only MXFP8 recipes are
@@ -191,6 +194,9 @@ class _MoEBlock(TransformerEngineBase):
191194
apply_topk_weights_early: bool = False
192195
recv_capacity_per_rank: Optional[int] = None
193196
dispatch_checkpoint_name: Optional[str] = None
197+
wi_0_checkpoint_name: Optional[str] = None
198+
wi_1_checkpoint_name: Optional[str] = None
199+
wo_checkpoint_name: Optional[str] = None
194200
dispatch_quantization_recipe: Optional[Recipe] = None
195201
collect_expert_counts: bool = True
196202
enable_ep_overlap: bool = False
@@ -403,6 +409,9 @@ def make_grouped_quantizer_set(postfix):
403409
wo_kernel_axes=wo_kernel_axes,
404410
dtype=self.dtype,
405411
dispatch_checkpoint_name=self.dispatch_checkpoint_name,
412+
wi_0_checkpoint_name=self.wi_0_checkpoint_name,
413+
wi_1_checkpoint_name=self.wi_1_checkpoint_name,
414+
wo_checkpoint_name=self.wo_checkpoint_name,
406415
dispatch_quantizer=dispatch_quantizer,
407416
enable_ep_overlap=self.enable_ep_overlap,
408417
fc2_native_weight_layout=self.fc2_native_weight_layout,

‎transformer_engine/jax/moe.py‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1621,6 +1621,8 @@ def _moe_fwd_rule(
16211621
if quant_before_fsdp_ag
16221622
else None
16231623
),
1624+
dispatch_checkpoint_name=dispatch_checkpoint_name,
1625+
fc1_checkpoint_names=(wi_0_checkpoint_name, wi_1_checkpoint_name),
16241626
)
16251627
output = with_sharding_constraint_by_logical_axes(output, input_axes)
16261628
ctx = _Ctx(
@@ -2204,7 +2206,6 @@ def _ep_overlap_errors(
22042206
quant_before_fsdp_ag,
22052207
recv_capacity_per_rank,
22062208
use_cudnn_fusion,
2207-
checkpoint_names,
22082209
wi_kernel_axes=(),
22092210
wo_kernel_axes=(),
22102211
) -> list:
@@ -2237,8 +2238,6 @@ def _ep_overlap_errors(
22372238
"quant_before_fsdp_ag needs the expert dimension of wi and wo sharded over (ep,"
22382239
" fsdp) (e.g. logical rule exp -> (ep, fsdp)); hidden-dim FSDP is not supported"
22392240
)
2240-
if any(n is not None for n in checkpoint_names):
2241-
errors.append("TE checkpoint (remat) names are not supported")
22422241
hidden = x.shape[-1]
22432242
if mxfp8 and hidden % 512:
22442243
errors.append(f"MXFP8 needs hidden_dim a multiple of 512, got {hidden}")
@@ -2380,14 +2379,36 @@ def _ep_overlap_fwd(
23802379
mxfp8=False,
23812380
quantizer_sets=None,
23822381
quant_gather_axis=None,
2382+
dispatch_checkpoint_name=None,
2383+
fc1_checkpoint_names=(None, None),
23832384
):
23842385
"""Overlapped dispatch/FC1/SwiGLU/FC2/combine. MXFP8 quantizes the weights with the FC1/FC2
23852386
kernel quantizers of ``quantizer_sets`` (rowwise and columnwise). With ``quant_gather_axis``
23862387
(the FSDP axis, sharding the expert dimension together with EP), the weights enter as their
23872388
local shards, are quantized there and gathered as MXFP8 (``_gather_quantized_weight``).
2388-
Returns (output [B,S,H], total_recv_tokens, recv_topk_weights, handle_mem, residuals)."""
2389+
Returns (output [B,S,H], total_recv_tokens, recv_topk_weights, handle_mem, residuals).
2390+
2391+
TE checkpoint names tag the residuals of the fused dispatch+FC1 call: the routing state
2392+
(``handle_mem``), received tokens (and their MXFP8 scales), received routing weights,
2393+
per-expert counts, the FC1 output and, for BF16, the SwiGLU output (MXFP8 recomputes the
2394+
activation in the backward). The wo name tags nothing: the backward does not read FC2's
2395+
output. Under a names-based remat policy JAX rebuilds unsaved residuals by re-running the
2396+
fused dispatch+FC1 call only; FC2+combine is never re-run.
2397+
2398+
A re-run dispatch may place the received rows in a different order, so the residuals must be
2399+
saved or rebuilt together: each carries every given name (dispatch, wi_0, wi_1), nested, and
2400+
is saved when the policy saves any of them. A mixed policy (dispatch saved and FC1
2401+
rematerialized, or the reverse) therefore saves all of them."""
23892402
from jax.experimental.shard_map import shard_map
23902403

2404+
residual_names = (dispatch_checkpoint_name, *fc1_checkpoint_names)
2405+
2406+
def _named(values):
2407+
for name in residual_names:
2408+
if name is not None:
2409+
values = tuple(checkpoint_name(v, name) for v in values)
2410+
return values
2411+
23912412
H = x.shape[-1]
23922413
K = cfg.top_k
23932414
align = cfg.dispatch_output_per_expert_alignment
@@ -2474,6 +2495,9 @@ def body(x_l, idx_l, w_l, w1_l, w2_l):
24742495
handle_mem, act_out, recv_w, offsets, w2_l, num_tokens=T, top_k=K, alignment=align
24752496
)
24762497
weight_res = (w1_l, w2_l)
2498+
recv_tokens, recv_w, counts, handle_mem, gemm_out, act_out = _named(
2499+
(recv_tokens, recv_w, counts, handle_mem, gemm_out, act_out)
2500+
)
24772501
total = offsets[-1:]
24782502
return (
24792503
out.reshape(x_l.shape),
@@ -2798,10 +2822,16 @@ def moe(
27982822
``NVTE_ENABLE_CUTEDSL_BACKEND=1`` and ``NVTE_MOE_OVERLAP`` (else TE raises while the GEMMs
27992823
compile at trace time); no ``NCCL_EP_*_SMS`` override;
28002824
``ep_bootstrap(num_topk=top_k, max_num_sms>0)``; BF16 or MXFP8 (E4M3) recipe; BF16
2801-
inputs and weights; SwiGLU; no biases or checkpoint names; hidden % 256 == 0 and
2825+
inputs and weights; SwiGLU; no biases; hidden % 256 == 0 and
28022826
FFN % 64 == 0 (MXFP8: 512 and 256); recv_capacity_per_rank % 256 == 0. Matches the
28032827
regular path within BF16 rounding (the routing weight is applied
2804-
before FC2). Defaults to ``False``.
2828+
before FC2). TE checkpoint names: the dispatch, wi_0 and wi_1 names all tag the
2829+
residuals of the fused dispatch+FC1 call (routing state, received tokens/scales/weights,
2830+
counts, FC1 output and, for BF16, the SwiGLU output), which are saved when the policy
2831+
saves any of these names and otherwise rebuilt by re-running only the fused
2832+
dispatch+FC1 call (never FC2+combine); the wo name tags nothing (the backward does not
2833+
read FC2's output).
2834+
Defaults to ``False``.
28052835
fc2_native_weight_layout : bool
28062836
``True`` selects FC2 storage ``wo`` [E, H, F] (the overlap GEMM's layout) instead of
28072837
[E, F, H]. With ``enable_ep_overlap``, use it together with
@@ -2913,12 +2943,6 @@ def moe(
29132943
use_cudnn_fusion=use_cudnn_fusion,
29142944
wi_kernel_axes=wi_kernel_axes,
29152945
wo_kernel_axes=wo_kernel_axes,
2916-
checkpoint_names=(
2917-
wi_0_checkpoint_name,
2918-
wi_1_checkpoint_name,
2919-
wo_checkpoint_name,
2920-
dispatch_checkpoint_name,
2921-
),
29222946
)
29232947
if overlap_errors:
29242948
raise ValueError("enable_ep_overlap=True: " + "; ".join(overlap_errors))

0 commit comments

Comments
 (0)