Repository navigation
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
6209f6b to
1250ee1
Compare
1250ee1 to
89be9fe
Compare
flash_attn_varlen_func declares every tensor argument mutable, because the underlying kernel ops are registered with mutates_args unknown. A compiled region that calls it without a preallocated out buffer is therefore skipped by Inductor with "skipping cudagraphs due to mutated inputs". Add _flash_attn_varlen_forward_functional, an opaque custom op with mutates_args=[] and a fake implementation, and route to it only from dropout-free inference that omits out and passes no padded cu_seqlens. Dropout would make the op consume RNG that it is not registered to consume, backward writes dq/dk/dv in place, and padded cu_seqlens are validated by a host-side read that CUDA graph capture forbids; all three keep the previous in-place forward unchanged. Normalize the op's outputs so they match its fake on every backend: zero the unwritten rng_state, return an empty fp32 dropout mask whose dtype otherwise varies by backend, and drop the LSE that the gfx1250 ASM path returns even when it was not requested. Signed-off-by: Mikko Lauri <[email protected]> Co-authored-by: Cursor <[email protected]>
89be9fe to
b738248
Compare
|
Hi @amd-ruitang3 - what do you think of this PR? We found that ensuring graph capture works helps to reach consistent runtimes in workloads such as LTX2.5 (diffusion audio-video generation) that have parts that are sensitive to kernel dispatch latency. |
Forward Q/K/V descales through the CUDA-graph-capturable varlen path. Co-authored-by: Cursor <[email protected]>
|
Merge conflict fixed |
|
On MI355X (gfx950), the functional route is also taken in eager, where Eager
Outputs and LSE are bit-identical between the routes on all three backends. Of the ~10 µs, ~5.4 µs is the dispatcher and ~4.5 µs is the zero plus allocations (v3 bf16 d128). Two suggestions, both tested:
- rng_state.zero_()
...
capturable_inference = (
- out is None
+ torch.compiler.is_compiling()
+ and out is None |
|
Thanks @aghamari that's a great catch, both myself and my agent had missed the extra dispatch on the eager path. I pushed a new commit Now eager
I also tested again the original inference workload that prompted this fix PR, which takes the new functional path. It's still working as expected. |
|
No activity for 15 days, so this is now labelled |
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
|
@shay-li77 I've updated the PR removing the stale tag, and it has gone through an initial review. aiter-bot indicates it as ready for human review. May I request you to take a look? |
|
API Change @amd-ruitang3 @valarLip |
|
@ruanjm @minmengdie @amd-ruitang3 @valarLip could you join the review here? This PR wraps the whole |
|
You wrote your test with pytest, yet it don't run in CI. |
|
I don’t think users will leverage CUDA Graphs via |
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
CI runs op_tests/test_mha_varlen.py as a script, and __main__ did not call the new pytest cases. Run the capture and padded-input tests through pytest at the end of __main__, so that a failure gives a nonzero exit code. The FlyDSL varlen dispatch runs a host-side architecture probe that Dynamo cannot trace. Thus fullgraph=True fails before the forward under test. Compile the capture test with graph breaks permitted, and continue to require that each compiled region is captured. Remove the explicit out= test. It runs only in eager mode, where the new functional route is not used.
Thanks, fixed in 58e06bc New tests pass, current failures on shard 2 and 7 are unrelated.
Agreed on vLLM & co. The target here is image and video diffusion mainly with xDiT, where torch.compile is how users get CUDA graphs. The fix here runs only under torch.compile; eager dispatch and engine users are unchanged. |
|
Thanks @lauri9. Two notes from testing on current main (MI355X):
|
|
Thank you @amd-ruitang3 ! I reproduce your result vs eager on MI350X. Stacking #7741 on #5910 reduces graph launches and passes
Experiment detailsMI350X/gfx950, #5910 `b15862170202`, #7741 current head `90d2c30815db`. Sample: eight cross-attention layers with projections/residuals, batch 2, four heads, dropout 0, non-causal inference. **Median ms/block**, `reduce-overhead`, 20 × 200 calls; 256/128 repeated in reverse order on the same GPU.Thanks for pointing out the work toward stable, backend-neutral contracts. I see varlen is still listed as registration exception. Would you be okay accepting this (and maybe #7741 as complementary fix after review) until the broader consolidation is complete? Merge order is independent, both would be needed to get good compile perf with HIP graphs in torch.compile. |
Summary
Make compiled, dropout-free varlen attention inference CUDA-graph capturable when the caller passes no output buffer and no padded cumulative sequence lengths. Before this change, the forward's unknown mutation annotations made Inductor reject capture with
skipping cudagraphs due to mutated inputs. Inference workloads such as LTX2.5 attention then ran uncaptured and were exposed to CPU kernel-dispatch latency and variability.Changes
_flash_attn_varlen_forward_functionalcustom op, registered withmutates_args=[]and a fake-tensor implementation, around the existing forward kernels.FlashAttnVarlenFunccalls through it only whentorch.compiler.is_compiling()is true. Eager calls keep the direct forward, so eager dispatch latency is unchanged (see Performance).rng_state.zero_(); this inference route never reads or saves that state.op_tests/test_mha_varlen.py, add six CUDA-graph capture/replay cases and a padded-input boundary test, and run both from the script entry point that CI executes.The public signature and the kernels are unchanged. Calls that need gradients, use dropout, pass an explicit
out=, or pass paddedcu_seqlens_*_paddedkeep the existing forward: dropout consumes RNG, backward writes gradients in place, and padded offsets need a host-side validation read that a capturing graph forbids. No new dependencies and no breaking changes.Interaction with the FlyDSL varlen dispatch
On current
main, the publicflash_attn_varlen_funcfirst tries the FlyDSL varlen dispatch, which callsget_gfx_runtime(). That runs a host-siderocminfoprobe (shutil.which→posix.stat) that Dynamo cannot trace, sotorch.compile(fullgraph=True)fails before reaching attention. This is independent of this PR. With defaultfullgraph=False, the probe is a graph break, and the compiled region that holds the attention forward is captured. The capture test therefore permits graph breaks but still requires every compiled region to be captured. #7741 fixes the probe; after it lands, the test can return tofullgraph=True.Performance
Measured at
b3bfa0a10fd5on AMD Instinct MI350X (gfx950) withamdsiloai/pytorch-xdit:v26.10(PyTorch2.13.0+git3369fa2, HIP7.16.26323, FlyDSL0.5.0, CK96afae1d54fc). The PR'saiter/ops/mha.pydiff is identical at the current head, so these results still apply.Eager inference, batch 2 × sequence length 32, 4 heads, dropout 0, non-causal,
return_lse=True. Median of 20 interleaved AB/BA rounds × 500 calls, exclusive single-GPU allocation. The baseline uses the base routing with the same kernels.Output and LSE match bit-exactly. The earlier ~10 µs eager regression reported in review was fixed in
80b00475. For a single sequence-32 attention call, captured replay is slower than uncaptured compiled execution (48.7–49.5 µs vs 27.2–42.2 µs) because of cudagraph-tree bookkeeping and input copies; the benefit is for workloads that capture many dispatch-bound kernels. No end-to-end throughput number is claimed.PR Self-Review
Reviewed revision
58e06bc
Behavior and intent
Compiled, dropout-free
FlashAttnVarlenFuncinference with nooutbuffer and no padded cumulative sequence lengths now calls a custom op that declares no input mutation. Before this PR, the backend ops' unknown mutation annotations made Inductor reject CUDA graph capture. The new route permits capture and replay with the same kernels and public API. The compile-only gate keeps eager dispatch direct. Gradient, dropout, explicit-output, and padded-input calls keep the existing forward. The latest commit changes tests only: it runs the new tests from the CI entry point, permits graph breaks in the capture test because of the pre-existing FlyDSL probe, and removes an eager-onlyout=test that could not exercise the new route.Validation and unverified scope
Validated on 2026-11-24 on MI350X (gfx950) in two environments:
amdsiloai/pytorch-xdit-staging:b69c7a4-temp(PyTorch2.13.0+git3369fa2, FlyDSL0.5.0) and the upstream CI imagerocm/pytorch:rocm7.2.4_ubuntu24.04_py3.12_pytorch_release_2.10.0(PyTorch2.10.0+rocm7.2.4, FlyDSL0.5.0, aiterrequirements.txtinstalled). CK was pinned to96afae1d54fc. "Base" means this head withaiter/ops/mha.pyfrom the mergedmainparentf283124a1bda. Every GPU command ran through brr on one GPU.skipping cudagraphs due to mutated inputs; padded test passedfullgraph=True, PRposix.stat)python3 op_tests/test_mha_varlen.py(CI entry point), PRCommands, run from the repository root:
The table runs used this test file with
-qwhere the committedpytest.maincall has-v -rs; the committed flags were rerun for the two-test selection on PyTorch 2.13: 7 passed. Black 26.10.1 and Ruff 0.16.0 pass. A mutation check that removed the padded-input gate from the implementation made the padded test fail with stream-capture errors.Earlier evidence for the unchanged implementation diff, at
b3bfa0a10fd5:torch.library.opcheckschema and fake-tensor checks passed 12/12; the eager timing above; normal PR CI run https://github.com/ROCm/aiter/actions/runs/42775861940 passed. The author independently validated the motivating LTX2.5 workload; that run's command and measurements are not recorded here.Remaining unverified: CI at this head (pending); gfx942/MI300X (main-branch CI runs it, and the bf16 192/128 case takes a different backend there); gfx1250 ASM capture (the tests skip devices other than gfx942/gfx950); strict
fullgraph=Truethrough the public API, which needs #7741; and the complete 45,105-case pytest matrix, which CI does not run and which has pre-existingnheads=9, gqa_ratio=8failures identical on base.PR-specific question
Before this PR, all six
test_flash_attn_varlen_func_without_out_is_cudagraph_capturablecases fail withskipping cudagraphs due to mutated inputsbecausecudagraph_or_error=Trueturns the capture rejection into an error; this was reproduced on base with PyTorch 2.13 and 2.10. The test also catches stale replay results (three distinct input sets with bit-exact comparison against eager), output/LSE metadata mismatches, and a wrong return type forreturn_lse=False. No existing canonical test compiles this path or requires CUDA graph capture: the eager correctness matrix and the script sweep cannot detect the regression. The padded test passes before this PR by design; it fails if the new route accepts padded inputs, because the host-side validation read then runs inside graph capture. Existing padded coverage is eager only.Changed op tests
Only
op_tests/test_mha_varlen.pychanges:test_flash_attn_varlen_func_without_out_is_cudagraph_capturable: six cases cover the v3 bf16 128/128, CK fp16 128/128, and OPUS bf16 192/128 (gfx950) paths, with and without LSE. Compiles with graph breaks permitted andcudagraph_or_error=True, then compares warmup, recording, and replay results bit-exactly against eager. Necessary because no existing test requires capture.test_flash_attn_varlen_func_with_padded_cu_seqlens_compiles_without_capture: compiles padded inference and compares output and LSE on real rows against eager. It guards the padded-input exclusion from the new route; existing padded tests are eager only.__main__now ends withpytest.mainon these two tests, because CI runs this file aspython3 op_tests/test_mha_varlen.pyand previously never ran them. The call exits nonzero on failure and prints skip reasons.out=test from an earlier revision is removed: it ran only in eager mode, where the new route is never taken, so it could not detect a regression in this PR.