Skip to content

[executorch][cuda] NVFP4 fused gated GEMM and dispatch - #25343

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

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

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Adds fused NVFP4 gate/up GEMM with a SiLU/multiply epilogue, split-K reduction, and scalar/per-row global-scale support. Registers the gated-linear custom op for CudaNVFP4Tensor weights (rows are [gate; up] from fuse_along_output, N even; fused prefill kernels with native FP4 and BF16 activations, or FP32 activations when the FP32 prefill policy applies, i.e. at prefill size, as in _linear; otherwise NVFP4 F.linear + SiLU-gating) and eager/export-time auto-dispatch helpers. Plain weights raise; the op, nvfp4_w4a4_gate_up (including the static activation scale's value in eager calls) and the epilogue validate their operands like nvfp4_w4a4, and the fused kernel uses int64 weight offsets. The autotuned gate/up launches get the traced M's bound for their split-K workspace check, and take the static activation scale as the weight's (1, 1) tensor (or None), so their launch keys see only static versus dynamic. nvfp4_auto_gate_up_prefill validates its operands and scale once at entry; its W4A4 candidates call the unchecked launch and raise InvalidLaunchParam without native FP4, so tuning skips them.

Serialized PTE tests cover all six split-K choices with random block scales, scalar/per-row scales, and dynamic input sizes, plus a module that calls the op on an NVFP4 parameter. The op's fused W4A4 branch (2-D/3-D inputs, static activation scale, FP32 prefill output), auto eager and autotuned prefill, and split-K autotuning are checked against W4A4/W4A16 references; these need native FP4 and run on an RTX 5090 (SM120). The weight-only path, CPU fallback and epilogue run on SM89+ here and on A100 from the software E4M3 decode later in the stack.

Authored with Claude Code.

Differential Revision: D132997716

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

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

❌ 2 New Failures

As of commit e0c2a71 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 added a commit that referenced this pull request Nov 21, 2026
Pull Request resolved: #25343

Adds fused NVFP4 gate/up GEMM with a SiLU/multiply epilogue, split-K reduction, and scalar/per-row global-scale support. Registers the gated-linear custom op and eager/export-time auto-dispatch helpers.

Serialized PTE tests cover all six split-K choices, scalar/per-row scales, and dynamic input sizes.

Authored with AI assistance (agentcloud).
ghstack-source-id: 480369812
@exported-using-ghexport

Differential Revision: [D132997716](https://our.internmc.facebook.com/intern/diff/D132997716/)
@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 27m 48s —— View job


Adds a fused NVFP4 gate/up Triton GEMM and the triton::nvfp4_gated_linear dispatch; I found no bugs in the kernel math, but recommend Request Changes because the new test can't reach an assertion on any CI hardware, and the custom op, auto-dispatch and epilogue kernel have no tests or callers.

Detailed review

PR Review: #25343

Summary

The PR adds _gate_up, a W4A4 gate/up GEMM with a fused SiLU·mul epilogue and split-K reduction. It also adds the nvfp4_gate_up_epilogue op, the autotuned triton::nvfp4_auto_gate_up_prefill, and the triton::nvfp4_gated_linear custom op with its CudaNVFP4Tensor handler.

Three independent reviewers traced the kernel's indexing, masks, grid, int64 offsets, split-K partial layout and reduction, and BF16 rounding, and found no correctness bugs. The problems are:

  • the new test never reaches an assertion in CI;
  • about half of the new code has no test and no caller;
  • the custom op's fake and real implementations disagree;
  • its contract is not written down.

I didn't run anything: the runner has no GPU and doesn't allow Python execution. Every finding below comes from reading the code.

Code Quality

  • nvfp4_dispatch.py:163-204: the three implementations of triton::nvfp4_gated_linear disagree.
    • Shape checks. The even-N and matching-K checks exist only in _fake_gated_linear (165-166). For CudaNVFP4Tensor weights, what actually runs is _gated_linear, both in eager and under fake/export tracing, because FakeTensorMode defers to the subclass. _gated_linear checks neither, unlike _linear (215-216). Two consequences:
      • Odd N on SM120, eager auto mode: outside the AOTI launch context, autotune_launch_param uses the first candidate (launch_params.py:43-45). That is _MODE_SPLITS[0], i.e. W4A16 followed by nvfp4_gate_up_epilogue. That path silently returns N // 2 columns with the up half shifted. Only the explicit w4a4 launcher raises a clear error (nvfp4_gated_gemm.py:177).
      • K mismatch: _launch_w4a4_gate_up_impl (nvfp4_gated_gemm.py:175) and _launch_w4a16_impl (nvfp4_quantized_gemm.py:972) take K from x and use it as the stride into qdata/scale. They read past the weight rows instead of raising.
    • Dtype. Under ET_CUDA_NVFP4_PREFILL_OUTPUT=fp32, when M is not statically ≤ 4, the fake returns float32. The default body (158-160, used for plain weights) returns x.dtype, so torch.library.opcheck would flag the op.
    • Fix this →
  • Copied logic has already drifted from the original.
    • _gate_up's main loop (nvfp4_gated_gemm.py:65-104) is a line-for-line copy of _w4a4's (nvfp4_quantized_gemm.py:344-380). Only the n/column remap and the masks differ.
    • _gated_linear copies _linear's ET_CUDA_NVFP4_ACT parsing (175-177 vs 212-214), and the dense gated body appears twice (158-160 and 188-190).
    • The copied routing no longer matches _linear's:
      • fp16 never takes the fused path (181-184), but _linear sends fp16 to Triton.
      • The fused path requires _has_native_fp4() (186), even for the W4A16 + epilogue candidate, which needs neither SM120 nor bf16. So gate/up never fuses on H100 or B200.
    • A shared @triton.jit main-loop helper that takes n and the column mask, plus one eligibility helper used by both _linear and _gated_linear, would keep the two paths in sync.

Infrastructure

  • targets.bzl:689-696, test_nvfp4_gate_up.py:22-25,69-71: the new test can't reach an assertion on any CI hardware.
    • pytestmark requires _has_native_fp4(), i.e. compute capability ≥ 12.0 (nvfp4_dispatch.py:33-35).
    • In fbcode, the new target is pinned to subplatform = "A100" (SM80).
    • In OSS, the file lands in the unittest-cuda system shard, which runs on mt-l-x86aavx2-11-41-a10g (SM86; .github/workflows/cuda.yml:529,538-539).
    • So all 12 cases always skip. Even on SM120, fbcode returns at line 69 before any numeric check.
    • The sibling NVFP4 targets share the A100 pin. For this PR, though, it means the fused kernel, the split-K reduction and the PTE round trip get no automated signal at all.
    • Fix: use an SM120 remote-execution platform if one exists. Otherwise, say in the PR that the test is local-only, and add a CPU target (like test_nvfp4_launch_validation_cpu) for the parts that need no FP4 hardware: op registration and the fake's shape/dtype rules.
  • targets.bzl:689-696: the new target duplicates test_nvfp4_dispatch.
    • It has the same deps and the same A100 platform. Three of those deps are not imported by the test: :nvfp4_test_utils, :nvfp4_tensor, and //executorch/extension/llm/export:nvfp4.
    • The sibling PTE test test_nvfp4_split_k_export.py is already a src of test_nvfp4_dispatch (654-661).
    • Fix this →

Testing

  • test_nvfp4_gate_up.py:42: about half of the new code has no test and no caller.
    • The test only calls nvfp4_w4a4_gate_up with an explicit split_k.
    • Nothing in the repo calls triton::nvfp4_gated_linear, nvfp4_auto_gate_up_prefill or nvfp4_gate_up_epilogue; grep finds only their definitions.
    • That leaves these untested:
      • _gated_linear: the env modes, the fallback and the 3-D reshape;
      • _fake_gated_linear;
      • the _prefill_gate_up mode/split decoding;
      • the _gate_up_epilogue kernel, which is what eager auto mode actually runs;
      • the autotuned split_k=-1 path;
      • a nonzero static_scale/act_per_tensor_scale;
      • output_dtype=torch.float32.
    • These are the "custom op and eager/export-time auto-dispatch helpers" the description says the PR registers.
    • Fix this →
  • test_nvfp4_gate_up.py:34-36,79-87: the numeric check can't catch errors in the new scale remapping.
    • Every block scale is 0.0625. Suppose a regression loaded BS with column instead of n (nvfp4_gated_gemm.py:100), giving the up half the gate rows' scales, or read the wrong K group. The output would not change.
    • The expected value comes from the Triton nvfp4_w4a4, which shares nvfp4_quantize_activation and the dot_scaled loop that _gate_up copies. A bug in that shared code would affect both sides equally and go unnoticed.
    • nvfp4_test_utils.weight() already builds random E4M3 scales, and test_nvfp4_split_k_export.py:79-107 has an independent float64 dequant reference.
    • Fix this →

API Design

  • nvfp4_dispatch.py:150-157: triton::nvfp4_gated_linear's contract isn't written down.
    • The docstring explains the Dynamo constant-capture workaround, but not what callers must provide:
      • weight rows must be [gate; up], in the order CudaNVFP4Tensor.fuse_along_output([gate, up]) produces, with per-row per_tensor_scale in the same order;
      • the op returns silu(x @ gate.T) * (x @ up.T);
      • N must be even.
    • A checkpoint with interleaved gate/up rows would give silently wrong output.
    • The generic name also hides that the op always routes to prefill kernels. A decode method (static M ≤ NVFP4_DECODE_MAX_ROWS) calling it loses the GEMV path that _linear picks for the same weight (237, 247-259).
    • Fix: document the op as prefill-only, or name it that way, or add the small-M branch.
    • Fix this →

Recommendation

Request Changes

Two things block approval:

  • The custom op, the auto-dispatch and the epilogue kernel have no tests.
  • The one test added can't reach an assertion on any CI target.

To unblock, add coverage for nvfp4_gated_linear. Then either run the test on SM120 hardware, or document it as local-only and add CPU coverage for the op registration. The other findings are minor.

Review steps
  • Gathered context: diff against origin/gh/gasoonjia/218/base, 5 files, +421/-0
  • Ran three independent reviewers
  • Merged about 30 raw findings into the 7 above
  • Fact-checked every finding against the code. I dropped one suspected finding: that the F.linear fallback in _gated_linear dequantizes the whole weight through _transpose. The custom op's autograd kernel redispatches below autograd, so aten.linear.default reaches _linear. I also dropped a style note on the hand-written SiLU, whose x / (1 + exp(-x)) form appears to mirror PyTorch's CUDA SiLU.
  • Not done: running tests or Python (no GPU, and Python execution isn't permitted in this runner)

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks. Round 6: test_nvfp4_gate_up.py now has the autouse fixture that clears ET_CUDA_NVFP4_ACT/ET_CUDA_NVFP4_PREFILL_OUTPUT. nvfp4_w4a4_gate_up checks the static scale's value in eager calls, as nvfp4_w4a4 does, and a CPU test covers 0, -1, inf and nan.

@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 18m 37s —— View job


Approve: no reviewer found a bug in the kernels, the dispatch or the round-6 changes. Three minor findings remain: no CPU test checks that nvfp4_gated_linear keeps its weight a named parameter, the kernel file imports the CUDA-specific libdevice, and one delenv is now redundant.

Detailed review

PR Review: #25343

Summary

The PR adds:

  • _gate_up, a W4A4 gate/up GEMM with split-K and a fused SiLU·mul epilogue;
  • the W4A16 + nvfp4_gate_up_epilogue alternative;
  • the autotuned triton::nvfp4_auto_gate_up_prefill;
  • the triton::nvfp4_gated_linear op and its CudaNVFP4Tensor handler.

No reviewer found a bug in the kernels, the dispatch, or the round-6 changes (the autouse policy fixture and the static-scale check). Three minor findings remain. I didn't run anything because the runner has no GPU, so every finding comes from reading the code.

Testing

  • test_nvfp4_gate_up.py:349-365: no test checks the property the op exists for, that its weight stays a named parameter.
    • What the docstring promises (nvfp4_dispatch.py:191-194): the weight stays an op argument. If a model's forward reads an NVFP4 parameter's fields, Dynamo captures them as anonymous constants. Those constants can't share GPU storage with the decode method's named parameters.
    • Why it would matter: the CUDA weight collector keys _tensor_constant* FQNs by AOTI library (cuda_weight_collector.py:247-251). So each method would carry its own copy of the weight.
    • What the tests check: test_gated_linear_auto_export_traces_the_auto_op and test_gated_linear_parameter_pte both export a module with an NVFP4 parameter. They only assert which kernel op ran and the numerics.
    • Trigger: suppose a PyTorch upgrade or a refactor lets tracing see the weight's fields. One example is moving the fused-path call (nvfp4_w4a4_gate_up(x, w.qdata, ...)) from _gated_linear into a model forward. Every test in this file would still pass. The duplicated GPU weights would only show up in a multi-method program.
    • Fix: in the CPU export test (which CI runs), keep the program that torch.export.export returns before calling run_decompositions(). Then assert that it lifts no tensor constants and that weight is in graph_signature.parameters. For example: assert not exported.graph_signature.lifted_tensor_constants and assert "weight" in exported.graph_signature.parameters. I haven't run this assertion.
    • Fix this →

Code Quality

  • nvfp4_gated_gemm.py:33: the file imports the CUDA-specific libdevice, unlike the rest of the package.
    • quantized_gemm_utils.py:38 imports from triton.language.extra import libdevice. Triton resolves that module to the target's libdevice when it compiles the kernel, and that file also builds for HIP (_IS_HIP, line 43).
    • nvfp4_gated_gemm.py is the only file in backends/ that imports triton.language.extra.cuda. On NVIDIA both imports give the same exp, so switching costs nothing.
    • On ROCm, the CUDA import probably means _silu_mul can't compile. nvfp4_gate_up_epilogue is a public op with no device check, so a direct call there would fail. I haven't verified this, and the test file skips HIP.
    • Fix this →
  • test_nvfp4_gate_up.py:170: this monkeypatch.delenv("ET_CUDA_NVFP4_PREFILL_OUTPUT", ...) is now redundant. The autouse default_policy fixture (lines 54-57) already clears the variable before each test.

Recommendation

Approve

Nothing blocks approval, and each finding is a small fix. The first is the most useful, because CI can run it on CPU. The gap you deferred in round 5, a second N tile and _gate_up's small-M configs, is still open.

Review steps
  • Gathered context: the diff against origin/gh/gasoonjia/218/base (5 files, +886/-1), the round 1–6 reviews and your replies
  • Ran three independent reviewers, who covered all five changed files between them
  • Merged 19 raw findings into 12 candidates
  • Fact-checked each candidate against the code; three survived. Dropped:
    • In auto mode, decode-size BF16 calls take the prefill kernels and never GEMV (all three reviewers, rated major). The docstring documents this (nvfp4_dispatch.py:186-189), and rounds 3–6 dropped it for that reason.
    • No CI runner reaches the fused kernels (all three). You've acknowledged this.
    • gate_up_weight fuses unequal 31/19-row shards (all three). Rounds 2 and 4–6 dropped this. The split-K PTE test's linspace row scales cover the per-row lookup in both halves.
    • _gated_linear repeats _linear's policy and excludes FP16, and raises ValueError rather than RuntimeError for a K mismatch (all three). The duplication was raised in round 1. The docstring documents the FP16 exclusion, and the module already uses both exception types.
    • Importing nvfp4_dispatch doesn't register the nvfp4_gated_gemm ops (one). Dropped in rounds 5 and 6.
    • Tiles past the first along N (one). You deferred this in round 5; see the Recommendation.
    • Missing routing rows (two): BF16 at decode size, FP16 under the FP32 policy, w4a4 without native FP4, and an invalid ET_CUDA_NVFP4_ACT. The decode row would only pin documented behavior. The FP16 and no-FP4 w4a4 cases fall back to _linear, whose policy test_nvfp4_fusion.py tests. The invalid-mode check is one line.
    • The CPU export test duplicates test_gated_linear_routing (one, as part of the first finding). It doesn't: it is the only routing test with a dynamic M. I kept only the graph-signature part.
    • test_auto_gate_up_body_forwards_mode_split defines a recorder that shadows the module-level one (one). This is naming only.
    • test_gate_up_epilogue covers only one BF16 shape (one). Round 4 judged this low value.
  • Not done: running tests (the runner has no GPU)

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

  • The CPU export test now asserts that the NVFP4 weight stays a named parameter: no lifted tensor constants, and weight is in graph_signature.parameters.
  • I removed the redundant delenv.
  • nvfp4_auto_gate_up_prefill validates once at entry; its W4A4 candidates use the unchecked launch and are skipped without native FP4 (tested).
  • libdevice left as is.

@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 30m 52s —— View job


Approve: no kernel or dispatch bug found, but two minor test gaps remain: the round-7 changes have no test, and no test exports the F.linear fallback that every GPU below SM120 compiles.

Detailed review

PR Review: #25343

Summary

The PR adds a fused NVFP4 gate/up GEMM with a SiLU·mul epilogue and split-K. It also adds a triton::nvfp4_gated_linear op, which routes a [gate; up] CudaNVFP4Tensor either to that GEMM or to an F.linear + SiLU fallback. No reviewer found a kernel, routing, or validation bug. Two minor test gaps remain.

Testing

  • The round-7 changes to the gated W4A4 path have no test (nvfp4_dispatch.py:199-200, nvfp4_gated_gemm.py:186).

    • Entry check. test_w4a4_gate_up_rejects_invalid_static_scale (test_nvfp4_gate_up.py:227-233) calls only nvfp4_w4a4_gate_up. Deleting the new _check_static_scale call in nvfp4_auto_gate_up_prefill would not fail any test.
    • Unchecked _quantize_activation call. This change only matters during tuning:
      • Timing replaces every float tensor argument with a normal_(0.0, 0.5) stand-in, and that includes the static scale (launch_params.py:190-191, 245-246). So the stand-in scale is ≤ 0 half the time.
      • A checked call would then raise a plain ValueError (nvfp4_quantized_gemm.py:113-119).
      • The prepass and timing catch only InvalidLaunchParam (launch_params.py:214, 258), so lowering would fail.
    • No gated test tunes with a static scale:
      • test_gated_linear_auto_and_autotuned_prefill passes none (test_nvfp4_gate_up.py:315, 328).
      • GatedLinear's weight has none (350).
      • test_gated_linear_fused_w4a4 sets one, but runs outside tuning.
      • The linear ops do have this coverage: test_auto_prefill_tunes_with_a_static_scale (test_nvfp4_fusion.py:221-242) and test_static_scales_share_one_tuning (test_nvfp4_kernels.py:209-223).
    • Fix:
      • Parametrize the invalid-scale test over both ops. It runs on CPU, because both ops validate before any kernel launch.
      • In test_gated_linear_auto_and_autotuned_prefill, build the weight with act_scale=0.002 and add weight.act_per_tensor_scale to args. w4a4_gated_reference already applies it.
    • Fix this →
  • No test exports or lowers the F.linear + SiLU fallback in _gated_linear (nvfp4_dispatch.py:249-260).

    • Who compiles it. Every GPU below SM120 compiles this path, including H100 and B200. So does w4a16 mode on any GPU.
    • What reaches it today. Only the eager tests (test_gated_linear_cpu_fallback, test_gated_linear_weight_only) and two bare-FakeTensorMode routing cases (test_nvfp4_gate_up.py:110, 112). The CPU export test patches _has_native_fp4 to True (364), and the PTE tests are @NATIVE_FP4 (381).
    • What is untested. Under export, this path calls F.linear on the subclass from inside the subclass's own dispatch handler, and no test runs that through torch.export. The risk is low, because _linear is registered for both F.linear and aten.linear (nvfp4_dispatch.py:288-289).
    • Fix: copy test_gated_linear_auto_export_traces_the_auto_op, but patch _has_native_fp4 to return False. Record nvfp4_quantized_gemm.nvfp4_w4a16, and assert after run_decompositions() that it was the only op recorded. This runs on CPU in CI.
    • Fix this →

Recommendation

Approve

Neither finding blocks approval. The test gap you deferred in round 5 is still open: no test reaches a second N tile or the small-M configs of _gate_up, and GateUp still has 70 rows.

Review steps
  • Gathered context:
    • the diff against origin/gh/gasoonjia/218/base (5 files, +909/−1);
    • the PR description;
    • the discussion from rounds 1–7, including your round-7 replies.
  • Ran three independent reviewers over all five files. None reported a kernel, routing, or validation bug.
  • Consolidated their findings. For each one, I re-read the cited code in launch_params.py, nvfp4_quantized_gemm.py, nvfp4_dispatch.py, nvfp4_gated_gemm.py and the three NVFP4 test files.
  • Dropped after fact-checking:
    • Even N not checked at op entry (raised by all three reviewers). Every path raises a clear even-N ValueError before it returns. The only cost is one wasted eager GEMM.
    • Assert the parameter signature on the decomposed program. This contradicts the round-7 request, and Dynamo captures any anonymous constants before decomposition.
    • The CPU export test stubs the op, and the auto PTE reference follows the tuner's pick. Both follow the round-4 design.
    • Already settled in earlier rounds:
      • lazy kernel imports;
      • SiLU missing from the op name;
      • "fused" in the docstring;
      • duplication with _prefill and _linear;
      • ValueError vs RuntimeError;
      • libdevice on ROCm.
    • Untested minor branches. Low value.
    • Acknowledged limits:
      • decode-size BF16 runs the prefill kernels;
      • FP16 is excluded;
      • CI has no SM120 GPU.
  • This runner has no GPU, so I did not run any tests.
  • CI had no failures when I checked: 11 runs passed and 13 were still pending.

This branch was successfully deployed

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