Repository navigation
[#19943][fix] Return an owning fragment from util_convert_type - #20017
Conversation
util_convert_type returned a cute::ViewEngine over its own local frag: make_rmem_ptr on a raw pointer is the identity, so the returned tensor pointed at a stack array that is destroyed when the function returns, and both call sites in fused_moe_kernel_routine.cuh read through it afterwards. With nvcc the read happens to return stale stack bytes; with clang (device code at -O3, sm_121a) the conversion is eliminated, ptxas removes the MMAs whose results nothing uses, and the kernel stores registers that were never written, corrupting every output row of a bf16/fp16 MoE call. Return a fragment that owns its storage instead (cute::make_tensor<To_type> of the same layout) and copy the converted elements into it. Same layout, same element order, same per-thread fragment size; the call sites use CTAD and are unaffected by the engine type change (ViewEngine<To_type*> -> ArrayEngine<To_type, numel>). Verified with nvcc 13.0 against the real kernel-traits header: the call site sequence (convert, make_tiled_copy_C, retile_S, partition_D, copy) instantiates with the change, and every per-thread accumulator layout from partition_fragment_C over the SM80 fused-MoE tile set (f16/bf16, TileM 16-128, TileN 32-256) has cosize == size, the contiguity the existing HACK comment assumes. A host-side replay of the function body under ASAN reports stack-use-after-return before and runs clean after, with values and logical element order unchanged over 25 dtype/layout cases. No end-to-end GPU run. Fixes NVIDIA#19943 Signed-off-by: Peter Chen J. <[email protected]>
…rt_type The flat copy in util_convert_type relies on the input fragment layout being contiguous, and that precondition currently lives only in the HACK comment above the reinterpret_cast. Assert cosize_v<Layout> == numel so a non-contiguous instantiation fails at compile time instead of reading out of the fragment storage. The precondition holds for every real instantiation: the SM80 fused-MoE accumulator tile set (f16/bf16, TileM 16-128, TileN 32-256) was checked per-thread (cosize == size for all of them), and the kernel-traits translation unit compiles with the assert in place. Verified after this change: the host-side ASAN replay of the function (25 dtype/layout cases) and the nvcc real-header compile check (call-site statement sequence, ViewEngine to ArrayEngine type change) both pass. Signed-off-by: Peter Chen J. <[email protected]>
Barry-Delaney
left a comment
There was a problem hiding this comment.
Reviewed b644ca1. Returning an owning CuTe tensor fixes the local-fragment lifetime defect while preserving the layout and physical element order. I checked both fused-MoE call sites and the contiguous-storage assertion; no blocking issue found. Local validation: git diff --check and source review. I did not rerun CUDA compilation or GPU numerics; the ASAN/nvcc results are author-reported.
|
Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements. |
Signed-off-by: Peter Chen J. <[email protected]>
Barry-Delaney
left a comment
There was a problem hiding this comment.
Re-reviewed de58e1a. The only increment replaces the element loop with cute::copy from a temporary non-owning view of frag into the owning converted tensor. Source and destination use the same layout, the contiguous-storage assertion remains, and the returned tensor still owns its storage after frag is destroyed. Both existing call sites retain the same contract. No blocking code finding; git diff --check passes. CUDA compilation and GPU numerics were not rerun locally.
|
/bot run |
|
PR_Github #81717 [ run ] triggered by Bot. Commit: |
|
PR_Github #81717 [ run ] completed with state |
<!-- .github/pull_request_template.md --> ## 📌 Description Four fixes to the TRT-LLM CUTLASS MoE / GEMM sources under `csrc/nv_internal`, from upstream TensorRT-LLM commits FlashInfer's copies predate, plus one FlashInfer-side fix in the same quantization kernel. - ~~PDL wait without a memory clobber (NVIDIA/TensorRT-LLM#9695, header part)~~ dropped at review (`2419e49d6`): the header it changed, `cutlass_extensions/arch/grid_dependency_control.h`, is included by nothing in this tree. The MoE kernels (and TRT-LLM's own pingpong GEMM) take `cutlass/arch/grid_dependency_control.h` from the CUTLASS submodule, which is bare at pin `b46b16d0` and already carries the clobber on CUTLASS main; the fix arrives with the submodule bump, not here. - **NaN from `448 / amax`** ([NVIDIA/TensorRT-LLM#11256](NVIDIA/TensorRT-LLM#11256)). The 1x128 and 128x128 block-scale quantization kernels in `fp8_blockscale_gemm_kernel.cuh` guarded only `amax == 0`; a tiny nonzero amax gave an inf scale and NaN output. `amax` is clamped to `1e-10` first. - **`util_convert_type` returned a dangling fragment** ([NVIDIA/TensorRT-LLM#20017](NVIDIA/TensorRT-LLM#20017)). `moe_cute_util.cuh` built the result tensor over a stack `cutlass::Array` that goes out of scope on return; it now copies into a tensor that owns its storage, with a static assert that the input is contiguous. - **SM120 / SM121 launch check** ([NVIDIA/TensorRT-LLM#12704](NVIDIA/TensorRT-LLM#12704), launcher part). Consumer Blackwell has 99 KiB of shared memory per block; both TMA warp-specialized launchers now check the kernel's `SharedStorage` against `cudaDevAttrMaxSharedMemoryPerBlockOptin` before launching, so an oversized tile fails with a message instead of a launch error. Upstream's heuristic-level filter (keep only `CtaShape128x128x64B`) is not taken: FlashInfer's SM120 list already drops the `...x64B` tiles for FP8 activations, so the filter left W4A8 with no tactic on RTX PRO 6000 / Spark (first push of this PR), and the `128x128x128B` tile it relies on fits there. - **`scale_128x128_kernel` reduced its amax over the wrong rows** (FlashInfer-side, found in review). The reduction loop bounded the column check with the row index `i` instead of the inner index `j` (the write loop already used `j`): `scales_idx_x * 128 + i * 32 + lane_id >= dim_x` breaks out of the reduction at row `i >= (dim_x - scales_idx_x * 128) / 32`, so for any `dim_x` below about 4200 every 128x128 block's amax came from its first rows only and the remaining rows saturate at 448. Upstream still has `i`; FlashInfer's 2025-10 import carried it over and this fix is FlashInfer-first. Only the internal BF16-weight quantization path (`weight_scale=None`) is affected, and that kernel now reads all 128 rows of a block for the amax where it read the first few; its write loop already read the whole block, so the kernel is at most about 2x its old (wrong) cost on that path only. The amax floor is applied in fp32 so a half instantiation would not flush `1e-10` to 0. No kernel arithmetic changes except the amax clamp and the reduction bound above. ## 🔍 Related Issues [NVIDIA/TensorRT-LLM#9695](NVIDIA/TensorRT-LLM#9695), [NVIDIA/TensorRT-LLM#11256](NVIDIA/TensorRT-LLM#11256), [NVIDIA/TensorRT-LLM#20017](NVIDIA/TensorRT-LLM#20017), [NVIDIA/TensorRT-LLM#12704](NVIDIA/TensorRT-LLM#12704) (launcher part). [NVIDIA/TensorRT-LLM#11561](NVIDIA/TensorRT-LLM#11561) is not needed: FlashInfer gates the SM120 TMA warp-specialized path on `isValidSM120MOESpecialisation`, so pure-int weight-only configs never reach the SM120 list. ## 🚀 Pull Request Checklist Thank you for contributing to FlashInfer! Before we review your pull request, please make sure the following items are complete. ### ✅ Pre-commit Checks - [x] I have installed `pre-commit` by running `pip install pre-commit` (or used your preferred method). - [x] I have installed the hooks with `pre-commit install`. - [x] I have run the hooks manually with `pre-commit run --all-files` and fixed any reported issues. > If you are unsure about how to set up `pre-commit`, see [the pre-commit documentation](https://pre-commit.com/). ## 🧪 Tests - [x] Tests have been added or updated as needed. - [x] All tests are passing (`unittest`, etc.). New: `test_fp8_blockscale_gemm_weight_amax_covers_whole_block` (SM90a): weight blocks whose rows 0-3 are tiny and whose other rows sit near the FP8 maximum, against the BF16 reference; a reduction that stops after the first rows saturates the block. It runs in the GitLab H100 job (the file is SM90-only and skips on B200). For the upstream fixes no new tests: the SM120 / SM121 launch check needs consumer Blackwell hardware, the dangling fragment is undefined behavior that happens to work today, and the NaN needs an amax below `1e-10`. Run on B200 (CUDA 13.0 CI container): `tests/gemm/test_fp8_blockscale_gemm.py` and `tests/moe/test_trtllm_cutlass_fused_moe.py -k "test_moe[ or test_moe_fp8_block_scaling or test_moe_w4a8[ or test_moe_fp8[ or test_moe_nvfp4["`: 56 passed, 86 skipped (SM90-only and Hopper-only variants), at FlashInfer `e3ebb9e7dd` + this commit. ## 🔬 Experimental Track <!-- Only for PRs submitted under the experimental policy (CONTRIBUTING.md → "Experimental APIs and Backends"). Leave this section untouched for normal PRs. --> - [ ] This PR is **experimental**: it adds or changes code under `flashinfer/experimental/` and/or an `@flashinfer_experimental_api`. Tracking issue: # - [ ] The tracking issue names an owner, the reason for the experimental path, and a graduation plan with a target release. - [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff). - [ ] Tests live in `tests/experimental/` and were validated on the intended hardware; a runnable example is included. - [ ] Nothing is registered in `flashinfer/aot.py`, and no experimental backend is reachable from `backend="auto"` without `FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1`. (Calling an `@flashinfer_experimental_api` or naming a backend explicitly is itself the opt-in and needs no environment variable.) - [ ] **Test scope declared below.** The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows. <!-- Required for experimental PRs. Replace the commented lines below with your targets. Do not delete the fence or change its `experimental-tests` tag — the experimental-track watcher reads it verbatim to decide which targets to ask CI for. --> ```experimental-tests # One target per line: a directory or a file. (A pytest ::selector is not # supported -- the sharding runner cannot consume one.) Must be under # tests/experimental/ and must exist. Delete these comment lines and add yours, e.g. # # tests/experimental/test_my_backend.py # tests/experimental/my_backend/ # # Declaring the whole tree (tests/experimental/) is allowed but means every # experimental PR pays for every other feature's tests, in every matrix cell. ``` ## Reviewer Notes Reviewers with SM120 / SM121 hardware: `tests/moe/test_trtllm_cutlass_fused_moe.py` covers the launch check; the GitLab lane runs it on RTX PRO 6000 and Spark.
Description
util_convert_typereturns acute::ViewEngineover its own localfrag(issue #19943):make_rmem_ptron a raw pointer is the identity, so the returned tensor points at a stack array that is destroyed when the function returns. Both call sites infused_moe_kernel_routine.cuh(lines 405 and 760) then read through that pointer. With nvcc the read happens to return stale stack bytes; with clang (device code at -O3, sm_121a) the conversion is eliminated, ptxas removes the MMAs whose results nothing uses, and the kernel stores registers that were never written, corrupting every output row of a bf16/fp16 MoE call.This change returns a fragment that owns its storage instead:
cute::make_tensor<To_type>(tensor.layout())of the same layout, with the converted elements copied in. Same layout, same element order, same per-thread fragment size; the engine type changes fromViewEngine<To_type*>toArrayEngine<To_type, numel>and the call sites use CTAD, so they are unaffected. Thestatic_assertthe issue suggested (cosize_v<Layout> == numel) is included, so a non-contiguous instantiation now fails at compile time instead of reading out of the fragment storage.Verified with nvcc 13.0 against the real kernel-traits header: the call-site sequence (
convert,make_tiled_copy_C,retile_S,partition_D,copy) instantiates with the change, and every per-thread accumulator layout frompartition_fragment_Cover the SM80 fused-MoE tile set (f16/bf16, TileM 16-128, TileN 32-256) hascosize == size, the contiguity the existing HACK comment assumes and the assertion now enforces.Sibling audit: the same view-over-a-local pattern exists in
kernels/flashMLA/utils.h(convert_typereturns a view over its localfragat line 285, andflash_fwd_mla_kernel.hreads it at lines 271 and 817) and in the exported dev tree attrtllmGenKernels/fmha/trtllmGen_fmha_export/trtllm/dev/CuteUtils.h(no in-tree call sites). Both are left untouched to keep this PR scoped to the reported file; happy to send the flashMLA one as a follow-up if wanted.Fixes #19943.
Test Coverage
git diff --checkuvx pre-commit run --files cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/gemm/kernel/moe_cute_util.cuhdetect_stack_use_after_return=1, clang 18): the stock code reportsstack-use-after-returnpointing atfragin theutil_convert_typeframe; with this change the same 25 dtype/layout cases run clean, with values and logical element order unchanged.fused_moe_kernel_traits.cuh: engine-type static asserts readViewEngine<ElementOutput*>before andArrayEngine<ElementOutput, numel>after the change, with the per-thread fragment size unchanged (8 to 256 elements over the tile set). Re-run with thestatic_assertin place:cosize == sizeholds for every layout above, so the assertion compiles for the whole tile set.PR Checklist
Dev Engineer Review
util_convert_typenow returns an owning tensor instead of a view into a local conversion fragment. It preserves the input layout and usescute::copyto copy the converted values. A compile-time assertion rejects layouts whose cosize differs from the element count. The change is limited to the MoE utility; no exported API changes are reported. Reported validation includes an ASAN lifetime check and an nvcc compile check. No end-to-end GPU run is reported.QA Engineer Review
No test changes.
Per-File QA Perspective
cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/gemm/kernel/moe_cute_util.cuh: Verify that returned values remain valid after the function returns and retain the expected element order. Verify that layouts whose cosize differs from the element count fail at compile time.