Skip to content

Fix fake metadata for CuTeDSL 32x1 MXFP8 quantization - #4702

Closed
alexsamardzic wants to merge 6 commits into
gh/alexsamardzic/10/headfrom
gh/alexsamardzic/11/head
Closed

alexsamardzic wants to merge 6 commits into
gh/alexsamardzic/10/headfrom
gh/alexsamardzic/11/head

Conversation

@alexsamardzic

@alexsamardzic alexsamardzic commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

(Replaces #4589 due to incorrect ghstack base branch targeting.)

To test:

pytest -q test/prototype/moe_training/test_kernels.py -k "cutedsl and 32x1"

This PR also contains a script to validate/benchmark the CuTeDSL 2D 32x1 dim1 quantization path against the existing CUDA path inside the wgrad workflow; the script is temporary and will be deleted when the torchao._C_mxfp8 extension removed.

[ghstack-poisoned]
@alexsamardzic

alexsamardzic commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@pytorch-bot

pytorch-bot Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/ao/4702

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

❌ 1 Unclassified Failure

As of commit 0c9947a with merge base 9d0c494 (image):

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • Run PT2E GPU Tests (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

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

@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 Aug 5, 2026
@alexsamardzic alexsamardzic added module: training quantize_ api training flow moe labels Aug 5, 2026
@alexsamardzic
alexsamardzic changed the base branch from gh/alexsamardzic/10/head to main August 5, 2026 19:07
@alexsamardzic
alexsamardzic changed the base branch from main to gh/alexsamardzic/10/head August 6, 2026 07:40
Comment thread scripts/validate_wgrad_dim1_cutedsl.py Outdated
@@ -0,0 +1,250 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

split logic to test and benchmarks

@vkuzo

vkuzo commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Claude finished @vkuzo's task in 1m 33s —— View job


Claude Code Review

  • Read the PR diff
  • Review torchao/prototype/moe_training/kernels/mxfp8/quant.py
  • Review scripts/validate_wgrad_dim1_cutedsl.py
  • Post review

I reviewed the fake-metadata fix against the real kernel in cutedsl_quantize_2d_32x1.py. The core fix is correct — the fake op now faithfully mirrors the real op's output metadata.

✅ Correctness of the fake metadata

Field Real kernel (mxfp8_quantize_cutedsl_2d_32x1) Fake (this PR) Match
q_data strides empty_strided((M,K), (1,M)) — column-major empty_strided((m,k), (1,m)) ✅ (was (k,1), i.e. row-major — this was the bug)
q_data dtype float8_e4m3fn float8_e4m3fn ✅
blocked scales flat (ceil_div(K,128)*128 * ceil_div(m_blocks,4)*4,) flat (ceil_div(k,128)*128 * ceil_div(m_blocks,4)*4,) ✅ (product is commutative)
non-blocked scales (K, m_blocks) (k, m_blocks) ✅ (previously the fake had no non-blocked branch at all)
scales dtype float8_e8m0fnu float8_e8m0fnu ✅

The two real problems are addressed: (1) the q_data stride was (k, 1) (row-major) but the kernel produces column-major (1, M), and (2) the fake unconditionally assumed blocked_scale_output=True, so it returned wrong metadata whenever the op was called with blocked_scale_output=False (as the validation script and wgrad path do). Both are now fixed.

🔵 Minor: swapped variable names in the blocked branch

quant.py:1153-1154

padded_scale_rows = ceil_div(m_blocks, 4) * 4
padded_scale_cols = ceil_div(k, 128) * 128

The final tensor is 1-D (padded_scale_cols * padded_scale_rows), so the size is correct regardless. But the naming is inverted relative to the real kernel, where padded_scale_rows is derived from K (rounded to 128) and padded_scale_cols from m_blocks (rounded to 4). Aligning the names with the real kernel would make it easier to keep the two in sync and avoid future confusion. Purely cosmetic — no behavioral impact.

Fix this →

🔵 Minor: dropped explanatory comments

The previous version had short comments explaining the padding rationale ("Only scales tensor needs padding for 4x128 scale factor tiles", "output data has same dimensions as input"). Those were removed. Since the real kernel keeps equivalent comments (cutedsl_quantize_2d_32x1.py:1033-1051), it'd be nice to keep a one-liner here too so the fake stays self-documenting.

🔵 Script: scripts/validate_wgrad_dim1_cutedsl.py

  • This matches @vkuzo's inline suggestion to split the logic into test/ and benchmarks/. The file mixes numeric validation (torch.equal, SQNR reporting) with benchmarking (benchmark_function, CUDA-graph timing). Given benchmarks/utils.py already exists and is imported here, moving the timing path under benchmarks/ and the equality check into a test under test/prototype/moe_training/ would fit the repo layout better. The PR body notes the script is temporary (to be deleted when torchao._C_mxfp8 is removed), so this is a judgment call on whether it's worth splitting a throwaway file.
  • Minor: run() computes grad_weight.transpose(-2, -1) and the diff-coordinate flattening at lines 209-213 assumes a 3-D output — worth a brief comment that this is the grouped (per-expert) 3-D result, since it's not obvious from the 2-D inputs.

Summary

The metadata fix is correct and well-targeted — the stride and the missing blocked_scale_output=False branch are exactly the discrepancies that would have caused wrong behavior under torch.compile/fake-tensor tracing. Only cosmetic nits remain (variable naming, dropped comments) plus @vkuzo's test/benchmark split suggestion for the script. Nothing blocking on the kernel change itself.
· branch gh/alexsamardzic/11/head

[ghstack-poisoned]
@alexsamardzic

Copy link
Copy Markdown
Contributor Author

All comments addressed.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
sanketpurandare added a commit that referenced this pull request Oct 14, 2026
Performnace of this fused cute-dsl quantizer is better than cuda, a single API for dense and grouped mxfp8 linears, no need for scale rearrangements since swizzled layouts are directly output.

AI-assisted implementation details:

> Keep Protonu's original authored fused kernel from #4895 as the
> parent commit and consolidate current-main correctness fixes in this PR.
> Credit: Protonu (@protonu), original commit
> 1d4e8d3; Aleksandar Samardzic's #4702
> independently addressed the single-axis FakeTensor metadata issue.
>
> Match the public/custom-op/fake argument order to surrounding APIs. None
> offsets select dense placement in the same kernel, with compact blocked
> scales and no synthetic endpoint or offset search. Tensor offsets retain
> grouped placement, empty experts and uncovered-tail behavior.
>
> Correct the scale0/1 RCEIL cutoff to 448*2^-127, preserve NOSAT nonfinite
> semantics, and compare both axes directly to to_mx with group unblocking.
> Cover exact cutoff neighbors, mixed magnitudes, special values, empty groups,
> dirty destinations, actual compile/fake contracts and device selection.
>
> Validate aligned destination metadata and nonoverlapping byte intervals.
> Enable device assertions explicitly for grouped compilation; CuTeDSL strips
> them by default. Reuse the endpoint validation loop for ordering and bounds.
> Remove unreachable CTA work and redundant reciprocal conventions.
>
> Test plan: affected fused/single-axis CUDA tests, repository Ruff checks,
> strict API documentation rendering, matched replay timings and traces, and
> real TorchTitan FSDP/MXFP8 eager/capture consumer tests.

Pull Request resolved: #4995
vkuzo pushed a commit that referenced this pull request Oct 15, 2026
…ta (#4995)

* [moe_training] Add a fused 1x32 + 32x1 MXFP8 quantization kernel

Quantizing a 2D tensor along both axes currently takes three kernels and two
full reads of the same tensor: the 1x32 CuTeDSL cast along N, the 32x1 CUDA cast
along M, and a standalone Triton K-groups swizzle of the colwise scales. Add a
CuTeDSL kernel that reads the input once and emits all four outputs, with both
scale tensors already in the blocked layouts their consumers expect. Byte
accounting drops from 6.125 to 4.0625 bytes per input element.

The kernel puts one CTA on each (128, 128) input tile, stages it into SMEM with
cp.async, and runs the rowwise and colwise passes sequentially at full CTA
width. The arithmetic is packed 16-bit throughout -- max.u16x2 on sign-masked
bf16 for amax, cvt.rn.satfinite.e4m3x2.bf16x2 for the cast -- and prmt.b32 byte
permutes keep the logically transposed colwise store fully coalesced. bf16 and
rceil only; both dimensions and every group size must be multiples of 128.

Exposed as mxfp8_quantize_2d_1x32_32x1_cutedsl, registered as a custom op with a
fake impl, alongside the two kernels it composes.

Uncovered tail. offs[-1] < total_M is supported and is the norm rather than a
corner case: a dropless MoE dispatcher sizes its buffer for worst-case padding
and fills only a prefix. Rows past offs[-1] are still quantized, but their
colwise scale bytes are zeroed to match the K-groups swizzle, which iterates
groups and returns new_zeros. Falling through to the placement math instead aims
the store into group 0's slab and races every n-tile CTA on one 512-byte line.

Bug-compatible where the two kernels it replaces disagree with each other, since
the point is to be a drop-in:

  * A block whose amax is subnormal enough to reach E8M0 scale byte 0 gets a
    2**127 multiplier on both outputs, matching the 254 - scale_biased
    reciprocal both use.
  * Inf: the rowwise kernel converts NOSAT, so Inf poisons the block to scale
    255 and all-NaN data; the colwise CUDA kernel converts SATFINITE, so Inf
    clamps to scale 254 with finite data. Both are reproduced.

The one deliberate divergence is NaN on the colwise output. The CUDA kernel
drops NaN from its amax entirely -- an all-NaN block still gets the scale its
finite elements imply -- and reproducing that would need a per-element NaN test
in the hottest loop in order to imitate a behavior that hides NaN corruption
rather than surfacing it. The fused kernel poisons instead, and the test asserts
the difference so it fails loudly if either side changes.

Tests compare raw bytes at atol=0/rtol=0 against the three-kernel composition,
not against to_mx, because being a drop-in for that composition is the contract.
They cover shapes and group counts, uncovered tails including the zero-fill,
degenerate and mixed-magnitude blocks, Inf/NaN, dirty destination buffers so a
never-written region cannot hide behind a zeroed page, determinism across
repeated launches, and input validation. The rowwise half is additionally
checked against the shared MXFP8 semantic contract.

The benchmark follows the existing 1x32 and 32x1 scripts, but times both sides
under CUDA-graph replay rather than eagerly. torchao's triton_op dispatch costs
on the order of 100us per call regardless of problem size and the baseline pays
it three times, which timed eagerly swamps every shape below roughly 0.5 GB and
reports 15x on small shapes -- launch overhead, not a kernel win. It also checks
that the kernel does not capture as an empty graph, which is what happens when a
CuTeDSL kernel ignores the caller's stream and which would read as a 100x win.
Geomean is 2.6x across the swept shapes, 2.0x on the largest, at up to 95% of
the measured SM bandwidth roof on a GB200 at 2062 MHz.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [moe_training] Match MXFP8 dense and grouped contracts

Performnace of this fused cute-dsl quantizer is better than cuda, a single API for dense and grouped mxfp8 linears, no need for scale rearrangements since swizzled layouts are directly output.

AI-assisted implementation details:

> Keep Protonu's original authored fused kernel from #4895 as the
> parent commit and consolidate current-main correctness fixes in this PR.
> Credit: Protonu (@protonu), original commit
> 1d4e8d3; Aleksandar Samardzic's #4702
> independently addressed the single-axis FakeTensor metadata issue.
>
> Match the public/custom-op/fake argument order to surrounding APIs. None
> offsets select dense placement in the same kernel, with compact blocked
> scales and no synthetic endpoint or offset search. Tensor offsets retain
> grouped placement, empty experts and uncovered-tail behavior.
>
> Correct the scale0/1 RCEIL cutoff to 448*2^-127, preserve NOSAT nonfinite
> semantics, and compare both axes directly to to_mx with group unblocking.
> Cover exact cutoff neighbors, mixed magnitudes, special values, empty groups,
> dirty destinations, actual compile/fake contracts and device selection.
>
> Validate aligned destination metadata and nonoverlapping byte intervals.
> Enable device assertions explicitly for grouped compilation; CuTeDSL strips
> them by default. Reuse the endpoint validation loop for ordering and bounds.
> Remove unreachable CTA work and redundant reciprocal conventions.
>
> Test plan: affected fused/single-axis CUDA tests, repository Ruff checks,
> strict API documentation rendering, matched replay timings and traces, and
> real TorchTitan FSDP/MXFP8 eager/capture consumer tests.

Pull Request resolved: #4995

---------

Co-authored-by: protonu <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@alexsamardzic

Copy link
Copy Markdown
Contributor Author

Closing: the fake-metadata fix landed on main as part of #4995, which also added an opcheck-based fake-tensor test for this op. The wgrad dim1 benchmark was only temporary, and the fused kernel from #4995 now covers the three-kernel path it measured.

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. module: training quantize_ api training flow moe

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants