Skip to content

[#19943][fix] Return an owning fragment from util_convert_type - #20017

Merged
zhangcl merged 3 commits into
NVIDIA:mainfrom
peter941221:fix/moe-cute-util-dangling-view
Oct 31, 2026
Merged

zhangcl merged 3 commits into
NVIDIA:mainfrom
peter941221:fix/moe-cute-util-dangling-view

Conversation

@peter941221

@peter941221 peter941221 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

util_convert_type returns a cute::ViewEngine over its own local frag (issue #19943): make_rmem_ptr on 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 in fused_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 from ViewEngine<To_type*> to ArrayEngine<To_type, numel> and the call sites use CTAD, so they are unaffected. The static_assert the 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 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 and the assertion now enforces.

Sibling audit: the same view-over-a-local pattern exists in kernels/flashMLA/utils.h (convert_type returns a view over its local frag at line 285, and flash_fwd_mla_kernel.h reads it at lines 271 and 817) and in the exported dev tree at trtllmGenKernels/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 --check
  • uvx pre-commit run --files cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/gemm/kernel/moe_cute_util.cuh
  • Host-side replay of the function body under ASAN (detect_stack_use_after_return=1, clang 18): the stock code reports stack-use-after-return pointing at frag in the util_convert_type frame; with this change the same 25 dtype/layout cases run clean, with values and logical element order unchanged.
  • nvcc 13.0 compile check against the real fused_moe_kernel_traits.cuh: engine-type static asserts read ViewEngine<ElementOutput*> before and ArrayEngine<ElementOutput, numel> after the change, with the per-thread fragment size unchanged (8 to 256 elements over the tile set). Re-run with the static_assert in place: cosize == size holds for every layout above, so the assertion compiles for the whole tile set.
  • No end-to-end GPU run: this PR does not claim the SM121 clang failure is reproduced locally, only the lifetime defect and this fix.

PR Checklist

  • Please check this after reviewing the above items as appropriate for this PR.

Dev Engineer Review

util_convert_type now returns an owning tensor instead of a view into a local conversion fragment. It preserves the input layout and uses cute::copy to 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.

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]>
@peter941221
peter941221 marked this pull request as ready for review October 9, 2026 03:05
@peter941221
peter941221 requested a review from a team as a code owner October 9, 2026 03:05
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/TensorRT-LLM/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: 80ff0614-8826-402d-bc9d-b830354ab6af
📥 Commits

Reviewing files that changed from the base of the PR and between b644ca1 and de58e1a.

📒 Files selected for processing: 1
  • cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/gemm/kernel/moe_cute_util.cuh

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

Walkthrough

util_convert_type now checks that the input layout’s cosize equals its element count. It copies converted values into a tensor with the input layout and returns that tensor instead of a view of a local fragment.

Changes

Converted tensor ownership

Layer / File(s) Summary
Create an owning output tensor
cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/gemm/kernel/moe_cute_util.cuh
util_convert_type checks that the layout cosize equals the element count at compile time. It copies converted values into a tensor with the input layout and returns it.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to de58e

The change is intended to prevent converted MoE tensors from referencing expired local storage by returning an owning tensor. No actionable merge-blocking issue is established by the available evidence.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly identifies the fix and matches the main change: returning an owning fragment from util_convert_type. It uses the required GitHub issue and type format.
Description check Passed The description includes the required Description, Test Coverage, and PR Checklist sections. It clearly explains the defect, the implementation, validation performed, and the limitation that no end-to…
Linked Issues check Passed Issue #19943 requires util_convert_type to avoid returning a view over local storage, preserve layout and element order, and enforce contiguous fragments. The diff adds `static_assert(cute::cosize_v…
Out of Scope Changes check Passed The whole-PR diff changes only moe_cute_util.cuh and only the util_convert_type implementation. The change directly supports issue #19943. No unrelated change is present, and the similar flashMLA …
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 0…
Full details: Description check

Explanation

The description includes the required Description, Test Coverage, and PR Checklist sections. It clearly explains the defect, the implementation, validation performed, and the limitation that no end-to-end GPU run was completed.

Full details: Linked Issues check

Explanation

Issue #19943 requires util_convert_type to avoid returning a view over local storage, preserve layout and element order, and enforce contiguous fragments. The diff adds static_assert(cute::cosize_v&lt;Layout&gt; == numel), creates an owning cute::make_tensor&lt;To_type&gt;(tensor.layout()), copies the converted values into it, and returns it. The reported ASAN and nvcc checks support the lifetime fix and call-site compatibility.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff changes only moe_cute_util.cuh and only the util_convert_type implementation. The change directly supports issue #19943. No unrelated change is present, and the similar flashMLA patterns remain outside this pull request.

Full details: Docstring Coverage

Explanation

No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 0 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

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

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.

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

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.

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

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.

@zhangcl

zhangcl commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #81717 [ run ] triggered by Bot. Commit: de58e1a Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #81717 [ run ] completed with state SUCCESS. Commit: de58e1a
/LLM/main/L0_MergeRequest_PR pipeline #67376 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

CI Report

Link to invocation

@zhangcl
zhangcl merged commit 2d1a7d1 into NVIDIA:main Oct 31, 2026
aleozlx pushed a commit to flashinfer-ai/flashinfer that referenced this pull request Nov 16, 2026
<!-- .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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

moe_cute_util.cuh: util_convert_type returns a tensor that points at a local array

6 participants