Skip to content

[executorch][cuda] NVFP4: dequant + matmul prefill by default without native FP4 - #25433

Open
Gasoonjia wants to merge 10 commits into
gh/Gasoonjia/140/basefrom
gh/Gasoonjia/140/head
Open

Gasoonjia wants to merge 10 commits into
gh/Gasoonjia/140/basefrom
gh/Gasoonjia/140/head

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Adds triton::nvfp4_dequant, a whole-weight NVFP4 to BF16/FP16 dequant whose values are bit-identical to the weights the fused W4A16 kernel builds in registers, and a _dequant_linear prefill path through chunked_dequant_linear (the same dequant-then-Inductor-matmul path the integer GGUF formats take for M > 64, chunked along N for huge weights).

ET_CUDA_NVFP4_PREFILL_IMPL=auto|kernel|dequant selects the prefill implementation. auto (default) keeps the fused W4A4/W4A16 kernels where FP4 tensor cores exist (SM120+); elsewhere it uses dequant + matmul only for M not statically <= 64 (like the GGUF formats), where it is faster than in-register dequant, and keeps the fused kernels, which read the packed weight once, for smaller or bounded M. kernel/dequant force one for M not statically <= 4; w4a4 and the FP32 prefill output policy always take the fused kernels. _linear and the gated linear share one _dequant_prefill predicate and validate ET_CUDA_NVFP4_PREFILL_IMPL up front; the crossover is the NVFP4-owned NVFP4_FUSED_PREFILL_MAX_ROWS (inclusive: a static M of 64 stays fused). The choice is made once per exported program from M's upper bound, and auto assumes (and the dispatch docstring states) that a dynamic-M method is exported with its largest M as the example, as the Muse Glimmer and Gemma 4 prefill methods are (the DFlash packed draft is traced with 2 context rows, so its dynamic linears dequantize without that measurement). Dynamic-M prefill methods (Muse Glimmer's default in-graph prefill is dynamic from 5 tokens, as are the DFlash and Gemma 4 31B prefills) therefore dequantize for short prompts too, which is also faster there: such a method tunes the fused kernel at its example M, and on A100 that large-M tile loses to dequant + cuBLAS at small M too (on H100 short prompts pay about 13% per layer for a 1.5-2x long-prompt gain; numbers below). The variable applies to every method traced in the process; kernel keeps the fused kernels for all of them, and the Muse Glimmer README says so. The dequant op takes a required output_dtype like its sibling ops, documents the finite-scale precondition, uses the exact software decode on every GPU and validates its operands.

Authored with Claude Code.

Differential Revision: D131418686

NOTE FOR REVIEWERS: This PR has internal Meta-specific changes or comments, please review them on Phabricator!

@pytorch-bot

pytorch-bot Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25433

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 1 Cancelled Job, 3 Pending

As of commit f6cc00c with merge base 9f49fe2 (image):

NEW FAILURE - The following job has failed:

CANCELLED JOB - The following job was cancelled. Please retry:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 21m 51s —— View job


Request Changes: on every GPU older than SM120 the new default sends NVFP4 linears with M > 4 (and any dynamic M) through whole-weight dequant + matmul instead of the M > 64 cutoff the code and description cite, ET_CUDA_NVFP4_PREFILL_IMPL=dequant doesn't force dequant as documented, and _gated_linear checks for dequant without the conditions _linear applies.

Detailed review

PR Review: #25433

Summary

The PR adds a whole-weight triton::nvfp4_dequant kernel and the ET_CUDA_NVFP4_PREFILL_IMPL setting, and makes dequant + matmul the default for non-decode NVFP4 linears on GPUs without native FP4.

  • The default applies from M > 4, not from the M > 64 its own docstrings cite.
  • The dequant override does not behave as documented in _linear or in _gated_linear.
  • No test deliberately exports and runs the new default path.

There is no GPU in this environment, so nothing was run. Every finding comes from reading the code.

Performance

  • On every GPU older than SM120, auto sends M = 5–64 and every dynamic M to whole-weight dequant (nvfp4_dispatch.py:398-403). The only check before the new branch is small, which means M is statically ≤ NVFP4_DECODE_MAX_ROWS, and that limit is 4 (nvfp4_output.py:12).
    • What the docs claim: nvfp4_dispatch.py:221-223, nvfp4_dequant.py:7-8 and the PR description all call this "the integer GGUF formats' M > 64 path".
    • What the GGUF formats do: they keep their fused kernels for static M ≤ 64 and for dynamic M provably within [1, 64] (DEFAULT_MAX_BUCKET = 64 at _gemm_family_dispatch.py:49; int5_dispatch.py:22-27).
    • Memory traffic: at small M both paths are memory-bound. Dequant + matmul reads about 0.56 B, writes 2 B and reads 2 B back per weight element. The fused W4A16 kernel reads about 0.56 B, so that is roughly 8× the traffic.
    • Temporary buffer: each linear also allocates a dense N×K copy of the weight (up to 65536 rows before chunking starts).
    • Dynamic-M exports are the worst case: a method exported with Dim(max=64) dequantizes the whole weight on every call, even when the runtime M is 1.
    • Who is affected: batched decode, speculative-decoding verification and chunked prefill. Under the default settings, the existing M=6 test at test_nvfp4_kernels.py:279 already goes through this path.
    • Why tests don't show it: the routing table pins kernel on the dynamic-M row without native FP4 (test_nvfp4_fusion.py:102).
    • Fix: take dequant only when not statically_known_true(M <= DEFAULT_MAX_BUCKET), like GGUF. Alternatively, add dequant + matmul as a timed candidate in the existing _prefill mode_split autotune instead of choosing it by GPU.
    • Benchmarks: please post numbers across M; "faster than in-register dequant" seems unlikely at M ≤ 64. The slowdown above is inferred from bytes moved, not measured.
    • Fix this →

API Design

  • ET_CUDA_NVFP4_PREFILL_IMPL=dequant does not "force" dequant as the module docstring says (nvfp4_dispatch.py:17-19). In _linear, the w4a4 branch (:363) runs before the dequant branch, and the dequant branch requires output_dtype is None (:400).
    • With ET_CUDA_NVFP4_ACT=w4a4 or ET_CUDA_NVFP4_PREFILL_OUTPUT=fp32, an explicit dequant is silently ignored.
    • For the same reason, auto on a GPU without native FP4 keeps nvfp4_w4a16 under the FP32 policy, which contradicts "dequant + matmul otherwise".
    • Fix: document this precedence, or raise when an explicit dequant can't be honoured.
    • No routing row has fp32=True with native=False.
    • Fix this →

Testing

  • No test deliberately exports or runs the new default path.
    • test_packed_linear_pte pins kernel (test_nvfp4_export.py:59), and that includes its dynamic-M runtime sweep over [1, 5, 37, 64].
    • The routing test swaps nvfp4_dequant for a Python stub (test_nvfp4_fusion.py:113-117).
    • The only .pte that reaches triton::nvfp4_dequant is test_gemma_packed_modules_pte[w4a16], and only by accident. It uses static M=37, doesn't check which op was emitted, and in fbcode returns before running the program (:194-195).
    • Fix: add a dynamic-M case with PREFILL_IMPL=dequant to test_packed_linear_pte. It should skip the tile-timing assertion and assert that the dequant op was emitted. It needs no native FP4, so it runs on the A100 target.
  • The bit-identity claim is only checked against a Python model of the kernel. test_dequant_is_bit_exact compares against kernel_order_reference. The one comparison with the real fused kernel (test_nvfp4_dequant.py:68-76) uses a 1e-2 max-relative tolerance, which can't catch a one-ulp difference in a single element.
    • Suggested check: nvfp4_w4a16(torch.eye(K, dtype=torch.bfloat16, device="cuda"), q, s, pts, split_k=1).T should reproduce the kernel's in-register weights exactly, because each output is a single product accumulated in FP32. That allows torch.equal against nvfp4_dequant(...) for every pts kind and dtype. I reasoned this out but did not run it.
  • The FP16 clamp at test_nvfp4_dequant.py:55-56 is unnecessary, and its comment is wrong. All of the kernel's math is FP32 (_fp4_pair_f16 and _e4m3_f16 return FP32), and the largest value, 6·448·1.5 = 4032, fits easily in FP16. The clamp only removes FP16 coverage of scale bytes 0x61–0x7E.
  • The autouse default_policy fixtures don't clear ET_CUDA_NVFP4_PREFILL_IMPL. They clear only ACT and PREFILL_OUTPUT (test_nvfp4_kernels.py:44, test_nvfp4_fusion.py:36, test_nvfp4_gate_up.py:56), so a value set in the environment changes their routing.
    • The new file has no such fixture at all. If ET_CUDA_NVFP4_PREFILL_OUTPUT=fp32 is set in the environment, test_linear_prefill_dispatch[dequant-*] fails its spy.call_count == 1 check.
    • Fix these →

Code Quality

  • _gated_linear checks for dequant without the conditions _linear applies (nvfp4_dispatch.py:287).
    • Under auto the new check does nothing: without native FP4, the existing not _has_native_fp4() clause (:293) already falls back.
    • It only takes effect with an explicit dequant on SM120+. There it drops the fused gate/up kernels for decode-size M, for ACT=w4a4 and for the FP32 policy. _linear then picks nvfp4_auto_decode, nvfp4_w4a4 or nvfp4_auto_prefill anyway, followed by a separate SiLU-mul. The result is neither fused nor dequant, and a setting documented as prefill-only changes decode routing.
    • Fix: share one predicate with _linear: M not small, mode not w4a4, and output_dtype is None.
    • The nvfp4_gated_linear docstring (:255-258) was not updated.
    • No test covers this check. Every gated routing row pins kernel (test_nvfp4_gate_up.py:144), and test_nvfp4_fusion.py only routes F.linear.
    • Fix this →
  • triton::nvfp4_dequant skips the input validation its sibling ops do (nvfp4_dequant.py:78).
    • The sibling NVFP4 ops check their inputs with _check_operands / _check_weight (for example nvfp4_auto_decode at nvfp4_dispatch.py:152).
    • This op assumes row strides of K//2 and K//16 and reads PTS + n without checking. A direct call with a non-contiguous qdata, a wrongly shaped scale, or a per_tensor_scale with neither 1 nor N values silently reads the wrong memory.
    • dtype is not limited to BF16/FP16.
    • _dequant_linear itself is safe: the CudaNVFP4Tensor fields are validated, and the row slices it passes are contiguous.
    • Fix this →
  • The kernel's NATIVE branch only runs with an explicit dequant on SM120+, and CI never runs it (nvfp4_dequant.py:48-49).
    • auto picks dequant only when _has_native_fp4() is False, and that is the same check (_has_native_fp4_conversion) that sets NATIVE.
    • The only test target is an A100 (targets.bzl).
    • The soft branch is already exact for every finite code, and the kernel is memory-bound.
    • Fix: drop the branch and its _scaled_pair / _e4m3_to_f32 / _has_native_fp4_conversion imports, or add SM120 coverage.
    • Fix this →
  • nvfp4_dispatch.py:401: the x.dtype in (torch.bfloat16, torch.float16) check is redundant. In this else branch allowed_dtype is already true. Together with output_dtype is None, that implies BF16 or FP16, since nvfp4_prefill_output_dtype only returns None or torch.float32.

Recommendation

Request Changes

The default change affects every GPU older than SM120, and it starts at M > 4 rather than the M > 64 that the code and PR description cite. Without benchmarks at small and dynamic M, this looks like a slowdown for decode and short prefill. Before approval:

  • Align the threshold with DEFAULT_MAX_BUCKET, or make dequant a timed candidate.
  • Make the _gated_linear check match _linear.
  • Add an export test of the new default.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks.

  • Wording: the docstring, _dequant_prefill and the README now say the choice is made per linear, from that linear's M bound at export. One method can mix both paths (a dynamic method's LM head over at most 64 selected rows stays fused). ROCm also takes dequant. dequant does not override --nvfp4-act w4a4 or ET_CUDA_NVFP4_PREFILL_OUTPUT=fp32.
  • Static M just above 64: left as is. No default export has a static NVFP4 method above 64 rows: export_solo's forward sizes stop at 64, and the DFlash static drafts are count * block <= 64 at the default block. Only a user --forward-sizes above 64 reaches it. Giving static M its own cutoff needs static-M measurements at 96-256 on A100 and H100, which I don't have. ET_CUDA_NVFP4_PREFILL_IMPL=kernel restores the fused kernel there. _dequant_prefill's docstring now says the dequant advantage was measured for dynamic M only.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 20m 33s —— View job


Approve: nothing blocks, and four minor points remain: auto keeps the fused W4A16 kernel for long prompts on SM120 under --nvfp4-act w4a16/w4a8 (not measured), the README is wrong about which linears dequantize under --logits and dequant, the new tests skip ROCm even though ROCm CI runs them and this PR makes the kernel ROCm's default, and a comment in a shared helper is still incomplete.

Detailed review

PR Review: #25433

Summary

Without native FP4 (below SM120, and on ROCm), NVFP4 linears whose M is not statically ≤ 64 now default to a whole-weight triton::nvfp4_dequant followed by a matmul. ET_CUDA_NVFP4_PREFILL_IMPL selects the implementation.

The reviewers found no correctness bug in the kernel or the dispatch. Four minor issues remain:

  • one routing question;
  • one README inaccuracy;
  • one test-coverage gap;
  • one incomplete comment.

There is no GPU here, so nothing was run. Every finding comes from reading the code.

Code Quality

  • The comment at backends/cuda/quantize_op_dispatch/_gemm_family_dispatch.py:33-34 is still incomplete. It hasn't changed since the last round.
    • It says "(NVFP4 prefill without native FP4)".
    • But _dequant_prefill also takes the chunked path with native FP4 under ET_CUDA_NVFP4_PREFILL_IMPL=dequant (nvfp4_dispatch.py:277).
    • And under auto it takes it only for M not statically ≤ 64 (:273-276).
    • Example: an SM120 export with dequant and an LM head above 65536 rows is chunked, although the comment says it isn't.
    • Fix: point to nvfp4_dispatch._dequant_prefill instead of restating NVFP4's policy in a shared helper.
    • Fix this →

Testing

  • The new tests skip ROCm, but this PR makes ROCm a default user of the path (backends/cuda/tests/test_nvfp4_dequant.py:17-20).
    • ROCm CI would run them: it runs all of backends/cuda/tests (.ci/scripts/test-rocm-aoti.sh:156-159) and doesn't exclude this file.
    • The skip: the CUDA marker skips HIP with the reason "NVIDIA CUDA required".
    • ROCm is now a default user: the docstring and README say ROCm takes dequant + matmul by default, because _has_native_fp4_conversion is False on HIP (nvfp4_quantized_gemm.py:278).
    • Nothing NVIDIA-only is needed: the kernel uses only the software decode, and W4A16 runs on ROCm (nvfp4_dispatch.py:13). That covers test_dequant_is_bit_exact, test_dequant_matches_fused_w4a16_weights_bitwise, test_linear_prefill_dispatch and test_dequant_linear_chunks_huge_weights.
    • Context: every other NVFP4 test file skips HIP the same way, so NVFP4 on ROCm was untested before this PR too. But this PR is what makes this kernel the ROCm default.
    • Fix: drop the HIP condition in this file. If something does block ROCm, say what in the skip reason.
    • Fix this →

API Design

  • The README is wrong about which linears dequantize (examples/models/muse-glimmer/README.md:428-437).
    • --logits exports. The README says a dynamic-M prefill method's "LM head over at most 64 selected rows stays fused". That isn't true with --logits:
      • sample=not args.logits (export_solo.py:1390), so forward_from_embeddings becomes prefill_from_embeds (:828-830), with T in [5, max_prefill] (:826).
      • prefill_from_embeds applies the LM head to every row (model/model.py:648-650).
      • So below SM120, an NVFP4 LM head dequantizes on every prefill call, short prompts included.
      • The posted measurements cover qko, v, gate_up, o and down, not the LM head.
    • dequant. The README says it "forces dequant + matmul" and names only the w4a4 and FP32 exceptions. But it applies to every M not statically ≤ 4 (nvfp4_dispatch.py:19-22, :270, :277):
      • In an --use-offgraph-kv-cache export it also dequantizes the static forward_8 … forward_64 methods (DEFAULT_FORWARD_SIZES, export_solo.py:259).
      • Your static-M A100 numbers have the fused kernel 1.8–3× faster for those sizes (28.8 vs 85.4 ms per forward at M=16).
      • forward_1/_2/_4 stay fused.
      • The README mentions neither point.
    • Fix this →

Performance

  • auto picks dequant based on the GPU, not on whether FP4 tensor cores are actually used (nvfp4_dispatch.py:273-276, _linear at :444-449).
    • Which kernel runs: on SM120 under --nvfp4-act w4a16 or w4a8, a dynamic-M prefill linear skips the dequant branch, because _has_native_fp4() is True. It runs nvfp4_w4a16 instead: the in-register-dequant BF16 kernel, tuned at the example M.
    • The stated reason doesn't apply: the fused kernels are kept with native FP4 because of the FP4 tensor cores (W4A4), and no FP4 MMA runs in these two modes.
    • What you measured: on A100/H100, dequant + matmul beat this same kernel (with the software decode) by 1.5–2.4× at T = 512–2048.
    • What's unknown: on SM120 nvfp4_w4a16 uses the native cvt, so the margin may be smaller. This is suspected, not measured.
    • Same numerics: dequant + matmul keeps the w4a16 contract, with BF16 activations and the same rounded weights.
    • Ask: time kernel against dequant under w4a16 on the 5090.
      • If dequant wins, make the auto branch return True for these modes as well (mode in ("w4a16", "w4a8") or not _has_native_fp4()).
      • Otherwise, state in the docstrings that auto picks based on the GPU, not the activation mode.
    • Fix this →

Recommendation

Approve

Nothing blocks. Three of the four findings are fixes to docs, comments or test markers that don't change any compiled program. The SM120 w4a16/w4a8 routing only matters for an opt-in activation mode, and settling it needs a measurement.

  • Gather the PR context, the diff (14 files, +608/−30) and the earlier review rounds
  • Get independent reviews of every changed file from three reviewers
  • Consolidate the findings
  • Fact-check the findings against the code
  • Post the review

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

CI update: the A10G unittest-cuda (system) job hit the 2-hour limit on the top of this stack (NVFP4 tests were ~60 min on A100, more on A10G). This PR's tests now run representative cases by default via sweep(full, quick) in nvfp4_test_utils; the full lists run with ET_CUDA_NVFP4_EXHAUSTIVE_TESTS=1, which the new unittest-cuda-nvfp4-exhaustive job in #25437 sets. No kernel or dispatch code changed in this update. Whole-stack NVFP4 test time on A100: 3582 s -> 752 s.

Authored with Claude Code.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 25m 7s —— View job


Approve: nothing blocks; one new question is whether the A100/H100 numbers behind the auto default came from CudaBackend-lowered programs, since the description credits cuBLAS but the backend builds the dense matmul from Triton templates only.

Detailed review

PR Review: #25433

Summary

On GPUs without native FP4 (below SM120, and ROCm), NVFP4 linears whose M is not statically ≤ 64 now default to whole-weight triton::nvfp4_dequant plus a matmul, except under W4A4 and the FP32 output policy; ET_CUDA_NVFP4_PREFILL_IMPL=auto|kernel|dequant selects the path. There is no GPU here, so nothing was run; every finding comes from reading the code. One new question is below. The previous round's four minor points have no reply and are unchanged in the code: auto keeps the fused W4A16 kernel for long prompts on SM120 under --nvfp4-act w4a16/w4a8 without a measurement, the README (examples/models/muse-glimmer/README.md:428-437) misstates which linears dequantize under --logits and dequant, test_nvfp4_dequant.py skips ROCm, and the comment at _gemm_family_dispatch.py:33-34 leaves out dequant on native-FP4 GPUs.

Performance

  • The description credits cuBLAS, but CudaBackend builds the dense matmul from Triton templates only (backends/cuda/cuda_backend.py:1556-1558).
    • CudaBackend compiles with max_autotune=True and max_autotune_gemm_backends="TRITON", and neither backends/cuda nor backends/aoti provides an ATen mm shim. So the F.linear in _dequant_linear (nvfp4_dispatch.py:280-291) becomes an Inductor Triton mm template.
    • For a dynamic-M method, that template is autotuned once at the export example M, the same as the fused kernel. The description's argument ("such a method tunes the fused kernel at its example M, and on A100 that large-M tile loses to dequant + cuBLAS at small M too") relies on the matmul choosing a kernel for the runtime M. cuBLAS does that; a single Triton template doesn't.
    • If the A100/H100 tables were timed on .pte files lowered through CudaBackend: only the wording is off. Say "dequant + Inductor Triton matmul".
    • If they were timed in eager PyTorch or with stock AOTI (cuBLAS): the short-prompt rows that justify dequantizing dynamic-M methods from M = 5 don't describe the shipped program. Timing M = 5–64 on a CudaBackend .pte would settle it.
    • Low confidence: this is a question about how the numbers were taken, not a defect in the code.

Recommendation

Approve

Nothing blocks. The question above only bears on how well the measurements support the auto default, and ET_CUDA_NVFP4_PREFILL_IMPL=kernel restores the fused kernel if short prompts turn out slower.

  • Gather the PR context, the diff (14 files, +624/−30) and the earlier review rounds
  • Get independent reviews of every changed file from three reviewers
  • Consolidate the findings
  • Fact-check the findings against the code
  • Post the review

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Follow-up: the exhaustive switch is now the directory's existing EXECUTORCH_CUDA_EXHAUSTIVE_TESTS (as in test_conv_implicit_gemm.py) instead of a new ET_CUDA_NVFP4_EXHAUSTIVE_TESTS, in code, the commit message and #25437's job.

Authored with Claude Code.

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — f6cc00c5 Deployed Nov 23, 2026 by Gasoonjia via upload-benchmark-results #23171
cadence — f6cc00c5 Deployed Nov 23, 2026 by Gasoonjia via hifi-op-test / hifi4 #40342
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant