Repository navigation
[WS1][Qwen-Image][CUDA/ROCm] Qwen-Image MLP down projection (mlp_down_gemm, CUDA) - #499
luoyueyuguang wants to merge 41 commits into
Conversation
Refs RL-Align#386; y = single_cast(x @ W^T + b), [*, 12288] -> [*, 3072], forward and backward. * feat(mlp_down_gemm): add the fp32 CPU reference and the two device contracts * feat(mlp_down_gemm): add the portable tree CUDA path, byte-equal to that reference * perf(mlp_down_gemm): add the Hopper TMA + wgmma path for the hardware-order contract * feat(mlp_down_gemm): add Triton, the contract selector and the registry entry * test(mlp_down_gemm): per-contract byte equality, invariance, accuracy and the backward * docs(mlp_down_gemm): add the operator page, the benchmark and the gtest inputs Two contracts, one per implementation. The portable one (mlp-down-gemm-tree-v1, the general CUDA path on fp32 CUDA cores, ~11 TFLOP/s) computes exactly the tree the fp32 CPU reference computes, so it is byte-equal to that reference (fwd/dx/dW/db, 0 mismatching bytes). The hardware one (mlp-down-gemm-mma-v1, Hopper TMA + wgmma and Triton, 448-476 TFLOP/s, byte-identical to each other) pins the tensor-core k16 chain, which no documented model reproduces bit for bit (best fit 6.755e-07 of elements), so it sits inside the declared tolerance of the reference instead. db is the ascending fp32 fold either way; the route report carries the contract and RL_KERNEL_MLP_DOWN_GEMM_BACKEND pins it. 129 tests pass on the SM90 build, 114 with 15 skipped on the default build. Signed-off-by: luoyueyuguang <[email protected]>
…nd the docs * fix(triton): normalize the bias before the launch. The kernel indexes it at unit stride, so a strided view was read at the wrong elements and the forward silently returned wrong values; the CUDA entry points already converted it. * fix(cuda): gate the Hopper path to compute capability 9.0 exactly, in C++ and in the wrapper. The wgmma body only exists under __CUDA_ARCH_FEAT_SM90_ALL, so a cc >= 10 build dispatched to an inert kernel instead of failing closed. * test(mlp_down_gemm): add the strided-bias and cc >= 10 regressions, cover backward at the 6889/6032 tiers by byte equality against the Hopper kernel plus the portable tree contract with db bit-exact against the fp32 fold, and extend forward byte equality to all three tiers. * docs(operators): drop the description of a `general` mma.sync kernel that is not in this PR, and its two benchmark rows; state the two contracts' byte relations and add the measured portable-tree numbers. * docs(operators): record why the C3/C4 scripts are not this row's gate, and spell out the ROCm qualification steps with their expected results. * docs(benchmarks): correct the extra-memory claim for the portable tree path. * chore(cuda): remove the orphaned db comments in mlp_down_gemm_sm90.cu. * test(mlp_down_gemm): 138 passed on an H100 80GB HBM3 (SM90 build, 129 before); gtest cuda and triton pass_rate=1.0000. Signed-off-by: luoyueyuguang <[email protected]>
* refactor(cuda): `mlp-down-gemm-mma` / `mlp-down-gemm-tree` are the ids now. The
`contract` vocabulary, `mlp_down_gemm_contract_used()` and the route line's
`contract=` field stay as they were.
* refactor(cuda): the constants are `MMA_CONTRACT` / `TREE_CONTRACT` on the CUDA side
and `MLP_DOWN_GEMM_CONTRACT` in the Triton and PyTorch modules, since the ids carry
no version any more.
* chore(cuda): drop the static `contract_version` attribute. It advertised the mma id
even on builds where every call takes the tree, contradicting
`mlp_down_gemm_contract_used()`, which is now the only source.
* chore(pytorch): drop the unused `ROW_CONTRACT_VERSION` and the two tests that
asserted a constant equals its own literal.
* fix(triton): gate the device on `device.type in ("cuda", "hip", "xpu", "musa")` and
raise RuntimeError, as the sibling Triton ops do; `is_cuda` rejected the MUSA slot
the registry routes to this backend.
* docs(operators): update the ids on the operator page; the `## Contract` section and
the `## Tensor Contract` heading keep their wording.
* test(mlp_down_gemm): 138 passed on an H100 80GB HBM3 (SM90 build); gtest cuda and
triton pass_rate=1.0000; the route line reads
`... reason=general_is_the_portable_tree_contract (...) contract=mlp-down-gemm-tree`
when pinned to `general`.
Signed-off-by: luoyueyuguang <[email protected]>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
mlp_down_gemm, CUDA)mlp_down_gemm, CUDA)
…p-down-gemm Bring the PR RL-Align#497 layout refactor ("organize models, backends, contracts and train and rollout engines") onto the WS1 MLP down projection row. The row's three commits keep their content; only its placement follows the refactor's ownership rules. Conflicts (5 files) and how each was resolved: * rl_engine/kernels/registry.py, rl_engine/kernels/gtest/operator_inputs.py and rl_engine/kernels/gtest/operator_specs.py: take the refactor's content. Those paths are compatibility shims now, so the row is not added there; its registrations move to rl_engine/runtime/registry.py (the OpBackend entries plus the cuda, rocm, musa and cpu priority maps) and to rl_engine/validation/operators/{operator_specs,operator_inputs}.py. * setup.py: take the refactor's thin entry point; the row's two native sources go into build_tools/extensions.py, which owns the source lists now -- csrc/cuda/gemm/mlp_down_gemm.cu in cuda_sources and csrc/cuda/gemm/mlp_down_gemm_sm90.cu in sm90_srcs. * docs/benchmarking/README.md: keep the refactor's paths and list the row's benchmark at its new path. Placement of the row, per docs/contributing/contributor-guide.md: * rl_engine/kernels/ops/cuda/linear/mlp_down_gemm.py -> rl_engine/backends/cuda/gemm/mlp_down_gemm.py * rl_engine/kernels/ops/pytorch/linear/mlp_down_gemm.py -> rl_engine/reference/gemm/mlp_down_gemm.py * rl_engine/kernels/ops/triton/linear/mlp_down_gemm.py -> rl_engine/backends/shared/triton/gemm/mlp_down_gemm.py * tests/test_mlp_down_gemm.py, tests/test_mlp_down_gemm_triton.py -> tests/ops/gemm/ * benchmarks/benchmark_mlp_down_gemm.py -> benchmarks/operators/gemm/benchmark_mlp_down_gemm.py The moved implementations, the operator page, the benchmark, the WS1 gtest launcher and the WS1 GPU workflow now import/name the canonical modules (rl_engine.backends.cuda.gemm, rl_engine.reference.gemm, rl_engine.backends.shared.triton.gemm, rl_engine.runtime.registry, rl_engine.validation.operators.*, rl_engine.backends.extension, rl_engine.ops.autograd.backward_runtime, rl_engine.runtime.policy). No new implementation is left under a compatibility path; the row has no legacy imports of its own to preserve. The row is also listed in benchmarks/README.md and in the WS1 GPU gate (ci/scripts/run_ws1_gtest.sh, .github/workflows/ws1-gtest-gpu.yml), the way the sibling mlp_up_gemm_gelu row is listed. Verification: * CPU checkout: `python -m pytest tests/runtime -q` 78 passed, 2 skipped; `python ci/run.py layout -q` 32 passed, 1 skipped; `tools/validation/operators/check_operator.py --op mlp_down_gemm --candidate pytorch --device cpu --dtype fp32 --check-grad` pass_rate=1.0000. * H100 80GB HBM3, SM90 build (KERNEL_ALIGN_FORCE_SM90=1, nvcc exit 0): `pytest tests/ops/gemm/test_mlp_down_gemm.py tests/ops/gemm/test_mlp_down_gemm_triton.py -q` 138 passed; the row's cases in `tests/validation/operators/test_ws1_gtest_gpu.py` 3 passed; `benchmarks/operators/gemm/benchmark_mlp_down_gemm.py --help` exits 0. * Known pre-existing failure, unrelated to this row: on a CUDA build `tests/runtime/test_attention_dispatch.py::test_registered_backend_resolves_with_provenance` fails (provenance["fallback"] is True). It fails identically on the refactor tip without this row, and passes on the CPU-only run. Signed-off-by: luoyueyuguang <[email protected]>
…ntry points f41c907 dropped the -v1 suffix from the two contract ids, but the two comments and the six m.def docstrings in csrc/bindings/ops.cpp still advertised mlp-down-gemm-tree-v1 / mlp-down-gemm-mma-v1, so help() on the extension named ids that no constant, route report or operator page uses any more. Verified on the H100 SM90 build: the incremental relink exits 0 and _C.mlp_down_gemm_cuda_forward.__doc__ now ends with mlp-down-gemm-tree, with no -v1 left among the mlp_down_gemm* entries. Signed-off-by: luoyueyuguang <[email protected]>
The merged tree is now under the refactor's checks, and the row was the only source of black/isort/flake8 findings in the repository (pre-commit on the refactor tip is clean over all 1032 files): black 24.4.2 reformats the row's modules, tests and benchmark, isort flags the CUDA wrapper's import block, and flake8 reports 11 E501 plus one E402, all in the row's files. * black and isort applied to the row's 11 Python files (line length 100). * cuda backend: hoisted `rl_engine.runtime.policy` into the top import block (E402). runtime.policy imports stdlib only, so the move introduces no cycle. * cuda/triton _grads_for_test: take the grads from `torch.autograd.grad` instead of `x.grad`/`weight.grad`, which mypy types as `Tensor | None`; the row was the only source of new mypy errors over the refactor tip (14 -> 16). * benchmark: wrap the usage example that the longer operators/ path pushed past 100 columns. Verified: `pre-commit run --all-files` passes all seven hooks; black --check, isort --check-only and flake8 are clean repo-wide; mypy --ignore-missing-imports rl_engine/ reports exactly the refactor tip's 14 pre-existing errors; `mkdocs build --strict` exits 0; on an H100 80GB HBM3 SM90 build the row's suites report 138 passed and the row's WS1 GPU gate cases 3 passed, with the remote tree md5-identical to this commit's files. Signed-off-by: luoyueyuguang <[email protected]>
|
@zhangj1an PTAL, Thank you. |
|
please resolve DCO error first, thx! @luoyueyuguang |
|
🔍 OpenCodeReview found 5 issue(s) in this PR.
📄
|
|
@luoyueyuguang The automated OCR review has completed. Please review and address all automated review bot findings, then push your updates. Maintainers will begin manual review after the bot findings have been addressed. |
6965889 to
cf3bb34
Compare
Guard the db fold against a zero-width gradient before dividing by cols, match the ROCm declaration guard on the pybind registrations, round a non-bf16 cotangent once in the CUDA backward (db included), and restore x's leading dims on the reference grad_x. Adds a CPU regression test for the batched backward shape. Signed-off-by: luoyueyuguang <[email protected]>
e94e77f to
bfe3355
Compare
…rker The ROCm guard's closing comment still said `!USE_ROCM` after the guard was widened to `!USE_ROCM && !KERNEL_ALIGN_WITH_ROCM`, and the new route-helper test carried the CUDA marker twice. Detach the reference in the deviation helper so a grad-enabled reference no longer warns when measured. Signed-off-by: luoyueyuguang <[email protected]>
Classify operands without raising in the route helpers under a hopper pin (strict=False), apply the row's CUDA selector to the device get_op actually dispatches to (not only the process default), report an unserved pin from the Triton route line with fallback=true plus a warning, clear the ambient pin in the default-auto test, and replace the false 'bit-identical below K=128' claim with the measured one-ulp bound in the comments, tests and docs page. Signed-off-by: luoyueyuguang <[email protected]>
Suppress the benchmark's TFLOP/s for the fp64 reference at every row count, log a valid-but-not-process-default selector instead of dropping it silently, and make the dispatch-time pin fail closed with a pin-specific diagnostic when the native CUDA backend cannot be constructed (instead of a generic 'no backend' error). Signed-off-by: luoyueyuguang <[email protected]>
Mirror the Triton operand-rank guards in the CUDA entry point (2-D weight, 1-D bias) so a 3-D weight or broadcastable 2-D bias is rejected at the Python boundary instead of reaching C++, and document and test that the CPU runtime row's reference is not a validation candidate (validation never compares the gold with itself). Signed-off-by: luoyueyuguang <[email protected]>
State the Hopper gate's real requirement (K and N multiples of 8, as the C++ entry checks) instead of a row-stride rationale that only names K, and document that an empty row count is returned before any TMA/wgmma launch (with a pinned empty-batch test). Mirror the operand-rank guards in the fp32 reference so the gold rejects malformed operands the way both device backends do. Signed-off-by: luoyueyuguang <[email protected]>
Derive the MN-major TMA box from the geometry's BK instead of hard-coding 64x64 (so a BK=32/SWIZZLE_64B instantiation cannot build a mismatched map), document that this row's only registry-level eligibility check is backend instantiation (the per-call arch/dtype/alignment gate lives in the op), and exercise the real _get_or_create_backend None contract in the pin-failure test. Signed-off-by: luoyueyuguang <[email protected]>
Keep the row's selector dispatch-time only: the priority map no longer takes a construction-time snapshot, so setting or releasing the pin after registry construction cannot leave a sticky CUDA-only order (with a live-env regression test). Document that the Triton-first ordering's byte-parity evidence is Hopper-specific, with pre-Hopper Triton covered by the tolerance gate. Signed-off-by: luoyueyuguang <[email protected]>
Fail closed when the CUDA selector cannot be served on the dispatch platform (CPU still accepts 'general', where the reference itself is the tree contract), require the exact cc 9.0 tuple in both the Python route gate and the C++ sm90 device gate (sm_90a only), and note that the row's listed bias gradient is compared, not skipped. Signed-off-by: luoyueyuguang <[email protected]>
Re-emit the route report when the operand-dependent (requested, actual, contract) route changes instead of latching the first call's shape, include weight.dtype in the Hopper gate so the reporting helpers match the kernel, require cc (9, 0) in the backward_impl hint, and parse the selector once per dispatch so the branch and its diagnostic cannot disagree. Signed-off-by: luoyueyuguang <[email protected]>
|
My account has no access to rerun it. Could someone with admin rights hit Re-run jobs on run 43240075310 (https://github.com/RL-Align/RL-Kernel/actions/runs/43240075310)? Note the failure is the 500k token budget, so a rerun may hit it again. |
|
please resolve the conflicts first, thx! @luoyueyuguang |
Signed-off-by: luoyueyuguang <[email protected]>
Signed-off-by: luoyueyuguang <[email protected]>
Signed-off-by: luoyueyuguang <[email protected]>
`mlp_down_gemm_cuda_dw_sm90` only short-circuited when the output matrix was empty. With S == 0 and Ng/Kx > 0 the output is nonempty while the reduction is empty, so it built a 0-row tensor map and `cuTensorMapEncodeTiled` raised instead of returning the zeros the tree path and the reference produce. Guard S == 0 before the TMA/wgmma setup. Add the Hopper empty-batch backward case to the GPU suite. Signed-off-by: luoyueyuguang <[email protected]>
The NPU map literal was overwritten wholesale by the CPU copy two statements later, and its comment claimed a runtime CPU fallback that does not exist: dispatch reads the row with `.get(op_type, [PYTORCH_NATIVE])`, so an explicit empty list stays empty and `get_op` raises. Replace the dead literal and the stale comment with the actual flow. Add a regression test asserting the NPU row is empty and that dispatch on NPU raises instead of serving the fp32 reference. Signed-off-by: luoyueyuguang <[email protected]>
Signed-off-by: luoyueyuguang <[email protected]>
|
Hi, @maxiaosong1124. Conflicts resolved. As long as there are no new changes to registry.py, it should stay conflict-free. Looking forward to another review — thanks! |
The RL-Align#538 merge dropped the `for platform in ("rocm", "npu", "musa"):` header and left `qwenimage_final_adaln_out` at an orphaned indentation, which made registry.py fail to parse (flake8 E999). Restore the loop from the base (likely conflict resolution dropped the header). The MLP down NPU fail-closed line stays right after it. Signed-off-by: luoyueyuguang <[email protected]>
… merge Signed-off-by: luoyueyuguang <[email protected]>
[WS1][Qwen-Image][CUDA/ROCm] Qwen-Image MLP down projection (
mlp_down_gemm, CUDA)Summary
Adds the Qwen-Image MMDiT feed-forward down projection as a WS1 row — the
mlp_down_gemmrow of #386 — plus its Triton backend, an FP32 reference, a benchmarkand the operator page. Both streams have the same shape (
img_mlp.net.2,txt_mlp.net.2), so one row covers both.Forward and backward (
dx,dW,db) are implemented on every path.Two implementations ship, and they do not produce the same bytes. The portable fp32
tree on CUDA cores matches the fp32 reference byte for byte; the tensor-core path
(Hopper TMA+wgmma, and Triton) is byte-identical to itself and sits inside the
declared tolerance of the reference. Tensor cores cannot compute a tree, so the tree
is what buys byte equality and the tensor-core path is what makes it fast. Both are
frozen and carry a contract id the row reports —
mlp-down-gemm-tree/mlp-down-gemm-mma.autotakes the tensor-core order only when the SM90 build anda cc 9.0 device are present;
mlp_down_gemm_contract_used()returns the id a calltook, and the row prints it once per process as
[RL-Kernel][route] ... contract=....csrc/cuda/gemm/mlp_down_gemm.cu, 749 lines)mlp_tree_kernel(byte-equal to the fp32 reference) plus thedW/dbfolds; always compiled, sm80+.csrc/cuda/gemm/mlp_down_gemm_sm90.cu, 691 lines)wgmma.mma_async,STAGES=4,KG=1; built only withKERNEL_ALIGN_FORCE_SM90=1.rl_engine/kernels/ops/triton/linear/mlp_down_gemm.py, 549 lines)input_precision="ieee"; also the ROCm/MUSA slot.rl_engine/kernels/ops/pytorch/linear/mlp_down_gemm.py)dx/dW/dbVJP.rl_engine/kernels/ops/cuda/linear/mlp_down_gemm.py)registry.py+22,csrc/ops.cpp+49 (7 symbols),setup.py+7,_C.pyi+11.operator_specs.py+12,operator_inputs.py+18,tests/test_ws1_gtest_gpu.py+3.19 files, +5461/-0. No existing code path changes: the ten pre-existing files only
gain lines.
Implementation
csrc/cuda/gemm/mlp_down_gemm.cu(749 lines):mlp_tree_kernelstages one 32-wideleaf per stage and replays the reference's mid-split tree through a per-thread
level array, so a row's bytes depend only on K. Also
mlp_down_dw_left_fold_kerneland
mlp_down_db_fold_wide_kernel. Always compiled, sm80+.csrc/cuda/gemm/mlp_down_gemm_sm90.cu(691 lines): TMA 2-D bulk-tensor stagingdriving
wgmma.mma_async(m64n256k16forward,m64n128k16fordx/dW), onefp32 accumulator chain in ascending k16 order, no split-K, no atomics. Built only
with
KERNEL_ALIGN_FORCE_SM90=1.rl_engine/kernels/ops/triton/linear/mlp_down_gemm.py(549 lines): three pinnedtiles,
input_precision="ieee",do_not_specialize=["M"]; one program per outputtile walks the whole reduction. This is also the ROCm/MUSA slot.
Tensor::to(kFloat), exact) for thetree, normalize the bias, add it once in fp32 after the reduction and store bf16
once. Fail closed on fp32, non-CUDA,
cc < 8.0, K mismatch, non-bf16 bias,non-contiguous Hopper operands, ROCm.
__CUDA_ARCH_FEAT_SM90_ALL), so Blackwell takes the tree, andRL_KERNEL_MLP_DOWN_GEMM_BACKEND=hopperraises there instead of silently switchingto the other order.
kernel_registry.get_op("mlp_down_gemm")→TritonMlpDownGemmOpbydefault (or
CudaMlpDownGemmOp) →forward→_C.mlp_down_gemm_cuda_forward_sm90/
..._forward/ the Triton kernel; backward →..._dx/..._dw/..._dbor theTriton kernels.
dbis the ascending-row fold in the portable source, shared byboth CUDA paths.
Validation environment
nvcccuda_12.8.r12.8/compiler.35583870_0)KERNEL_ALIGN_FORCE_SM90=1;_Cexposesmlp_down_gemm_cuda_{forward,dx,dw,db}and..._{forward,dx,dw}_sm90KERNEL_ALIGN_FORCE_SM90=1,KERNEL_ALIGN_DEV_RPATH=1,MAX_JOBS=48Correctness / Tests
Unit coverage
CUDA_VISIBLE_DEVICES=0 PYTHONPATH=. python -m pytest \ tests/ops/gemm/test_mlp_down_gemm.py tests/ops/gemm/test_mlp_down_gemm_triton.py -qResult: 147 passed on 2026-11-12 (torch 2.12.0+cu130, Triton 3.7.0, CUDA 13.0, H100
80GB HBM3 SXM). The full row gate also runs the 16
tests/validation/operators/ test_op_checks.pytests: 163 passed in 132.90 s.Forward/
dx/dW/dbon both backends; the declared tolerance and byte-equalityagainst the fp32 reference (anchor whole, the RFC tiers, the
K = 100/12287/12289tails); bitwise row/tiling/padding/rerun invariance; the
K = 128one-ulpbound; one-hot leaf probes and integer identities; an fp64 oracle; dispatch and
route reporting; every fail-closed case.
At 6889 and 6032 rows the fp32 reference is out of budget (it walks K steps over
[M, N]), so those tiers are checked by byte equality against the Hopper kernel andagainst the portable tree, plus
dbbit-exact against the reference fold (which isO(M·N) and affordable at any M).
Accuracy gate
python benchmarks/benchmark_mlp_down_gemm.py --backend {cuda,triton} --dtype bf16 --batch M --seq 1runs this gate on a 256-row window before timing anything:
dxdWdbcuda and triton are byte-identical to each other on forward/
dx/dW/db(
torch.equalat 4096, 6032 and 6889 rows).gtest
Common prefix:
python scripts/check_operator.py --op mlp_down_gemm --device cuda --dtype bf16 --k-dim 12288 --n-dim 3072 --check-gradAll Pass
Both candidates report
pass_rate=1.0000.Benchmarks
python benchmarks/benchmark_mlp_down_gemm.py --backend {cuda,triton} --dtype bf16 --batch M --seq 1(5 warmup, 20 iterations). ms / TFLOP/s.
Forward
Forward + backward
Forward +
dx+dW+db, i.e. three equal GEMMs.Hopper and Triton are within noise on the forward, Hopper is 5-8 % faster end to end.
The portable tree is ~38x slower end to end and needs 360-677 MB more memory (it
up-converts its operands to fp32) — the price of matching the reference byte for byte.
The operator page also carries the author's H100 PCIe numbers for the two mma paths.
ROCm (help wanted)
The CUDA sources are NVIDIA PTX and
csrc/ops.cppkeeps them out of a ROCm build, soTriton serves that slot. There is no AMD host here, so the slot is still open and
everything above is CUDA. If someone has a machine to spare, this is what I would
check; the comments are what CUDA gives, as a reference rather than a bar.
Anything different is worth reporting. If the Triton op raises "requires CUDA tensors
on one device" under HIP, that is a bug —
Tensor.is_cudais true for HIP tensors.Files
New:
csrc/cuda/gemm/mlp_down_gemm.cu,csrc/cuda/gemm/mlp_down_gemm_sm90.curl_engine/kernels/ops/pytorch/linear/mlp_down_gemm.pyrl_engine/kernels/ops/triton/linear/mlp_down_gemm.pyrl_engine/kernels/ops/cuda/linear/mlp_down_gemm.pytests/test_mlp_down_gemm.py,tests/test_mlp_down_gemm_triton.pybenchmarks/benchmark_mlp_down_gemm.py,docs/operators/mlp-down-gemm.mdLines appended to:
rl_engine/kernels/registry.py(+22),csrc/ops.cpp(+49),setup.py(+7),rl_engine/_C.pyi(+11),rl_engine/kernels/gtest/operator_specs.py(+12),rl_engine/kernels/gtest/operator_inputs.py(+18),tests/test_ws1_gtest_gpu.py(+3),docs/.nav.yml(+1),docs/operators/README.md(+1),docs/benchmarking/README.md(+1).Open items
ncurefuses to attach on this box(
ERR_NVGPUCTRPERM, GPU counters not exposed) andnsysis not installed, so theperformance notes on the operator page are timing- and component-isolation-based,
not counter-based.