Skip to content

[executorch][cuda] NVFP4 W4A4 kernels and activation quantization - #25340

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

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

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Adds dynamic NVFP4 activation quantization and native W4A4 GEMM using tl.dot_scaled, with split-K launch selection and tile tuning. Extends the shared autotune timer with optional callbacks and median-of-three cold CUDA-graph means while preserving existing timing defaults; the shared Triton do_bench takes the statistic and replay count (NVFP4 uses three means) and no longer swallows ParkedTensorsNotRestored. nvfp4_w4a4 rejects malformed operands (K, scale shape, global-scale length/dtype, contiguity, device), a static activation scale that is not a one-element float32 tensor on the activation's device (and, in eager calls on real data, one that is not finite and positive), and targets without native FP4 (SM120+, not ROCm). nvfp4_quantize_activation checks the scale the same way. Each public op validates once at entry; the launch path, which split-K timing runs on random stand-ins, uses an unchecked private quantizer. The value check is skipped for fake and meta tensors and inside CUDA-graph capture. A split-K candidate must fit its (split_k, M, N) workspace at M's upper bound, not the export hint: the op computes the bound from the traced M and passes it to the autotuned launch, so timing (which runs at hinted sizes) rejects the same splits as the final traced call, and an unbounded dynamic M tunes only split 1. The optional static activation scale is a runtime tensor operand read by the quantizer kernels, and only whether one is present (HAS_STATIC, a constexpr) enters the Triton specialization, the autotune key and the split-K launch key, so layers with different calibrated scales share one compiled kernel and one tuning per shape.

Tests cover independent quantization references, rounding boundaries, native GEMM, split-K, 64-bit workspace offsets, and the shared timing/autotune/AOT paths.

Authored with Claude Code.

Differential Revision: D132997450

[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/25340

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

❌ 2 New Failures

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

NEW FAILURES - The following jobs have failed:

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


Request changes: the reference in test_activation_reference[0.001] ignores E4M3 saturation, so the test is expected to fail on SM89+ GPUs; no CI runner can run the W4A4 numerics tests; and the new ops lack input and capability validation (full review below).

Full review

PR Review: #25340

Summary

This PR adds NVFP4 dynamic activation quantization and a tl.dot_scaled W4A4 GEMM with split-K autotuning. It also extends the shared CUDA-graph timer with a median-of-replay-means statistic.

Problems found:

  • A test reference disagrees with the kernels' E4M3 saturation.
  • No CI runner can execute the W4A4 numerics tests.
  • The new ops have no input or capability validation.
  • The static activation scale is compiled into the kernels.
  • Split-K and tile picks made at the export size hint are reused for every runtime M.

All 11 files were reviewed. Nothing was executed, because this job has no GPU, so the runtime claims come from reading the code.

Code Quality

  • _has_native_fp4_conversion() gates more than the conversion (backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:113-115).

    • SM100 excluded: major >= 12 leaves out SM100/SM103 (B200/GB200/B300). PTX ISA 8.6 also exposes cvt.rn.satfinite.e2m1x2.f32 on sm_100a, which Triton targets there, yet those parts take the two-kernel software path.
    • Wrong test gate: the GEMM tests reuse this predicate as their skip (test_nvfp4_w4a4.py:77,93,111). tl.dot_scaled doesn't need that conversion, and W4A4 is never tested on datacenter Blackwell.
    • No check in the op: nvfp4_w4a4 has no capability check of its own. On SM89/SM90/SM100 it runs untested or fails inside Triton compilation, instead of being rejected up front the way the INT formats' unsupported_reason does.
    • ROCm: it ignores torch.version.hip. ROCm gfx12 reports major 12, so it would take the NVIDIA inline-PTX path.
    • Question/fix: is the SM100 exclusion intentional? If not, gate the fused conversion on CUDA 10.x/12.x, gate the GEMM tests separately, and have the op reject unsupported devices.
  • No input validation (nvfp4_quantized_gemm.py:166-168, :426-431).

    • Contiguity: the kernels address raw pointers as X + row * K, B + n * (K // 2) and BS + n * (K // 16), with no strides (:75, :85, :132, :365, :375). The only check is k % 16. A non-contiguous 2-D x (a column slice of a fused projection output, or a transposed view) is quantized from the wrong elements with no error.
    • K mismatch: a weight whose K differs from x's reads out of bounds, because the masks use the activation's K. CudaNVFP4Tensor.__new__ checks a weight's own fields, but nothing checks the raw op arguments against x.
    • Fix: the INT formats reject these cases with check_dtypes, check_contiguous, check_device and check_k (quantized_gemm_utils.py:457-505). Do the same here, or call .contiguous(). Fix this →
  • The NVFP4 tuning helpers fork shared ones.

    • autotune_do_bench copy: nvfp4_tuning.py:34-56 copies quantized_gemm_utils.autotune_do_bench (:378-401) with three silent differences:
      • it takes the mean of 3 replays;
      • it re-raises ParkedTensorsNotRestored;
      • its return_mode="mean" fallback ignores quantiles.
    • Pre-existing bug fixed only for NVFP4: ParkedTensorsNotRestored subclasses RuntimeError (cuda_graph_timing.py:220). The shared helper's except RuntimeError (quantized_gemm_utils.py:392) swallows it, so INT4/5/6/8 keep tuning with weight storages resized to 0.
    • launch_nvfp4_kernel copy: nvfp4_tuning.py:59-67 re-implements the tail of launch_split_k_gemm (quantized_gemm_family.py:564-574). It drops the "candidate prepass lost its active compile pool" guard, and it finds M by magic positional index (4, 7).
    • Fix: fix and parameterize the shared helpers instead of keeping two autotune_do_benchs in sibling modules. Fix this →
  • Branches that only preserve old mock call shapes.

    • Both arms behave the same, given the defaults, in:

      • the if statistic == "min" and replays == 1 branches in time_with_cuda_graph_us_counted (cuda_graph_timing.py:104-113) and _time_capturing_robustly (:290-295);
      • timing_kwargs = {} if do_bench is None else … (launch_params.py:292, :371).

      Always forward the kwargs and update the mocks.

    • nvfp4_w4a4 (nvfp4_quantized_gemm.py:484-488) switches to _launch_w4a4_impl for an explicit split_k, but the wrapper already honours one (launch_params.py:353-355).

  • Dead or speculative code.

    • _fp4 (nvfp4_quantized_gemm.py:59-68) is unused.
    • The FP4_ACT argument of _reduce_partials is always True (:459).
    • prune_nvfp4_stages reads SPLIT, HALF2 and NATIVE keys that no kernel defines (nvfp4_tuning.py:72-77).
    • The tests parametrize mode over the single value "w4a4" and branch on it.

    If later stack PRs use these, move them there.

  • Remaining int32 offsets.

    • Weight addresses: n stays int32 in the weight and weight-scale addresses (nvfp4_quantized_gemm.py:365, :375), while m is promoted. This overflows once N·K ≥ 2³², which is rare.
    • Partial store: _w4a4 computes its int64 offset inline (:387) instead of through _partial_offsets. The cheap test_partial_offsets_and_masks_are_int64 probe therefore covers only _reduce_partials. The GEMM side is covered only by the 13 GiB SM12x test.

Infrastructure

  • No CI runs the W4A4 numerics tests.
    • Skips: test_nvfp4_w4a4.py:15-18 skips the whole module below SM89, and the GEMM tests also need SM12x.
    • Runners:
      • The new Buck target runs on A100, which is SM80 (backends/cuda/tests/targets.bzl:628).
      • OSS CUDA CI runs on A10G, which is SM86 (.github/workflows/cuda.yml:529).
      • The files aren't in KERNEL_TESTS/QUANTIZED_GEMM_TESTS (cuda.yml:540-569), so they fall into the system shard.
    • Result: every test the description lists is skipped on every CUDA runner: activation reference, rounding boundary, native GEMM, split-K and int64 workspace. Only test_nvfp4_launch_validation.py runs there.
    • ROCm: .ci/scripts/test-rocm-aoti.sh:156-158 collects all of backends/cuda/tests. MI-series GPUs report capability (9, x), so the module skip doesn't exclude AMD, and the activation tests run there through tl.float8e4nv. Check the in-progress ROCm job, or add a torch.version.hip skip.
    • Fix: register the tests on an SM89+/SM12x pool, or state in the PR that they are manual-only.

Testing

  • test_activation_reference[0.001] is expected to fail on SM89+ (test_nvfp4_w4a4.py:35-37).
    • Kernel: both quantizers cast block scales with .to(tl.float8e4nv) (nvfp4_quantized_gemm.py:87, :136). This lowers to cvt.rn.satfinite.e4m3x2.f32, which clamps to 448 (0x7E).
    • Reference: .to(torch.float8_e4m3fn) doesn't saturate; values above 464 become NaN (0x7F).
    • Trigger: with static=0.001 the block scale is amax / 0.006, so every 16-element block with |x| > 2.784 diverges. About 6 of the 1,152 non-zero randn values should exceed that, so seed 123 has only about a 0.2% chance of avoiding it.
    • Effect: torch.equal(s, …) fails. The codes diverge too, because the reference divides NaN-scale blocks by 1.0. The Infrastructure finding above is why no CI catches this.
    • Fix: clamp to 448 before the cast, as torchao's to_fp8_saturated does, and add an explicit above-range static case. Fix this →
  • Production paths without coverage:
    • Per-row per_tensor_scale (ROW_PTS, nvfp4_quantized_gemm.py:381-384, :418-420): this path is real, because CudaNVFP4Tensor.fuse_along_output builds N-valued scales (nvfp4_tensor.py:105-110). weight() always uses a scalar.
    • Op arguments: output_dtype, and static_scale passed through nvfp4_w4a4.
    • Autotuned path: split_k=-1 under autotune_launch_params(), i.e. nvfp4_launch_bench, the prepass, _QUEUING_ONLY and the hinted _tuned_kernel pick. test_native_w4a4 runs without a timing session, so it always gets split_k=1.
    • Export/AOTI: no lowering of nvfp4_w4a4, a triton_op that calls another triton_op. The "AOT paths" in the description are covered only by the toy offload test.
    • Median-of-means value (cuda_graph_timing.py:159-165): one test only counts replays, and the other mocks the timer.

API Design

  • do_bench= on autotune_launch_param (launch_params.py:323) reuses Triton's name with a different contract.
    • Mismatch: it takes a one-argument callback that returns microseconds. In the same PR, triton.autotune(do_bench=autotune_do_bench) (nvfp4_quantized_gemm.py:121, :322) takes (fn, quantiles) and returns milliseconds.
    • Effect: passing triton.testing.do_bench records times_us 1000× off, and passing autotune_do_bench raises TypeError.
    • Fix: rename it, e.g. timer_us.

Performance

  • The static activation scale is compiled in.
    • Where: STATIC is a tl.constexpr in _row_scale (nvfp4_quantized_gemm.py:72) and _fused_activation (:125). It is also in the latter's autotune key (:120).
    • Effect: every distinct calibrated scale compiles its own quantizer, and on SM12x autotunes it too. Split-K is also re-timed for each value, because the float goes into _argument_key (launch_params.py:162-163).
    • Impact: CudaNVFP4Tensor.act_per_tensor_scale is a per-weight float (nvfp4_tensor.py:56-57). A statically calibrated model would carry one quantizer specialization per distinct layer scale in the AOTI .so.
    • Fix: pass the scale as a runtime fp32 argument with a HAS_STATIC: tl.constexpr flag, and drop it from the key. Fix this →
  • Split-K and tile picks made at the export size hint are reused for every runtime M.
    • Mechanism:
      • _check_split_workspace bounds split_k * _size_hint(m) * n * 4 (nvfp4_quantized_gemm.py:44).
      • The split pick is cached by hinted shape (launch_params.py:155-162).
      • launch_nvfp4_kernel pins _w4a4 to the config tuned at _size_hint(M) (nvfp4_tuning.py:64-66).
      • The (split_k, m, n) FP32 workspace is allocated with the runtime m (nvfp4_quantized_gemm.py:434-435), and the compiled graph never re-checks it.
    • Trigger: take a dynamic M with a decode-sized hint, and a split-32 pick, which is plausible for a down projection with few N tiles. At M=4096 that allocates 32·4096·4096·4 B ≈ 2.1 GB per call and runs prefill on the BM=16 decode tiles.
    • Fix: the INT family avoids both by tuning and sizing per static M bucket (quantized_gemm_family.py:531-538, check_rows). Adopt buckets, or bound the workspace by M's upper bound.
    • Workspace limit: separately, the limit is half of total memory on torch.cuda.current_device() (:35-39), not free memory on x.device. With weights resident, a passing candidate can still OOM into the retry/park path.

Recommendation

Request Changes

  • Blocking: the activation reference test is expected to fail on the hardware it targets, and no CI runner exercises these kernels, so CI validates none of the new numerics.
  • Before callers adopt nvfp4_w4a4: add input and capability validation, and pass the static scale at runtime.
  • Needs a decision: how the split/tile picks handle dynamic M, either buckets or an upper bound.

…code down so A100 CI runs the NVFP4 kernels

[ghstack-poisoned]
@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 32m 22s —— View job


Requesting changes for one design issue: the new timing_on_random_inputs() flag adds a side channel to the shared launch-param autotuner just so a second, redundant scale check can be skipped during timing, and a private unchecked helper would remove both; the other findings are minor.

Detailed review

PR Review: #25340

Summary

This PR adds NVFP4 W4A4 to the CUDA backend: Triton activation quantization (fused native FP4 on SM120, software elsewhere), a tl.dot_scaled GEMM with autotuned split-K, and mean/multi-replay CUDA-graph timing for NVFP4 tuning. One design issue should be fixed before landing (API Design). The rest are minor; the aliasing item is low confidence.

API Design

  • timing_on_random_inputs() is a side channel in the shared autotuner. It exists only to undo a double scale check.

    • Where: defined at backends/cuda/autotune/launch_params.py:121-139, entered at :256, and read at backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:118.
    • Why it exists: nvfp4_w4a4 checks the scale at :590. _launch_w4a4_impl (:537) then calls the public op nvfp4_quantize_activation, which checks it again at :274.
    • During split-K timing, that second check sees the normal(0, 0.5) stand-ins from _random_like. Without the flag, about half of the timed shapes that have a static scale would raise a plain ValueError (not InvalidLaunchParam), and the compile would abort.

    Consequences:

    • Every launch function now has an unwritten rule: read the flag before value-checking an input. The rule is not in the module doc's random-input contract (launch_params.py:24-28), and the flag is not in __all__ (:435-442). The next launch function that reaches a validating op will abort compiles the same way unless its author knows about the flag.
    • Each eager nvfp4_w4a4(..., static_scale=<CUDA tensor>) call does two blocking bool() device-to-host syncs instead of one (nvfp4_quantized_gemm.py:590 and :274).

    Fix:

    1. Move the op body that follows its checks (:275-294) into a private unchecked _quantize_activation(x, static_scale).
    2. Call it from both nvfp4_quantize_activation and _launch_w4a4_impl. Each public op then checks once, at entry. No check is lost: _check_operands/_check_weight already imply K % 16 == 0 and contiguity, and :590 covers the scale.
    3. Delete _ON_RANDOM_INPUTS, _on_random_inputs, timing_on_random_inputs, the :118 clause, and test_timing_is_flagged_as_running_on_random_inputs (test_autotune_launch_params.py:99-112).

    Fix this →

Testing

  • No test reaches the value-check skips in _check_static_scale (nvfp4_quantized_gemm.py:115-121).

    • The meta case of test_activation_rejects_invalid_static_scale (test_nvfp4_launch_validation.py:66) pairs a meta scale with a CPU x. The device check (nvfp4_quantized_gemm.py:106) rejects it before it reaches the meta skip (:117).
    • No test calls the check under CUDA-graph capture (:119). A regression there would only show up when a user captures an eager model.

    Add a case with a meta x and a zero meta scale that must not raise. Also add a CUDA-only case, like test_partial_offsets_and_masks_are_int64 in the same file, that calls the check with a zero scale inside torch.cuda.graph(...). Fix this →

Code Quality

  • The activation dtype is still unchecked (open since round 4). _check_operands (nvfp4_quantized_gemm.py:125-135) and nvfp4_quantize_activation (:269-274) accept any x.dtype. The output dtype defaults to x.dtype (:538), so an integer x returns silently truncated results. INT4 rejects non-bf16 activations with check_dtypes (int4_quantized_gemm.py:1709-1711). This check can go in with the pending rank/output_dtype checks. Fix this →

  • Low confidence: on the dynamic path, g is passed as both the written G and the unread STATIC (nvfp4_quantized_gemm.py:279, launched at :281-293).

    • This is harmless while torch's TTIR mutation analysis of the kernel succeeds.
    • If that analysis fails, torch assumes every tensor argument is mutated. Functionalization then clones G and STATIC separately and replaces g with each output in argument order. STATIC's unwritten clone wins, so the compiled op returns uninitialized g.
    • Torch's analysis has historically given up on tt.elementwise_inline_asm, which _fused_activation uses at :244. I could not check whether the pinned torch accepts it with is_pure=True. A warning containing "assuming every input is mutated" when test_static_scales_share_one_inductor_kernel runs on SM120 would confirm the failure.
    • No test here compiles static_scale=None; that test (test_nvfp4_w4a4.py:201-215) uses static scales only.

    Passing the read-only x as the placeholder removes the hazard, and adding None to that test would catch it. Fix this →

  • The PR description does not mention two changes to shared timing code.

    • quantized_gemm_utils.autotune_do_bench now re-raises ParkedTensorsNotRestored (quantized_gemm_utils.py:399-400). INT4/5/6/8 compiles that used to warn and fall back to Triton timing now abort.
    • _parked_on_cpu now parks and restores outside fake/functional modes (cuda_graph_timing.py:237-260).

    The description only says the existing timing defaults are preserved. List these changes there, or split them into their own stack entry, so the owners of the integer kernels see them.

  • Smaller cleanups:

    • _SMALL_M_CONFIGS (nvfp4_quantized_gemm.py:297-375, open since round 5) is 25 hand-written configs. They are 10 tiles at num_stages 1 and 2, plus stage 3 for five of those tiles, so a table of tiles could generate them.
    • M is unused in _row_scale (:154) and _activation (:167).
    • test_split_workspace_exceeds_int32 re-imports kernels (test_nvfp4_w4a4.py:254), which is already imported at :20.

    Fix this →

Recommendation

Request Changes

The API Design item is the only blocker. Its fix is small and deletes code, and it should land before other launch functions start relying on timing_on_random_inputs(). The other items are minor, and the aliasing item is low confidence.


  • Gather PR context, the diff against origin/gh/gasoonjia/215/base, and earlier rounds
  • Three independent reviews (all 13 changed files covered)
  • Consolidate findings
  • Fact-check
  • Post review

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

Copy link
Copy Markdown
Contributor Author

Thanks. Round 7:

  • I removed timing_on_random_inputs(), its context manager and its test; launch_params.py is back to its round-5 state.
  • The quantizer body is now a private, unchecked _quantize_activation. nvfp4_quantize_activation checks once and calls it, and _launch_w4a4_impl calls it directly. Each public op validates once at entry, so an eager call with a CUDA scale syncs once. Tuning on random stand-ins never reaches a value check.
  • Upstack callers in launch paths also use the unchecked paths. The auto ops call _launch_w4a4_impl and _launch_w4a4_gate_up_impl, and the small-M W4A4 launch uses _quantize_activation. Each of those public ops validates once at entry.
  • New tests reach the value-check skips: a meta x with a zero meta scale, and a zero CUDA scale inside torch.cuda.graph capture. The public ops still reject tensor 0, -1, inf and nan, and a CUDA test shows an eager nvfp4_auto_prefill with a static scale tunes cleanly. The RTX 5090 PTE export with a static scale passes again (see validation).
  • Still deferred: rank, activation dtype and output_dtype checks.

@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 34m 32s —— View job


Round 8 has no blockers. There are two minor findings: the Buck A100 target's pytest_expr skips the new graph-capture test, and the public nvfp4_quantize_activation op has no SM89+ capability check even though its software path needs one. Recommendation: Approve.

Detailed review

PR Review: #25340

Summary

This PR adds NVFP4 W4A4 Triton kernels to the CUDA backend:

  • activation quantization, either fused (SM120) or software, with an optional static scale read at run time;
  • a tl.dot_scaled GEMM with autotuned split-K and int64 partial-workspace offsets;
  • changes to the shared CUDA-graph timing code that these kernels use.

All 13 changed files were reviewed. Two minor issues remain and neither blocks approval. Nothing could be run in this job (no GPU and no Python), so the findings come from reading the code.

Infrastructure

  • The graph-capture test added in round 7 never runs in Buck (backends/cuda/tests/targets.bzl:635, :648). The test is test_static_scale_values_are_not_read_during_graph_capture (test_nvfp4_launch_validation.py:96-101).

    • The CPU target test_nvfp4_launch_validation_cpu (pytest_expr = ["not partial_offsets_and_masks"]) selects it, but there is no CUDA there, so its skipif skips it.
    • The A100 target test_nvfp4_launch_validation (pytest_expr = ["partial_offsets_and_masks"]) leaves it out.

    As a result, the capture-time check in _check_static_scale (nvfp4_quantized_gemm.py:113-119) is not tested internally. Only the OSS A10G system shard in cuda.yml runs it. Fix: change line 648 to pytest_expr = ["partial_offsets_and_masks or graph_capture"].
    Fix this →

Code Quality

  • triton::nvfp4_quantize_activation has no capability check (backends/cuda/triton/kernels/nvfp4_quantized_gemm.py:266-271).

    • Below SM120 the op takes the software path, where _activation casts to tl.float8e4nv (line 170). The test gate (test_nvfp4_w4a4.py:27-32) and the comment at test_nvfp4_w4a4.py:36-37 say this path needs SM89+.
    • nvfp4_w4a4 raises a clear RuntimeError when its own hardware requirement is not met (lines 594-595). This op does not.
    • A direct call on SM80 or SM86 (the A100 and A10G CI GPUs) fails while Triton compiles _activation.
    • Under torch.export, which traces without compiling, the failure only appears at AOTI compile time.

    No non-test code calls the op yet, so this is minor. Fix: after the existing validation, raise RuntimeError unless the target is NVIDIA CUDA SM89 or newer. Mirror lines 594-595 and the assume_constant_result predicate at line 196, and add a CPU test that mocks the predicate to return False.
    Fix this →

Recommendation

Approve

Nothing blocks approval. Both findings are small and can be fixed in this round or in a follow-up.


Review progress

  • Gather PR context and the diff against origin/gh/gasoonjia/215/base
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post 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 30m 32s —— View job


Claude finished @Gasoonjia's task

Approve, with four minor follow-ups: this PR's tests don't call the new sweep() helper yet, the graph-capture test never runs under Buck, the W4A4 output checks only verify whichever config the autotuner picks (always at M ≤ 37), and nvfp4_quantize_activation has no SM89+ check.

Detailed review

PR Review: #25340

Summary

This PR adds the NVFP4 W4A4 Triton path:

  • an SM120 fused activation quantizer and an SM89+ software one;
  • a tl.dot_scaled GEMM with autotuned split-K and a bounded fp32 workspace;
  • statistic and replays options for the shared CUDA-graph timing.

Since the last review, the only change here is the sweep() helper that the base update added to nvfp4_test_utils.py. This PR's own diff hasn't changed.

Four minor issues remain, and none blocks. Two of them (the Buck test selection and the capability check) were raised last round and are still open.

Nothing was executed, because this job has no GPU and couldn't run Python. Everything below comes from reading the code.

Infrastructure

1. This PR's tests never call sweep(), so the update's "representative cases by default" claim doesn't apply here.

Neither test_nvfp4_w4a4.py nor test_nvfp4_launch_validation.py imports sweep, and nothing in backends/cuda calls it (it is defined at nvfp4_test_utils.py:16). A default run and an ET_CUDA_NVFP4_EXHAUSTIVE_TESTS=1 run execute exactly the same cases.

On A100 the W4A4 file skips entirely, because its module gate needs SM89+. The cost falls on SM120 machines, where every default run includes:

  • test_split_workspace_exceeds_int32 (test_nvfp4_w4a4.py:250-294). It allocates a (16, 4096, 39936) fp32 workspace, about 9.75 GiB, whenever 13 GiB is free.
  • test_gemm_split_k (test_nvfp4_w4a4.py:236-247). It runs six splits, and each is a separate _w4a4 autotune key because SPLIT_K is part of the key (nvfp4_quantized_gemm.py:431).

Wrap both tests in sweep. If the reduction is meant to land upstack (#25341 renames this file), say so in the PR body instead.

Fix this →

2. test_static_scale_values_are_not_read_during_graph_capture never runs under Buck (also raised last round).

  • The CPU target (targets.bzl:635, not partial_offsets_and_masks) selects it, but its skipif(not torch.cuda.is_available()) (test_nvfp4_launch_validation.py:96) skips it there.
  • The A100 target (targets.bzl:648, partial_offsets_and_masks) deselects it.

Tests are assigned to targets by name, and these are the only pytest_expr uses in targets.bzl. Any CUDA test added to this file later will also be skipped silently in Buck. Add or graph_capture to the GPU expression and exclude it from the CPU one.

Fix this →

Testing

3. The W4A4 output checks only verify the config the autotuner picks, and only at M ≤ 37.

_w4a4 has 54 configs: 29 at nvfp4_quantized_gemm.py:397-427 plus the 25 in _SMALL_M_CONFIGS. Each autotuned output check verifies only whichever config wins the timing for its key, and all of them use M ≤ 37.

  • Every GROUP_M > 1 config has BM ≥ 64. At M ≤ 37 there is a single M tile, so the grouped pid→tile mapping (nvfp4_quantized_gemm.py:458-461) reduces to the identity. Its behavior across several M tiles and a partial last group is never output-checked.
  • The same goes for the BM=256 and BN=256 "M=4096 search leaders" (:405-425) at the shapes they were added for.
  • test_split_workspace_exceeds_int32 does run at M=4096, but it launches one fixed GROUP_M=1 config.

The other quantized GEMMs in this directory check each config's output separately through triton.autotune(configs=[config], ...) (test_int4_quantized_gemm.py:648-651, test_int8_quantized_gemm.py:92, test_triton_sdpa.py:333-334). Add the same for _w4a4 on SM120, at a shape with several M tiles and a partial last group (for example M=600, N=384). Put it behind sweep if it is too slow by default.

Fix this →

Code Quality

4. nvfp4_quantize_activation has no capability check (also raised last round).

The software path casts to tl.float8e4nv (nvfp4_quantized_gemm.py:170), and the tests' own gate says that path needs SM89+ (test_nvfp4_w4a4.py:27-32, :36-37). On SM80/SM86, including the A100 this PR's Buck targets use, a direct call to the public op (:260-271) fails inside Triton compilation, where fp8e4nv isn't supported. nvfp4_w4a4, by contrast, raises a clear error (:594-595).

Add the same kind of check after the existing validation, so the CPU tests that expect ValueError keep passing.

Fix this →

Recommendation

Approve. None of the four items is a correctness or compatibility problem in the kernels or dispatch, so all of them can be follow-ups. If the sweep change is meant to land upstack, item 1 only needs a one-line answer.


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

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Moved. sweep is now added in #25341 together with its first caller, so neither this PR nor #25339 adds an unused helper. This PR's diff is unchanged.

Authored with Claude Code.

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Rebased onto main. _parked_on_cpu conflicted with upstream's share_weights change (#24937). That change added _parkable() and skips the parked retry when nothing is parkable. The real-tensor guard (unset_fake_temporarily() / _disable_current_modes()) is now an ExitStack entered before the parking loop and closed before the yield (and in finally), so the loop body itself is unchanged and the change applies on either version of the loop. In test_cuda_graph_timing.py, test_mean_statistic_survives_oom_retries_and_offload offloads a real CUDA tensor, so the parked retry runs with or without upstream's _parkable check. _time_capturing_robustly forwards statistic/replays to time_with_cuda_graph_us only when they differ from the defaults. A one-argument timer, like the mocks in upstream's new test_oom_with_nothing_to_park_falls_back_without_parking and the older OOM tests, keeps working, so those tests stay unmodified. test_autotune_launch_params.py keeps upstream's new test and this PR's two.

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


Claude finished @Gasoonjia's task

Approve for 9ff8f07 with minor follow-ups, but the rebase described at 18:13 UTC isn't on the branch yet (head is still 9ff8f07 from 14:33 UTC), so its conflict resolution with main's _parkable() hasn't been reviewed.

Detailed review

PR Review: #25340

Summary

This PR adds NVFP4 activation quantization (a fused SM120 kernel and an SM89+ software path), an SM120 tl.dot_scaled W4A4 GEMM with autotuned split-K, and statistic/replays options for the shared CUDA-graph timing.

  • The rebase described in the 18:13 UTC reply is not on the branch. origin/gh/gasoonjia/215/head is still 9ff8f07, pushed at 14:33 UTC. That commit has:

    • no _parkable();
    • nested with guards in _parked_on_cpu (cuda_graph_timing.py:239, :254), not an ExitStack;
    • statistic/replays forwarded on every attempt (:282, :287, :299);
    • offload=lambda: [] in test_mean_statistic_survives_oom_retries_and_offload (test_cuda_graph_timing.py:330). That test would fail against main's nothing-to-park re-raise (origin/main cuda_graph_timing.py:269).

    This review covers 9ff8f07, which is round 9's diff minus sweep. Please re-push with ghstack so the conflict resolution can be checked.

  • The resolution the reply describes adds a branch to shared code for test mocks. It forwards statistic/replays only when they differ from the defaults, so that one-argument mocks keep working. Giving those mocks **kwargs keeps one unconditional call. This PR already does that for flaky (test_cuda_graph_timing.py:108) and oom (:140).

  • The PR description doesn't mention the _parked_on_cpu real-tensor guard (cuda_graph_timing.py:237-260). That guard changes shared code outside NVFP4.

Apart from that, the items for 9ff8f07 are minor: a Buck selection gap, untested device checks, and cleanups.

Infrastructure

  • test_static_scale_values_are_not_read_during_graph_capture still never runs in Buck. This was raised in rounds 8 and 9 and has no reply.

    • The CPU target selects it (not partial_offsets_and_masks, targets.bzl:635), but the test's CUDA skipif (test_nvfp4_launch_validation.py:96) skips it there.
    • The A100 target excludes it (partial_offsets_and_masks, :648).
    • So the capture branch of _check_static_scale (nvfp4_quantized_gemm.py:116) has no Buck coverage.
    • Fix: use ["partial_offsets_and_masks or graph_capture"] on the A100 target and ["not (partial_offsets_and_masks or graph_capture)"] on the CPU target.

    Fix this →

Testing

  • The device checks listed in the PR description are untested. No case in test_w4a4_rejects_malformed_operands (test_nvfp4_launch_validation.py:25-58) reaches nvfp4_quantized_gemm.py:95-96 or :131-132. This was raised in round 6 and has no reply.

    • Meta tensors reach both checks on CPU-only hosts, as the existing meta static-scale case does (:66). Put scale on meta for the first check, and all three weight tensors on meta for the second.
    • Only pts_dtype exercises the dtype tuple at :87-92. No case changes the qdata or scale dtype.

    Fix this →

Code Quality

  • nvfp4_quantize_activation has no target check (nvfp4_quantized_gemm.py:260-271). This was raised in rounds 8 and 9 and has no reply.

    • Without native FP4, the op takes the software path, whose tl.float8e4nv cast (:170) needs SM89+.
    • On SM80 it fails while Triton compiles that cast, not with a clear error like nvfp4_w4a4's (:594-595). ROCm, which the stack excludes, is not rejected either.
    • Put the check after the operand checks, as nvfp4_w4a4 does, so the CPU validation tests keep passing.

    Fix this →

  • A failed weight restore is now also counted as a fallback.

    • This PR stops autotune_do_bench from swallowing ParkedTensorsNotRestored (quantized_gemm_utils.py:399-400), so the compile aborts.
    • But time_with_cuda_graph_us_counted still adds the error to fallbacks before re-raising (cuda_graph_timing.py:105-109).
    • The aborting compile therefore logs "1 fell back" (:393-400). The Inductor path doesn't count it (:325-326).

    Fix this →

  • Smaller items:

    • M is unused in _row_scale (nvfp4_quantized_gemm.py:151) and _activation (:164).
    • _max_rows runs in the op (:606) and again on its result (:58). Only the SymInt tests (test_nvfp4_launch_validation.py:132-134) need the second call. _check_split names the same bound m (:69-75).
    • _launch_w4a4_impl already defaults output_dtype to None (:535, :541), so the conditional at :598-599 isn't needed.
    • _SMALL_M_CONFIGS writes out 25 triton.Config(...) calls across a list and a += (:300-378). The configs next to it use a tuple table (:392-429).
    • Two docstrings describe the change rather than the code: cuda_graph_timing.py:147-148 ("Defaults retain the existing single-replay minimum used by Inductor and INT4") and launch_params.py:331 ("Its default retains the existing CUDA-graph minimum timing").
    • test_native_w4a4 re-implements w4a4_reference inline (test_nvfp4_w4a4.py:130-134 vs :139-143).
    • test_split_workspace_exceeds_int32 re-imports kernels (:254), which is already imported at :20.

    Fix this →

Recommendation

Approve (9ff8f07). None of the findings above blocks merging. The one piece not reviewed is the conflict resolution in the shared timing code: _parked_on_cpu, _time_capturing_robustly and the offload test. It needs a look once the rebase is pushed.


  • Gather context (diff against origin/gh/gasoonjia/215/base, rebase changes, prior rounds)
  • Run three independent reviewers
  • Consolidate findings
  • Fact-check findings
  • Post review

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — 9ff8f079 Deployed Nov 23, 2026 by Gasoonjia via upload-benchmark-results #23170
cadence — 9ff8f079 Deployed Nov 23, 2026 by Gasoonjia via hifi5s-op-test / hifi5s #40345
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