Skip to content

feat(adaln): add indexed CUDA/Triton modulation and explicit strict qualification - #621

Merged
maxiaosong1124 merged 46 commits into
RL-Align:test-qwenimagefrom
hongleng:feat/adaln-indexed
Nov 20, 2026
Merged

maxiaosong1124 merged 46 commits into
RL-Align:test-qwenimagefrom
hongleng:feat/adaln-indexed

Conversation

@hongleng

@hongleng hongleng commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add dedicated CUDA and NVIDIA Triton FP32/BF16 forward/backward for indexed AdaLN, extending the shared implementation in #559. Each token selects one of two per-sample modulation banks, applies parameter-free LayerNorm followed by scale/shift, and returns the selected gate separately.

Backend dispatch selects CUDA, Triton, or the existing framework select01 fallback according to availability and supported input domains. Valid inputs outside the dedicated backend domain retain ordinary fallback.

Implementation

  • Accept modulation [2B,3H] and Boolean/integer 0/1 routes [B,S] or batch-broadcast [1,S]. Return modulated output and gate [B,S,H], with gradients to the input and both modulation banks.
  • Use fixed FP32 hidden reductions and ascending selected-token folds for modulation gradients, preserving gate bits and the distinction between absent and explicit-zero upstream gradients. Accuracy and byte equality use separate independent references.
  • Support H ≤ 4096 and B ≤ 65535 within the documented eps/addressing domain. Public Python wrappers accept supported strided/expanded inputs and upstreams by making contiguous copies; the underlying CUDA/Triton kernels operate on contiguous storage.
  • Validate the execution domain before copies or kernel allocations, and report the actual backend and fallback per validation CLI case.

See the operator contract at this PR revision for the full numerical and dispatch behavior.

Validation & Performance

H100 NVL/SM90 validation recorded 720 correctness node calls and 1,408 sanitizer node calls, including CPU policy/boundary checks. All recorded phases passed, with no skips/xfails. Both backends were checked with memcheck, racecheck, initcheck and synccheck, with no reported errors, hazards or warnings in the tested configurations. These tools ran locked small-matrix subsets at default launch settings; H3072 workloads and alternate launch settings have separate correctness coverage.

Correctness checks cover independent output/gradient accuracy, fixed bytes, routing, views, upstream semantics, large offsets, H3072 workloads, shared regressions and explicit strict activation.

The indexed benchmark covers 18 cases across FP32/BF16, small inputs and H3072 image workloads. Warm wall-time speedups against framework select01 are ranges of per-case median ratios:

Measured surface CUDA Triton
Direct forward 1.650–6.360× 1.670–5.348×
Direct backward-only 1.082–3.796× 1.348–3.440×
Direct forward+backward 1.363–2.802× 1.651–2.714×
Dispatch forward+backward 1.365–3.034× 1.654–2.889×

These are whole-call measurements from one successful process using eps=7, including applicable validation, copies, allocations and autograd. Latency and memory gains vary by case; the linked performance report contains sample variation, memory tradeoffs and first-use/JIT costs. These are operator-level measurements rather than model-level training benchmarks.

The published GPU results apply to source 5490223a850fe9cb1efd5c3cceeb0fb964ee5c1c. Current HEAD 496324d additionally includes formatting, device-context guards for shared/indexed Triton forward launches, CLI backend reporting, and test coverage for optional and required extensions; kernel arithmetic is unchanged. Focused CPU checks for the device-guard follow-up recorded 70 passed / 42 skipped with GPUs hidden. The subsequent changes have not been revalidated on H100, and the new two-GPU regression remains unexecuted.

Dependencies & Limitations

#559 remains open. This PR targets test-qwenimage, so its diff includes the shared parent implementation.

The GPU evidence uses a fresh AdaLN-only extension built from production sources/bindings in the recorded H100 environment; full-extension build/link integration remains unvalidated.

Indexed strict qualification remains default-closed. Execution requires an explicit backend/target/runtime scope following external evidence review; the published qualification record does not activate it.

Evidence

Merge Danger

Door: two-way

Reverting removes the operator/backend additions; no persisted data migration is involved.

Blast Radius: operators

Adds native symbols and AdaLN runtime/validation paths, including the shared parent changes. Valid unsupported indexed inputs retain explicit ordinary fallback; strict rejects unqualified execution. Successful-forward trace metadata is not backward, profiler or binary-attestation evidence. Evidence is linked above. Qualification evidence acceptance is limited to the disclosed target/build/matrix; no runtime scope is installed or enabled by this PR.

Summary by CodeRabbit

  • New Features
    • Added AdaLN modulation with shared and indexed modes, including forward and gradient support across PyTorch, Triton, and CUDA backends.
    • Added backend selection with fallback for unsupported execution domains, plus strict-mode qualification for indexed execution.
    • Added a benchmark for comparing AdaLN backend performance and memory use.
    • Operator validation reports now show the selected backend and fallback details.
  • Documentation
    • Added AdaLN usage, behavior, and validation guidance.
  • Tests
    • Expanded coverage for numerical accuracy, gradients, input validation, backend selection, and fallback behavior.

…n Fixes

- Updated CUDA kernel functions to accept a configurable number of threads (128, 256, or 512) for improved flexibility.
- Added synchronization after reading the reduction result in the fixed_sum function to prevent shared memory hazards.
- Modified the Python bindings and C++ interface to accommodate the new threads parameter in forward and backward functions.
- Enhanced documentation to include the new thread configuration options.
- Implemented additional tests to validate the behavior of the AdaLN modulation with different thread configurations and ensure numerical stability.
- Introduced a race condition check script to validate shared memory access in CUDA kernels.

Signed-off-by: hongleng-github <[email protected]>
- Deleted installation script for CUDA 12.6 on WSL.
- Removed verification script for CUDA 12.6 installation.
- Eliminated build extension script for CUDA-related extensions.
- Removed testing scripts for AdaLN CUDA extension.
- Deleted benchmarking script for AdaLN CUDA operations.
- Removed race checking script for AdaLN CUDA extension.

Signed-off-by: hongleng-github <[email protected]>
…servation

- Introduced strict dispatch and execution observations for AdaLN modulation, enforcing arithmetic profiles and backend qualifications.
- Added `AdaLNDispatch` class to manage execution traces and backend information.
- Updated `KernelRegistry` to support strict mode and handle arithmetic profiles.
- Enhanced backend provenance tracking in GTest to validate execution against declared profiles.
- Created tests for strict dispatch behavior, including validation of backend observations and error handling for unsupported profiles.
- Added benchmark tests for CPU checks and CLI contract validation.
- Refactored existing tests to ensure compatibility with new dispatch and backend observation mechanisms.

Signed-off-by: hongleng-github <[email protected]>
Rebase the existing AdaLN work onto fixed test-qwenimage revision 16b8117. Move reference, backends, dispatch, tests and benchmark into their canonical owners; preserve legacy module and stable operator identity, arithmetic, independent gold and shared precision thresholds.

Validation: 229 CPU-focused tests passed, 302 hardware/opt-in tests skipped; focused mypy, Ruff and BF16 H3072 forward/backward CLI passed. GPU builds, H100 tests, sanitizer, benchmarks and the repository-wide suite remain manual; updated commands are documented.
Signed-off-by: hongleng-github <[email protected]>
Delete the five AdaLN import/benchmark shims and their compatibility checks. Remove AdaLN-only local migration and identity aliases while keeping upstream compatibility and canonical implementations unchanged.

Validation: focused CPU regression 223 passed, 302 skipped; BF16 H3072 CPU forward/backward CLI, Ruff and diff checks passed. Migrated ten external local scripts, including a CPU-only probe (4 passed). GPU/H100 and full-repository validation were not run.
Signed-off-by: hongleng-github <[email protected]>
…backward_reduce_kernel

Signed-off-by: hongleng-github <[email protected]>
Remove automatic AdaLN provenance observation and retain generic trace snapshots, FP32 reference inputs and output dtype checks. Preserve comparison on the original device when candidate and gold share it.

Validation: op_checks 19 passed; AdaLN subset 333 passed; targeted mypy and Ruff passed. Full pytest stopped during collection on an unchanged ROCm import of _AITER_FWD_REQUIRED_KEYWORDS.
Signed-off-by: hongleng-github <[email protected]>
Restore non-AdaLN gold and candidate paths and unrelated import formatting to the fixed integration baseline. Preserve AdaLN registration, precision settings, independent reference and optional backend observation.

Validation: 65 focused tests passed; mypy, Ruff and diff checks passed. Both review axes reported no findings. Full pytest stopped during collection on the existing ROCm _AITER_FWD_REQUIRED_KEYWORDS import error.
Signed-off-by: hongleng-github <[email protected]>
Apply the test-only layout update from parent PR RL-Align#559 commit 38352b0. Move resolver and fallback policy cases into tests/runtime while retaining operator accuracy and invariance cases in tests/ops. Preserve existing test names, assertions and decorators.

Signed-off-by: hongleng-github <[email protected]>
Route supported B2/S8/H2 FP32 inputs with int32 indices through dedicated CUDA kernels. Preserve explicit framework fallback outside the slice and keep indexed strict execution rejected.

Add an independent CPU byte reference, literal VJP and token-order checks, and direct backend plus public dispatch coverage. Share FP32 eps eligibility and indexed trace construction, and isolate NVIDIA-only tests from ROCm.

Validation: bounded CPU-only regression passed with 135 passed and 305 skipped; targeted Ruff and diff checks passed. Historical SM86 evidence predates the Python refactors; current-source GPU acceptance, full-extension linkage, H100 and strict qualification remain pending.
Signed-off-by: hongleng-github <[email protected]>

Copy link
Copy Markdown
Contributor Author

Follow-up on the shared Triton _bwd_reduce FTZ finding in the OCR summary:

Checked against Triton 3.7.1. enable_reflect_ftz controls libdevice reflection, not ordinary FP32 addition globally. This kernel has no libdevice calls.

An offline SM90a compilation comparison produced identical cubins with the flag enabled and disabled for the checked FP32/BF16 configurations. Both use FP32 FADD without FTZ.

I don't see a numerical defect here. The missing flag could be added for consistency, but it is not a required correctness fix.

Copy link
Copy Markdown
Contributor Author

Follow-up on the index-validation stream claim in the OCR summary:

I checked the generated ATen wrappers in Torch 2.12.1. The validation operations select the tensor's CUDA device and use its current stream, rather than unconditionally running on the default stream.

The .item() host synchronization is real, as noted in my earlier reply, but moving CUDAGuard before validation would not eliminate it. Removing native value checks would leave direct _C callers without validation.

I'll keep the current ordering and checks.

Comment thread csrc/cuda/norm/adaln_modulation.cu Resolved
@Flink-ddd Flink-ddd added platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) new-model qwen labels Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on two findings in the latest OCR summary, checked against 496324d:

  1. Select01 BF16 gate: The FP32 round trip does change NaN payloads: a Torch 2.12.1 CPU check maps 0x7F81 to 0xFFFF. Framework select01 has no bitwise gate guarantee and is excluded from indexed strict execution. The bit-preserving indexed profile uses the separate IndexedAdaLNFixedReference and dedicated CUDA/Triton implementations. No select01 change is required by the current contract.

  2. Triton range(S): tl.constexpr specializes the bound; it does not force full unrolling. Retained H100 _fold IR/PTX for S=4096/6889/6032 contains runtime token loops and backedges, with 390–409 PTX lines per variant. Offline compilation of current _bwd_reduce with Triton 3.7.1 for SM90 at S=4096/6889 likewise produces runtime loops, both with 273 PTX lines. Switching to tl.range(S) is unnecessary. Per-S compilation is real and already documented.

Comment thread rl_engine/runtime/registry.py Resolved

Copy link
Copy Markdown
Contributor Author

Regarding the CUDA accumulation-order finding in the OCR summary:

The retained H100 build used source 5490223, nvcc 12.6.85 and -O3 --fmad=false --ftz=false. Its shared FP32 PTX updates the same two accumulators with add.rn.f32, advances one token and branches back; SASS retains the dependent FADD chains and backedge. Indexed FP32 likewise retains sequential selected-bank updates and loop backedges. Neither reduction's FP32 SASS contains FFMA or FTZ.

Interleaving independent shift/scale chains does not change either chain's summation order. The recorded shared FP32 byte comparisons and indexed cancellation/product-rounding tests passed. The CUDA source is unchanged at 259a66e. The compiled evidence supports the declared order for this pinned build; no kernel change is justified.

Comment thread csrc/bindings/ops.cpp Resolved
Comment thread csrc/cuda/norm/adaln_modulation.cu Resolved
Comment thread rl_engine/runtime/adaln.py Resolved

@Flink-ddd Flink-ddd 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.

LGTM

@maxiaosong1124

Copy link
Copy Markdown
Collaborator

please resolve the conflicts first, thx @hongleng

Comment thread build_tools/extensions.py
"csrc/cuda/activation/activation.cu",
"csrc/cuda/attention/deterministic_attention.cu",
]
adaln_cuda_enabled = not is_rocm and not envs.env_flag(envs.KERNEL_ALIGN_USE_FAST_MATH)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
The native AdaLN gate only checks KERNEL_ALIGN_USE_FAST_MATH and ignores externally supplied relaxed-math NVCC flags (NVCC_PREPEND_FLAGS/NVCC_APPEND_FLAGS/TORCH_NVCC_FLAGS). With e.g. NVCC_APPEND_FLAGS=--use_fast_math, csrc/cuda/norm/adaln_modulation.cu is still compiled and its #if defined(__CUDA_FAST_MATH__) #error (line 13) aborts the build; with --ftz=true/--prec-div=false the build succeeds but AdaLN's FP32 pairwise-tree results no longer match the exact reference (the doc claims no fast math). This is inconsistent with the joint_attn_softmax_enabled gating immediately below. Reuse the already-computed use_fast_math/relaxed_math_env values.

Suggestion:

Suggested change
adaln_cuda_enabled = not is_rocm and not envs.env_flag(envs.KERNEL_ALIGN_USE_FAST_MATH)
adaln_cuda_enabled = not is_rocm and not use_fast_math and not relaxed_math_env

@maxiaosong1124 maxiaosong1124 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.

LGTM!

@maxiaosong1124
maxiaosong1124 merged commit 1421a69 into RL-Align:test-qwenimage Nov 20, 2026
4 of 6 checks passed
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 20, 2026
…L-Align#538

Resolve additive conflicts in build_tools/extensions.py, csrc/bindings/ops.cpp
and rl_engine/runtime/registry.py by keeping both the final_adaln_out
(token_sum) entries and the upstream latent pack/unpack entries.

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 20, 2026
The pytest node IDs in tests/runtime/test_adaln_test_environments.py (from
RL-Align#621 on test-qwenimage) exceeded the 100-character limit, so the linting job
failed and unit-tests was skipped. Build them from per-module prefixes; the
selected tests are unchanged.

Signed-off-by: Wenbo Ji <[email protected]>
@hongleng
hongleng deleted the feat/adaln-indexed branch November 24, 2026 06:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-model platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) qwen

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants