Skip to content

[executorch][cuda] NVFP4 W4A16, GEMV and embedding kernels - #25341

Open
Gasoonjia wants to merge 11 commits into
gh/gasoonjia/216/basefrom
gh/gasoonjia/216/head
Open

Gasoonjia wants to merge 11 commits into
gh/gasoonjia/216/basefrom
gh/gasoonjia/216/head

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Adds W4A16 matrix multiplication, decode GEMV, and embedding kernels for packed NVFP4 weights, including native paired decoding and scalar/per-row global-scale support.

nvfp4_gemv(unit_scale=True) skips the global scale and relies on the CudaNVFP4Tensor.unit_scale contract; the GEMV output keeps x.dtype. W4A16 computes FP32 activations in BF16. Eager embedding outside CUDA-graph capture rejects out-of-range ids; compiled graphs return zero rows for them. All three ops reject malformed operands (the embedding also non-integer or wrong-device ids), the GEMV rejects more than 65535 rows (grid axis 1), weight addresses use int64 offsets, and W4A16 validates its launch before casting FP32 activations. W4A16 and the GEMV pass M's upper bound into their autotuned split-K launch like W4A4. The test_nvfp4_w4a4 target becomes test_nvfp4_kernels.

Kernel tests cover both GEMM modes, activation quantization, GEMV, embedding, per-row global scales, split-K, and large-workspace addressing, and launch every GEMV/W4A16 decode variant (native/software, HALF2, row scales, unit scale) with pinned constexprs instead of relying on the autotuner's pick. These kernels decode scales with native E4M3 until the software decode later in the stack, so CI (A100/A10G) skips them here; everything, including the SM120-only native variants, was run on an RTX 5090.

Authored with Claude Code.

Differential Revision: D132997505

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 5c79998 with merge base 9f49fe2 (image):
💚 Looks good so far! There are no failures yet. 💚

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 21, 2026 •

Copy link
Copy Markdown

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


PR #25341 review: Reading the code turned up no numerical bug in the new NVFP4 W4A16, GEMV and embedding kernels, but none of the new kernels run in any CI job, the per-row global scale and HALF2/native variants go untested even on capable GPUs, and nvfp4_gemv(unit_scale=True) silently drops the global scale and has no documented contract, so I recommend Request Changes.

Detailed review

PR Review: #25341

Summary

The PR adds triton::nvfp4_w4a16, triton::nvfp4_gemv and triton::nvfp4_embedding for packed NVFP4 weights, plus tests and a microbenchmark.

I read the kernels against the existing W4A4 code and the packer, covering nibble order, E4M3 decode, masks, int64 offsets and the split-K reduce, and found no numerical bug. The problems are:

  • Coverage: the new code never executes in CI, and key branches are untested even on capable GPUs.
  • An unchecked unit_scale contract on a public op.
  • Some missing validation, dead code and duplication.

No GPU was available, so I ran none of the tests. The performance points below are marked as suspected.

Code Quality

  • _launch_w4a16_impl allocates before it validates (nvfp4_quantized_gemm.py:970-974).
    • An fp32 x is cast to bf16 before _check_split runs, so every split-K candidate rejected in the autotune prepass still pays for an m×k cast.
    • _launch_w4a4_impl (:432) and _launch_gemv_impl (:728-731) validate first, and this PR tests that ordering for the GEMV (test_gemv_workspace_rejected_before_output_allocation).
    • Fix this →
  • The GEMV and W4A16 launchers don't check shapes or strides (:725-731, :968-975).
    • K is taken from x and never compared with qdata.shape[1] * 2 or scale.shape[1] * 16. W4A4 at least rejects k % 16 through nvfp4_quantize_activation (:168).
    • The kernels index X + m * K + k and never call .contiguous().
    • A K mismatch reads past the end of qdata. A strided view such as h[:, -1, :] with batch > 1 silently reads the wrong rows.
    • nvfp4_embedding already makes its input contiguous (indices.contiguous(), :1082). W4A4 has the same stride gap.
  • Dead code and triplicated inline asm in the kernel file:
    • _gemv_half2 has one call site (:716-718), and it passes HALF2=True, SCALE_ONCE=True as literals. That makes these branches unreachable:
      • the SCALE_ONCE=False branch (:571-578)
      • the fp32 else branches (:566-567, :577-578)
      • _scaled_pair's if not HALF2 branch (:517-519)
    • The cvt.rn.f16x2.e2m1x2 asm is copied at :495, :640 and :894. One @triton.jit decode helper could serve all three.
    • ROW_PTS is passed to _reduce_partials with FP4_ACT=False (:768, :1004). It is unused there and only adds a compiled variant.
    • The constexpr names SPLIT (_gemv*, _w4a16_paired) and SPLIT_K (_w4a16, _w4a16_original, _reduce_partials) differ even within one dispatch (_w4a16 → _w4a16_paired). That is why prune_nvfp4_stages has to read both (nvfp4_tuning.py:72).
    • Fix this →
  • weight() is a verbatim copy of nvfp4_test_utils.weight (test_nvfp4_kernels.py:23-31 vs nvfp4_test_utils.py:35-43).
    • The PR removed the import, so the original is now unused: test_nvfp4_tensor.py imports portable_weight as weight instead.
    • Both Buck targets still depend on :nvfp4_test_utils.
    • Restore the import. Fix this →
  • Embedding bounds checking depends on the execution mode (:1075-1081).
    • In eager mode the check forces a blocking device-to-host sync on every call (bool((...).any())).
    • Under export/AOTI (fake tensors) the check is skipped, and out-of-range ids silently become zero rows (:1051-1053). aten.embedding fails with a device assert instead.
    • So test_embedding_rejects_out_of_range_ids asserts behaviour that doesn't hold in deployment. At minimum, document on the op that compiled graphs don't validate ids.
  • Benchmark (nvfp4_gemm_bench.py):
    • The docstring (:5) names "Muse Glimmer". If that is an internal model codename, it should not land in OSS. The same arguably applies to the SHAPES table (:37-46), which encodes that model's dimensions. Please confirm.
    • if stats.picks: (:119) is always true, because :113-114 already raises when it is empty.
    • RTX 5090 peaks are baked into the column names and denominators (:77-79, :193, :202), whatever GPU get_device_name() reports.
    • W4A4 is benchmarked without a _has_native_fp4_conversion() check (:103), even though the tests skip it as "native FP4 required".
    • The tile lookup depends on the Triton autotuner's cache-key layout (key[:4] == (m, n, k, split), :166-170).
    • The file name breaks the benchmark_*.py convention of benchmark_moe.py and benchmark_sdpa.py.
    • Fix this →

Infrastructure

  • Redundant Buck target (targets.bzl:623-631).
    • test_nvfp4_w4a4 now runs test_nvfp4_kernels.py with pytest_expr = ["activation or w4a4"]. That is a strict subset of the new unfiltered test_nvfp4_kernels target (:633-640), which has the same deps and platform.
    • As a result, every W4A4 and activation test is scheduled twice, including the 13 GiB workspace test.
    • Nothing else in the tree references the old name. If it is kept for an internal test config, say so; otherwise delete it.

Testing

  • None of the new kernels run in any CI job:
    • test_nvfp4_kernels.py:17-20 skips the whole module below SM89.
    • Both Buck targets run on A100, which is SM80 (targets.bzl:629, :638).
    • OSS runs the file in the system shard on an A10G, which is SM86 (.github/workflows/cuda.yml:529, :647).
    • So every W4A16, GEMV and embedding test reports as skipped, and CI stays green. No runner at all covers the SM12x-only paths (_has_native_fp4_conversion, :115-116).
    • The only new code that does execute is the two mocked CPU launcher tests in test_nvfp4_launch_validation.py.
    • Please say in the test plan which GPUs these tests were run on, and consider an SM89+ runner (e.g. L4 or H100). Per cuda.yml:538-539, also list this file under KERNEL_TESTS.
    • The gap already existed for W4A4, but this PR puts about 600 more kernel lines behind it.
  • The per-row global scale is never tested.
    • Every test uses a one-element per_tensor_scale: weight() uses 0.25 (:31), test_gemv_split_k uses [0.37] (:137), and the workspace test uses ones(1).
    • So ROW_PTS=True is never compiled for any of the new kernels:
      • _gemv_half2 (:549-550)
      • _gemv_original (:630-631)
      • _w4a16_original (:824-825, [None, :])
      • _w4a16_paired (:879-880, [:, None])
      • _embedding (:1061)
    • The two W4A16 variants broadcast the scale in opposite orientations, because their weight tiles are transposed. That is exactly what a test should pin down.
    • This is the production case: CudaNVFP4Tensor.fuse_along_output (nvfp4_tensor.py:105-110) produces an (N,) scale for fused gate/up or QKV weights whose global scales differ. The PR description also claims per-row support.
    • nvfp4_test_utils.shards() plus fuse_along_output is a ready-made fixture. Fix this →
  • The autotuner or the GPU picks the decode variant; the tests never do:
    • HALF2 is an autotune parameter (:679-691), and prune_nvfp4_stages removes it only on non-native GPUs.
    • On SM12x, timing therefore decides which kernel gets compared against the reference: _gemv_half2 (with its packed f16x2 multiply and the cvt.rn.bf16x2.f32 $0, $2, $1 operand order) or _gemv_original(NATIVE=True).
    • On SM89-SM100 only the _original variants run. On SM12x the public-op tests never reach the _fp4 fallbacks.
    • The int64 workspace test launches kernels._w4a16.fn[...] without NATIVE (:186-202), so it only exercises _w4a16_original.
    • Pin HALF2 and NATIVE with direct .fn[...] launches, as that test already does for tile sizes, and/or patch _has_native_fp4_conversion. Fix this →
  • test_gemv_split_k doesn't check what its comment claims (:135-141).
    • The comment says "A non-power-of-two global scale checks rounding of the BF16 weights".
    • With K=2176, skipping the BF16 weight rounding would shift outputs by roughly 0.01 rms. That is my rough estimate, not a measurement.
    • The tolerance is 0.015 + 0.015·|y|, about 0.09 at a typical |y|≈5, so a kernel that doesn't round would usually still pass.
    • A one-hot x row, or a single K16 group compared at atol=0, would actually test the rounding.

API Design

  • unit_scale on triton::nvfp4_gemv has a precondition that is neither documented nor checked (:788; kernel branches at :547-548, :580-581, :628-629, :664-665).
    • With unit_scale=True, both GEMV kernels replace per_tensor_scale with 1.0, and _reduce_partials(FP4_ACT=False) never applies it either. A caller who passes the flag with a non-unit scale gets wrong output and no error.
    • Nothing in this PR passes unit_scale=True, and no test covers either kernel's UNIT_SCALE branch.
    • The benchmark builds a unit-scale weight (pts = 1.0, scale bytes < 127, :90-97) but calls nvfp4_gemv without the flag, so the speedup is never measured.
    • nvfp4_w4a16 and nvfp4_embedding have no equivalent flag.
    • Document the contract on the op and its link to CudaNVFP4Tensor.unit_scale, test both branches, and benchmark it. Alternatively, defer the flag to the PR that adds its caller. Fix this →
  • nvfp4_gemv and nvfp4_w4a16 disagree on their dtype contract.
    • nvfp4_gemv has no output_dtype and always returns x.dtype (:731), while nvfp4_w4a16 and nvfp4_w4a4 accept one.
    • For an fp32 x, W4A16 rounds activations and decoded weights to bf16 (:970-971, :843, :908-909). The GEMV keeps fp32 throughout (:594-595, :667-668).
    • A caller that sends M ≤ 4 to the GEMV, as test_w4a16 and the benchmark do, gets numerics that depend on M and can't request an output dtype during decode.
    • test_w4a16_keeps_float32_output (:240-247) checks only .dtype, and no test uses an fp16 x.

Performance

  • The GEMV decodes the weights again for each activation row (:737). Suspected.
    • The grid is (cdiv(n, BN), m, split_k), so at M=2-4 each row's programs reload and re-decode the whole weight slice.
    • In practice the N-blocks are scheduled first. A large projection (the benchmark's gate_up is about 150 MB packed) has then probably left L2 by the time row 1 runs, so DRAM traffic grows with M.
    • The benchmark's default --m 1 4096 (bench :52) never measures M=2-4, which is the range the tests and the benchmark send to the GEMV.
    • Because M is on grid axis 1, the public op is also capped at 65535 rows, with no guard.
    • Please benchmark M ∈ {2, 4} against nvfp4_w4a16.
  • _w4a16_original decodes one element at a time (:832-843). Suspected; only one reviewer raised it and it is not benchmarked.
    • This is the path every non-SM12x GPU runs (SM89/90/100).
    • It loads each packed byte twice (kk[:, None] // 2) and each scale byte 16 times (kk // 16).
    • _gemv_original already decodes in pairs without native support (_fp4(q & 15) / _fp4(q >> 4), :657-658). Giving _w4a16_paired the same fallback could replace _w4a16_original and remove about 50 duplicated lines.
    • Worth measuring on SM90.

Recommendation

Request Changes. Before landing:

  • Add tests for the per-row global scale and for pinned HALF2/NATIVE variants.
  • Resolve the unit_scale contract: document and test it, or defer the flag.
  • At least acknowledge in the test plan that no CI job runs these tests on hardware.

The remaining items are minor.


…code down so A100 CI runs the NVFP4 kernels

[ghstack-poisoned]
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks. Round 6: the commit message is current: no benchmark sentence, and it has a full test plan. The test plan now gives the hardware coverage. At this commit the kernel tests need SM89+, and they ran on an RTX 5090, including _w4a16_original (NATIVE=False) at split-K 1 and 2. A100 and A10G run them only from the software E4M3 decode later in the stack. The commit message is what goes to the PR body.

@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 41m 5s —— View job


PR #25341 re-review (round 7)

  • Gather PR context
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check against b516e1c
  • Post review

Approve: no numerical bug or blocker at b516e1c, but no CI runner is SM89+, so none of the new kernels ever runs in CI, and the remaining items are test gaps, missing dtype checks and small consistency fixes.

Detailed review

PR Review: #25341

Summary

Adds NVFP4 W4A16 GEMM, small-M GEMV and embedding Triton kernels, registered as triton_ops for AOTI capture, with tests. I found no numerical bug at b516e1c. The main problem, newly found this round: no CI runner is SM89+, so none of the new kernels is ever launched in CI. The rest are test gaps (chiefly, nothing compiles the three new ops), missing dtype checks on the public ops, an embedding host check without the base's meta guard, an unneeded NATIVE gate, and two hand-rolled offsets that should use _partial_offsets. Everything here comes from reading the code. Nothing was run, because importing torch needed approval in this job, so items marked suspected are unconfirmed.

Code Quality

  • The embedding range check lacks the guards the base's _check_static_scale gained this round. Compare nvfp4_quantized_gemm.py:1198-1203 with :115-119.
    • There is no device.type != "meta" term. triton_op registers the op body as its Meta kernel, so an all-meta call reaches bool(...) on a meta tensor and raises instead of returning a meta output. Suspected: not run.
    • CudaNVFP4Tensor guards meta the same way (nvfp4_tensor.py:85, :115).
    • torch.cuda.is_current_stream_capturing() is called without the is_cuda guard.
    • test_embedding_rejects_malformed_ids (test_nvfp4_launch_validation.py:96-106) never reaches this check, because meta ids with CPU weights fail the device check first.
    • Fix: use the same guards, and add an all-meta call to the launch-validation tests. Fix this →
  • _w4a16_original and _w4a16_paired build the split-plane store offset inline (lines 960, 1027; still open from round 4).
    • _w4a4 (line 494), both GEMV bodies (705, 777) and _reduce_partials (519) all call _partial_offsets (499-501), whose int64 behaviour test_partial_offsets_and_masks_are_int64 pins.
    • Fix: offsets, _ = _partial_offsets(split, m[:, None] * N + n[None, :], M, N), as at line 494. Fix this →

Infrastructure

  • No CI runner can run the new kernel tests (major).
    • test_nvfp4_kernels.py skips the whole module below SM89 (lines 31-36).
    • Its Buck target runs on an A100, which is SM80 (backends/cuda/tests/targets.bzl:628).
    • In OSS it lands in the system shard, which runs on the A10G runner, SM86 (.github/workflows/cuda.yml:529, :647). Every CUDA runner in cuda.yml is an A10G or an A100.
    • So none of the GEMV, W4A16 or embedding kernels this PR adds is launched in CI, and every Testing item below applies only to local runs.
    • The base's W4A4 tests already had this gap, but this PR edits that target and puts three more kernels behind it.
    • Fix: move the target to an SM89+ RE subplatform, if one exists. Otherwise, list in the test plan which GPUs ran the suite: SM89–SM100 and SM120 take different decode paths.
    • The GitHub PR body still has no test plan and still has the microbenchmark sentence (still open from round 6). If the commit message is current, ghstack submit -u copies it into the body; plain ghstack submit leaves an existing body alone.
    • Fix this →

Testing

  • Nothing compiles the three new ops (still open from round 6).
    • The module docstring (line 5) says these kernels are captured into AOTI. But the only torch.compile test (test_nvfp4_kernels.py:220-234) covers activation quantization.
    • The reduce launches pass ROW_PTS=False explicitly (lines 873, 1118) to avoid Inductor's launcher() missing '_grid_2' failure. That value is the default (line 515) and has no comment, so removing it as redundant would pass every test.
    • The compiled-graph behaviour promised in the embedding docstring (lines 1190-1191) is only checked by a direct _embedding launch (test line 506).
    • Fix: add a one-line comment at both ROW_PTS=False sites, plus a torch.compile(fullgraph=True) test modelled on lines 220-234. It should compare compiled and eager nvfp4_gemv(split_k=2), nvfp4_w4a16(split_k=2) and nvfp4_embedding, and check that compiled nvfp4_embedding returns a zero row for an out-of-range id. Fix this →
  • The pinned variant tests are BF16-only, and the FP32 check is too loose to test FP32 math (still open from round 4).
    • test_pinned_gemv_variants and test_pinned_w4a16_variants build BF16 activations only (lines 301, 342). The FP16/FP32 branches run only through autotuned calls, so which variant they reach depends on the GPU and on timing.
    • On SM120, NATIVE is always True. _gemv_original(NATIVE=False) and _w4a16_original then never see FP16 or FP32, and the non-BF16 branch of _gemv_half2 (lines 697-699) runs only if a HALF2 config wins.
    • test_activation_dtypes checks the FP32 GEMV at rtol=atol=0.015 (line 535). Rounding x to BF16 moves results by about 2^-9 relative, and the test weights are exact in BF16, so a BF16 kernel would pass. The "GEMV keeps FP32 math" promise (lines 1140-1141) is therefore untested.
    • Fix: parametrize the pinned GEMV test over bf16/fp16/fp32 and the pinned W4A16 test over bf16/fp16, with w.dequantize(dtype) as the reference, and check FP32 at about 1e-4. Fix this →
  • test_embedding_kernel_returns_zero_rows_for_invalid_ids cannot catch what its comment describes (still open from round 5).
    • out comes from torch.empty (line 510), so a kernel that skipped the store for invalid ids would pass whenever that memory was already zero.
    • Without the clamp (lines 1167-1169), id 97 reads 96 B past qdata (9312 B) and 12 B past scale (1164 B). Both reads land in the caching allocator's 512 B rounding of those blocks, which is often zero. Suspected: not run.
    • Fix: prefill out with NaN. Launch on interior row views of tables with nonzero guard rows, e.g. torch.full((99, 96), 0x77, ...)[1:98] holding a copy of w.qdata, and the same for scale. Fix this →
  • Two smaller gaps.
    • No embedding test uses int32 ids, although the op accepts them (line 1193).
    • nvfp4_w4a16 is never called with M ≤ 4. test_w4a16 (lines 46-50) and test_row_global_scale (line 383) send those M to the GEMV, but the op accepts any M.
    • Fix: add int32 ids to one embedding test, and check both ops for m ≤ 4 in test_w4a16. Fix this →

API Design

  • The public ops accept integer activation and output dtypes (still open from round 5).
    • _check_operands (lines 125-135) never checks x.dtype, and output_dtype is used unchecked (lines 1086, 1206).
    • An integer x makes the GEMV round decoded weights to that type (lines 698, 771) and store truncated sums. An integer output_dtype truncates everything nvfp4_w4a16 or nvfp4_embedding writes.
    • The only nearby dtype guard is CudaNVFP4Tensor.__new__'s check on orig_dtype (nvfp4_tensor.py:60-61). It never sees x, and direct triton::nvfp4_* callers bypass it.
    • Fix: reject x.dtype outside bf16/fp16/fp32 in _check_operands, and a non-floating output_dtype in both ops. Fix this →

Performance

  • The unit-scale shortcut in _gemv_original needs NATIVE for no reason (line 768).
    • _fp4 (lines 139-149) is exact too, so under the unit_scale contract lo * sf is exact in BF16 whichever decode produced it.
    • So on SM89–SM100, unit_scale=True still pays the BF16 round trip at lines 771-772. The cost is likely small, since the GEMV is memory-bound.
    • Fix: drop NATIVE from the condition. Fix this →

Recommendation

Approve. Nothing in the code blocks merge. CI can't run these tests (see Infrastructure), so this approval rests on the author's own SM89+ and SM120 runs; please record them in the PR body. The most valuable code follow-up is the compile test. It is the only thing that would catch removal of the ROW_PTS=False workaround, and the only check on the embedding's compiled-graph behaviour.


@Gasoonjia
Gasoonjia deployed to upload-benchmark-results November 22, 2026 01:52 — with GitHub Actions Active
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks. Round 7: no changes beyond the rebase. The other items are deferred.

@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 24m 33s —— View job


PR #25341 re-review (round 8)

  • Gather context (head a2acf1f; 4 files, +1019/−9)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check against a2acf1f
  • Post review

Approve: the diff is unchanged since round 7 apart from the rebase and has no correctness bug; the one new, minor item is that the pinned-variant tests use K=512, so _w4a16_original, the only W4A16 kernel on SM89–SM100, never runs a partial K block on the RTX 5090.

Detailed review

PR Review: #25341

Summary

Adds NVFP4 W4A16 GEMM, small-M GEMV and embedding Triton kernels to the CUDA backend, with pinned-variant and launch-validation tests. The PR's own diff stats match round 7 (same four files, +1019/−9), which agrees with your note that only the rebase changed. No correctness bug was found. The one new item is minor test coverage, below. The round-7 items you deferred are unchanged at this head and aren't repeated.

Testing

  • No pinned variant runs a partial K block (backends/cuda/tests/test_nvfp4_kernels.py:282-283). pinned_weight uses K=512. That is a multiple of BK·split for both pinned tests, the GEMV at BK=256 (:319) and the W4A16 at BK=128 (:361), each with one or two splits. So the K masks never turn off a lane in _gemv_half2 (nvfp4_quantized_gemm.py:672, :679, :703-704), _gemv_original (:743, :776-777), _w4a16_original (:950, :952) or _w4a16_paired (:1006, :1008).

    The gap matters for _w4a16_original. SM120 always passes NATIVE=True (:1107), so on the RTX 5090 this kernel runs only in test_pinned_w4a16_variants(native=False). Its K masks are separate code from _w4a16_paired's and haven't run on ragged K at this commit, yet it is the only W4A16 kernel on SM89–SM100. The GEMV variants get ragged K only through the public-op tests (e.g. test_w4a16, test_gemv_split_k), where autotuner timing decides which variant's output is checked.

    The masks look correct on reading: masked lanes decode _fp4(0) to +0 and load zero scales and activations. Per your round-6 note, the A100/A10G runs later in the stack reach _w4a16_original through the public tests. Until then, K=592 (37·16) gives every pinned case a partial K block, and the two-split cases also get a fully masked one. Update the comment at :299 to match.
    Fix this →

Recommendation

Approve

Nothing blocks. The code is unchanged since round 7, and the one new item is a minor coverage gap with a one-line fix.

@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 33m 51s —— View job


PR #25341 re-review (round 9)

  • Compare with round 8: only the test_gemm_split_k / test_gemv_split_k parametrizations changed (now sweep(full, quick))
  • Run three independent reviewers: no numerical bug; most findings repeat items deferred in round 7
  • Consolidate findings, keeping what's new
  • Fact-check against 874b76f
  • Post review

Approve: round 9 only changes the split-K test parametrization and turns up no correctness problems; two new minor test gaps remain (weight offsets above 2³¹ bytes are never exercised, and nvfp4_embedding is never called under CUDA-graph capture).

Detailed review

PR Review: #25341

Summary

Adds Triton NVFP4 W4A16, small-M GEMV (split-K, native SM120 E2M1 decode) and embedding kernels, with tests. Since round 8 the only change is the sweep(full, quick) parametrization of test_gemm_split_k and test_gemv_split_k, which raises no issue: the quick lists still hit partial and empty split blocks. No correctness problems were found; the two findings below are minor test gaps. Items decided or deferred in round 7 (activation/output dtype checks, the SM89 module skip until #25411, inline W4A16 offsets, BF16-only pinned tests, embedding device guards and int32 ids, the GEMV/W4A16 interface split) are not repeated. Nothing was run, since this job has no GPU; everything below comes from reading 874b76f.

Testing

  • Weight offsets above 2³¹ bytes are never exercised (minor, low priority). Every kernel indexes weights as Q + n * (K // 2) + … with n cast to int64 (nvfp4_quantized_gemm.py:658, :729, :938, :992, :1167), but the largest test weight is 40.9 MB of constant bytes (test_split_workspace_exceeds_int32), and test_w4a16_output_offsets_exceed_int32 pushes only the output offsets past 2³¹, with a 2 MB weight. Dropping one of these casts would go unnoticed, though it only matters for a single matrix with more than 2³² elements. A test in the style of test_w4a16_output_offsets_exceed_int32 would cover all three ops: N=131200, K=32768 (2,149,580,800 qdata bytes, about 2.3 GiB with scales), random qdata and scale bytes below 0x7F (constant bytes hide a wrapped offset), then compare the last 8 columns of nvfp4_gemv (M=1, split_k=1) and nvfp4_w4a16 (M=17, split_k=1), and nvfp4_embedding on ids N-8..N-1, against the same calls on qdata[-8:], scale[-8:].
    Fix this →
  • The CUDA-graph capture branch of nvfp4_embedding is untested (minor). The docstring (nvfp4_quantized_gemm.py:1193-1194) promises that captured calls skip the id check and return zero rows, and :1204 implements the skip, but test_embedding_kernel_returns_zero_rows_for_invalid_ids launches _embedding directly, and the only capture test (test_nvfp4_launch_validation.py:100) covers _check_static_scale. If the guard is dropped or moved after the .any() at :1205, that host sync fails every eager capture containing the embedding, and no test catches it. Suggested test, next to test_embedding_kernel_returns_zero_rows_for_invalid_ids: warm up with valid ids, capture nvfp4_embedding on ids [3, -1, 97] against weight(97, 192) inside torch.cuda.graph, replay, then check that row 0 equals w.dequantize(torch.float32)[3] exactly and rows 1-2 are zero.
    Fix this →

Recommendation

Approve

Both findings are minor coverage gaps; neither blocks merging.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

nvfp4_test_utils.sweep and EXHAUSTIVE now land in this PR, next to their first caller (the test_nvfp4_kernels.py split-K sweeps), instead of in #25339. They read the existing EXECUTORCH_CUDA_EXHAUSTIVE_TESTS switch (see test_conv_implicit_gemm.py). The Test Plan says so.

Authored with Claude Code.

This branch was successfully deployed

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