Skip to content

[executorch][cuda] NVFP4: exact software E4M3 scale decode below SM89 - #25411

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

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

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Triton has no float8e4nv before SM89, so every NVFP4 kernel failed to compile on SM80/SM86. _e4m3_to_f32 now builds the FP32 bits of each E4M3 scale in integer math there (normal and subnormal, sign included, 0x7F/0xFF as NaN; bit-exact with torch.float8_e4m3fn) and keeps the native conversion on SM89+. The path is chosen by an assume_constant_result capability predicate passed to the kernels as the NATIVE_E4M3 constexpr, the same pattern as NATIVE, so importing the module does not query the GPU and forked compile workers build exactly what the parent's constants select. It is part of the GEMV/W4A16 autotune keys. The paired W4A16 kernel only runs with native FP4 (SM120) and keeps the native decode.

The NVFP4 kernel tests no longer skip below SM89; only the activation quantizer (used by native W4A4) still needs native E4M3.

Authored with Claude Code.

Differential Revision: D131418682

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

…code down so A100 CI runs the NVFP4 kernels

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 1 Cancelled Job, 2 Pending

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

NEW FAILURES - The following jobs have failed:

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

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

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

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

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

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


Summary: Requesting changes: _NATIVE_E4M3 is set by a CUDA driver query when the module is imported, with a fragile nvidia-smi fallback for compile workers, instead of the assume_constant_result + constexpr-argument pattern this file already uses for NATIVE; the other four findings are minor.

Detailed review

PR Review: #25411

Summary

The PR adds an integer-math E4M3→FP32 scale decode for GPUs below SM89, chosen by a module-level _NATIVE_E4M3 constexpr, and drops the SM89 skips from the NVFP4 tests. How that branch is chosen is the main problem (see Backward Compatibility); everything else is minor. All 8 changed files were reviewed. Nothing was run on a GPU because this runner has none, so the decode math was checked by hand.

Code Quality

  • NaN scale bytes decode to ±480 on the software path (minor).
    • Where: backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:163.
    • Problem: byte 0x7F gives (0x7F << 20) + (120 << 23) = 0x43F00000, which is 480.0, and 0xFF gives −480.0. The native float8e4nv conversion returns NaN for both.
    • When it matters: PyTorch's float8_e4m3fn cast turns magnitudes ≥ 480 into these bytes. A corrupt or unclamped scale then gives NaN output on SM89+, but on SM80/86 it silently scales the weights by 480.
    • The "bit-exact" claim only holds because finite_e4m3_bytes() (test_nvfp4_soft_decode.py:30-32) leaves these bytes out.
    • Fix: map (u & 0x7F) == 0x7F to NaN with one more tl.where, and add both bytes to test_e4m3_decode_is_exact. At minimum, say "finite" in the comment at :126-127. Fix this →
  • The _gemv_half2 hunk edits branches that never compile (minor).
    • Where: nvfp4_quantized_gemm.py:629-641.
    • Problem: the only caller is _gemv (:776-779). It calls _gemv_half2 only under NATIVE and HALF2, always with HALF2=True, SCALE_ONCE=True. So the new _e4m3_to_f32 calls at :632 and :641 never run, and the hunk only copies the bitcast into both branches.
    • Fix: revert the hunk so the diff only touches the kernels SM80/86 actually compile: _gemv_original, _w4a16_original and _embedding. Fix this →

Infrastructure

  • The newly unskipped NVFP4 tests all land in the A10G system shard (minor; question for the author).
    • Background: unittest-cuda runs on mt-l-x86aavx2-11-41-a10g (SM86), where every module this PR unskips used to be skipped. .github/workflows/cuda.yml:538-539 sends any test not listed in KERNEL_TESTS to the system shard. :516-518 says the two shards together already don't fit the 120-minute timeout.
    • What the system shard now also runs:
      • the new Triton-kernel test test_nvfp4_soft_decode.py, which isn't added to KERNEL_TESTS;
      • the kernel cases in test_nvfp4_kernels.py and test_nvfp4_fusion.py;
      • 24 AOTI export→PTE runs from test_split_k_pte, i.e. gemv/w4a16, two row-scale settings, six splits;
      • the w4a16 cases of test_packed_linear_pte and test_fused_row_scale_pte.
    • Ask: please check how long the system shard takes on this PR's run (it was still in progress when I looked). Also add test_nvfp4_soft_decode.py, and probably test_nvfp4_kernels.py, to KERNEL_TESTS. Fix this →

Testing

  • The end-to-end soft-decode tests can't catch errors in individual scales (minor). All in backends/cuda/tests/test_nvfp4_soft_decode.py:
    • test_kernels_decode_every_scale divides the error by the largest output (relative_error, :61-62, checked at :124). Every row mixes random scales from 2⁻⁹ to 448, so the 1e-2 bound allows absolute errors far larger than anything the subnormal or small normal scales contribute. Decoding every subnormal scale as 0 in _gemv_original or _w4a16_original would still pass.
    • test_embedding_decodes_every_scale_exactly looks up only 7 distinct rows (:131). That is 56 of the 2,032 scale bytes, so whether a given byte, or any subnormal, is covered depends on the seed.
    • full_range_weight promises "every finite E4M3 scale byte" (:42). But torch.randint(0, 0x7F) (:47-49) draws only 0x00–0x7E, so the sign bit is never set.
    • Fix: give each row a single scale byte (e.g. s[r, :] = r % 127) and check the error per row. In the embedding test, use ids = torch.arange(n). Fix this →

Backward Compatibility

  • _NATIVE_E4M3 comes from a CUDA driver query at import time (major). The code is at nvfp4_quantized_gemm.py:128-153.
    • Importing the package now initializes CUDA on GPU hosts.

      • torch.cuda.get_device_capability() runs torch.cuda._lazy_init() when the module loads.
      • quantize_op_dispatch/__init__.py:27-33 imports nvfp4_dispatch for every dtype, and nvfp4_dispatch.py:32 imports this module at the top level.
      • So import executorch.backends.cuda.quantize_op_dispatch now initializes CUDA. That is the documented entry point for INT4/5/6/8 users as well as NVFP4.
      • A script that imports it, then forks CUDA-using child processes before touching CUDA itself, now fails with "Cannot re-initialize CUDA in forked subprocess".
    • It breaks a written rule and this file's own pattern. quantized_gemm_utils.py:40-43 says module-level constexprs must be set without querying the driver, because compile workers are forked and cannot initialize CUDA. This file already follows that rule for its other capability switch: _has_native_fp4_conversion() is an assume_constant_result predicate, passed to the kernels as the NATIVE constexpr (:817, :1057).

    • The nvidia-smi fallback this design needs is fragile.

      • It asks about the wrong GPU. _compile_in_process sets CUDA_VISIBLE_DEVICES="" before importing the module (quantized_gemm_family.py:245, :253). So first (:138) is always "0", and the worker asks about the first GPU in nvidia-smi's PCI order, not the parent's device. On a host with mixed GPU types the worker can build the other branch, and the parent then compiles again itself.
      • Its test checks a state the real worker never reaches. test_native_e4m3_in_forked_worker sets CUDA_VISIBLE_DEVICES="3,1" and asserts -i 3.
      • Failures aren't handled. Nothing covers a missing binary (FileNotFoundError), non-numeric output (ValueError from int()), a non-zero return code, or a hang (there is no timeout).
      • The error escapes the module import. _compile_in_process only catches ImportError/AttributeError, so _workers_failed treats the error as one config failing. Every NVFP4 config then logs a warning and is compiled again in the parent. Each request also retries the import, because a failed import isn't cached.
    • The software path can't be tested on newer GPUs. The branch is fixed for the whole process, so nothing can select the software decode on an SM89+ GPU. There, test_e4m3_decode_is_exact only compares the native conversion with PyTorch, and the integer path runs only on SM80/86.

    • Fix:

      • Add an @torch._dynamo.assume_constant_result predicate next to _has_native_fp4_conversion, keeping its HIP check.
      • Pass it as a constexpr from _launch_gemv_impl, _launch_w4a16_impl and nvfp4_embedding.
      • Make _e4m3_to_f32 take it as a tl.constexpr argument.
      • With that, workers compile exactly what the parent's constants say, the nvidia-smi code and its test go away, and one test can check both branches on any GPU.

      Fix this →

Recommendation

Request Changes. Replace the import-time driver query and its nvidia-smi fallback with the existing assume_constant_result + constexpr-argument pattern. That also lets the software path be tested on SM89+. The other findings are minor.

Gasoonjia added a commit that referenced this pull request Nov 21, 2026
Pull Request resolved: #25411

Triton has no `float8e4nv` before SM89, so every NVFP4 kernel failed to compile on SM80/SM86. `_e4m3_to_f32` now builds the FP32 bits of each E4M3 scale in integer math there (normal and subnormal, sign included, 0x7F/0xFF as NaN; bit-exact with `torch.float8_e4m3fn`) and keeps the native conversion on SM89+. The path is chosen by an `assume_constant_result` capability predicate passed to the kernels as the `NATIVE_E4M3` constexpr, the same pattern as `NATIVE`, so importing the module does not query the GPU and forked compile workers build exactly what the parent's constants select.

The NVFP4 kernel tests no longer skip below SM89; only the activation quantizer (used by native W4A4) still needs native E4M3.

Authored with Claude Code.

Differential Revision: [D131418682](https://our.internmc.facebook.com/intern/diff/D131418682/)

**NOTE FOR REVIEWERS**: This PR has internal Meta-specific changes or comments, please review them on [Phabricator](https://our.internmc.facebook.com/intern/diff/D131418682/)!
ghstack-source-id: 480463866
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Fixed:

  • No import-time GPU query: _NATIVE_E4M3 and the nvidia-smi fallback are replaced by _has_native_e4m3() (assume_constant_result, with the HIP check), passed as the NATIVE_E4M3 constexpr from the GEMV/W4A16/embedding launchers into _e4m3_to_f32, the same pattern as NATIVE. Compile workers build exactly what the parent's constants select, and the forked-worker test is gone.
  • The software path decodes 0x7F/0xFF to NaN.
  • _gemv_half2 is untouched: its dead branches were removed in [executorch][cuda] NVFP4 W4A16, GEMV and embedding kernels #25341.
  • Tests:
    • Both decode paths are checked against torch.float8_e4m3fn for all 256 bytes; the software path is selectable on any GPU.
    • The GEMV/W4A16/embedding tests give each weight row a single scale byte (254 rows = every finite byte, both signs, all subnormals) and check error row by row.
    • The embedding test uses arange(n) ids.
  • test_nvfp4_soft_decode.py is in KERNEL_TESTS.
  • On A100 (SM80), every NVFP4 kernel, soft-decode and gate/up test that does not need native FP4 passes. The only failures there are environment ones: the A100 env's torch lacks has_grouped_mm_triton_support, which breaks every AOTI lowering, and it has no ExecuTorch pybindings. The 3 timing/autotune export tests fail the same way on base.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 28m 30s —— View job


Summary: I'd approve this. All eight findings are minor, but two should be fixed before landing: the KERNEL_TESTS change your reply describes isn't in the push, and the tests that launch kernels directly don't pass NATIVE_E4M3, so they now build decode variants that no launcher builds.

Detailed review

PR Review: #25411

Summary

The PR adds an integer-math E4M3→FP32 scale decode for GPUs below SM89, selected by a new NATIVE_E4M3 constexpr that comes from an assume_constant_result predicate, and unskips the NVFP4 tests below SM89.

  • All 9 changed files were reviewed, and all eight findings are minor: three code quality, one infrastructure, two testing, two performance.
  • Nothing was run. This runner has no GPU and CPU-side Python checks weren't permitted, so the decode bit math was checked by hand.
  • unittest-cuda (system) and unittest-cuda (kernel) for 866b46a were still running when this review was written.

Code Quality

  • _w4a16_paired gained a software-decode branch that no launcher builds (minor).
    • Where: nvfp4_quantized_gemm.py:964 and :1000-1003.
    • Problem: _w4a16_paired only runs under NATIVE (:1059-1062). NATIVE needs SM12x (_has_native_fp4_conversion, :191-197), which always has native E4M3. _gemv_half2, the other NATIVE-only kernel, keeps the native decode (:642-650).
    • Reach: the new branch is reachable only from the direct test launches covered under Testing.
    • Fix: revert the _w4a16_paired hunk and pass NATIVE_E4M3 only to _w4a16_original. Fix this →
  • The PR description is out of date (minor).
    • Problem: "The capability check falls back to nvidia-smi inside forked compile workers" no longer matches the code. _has_native_e4m3 (nvfp4_quantized_gemm.py:164-170) is a plain assume_constant_result predicate passed in as a constexpr.
    • Fix: this text becomes the landed commit message, so please update it here and in the D131418682 summary.
  • The new test file has two leftovers (minor). Both are in test_nvfp4_soft_decode.py:
    • relative_error (:66-67) is never called.
    • test_has_native_e4m3_matches_device (:90-91) repeats the predicate's own >= (8, 9) check. The module mark already skips HIP and no-CUDA, so the test can only fail if the two copies drift apart.
    • Fix: delete both. Fix this →

Infrastructure

  • test_nvfp4_soft_decode.py is not in KERNEL_TESTS, though your reply says it is (minor).
    • Where: .github/workflows/cuda.yml:540-559. The workflow file isn't part of this PR, and the list still contains no NVFP4 file.
    • Effect:
      • Per cuda.yml:538-539, the file runs in the A10G system shard.
      • So does every NVFP4 test this PR unskips, including test_nvfp4_kernels.py, although cuda.yml:516 puts Triton kernel tests in the kernel shard.
      • Both shards were still running for 866b46a, so I couldn't check the system shard's run time against the 120-minute timeout (:528).
    • Buck:
      • test_nvfp4_kernels and test_nvfp4_dispatch (backends/cuda/tests/targets.bzl:623-652) run only on A100, so every test this PR unskips runs there for the first time.
      • No passing run below SM89 has been reported for the AOTI/.pte tests in test_nvfp4_dispatch. Your reply says the A100 environment you used lacks has_grouped_mm_triton_support, which breaks every AOTI lowering.
    • Fix: add test_nvfp4_soft_decode.py and test_nvfp4_kernels.py to KERNEL_TESTS. Then confirm the system shard's run time and the A100 results for test_nvfp4_dispatch. Fix this →

Testing

  • Tests that launch kernels directly don't pass NATIVE_E4M3, so they get the False default on every GPU (minor).
    • Where: test_nvfp4_kernels.py:234, :265, :360 and :412, and test_nvfp4_unit_scale.py:48.
    • On SM12x: four tests now build NATIVE=True with the software decode, which no launcher builds:
      • test_pinned_gemv_variants[native=True, half2=False]
      • test_pinned_w4a16_variants[native=True]
      • test_split_workspace_exceeds_int32[w4a16]
      • test_unit_scale_gemv_bitwise_same_tile[half2=False]
    • Lost coverage: nothing pins the _gemv_original variant the autotuner can actually pick on SM12x any more, which defeats "pin each one here" (test_nvfp4_kernels.py:221).
    • On SM89+: the native=False pins and the embedding and workspace tests also switch from the decode production uses to the software one.
    • Fix: pass NATIVE_E4M3=_has_native_e4m3() at these five launches. If you also want the software decode to run inside the real kernels on SM89+, parametrize it for the native=False cases only. Fix this →
  • test_kernels_decode_every_scale can fail at m=1 even when the decode is exact (minor, low confidence).
    • Where: test_nvfp4_soft_decode.py:105-115, with relative_error_per_row at :33-38.
    • Problem: with one activation row, size is a single dot product per column. When a column's 512 terms nearly cancel, the normal fp32 difference between the kernel's and cuBLAS's summation order becomes a large relative error.
    • Why it is fragile:
      • The root conftest.py:100-103 seeds each test from its node id, so a given seed passes or fails every time. The autotuned config still changes the kernel's summation order.
      • I estimate (without running it) that roughly 1–4% of seeds fail across the ~500 m=1 column checks per parametrization.
      • So renaming or re-parametrizing the test, or adding a random draw before x, could turn it red.
    • Fix: divide by (x.float().abs() @ w.abs().T).amax(0) instead of expected.abs().amax(0). Each row still catches a wrong scale. Fix this →

Performance

  • NATIVE_E4M3 is missing from the autotune keys (minor).
    • Where: nvfp4_quantized_gemm.py:765 (_gemv) and :1036 (_w4a16). The other path switches, NATIVE, ROW_PTS and UNIT_SCALE, are already in them.
    • Problem: _tuning_key (quantized_gemm_family.py:155-164) is built from these keys.
      • A process can launch both decode variants, for example a test that monkeypatches _has_native_e4m3. The second variant then reuses the config tuned for the first.
      • Compiled binaries are still keyed by every constexpr, so this affects only performance.
    • Fix: add "NATIVE_E4M3" to both keys. Fix this →
  • The software decode runs once per loaded element instead of once per scale (minor, low confidence).
    • Where: _gemv_original (:733-735, tile [BN, BK//2]) decodes each scale 8 times per K16 group, and _w4a16_original (:935-938) decodes it 16 times.
    • Why it matters: repeating the single native conversion was cheap, but the integer path takes more than a dozen operations per element. _gemv_half2 (:640-651) already loads one scale per group and broadcasts it.
    • Ask: I have no measurement. An SM80 timing of nvfp4_gemv and nvfp4_w4a16 would show whether decoding once per group is worth doing.

Recommendation

Approve. Nothing blocks. Before landing, push the KERNEL_TESTS change and pass NATIVE_E4M3 in the direct test launches. The rest can be follow-ups.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks. Round 7: no changes beyond the rebase.

@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 17m 39s —— View job


Summary: I'd approve this once both A10G unittest-cuda shards pass for f7c65cf. The PR's code hasn't changed since the last round. This round adds two minor findings, and nine minors from earlier rounds are still in the code.

Detailed review

PR Review: #25411

Summary

The PR decodes E4M3 scales with integer math below SM89 (_e4m3_to_f32). The NATIVE_E4M3 constexpr, set from _has_native_e4m3(), picks that path or the native one. The PR also removes the SM89 skips from the NVFP4 tests.

  • The PR's own diff is the same as at 5ff6bf8; only the base (the lower stack PRs) moved. I reviewed all 9 changed files against the updated base.
  • There are two new findings, both minor. Nine minors from earlier rounds are listed briefly below. Nothing blocks the merge.
  • I ran nothing, because this runner has no GPU. Both unittest-cuda shards for f7c65cf were still queued or running when I wrote this.

Code Quality

  • New: the software branch of _e4m3_to_f32 doesn't follow the idioms around it (minor). This is at nvfp4_quantized_gemm.py:212-220, and neither point changes the result.
    • NaN: :216 builds the NaN with tl.full(mag.shape, 0x7FC00000, tl.int32).to(tl.float32, bitcast=True). topk.py:91, in the same kernels directory, writes tl.where(was_nan, float("nan"), vsel). So :216-217 can become one line, mag = tl.where((u & 0x7F) == 0x7F, float("nan"), mag).
    • Sign: :219-220 shift the sign into bit 31 of a signed int32. _fp4, the helper just above, ORs its sign in as uint32 (:145-146).
    • Fix this →
  • New: a test comment is wrong on the GPUs this PR enables (minor).
    • test_nvfp4_unit_scale.py:122 says "The launcher builds the decode the device supports natively." On SM80/86, where this test now runs, the launcher builds the software decode.
    • Fix: reword it (e.g. "The launcher picks the E4M3 decode from the device") or drop it. Fix this →
  • Still open from earlier rounds (I re-checked each one in f7c65cf):
    • PR description: it still says "The capability check falls back to nvidia-smi inside forked compile workers". No such fallback exists: _has_native_e4m3 (nvfp4_quantized_gemm.py:196-202) only queries torch.cuda. ghstack turns this text into the commit message.
    • NATIVE_E4M3 defaults: it defaults to False on all five kernels (:755, :847, :972, :1120, :1211). A launch that leaves it out silently builds the slower software decode on SM89+. Only the _gemv launch is checked (test_nvfp4_unit_scale.py:123).
    • Native FP4 vs native E4M3: "native FP4 implies native E4M3" isn't enforced. _gemv (:849) and _w4a16 (:1122) send NATIVE=True to _gemv_half2 and _w4a16_paired, which ignore NATIVE_E4M3. A tl.static_assert(NATIVE_E4M3 or not NATIVE) in both would make a mismatched launch fail to compile.
    • Activation quantizer: nvfp4_quantize_activation (:287-298) has no SM89 check. On SM80/86 it fails inside Triton at the .to(tl.float8e4nv) in _activation (:170). nvfp4_w4a4 raises a clear RuntimeError in the same situation.
    • Marker name: the native_e4m3 marker (test_nvfp4_kernels.py:37) has the same name as the bool parameter at :331, :356 and :401. Sibling files name markers in upper case (NATIVE_FP4, CUDA).
    • Single-use helpers: finite_e4m3_bytes (test_nvfp4_soft_decode.py:28) and assert_bits_equal (:42) are each used once, which CLAUDE.md asks you to avoid.
    • FP32 activations (question, low confidence): with FP32 activations and a non-FP32 output dtype, _linear still falls back to dequantize() (nvfp4_dispatch.py:300-310). That views the scales as torch.float8_e4m3fn (nvfp4_tensor.py:185). Nobody has yet checked whether Inductor lowers that view to tl.float8e4nv, which Triton rejects below SM89, in an AOTI export.
    • Fix these →

Infrastructure

  • Still unconfirmed: none of the un-skipped .pte tests has a reported pass with the software decode (no code change needed).
    • Buck A100 lowers these cases but returns before it runs the .pte. The early returns are at test_nvfp4_export.py:136 and :191, test_nvfp4_split_k_export.py:88, test_nvfp4_fusion.py:446 and test_nvfp4_unit_scale.py:149.
    • Author's runs: the author's A100 environment can't lower through AOTI, and the RTX 5090 builds the native decode.
    • So OSS CI is the only check: unittest-cuda (system) on the A10G (SM86, .github/workflows/cuda.yml:528-529) is the only run that checks these PTEs' output with the software decode.
      • KERNEL_TESTS (:540-559) still has no NVFP4 file. So until Require gguf>=0.19 for the GGUF tests #25420 lands, that shard also runs test_nvfp4_soft_decode.py and test_nvfp4_kernels.py, within its 120-minute timeout.
      • Both shards for f7c65cf were still queued or running when I wrote this. No result for an earlier push has been posted.
    • Ask: confirm that both unittest-cuda shards pass for f7c65cf, and say how long the system shard took.

Testing

  • Still open from earlier rounds. Both are in test_nvfp4_soft_decode.py:
    • Native-only coverage on SM89+: the full-range tests (:91-126) go through the public launchers.
      • So on SM89+ they only build the native decode, and on SM120 nvfp4_w4a16 goes to _w4a16_paired.
      • Nothing runs the _embedding software decode on SM89+, because the direct launch at test_nvfp4_kernels.py:574 also passes the device's flag.
    • Weak per-row check: test_kernels_decode_every_scale (:101-112) uses codes and activations with random signs. The |x| @ |w| normaliser therefore dilutes a one-step scale error in a single row, so the m=1 and m=3 GEMV checks can miss it. This is an estimate; I haven't run it.
    • Fix this →

Recommendation

Approve, once both unittest-cuda shards pass for f7c65cf. None of the findings blocks the merge.

@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 23m 9s —— View job


Summary: I'd approve this once the A10G unittest-cuda (system) shard passes for fe01f5e within its 120-minute limit, since neither the minor coverage gap from this round's test trim nor the still-open minors from earlier rounds blocks the merge.

Detailed review

PR Review: #25411

Summary

The PR adds an integer-math E4M3 scale decode (_e4m3_to_f32), selected below SM89 by the NATIVE_E4M3 constexpr that the launchers set from _has_native_e4m3(), and removes the SM89 skips from the NVFP4 tests.

  • This round: the PR adds a Buck target for test_nvfp4_soft_decode.py and trims test_kernels_decode_every_scale with sweep. The trim causes the one new finding below, which is minor.
  • Earlier minors: all are still in the code and are listed briefly below.
  • Not run: I reviewed all 9 changed files but ran nothing, because this runner has no GPU. Test CUDA Builds for fe01f5e was still queued.

Testing

  • New: the default GEMV check now uses a single activation row (backends/cuda/tests/test_nvfp4_soft_decode.py:104).
    • What changed: without ET_CUDA_NVFP4_EXHAUSTIVE_TESTS=1, which neither A10G CI nor Buck A100 sets, sweep returns [(1, 4), (37, 1)]. So nvfp4_gemv is only checked at m=1. The full list gave it 8 activation rows: m ∈ {1, 3} × split ∈ {1, 4}.
    • Why one row is weak: x and the codes have random signs. A row's |x @ w| is typically about 7% of the |x| @ |w| value it is divided by (:39), which shrinks a scale error about 14×.
    • Effect (my estimate, not run): suppose a single row's scale is off by one E4M3 step.
      • For a 1/8 step, the GEMV check now misses it about 73% of the time, against about 8% with the full list.
      • For a 1/15 step, it misses it about 96% of the time.
      • The m=37 W4A16 case still catches both.
    • What it doesn't affect: the random draws are fixed per test id (root conftest.py:100-103), so a miss is deterministic, not a flake. test_e4m3_decode_is_exact still checks the helper bit-exactly. Only the per-row kernel claim in the docstring (:35-37) is weaker.
    • Fix: give every term in a row the same sign, with q = q & 0x77 and x = torch.randn(...).abs(). The per-row error then equals the scale error, so any one-step error fails the 1e-2 bound, even in the single m=1 case. This was suggested before; the trim makes it matter more. Fix this →
  • Still open: on SM89+ GPUs the full-range tests only run the native decode (:93, :116).
    • Why: both tests call the public launchers, and no test patches _has_native_e4m3.
    • Effect on SM89+:
      • The software decode inside _embedding never runs.
      • _gemv_original and _w4a16_original run it only in the pinned tests. Their shards() scales are all positive normals between 0.03 and 0.15 (nvfp4_test_utils.py:28-29).
    • Scope: CI's A10G and A100 take the software path, so this only matters for local runs on newer GPUs such as your RTX 5090.
    • Fix: parametrize both tests. In the software case, patch kernels._has_native_e4m3 and kernels._has_native_fp4_conversion to return False, as use_quantizer does (test_nvfp4_kernels.py:64-70). Fix this →

Code Quality

  • Still open from earlier rounds. I re-checked each of these at fe01f5e:
    • "Native FP4 implies native E4M3" isn't enforced.
      • _gemv (nvfp4_quantized_gemm.py:849-850) sends NATIVE=True to _gemv_half2, which hard-codes tl.float8e4nv (:709). _w4a16 (:1122-1124) does the same with _w4a16_paired (:1064).
      • So a launch with NATIVE=True, NATIVE_E4M3=False compiles and quietly keeps the native decode.
      • Fix: add tl.static_assert(NATIVE_E4M3 or not NATIVE) to both. Two reviewers found this again independently.
    • NATIVE_E4M3 defaults to False on all five kernels (:755, :847, :972, :1120, :1211). Only the _gemv launch is checked (test_nvfp4_unit_scale.py:123). A launch that leaves the flag out quietly builds the slower software decode on SM89+.
    • nvfp4_quantize_activation (:287-298) has no SM89 check. On SM80/86 a direct call fails inside Triton, at the .to(tl.float8e4nv) in _activation (:170). nvfp4_w4a4 raises a clear RuntimeError instead (:622).
    • _e4m3_to_f32 doesn't follow nearby idioms.
      • It builds the NaN with a tl.full bitcast (:216), where tl.where(..., float("nan"), mag) would do.
      • It ORs the sign in as int32 (:219-220), while _fp4 uses uint32 (:145-146).
    • A comment is wrong on SM80/86: test_nvfp4_unit_scale.py:122 says the launcher builds "the decode the device supports natively", but on those GPUs it builds the software decode.
    • Marker name: the native_e4m3 marker (test_nvfp4_kernels.py:38) has the same name as the bool parameter at :332, :357 and :402. Sibling files use upper case (NATIVE_FP4, CUDA).
    • Single-use helpers: finite_e4m3_bytes (test_nvfp4_soft_decode.py:29) and assert_bits_equal (:43) are each used once, which CLAUDE.md asks you to avoid.
    • Fix these →
  • Still open: FP32 activations below SM89 (a question, low confidence). Two reviewers raised this again independently.
    • The path: for FP32 activations whose output dtype isn't FP32, _linear traces dequantize() into the export graph (nvfp4_dispatch.py:300-310). The routing case at test_nvfp4_gate_up.py:122-124 confirms that decode-size FP32 takes this path. dequantize reads the scales as torch.float8_e4m3fn (nvfp4_tensor.py:185).
    • The risk: if Inductor lowers that view to tl.float8e4nv, an AOTI export on SM80/86 hits the same Triton error this PR fixes. Every un-skipped PTE test uses BF16 activations, so CI won't show it.
    • How to settle it: run torch.compile(lambda s: s.view(torch.float8_e4m3fn).float())(w.scale) on your A100. If that fails, dequantize could decode the bytes with integer ops, or the description could state the limitation.

Recommendation

Approve, once unittest-cuda (system) passes for fe01f5e within its 120-minute timeout (.github/workflows/cuda.yml:528).

  • That A10G (SM86) shard is the only run that executes the un-skipped PTEs with the software decode, because the Buck A100 tests return right after lowering in fbcode.
  • None of the findings above blocks the merge.

@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 — ce46f7cc Deployed Nov 23, 2026 by Gasoonjia via upload-benchmark-results #23166
cadence — ce46f7cc Deployed Nov 23, 2026 by Gasoonjia via hifi-op-test / hifi4 #40337
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