Repository navigation
Switch to Python binding for cuDNN frontend - #3693
vcherepanov-nv wants to merge 72 commits into
Conversation
Build and select cuDNN attention plans through the Python frontend for ordinary and score-modified attention. Share graph serialization and a JAX-owned C++ FFI executor with per-device plan and handle caches and CUDA command-buffer support. Remove JAX's calls to TE common attention APIs while leaving TE common and PyTorch unchanged. Expose current tensor-scaled FP8 forward and backward through fused_attn and Flax attention modules, retaining FP16/BF16 inputs, outputs, and input gradients. Add ALiBi and preserve packed and ragged layouts, GQA, masks, sliding windows, dropout replay, attention sinks, max logits, and Ring and AllGather context parallelism. Preserve neutral statistics for empty ragged ring blocks and differentiation with is_training=False. Document FP8 availability, scaling, remaining feature gaps, and the NVTE_FP8_DPA_BWD switch. Add independent numerical references and focused regression coverage for the new precision and execution paths. Validate with the editable JAX build, the requested attention suites (1,241 passed, 3,901 skipped), and additional FP8, Flax, deterministic, two-GPU context-parallel, and CUDA command-buffer checks. JAX L0 lint, pre-commit, and changed-file license checks pass. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Move cuDNN attention support queries, graph construction, plan caching, and forward/backward execution into the PyTorch Python frontend. Cover FP16/BF16, FP8 and MXFP8 while preserving layout, masking, softmax, ragged and paged KV, quantization, and context-parallel behavior. Share graph lifecycle helpers with experimental flex attention. Remove the obsolete PyTorch bindings to common attention execution and retain a capture-safe C++ Philox helper for PyTorch generator state. Keep the common and JAX attention implementations intact. Add numerical-reference, execution-path isolation, capability-exclusion, and CUDA generator replay regressions, and document the Python frontend dependency and graph caching behavior. Validation on GB200 with cuDNN 9.27 and frontend 1.30: - Editable PyTorch build succeeded. - Requested attention/flex suites: 2,869 passed, 2,425 skipped. - Final focused numerical coverage: 629 passed, 560 skipped. - Deterministic attention: 2,231 passed, 3,038 skipped with NVTE_ALLOW_NONDETERMINISTIC_ALGO=0 and NVTE_FLASH_ATTN_V4=0. - Compiled attention: 52 passed; CUDA graph and two-/four-GPU context-parallel coverage passed. - Default/custom generator replay passed; FP8 dropout replay was skipped because cuDNN does not support the tested Blackwell configuration. - Changed-code lint, formatting, and whitespace checks passed. Whole-repository checks still report an existing Python import-order violation in fused_mla_q_uproj.py and missing license headers in the untracked nccl_ep directory. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Share tensor descriptors, SDPA construction, graph lifecycle stages, diagnostics, and score-modification cache utilities between PyTorch and JAX. Keep allocation, quantization, RNG, and execution in framework adapters. Separate support checks from compilation, fix JAX anonymous callback cache keys, preserve empty ragged capacities, and align frontend requirements and documentation. Validation: editable PyTorch build succeeded. Attention and Flex suites reported 2,877 passed and 2,426 skipped; both checkpoint-loading failures passed on retry with NVTE_ALLOW_UNSAFE_PICKLE_EXTRA_STATE=1. Pre-commit, Python lint, license checks, and JAX descriptor checks passed. JAX build and runtime validation remain for a separate session. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Restore bucketed total-token bounds for FP16/BF16 packed backward graphs and forward Q and KV bounds independently to preserve mixed layouts. Extend graph reuse coverage to backward and compare packed and mixed layout outputs and gradients against FP32 SDPA. Update the torch.compile backend-selection regression to patch the Python support probe after removal of the C++ binding. Pin each JAX build's runtime cuDNN Frontend dependency to the distribution supplying its build headers while retaining the minimum supported version. Document the exact-version requirement and test generated dependency metadata for frontend versions 1.29.0 and 1.30.0. Validation: 382 compile tests passed, 24 skipped, and 1 xpassed; 34 focused attention tests and 3 dependency-metadata tests passed. Pre-commit, JAX Python lint, and changed-file license checks passed. JAX runtime validation was unavailable because JAX is not installed. Full PyTorch lint and repository license checks report existing issues in unrelated files and untracked nccl_ep headers. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Address the remaining issues from PR NVIDIA#3289 in the shared cuDNN graph paths. Key plain callbacks on their code and typed snapshots of positional and keyword defaults so callbacks with different graph structure cannot reuse the same cached plan. Disable implicit caching for tensor, opaque, or recursive defaults while retaining the explicit structural-key protocol. Apply dense per-sequence statistics and dimensions throughout the SM12x family in common C++, PyTorch, and JAX. Share the Python layout predicate with context-parallel LSE handling and extend the related backend gates. Add forward/backward cache-lookup regressions for code and default changes, SM121/SM129 layout and eligibility coverage, an SM130 control, and matching JAX configuration tests. Document the caching and statistics conventions. Validation: - Rebuild the editable PyTorch installation with its cached configuration. - Compile suite: 382 passed, 24 skipped, 1 xpassed. - Focused attention regressions: 93 passed. - Common C API: four FP16/BF16 dense/packed support queries passed. - Two-GB200 THD context-parallel forward/backward regression passed. - Pre-commit, C++ lint, JAX Python lint, and changed-file license checks passed. JAX and physical SM121 runtime validation were unavailable. PyTorch Python lint still reports the pre-existing import-order issue in fused_mla_q_uproj.py. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Use the shared architecture predicate for JAX Max tensors and PyTorch fake saved statistics. Add regression coverage for SM121 and SM129 alongside neighboring architecture families. Validation: 19 focused JAX tests, pre-commit, and both Python lint suites passed. PyTorch tests require the unavailable torch package. The license check reports existing untracked nccl_ep headers. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Retain both the SM12x fused-attention restriction tests from py-all and the FA4 D=256 sequence-metadata eligibility tests from main. Validation: 19 focused JAX attention tests, pre-commit on overlapping files, and PyTorch Python lint passed. PyTorch runtime tests could not collect because torch is unavailable. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
|
@greptile full review |
[High impact] The latest change appears safe to merge; the two earlier concerns remain non-blocking. FindingsSummaryMoves PyTorch and JAX attention to shared cuDNN Frontend Python graph helpers.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
PT[PyTorch attention] --> Shared[Shared Python graph helpers]
JAX[JAX attention] --> Shared
Shared --> PTExec[PyTorch graph execution]
Shared --> Plans[Serialized cuDNN plans]
Plans --> FFI[JAX native FFI execution]
Reviews (48) · Last reviewed commit: "Size K and V from their lengths in the d..." · Reviewed by Greptile |
Restore specialized FP16/BF16 THD learnable-softmax kernels before cuDNN 9.26 and reject all affected FP8 THD sink-token backward paths in JAX. Preserve the FP16/BF16 backward fallback. Skip fills for fully written JAX outputs while retaining initialization for ragged buffers and unwritten optional results. Add support-policy, buffer-binding, and numerical regression coverage, and document the version restrictions. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
|
@greptile full review |
Temporarily expose the checkout root while importing build_tools so the new tests collect from the CI working directory. Restore the import path immediately to preserve installed-package resolution. Validation: all three tests pass with direct pytest and from the JAX CI working directory; import-path restoration and git diff --check pass. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Match the existing backend policy when the Python execution test forces cuDNN. Skip deterministic training below SM90 before disabling the fallback backends. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Centralize operand directions, scale padding and reordering, alignment checks, and known backend exclusions. Adapt the existing PyTorch preparation without changing tensor ownership or GPU execution. Validation: 14 JAX metadata tests and changed-file pre-commit checks pass. PyTorch runtime validation is unavailable in this JAX environment. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Expose fp8="mxfp8" through fused_attn and Flax modules. Prepare independent contraction-axis quantizations and per-head reordered E8M0 scales using existing common quantization kernels, then execute shared MXFP8 graphs through the existing JAX FFI executor. Validation on four GB200 GPUs with cuDNN 9.26 / Frontend 1.29: 30 focused MXFP8 tests and 15 existing attention regressions pass. Changed-file pre-commit and focused JAX pylint pass. Full license checking encounters existing failures including untracked nccl_ep headers. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Support packed QKV/KV storage, GQA masks, sliding windows, sink softmax, unequal head dimensions, and deterministic execution. Keep original model-precision dO layout and use the common fused quantizer for columnwise operands to avoid constant-zero NaNs in the pure-JAX fallback. Validate 60 focused cases across these capabilities, FP16/BF16 backward, and checkpointing on GB200 with cuDNN 9.26. Add explicit SM12x and dropout exclusions. Changed-file pre-commit and focused JAX pylint pass. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Accept independent rowwise/columnwise ScaledTensor2x operands alongside model-precision gradient targets. Consume supplied FP8 buffers directly in the shared cuDNN graph, reorder scales after partitioning, and preserve original operands for model-precision backward. Add quantize_attention_qkv, API documentation, and nine passing GB200 tests for packed layouts, both backward modes, supplied values, validation, and two-GPU data/tensor sharding. Focused JAX pylint and changed-file pre-commit pass. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Decode supplied MXFP8 operands before model-precision Ring/AllGather communication and quantize each local attention step. Support packed storage, causal load balancing, prequantized Flax BSHD/SBHD calls, checkpointing, and vmapped training. Preserve scale boundaries for replicated, data-parallel, and tensor-parallel execution. Reject the confirmed cuDNN Frontend 1.29.0 backward scale-stride defect for Q/K heads wider than 128 in the shared graph builder. Model-precision backward remains available via NVTE_FP8_DPA_BWD=0. Validation on four GB200 GPUs (SM100), cuDNN 9.26 / Frontend 1.29.0: full focused suite passes 109 tests, followed by 15 final checks including the added replicated-mesh case (110 distinct MXFP8 cases total). Existing attention, score-modification, and build-tools regressions: 58 passed, one skipped. JAX Python lint, changed-file pre-commit, and changed-file license checks pass. Tree-wide license checking encounters existing failures; PyTorch runtime validation is unavailable in this environment. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Query fused attention backend support before running FP8 tests instead of assuming Hopper supports FP16/BF16 outputs. Preserve cuDNN rejection reasons and match context-parallel queries to their per-device shapes and layouts. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Validate model-precision backward graphs when NVTE_FP8_DPA_BWD=0, retaining the original QKV layout and nominal dtype. Normalize inference dropout before preparing runtime graph inputs. Add regression coverage for FP8 backward selection and inference output against zero-dropout execution and FP32 SDPA. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Map paged K/V dimensions to BHSD consistently with their strides. Add FP16/BF16 regression coverage for all six paged layouts against FP32 SDPA. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Keep both JAX API documentation additions and preserve ragged-attention and configurable-device imports. Retain the shared cuDNN graph helpers and port configurable device checks and device-index normalization into the shared PyTorch adapter. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Return No_Backend instead of raising from PyTorch and JAX backend selection when the cuDNN frontend package is missing, its version does not match the C++ build, or it rejects the graph with a frontend error. Report a clear error when building TE/JAX without nvidia-cudnn-frontend. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Resolve NVTE_FUSED_ATTN_CACHE_DEBUG and the rank filter once, on first use, instead of re-reading the environment on every cache event in the attention hot path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Restore the original handling in PyTorch and JAX backend selection: only a configuration rejected by cuDNN falls back to another backend, while a missing frontend, a frontend version mismatch, or a device failure is raised. Falling back hid broken installs behind a silent switch to unfused attention and broke test_fused_attn_query_propagates_setup_errors. This reverts the attention changes from cad3188 and keeps its build_tools/jax.py error message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
| bottom_right = "bottom_right" in mask | ||
| left, right = p["window_size"] or (-1, -1) | ||
| if not causal and (left, right) == (-1, -1): | ||
| bottom_right = False |
There was a problem hiding this comment.
Can you check if our default is bottom_right=True or False please? For example, https://github.com/vcherepanov-nv/TransformerEngine/blob/346d18b67d90e2e31de5850040cd5719621a2bdf/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py#L772
There was a problem hiding this comment.
The public DotProductAttention argument defaults to None. Plain causal and padding_causal resolve to False (top-left), and the *_bottom_right masks resolve to True. Other masks preserve an explicit setting and fall back to True. The False here canonicalizes the cuDNN graph option for full noncausal attention, where there is no causal or sliding-window band to align.
There was a problem hiding this comment.
"Other masks preserve an explicit setting and fall back to True." - should we preserve the True value as default then? What about "no_mask" + ALIBI (which has top left/bottom right diagonals)? I think "padding" doesn't work with any bias, so probably not a problem. The question is, why don't we keep the default the same as "main"? If window size is (20,2), I think we want to do it as bottom_right=True as well, even if causal = False.
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
| if attn.fp8: | ||
| do_scale_fmt = name(QKVFormat, config.do_scale_inv_format) or dofmt | ||
| scale("descale_do", "do", do_scale_fmt) | ||
| if attn.mxfp8: |
There was a problem hiding this comment.
I still feel a bit confused sometimes about the relationship between .fp8 and .mxfp8. I feel sometimes it's that fp8 includes ds, cs, mxfp8, and sometimes, fp8 is only ds and cs. Maybe my understanding is wrong but please make sure there's no major inconsistencies regarding this.
There was a problem hiding this comment.
I checked the support-query and execution paths. In both, fp8 means the graph uses FP8 Q/K/V, including MXFP8. mxfp8 selects block scaling, and fp8 and not mxfp8 selects the tensor-scaled delayed/current paths. The shared builder maps those cases to sdpa_mxfp8 and sdpa_fp8, respectively. The flags describe each pass independently, so an FP8 forward can still use the model-precision graph for backward.
There was a problem hiding this comment.
"In both, fp8 means the graph uses FP8 Q/K/V, including MXFP8." - is this true for Jax as well?
Also, if mxfp8 is a variant of fp8, what warrants it a separate "arg"? Why not just have mxfp8 be a value of the fp8 option? (Just an idea, no need to make the change if it's not appropriate - or, making the change in a future PR is ok too.)
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
| valid = jnp.arange(rows)[None, :] < lengths[:, None] | ||
| dense = jnp.take(value.reshape(-1, heads, 1), indices, axis=0, mode="fill", fill_value=0) | ||
| dense = jnp.where(valid[:, :, None, None], dense, 0) | ||
| return dense.transpose(0, 2, 1, 3) |
There was a problem hiding this comment.
Re _dense_stats_to_packed and _packed_stats_to_dense:
I don't think we're doing this on "main"? If it's a conversion between BHS1 and BSH1 (i.e. TH1, where T=BS), cuDNN can take different strides for them without doing the transposes. These small kernels might cost too much.
There was a problem hiding this comment.
The old JAX path passed the dense statistics buffer from forward to backward. Here the conversion also maps each segment row to offset[segment] + row, so a fixed stride only works when the segment starts have fixed spacing. cuDNN Frontend 1.31 rejects ragged LSE for THD backward on SM12x. I forced the dense-statistics path on a GB200 and profiled a JIT-compiled THD forward/backward with runtime segment offsets. It used two packing kernels (fill and scatter) and one fused unpacking kernel, with and without CUDA command buffering. Carrying the dense statistics directly into backward would remove this round trip for ordinary training. The end-to-end cost on SM12x remains to be measured.
There was a problem hiding this comment.
I don't think I quite understand this, but let's discuss it for the next PR. At worst, we're calling some extra kernels here for sm12x + THD and the blast radius is not as wide.
cyanguwa
left a comment
There was a problem hiding this comment.
I feel the new tests are still a bit messy but we can work on cleaning them up and giving them more of a structure later. At least some of the important features are getting tested, like MXFP8 on the Jax side and some of the graph caching related things.
I left a few more comments - mostly minor - please try to address them and run CI again. I'm happy to give it a quick review and approve. Thanks!
Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
Yeah, at this point I'd prefer to defer this to a follow-up. My main concern - ideally, after tests cleanup / refactoring, we'd want to collect CI stats re test skips, etc, again, making sure no decrease in coverage. Not sure if enough time for this now. |
The DotProductAttention case of test_current_device uses packed THD tensors on a GPU other than the current device. Since 41fb9bc, it generates query and key/value sequence lengths independently, but allocates all three input tensors using the final query offset. When the final K/V offset exceeds the query token count, the K/V metadata describes rows beyond the allocated inputs. cuDNN uses those offsets to address K and V in forward and their gradients in backward. In a controlled GB200 probe with two allocated K/V rows and metadata describing 18, both the Python cuDNN frontend and the legacy C path read past the logical V tensor and wrote 512 dV values into guard rows beyond the declared gradient shape. CUDA launches are asynchronous, so the attention case can report success before a later operation surfaces the error. In the two affected H100 CI runs, Linear reported a cuBLAS launch failure after the attention case, and GroupedLinear then reported a sticky CUDA illegal-address error during parameter initialization. The random lengths and GPU allocation layout can affect whether the invalid accesses become visible. The GB200 probe confirms the bounds violation. The precise origin of the H100 errors was not captured by those traces. Use the last query offset for the Q allocation and the output gradient. Use the last K/V offset for both K and V so the packed allocations cover the rows described by their metadata. The test continues to exercise independent sequence lengths and checks that forward and backward keep tensors on the target GPU while preserving the caller's current device. Validation - Run all five distributed sanity tests on two GB200 GPUs with NVTE_FLASH_ATTN_V4=0. All five pass. - Force the edited test through cuDNN with query lengths [1, 1] and K/V lengths [9, 9]. Verify the two-row Q and dO buffers, the 18-row K, V, dK, and dV buffers, and successful synchronized forward and backward. - Pass the applicable pre-commit hooks and git diff --check. Signed-off-by: Vladimir Cherepanov <vcherepanov@nvidia.com>
cyanguwa
left a comment
There was a problem hiding this comment.
Thanks for the latest changes. Please make sure CI passes and also the number of tests passed/skipped still matches "main". Thanks.
Description
Migrate PyTorch and JAX cuDNN attention to the cuDNN Frontend Python API,
with shared graph-building helpers and framework-specific execution.
The public C attention APIs remain available for compatibility but are now
deprecated. The migrated PyTorch and JAX attention paths no longer call them.
Type of change
Changes
and cache diagnostics across PyTorch and JAX.
current scaling) and block-scaled MXFP8.
precompiled cuDNN plans.
Q/K/V and supported context-parallel configurations. JAX attention rejects
delayed and current tensor scaling.
regression coverage for dropout replay and backward precision.
cuDNN cannot currently serialize those plans for execution through the
native executor.
Checklist: