Skip to content

[WS1][Qwen-Image][CUDA/ROCm] Qwen-Image MLP down projection (mlp_down_gemm, CUDA) - #499

Open
luoyueyuguang wants to merge 41 commits into
RL-Align:test-qwenimagefrom
luoyueyuguang:feat/ws1-mlp-down-gemm
Open

luoyueyuguang wants to merge 41 commits into
RL-Align:test-qwenimagefrom
luoyueyuguang:feat/ws1-mlp-down-gemm

Conversation

@luoyueyuguang

@luoyueyuguang luoyueyuguang commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

[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_gemm row of #386 — plus its Triton backend, an FP32 reference, a benchmark
and the operator page. Both streams have the same shape (img_mlp.net.2,
txt_mlp.net.2), so one row covers both.

y[t] = bf16(fp32(x[t, :] @ W.T) + b)      x:[M,12288]  W:[3072,12288]  b:[3072]

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. auto takes the tensor-core order only when the SM90 build and
a cc 9.0 device are present; mlp_down_gemm_contract_used() returns the id a call
took, and the row prints it once per process as [RL-Kernel][route] ... contract=....

Path Status
Portable CUDA tree (csrc/cuda/gemm/mlp_down_gemm.cu, 749 lines) New. mlp_tree_kernel (byte-equal to the fp32 reference) plus the dW/db folds; always compiled, sm80+.
Hopper CUDA (csrc/cuda/gemm/mlp_down_gemm_sm90.cu, 691 lines) New. TMA + wgmma.mma_async, STAGES=4, KG=1; built only with KERNEL_ALIGN_FORCE_SM90=1.
Triton (rl_engine/kernels/ops/triton/linear/mlp_down_gemm.py, 549 lines) New. Pinned tiles, no autotune, input_precision="ieee"; also the ROCm/MUSA slot.
FP32 reference (rl_engine/kernels/ops/pytorch/linear/mlp_down_gemm.py) New. fp64-emulated correctly-rounded FMA tree plus the dx/dW/db VJP.
Dispatch (rl_engine/kernels/ops/cuda/linear/mlp_down_gemm.py) New. Path selection, the route report, fail-closed gates.
Registry, bindings, build Lines appended: registry.py +22, csrc/ops.cpp +49 (7 symbols), setup.py +7, _C.pyi +11.
gtest Lines appended: operator_specs.py +12, operator_inputs.py +18, tests/test_ws1_gtest_gpu.py +3.
Tests, benchmark, docs New: the two test files, the benchmark, the operator page.

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_kernel stages one 32-wide
    leaf 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_kernel
    and mlp_down_db_fold_wide_kernel. Always compiled, sm80+.
  • csrc/cuda/gemm/mlp_down_gemm_sm90.cu (691 lines): TMA 2-D bulk-tensor staging
    driving wgmma.mma_async (m64n256k16 forward, m64n128k16 for dx/dW), one
    fp32 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 pinned
    tiles, input_precision="ieee", do_not_specialize=["M"]; one program per output
    tile walks the whole reduction. This is also the ROCm/MUSA slot.
  • Both CUDA entry points up-convert operands (Tensor::to(kFloat), exact) for the
    tree, 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.
  • The Hopper path requires cc 9.0 exactly (its wgmma body only exists under
    __CUDA_ARCH_FEAT_SM90_ALL), so Blackwell takes the tree, and
    RL_KERNEL_MLP_DOWN_GEMM_BACKEND=hopper raises there instead of silently switching
    to the other order.
  • Call flow: kernel_registry.get_op("mlp_down_gemm") → TritonMlpDownGemmOp by
    default (or CudaMlpDownGemmOp) → forward → _C.mlp_down_gemm_cuda_forward_sm90
    / ..._forward / the Triton kernel; backward → ..._dx/..._dw/..._db or the
    Triton kernels. db is the ascending-row fold in the portable source, shared by
    both CUDA paths.

Validation environment

Item Value
GPU NVIDIA H100 80GB HBM3 (SXM), compute capability 9.0
Driver 550.163.01 (CUDA driver 12.8)
CUDA toolkit / nvcc 12.8 (cuda_12.8.r12.8/compiler.35583870_0)
PyTorch 2.11.0+cu128
Triton 3.6.0
Python 3.12.3
Host compiler gcc 13.3.0
Extension built with KERNEL_ALIGN_FORCE_SM90=1; _C exposes mlp_down_gemm_cuda_{forward,dx,dw,db} and ..._{forward,dx,dw}_sm90
Build vars KERNEL_ALIGN_FORCE_SM90=1, KERNEL_ALIGN_DEV_RPATH=1, MAX_JOBS=48

Correctness / 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 -q

Result: 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.py tests: 163 passed in 132.90 s.

Forward/dx/dW/db on both backends; the declared tolerance and byte-equality
against the fp32 reference (anchor whole, the RFC tiers, the K = 100/12287/12289
tails); bitwise row/tiling/padding/rerun invariance; the K = 128 one-ulp
bound; 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 and
against the portable tree, plus db bit-exact against the reference fold (which is
O(M·N) and affordable at any M).

Accuracy gate

python benchmarks/benchmark_mlp_down_gemm.py --backend {cuda,triton} --dtype bf16 --batch M --seq 1
runs this gate on a 256-row window before timing anything:

Path forward identical worst dx dW db
tensor-core (Hopper / Triton) 99.32 % 0.82 bf16-ulp 99.83 % 99.99 % 100 %
portable tree (fp32 cores) 100.00 % 0.00 bf16-ulp 100 % 100 % 100 %

cuda and triton are byte-identical to each other on forward/dx/dW/db
(torch.equal at 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-grad

All Pass

... --candidate cuda   --batch 64 --seq 64   # 1024^2  = 4096 tokens
... --candidate triton --batch 83 --seq 83   # 1328^2  = 6889 tokens
candidate case max_abs tol passed
cuda forward 4096x12288x3072 1.96 atol=5e-2, rtol=2e-2 True
cuda gradient:x / weight / bias 1.00 / 2.00 / 0.00 atol=1e-1, rtol=2e-2 True
triton forward 6889x12288x3072 1.96 atol=5e-2, rtol=2e-2 True
triton gradient:x / weight / bias 1.00 / 2.00 / 3.9e-3 atol=1e-1, rtol=2e-2 True

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

M cuda (Hopper TMA+wgmma) triton portable tree
4096 (1024²) 0.420 / 735.6 0.409 / 755.4 21.741 / 14.2
6032 (1664x928) 0.675 / 674.3 0.673 / 677.1 31.887 / 14.3
6889 (1328²) 0.704 / 738.7 0.700 / 743.1 36.408 / 14.3

Forward + backward

Forward + dx + dW + db, i.e. three equal GEMMs.

M cuda (Hopper TMA+wgmma) triton portable tree
4096 (1024²) 1.498 / 619.2 1.582 / 586.5 57.723 / 16.1
6032 (1664x928) 2.320 / 588.9 2.470 / 553.1 85.125 / 16.1
6889 (1328²) 2.529 / 617.0 2.740 / 569.5 96.885 / 16.1

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.cpp keeps them out of a ROCm build, so
Triton 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.

pip install -e . --no-build-isolation                     # FORCE_SM90 is a no-op on ROCm
python -c "import rl_engine._C as C; print([n for n in dir(C) if 'mlp_down_gemm' in n])"
#   expect [] -- no mlp_down_gemm_cuda* symbols in a ROCm build
python -c "import torch; from rl_engine.kernels.registry import kernel_registry as r; print(type(r.get_op('mlp_down_gemm', device='cuda')).__name__)"
#   expect TritonMlpDownGemmOp
python -m pytest tests/test_mlp_down_gemm_triton.py -q -rs
#   expect pass, with TestCudaByteEquality skipped (needs the SM90 build and cc 9.0)
python scripts/check_operator.py --op mlp_down_gemm --candidate triton --device cuda \
    --dtype bf16 --batch 2 --seq 16 --k-dim 12288 --n-dim 3072 --check-grad
#   expect pass_rate=1.0000 under the shared dtype policy
python benchmarks/benchmark_mlp_down_gemm.py --backend triton --dtype bf16 --batch 4096 --seq 1
#   expect gate ~99.3 % identical, worst <= 0.9 bf16-ulp, db 100 % / 0.0 ulp

Anything different is worth reporting. If the Triton op raises "requires CUDA tensors
on one device" under HIP, that is a bug — Tensor.is_cuda is true for HIP tensors.

Files

New:

  • csrc/cuda/gemm/mlp_down_gemm.cu, csrc/cuda/gemm/mlp_down_gemm_sm90.cu
  • rl_engine/kernels/ops/pytorch/linear/mlp_down_gemm.py
  • rl_engine/kernels/ops/triton/linear/mlp_down_gemm.py
  • rl_engine/kernels/ops/cuda/linear/mlp_down_gemm.py
  • tests/test_mlp_down_gemm.py, tests/test_mlp_down_gemm_triton.py
  • benchmarks/benchmark_mlp_down_gemm.py, docs/operators/mlp-down-gemm.md

Lines 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

  • ROCm unvalidated (above). The row's ROCm slot stays open.
  • No profiler numbers. ncu refuses to attach on this box
    (ERR_NVGPUCTRPERM, GPU counters not exposed) and nsys is not installed, so the
    performance notes on the operator page are timing- and component-isolation-based,
    not counter-based.

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]>
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fe181014-cad6-4ec5-8795-94fe72875553

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@luoyueyuguang luoyueyuguang changed the title [WS1][kernels] Qwen-Image MLP down projection (mlp_down_gemm, CUDA) [WS1][Qwen-Image][CUDA/ROCm] Qwen-Image MLP down projection (mlp_down_gemm, CUDA) Oct 8, 2026
@Flink-ddd Flink-ddd added platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) new-model qwen WS1 labels Oct 9, 2026
…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]>
@Flink-ddd

Copy link
Copy Markdown
Collaborator

@zhangj1an PTAL, Thank you.

@maxiaosong1124

Copy link
Copy Markdown
Collaborator

please resolve DCO error first, thx! @luoyueyuguang

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 5 issue(s) in this PR.

  • ✅ Successfully posted inline: 0 comment(s)
  • 📋 Routed to summary by policy: 5 comment(s)

⚠️ 5 warning(s) occurred during review.


bug · medium

📄 tests/ops/gemm/test_mlp_down_gemm_triton.py (L83-L83)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

_hopper_available gates BYTE_EXACT on the major capability number ([0] == 9), but the CUDA backend's actual Hopper route requires exactly (9, 0) (mlp_down_gemm_backend_used checks get_device_capability(x.device) == (9, 0)), and test_mlp_down_gemm.py::_hopper_serves correctly uses == (9, 0). On any future cc 9.x part (e.g. 9.1) with the SM90 build, _hopper_available() returns True, so TestCudaByteEquality runs, but _pinned("hopper") then raises (and backend_used returns "general"), turning a skip into a test error/assertion failure instead of skipping. Match the runtime gate exactly.


test · medium

📄 tests/ops/gemm/test_mlp_down_gemm.py (L244-L246)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category test)

This test is a tautology, not a dtype-path check: NativeMlpDownGemmOp.forward_fp32 simply calls mlp_down_gemm_reference_forward, so it compares the reference against itself and can never fail. The name claims to verify the gold op's dtype path agrees, but the bf16-producing path (op(x, weight, bias=bias) / _MlpDownGemmTreeFunction, which does the single output cast) is never exercised. A bug in the cast/return dtype would pass unnoticed. Compare the actual dtype path against the reference rounded to bf16.


maintainability · medium

📄 benchmarks/operators/gemm/benchmark_mlp_down_gemm.py (L147-L147)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category maintainability)

The gate applies the mma tolerance (DECLARED_MIN_IDENTICAL_FRACTION / DECLARED_MAX_ULPS) unconditionally, but --backend cuda can resolve to the mlp-down-gemm-tree contract (non-Hopper device/build, or an operand not TC-eligible), whose declared contract is byte equality with this same fp32 reference. In that case a regression that changes a small fraction of bytes (e.g. a leaf/tail boundary bug) can still leave identical >= 0.99 and worst <= 8 ulp and be reported as gate verdict: PASS, contradicting the tree contract. Select the bound from the resolved contract (pass the result of mlp_down_gemm_contract_used into _accuracy_gate and require identical == 1.0 for the tree path).


bug · medium

📄 build_tools/extensions.py (L354-L354)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity medium · category bug)

The portable tree source (mlp-down-gemm-tree) is declared to be byte-equal to the independent fp32 CPU reference (mlp_down_gemm_reference_forward/backward, which round each FMA/add without denormal flushing). But it is appended unconditionally while nvcc_flags may contain --use_fast_math (and relaxed_math_env), exactly the mode that the file just above (joint_attn_softmax.cu) is deliberately excluded from because it "must never inherit fast-math". --use_fast_math implies -ftz=true, so the tree's plain fp32 merge adds (cur[r] = lvl[j][r] + cur[r], v = v + bias[col]) compile to .ftz variants and flush denormal intermediates (and fast-math may otherwise reassociate), so a fast-math build silently produces a tree kernel that is no longer byte-equal to the reference it defines. Trigger: any build with KERNEL_ALIGN_* fast-math/relaxed-math enabled. Impact: the row's frozen tree contract is violated for denormal-bearing inputs; the byte-equality validation gate would fail on such a build. Gate the source the same way as joint_attn_softmax.cu (or compile it without fast-math).

💡 Suggested Change

Before:

            cuda_sources.append("csrc/cuda/gemm/mlp_down_gemm.cu")

After:

            # The portable fp32-tree contract (mlp-down-gemm-tree) is byte-equal to
            # the fp32 reference, so it must never inherit fast-math (denormal
            # flushing / reassociation would break byte-equality).
            if not use_fast_math and not relaxed_math_env:
                cuda_sources.append("csrc/cuda/gemm/mlp_down_gemm.cu")

test · low

📄 tests/runtime/test_adaln_test_environments.py (L103-L104)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category test)

These explicit node IDs duplicate the f"{STRICT_TESTS}..." entries in the same run_pytest call (STRICT_TESTS is literally "tests/runtime/test_adaln_strict_policy.py::", defined at line 55). The same duplication applies to the modulation block above: the added "tests/ops/norm/test_adaln_modulation.py::..." entries repeat the f"{MODULATION_TESTS}..." entries if MODULATION_TESTS uses that file prefix. Since those tests are already selected by the f-string arguments, passing the same node IDs again collects them twice (wasted runtime; no extra coverage). Remove the duplicated explicit paths and rely on the existing prefix-based arguments.


⚠️ Warnings:

  • benchmarks/operators/gemm/benchmark_mlp_down_gemm.py,tests/ops/gemm/test_mlp_down_gemm.py,tests/ops/gemm/test_mlp_down_gemm_triton.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round completed the task
  • benchmarks/operators/gemm/benchmark_mlp_down_gemm.py (token_budget_reached): skipped round 2 of group "benchmarks/operators/gemm/benchmark_mlp_down_gemm.py,tests/ops/gemm/test_mlp_down_gemm.py,tests/ops/gemm/test_mlp_down_gemm_triton.py": used 755077 tokens exceeds budget 500000
  • rl_engine/validation/operators/operator_inputs.py (token_budget_reached): stopped dispatch: used 755077 tokens + group estimate 73396 = projected 828473 exceeds budget 500000
  • build_tools/extensions.py,csrc/bindings/ops.cpp,csrc/cuda/gemm/mlp_down_gemm.cu,csrc/cuda/gemm/mlp_down_gemm_sm90.cu,rl_engine/_C.pyi,rl_engine/backends/cuda/gemm/mlp_down_gemm.py,rl_engine/backends/shared/triton/gemm/mlp_down_gemm.py,rl_engine/reference/gemm/mlp_down_gemm.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • rl_engine/runtime/registry.py,tests/runtime/test_adaln_test_environments.py,tests/runtime/test_dispatch.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task

Comment thread csrc/bindings/ops.cpp Resolved
@github-actions

Copy link
Copy Markdown

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

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]>
…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]>
Comment thread rl_engine/runtime/registry.py Resolved
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]>

@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. The previous findings are addressed and the layout follows #497. please rerun the failed automated review job before merging.

@luoyueyuguang

Copy link
Copy Markdown
Contributor Author

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.

@maxiaosong1124

Copy link
Copy Markdown
Collaborator

please resolve the conflicts first, thx! @luoyueyuguang

Comment thread csrc/cuda/gemm/mlp_down_gemm_sm90.cu Resolved
`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]>
Comment thread rl_engine/runtime/registry.py Resolved
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]>
@luoyueyuguang

Copy link
Copy Markdown
Contributor Author

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!

luoyueyuguang and others added 3 commits November 21, 2026 21:58
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]>
@Flink-ddd Flink-ddd added the multimodal Features, bugs, or optimizations specific to multimodal support. label Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

multimodal Features, bugs, or optimizations specific to multimodal support. new-model platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) qwen WS1

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants