Skip to content

[executorch][cuda] NVFP4: exact FP16-bit FP4 decode and paired W4A16 without native FP4 - #25430

Open
Gasoonjia wants to merge 9 commits into
gh/Gasoonjia/137/basefrom
gh/Gasoonjia/137/head
Open

Gasoonjia wants to merge 9 commits into
gh/Gasoonjia/137/basefrom
gh/Gasoonjia/137/head

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Without native E2M1 conversion (below SM120) the GEMV decoded each code through a float LUT expression, and W4A16 used a separate element-wise kernel. Both now place the bits directly: an E2M1 code becomes an FP16 value times 2**-14 and an E4M3 scale an FP16 value times 2**-8, both exact for every finite byte, and one FP32 multiply by 2**22 restores the product. Kernels assume finite E4M3 scales: CudaNVFP4Tensor.from_exportable rejects the NaN bytes 0x7F/0xFF (after the constructor's dtype checks), so the decode needs no NaN select (on A100 one cost ~0.29 ms/token in the W4A8 decode GEMV). The in-repo quantizer used to give an all-zero weight a zero global scale and so NaN block scales; it now uses a unit global scale there, and the weight packs and runs as zeros. GEMV and W4A16 share one _decode_pair(q, s, NATIVE) helper that returns the exact products; the GEMV's NATIVE_E4M3 variant is gone (native FP4 implies native E4M3). W4A16 runs the paired (two codes per byte) kernel on every GPU, so the old element-wise kernel is removed. Unit-scale BF16 GEMV skips the extra rounding on all GPUs: E2M1 x E4M3 products have at most six significant bits, so unit_scale now only requires a global scale of 1 (finite scales of either sign).

Authored with Claude Code.

Differential Revision: D131418683

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/25430

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

❌ 1 New Failure, 1 Cancelled Job, 1 Pending

As of commit 0fe52bc 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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 22, 2026
@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 19m 27s —— View job


Summary: The decode math is exact for every finite input, but the new _e4m3_f16 turns NaN scale bytes into ±480 on every GPU below SM120, the NATIVE_E4M3 removal was only done for W4A16 and not GEMV, and the new tests are weaker than the existing ones in the same file.

PR Review: #25430 — detailed findings

Summary

This PR replaces the software E2M1/E4M3 decode in the NVFP4 GEMV and W4A16 kernels (used on GPUs without native FP4) with exact FP16 bit placement. It also runs the paired W4A16 kernel on every GPU and turns on the unit-scale BF16 shortcut for the software path.

I checked the math by working through the bits by hand: all 16 E2M1 codes, all 254 finite E4M3 bytes, and their FP32 products come out exact. The problems are how NaN scales are handled, NATIVE_E4M3 still being in GEMV, and gaps in the new tests. I did not run any GPU tests because this environment has no GPU.

Code Quality

  • NaN scales now decode to ±480 below SM120 (backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:236-240).
    • What happens: _e4m3_f16(0x7F) produces FP16 0x3F80 (1.875). After the 2**22 rescale that is 480, and 0xFF gives −480.
    • Before this PR: the software GEMV and W4A16 paths decoded scales with _e4m3_to_f32, whose docstring says "0x7F/0xFF decode to NaN either way". The native branches (:815, :1047), _embedding (:1210) and CudaNVFP4Tensor.dequantize still return NaN.
    • When it triggers: a weight without unit_scale that has a NaN block scale, for example one quantized from a NaN or Inf weight. The unit_scale contract (nvfp4_tensor.py:54-58) only rules out 0x7F for unit-scale weights.
    • Effect: on A100, H100 and B200, nvfp4_gemv and nvfp4_w4a16 return finite code × 480 × pts values without any error. SM120 returns NaN for the same weight.
    • Why nothing catches it: the docstring "exact (FP16 holds every E4M3 value)" is wrong for these two bytes, and test_fp16_bit_placement_is_exact filters them out (test_nvfp4_soft_decode.py:160).
    • Fix: add the (u & 0x7F) == 0x7F NaN select that _e4m3_to_f32 has, or document that these kernels need finite scales and add a test for that. Fix this →
  • NATIVE_E4M3 was removed from W4A16 but kept in GEMV, where it no longer does anything (nvfp4_quantized_gemm.py:779, 815-818, 857, 878, 898, 934).
    • Why it's dead: it is only read inside if NATIVE:. Production sets NATIVE only on SM120, and there _has_native_e4m3() is always True.
    • Duplicate test runs: test_pinned_gemv_variants (test_nvfp4_kernels.py:353) still parametrizes native_e4m3. On SM89+ the native=False cases compile and run the same kernel twice.
    • Outdated text: the skip_unbuilt_variant docstring (test_nvfp4_kernels.py:332-333) and the assert and comment at test_nvfp4_unit_scale.py:122-123 ("The launcher builds the decode the device supports natively") describe a choice that no longer happens below SM120.
    • Test builds an unused combination: fixed_gemv (test_nvfp4_soft_decode.py:182-198) leaves out NATIVE_E4M3. Its native=True case on SM120 therefore combines native FP4 with the software E4M3 decode. Production never builds that, and skip_unbuilt_variant skips it on purpose (test_nvfp4_kernels.py:338-339).
    • Diverging copies: the (lo, hi, sf) decode blocks at :797-826 and :1029-1059 are now near-copies. Their native branches decode the scale differently: _e4m3_to_f32(…, NATIVE_E4M3) in one, .to(tl.float8e4nv, bitcast=True) in the other.
    • Fix: removing NATIVE_E4M3 from GEMV lets one @triton.jit decode helper serve both kernels. Fix this →
  • _w4a16_paired now defaults NATIVE to True (nvfp4_quantized_gemm.py:1003).
    • Conflict: its only caller, _w4a16, defaults NATIVE to False (:1111) and has become a one-line forwarder (:1114-1116).
    • Risk: a future caller that leaves the flag out gets SM120-only inline PTX. That fails to compile on every other GPU this kernel now runs on.
    • Fix: move the body into _w4a16, which removes both the forwarder and the conflicting default. Fix this →
  • set_wrap_triton_enabled(False) appears to do nothing (test_nvfp4_soft_decode.py:243, 254).
    • Why: it and its import inside the function only wrap raw kernels._w4a16.fn[grid] launches, which do not go through wrap_triton.
    • Inconsistency: fixed_gemv and test_pinned_w4a16_variants launch the same way without it.

Testing

  • Nothing checks the unit-scale BF16 shortcut bit-for-bit on the software path (nvfp4_quantized_gemm.py:828).
    • Why the existing test doesn't help: test_unit_scale_gemv_bitwise_same_tile (test_nvfp4_unit_scale.py:39-80) hard-codes NATIVE=True and skips without native FP4. The CUDA CI runners (.github/workflows/cuda.yml) are A10G and A100, so it always skips there.
    • Current CI coverage: only the ("unit", True) case, with a 1e-2 tolerance (test_nvfp4_soft_decode.py:237).
    • Fix: parametrize that test over NATIVE so CI checks the exactness claim. Fix this →
  • The new kernel sweeps use the weak inputs that this file's own helpers were written to avoid (test_nvfp4_soft_decode.py:224, 237, 246, 277).
    • Inputs: random_weight draws only non-negative scale bytes and mixes 0..0x7E within each row.
    • Error measure: relative_error divides by the largest output, so a decode error limited to small or subnormal scales can stay under 1e-2.
    • Existing better helpers: full_range_weight and relative_error_per_row (lines 35-58) exist "so a wrong small or subnormal scale cannot hide behind larger rows".
    • K tail never exercised: K=1024 is a multiple of every BK in the sweep, so the masked K tail is never hit.
    • No FP16 activations: neither this file nor test_nvfp4_kernels.py uses FP16 activations, even though FP16 W4A16 now also runs the software paired kernel on every GPU except SM120. Fix this →
  • native_modes() drops the native case without a skip (test_nvfp4_soft_decode.py:214-218, 240).
    • Problem: it queries the GPU while pytest is collecting tests and quietly leaves out the native case. Missing native coverage therefore never shows up as a skip.
    • Existing pattern: the same file (lines 91-95) and test_nvfp4_kernels.py:399-402 parametrize [False, True] and call pytest.skip inside the test.

Performance

  • No timings for the GPUs this PR changes. The software path runs wherever _has_native_fp4_conversion() is False, which means compute capability major < 12. That includes B200/GB200, so the description's "pre-SM100" understates what changes.
    • W4A16 on these GPUs: it moves from the element-wise kernel to the paired kernel's tl.join(...).reshape(...) + tl.trans B-tile path, which until now ran only on SM120.
    • Scale decode on SM89–SM10x (L4, H100, B200): both GEMV and W4A16 replace the hardware E4M3 conversion with the integer bit-placement decode.
    • Request: the element-wise kernel is deleted with no fallback, so please share before/after W4A16 and GEMV timings on at least A100 and H100, plus B200 if available.
    • Confidence: low; I could not measure any of this.

Recommendation

Request Changes: decide on NaN-scale behaviour and document it (or bring back NaN propagation), and remove NATIVE_E4M3 from GEMV so the tests and assertions match the kernels. The other findings are minor.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run independent reviews (3 reviewers)
  • Consolidate findings
  • Fact-check findings
  • Post final review

Not done: GPU tests were not run because there is no GPU here. The numeric claims were checked by working through the bits by hand.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 19m 49s —— View job


No new issues this round. Three minor items from earlier rounds are still open; they are listed below but not argued again. Approve.

PR Review: #25430 — detailed findings

Summary

Below SM120, the PR decodes NVFP4 exactly by placing FP16 bits in a shared _decode_pair. It also runs the paired W4A16 kernel on every GPU, makes CudaNVFP4Tensor.from_exportable reject NaN scale bytes, and has the quantizer give an all-zero weight a unit global scale. I found no new issues.

These items from earlier rounds are still open at this head. I did not raise them again as findings:

  • _embedding still uses its own decoders: _fp4, plus _e4m3_to_f32 with the NaN select and NATIVE_E4M3=_has_native_e4m3() (backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:1147, :1159, :1200).
  • fixed_gemv passes ROW_PTS=pts.numel() != 1 to _reduce_partials (backends/cuda/tests/test_nvfp4_soft_decode.py:205), but _launch_gemv_impl passes False (nvfp4_quantized_gemm.py:945).
  • The soft-decode sweeps still use a 1e-2 per-row bound (test_nvfp4_soft_decode.py:250, :288).

Recommendation

Approve. Nothing blocks.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run independent reviews (3 reviewers)
  • Consolidate findings
  • Fact-check findings
  • Post final review

Not run: no tests, on GPU or otherwise, because there is no GPU here. This review comes from reading the code at gh/Gasoonjia/137/head against origin/gh/Gasoonjia/137/base. The third-party/ao submodule isn't checked out, so I could not check what torchao produces for an all-zero weight; I relied on your confirmation.

@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 19m 28s —— View job


No correctness bugs. One item should be fixed before landing: the quick/exhaustive split from the latest update misses this PR's two largest kernel sweeps, and both run in the system shard that hit the time limit. Approve.

PR Review: #25430 — detailed findings

Summary

Below SM120, the PR decodes NVFP4 exactly by FP16 bit placement through a shared _decode_pair and runs the paired W4A16 kernel on every GPU. It also rejects NaN scale bytes in CudaNVFP4Tensor.from_exportable and gives an all-zero weight a unit global scale. I found no correctness bugs. Two minor items are new this round: two sweeps aren't gated by sweep, and one error message doesn't name the bad weight.

Still open from earlier rounds (listed, not argued again):

  • _embedding still has its own decoders: _fp4, _e4m3_to_f32, and NATIVE_E4M3=_has_native_e4m3() (backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:1147, :1159-1161, :1200).
  • fixed_gemv passes ROW_PTS=pts.numel() != 1 to _reduce_partials (backends/cuda/tests/test_nvfp4_soft_decode.py:206), but _launch_gemv_impl passes False (nvfp4_quantized_gemm.py:945).
  • Two module docstrings describe only one decode path, but the tests now cover both: test_nvfp4_soft_decode.py:5 ("GPUs without native FP8/FP4 conversion") and test_nvfp4_unit_scale.py:5 ("native GEMV equivalence").
  • The soft-decode sweeps still use a 1e-2 per-row bound (test_nvfp4_soft_decode.py:251, :289).

Infrastructure

  • The quick/exhaustive split misses this PR's two largest kernel sweeps. In this diff, only test_w4a16_soft_fp4_matches_reference goes through sweep (backends/cuda/tests/test_nvfp4_soft_decode.py:268).

    • test_gemv_soft_fp4_matches_reference (:238-251):
      • Each case loops over all 8 gemv_configs(half2=False) × split_k (1, 2) × m (1, 3).
      • BN, BK and SPLIT are constexpr (nvfp4_quantized_gemm.py:870-872), so each case builds 16 kernel variants, or 32 if Triton specializes M == 1.
      • By my estimate that is about 100–190 _gemv compiles over the 6 cases that run on A10G/A100. SM120 runs 12 cases.
    • test_unit_scale_gemv_bitwise_same_tile (backends/cuda/tests/test_nvfp4_unit_scale.py:37):
      • Before this PR it skipped without native FP4. Now its 24 (False, False) cases run on A10G/A100, with two _gemv compiles each.
      • It still uses the full split list [1, 2, 4, 8, 16, 32]. The base already wraps that same list in sweep at test_nvfp4_kernels.py:307, :322 and test_nvfp4_fusion.py:361, :372.
    • Why it matters: neither file is in KERNEL_TESTS (.github/workflows/cuda.yml:540-559). Both run serially in the A10G system shard (:647, 120-minute timeout at :528), the job your update says hit the limit.
    • Fix:
      • In the GEMV test, wrap the configs and (m, split_k) pairs in sweep(...), as test_kernels_decode_every_scale does at :102-103. For example, the quick list could keep one config per distinct BK (256, 512, 1024). TAIL_K = 1040 still gives a masked tail for every BK.
      • Wrap the unit-scale split list in sweep([1, 2, 4, 8, 16, 32], ...).
    • To check the cost: the system shard prints --durations=20 (cuda.yml:647), so the next CUDA run will show what these two tests cost. That run was still queued when I checked.

    Fix this →

Code Quality

  • The new ValueError in from_exportable doesn't say which weight is bad (backends/cuda/nvfp4_tensor.py:141-142).

    • Callers: both packers call it once per tensor and don't add the name:
      • examples/models/muse-glimmer/loaders/checkpoint_loader.py:340, reached from the per-FQN loop at :373;
      • examples/models/gemma4_31b/cuda_packers.py:65.
    • Trigger: an external checkpoint with one NaN scale byte, for example an all-zero tensor from a two-level quantizer. Packing fails with "NVFP4 E4M3 scales must be finite (no 0x7F/0xFF bytes)", and nothing says which weight caused it.
    • Fix: put the scale shape and the first offending (row, block) index in the message, computed only when raising. Alternatively, have the two loaders re-raise with the FQN.

    Fix this →

Recommendation

Approve. Nothing blocks. The sweep gap is worth fixing before landing, because it affects the same job the latest update is meant to fix.


  • Gather context (diff, changed files, CLAUDE.md)
  • Run independent reviews (3 reviewers)
  • Consolidate findings
  • Fact-check findings
  • Post final review

Not run: no tests, because there is no GPU here. The CUDA workflow for this head was still queued, so I couldn't read its --durations output. The compile counts are estimates from reading the code at gh/Gasoonjia/137/head against origin/gh/Gasoonjia/137/base.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Done: both of this PR's large kernel sweeps are split now.

  • test_gemv_soft_fp4_matches_reference: by default it runs one single-stage tile per BK (4x256, 8x512, 8x1024) and two of the four (M, split-K) pairs, (1, 2) and (3, 1), with the masked K tail (TAIL_K=1040) unchanged. EXECUTORCH_CUDA_EXHAUSTIVE_TESTS=1 runs every tile against every pair.
  • test_unit_scale_gemv_bitwise_same_tile: splits 1 and 8 by default, all of 1..32 with the switch.
  • The W4A16 fixed-tile sweep was already split. The commit message and Add an NVFP4 GGUF solo Muse Glimmer CUDA e2e job #25437's exhaustive job cover all three.
  • RTX 5090: at this commit test_nvfp4_soft_decode.py + test_nvfp4_unit_scale.py pass in both modes: 54 passed in 60 s by default, 102 passed in 107 s with the switch.
  • 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 Add an NVFP4 GGUF solo Muse Glimmer CUDA e2e job #25437's job.

Authored with Claude Code.

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — 0fe52bc0 Deployed Nov 23, 2026 by Gasoonjia via upload-benchmark-results #23176
cadence — 0fe52bc0 Deployed Nov 23, 2026 by Gasoonjia via hifi-op-test / hifi4 #40348
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