Repository navigation
Add opt-in fused AutoEP DeepEP row weighting - #8644
Conversation
Add the opt-in row_weighting_impl switch and a separate Triton per-row weighting operator for the DeepEP route. Cover config validation, eager default behavior, unsupported fail-fast paths, and GPU-gated parity tests. Signed-off-by: yh0903 <[email protected]>
At step one Adam's bias correction makes every update plus or minus lr regardless of gradient magnitude, and these tests raise lr to 1e-2 precisely so the delta check can see a wrong sign. That makes the check hypersensitive to sign flips on near-zero gradients, which look identical in the message to a genuinely different update. The failure now names the reference and actual gradient at the worst coordinate, the reference gradient's maximum, and whether the signs differ, so the two cases can be told apart without another run. Signed-off-by: yh0903 <[email protected]>
Interleaving the two checks per parameter stopped at the first failing update and left every later gradient unexamined, so a passing run said less than it appeared to. The gradients are now all checked first. The failure message also carries the updates at the worst coordinate and their maxima, not only the gradients. These tests leave gradient_clipping at its default of 1.0, so a quantitative reading has to account for the clip scale; the message states that clipping is a single positive factor and therefore cannot flip a sign, which is what makes the sign comparison conclusive on its own. Signed-off-by: yh0903 <[email protected]>
…s order matched On H100 the eager-versus-fused parity comparisons repeat bit-for-bit, and matching only the weight gradient's summation order makes the fused path bit-exact against eager across both score boundaries, reentrant checkpointing and skewed routing. The fused forward and row gradient are already bitwise eager's. The remaining difference is that FP32 order, and Adam's first update, about lr times the gradient's sign, turns order-level changes in near-zero gradients into full 2*lr parameter differences. Neither order is more accurate. Against an FP64 reference at 4096x2048 the fused sum has a lower maximum relative error (8.5e-5 against 2.9e-4) and a lower median (6.9e-8 against 7.1e-8), with a slightly higher maximum absolute error (1.8e-5 against 1.5e-5). So the model-level comparisons now sum the fused weight gradient in eager's order and keep every tolerance, and a new op test holds the real fused sum to an FP32 tree-summation error bound and to no worse than twice eager's error against FP64. Signed-off-by: yh0903 <[email protected]>
Compare the unmodified fused backward with eager at both score boundaries using norm-scaled gradients before Adam. Keep the summation-order attribution control and document the numerical behavior and independent DeepEP corrections. Signed-off-by: yh0903 <[email protected]>
Document that the MoE norm fix also applies to BF16 configurations using the FP16 optimizer wrapper. Identify the native gradient comparison as pre-clipping and describe Adam sign-flip effects as learning-rate-scale rather than a fixed delta. Signed-off-by: yh0903 <[email protected]>
c95b768 to
1c26fe6
Compare
Do you mind tell me what is the baseline seconds per step and what the new seconds per step is? |
Thanks @pengdurice!
|
tohtana
left a comment
There was a problem hiding this comment.
@yh0903 Thank you for the improvement! The code change looks good to me.
Let's merge after confirming @pengdurice is good with it too.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The shared test helper’s learning-rate override introduces failures in existing DeepEP cleanup comparisons.
Review effort: Balanced
Findings: 1
Open (1)
What changed in this PR
Adds opt-in Triton-fused row weighting to the AutoEP DeepEP path while preserving eager behavior by default.
Changes:
- Adds fused forward/backward kernels and configuration validation.
- Integrates weighting at pre/post score boundaries.
- Adds documentation and operator/model parity tests.
| File | Description |
|---|---|
deepspeed/ops/triton_ops/autoep_fused_token_ops.py |
Implements fused row weighting. |
deepspeed/module_inject/auto_ep_layer.py |
Integrates fused weighting into DeepEP routing. |
deepspeed/module_inject/auto_ep_config.py |
Parses and validates the option. |
deepspeed/module_inject/auto_ep_presets/base.py |
Adds the configuration field. |
tests/unit/v1/ops/triton_ops/test_autoep_fused_token_ops.py |
Tests kernel outputs, gradients, and guards. |
tests/unit/v1/moe/test_autoep_unit.py |
Tests configuration behavior. |
tests/unit/v1/moe/test_autoep_deepep_parity.py |
Adds distributed model parity coverage. |
tests/unit/module_inject/test_auto_ep_comm.py |
Tests DeepEP integration boundaries. |
docs/code-docs/source/autoep.rst |
Documents semantics and limitations. |
docs/_pages/config-json.md |
Documents the configuration option. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
@yh0903 , feel free to fix the copilot review then lgtm |
Keep the shared DeepEP cleanup and legacy comparisons at their original optimizer learning rate. The explicit eager/fused comparisons retain their higher rate so their first-step delta assertion stays meaningful; cover all three helper configurations with a targeted regression. Signed-off-by: yh0903 <[email protected]>
|
@pengdurice The shared test-helper learning-rate issue is fixed in 9059729: existing default/cleanup/legacy tests use the original rate, while only the new eager/fused comparisons use the higher rate. Focused H100 validation passed 7/7, including both cleanup/legacy cases and both score boundaries. Could you please take another look? thanks! |
…eepspeedai#8663) ## Summary Adds an opt-in fused Triton kernel for Hugging Face's split-half rotary position embedding, `apply_rotary_pos_emb`, as used by Llama-, Mistral-, Qwen- and DeepSeek-V3-style models: ```python from deepspeed.ops.triton_ops.fused_rotary_pos_emb import replace_rotary_pos_emb patched = replace_rotary_pos_emb(model) # number of modeling modules patched; 1 for Qwen3-30B-A3B ``` The eager function, `q * cos + rotate_half(q) * sin`, runs several elementwise kernels, each reading and writing the whole query or key tensor, and its backward does the same again. The fused kernel reads and writes each tensor once per pass and applies each position's `cos`/`sin` to all of that position's heads. Nothing changes unless `replace_rotary_pos_emb` is called. ## Semantics and safety - **Process-wide patch.** Attention layers look `apply_rotary_pos_emb` up in their modeling module, so the installer replaces it there. The replacement applies to every model of that architecture in the process, not only to `model`. Calling it again is a no-op, and `restore_rotary_pos_emb()` undoes it. - **Which modules.** A modeling module is patched only if all of these hold: - one of the model's submodules is defined in it; - it is listed in `SUPPORTED_ROTARY_MODULES` (Llama, Mistral, Mixtral, Qwen2, Qwen2-MoE, Qwen3, Qwen3-MoE, DeepSeek-V3); - its `apply_rotary_pos_emb` and `rotate_half` still have the split-half expression's code: the same bytecode, names, constants and defaults, whatever their docstrings. Constants are compared because bytecode refers to them by index: a `rotate_half` that splits at a quarter, or along another axis, otherwise has the same bytecode. Several architectures define functions of the same name that rotate part of the head dimension or add casts (for example Phi-3 and OLMo-2). A module whose functions differ is left alone with a warning. This includes transformers releases whose `apply_rotary_pos_emb` still takes `position_ids`, such as 4.51. - **Fallback.** For any input the kernel does not cover, the patched function runs the original eager function and warns once. Uncovered inputs are: - dtypes other than bf16/fp16, or mixed dtypes; - tensors not on one CUDA device; - an odd head dimension, one over 512, or one without unit stride; - shapes whose batch, sequence or head dimension do not match `cos`/`sin`; - `unsqueeze_dim` other than 1 or 2; - `cos`/`sin` that require grad. Without Triton, or on ROCm, it always runs eager. - **Direct call.** `fused_apply_rotary_pos_emb` applies the kernel directly and raises on unsupported inputs instead. - **Launch device.** Forward and backward select the inputs' CUDA device for the Triton launch, use that device's current stream, and restore the caller's current device. Inputs need not be on the device that was current when the function was called. - **Autograd.** Gradients are first order, for `q` and `k`; `cos` and `sin` are constants. Double backward raises. ## Numerics and layout Every product and sum is rounded to the input dtype where the eager expression rounds it. The kernel is compiled with `enable_fp_fusion=False`, because an FMA contraction would skip a product's rounding. Outputs and the gradients for `q` and `k` equal eager's element for element under `torch.equal`, which does not distinguish `+0.0` from `-0.0`. Layout: - For dense inputs, such as attention's transposed projection, outputs keep the input strides, as eager's do. - Other non-contiguous inputs can give outputs laid out differently from eager's, with equal values. - The gradients for `q` and `k` take the outputs' layout, whereas eager's follow the incoming gradient. Weight gradients computed from them further back can therefore differ in the last bits (see the attention block below). ## Validation Three levels, reported separately. **1. Operator.** Earlier validation passed the original 32 cases on one H100. The review follow-up adds two cross-device cases (BF16/FP16); current regression results are listed below. **2. Full attention block, one H100.** Qwen3-30B-A3B attention layer (32 query heads, 4 KV heads, head dim 128). The unit is forward, recompute and backward under reentrant activation checkpointing; each arm ran twice in mirrored order. | Sequence | Eager RoPE | Fused RoPE | Saved per layer | RoPE segment | |---|---|---|---|---| | 8192 | 9.27 ms | 7.80 ms | 1.46 ms | 1.57 → 0.19 ms | | 16384 | 26.62 ms | 23.66 ms | 2.96 ms | 3.13 → 0.39 ms | - The block output and the block's input gradient equal eager's. - The `q_proj` and input-norm weight gradients differ from eager's by a relative 4e-5. A `torch.compile`d RoPE moves them too (8e-6 and 1e-5). This comes from the layout of the gradient the weight GEMMs receive, not from RoPE's arithmetic. - The fused kernel is about 0.2–0.4 ms per layer faster than a `torch.compile`d RoPE configured to reproduce eager rounding. **3. End to end, together with the narrow-row RMSNorm change.** AutoEP training of Qwen3-30B-A3B: - 16× H100, expert parallel 16, 48 layers, one sequence per GPU, BF16, activation checkpointing. - Both arms use other opt-in AutoEP changes, including the fused row weighting (deepspeedai#8644), fused RMSNorm (deepspeedai#8645) and chunked loss (deepspeedai#8653). - "After" adds this PR and a narrow-row path for the fused RMSNorm (a follow-up to deepspeedai#8645), and nothing else. - Both arms ran on the same 16 GPUs, two runs each. | Sequence | Before | After | Change | |---|---|---|---| | 8192 | 1713.8 ms | 1654.2 ms | −3.5% | | 16384 | 3631.7 ms | 3510.5 ms | −3.3% | - At 8192 the result separates: both "after" runs are below both "before" runs. At 16384 the run ranges overlap, so that result is indicative. - These numbers cover both changes and cannot be split between them. In the attention-block measurement scaled to 48 layers, RoPE accounts for 70 of the 84 ms the two save at 8192, and 142 of 179 ms at 16384. End to end, about 70% of that combined estimate shows up. - Peak allocated memory is unchanged. - The step-0 loss differs by 8e-4. That comes from the narrow-row RMSNorm's reduction order, since RoPE's forward equals eager's. Final-step losses differ by at most 0.0023, within the 0.0016–0.0068 spread between runs of the same arm. This is a short-run check, not a convergence result. The attention-block and end-to-end numbers were measured with this PR's kernel and autograd function. Earlier follow-ups hardened the installer check, tests and documentation. The multi-GPU review follow-up adds an input-device guard to the shared forward/backward launcher; kernel arithmetic and launch configuration are unchanged. The existing performance measurements were not rerun for this correctness fix. ## Tests `tests/unit/v1/ops/triton_ops/test_fused_rotary_pos_emb.py`, 34 tests. They need CUDA and Triton and are skipped otherwise; the two cross-device cases additionally require two visible CUDA devices. Comparisons with eager use `torch.equal`. Coverage: - forward and backward in bf16/fp16 across shapes, for attention's transposed projection and for contiguous inputs, including output and gradient strides; - `unsqueeze_dim=2`, a table broadcast over the batch, non-contiguous incoming gradients, an unused output leaving no gradient, an empty sequence, and double backward raising; - every rejected input on the direct call, and the eager fallback of the installed function; - an installed two-layer Qwen3 (eager attention, small shapes) whose logits and every parameter gradient equal eager's; - installer idempotence and restore, and an unlisted model; - refusal of a changed expression, and of two `rotate_half` variants that differ from the split-half one only in constants; - acceptance of functions that differ only in their docstrings. - BF16/FP16 inputs and a non-default stream on one device while another device is current: compare outputs and both input gradients against eager, and check caller device and stream restoration. The rejected-input cases are parametrized by name and built inside the test, so collection creates no tensors on any device. Results: - 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: 32 passed. - The same tests against the previous installer check, which compared bytecode, names and defaults but not constants: 30 passed. The two constant-variant tests failed because that check patched the module. - CPU review regression: 34 skipped under `pytest -n 4 --forked`. - Multi-GPU review regression on two NVIDIA H100 80GB HBM3 GPUs, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: the full suite passes all 34 cases under `pytest --forked`, with no skips. The two BF16/FP16 cross-device cases also pass plain pytest and `pytest -n 4 --forked`. - With the same new tests and the previous runtime, both cross-device cases fail with the reported `Pointer argument ... cannot be accessed from Triton` error. This confirms the device guard fixes the reported issue. - Code check without a GPU, on transformers 5.12 and 5.17 under Python 3.13 and 3.14: all eight listed modules still match. The functions of Phi-3, OLMo-2, GPT-NeoX, Qwen3-Next, GLM-4-MoE, ERNIE-4.5-MoE and Cohere, none of them listed, are refused. - `pre-commit run --files` on the changed files: passed. ## CI - `cpu-torch-latest` collects the file and skips it. - `python ci/tests_fetcher.py --base upstream/master --explain` selects exactly this file. `modal-torch-latest` runs it on the GPU, without `--forked`, when the PR enters the merge queue. - `aws-torch-latest` runs `tests/unit/v1` with `pytest --forked`. The cases now use `DistributedTest(world_size=1, init_distributed=False)` to run in clean workers despite CUDA state created during collection. This file no longer probes CUDA availability in its collection-time skip condition; process-wide installer patches are restored in the worker that installed them. Documentation: a new "Fused rotary position embedding (experimental)" section in `docs/code-docs/source/autoep.rst`, before the AutoEP constraints. ## Not covered - Architectures outside `SUPPORTED_ROTARY_MODULES`. For example, Gemma's functions also match the split-half expression but are not listed or tested. - Transformers releases whose `apply_rotary_pos_emb` takes `position_ids`, which are left unpatched. - Partial, interleaved or other RoPE variants, fp32, ROCm, and `torch.compile`/`torch.func` transforms. - Matching eager's layout for non-dense inputs; the values are equal. - Splitting the end-to-end gain between this PR and the narrow-row RMSNorm change, and long-run convergence. --------- Signed-off-by: yh0903 <[email protected]> Co-authored-by: Masahiro Tanaka <[email protected]>
deepspeedai#8645) ## Summary Adds `deepspeed/ops/triton_ops/fused_rms_norm.py`: - `fused_rms_norm(hidden, weight, eps)`: Triton forward and backward kernels for the RMSNorm expression that Llama-style Hugging Face models share, `weight * (x.float() * rsqrt(mean(x.float()**2) + eps)).to(x.dtype)`. - `replace_rms_norm(model) -> int`: an explicit, opt-in installer that runs the kernels in place of the forward of each supported RMSNorm module (the RMSNorm classes of Llama, Mistral, Mixtral, Phi-3, Qwen2, Qwen2-MoE, Qwen3, Qwen3-MoE, DeepSeek-V2 and DeepSeek-V3) and returns how many modules it replaced. For inputs the kernels do not take, a replaced module runs its own eager forward. Nothing changes unless `replace_rms_norm` (or `fused_rms_norm`) is called. In the AutoEP Qwen3-30B-A3B training setup described under Performance, it cut the median step time by **9.0%**, with peak memory unchanged. ## Module copying and checkpoints The installer uses a class descriptor and a per-instance opt-in marker, rather than storing a bound `forward` method on each module. The dispatcher is process-wide, but instances not explicitly selected keep their original eager forward and remain eligible for a later opt-in. Shallow/deep copies and `torch.nn.DataParallel` replicas retain their live opt-in and bind to their own receiver, weights and epsilon. HF module classes, Parameters and state-dict keys are unchanged. Full-model `torch.save(model, ...)` / `torch.load(..., weights_only=False)` clears the opt-in: the marker serializes as `False`, not as an enabled flag. The loaded model remains eager until `replace_rms_norm(model)` is called again, even when another instance has already installed the class dispatcher in the loading process. Legacy boolean markers also cannot enable the new dispatcher. The original class/instance-patch guards, idempotence and unsupported-input fallback are preserved. This follow-up preserves the earlier master merge and receiver-binding fix; it does not include the narrow-row scheduling changes from deepspeedai#8664. ## Semantics The kernels keep the eager order: FP32 variance and normalization, one rounding of the normalized value to the input dtype, then the multiply by the weight (gamma). The backward rounds where eager autograd rounds: `grad_out * weight` is rounded to the input dtype before use, and the gamma-gradient product `grad_out * normalized` is rounded to the input dtype before its FP32 column sum. Results are still not bitwise identical to eager, because the FP32 reductions sum in a different order. ## Which modules are replaced Instances of the exact classes listed in `SUPPORTED_RMS_NORM_CLASSES` that still run their class's own `forward` and are at most 2048 wide. The list is explicit because a class name ending in `RMSNorm`, a 1-D `weight` and a float `variance_epsilon` do not determine the math. In transformers 5.17, 140 `*RMSNorm` classes pass that rule, and 8 of them multiply by the weight *before* the cast: `GptOssRMSNorm`, `Olmo2RMSNorm`, `Olmo3RMSNorm`, `FlexOlmoRMSNorm`, `OlmoHybridRMSNorm`, `HeliumRMSNorm`, `AfmoeRMSNorm` and `OpenAIPrivacyFilterRMSNorm`. `Olmo2RMSNorm` changed order between releases: it casts before gamma in 4.51.3 and after gamma in 5.17. The kernels would run on those modules without error and silently change their numerics, so falling back to eager cannot catch this; the selection has to. The installer therefore: - replaces only exact instances of the listed classes. CPU tests hold the currently listed classes to the kernels' expression using `torch.equal` (which does not distinguish signed zero), so a class that changes its cast order upstream fails CI. Adding a class also requires updating the collection-safe class-name metadata in the tests; - leaves subclasses alone, as well as modules whose `forward` was patched or wrapped on the class or on the instance, whether by another kernel installer or by an earlier call (so a second call replaces nothing). A wrapper made with `functools.wraps` carries the original's name, so it is recognized by the `__wrapped__` attribute that `functools.wraps` sets; - leaves norms wider than 2048 eager, because the kernels hold a whole row in one block. On Qwen3-30B-A3B it replaces all 193 RMSNorm modules: `input_layernorm`, `post_attention_layernorm`, `q_norm` and `k_norm` in each of the 48 layers, plus the final norm. On Qwen3-235B-A22B (hidden size 4096) it replaces the 188 128-wide `q_norm` and `k_norm` modules and leaves the 189 4096-wide norms eager. ## Where the kernels run | | | |---|---| | Kernels | Input and weight are bfloat16 or float16 CUDA tensors of the same dtype, and Triton is available on CUDA (not ROCm). | | Everything else | The module runs its class's own eager forward, so the result is exactly eager's, and a warning is logged once. This includes CPU tensors, float32 inputs and float32 weights under autocast, so the installer can run before the model moves to the GPU. | | Layout | Any leading shape. Non-contiguous inputs and weights are copied before the kernels run. The kernels' output and input gradient are contiguous, whereas eager follows the input and upstream-gradient strides. | | Autograd | First-order gradients for input and weight; `eps` is a constant. On the kernel path, double backward raises (`once_differentiable`) instead of silently dropping this op's second derivative. `torch.compile` and `torch.func` transforms are not covered. | | `fused_rms_norm` | Applies the kernels directly and raises on unsupported inputs instead of falling back. | ## Correctness evidence Three separate questions, each with its own evidence. ### 1. Does the operator compute the expression? (unit tests, random inputs) The reference is the eager expression in the same dtype. The metric is the distance in units in the last place (ULP), computed from ordered bit patterns: - forward: max ≤ 2 ULP, and ≥ 99% of elements within 1 ULP - input and gamma gradients: max ≤ 8 ULP, and ≥ 95% within 1 ULP (≤ 16 ULP and ≥ 90% at input scales of 1e-4 and 1e4) Coverage: bfloat16 and float16; widths 128, 130, 256 and 2048, plus an empty input; head-major non-contiguous input; strided weight; and the installer on every listed class, against that class's own eager forward, with a non-default epsilon and the head-major upstream gradient that attention produces. Every random input comes from a seeded generator. ### 2. Does it hold on real training tensors? (frozen replay, Qwen3-30B-A3B) 21 RMSNorm boundaries were captured from one eager Qwen3-30B-A3B training step (48 layers, EP16, sequence length 1024): all four norm kinds at layers 0, 11, 23, 35 and 47, plus the final norm, with the real inputs, gamma, epsilon, upstream gradients and strides. The eager replay reproduces the captured outputs exactly (relative L2 of 0 in all 21 cases). Fused against eager, on one H100: | | Result | |---|---| | Gamma gradient | Bitwise identical in 20 of 21 cases; one element differs in the remaining case | | Input gradient | 15–136 differing elements per case (out of 0.5M–4.2M), relative L2 ≤ 5e-5 | | Forward | 0–14 differing elements per case | | Elements outside \|a − b\| ≤ 2⁻⁶ + 2⁻⁶·\|b\| (BF16 policy) | 0 in every case | The forward differences come from the FP32 summation order of the variance, which a `torch.compile`d RMSNorm does not reproduce either. No replay was run for the other listed classes; for them, the evidence is the unit tests above plus each class computing the same expression bitwise. ### 3. What does it do to a short training run? (sensitivity, not equivalence) These are paired 24-step runs in the setup described under Performance, with 4 repeats per arm: - step 0: mean loss differs by about 4e-4 (forward rounding) - step 1: 17.100 eager vs 17.044 fused (−0.056), where eager repeats agree to within 0.004 - max |Δ mean loss| over the 24 steps: fused 0.058; eager vs eager 0.013–0.019 A control changes only the eager RMSNorm's variance reduction, computing it in FP64 before the usual FP32 steps, which gives a more accurate eager norm. It moved step 1 by +0.043 and reached a max |Δ| of 0.049. So a 0.02 threshold on short-run loss also rejects a more accurate eager norm: ULP-level changes in the norm move the first AdamW steps by more than 0.02, and the threshold cannot decide on its own whether a kernel is correct. Runs this short cannot establish long-run training equivalence, and this PR does not claim it. ## Performance Measured setup, identical in both arms except for the RMSNorm implementation: - Qwen3-30B-A3B, 48 layers, sequence length 8192, micro-batch 1 per GPU - AutoEP with the DeepEP backend, EP16 on 2 nodes × 8 H100 80GB, with both arms on the same allocation - BF16, ZeRO stage 1 with FP32 gradient accumulation, AdamW, reentrant activation checkpointing, Python GC disabled during training - a fixed routing schedule (identical route histograms in both arms); HF router logits on, so both arms also build the zero-coefficient load-balancing loss - both arms include two changes that are not part of this PR: the DeepEP cached-dispatch layout fix (deepspeedai#8636) and the opt-in fused AutoEP row weighting (deepspeedai#8644) - 24 steps, of which the first 12 are excluded; step time is the synchronized training step, taking the maximum across ranks - one discarded preflight run per arm, then 4 runs per arm in ABBA BAAB order | | Median step (ms) | Per-repeat medians (ms) | |---|---|---| | Eager RMSNorm | 1934.3 | 1881.2, 1910.7, 1977.1, 1958.0 | | Fused RMSNorm | 1760.4 | 1814.3, 1706.5, 1693.1, 1869.3 | That is −174 ms (−9.0%). All four paired repeats are faster (−3.6%, −10.7%, −14.4%, −4.5%), and the 95% t-interval over those four deltas is [−16.5%, −0.1%]. Peak memory is unchanged (58.3 GiB allocated, 71.2 GiB reserved). An earlier screen on a different allocation, run before the gamma-gradient rounding fix, measured −8.96%. Scope: one model, one parallel configuration and one sequence length, on H100. The interval is wide, so read this as "about 9% in this configuration", not as a general speedup. Not measured: the other listed model families, other widths, sequence lengths or EP sizes, other GPUs, ZeRO-3, `torch.compile`, and non-reentrant checkpointing. The measured kernels are byte-identical to this PR's. Since those runs, the installer covers more classes and is stricter about which modules it takes (it still replaces the same 193 modules on this model), replaced modules fall back to eager for inputs the kernels do not take, `fused_rms_norm` copies a non-contiguous weight first (a no-op for the contiguous weights measured), and the backward became `once_differentiable` (first-order gradients unchanged). On supported inputs a replaced module still makes one input check per call and then runs the same kernels. The receiver-binding and checkpoint opt-in follow-ups change only module dispatch and checkpoint behavior, not the kernels, autograd or direct operator implementation. The existing performance and replay evidence is reused; there is no new timing or full E2E run, and the historical percentage is not an independently retimed measurement of the new dispatcher. ## Tests `tests/unit/v1/ops/triton_ops/test_fused_rms_norm.py`: 70 cases, including the original numerical and receiver/checkpoint coverage: - GPU (31 original numerical/installer cases): forward and backward against eager (dtypes × widths, empty input, head-major input, extreme magnitudes, strided weight); `fused_rms_norm` rejecting widths above 2048, float32 and mixed dtypes; double backward raising; the installer on each listed class against that class's own eager forward (count, the module's own epsilon, gradients reaching the module weights, a second call replacing nothing); a replaced module taking the kernels for supported input and returning exactly eager's result for float32 input. - CPU (30 original cases): device and dtype guards of `fused_rms_norm`; each listed class matching the kernels' expression under `torch.equal`, on inputs where the two cast orders differ; each listed class replaced and still returning exactly its eager result for CPU input; the 2048-wide boundary; a local name-alike class, `Olmo2RMSNorm`, `GptOssRMSNorm`, a `Qwen3MoeRMSNorm` subclass, and class-patched, class-wrapped (`functools.wraps`) and instance-patched forwards all left unreplaced. - Receiver/checkpoint cases (9): shallow/deep copies retaining opt-in with their own epsilon on CPU/CUDA; full-model round trips on CPU/CUDA that retain eager layout until explicit reinstallation and check independently derived forward/input/weight gradients; loading in a fresh interpreter with and without a previously installed dispatcher; and actual two-GPU `DataParallel` training against the eager expression over two SGD steps. Constant rows make the extra BF16 DP gradient reduction exact; the existing forward/gradient ULP thresholds are unchanged. The existing conditional-kernel test also verifies that an unselected sibling stays eager and can opt in later. Results: - Current checkpoint/forked-test follow-up on two NVIDIA H100 80GB HBM3 GPUs, torch 2.10/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0: **70 passed, 0 skipped** under `pytest --forked`. The 9 receiver/checkpoint/DataParallel cases also pass `pytest -n 4 --forked`. - Collection regression on the same hardware: the new file does not import the RMSNorm Triton module or initialize CUDA during collection, and a child forked afterwards allocates CUDA successfully. The preceding test file initializes CUDA during collection and its forked child fails with the reported bad-fork error. - With the preceding class-dispatcher runtime and the same new tests, both CPU/CUDA same-process checkpoint cases and the fresh-process/preinstalled-dispatcher case fail as expected (**3 failed, 0 skipped**). - CPU follow-up, torch 2.14 and transformers 5.12.0: **35 passed, 35 CUDA cases skipped** with `pytest --forked`. Against the preceding class-dispatcher runtime, the same-process checkpoint and fresh-process/preinstalled-dispatcher cases both fail as expected. - A local macOS / torch 2.14 `-n 4 --forked` attempt aborted in the eager reference's native autograd engine (SIGABRT); single-runner CPU validation and the Linux CI-style receiver/checkpoint matrix above passed. No assertions were removed or platform safety checks disabled to bypass that abort. - Current-master targeted receiver/installer run on NVIDIA H100 80GB HBM3: **35 passed, 0 skipped** (the 29 existing installer cases plus all six new regressions), with torch 2.10/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0. The DataParallel case used two GPUs and checked two SGD steps against the independent eager expression. This was targeted validation, not a rerun of the full 67-case suite or E2E. - Old-runtime negative control with the same new tests: **all six fail as expected, 0 skipped**. Only the tests are changed in this arm, so it retains the actual prior instance-bound runtime and the same kernel/autograd code. - 1× NVIDIA H100 80GB HBM3, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: 61 passed, 0 skipped. - The same tests against the first version of this PR (same kernels, only `Qwen3MoeRMSNorm` listed, so 34 collected): 14 failed, 20 passed. A strided weight put the forward up to 34,883 ULP off; double backward did not raise; the seven name-alike, subclass, and patched or wrapped modules were matched; CPU and float32 inputs raised instead of running eager; a 2048-wide norm on the CPU was rejected; and a second call replaced the norms again. Every kernel accuracy test passed in both runs. - CPU only, torch 2.14: 30 passed and 31 skipped with transformers 5.17; 27 passed and 34 skipped with transformers 4.51.3, the `requirements-dev.txt` minimum, where `DeepseekV2RMSNorm` and `GptOssRMSNorm` do not exist. - `pre-commit run --files` on the changed files: passed. ## CI - Published follow-up head: DCO and test collection passed. Full GPU CI was skipped on the PR event; the targeted H100 execution above is the new device-validation evidence. - `cpu-torch-latest` runs the 35 CPU cases, with transformers from git main on PRs. CUDA cases defer Triton imports and device-availability checks to execution, and use `DistributedTest(world_size=1, init_distributed=False)` for fresh workers under forked CI. Parametrization and collection-time skipping use only metadata. The DataParallel regression requires two CUDA devices and skips on a single-GPU runner. - For `modal-torch-latest` (L40S), `python ci/tests_fetcher.py --base upstream/master --explain` selects exactly `tests/unit/v1/ops/triton_ops/test_fused_rms_norm.py`. That workflow only selects tests on PR events and runs them on the GPU when the PR enters the merge queue, so until then the GPU results are the H100 run above. ## Merge dependency As requested in the review, deepspeedai#8737 should land before this PR. It addresses a pre-existing Transformers 4.51.3 / Hybrid Engine OPT circular import when loading a checkpoint before importing DeepSpeed. This follow-up does not fold in or work around that separate import-order bug. ## Not covered None of these apply to the measured configuration (Qwen3-30B-A3B, BF16, H100, ZeRO-1, reentrant checkpointing, contiguous weights, first-order gradients). - Norms wider than 2048 stay eager. That includes the hidden-size norms of most models of 7B parameters and up (hidden sizes of 3584 for Qwen2.5-7B, 4096 for Llama-3-8B and Mistral-7B); in those models only narrower norms, such as Qwen3's 128-wide query and key norms, are replaced. Wider rows need a kernel change and new measurements. - RMSNorm classes that are not listed, including those with different math (the Gemma family's `(1 + weight)`, GPT-OSS, OLMo 2 and 3) and classes from `trust_remote_code` modeling files. - Replay and training runs for the listed classes other than Qwen3-MoE. - ZeRO-3 partitioned weights, `torch.compile` or AutoEP regional compile around the norms, and `torch.func` transforms. - Non-reentrant activation checkpointing, and float16 end to end (float16 is covered by the unit tests only). - Long-run convergence: only 24-step runs were measured. --------- Signed-off-by: yh0903 <[email protected]> Co-authored-by: Olatunji Ruwase <[email protected]>
…32 tensor (deepspeedai#8653) ## Summary Adds an opt-in replacement for Hugging Face's `ForCausalLMLoss` that computes the same FP32 cross entropy without materializing any FP32 `[tokens, vocab]` tensor. `ForCausalLMLoss` upcasts the whole logits tensor to FP32 and calls `cross_entropy`, which saves an FP32 log-softmax for backward; backward then allocates two more FP32 `[tokens, vocab]` tensors. At 8,192 tokens with Qwen3's 151,936-token vocabulary each is 4.98 GB, and all three are alive when backward starts. `install_chunked_causal_lm_loss(model)` sets the model's `loss_function` to `ChunkedCausalLMLoss`: - Forward saves only the given logits and one FP32 log-sum-exp per token. Backward recomputes the softmax and writes the gradient directly in the logits' dtype, which is the dtype the stock path casts its FP32 gradient to. - On CUDA a Triton kernel does each pass in one read of the logits; a PyTorch backend does the same arithmetic in blocks of rows and runs anywhere. `backend="auto"` picks Triton when it can run, and naming a backend that cannot run raises instead of substituting. - It only replaces the stock `ForCausalLMLoss` and refuses any other `loss_function`. Nothing changes unless it is installed. ## Semantics As in `ForCausalLMLoss`: - labels are shifted by one position, padding with `ignore_index`, unless `shift_labels` is given; - class-index targets must be `torch.long`; floating-point, boolean and other non-long targets are rejected rather than silently converted. When `shift_labels` is supplied, only those actual targets are checked; unused `labels` retain the stock loss's behavior; - rows whose target is `ignore_index` get zero loss and zero gradient; - without `num_items_in_batch` the loss is the mean over non-ignored tokens (NaN if every token is ignored); with it, the sum divided by `num_items_in_batch`; - the loss is FP32 and the gradient has the logits' dtype. FP32 gradients match; BF16/FP16 gradients can differ by one representable step where the FP32 evaluation order lands on a rounding boundary. Beyond that: - `block_rows` must be a positive integer or `None` for automatic sizing. Constructor, installer and direct calls reject invalid values before a backend runs, including when the selected backend would not use row blocking; - targets may be strided; - an out-of-range target fails through a device-side assert, as `cross_entropy` does, without adding a host synchronization; - the range assertion uses the existing `required_torch_version` helper to call Torch 2.0's one-argument API and supply the message only on Torch 2.1+; - a non-writable stock `loss_function` produces an actionable installer error, including property setters raising `AttributeError` or `TypeError`; - backward with `create_graph=True` raises, because the gradient is computed outside autograd and a second derivative would otherwise be silently missing. ## Results (NVIDIA H100 80GB HBM3) **Operator speed.** Loss forward plus backward alone at 8192 × 151936 BF16 logits, median of 40 alternating iterations: | loss | time | | --- | --- | | `ForCausalLMLoss` | 20.82 ms | | chunked, Triton | 2.76 ms | | chunked, PyTorch | 35.23 ms | **Memory, end to end.** AutoEP training of Qwen3-30B-A3B (48 layers, sequence length 8192, EP16 on 16 GPUs, BF16, ZeRO stage 1, reentrant activation checkpointing), four mirrored repeats per arm that differ only in the loss. Both arms also use the opt-in fused row weighting (deepspeedai#8644) and fused RMSNorm (deepspeedai#8645). | | stock | chunked (Triton) | | --- | --- | --- | | peak allocated | 62.224 GB | 54.439 GB | | peak reserved | 70.477 GB | 57.481 GB | In the stock arm, the three FP32 `[tokens, vocab]` tensors account for 14.9 GB of the memory live at the peak. **Step time, end to end.** In the same runs, the median step is 1763.6 ms stock and 1752.8 ms chunked (−0.6%, 95% interval [−6.0%, +2.9%]). The ~18 ms the operator saves is about 1% of the step, below what this comparison resolves, so no end-to-end speedup is claimed. **Training loss.** Step 0 is identical. Over 24 steps the largest cross-arm difference is 0.0098, within the 0.0078–0.0124 spread between repeats of the same arm. This is a short-run check, not a convergence result. These operator and end-to-end numbers were measured at the "Compute the chunked causal-LM loss with Triton on CUDA" commit. For the contiguous, in-range targets used there, the later commits add a no-op `.contiguous()`, a device-side range check of the targets, and a grad-mode check in backward. The input-validation follow-up adds only API guards and compatibility handling. Triton kernels and both autograd implementations are byte-identical to the previously validated head. Existing memory/performance evidence is reused; no large-vocabulary allocation test or full E2E was rerun for this follow-up, and the historical timings are not new measurements of the added guards. ## Tests `tests/unit/v1/runtime/test_chunked_cross_entropy.py`: the original 28 cases plus input/installer/compatibility regressions (50 cases total): - loss and gradient against the stock `ForCausalLMLoss` for BF16, FP16 and FP32 on both backends, across Triton tile boundaries; - `num_items_in_batch`, a given `shift_labels`, ignored rows (zero gradient) and all-ignored (NaN), matching the stock loss; - a strided target on both backends; an out-of-range target raising on CPU, and failing the Triton backend in a subprocess instead of reading another row; - `create_graph=True` raising on both backends, and a named backend that cannot run raising; - no FP32 tensor larger than one value per row saved for backward; - a small Hugging Face causal LM giving the same loss and parameter gradients with the installed loss, and a non-stock loss being refused; - at the real shape (8192 × 151936 BF16), gradients 99.9% bit-identical and within one step, and a backward peak lower by more than two FP32 logits copies. - zero, negative and fractional row blocks; non-long actual targets through direct CE, the causal-LM wrapper and installed HF models; supplied `shift_labels` overriding unused floating/absent labels; non-writable loss properties leaving the stock function unchanged; Torch 2.0's one-argument assertion contract; and fresh collection followed by a real fork and CUDA allocation. Results: - Current follow-up on NVIDIA H100 80GB HBM3, torch 2.10/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0: plain pytest and `pytest --forked` each passed **49 cases, 0 skipped**. Only the previously validated large-vocabulary allocator case was deselected. Both runs retain the original loss/gradient tolerances. - Same new regressions against the prior runtime: **18 expected failures, 0 skipped**, covering row blocks, non-long targets, actual installed HF models, the legacy assertion signature and rejecting properties. Prior collection code with the fixed runtime independently reproduces the CUDA bad-fork error; the final import/fork/allocation regression passes in both test modes. - The Torch 2.0 assertion branch is exercised against its documented one-argument collaborator signature under the current runtime, not claimed as a separate Torch 2.0 hardware qualification. - 1× NVIDIA H100 80GB HBM3, torch 2.10 (CUDA 13.0), Triton 3.6.0, transformers 5.12.0: 28 passed, 0 skipped. The same tests against the runtime without the `create_graph` guard: 27 passed, and the Triton `create_graph` case failed because the second derivative was silently dropped. - CPU, torch 2.14: 16 passed and 12 skipped (CUDA-only), with transformers 5.17 and with 4.51.3. - `pre-commit run --files` on the changed files: passed. ## CI - Published follow-up head: DCO and test collection passed; full GPU CI and infrastructure smoke jobs were skipped on the PR event. Device evidence for this follow-up is the targeted plain/forked H100 run above. - `cpu-torch-latest` runs the CPU cases (30 after this follow-up). Collection uses NVML-based `device_count` and importability checks only. The loss runtime is imported by a worker-local fixture, because the shared Triton helper probes its driver on import; this prevents parent-process CUDA initialization before `--forked` workers without changing the shared helper. - The tests live under `tests/unit/v1`, where `modal-torch-latest` selects tests and `aws-torch-latest` runs them. `python ci/tests_fetcher.py --base upstream/master --explain` selects exactly this file; `modal-torch-latest` runs its selection on the GPU when the PR enters the merge queue. Documentation: a new section at the end of `docs/code-docs/source/autoep.rst`. ## Not covered - Label smoothing, soft labels, class weights, distributed or vocabulary-parallel cross entropy, and loss functions other than the stock `ForCausalLMLoss`. - Second derivatives through the loss, which raise. - Models other than the ones above (a small Llama in the unit tests, Qwen3-30B-A3B end to end), and long-run convergence. --------- Signed-off-by: yh0903 <[email protected]>

Summary
expert_parallel.row_weighting_impl="fused"for the AutoEP DeepEP route at bothscore_apply="pre"and"post"boundaries. The default"auto"still resolves to the existing eager expression; unsupported configurations fail explicitly rather than falling back.Numerical semantics
engine.backward()and beforeengine.step()clips gradients, using||fused - eager||_2 / ||eager||_2 <= 2e-2for each checked tensor/group. Same-seed eager/eager controls were bit-exact; the largest previously measured native fused/eager model-gradient relative L2 was 5.6e-3 (reentrant checkpointing), leaving about 3.6x headroom. Near-zero gradient sign flips can cause learning-rate-scale differences in Adam's first parameter update, so coordinate-wise update equality is not used as the native-path gate.Testing Done
preandpost) on 4 ranks of an 8-GPU NVIDIA H100 80GB HBM3 node. Neither case replacesd_weights; both check exact routes and normalized errors through routing scores, router gate, all model parameters, and model input. The separate summation-order-matched attribution controls remain in place.lr=1e-2; the original default/cleanup/legacy cases retainlr=1e-4. A targeted run on 4 ranks of an 8-GPU NVIDIA H100 80GB HBM3 node passed 7/7, 0 skipped: three config-scope cases, both cleanup/legacy cases, and eager/fused comparisons at both score boundaries.Dependencies and scope
master. The GPU tests used an earlier pinned source with both corrections applied separately; neither is included in this PR. The norm fix applies toFP16_Optimizer, which is also used by some BF16 configurations. The new model-level gradient gate reads gradients before this wrapper's norm/clipping inengine.step().[N, H]rows and FP32[N, 1]weights, and does not support ROCm or non-DeepEP/EP=1 routes. DeepEP v2 requires a compatible NCCL build with GIN support.