Skip to content

Add an opt-in fused Triton RoPE for Hugging Face split-half models - #8663

Merged
tohtana merged 7 commits into
deepspeedai:masterfrom
yh0903:yh0903/fused-rope
Oct 3, 2026
Merged

tohtana merged 7 commits into
deepspeedai:masterfrom
yh0903:yh0903/fused-rope

Conversation

@yh0903

@yh0903 yh0903 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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:

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.compiled 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.compiled RoPE configured to reproduce eager rounding.

3. End to end, together with the narrow-row RMSNorm change. AutoEP training of Qwen3-30B-A3B:

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.

replace_rotary_pos_emb(model) runs Hugging Face's apply_rotary_pos_emb with a
fused Triton kernel that reads and writes each query and key tensor once in
the forward and in the backward. Every product and sum is rounded where the
eager expression rounds it, so outputs and gradients are bitwise identical.
Only listed modeling modules whose functions still have the split-half code
are patched; unsupported inputs run the original function.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
…ents

Triton contracted a product and the following sum into one FMA, skipping the
product's rounding, so the kernel is now compiled without FP contraction.
Unused outputs no longer materialize zero gradients.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
The installer compared bytecode, names, variable names and defaults, but the
bytecode refers to constants by index, so a rotate_half that changed only a
constant still matched: splitting at a quarter instead of a half, or along
the sequence axis instead of the head dimension. Constants are now compared
too, with their types and recursively for nested code objects. A docstring
is stored as the first constant but changes nothing computed, so it is left
out of the comparison. The listed modules' own functions still match.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
…tion

The cases were parametrized from a function that created tensors on the
accelerator while the file was being collected, before the module's skip
could apply, so collecting it failed where that device cannot allocate. It
is now parametrized by case name, and the test builds its inputs.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
The tests compare with torch.equal, which does not distinguish +0.0 from
-0.0, so "bitwise identical" overstated them; the test helper and the two
tests named after it now say what they check. Outputs keep the input
strides for dense layouts, not for every non-contiguous input, and
gradients that take the outputs' layout can move weight gradients further
back in the last bits. The docs also stop referring to an RMSNorm section
this branch does not contain, and state that transformers releases whose
apply_rotary_pos_emb still takes position_ids are left unpatched.

Signed-off-by: yh0903 <helloyu0903@gmail.com>

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @yh0903,
Thank you for your great effort on a lot of optimizations!

For this one, I found one blocking multi-GPU issue; _launch invokes Triton without selecting that device. Triton therefore uses the current device and stream. With device 0 current and all inputs on device 1, the launch fails with ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?).

I think we can avoid this by wrapping the Triton launch in with torch.cuda.device(x.device) (like this).

meefs pushed a commit to meefs/DeepSpeed that referenced this pull request Oct 2, 2026
…speedai#8671)

## Summary

AutoEP's native collective path (`comm_backend="comm"`, NCCL all-to-all)
puts each rank's received rows into expert-major order before the
grouped GEMM, and back afterwards, with `permute_by_local_expert` and
`unpermute_by_local_expert`. The `autoep_size=1` path uses the same two
functions. Both moved every routed row more often than needed:

- **`permute_by_local_expert`:**
- appended a zero row to the received rows with `torch.vstack`, a full
copy, before indexing the padded expert-major buffer;
- its backward was an accumulating `index_put`, i.e. a sort plus atomic
adds.
- **`unpermute_by_local_expert`:** zero-filled an `[N + 1, H]` buffer,
then scattered into it with an elementwise `index_put`.

On CUDA with Triton, both directions are now gathers:

| Direction | Forward | Backward |
|---|---|---|
| permute | a Triton row gather that writes zero rows where
`generate_permute_indices` marked padding (`-1`) | `index_select`
through the inverse permutation |
| unpermute | `index_select` through the inverse permutation | the same
padded row gather |

**Scope.**

- This is a local, on-rank change to the expert reorder.
- The all-to-alls send and receive the same rows in the same order, so
communication volume is unchanged, and no communication/computation
overlap is added.
- `generate_permute_indices` is unchanged, and the DeepEP backend does
not call these functions.
- There is no switch: the gathers replace the previous code for 2-D CUDA
tensors when Triton is available, because their results are equal to it
(see Numerics). Other tensors keep the previous code.

## Permutation contract

`generate_permute_indices` sends each received row to exactly one slot
of the padded expert-major buffer and marks every other slot `-1`. The
gathers rely on that one-to-one mapping:

- **Permute forward:** writes each output row once: the row mapped to
its slot, or zeros at a padding slot.
- **Inverse permutation:** a scatter of slot positions into scratch of
`N + N_padded` entries. Each padding slot goes to its own entry past
`N`, so no entry is written twice, and every row's entry is written.
- **Unpermute forward:** reads each row's slot through the inverse;
padding rows are never read.
- **Backward:** each direction's backward is the other gather. A row's
gradient is that of the one slot it occupied, not a sum, and padding
slots get zero gradient. Both backwards are autograd functions
themselves, so double backward goes through the same pair.
- **Top-k:** each received row is one (token, expert) assignment.
Summing a token's top-k expert outputs, in the combine, and accumulating
its top-k gradients, in the backward of the routed gather
`x[token_indices // top_k]`, stay in the surrounding code, unchanged.

These helpers are therefore not a general gather/scatter.
`permute_rows`, `unpermute_rows` and `inverse_permutation` require the
valid entries to be a complete one-to-one permutation of the rows, and
do not check it; the docstrings say so.

Both callers meet the requirement, because the counts sum to the number
of rows:

- with expert parallelism, each all-to-all receives exactly the row sums
of the exchanged counts;
- with `autoep_size=1`, the `T × top_k` routed rows are sorted by
expert, and the counts are per expert.

The previous code tolerated counts that sum to fewer rows (the rows left
out came back as zeros); the gathers do not. The row gather reads its
index by linear offset, so it now makes the index contiguous first, as
it already did the source rows.

## Numerics

The gathers only move data. Outputs, gradients and double-backward
gradients equal the previous implementation's under `torch.equal`, which
does not distinguish `+0.0` from `-0.0`.

We also compared bit patterns on H100, in bf16, fp16 and fp32, with
inputs and upstream gradients of which a quarter were `-0.0`:

- Both outputs and the unpermute gradient are bitwise identical to the
previous implementation's.
- The permute gradient differs only where the upstream gradient is
`-0.0`. The previous backward accumulated it into a zero-filled buffer,
giving `+0.0`, whereas the gather passes `-0.0` through.

## Validation

**Unit tests** (below): the earlier H100 validation passed these 27
tests and the existing `tests/unit/v1/moe/test_autoep_unit.py` (217
tests). The review follow-up additionally validates all 27 reorder cases
with plain, forked and xdist-forked execution.

**Local token movement**, one rank's work for one MoE layer, on one
H100:

- Shape: T tokens, top-8 of 128 experts, EP16 (8 local experts), hidden
2048.
- The all-to-alls are replaced by the identity and the experts by a
scalar multiply, so only the local work is timed.
- Each iteration runs a no-grad forward, a grad forward and a backward,
as under reentrant activation checkpointing.
- The whole local chain is timed; only the reorder differs between the
two columns.

| T | Before | After | Saving × 48 layers |
|---|---|---|---|
| 8192 | 7.04 ms | 5.12 ms | −92 ms |
| 16384 | 13.53 ms | 9.58 ms | −190 ms |

At T=8192, per grad forward, the permute goes from 0.44 to 0.27 ms and
the unpermute from 0.71 to 0.21 ms.

**End to end**, Qwen3-30B-A3B training with AutoEP:

- 16× H100, expert parallel 16, 48 layers, micro-batch 1, BF16, ZeRO
stage 1, reentrant activation checkpointing, and a fixed routing, so
both arms route identically.
- `comm_backend="comm"` with `combine_impl="fused_weighted_sum"` and
`async_split_plan=true`.
- Both arms also carry other opt-in kernels under review: fused RMSNorm
(deepspeedai#8645, deepspeedai#8664), fused RoPE (deepspeedai#8663), chunked loss (deepspeedai#8653) and BF16
gradient release (deepspeedai#8654). The arms differ only in this PR.
- Both arms ran on the same 16 GPUs in mirrored order, two runs each.

| Sequence | Before | After | Change |
|---|---|---|---|
| 8192 | 2649.4 ms | 2554.3 ms | −95.2 ms (−3.6%) |
| 16384 | 5434.6 ms | 5244.5 ms | −190.2 ms (−3.5%) |

- Each arm's two runs agree within 5 ms.
- The end-to-end saving matches the local estimate scaled to 48 layers
(−92 and −190 ms).
- Peak memory and the step-0 loss are identical in both arms.

These numbers come from one model, two sequence lengths, one GPU type
and one parallel layout. The saving scales with the rows each rank
reorders, so its share of the step depends on the configuration.

Small shapes are not guaranteed to improve in every direction: a review
microbenchmark on RTX PRO 4500 found slower forwards at 8,192 rows ×
hidden 1,025, while both backwards improved. This PR does not add a
shape-dependent dispatch heuristic.

The local and end-to-end numbers were measured with this PR's first
commit. The later commits add `index.contiguous()`, a no-op for the
contiguous indices both callers pass, and change docstrings and tests.
The forked-runner review follow-up changes only test execution, not the
runtime implementation.

## Tests

`tests/unit/v1/moe/test_autoep_permute_rows.py`, 27 tests: 26 need CUDA
and Triton, and 1 runs on the host. All compare against the previous
zero-row-and-index implementation with `torch.equal`:

- forward and backward of both reorders:
  - bf16 and fp32;
  - hidden 2048, 100 and 1;
- source-major `[ep, E_local]` counts with and without empty experts,
and aggregated `[E_local]` counts;
- fp16 and bf16 rows read through a column-strided view, with
column-major upstream gradients, in both directions, including the
output strides;
- double backward of both reorders;
- a round trip with zero padding;
- zero tokens;
- the row gather with both padding encodings, through a contiguous and a
strided index;
- host tensors keeping the previous code.

Results:

- 1× NVIDIA H100 80GB HBM3, Python 3.12, torch 2.10 (CUDA 13.0), Triton
3.6.0: 27 passed, and 217 together with
`tests/unit/v1/moe/test_autoep_unit.py`.
- The same 27 tests against this PR's first commit, the code the timings
used: 26 passed. The strided-index case failed, because that commit read
the index as if contiguous.
- CPU, torch 2.14: 1 passed, 26 skipped.
- Forked-runner review regression on H100, torch 2.10 (CUDA 13.0),
Triton 3.6.0: plain pytest, `pytest --forked` and `pytest -n 4 --forked`
each pass all 27 cases, with no skips and no bad-fork errors. In the
same environment, the previous tests fail under `--forked` (26 failed, 1
host case passed), reproducing the reported issue.
- CPU review regression, torch 2.14: `--forked` and `-n 4 --forked` each
give 1 passed, 26 skipped.
- `pre-commit run --files` on the changed files: passed.

## CI

- `cpu-torch-latest` runs the host test and skips the rest.
- The test file is under `tests/unit/v1`, in the scope of both AWS and
Modal GPU CI; Modal executes the selected GPU tests when the PR enters
the merge queue.
- `aws-torch-latest` uses `pytest -n 4 --forked`. The GPU cases now use
`DistributedTest` with `world_size=1`, launching clean workers even when
CUDA was touched while importing DeepSpeed during collection. These
local operator tests do not need a process group
(`init_distributed=False`). CUDA availability is checked by the runner
during test execution, not by this file's collection-time skip
condition. The host case remains an ordinary test, and all 27 cases and
their numerical assertions are unchanged.

## Not covered

- ROCm: PyTorch reports ROCm devices as `cuda`, so the gathers would be
used there, as the existing Triton index generation is. Neither was
tested on ROCm here.
- Inputs that break the permutation contract. It is not checked; both
callers meet it by construction.
- `torch.compile` of the MoE layer itself. AutoEP's regional compilation
keeps that layer eager, and the path already launched Triton kernels
there.
- Models, sequence lengths, hardware and parallel layouts other than the
ones above.

---------

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
…cution

Triton uses the current CUDA device and stream rather than selecting them
from a tensor argument. Guard the shared forward/backward launcher with
the input device, restoring the caller's device on exit. Kernel arithmetic
and launch configuration are unchanged.

Add BF16 and FP16 regressions with inputs and a non-default stream on one
GPU while another GPU is current. Compare outputs and input gradients
against eager and check device and stream restoration.

Run the existing cases through DistributedTest with one worker so the new
regression and the suite work under pytest --forked. Restore process-wide
installer patches inside that worker; retain all existing assertions.

Signed-off-by: yh0903 <helloyu0903@gmail.com>
@yh0903

yh0903 commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Hi @yh0903, Thank you for your great effort on a lot of optimizations!

For this one, I found one blocking multi-GPU issue; _launch invokes Triton without selecting that device. Triton therefore uses the current device and stream. With device 0 current and all inputs on device 1, the launch fails with ValueError: Pointer argument cannot be accessed from Triton (cpu tensor?).

I think we can avoid this by wrapping the Triton launch in with torch.cuda.device(x.device) (like this).

Thanks @tohtana for catching this! Fixed in the latest commit: the shared _launch now uses  with torch.cuda.device(x.device), so both forward and backward launch on the input device’s current stream and restore the caller’s current device. Kernel arithmetic and launch configuration are unchanged.
Added BF16/FP16 regressions with device 0 current and inputs plus a non-default stream on device 1. They compare outputs and both input gradients against eager and check device/stream preservation. With the previous runtime, both cases reproduce the reported pointer-access error.
I have also validated on two H100 80GB GPUs.

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the update! Looks good to me.

@tohtana
tohtana enabled auto-merge October 3, 2026 20:45
@tohtana
tohtana added this pull request to the merge queue Oct 3, 2026
Merged via the queue into deepspeedai:master with commit 583fc9c Oct 3, 2026
13 checks passed
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 15, 2026
…norms (deepspeedai#8664)

## Summary

Builds on the opt-in fused RMSNorm implementation merged in
deepspeedai#8645. This branch has been rebased onto current
upstream `master`: the PR diff contains only narrow-row
scheduling/backward changes, boundary tests and documentation, not the
former parent commits.

The merged parent's per-instance opt-in, checkpoint opt-out,
copy/DataParallel behavior, eager fallback and collection-safe CUDA test
framework are preserved.

The parent fused RMSNorm kernels run one row per program. For the
128-wide query and key norms of models like Qwen3, that leaves most of
each program idle. The backward also reads `hidden` and the incoming
gradient twice, once in the dx kernel and once in the weight-gradient
partial kernel.

For norms at most 128 wide, this change:

- runs up to 4096 elements per program in the forward (32 rows at width
128), with smaller power-of-two row tiles for short inputs;
- uses one backward kernel that reads each row once and writes both the
input gradient and the per-block weight-gradient partials, which are
then summed as before.

Wider norms, including the hidden-size norms, keep the existing row
kernels unchanged.

The short-input cap addresses the Codex review in this existing PR,
rather than opening a duplicate optimization PR. Both passes use
`min(max_rows_per_tile, next_power_of_2(n_rows))`; a single width-128 or
width-one row uses `BLOCK_M=1`, not 32 or 256 padded rows. Filled tiles
keep their original scheduling. AI assistance was used for this
follow-up, with author review before submission.

## Numerics

The expression and its rounding points are the same as the parent row
kernels'. Multi-row scheduling can change the FP32 reduction order for
variance, `grad_rstd`, and weight-gradient partials. **Bitwise equality
with eager is not claimed**. Forward, gamma-gradient and wide-path
numerical thresholds are unchanged. The narrow-shape input-gradient
comparison accepts each element at **at most 8 ULP or absolute error at
most 1e-7**, while still requiring **at least 95% within one ULP**. This
bounds near-zero cancellation errors without increasing the ULP limit
for other elements. Identical fused runs give repeatable input and
weight gradients at widths 128 and 2048, which is a separate determinism
property.

At width one and `eps > 0`, the pre-gamma input derivative is `eps /
(x**2 + eps)**(3/2)`, not strictly zero. A tiny epsilon can make that
value hard to distinguish from low-precision cancellation. The dedicated
width-one test uses `eps=0.25` and an FP64 reference so the nonzero
gradient is measurable, without relaxing the existing ULP thresholds.

## Tests

The existing `test_fused_rms_norm.py` forward/backward test gains narrow
shapes:

- many rows with a partial last block: `(4099, 128)`;
- the head-major query-norm shape: `(2, 300, 32, 128)`;
- width 96 with masked columns, and widths 64 and 16 at the scheduling
boundary;
- widths 7 and 15 with masked columns and partial last blocks, under the
same forward/dx/dgamma ULP thresholds.

A width-one test checks the nonzero input derivative against FP64 and
forward/gradient parity with eager. The repeated-run test checks fused
input and weight gradients at widths 128 and 2048. Existing tests cover
head-major non-contiguous inputs, transposed incoming gradients, and
non-contiguous weights.

The first width outside the narrow cutoff, 129, is additionally checked
in BF16/FP16 under the unchanged wide-path accuracy contract. The shape,
FP64 width-one and determinism cases now run inside the merged parent's
`DistributedTest` CUDA class, with Triton imports and availability
checks deferred to execution.

Earlier validation passed the six BF16/FP16 sub-16 and width-one cases
on one NVIDIA H100 80GB HBM3 (torch 2.10/CUDA 13.0, Triton 3.6).

Pre-cap rebased validation on two NVIDIA H100 80GB HBM3 GPUs, torch
2.10/CUDA 13.0, Triton 3.6.0 and transformers 5.12.0: **90 passed, 0
skipped** under `pytest --forked`. This includes the narrow
numerical/masked-width/FP64/determinism tests and the merged parent's
guards, copying, checkpoint loading/reinstallation and two-GPU
DataParallel training.

A separate public-operator comparison with the merged parent at widths
**129, 130, 256 and 2048** passes for BF16 and FP16: all sampled
outputs, input gradients and weight gradients have identical bit
patterns in these 8 comparisons. The wide kernel implementations and
parent dispatch/checkpoint logic are also unchanged by AST comparison.

Short-row follow-up in the same pinned two-H100 environment: **56
focused tests passed, 0 skipped**, including 21 explicit scheduling
cases and BF16/FP16 regressions that record both real Triton launches
while checking forward/dx/dgamma under the unchanged ULP limits. These
cover empty, single-row, non-power-of-two, tile-boundary and filled
inputs, the FP64 width-one oracle, and affected copying, checkpoint
round-trip and two-GPU DataParallel paths.

The two new real-launch regressions fail against the previous runtime: a
single width-one row launches `BLOCK_M=256` in both passes instead of 1.
Separate public-operator controls at `(8192, 128)`, `(257, 16)`, `(7,
129)` and `(7, 2048)` pass in BF16/FP16, with identical output/dx/dgamma
bit patterns in all 8 before/after comparisons.

Focused GPU selector, from `tests/`:

```bash
PYTHONPATH=.. pytest --forked unit/v1/ops/triton_ops/test_fused_rms_norm.py \
  -k 'narrow_tile or matches_hf_forward_and_backward or width_one or copy_uses_its_own_epsilon or model_round_trip or data_parallel'
```

The pre-numerical-review file on CPU (macOS, torch 2.10.0, transformers
5.12.0) with `DS_ACCELERATOR=cpu` and `pytest --forked`: **56 passed, 57
CUDA cases skipped**. Existing support limits and opt-in/fallback
behavior are unchanged; ZeRO/offload/TP/PP and other GPU architectures
were not newly exercised by this bounded follow-up. No full E2E or new
performance matrix was rerun, and no measured latency claim for short
decoding batches is made.

**RTX numerical-review follow-up:** the reviewer reported one of
2,457,600 BF16 `dx` values at 119 ULP in `(2, 300, 32, 128)` on RTX PRO
4500 and suggested an absolute alternative. Only the narrow common `dx`
assertion now has the bounded alternative above; kernels, scheduling,
forward/dgamma checks and the separate FP64 width-one oracle are
unchanged. Five CPU assertion regressions cover mixed per-element
ULP/absolute acceptance, strict default behavior, errors beyond both
limits, too many small outliers, and NaN/Inf rejection. A synthetic BF16
119-ULP example has absolute error 1.39e-8; it is not the reviewer's
tensor.

The current whole file passes on CPU under `pytest --forked`: **61
passed, 57 CUDA cases skipped**. The focused H100 run passes **9 tests,
0 skipped** under `--forked`: the five assertion cases, BF16/FP16 at the
reported shape and both short-tile correctness/launch regressions. The
allocation has 2x H100 80GB HBM3, driver 580.159.04, torch 2.10.0.2/CUDA
13.0, Triton 3.6.0 and transformers 5.12.0. On that H100 environment the
reported shape has max `dx` distance 1 ULP in BF16 and 2 ULP in FP16;
neither reproduces the RTX outlier. **RTX PRO 4500 has not been rerun by
the author for this follow-up**, so confirmation of the reported case on
that hardware remains with review. Changed-files pre-commit passed.

Focused reproduction, from `tests/`:

```bash
PYTHONPATH=.. pytest --forked unit/v1/ops/triton_ops/test_fused_rms_norm.py \
  -k 'dx_tolerance or (matches_hf_forward_and_backward and shape6) or narrow_tiles'
```

## Performance

**Hardware-dependent tradeoff:** the reviewer measured narrow forward
**11-16% slower on RTX PRO 4500** than the parent row kernels. This is a
reviewer-reported forward-only observation, not an author-reproduced
timing or a measured E2E regression. The H100 training benefits below do
not imply a universal speedup; the path remains opt-in. No new
performance tuning or benchmark matrix was added in this review
follow-up.

**Incremental local effect of this PR:** measured on one H100,
Qwen3-30B-A3B attention layer under reentrant checkpointing (forward,
recompute and backward), with fused RoPE already enabled in both arms.

| Sequence | Q/K norm time | Attention-layer time |
|---|---|---|
| 8192 | 0.73 → 0.33 ms | 7.80 → 7.52 ms |
| 16384 | 1.40 → 0.45 ms | 23.66 → 22.89 ms |

**Combined E2E effect:** Qwen3-30B-A3B training with AutoEP, 16x H100,
expert parallel 16, 48 layers, one sequence per GPU, activation
checkpointing. The "after" arm adds **both this narrow-row RMSNorm
change and fused RoPE (deepspeedai#8663)** on an otherwise
identical stack, in the same allocation. The total change cannot be
attributed to this PR alone:

| Sequence | Before | After | Change |
|---|---|---|---|
| 8192 | 1714 ms | 1654 ms | −3.5% |
| 16384 | 3632 ms | 3511 ms | −3.3% |

- The 8192 result separates cleanly: both "after" runs are below both
"before" runs.
- The 16384 run ranges overlap, so its −3.3% result is **indicative**,
not a confirmed independent speedup.
- Peak allocated memory did not increase at either length (50.434 GB at
8192; 57.161 GB at 16384). Peak reserved memory decreased slightly.
- Final-step losses differed by at most 0.0023 in these paired runs
(within-arm run-to-run spread: 0.0016–0.0068). This is a **final-step
observation, not a bound across all steps**.

The narrow kernel arithmetic and filled-tile scheduling used by these
measured workloads are unchanged; only underfilled short inputs use the
smaller row tile. Rebase/conflict resolution preserves the merged parent
rather than reinstating the former instance-bound forward or serialized
opt-in behavior. The performance numbers above are reused historical
measurements, not a retiming of the rebased stack or the short-row
follow-up.

## CI

`ci/tests_fetcher.py` against current master selects exactly
`tests/unit/v1/ops/triton_ops/test_fused_rms_norm.py`. The file retains
the parent's fork-safe worker execution and CPU coverage; the
DataParallel case additionally requires two CUDA devices. Full GPU CI
follows the repository's merge-queue workflow.

---------

Signed-off-by: yh0903 <helloyu0903@gmail.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Masahiro Tanaka <81312776+tohtana@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants