Repository navigation
Add an opt-in fused Triton RoPE for Hugging Face split-half models - #8663
Conversation
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>
b3833f8 to
f5aa916
Compare
tohtana
left a comment
There was a problem hiding this comment.
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).
…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>
Thanks @tohtana for catching this! Fixed in the latest commit: the shared |
tohtana
left a comment
There was a problem hiding this comment.
Thank you for the update! Looks good to me.
…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>
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: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'scos/sinto all of that position's heads. Nothing changes unlessreplace_rotary_pos_embis called.Semantics and safety
Process-wide patch. Attention layers look
apply_rotary_pos_embup in their modeling module, so the installer replaces it there. The replacement applies to every model of that architecture in the process, not only tomodel. Calling it again is a no-op, andrestore_rotary_pos_emb()undoes it.Which modules. A modeling module is patched only if all of these hold:
SUPPORTED_ROTARY_MODULES(Llama, Mistral, Mixtral, Qwen2, Qwen2-MoE, Qwen3, Qwen3-MoE, DeepSeek-V3);apply_rotary_pos_embandrotate_halfstill 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_halfthat 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 whoseapply_rotary_pos_embstill takesposition_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:
cos/sin;unsqueeze_dimother than 1 or 2;cos/sinthat require grad.Without Triton, or on ROCm, it always runs eager.
Direct call.
fused_apply_rotary_pos_embapplies 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
qandk;cosandsinare 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
qandkequal eager's element for element undertorch.equal, which does not distinguish+0.0from-0.0.Layout:
qandktake 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.
q_projand input-norm weight gradients differ from eager's by a relative 4e-5. Atorch.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.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:
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 usetorch.equal. Coverage: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;rotate_halfvariants that differ from the split-half one only in constants;The rejected-input cases are parametrized by name and built inside the test, so collection creates no tensors on any device.
Results:
pytest -n 4 --forked.pytest --forked, with no skips. The two BF16/FP16 cross-device cases also pass plain pytest andpytest -n 4 --forked.Pointer argument ... cannot be accessed from Tritonerror. This confirms the device guard fixes the reported issue.pre-commit run --fileson the changed files: passed.CI
cpu-torch-latestcollects the file and skips it.python ci/tests_fetcher.py --base upstream/master --explainselects exactly this file.modal-torch-latestruns it on the GPU, without--forked, when the PR enters the merge queue.aws-torch-latestrunstests/unit/v1withpytest --forked. The cases now useDistributedTest(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
SUPPORTED_ROTARY_MODULES. For example, Gemma's functions also match the split-half expression but are not listed or tested.apply_rotary_pos_embtakesposition_ids, which are left unpatched.torch.compile/torch.functransforms.