Skip to content

[executorch][cuda] NVFP4: per-weight activation dtype, MXFP8 attention projections - #25436

Open
Gasoonjia wants to merge 10 commits into
gh/Gasoonjia/143/basefrom
gh/Gasoonjia/143/head
Open

Gasoonjia wants to merge 10 commits into
gh/Gasoonjia/143/basefrom
gh/Gasoonjia/143/head

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

CudaNVFP4Tensor gets an act_dtype attribute (serialized with the tensor) that selects how a linear treats its activations:

  • fp4 (default): unchanged -- W4A4 where FP4 tensor cores exist, timed against W4A16 per shape.
  • mxfp8: prefill with K % 32 == 0 that the decode GEMV and the small-M buckets do not serve runs MXFP8 x MXFP8 with the weights still stored NVFP4 (triton::nvfp4_mxfp8; "MXFP8" rather than "W4A8", which elsewhere in the backend means INT8 activations). Decode never quantizes activations to FP4: M = 1 runs the W4A16 GEMV (on GPUs without FP4 conversion nvfp4_auto_decode times the INT8-activation W4A8 GEMV against it), and M = 2..16 (static, or dynamic bounded by 16) runs the small-M bucket ops nvfp4_small_m_gemm_m{2,4,8,16} with weight_only=True (only the BF16-activation rows and w4a16 kernels), except decode-size M where the decode GEMVs serve it (with native FP4, and for mxfp8 under w4a8).
  • bf16: weight-only, W4A16 on every path.

MXFP8 numerics (nvfp4_mxfp8.py):

  • Activations: E4M3 elements with one UE8M0 scale per 32 elements along K, exponent ceil(log2(amax / 448)), so a block maximum never saturates. Note that the OCP MX specification and torchao default to floor(log2(amax)) - 8, which can clip the block maximum.
  • Weights: each tile is converted in registers -- E2M1 codes decode exactly to FP16 (cvt.rn.f16x2.e2m1x2), each K32 group gets e = ceil(log2(6 * max|s16 pair| / 448)) (magnitude, so negative scale bytes convert correctly), each element becomes code * (s16 * 2^-e) in FP16 (exact) and is rounded once, to nearest even, to E4M3. Products with at most 4 significant bits stay exact (unless the pair's scales differ by about 2^10 or more and the smaller block lands in the E4M3 subnormal range); the rest move by at most half an E4M3 ulp. Inexact conversions are common: any code of magnitude 1.5, 3 or 6 times a normal K16 scale byte whose mantissa is 1, 3, 5, 6 or 7 (for a subnormal byte, mantissa 7 only).
  • tl.dot_scaled e4m3 x e4m3 with ue8m0 scales, FP32 accumulation, per-tensor scale in the epilogue.

Hardware: the native kernel needs FP4 conversion and block-scaled FP8 MMA (sm_120), and the op raises without it. Elsewhere mxfp8 prefill uses BF16 activations (W4A16, higher precision and faster); ET_CUDA_NVFP4_MXFP8_EMULATE=1 instead emulates it on the dequant + BF16 GEMM path (nvfp4_mxfp8_emu.py): activation QDQ and weight dequant onto exactly the native kernel's MXFP8 grids, BF16 GEMM with FP32 accumulation, so the result differs from the native kernel by accumulation order and output rounding; NaN activations stay NaN as in the native kernel, and since it dequantizes, ET_CUDA_NVFP4_PREFILL_IMPL=kernel turns it off.

Policies: marked weights follow ET_CUDA_NVFP4_ACT=w4a16 (no MXFP8 or INT8 activations), w4a8 (INT8-activation decode for mxfp8, which raises on ROCm like fp4 weights; MXFP8 prefill stays), ET_CUDA_NVFP4_PREFILL_IMPL (kernel forbids dequant and runs nvfp4_w4a16 where MXFP8 does not apply, dequant skips MXFP8) and ET_CUDA_NVFP4_SMALL_M, never take W4A4 (w4a4 means auto for them), and keep the activation dtype under the FP32 prefill output policy (FP32 activations then run in BF16 instead of the dense FP32 fallback); under w4a8 they keep the weight-only small-M buckets (above decode size for mxfp8); the nvfp4_dispatch docstring states this, and the --nvfp4-attn-act help and act_dtype docstrings point to it. Prefill that misses the MXFP8 path follows ET_CUDA_NVFP4_PREFILL_IMPL exactly as fp4 weights under w4a16 do: in auto, the fused W4A16 kernel with native FP4 or for static M <= 64, dequant + matmul otherwise (RTX 5090, M = 512, 52 layers: fused W4A16 141.5 ms vs dequant + matmul 168.1 ms per forward). ET_CUDA_NVFP4_MXFP8_EMULATE=1 also runs decode on the W4A16 GEMV, so it reproduces SM120 numerics for the marked weights end to end (other weights still differ: SM120 auto may time W4A4 for them).

Muse Glimmer: export_solo.py --nvfp4-attn-act {fp4,mxfp8,bf16} sets act_dtype on the attention projections (fused qko/qkv or q/k/og, v, o) and fails if there are none; FFN, embedding and lm_head keep their paths.

Authored with Claude Code.

Differential Revision: D132444851

@pytorch-bot

pytorch-bot Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Cancelled Job, 2 Pending

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

NEW FAILURE - The following job has failed:

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

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

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

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


Request Changes: CI never runs the new sm_120 MXFP8 kernel and skips the emulation tests on the sm_89+ GPUs that use emulation, marked weights silently ignore the documented ET_CUDA_NVFP4_* policies, and the "bit-identical" MXFP8 emulation rounds its output twice.

Detailed review of #25436

Summary

This PR adds a per-weight act_dtype (fp4 / mxfp8 / bf16) to CudaNVFP4Tensor, an MXFP8 × MXFP8 prefill kernel for sm_120 with opt-in emulation on other GPUs, and a --nvfp4-attn-act export flag that marks the muse-glimmer attention projections.

There are three main problems:

  • The tests that CI can run cover very little of the new kernels.
  • act_dtype silently overrides the existing env-var policies.
  • The emulation does not do what its documentation says.

These findings come from reading the code. No kernels or tests were run.

Code Quality

  • mxfp8 weights with K % 32 != 0 fail export on sm_120, but the emulation accepts them.

    • CudaNVFP4Tensor accepts any K divisible by 16.
    • On native GPUs, _bf16_act_linear always sends mxfp8 prefill to nvfp4_w4a8 (nvfp4_dispatch.py:395-399). That op raises ValueError for such K (nvfp4_w4a8.py:248-249) instead of falling back to _dequant_linear.
    • The emulation kernels mask the partial group and run, so the same model exports on other GPUs and fails on sm_120.
    • nvfp4_w4a8 also skips the _check_operands(x, qdata, scale, per_tensor_scale) call that every sibling op makes (nvfp4_dispatch.py:131,155,207, nvfp4_quantized_gemm.py:643,1001,1207, nvfp4_gated_gemm.py:232). A direct torch.ops.triton.nvfp4_w4a8 call with mismatched shapes can therefore read out of bounds instead of raising.

    Fix this →

  • mark_attention_act can silently do nothing, and it probes attributes with getattr.

    • export_solo.py:159 ignores the returned count. If the attention projections are not CudaNVFP4Tensor when it runs, --nvfp4-attn-act mxfp8 exports an unchanged model and only prints 0 linears.
    • The getattr(attn, name, None) / getattr(linear, "weight", None) probing over candidate names (nvfp4_attn_act.py:43-45) is the dynamic-getattr pattern that CLAUDE.md rules out.
    • Suggested fix: loop over layer.self_attn.named_children(), keep the names in ATTN_PROJECTIONS whose weight is a CudaNVFP4Tensor, and raise when nothing was marked.
    • test_nvfp4_attn_act_marking.py only covers the fused qko/v/o layout.

    Fix this →

  • Two small cleanups in nvfp4_dispatch.py. Fix this →

    • Line 379 hard-codes 4, while the fp4 branch uses the imported NVFP4_DECODE_MAX_ROWS (:445).
    • _mxfp8_emulated_linear re-imports chunked_dequant_linear (:332-334), although the module already imports it at the top (:35-38).

Testing

  • CI never runs the sm_120 kernel, and the emulation tests skip most of the GPUs that use emulation.

    • Buck pins test_nvfp4_attn_act to subplatform = "A100" (sm_80), and the OSS CUDA job runs on A10G (sm_86). TestNative is the only coverage of _w4a8_mx, _act_mxfp8 and the cvt.rn.f16x2.e2m1x2 asm, so none of them ever runs in CI.
    • TestEmulated skips at get_device_capability() >= (8, 9) (test_nvfp4_attn_act.py:406). Dispatch, however, emulates whenever _has_native_fp4() is false, which includes sm_89–sm_110 (L4, H100, B200). The ARCH >= 89 branches of _e4m3_value and _dequant_mxfp8_kernel are therefore never tested.
    • The emu module docstring gives the same wrong boundary: "on GPUs without FP8 tensor cores" (nvfp4_mxfp8_emu.py:5).
    • Even on sm_120, the native activation quantizer W8.quantize_activation_mxfp8 (a hardware .to(tl.float8e4nv) cast) is never bit-compared with act_mxfp8_reference, which is documented as its mirror (:118). Only the emulation's software encoder is compared (:427-431). So nothing checks the claimed bit-identity between the two activation paths.
    • Suggested fix: run the kernel-level emulation tests on every CUDA GPU, gate only the dispatch and export expectations on not native_fp4(), and add the native torch.equal check.

    Fix this →

  • The UE8M0 boundary cases collapse before they reach the kernel. test_activation_qdq_bit_identical builds the neighbours of 448 * 2**j with FP32 torch.nextafter (:421-425), then casts x to BF16 (:426). The cast rounds both one-FP32-ulp neighbours back to 448 * 2**j, so the boundary cases that the comment describes are never tested. Build the neighbours in BF16 instead, for example by adding and subtracting 1 on the int16 view of b.to(torch.bfloat16), which gives 446 * 2**j and 450 * 2**j. Fix this →

  • The configuration this PR targets is not tested, and neither are tiles that don't divide N or K.

    • Every test weight has a scalar per_tensor_scale: make_weight (:69), stress_weight (:94), and the fused weight at :202-204, which fuses two identical shards.
    • The fused qko/qkv projections built by fuse_along_output (checkpoint_loader.py:375) get per-row scales whenever the shard scales differ. That case uses the ROW_PTS path of _w4a8_mx (nvfp4_w4a8.py:218-219) and the row_pts branch of _mxfp8_emulated_linear (nvfp4_dispatch.py:348), and no test exercises either.
    • unit_scale=True (nvfp4_dispatch.py:346) is never tested.
    • FP16 activations, which _linear accepts (:418), are never tested.
    • Every GEMM and weight-conversion test uses N and K that are multiples of 256, so the N/K tail masking in _w4a8_mx and _dequant_mxfp8_kernel never runs.

    Fix this →

  • The dispatch tests depend on the caller's environment.

    • The expected dispatch depends on ET_CUDA_NVFP4_ACT, _SOFT_W4A8, _SMALL_M, _PREFILL_IMPL and _MXFP8_EMULATE. For example, TestDispatchDecisions expects dequant at M=64, but gets mxfp8_emulated if ET_CUDA_NVFP4_MXFP8_EMULATE=1 is exported.
    • Only TestEmulated patches the environment.
    • test_nvfp4_kernels.py:42-45 and test_nvfp4_gate_up.py:54-57 reset the policy variables with autouse fixtures. Do the same here, using mock.patch.dict(os.environ) in setUp, since these are unittest.TestCase classes.

    Fix this →

API Design

  • Marked weights silently bypass the policies documented in the nvfp4_dispatch.py module docstring, and the precedence is not written down anywhere.

    • ET_CUDA_NVFP4_PREFILL_OUTPUT=fp32 is ignored (output_dtype = None if bf16_act, :417).
      • BF16 inputs return BF16.
      • FP32 inputs fail allowed_dtype (:418-420) and take the dense FP32 dequant + FP32 F.linear fallback (:421-428), with no MXFP8 at all.
    • ET_CUDA_NVFP4_ACT=w4a16 ("forces weight-only") does not stop INT8 activations.
      • For fp4 weights, the soft W4A8 decode requires requested_mode == "auto" (:486). The mxfp8 branch (:380-384) has no such check.
      • As a result, under w4a16 the attention projections can decode with lower-precision activations than the FFN.
    • ET_CUDA_NVFP4_PREFILL_IMPL is never consulted.
      • dequant cannot turn off nvfp4_w4a8 on sm_120.
      • bf16 weights always take _dequant_linear (:402), even where auto or kernel picks the fused kernels for fp4 weights.
    • ET_CUDA_NVFP4_SMALL_M_MODES is ignored. The candidate modes are hard-coded to ("rows", "w4a16") (nvfp4_small_m_gemm.py:326). Intersecting them with _enabled_modes() would honor the setting.

    Either honor these policies for marked weights, or document in the module docstring which of them act_dtype overrides.

  • Without native FP4, --nvfp4-attn-act mxfp8 changes nothing for prefill or M=1 decode.

    • With the default ET_CUDA_NVFP4_MXFP8_EMULATE=0, mxfp8 prefill takes _dequant_linear (nvfp4_dispatch.py:402) and M=1 decode takes nvfp4_auto_decode_soft (:380-391). An fp4 weight already gets these same ops on those GPUs (:484-506).
    • The CLI help (export_solo.py:1312-1315) promises "prefill as MXFP8 x MXFP8 … and decode as W4A16", and export reports act_dtype=mxfp8: N linears.
    • Suggested fix: warn or raise in mark_attention_act / export_solo when mxfp8 is requested on a GPU without native FP4, and state the fallback in the help text.
  • ET_CUDA_NVFP4_MXFP8_EMULATE=1 is documented as bit-identical, but it is not. The module docstring (nvfp4_dispatch.py:22) and the test docstring (test_nvfp4_attn_act.py:10-11) say "bit-identical MXFP8 emulation", and nvfp4_mxfp8_emu.py:18 says "Only the accumulation order differs". In practice it differs in three more ways:

    • Rounding. The native kernel rounds once, storing acc * pts from FP32 (nvfp4_w4a8.py:222-226). _mxfp8_emulated_linear rounds the GEMM output to BF16, then rounds out.float() * pts a second time (nvfp4_dispatch.py:345-348).
    • FP16 precision. Both emulation ops return BF16 (nvfp4_mxfp8_emu.py:75,154), so FP16 models get BF16-precision outputs where the native kernel returns FP16.
    • Decode. Under EMULATE=1, decode still uses nvfp4_auto_decode_soft with INT8 activations (nvfp4_dispatch.py:380-391), while native uses nvfp4_gemv. test_nvfp4_attn_act.py:466 asserts this behavior.

    Either make the emulation round once (an FP32-output GEMM, then apply pts and cast) and send EMULATE=1 decode to nvfp4_gemv, or describe the mode as an MXFP8-grid emulation that matches native up to accumulation order and output rounding.

Backward Compatibility

  • Low confidence: tensors restored without calling __new__ have no act_dtype.

    • act_dtype is set only in __new__ (nvfp4_tensor.py:131), and the class has no default for it.
    • _linear (nvfp4_dispatch.py:416), _gated_linear (:290) and __tensor_flatten__ now read it unconditionally.
    • The class is registered for torch.load with add_safe_globals (nvfp4_tensor.py:237). If a CudaNVFP4Tensor serialized before this PR is rebuilt by restoring __dict__ without calling __new__, the first F.linear raises AttributeError.
    • I could not confirm that such files exist, or how torchao rebuilds these tensors. Either way, a class attribute act_dtype = "fp4" removes the risk.

    Fix this →

Recommendation

Request Changes

Blocking:

  • The Testing gaps: the sm_89+ emulation skip, the collapsed boundary cases, and the missing per-row per_tensor_scale coverage. CI cannot check the native kernel, so these tests are the only evidence for the PR's numerical claims.
  • A decision on how act_dtype interacts with the existing ET_CUDA_NVFP4_* policies, written into the module docstring.

The other findings can be addressed in this PR or in a follow-up.

Review progress
  • Gather context (diff, CLAUDE.md, checklist)
  • Run independent reviews (3-reviewer panel)
  • Consolidate findings
  • Fact-check findings
  • Post final review

Gasoonjia added a commit that referenced this pull request Nov 23, 2026
…n projections

Pull Request resolved: #25436

`CudaNVFP4Tensor` gets an `act_dtype` attribute (serialized with the tensor) that selects how a linear treats its activations:
- `fp4` (default): unchanged -- W4A4 where FP4 tensor cores exist, timed against W4A16 per shape.
- `mxfp8`: prefill with K % 32 == 0 that the decode GEMV and the small-M buckets do not serve runs MXFP8 x MXFP8 with the weights still stored NVFP4 (`triton::nvfp4_mxfp8`; "MXFP8" rather than "W4A8", which elsewhere in the backend means INT8 activations). Decode never quantizes activations to FP4: M = 1 runs the W4A16 GEMV (on GPUs without FP4 conversion `nvfp4_auto_decode` times the INT8-activation W4A8 GEMV against it), and M = 2..16 (static, or dynamic bounded by 16) runs the small-M bucket ops `nvfp4_small_m_gemm_m{2,4,8,16}` with `weight_only=True` (only the BF16-activation `rows` and `w4a16` kernels), except decode-size M where the decode GEMVs serve it (with native FP4, and for `mxfp8` under `w4a8`).
- `bf16`: weight-only, W4A16 on every path.

MXFP8 numerics (`nvfp4_mxfp8.py`):
- Activations: E4M3 elements with one UE8M0 scale per 32 elements along K, exponent `ceil(log2(amax / 448))`, so a block maximum never saturates. Note that the OCP MX specification and torchao default to `floor(log2(amax)) - 8`, which can clip the block maximum.
- Weights: each tile is converted in registers -- E2M1 codes decode exactly to FP16 (`cvt.rn.f16x2.e2m1x2`), each K32 group gets `e = ceil(log2(6 * max|s16 pair| / 448))` (magnitude, so negative scale bytes convert correctly), each element becomes `code * (s16 * 2^-e)` in FP16 (exact) and is rounded once, to nearest even, to E4M3. Products with at most 4 significant bits stay exact (unless the pair's scales differ by about 2^10 or more and the smaller block lands in the E4M3 subnormal range); the rest move by at most half an E4M3 ulp. Inexact conversions are common: any code of magnitude 1.5, 3 or 6 times a normal K16 scale byte whose mantissa is 1, 3, 5, 6 or 7 (for a subnormal byte, mantissa 7 only).
- `tl.dot_scaled` e4m3 x e4m3 with ue8m0 scales, FP32 accumulation, per-tensor scale in the epilogue.

Hardware: the native kernel needs FP4 conversion and block-scaled FP8 MMA (sm_120), and the op raises without it. Elsewhere `mxfp8` prefill uses BF16 activations (W4A16, higher precision and faster); `ET_CUDA_NVFP4_MXFP8_EMULATE=1` instead emulates it on the dequant + BF16 GEMM path (`nvfp4_mxfp8_emu.py`): activation QDQ and weight dequant onto exactly the native kernel's MXFP8 grids, BF16 GEMM with FP32 accumulation, so the result differs from the native kernel by accumulation order and output rounding; NaN activations stay NaN as in the native kernel, and since it dequantizes, `ET_CUDA_NVFP4_PREFILL_IMPL=kernel` turns it off.

Policies: marked weights follow `ET_CUDA_NVFP4_ACT=w4a16` (no MXFP8 or INT8 activations), `w4a8` (INT8-activation decode for mxfp8, which raises on ROCm like `fp4` weights; MXFP8 prefill stays), `ET_CUDA_NVFP4_PREFILL_IMPL` (`kernel` forbids dequant and runs `nvfp4_w4a16` where MXFP8 does not apply, `dequant` skips MXFP8) and `ET_CUDA_NVFP4_SMALL_M`, never take W4A4 (`w4a4` means `auto` for them), and keep the activation dtype under the FP32 prefill output policy (FP32 activations then run in BF16 instead of the dense FP32 fallback); under `w4a8` they keep the weight-only small-M buckets (above decode size for `mxfp8`); the `nvfp4_dispatch` docstring states this, and the `--nvfp4-attn-act` help and `act_dtype` docstrings point to it. Prefill that misses the MXFP8 path follows `ET_CUDA_NVFP4_PREFILL_IMPL` exactly as `fp4` weights under `w4a16` do: in `auto`, the fused W4A16 kernel with native FP4 or for static M <= 64, dequant + matmul otherwise (RTX 5090, M = 512, 52 layers: fused W4A16 141.5 ms vs dequant + matmul 168.1 ms per forward). `ET_CUDA_NVFP4_MXFP8_EMULATE=1` also runs decode on the W4A16 GEMV, so it reproduces SM120 numerics for the marked weights end to end (other weights still differ: SM120 `auto` may time W4A4 for them).

Muse Glimmer: `export_solo.py --nvfp4-attn-act {fp4,mxfp8,bf16}` sets `act_dtype` on the attention projections (fused qko/qkv or q/k/og, v, o) and fails if there are none; FFN, embedding and lm_head keep their paths.

Authored with Claude Code.

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

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

Copy link
Copy Markdown
Contributor Author

Thanks.

  • PREFILL_IMPL=kernel under the emulation: the code now matches the docs. The emulation dequantizes, so kernel turns it off and large-M mxfp8 prefill runs nvfp4_w4a16; native MXFP8 is unaffected. The docstring says so, and a non-native test_policies case pins it.
  • The exactness wording now reads: normal scale bytes with mantissa 1, 3, 5, 6 or 7; subnormal bytes only with mantissa 7.
  • NaN activations: the emulator now matches the native kernel. A NaN element stays NaN (code 0x7F under STORE_CODES) instead of becoming +-448*2^e; both share the same block-exponent computation. New test_activation_qdq_keeps_nan covers it.
  • The commit message is updated for all three.

@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 43m 57s —— View job


PR Review: #25436

Approve. Nothing blocks. Two dispatch docstrings are wrong for marked weights, the M=17 boundary is never asserted, four test gaps from round 6 are still open, the SM120 MXFP8 path at static M 17–64 has not been measured, and nvfp4_mxfp8.py has an int32 offset that could overflow on very large weights.

Detailed review

Summary

The PR does five things:

  • Adds a serialized per-weight act_dtype (fp4/mxfp8/bf16) to CudaNVFP4Tensor.
  • Adds an SM120 MXFP8×MXFP8 prefill kernel that converts NVFP4 weight tiles in registers.
  • Adds an MXFP8-grid emulation for GPUs older than SM120.
  • Changes dispatch so marked weights never take FP4 activations.
  • Adds a Muse Glimmer --nvfp4-attn-act flag.

Nothing blocks. I reviewed the code without running it: no SM120 hardware was available, and nothing was executed.

Code Quality

  • nvfp4_mxfp8.py:75,100: _mxfp8_gemm widens m to int64 (m64, line 203) but not n.

    • That leaves the weight offsets n * (K // 16) and n * (K // 2) in int32. They wrap once N·K/2 reaches about 2^31, for example on a 262144 × 16384 LM head marked mxfp8.
    • The sibling kernels widen n (nvfp4_quantized_gemm.py:539,1036), and so does the emulator (nvfp4_mxfp8_emu.py:125,128,152).
    • Today's attention projections are far below the limit, so nothing overflows yet.

    Fix this →

Testing

  • test_nvfp4_attn_act.py:330-352: test_mxfp8_never_w4a4 loops over M=17, the first M above the small-M buckets, but 17 is not in expected.

    • So the M=17 kernel is never checked. It should be nvfp4_mxfp8 with native FP4 and nvfp4_w4a16 without.
    • If the bucket boundary moved, the test would still pass.

    Fix this →

  • Still open from round 6:

    • FP32-policy cases (436-446): they check op names only.
      • The recorder returns x.new_zeros in the input dtype (270-272), so the output dtype is never checked.
      • Removing the BF16 cast at nvfp4_dispatch.py:557 would still pass, and so would removing the .to(flat.dtype) on line 558.
    • act_dtype save/load: no torch.save/torch.load(weights_only=True) round trip covers it.
      • That includes the class-default path for pickles restored without __new__ (nvfp4_tensor.py:86-87).
      • TestAttribute only exercises __tensor_flatten__/__tensor_unflatten__ (223-224). test_nvfp4_tensor.py:146-148 already has the save/load pattern to copy.
    • UE8M0 oracle: both activation-quantizer checks (633-642, 695-717) get their UE8M0 bytes from the test's _ceil_log2 (129-134), which copies the kernel's bit trick.
      • A wrong exponent rule would therefore agree with itself. Only the weight path is checked against an independent ceil(log2) reference (MX.nvfp4_to_mxfp8_weight_reference, 738-739).
      • Fix: check against an FP64 ceil(log2(amax/448)) over every positive finite BF16 block max.
    • TestNativeCompiles.setUp (557-563): it skips on any exception from the probe.
      • The probe calls private Triton APIs (ASTSource, GPUTarget, JITFunction; 533-550). A Triton update that breaks the helper would silently skip the only sm_120 coverage CI has (the A10G system shard, cuda.yml:647).

    Fix this →

API Design

  • nvfp4_small_m_gemm.py:21-24: this PR adds "a weight whose act_dtype is not fp4" to the weight-only callers, but the same parenthetical still says "a forced w4a4 never reaches these ops".

    • That clause is wrong for exactly those weights. _bf16_act_linear maps w4a4 to auto (nvfp4_dispatch.py:485), and the small-M buckets then run weight-only (494-498).
    • That matches the module docstring (nvfp4_dispatch.py:45-46,51). Limit the clause to fp4 weights.

    Fix this →

  • ROCm with w4a8: the module docstring (nvfp4_dispatch.py:14-17) says w4a8 "raises on ROCm", but only some weights raise:

    • fp4 weights raise at any M (_linear:570-571).
    • mxfp8 weights raise only at static decode-size M (_bf16_act_linear:499-501). At prefill-size M they run BF16 activations without raising.
    • bf16 weights never raise.
    • Only the decode case is tested (test_nvfp4_attn_act.py:458-460).

    Either raise for mxfp8 weights at every M (bf16 weights ignore the mode, so they need not raise), or describe the narrower rule in the w4a8 bullet and the marked-weight paragraph (45-61).

    Fix this →

Performance

  • SM120 path at static M 17–64 is untimed (low confidence; not measured, since no SM120 GPU was available).

    • _bf16_act_linear (nvfp4_dispatch.py:515-519) sends every mxfp8 linear above the small-M buckets straight to nvfp4_mxfp8 without timing. fp4 weights at the same M get the timed nvfp4_auto_prefill.
    • _CONFIGS (nvfp4_mxfp8.py:143-162) has no tile smaller than BM=64 or BN=64, and the kernel has no split-K (K loop at 207, grid at 266-267). With M ≤ 64 and N = 512–1024 that is at most 8–16 CTAs on a 170-SM RTX 5090.
    • nvfp4_w4a16 autotunes split-K (nvfp4_quantized_gemm.py:34,1068-1111). Where W4A16 is faster, MXFP8 loses on both speed and precision, the same argument the docstring makes for pre-SM120 GPUs (lines 55-56).

    Please measure nvfp4_mxfp8 against nvfp4_w4a16 at M 17–64. If W4A16 wins, add a row threshold or time the two.

    Fix this →

Recommendation

Approve. None of these findings breaks behavior on shapes that can occur today. The docstring fixes and the M=17 assertion are one-line changes. The SM120 measurement and the round-6 test items can come in a follow-up.


Todo

  • Gather context (diff against gh/Gasoonjia/143/base, PR description, prior rounds)
  • Three independent reviewers (dispatch-first, kernels-first, tests-first)
  • Consolidate and dedupe findings
  • Fact-check each finding against the code
  • Post final review

Gasoonjia added a commit that referenced this pull request Nov 23, 2026
…n projections

Pull Request resolved: #25436

`CudaNVFP4Tensor` gets an `act_dtype` attribute (serialized with the tensor) that selects how a linear treats its activations:
- `fp4` (default): unchanged -- W4A4 where FP4 tensor cores exist, timed against W4A16 per shape.
- `mxfp8`: prefill with K % 32 == 0 that the decode GEMV and the small-M buckets do not serve runs MXFP8 x MXFP8 with the weights still stored NVFP4 (`triton::nvfp4_mxfp8`; "MXFP8" rather than "W4A8", which elsewhere in the backend means INT8 activations). Decode never quantizes activations to FP4: M = 1 runs the W4A16 GEMV (on GPUs without FP4 conversion `nvfp4_auto_decode` times the INT8-activation W4A8 GEMV against it), and M = 2..16 (static, or dynamic bounded by 16) runs the small-M bucket ops `nvfp4_small_m_gemm_m{2,4,8,16}` with `weight_only=True` (only the BF16-activation `rows` and `w4a16` kernels), except decode-size M where the decode GEMVs serve it (with native FP4, and for `mxfp8` under `w4a8`).
- `bf16`: weight-only, W4A16 on every path.

MXFP8 numerics (`nvfp4_mxfp8.py`):
- Activations: E4M3 elements with one UE8M0 scale per 32 elements along K, exponent `ceil(log2(amax / 448))`, so a block maximum never saturates. Note that the OCP MX specification and torchao default to `floor(log2(amax)) - 8`, which can clip the block maximum.
- Weights: each tile is converted in registers -- E2M1 codes decode exactly to FP16 (`cvt.rn.f16x2.e2m1x2`), each K32 group gets `e = ceil(log2(6 * max|s16 pair| / 448))` (magnitude, so negative scale bytes convert correctly), each element becomes `code * (s16 * 2^-e)` in FP16 (exact) and is rounded once, to nearest even, to E4M3. Products with at most 4 significant bits stay exact (unless the pair's scales differ by about 2^10 or more and the smaller block lands in the E4M3 subnormal range); the rest move by at most half an E4M3 ulp. Inexact conversions are common: any code of magnitude 1.5, 3 or 6 times a normal K16 scale byte whose mantissa is 1, 3, 5, 6 or 7 (for a subnormal byte, mantissa 7 only).
- `tl.dot_scaled` e4m3 x e4m3 with ue8m0 scales, FP32 accumulation, per-tensor scale in the epilogue.

Hardware: the native kernel needs FP4 conversion and block-scaled FP8 MMA (sm_120), and the op raises without it. Elsewhere `mxfp8` prefill uses BF16 activations (W4A16, higher precision and faster); `ET_CUDA_NVFP4_MXFP8_EMULATE=1` instead emulates it on the dequant + BF16 GEMM path (`nvfp4_mxfp8_emu.py`): activation QDQ and weight dequant onto exactly the native kernel's MXFP8 grids, BF16 GEMM with FP32 accumulation, so the result differs from the native kernel by accumulation order and output rounding; NaN activations stay NaN as in the native kernel, and since it dequantizes, `ET_CUDA_NVFP4_PREFILL_IMPL=kernel` turns it off.

Policies: marked weights follow `ET_CUDA_NVFP4_ACT=w4a16` (no MXFP8 or INT8 activations), `w4a8` (INT8-activation decode for mxfp8, which raises on ROCm like `fp4` weights; MXFP8 prefill stays), `ET_CUDA_NVFP4_PREFILL_IMPL` (`kernel` forbids dequant and runs `nvfp4_w4a16` where MXFP8 does not apply, `dequant` skips MXFP8) and `ET_CUDA_NVFP4_SMALL_M`, never take W4A4 (`w4a4` means `auto` for them), and keep the activation dtype under the FP32 prefill output policy (FP32 activations then run in BF16 instead of the dense FP32 fallback); under `w4a8` they keep the weight-only small-M buckets (above decode size for `mxfp8`); the `nvfp4_dispatch` docstring states this, and the `--nvfp4-attn-act` help and `act_dtype` docstrings point to it. Prefill that misses the MXFP8 path follows `ET_CUDA_NVFP4_PREFILL_IMPL` exactly as `fp4` weights under `w4a16` do: in `auto`, the fused W4A16 kernel with native FP4 or for static M <= 64, dequant + matmul otherwise (RTX 5090, M = 512, 52 layers: fused W4A16 141.5 ms vs dequant + matmul 168.1 ms per forward). `ET_CUDA_NVFP4_MXFP8_EMULATE=1` also runs decode on the W4A16 GEMV, so it reproduces SM120 numerics for the marked weights end to end (other weights still differ: SM120 `auto` may time W4A4 for them).

Muse Glimmer: `export_solo.py --nvfp4-attn-act {fp4,mxfp8,bf16}` sets `act_dtype` on the attention projections (fused qko/qkv or q/k/og, v, o) and fails if there are none; FFN, embedding and lm_head keep their paths.

Authored with Claude Code.

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

**NOTE FOR REVIEWERS**: This PR has internal Meta-specific changes or comments, please review them on [Phabricator](https://our.internmc.facebook.com/intern/diff/D132444851/)!
ghstack-source-id: 481200154
@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 42m 38s —— View job


PR Review: #25436

Approve. Nothing blocks landing. The main new issue is that test_nvfp4_attn_act.py doesn't use the sweep(full, quick) split described in the latest comment, so its heaviest cases still run on every PR in the A10G system shard. The rest are doc mismatches and test gaps, several of them still open from round 7.

Detailed review

Summary

This PR adds a per-weight act_dtype (fp4 / mxfp8 / bf16) to CudaNVFP4Tensor:

  • Weights marked mxfp8 or bf16 never take FP4 activations.
  • mxfp8 prefill runs a new SM120 MXFP8×MXFP8 Triton kernel. An opt-in emulation covers GPUs before SM120.
  • export_solo --nvfp4-attn-act marks the Muse Glimmer attention projections.

All 11 changed files were reviewed. This was a static review only: running Python needed approval and no GPU was available, so nothing was executed.

Code Quality

  • int32 weight offsets. backends/cuda/triton/kernels/nvfp4_mxfp8.py:75,100 compute the weight offsets in int32 (n[:, None] * (K // 16) and n[:, None] * (K // 2)).
    • m is widened to int64 (203), and the emulation widens n (nvfp4_mxfp8_emu.py:125,128,152).
    • These only overflow past a 2 GiB packed weight, but with_act_dtype accepts any weight.
    • Still open from round 7. Fix this →
  • Misleading names. bf16_act (nvfp4_dispatch.py:541) and _bf16_act_linear (476) also send mxfp8 weights to MXFP8 and INT8 (W4A8) activations.
    • So elif bf16_act: (555) reads as if it were BF16-only.
    • A name like no_fp4_act would match the docstring ("never go below 8 bits"). Fix this →
  • Late failure for --nvfp4-attn-act. _validate_nvfp4_args checks --nvfp4-attn-act only against --backend (examples/models/muse-glimmer/export/export_solo.py:1181-1182).
    • On CUDA, only --gguf loads NVFP4 weights (1401-1413).
    • Without --gguf, the whole model loads before mark_attention_act raises "No NVFP4 attention projection…" (nvfp4_attn_act.py:52-53).
    • Fix: require --gguf, as --nvfp4-static-act already does (1179-1180). Fix this →

Infrastructure

  • backends/cuda/tests/test_nvfp4_attn_act.py doesn't use sweep(full, quick). The latest comment says this PR's tests now run representative cases by default via sweep in nvfp4_test_utils. This file never imports it (15-35).
    • test_nvfp4_kernels.py, test_nvfp4_fusion.py, test_nvfp4_small_m_gemm.py and others do import it.
    • Its Buck target (targets.bzl:847-868) has no :nvfp4_test_utils dep.
    • The file is not in KERNEL_TESTS (cuda.yml:538-559), so all of it runs on every PR in the A10G unittest-cuda (system) shard. That is the job the comment says hit the 2-hour limit.
    • The costliest cases:
      • test_every_gemm_config_compiles (572-590) runs 13 offline sm_120 compiles, plus the activation-quantizer compile (565-570).
      • test_weight_conversion_bit_identical (728-739) checks 6656×4096 and 4096×4096 weights against two references.
    • If the update just wasn't pushed to this PR, pushing it resolves this. Fix this →

Testing

  • No test fails if the w4a4 → auto mapping is removed. Deleting nvfp4_dispatch.py:485 would still pass test_policies. Its only w4a4 case (395: mxfp8, M 64, native) reaches nvfp4_mxfp8 either way. Two cases would catch the deletion:
    • mxfp8, M 1, non-native → nvfp4_auto_decode (nvfp4_gemv without the mapping).
    • bf16, M 4096, non-native → dequant (nvfp4_w4a16 without it, because _dequant_prefill returns False for w4a4 at 296-301).
  • test_marked_gated_weight_never_w4a4 (448-460) mixes in unrelated checks. It also asserts the ET_CUDA_NVFP4_MXFP8_EMULATE=on ValueError and the ROCm w4a8 RuntimeError. Both go through plain F.linear, so a regression there is reported under a gated-weight test name. Fix this →
  • Still open from round 7. Fix this →
    • test_mxfp8_never_w4a4 dispatches M=17 (337) but never asserts which kernel it reaches.
    • The FP32-policy cases (436-446) check op names only. The recorder returns zeros in the BF16 input dtype (269-272), so dropping .to(flat.dtype) at nvfp4_dispatch.py:558 would still pass.
    • test_restored_without_new_defaults_to_fp4 (240-244) deletes the attribute instead of doing a torch.save / torch.load round trip.
    • The reference _ceil_log2 / _pow2 (129-138) copy the kernel's bit trick, so the UE8M0 oracle isn't independent.
    • TestNativeCompiles.setUp (560-563) skips on any exception. Drift in the private Triton APIs used by compile_for_sm120 (533-550) would then silently remove CI's only sm_120 coverage.

API Design

  • Small-M docstring is wrong for marked weights. backends/cuda/triton/kernels/nvfp4_small_m_gemm.py:21-24 says "a forced w4a4 never reaches these ops".
    • For marked weights it does: _bf16_act_linear maps w4a4 to auto (nvfp4_dispatch.py:485), and M 2..16 then take the buckets weight-only (494-498).
    • Still open from round 7. Fix this →
  • w4a8 raises on ROCm only in some cases for marked weights. The module docstring (nvfp4_dispatch.py:14-16) says w4a8 "raises on ROCm", and fp4 weights do raise at any M (570-571). For marked weights:
    • _bf16_act_linear raises only for mxfp8 at static M ≤ 4 (499-501).
    • mxfp8 M 5..16 and mxfp8 prefill run without raising.
    • bf16 weights never raise.
    • Fix: raise up front in _bf16_act_linear for mode == "w4a8" on HIP, so one rule covers every weight. Fix this →
  • README not updated. The "NVFP4 GGUF on CUDA" section (examples/models/muse-glimmer/README.md:404-441) is the user-facing description of these flags.
    • It mentions neither --nvfp4-attn-act nor ET_CUDA_NVFP4_MXFP8_EMULATE.
    • Its statement that "w4a4 forces NVFP4 activations" (421) no longer holds for marked attention projections.
    • It doesn't say that the new flag exists only in export_solo, as it does for --nvfp4-static-act (427). Fix this →
  • Emulation accuracy claim (low confidence).
    • nvfp4_mxfp8_emu.py:17 says the emulation's BF16 GEMM has "FP32 accumulation".
    • Lines 19-21 and nvfp4_dispatch.py:57-58 then limit the gap from the native kernel to "accumulation order and output rounding".
    • The GEMM is a plain BF16 F.linear (nvfp4_dispatch.py:421). With torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction at its default (True), cuBLAS may reduce split-K partial sums at reduced precision. Fix this →

Performance

  • MXFP8 is not timed at static M 17..64 (low confidence, still open from round 7).
    • On SM120, mxfp8 weights at those M run nvfp4_mxfp8 without timing (nvfp4_dispatch.py:515-519). That kernel adds an activation-quantize pass and converts the weights in registers.
    • fp4 weights at the same M get nvfp4_auto_prefill's timing against W4A16.
    • W4A16 is also more accurate, so if it is faster there, the marked layers lose on both speed and accuracy.
    • Either time the two, or record the measurement in the docstring.

Recommendation

Approve. Nothing here blocks landing. The missing sweep split is worth fixing first, because the system shard has already hit its time limit on this stack. The other findings are doc mismatches and test gaps.

  • Gather context (diff vs gh/Gasoonjia/143/base, prior rounds, author replies)
  • Run independent reviews (three reviewers)
  • Consolidate findings
  • Fact-check findings
  • Post final review

@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Done. test_nvfp4_attn_act.py now uses the split for its heaviest cases.

  • The offline sm_120 compile builds the first and last MXFP8 GEMM autotune configs by default, and all 13 with EXECUTORCH_CUDA_EXHAUSTIVE_TESTS=1.
  • The emulated weight-conversion test uses a 512x1024 all-scale-bytes stress weight by default. The switch restores the 4096x4096 stress weight and adds the 6656x4096 attention-shaped weight.
  • The Buck target gains :nvfp4_test_utils, and the file joins Add an NVFP4 GGUF solo Muse Glimmer CUDA e2e job #25437's exhaustive job.
  • RTX 5090: at the top, test_nvfp4_attn_act.py, test_nvfp4_soft_decode.py, test_nvfp4_unit_scale.py and test_nvfp4_kernels.py together pass in both modes: 155 passed / 10 skipped in 118 s by default, 225 passed / 10 skipped in 150 s with the switch.

Authored with Claude Code.

This branch was successfully deployed

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