Repository navigation
Refine MXFP8 CUDA quantization semantics - #4725
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
|
Stack from ghstack (oldest at bottom): |
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/ao/4725
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 00055ce with merge base e74892b ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| const int32_t extracted_pow2 = | ||
| ((int_amax >> FP32_MANTISSA_BITS) & 0b11111111) - FP32_EXPONENT_BIAS; |
There was a problem hiding this comment.
This wasn't handling subnormals correctly.
| if (isinf(val)) { | ||
| return 0xFE; | ||
| } |
There was a problem hiding this comment.
This was causing Inf to become 2^127. It was clearly intentional, but I'd argue against it.
| (__CUDA_ARCH_HAS_FEATURE__(SM120_ALL))) | ||
| uint16_t out; | ||
| asm volatile("{\n" | ||
| "cvt.rp.satfinite.ue8m0x2.f32 %0, 0.0, %1;\n" |
There was a problem hiding this comment.
Similrly, .satfinite is also causing Inf to become 2^127. But we can just remove that modifier.
| */ | ||
| __device__ __forceinline__ float e8m0_to_scale_fp32(e8m0_t e8m0_biased_scale) { | ||
| int32_t exponent_as_int32 = static_cast<int32_t>(e8m0_biased_scale); | ||
| int32_t float_bits = exponent_as_int32 << FP32_MANTISSA_BITS; |
There was a problem hiding this comment.
Isn't handling 2^-127 correctly.
| data_lp = min(data_lp, F8E4M3_MAX); | ||
| data_lp = max(data_lp, -F8E4M3_MAX); | ||
|
|
||
| return static_cast<OType>(data_lp); |
There was a problem hiding this comment.
Must use explicit clamping, because the conversion function being used doesn't make it clear
| llvm.inline_asm( | ||
| T.i16(), | ||
| [cutlass.Float32(a).ir_value(loc=loc, ip=ip)], | ||
| "cvt.rp.satfinite.ue8m0x2.f32 $0, 0.0, $1;", |
There was a problem hiding this comment.
Again the .satfinite issue (we want this when doing fp32->e4m3, but not when doing fp32->e8m0)
| vals_vec = vals_block.load() | ||
| abs_vec = cute.where(vals_vec < 0, -vals_vec, vals_vec) | ||
| return cutlass.Float32( | ||
| abs_vec.reduce(cute.ReductionOp.MAX, cutlass.Float32(0.0), 0) |
There was a problem hiding this comment.
This reduction propagates NaNs
| if scale_biased == 0xFF: | ||
| inv_scale = cutlass.Float32(0.0) | ||
| elif scale_biased == 0: | ||
| inv_scale = cute.exp2(cutlass.Float32(126.0)) | ||
| else: | ||
| inv_scale = cute.exp2(cutlass.Float32(127 - scale_biased)) |
There was a problem hiding this comment.
I'm puzzled by what's going on here. NaN becomes 0, the inverse of 2^-127 is 2^126, ...
| scale_e8m0_biased == 0, # Zero case -> return 1.0 (no scaling) | ||
| 1.0, |
There was a problem hiding this comment.
I think this is a bug carried over from TransformerEngine, and since fixed there: NVIDIA/TransformerEngine#2647 and NVIDIA/TransformerEngine#3262
| exponent == 0, | ||
| 1.0, | ||
| torch.exp2(E8M0_EXPONENT_BIAS - exponent.to(torch.float32)), |
There was a problem hiding this comment.
Again the TE issue, plus NVIDIA/TransformerEngine#2408
|
|
||
| # Original floor implementation | ||
| # Calculate the e8m0 scale by extracting the exponent (floor) | ||
| max_abs = max_abs.to(tl.bfloat16) |
There was a problem hiding this comment.
So, this one is subtle: going fp32->bf16->e8m0 (instead of directly fp32->e8m0) can round some fp32 values across the threshold that makes them round up instead of down!
| else: | ||
| # Fallback implementation | ||
| scale_e8m0_unbiased = tl.clamp( | ||
| tl.ceil(tl.log2(scale_input)), |
There was a problem hiding this comment.
Log2 is too inaccurate for such an operation
[ghstack-poisoned]
[ghstack-poisoned]
Here's the steps of quantization, with the respective options and pitfalls. 1. **Compute the abs-max of the quantization tile** The main decision is what to do with NaNs: propagate them (one NaN "pollutes" the whole tile) or ignore them (amax is NaN only if the whole tile is NaN). CUDA and Triton default to ignore, PyTorch and CuTeDSL default to propagate. Here I opted to go for ignore, for a bunch of reasons: - It prevents NaNs from spreading: if we did bf16->mxfp8->bf16, the output will have the same number of NaNs as the input, in the same positions, whereas if we propagate NaNs we'd end up with full 1x32 tiles of NaNs. This is not a strong argument, because it only matters when mxfp8 is used for compressing activations or other secondary usages, since for matmuls both ignore and propagate have the same behavior (one NaN in a row or column makes the corresponding output element become NaN). - It seemed easier to align all backends to ignore NaNs rather that the other way around. This is also a poor argument, especially if some backends (e.g., CUDA) are slated for removal. - It's the default CUDA semantics. Also a bad argument, as it might make more sense to follow the standard backend-agnostic PyTorch convention. 2. **Convert the amax / fp8_max to a ue8m0 scale** - We need to decide what to do about Inf. Here I decided to make it produce a scale of NaN, as saturating it to the largest scale might end up hiding a numerical bug, and would cause an infinitely large quantization error. - Another catch is to make sure to handle subnormals correctly, since the lowest ue8m0 value is just outside the range of normals. - Also note that doing this via log2+ceil (or floor) is mathematically correct but numerically incorrect because of some inaccuracies of these functions (which are also quite expensive on GPU!). The best approach seems to be bit-manipulation (or, on Blackwell GPUs, just relying on the built-in PTX, albeit with the correct modifiers). 3. **Taking the reciprocal of the scale** NaNs must pass-through unchanged. And again there's the subnormal value (corresponding to 2^-127) which might need special care. A safe approach is to reinterpret this as 254 - x in uint8. 4. **Converting the reciprocal back to a fp32** Pretty much the symmetrical problems: handling NaN, mapping 2^-127 to a subnormal, avoiding exp2 due to numerical issues (and slowness). And again the solution is bit-manipulation or PTX builtins. 5. **Converting data to e4m3 or e5m2** This is pretty straightforward if we use the right builtins. One catch is that the floor mode needs to do clamping. It might be done automatically by the conversion if we use saturation, but if this isn't the case we need to do it manually. I'd appreciate some discussion of the above decisions, so that we get to a large consensus. The one I'm most unsure about is the ignore-vs-propagate for NaNs. I encoded this semantic on all the backends: torch (eager + compiled), CUDA C++, Triton, CuTeDSL. The FlyDSL changes are agent-authored and unreviewed! I also added extensive testing for all the delicate edge cases that I found. In principle every change I did would now cause a test to fail if it were reverted. I added some inline comments in this PR to highlight some of the above issues, but didn't do it with perfect coverage. ghstack-source-id: 2e1909c ghstack-comment-id: 5220768363 Pull-Request: #4725
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 66-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 66-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 66-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales.
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales.
nvidia-cutlass-dsl 4.6.0 renamed RoundingModeKind -> FPRoundingMode, while both existed in 4.5.0. #4725 recently added references to the old name, resulting in the following error. This breaks compatibility with vllm nightly, which currently depends on 4.6.2: ``` AttributeError: module 'cutlass._mlir.dialects.nvvm' has no attribute 'RoundingModeKind' at cute_utils.py:246, in compute_scale_rceil ``` According to claude: ``` Rename the three uses to `FPRoundingMode`, which is correct on every released version: - Values are identical for the members used here: RoundingModeKind: NONE=0 RN=1 RM=2 RP=3 RZ=4 FPRoundingMode: NONE=0 RN=1 RM=2 RP=3 RZ=4 RNA=5 (strict superset) - Both register attribute builders with the same body, emitting a signless i32 IntegerAttr from int(x), so the enum class does not affect the attribute. - From 4.6.0 the generated op requests 'FPRoundingModeAttr' (22 uses, 0 of 'RoundingModeKindAttr'), so this is the expected API there, not a shim. - FPRoundingMode is present in 4.4.2, 4.5.0, 4.6.0, 4.6.2 and 4.7.0, so the unconditional rename keeps older versions working. ```
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales.
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
nvidia-cutlass-dsl 4.6.0 renamed RoundingModeKind -> FPRoundingMode, while both existed in 4.5.0. #4725 recently added references to the old name, resulting in the following error. This breaks compatibility with vllm nightly, which currently depends on 4.6.2: ``` AttributeError: module 'cutlass._mlir.dialects.nvvm' has no attribute 'RoundingModeKind' at cute_utils.py:246, in compute_scale_rceil ``` According to claude: ``` Rename the three uses to `FPRoundingMode`, which is correct on every released version: - Values are identical for the members used here: RoundingModeKind: NONE=0 RN=1 RM=2 RP=3 RZ=4 FPRoundingMode: NONE=0 RN=1 RM=2 RP=3 RZ=4 RNA=5 (strict superset) - Both register attribute builders with the same body, emitting a signless i32 IntegerAttr from int(x), so the enum class does not affect the attribute. - From 4.6.0 the generated op requests 'FPRoundingModeAttr' (22 uses, 0 of 'RoundingModeKindAttr'), so this is the expected API there, not a shim. - FPRoundingMode is present in 4.4.2, 4.5.0, 4.6.0, 4.6.2 and 4.7.0, so the unconditional rename keeps older versions working. ```
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales.
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales. Same fix for `fmax`.
… Blackwell One CuTe DSL kernel fuses the gated activation (forward and backward) with the RCEIL MXFP8 cast: gate/up are read once and the bf16 activation never round-trips through global memory. Rowwise (1x32), colwise (32x1), or both scale modes come out of a single pass, in the same blocked tcgen05 layouts as the standalone quantizers, and bit-compatible with their special-value semantics (pytorch#4725 contract: NaN/Inf amax invalidates the block with scale byte 255 and all-NaN data; byte-0 scales descale by 2^127). Ops: torchao::gated_act_mxfp8_{forward,backward} custom ops with fake impls (torch.compile fullgraph works), public wrappers, 80-case numerics suite (bitwise forward, one-code-bounded backward), and an A/B benchmark vs the unfused Triton-activation + standalone-quantizer path. Co-Authored-By: Claude Fable 5 <[email protected]>
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in `cvt_packfloat_f32` and `cvt_packfloat`. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Repro on 4.6.0 (needs #4765 to run): ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Verified on 4.6.0 that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales. Same fix for `fmax`.
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in a few nvvm ops. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` Correct signature: ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.5.x[cu13], 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Note that we cannot simply gate this on the verison because different variants within the same version can have different signatures. Here is the complete table: ``` nvidia-cutlass-dsl 4.4.x, 4.5.x accepts `res` == T.i32() nvidia-cutlass-dsl[cu13] 4.4.x, 4.5.x no `res` nvidia-cutlass-dsl 4.6.0+ no `res` nvidia-cutlass-dsl[cu13] 4.6.0+ no `res` ``` Full list of affected ops used by `cute_utils.py`: ``` fmax cvt_packfloat cvt_packfloat32 ``` **Test Plan:** Full version sweep across the following versions. vllm nightly currently requires 4.6.2. ``` nvidia-cutlass-dsl 4.5.3, 4.6.0, 4.6.2, 4.7.1 nvidia-cutlass-dsl[cu13] 4.5.3, 4.6.0, 4.6.2, 4.7.1 ``` Repro: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_cuda_3d, ) x = torch.randn(2, 256, 256, device="cuda", dtype=torch.bfloat16) mxfp8_quantize_cuda_3d( x, scale_block_dim1=32, scale_block_dim2=32, scaling_mode="rceil", ) ``` Verified that the output is bitwise identical to `triton_to_mxfp8_dim0` for qdata and scales.
`nvidia-cutlass-dsl` 4.6.0 removed a leading argument in a few nvvm ops. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` Correct signature: ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.5.x[cu13], 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Note that we cannot simply gate this on the verison because different variants within the same version can have different signatures. Here is the complete table: ``` nvidia-cutlass-dsl 4.4.x, 4.5.x accepts `res` == T.i32() nvidia-cutlass-dsl[cu13] 4.4.x, 4.5.x no `res` nvidia-cutlass-dsl 4.6.0+ no `res` nvidia-cutlass-dsl[cu13] 4.6.0+ no `res` ``` Full list of affected ops used by `cute_utils.py`: ``` fmax cvt_packfloat cvt_packfloat32 ``` **Test Plan:** Full version sweep across the following versions. vllm nightly currently requires 4.6.2. ``` nvidia-cutlass-dsl 4.5.3, 4.6.0, 4.6.2, 4.7.1 nvidia-cutlass-dsl[cu13] 4.5.3, 4.6.0, 4.6.2, 4.7.1 ``` Repro: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_cuda_3d, ) x = torch.randn(2, 256, 256, device="cuda", dtype=torch.bfloat16) mxfp8_quantize_cuda_3d( x, scale_block_dim1=32, scale_block_dim2=32, scaling_mode="rceil", ) ```
**Summary:** `nvidia-cutlass-dsl` 4.6.0 removed a leading argument in a few nvvm ops. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` Correct signature: ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.5.x[cu13], 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Note that we cannot simply gate this on the verison because different variants within the same version can have different signatures. Here is the complete table: ``` nvidia-cutlass-dsl 4.4.x, 4.5.x accepts `res` == T.i32() nvidia-cutlass-dsl[cu13] 4.4.x, 4.5.x no `res` nvidia-cutlass-dsl 4.6.0+ no `res` nvidia-cutlass-dsl[cu13] 4.6.0+ no `res` ``` Full list of affected ops used by `cute_utils.py`: ``` fmax cvt_packfloat cvt_packfloat32 ``` **Test Plan:** Full version sweep across the following versions. vllm nightly currently requires 4.6.2. ``` nvidia-cutlass-dsl 4.5.3, 4.6.0, 4.6.2, 4.7.1 nvidia-cutlass-dsl[cu13] 4.5.3, 4.6.0, 4.6.2, 4.7.1 ``` Repro 1: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Repro 2: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_cuda_3d, ) x = torch.randn(2, 256, 256, device="cuda", dtype=torch.bfloat16) mxfp8_quantize_cuda_3d( x, scale_block_dim1=32, scale_block_dim2=32, scaling_mode="rceil", ) ```
**Summary:** `nvidia-cutlass-dsl` 4.6.0 removed a leading argument in a few nvvm ops. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` Correct signature: ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.5.x[cu13], 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Note that we cannot simply gate this on the verison because different variants within the same version can have different signatures. Here is the complete table: ``` nvidia-cutlass-dsl 4.4.x, 4.5.x accepts `res` == T.i32() nvidia-cutlass-dsl[cu13] 4.4.x, 4.5.x no `res` nvidia-cutlass-dsl 4.6.0+ no `res` nvidia-cutlass-dsl[cu13] 4.6.0+ no `res` ``` Full list of affected ops used by `cute_utils.py`: ``` fmax cvt_packfloat cvt_packfloat32 ``` **Test Plan:** Full version sweep across the following versions. vllm nightly currently requires 4.6.2. ``` nvidia-cutlass-dsl 4.5.3, 4.6.0, 4.6.2, 4.7.1 nvidia-cutlass-dsl[cu13] 4.5.3, 4.6.0, 4.6.2, 4.7.1 ``` Repro 1: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Repro 2: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_cuda_3d, ) x = torch.randn(2, 256, 256, device="cuda", dtype=torch.bfloat16) mxfp8_quantize_cuda_3d( x, scale_block_dim1=32, scale_block_dim2=32, scaling_mode="rceil", ) ```
**Summary:** `nvidia-cutlass-dsl` 4.6.0 removed a leading argument in a few nvvm ops. The current callsite in torchao (introduced in #4725) still includes this leading argument, resulting in the following error: ``` TypeError: cvt_packfloat_f32() takes 4 positional arguments but 5 were given ``` Correct signature: ``` \# 4.5.x nvvm.cvt_packfloat_f32(T.i32(), src_a, src_b, src_c, to, rnd=..., sat=...) \# 4.5.x[cu13], 4.6.0+ nvvm.cvt_packfloat_f32(src_a, src_b, src_c, to, rnd=..., sat=...) ``` Note that we cannot simply gate this on the verison because different variants within the same version can have different signatures. Here is the complete table: ``` nvidia-cutlass-dsl 4.4.x, 4.5.x accepts `res` == T.i32() nvidia-cutlass-dsl[cu13] 4.4.x, 4.5.x no `res` nvidia-cutlass-dsl 4.6.0+ no `res` nvidia-cutlass-dsl[cu13] 4.6.0+ no `res` ``` Full list of affected ops used by `cute_utils.py`: ``` fmax cvt_packfloat cvt_packfloat32 ``` **Test Plan:** Full version sweep across the following versions. vllm nightly currently requires 4.6.2. ``` nvidia-cutlass-dsl 4.5.3, 4.6.0, 4.6.2, 4.7.1 nvidia-cutlass-dsl[cu13] 4.5.3, 4.6.0, 4.6.2, 4.7.1 ``` Repro 1: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_2d_1x32_cutedsl, ) x = torch.randn(128, 2048, device="cuda", dtype=torch.bfloat16) offs = torch.tensor([128], device="cuda", dtype=torch.int32) mxfp8_quantize_2d_1x32_cutedsl(x, scaling_mode="rceil", offs=offs) ``` Repro 2: ``` import torch from torchao.prototype.moe_training.kernels.mxfp8 import ( mxfp8_quantize_cuda_3d, ) x = torch.randn(2, 256, 256, device="cuda", dtype=torch.bfloat16) mxfp8_quantize_cuda_3d( x, scale_block_dim1=32, scale_block_dim2=32, scaling_mode="rceil", ) ```
…aster one The generic, warp-specialized, TMA-pipelined kernel is replaced with two dtype-specific implementations with fixed occupancy and no pipeline, dispatched on `x.dtype` inside the same public function -- packed bf16x2 inline PTX for bf16; the hardware cvt.rp.ue8m0x2.f32 instruction used directly for fp32, in place of a generic TMA copy pipeline. Full feature parity with the kernel it replaces -- RCEIL/FLOOR, blocked and plain scale output, offs group validation, bf16 and fp32 -- except stage_count, which has no meaning here (no TMA pipeline to configure the stage count of) and is kept in the public signature purely for call-site parity, same precedent as the dim-0 (1x32) replacement (85c2581). No other file needed to change; quant.py's custom op already calls this file by the same name and forwards stage_count regardless of whether the callee uses it. FLOOR mode is not the performance-critical path (production uses RCEIL), so both dtypes reuse cute_utils.compute_scale_from_amax directly for it rather than hand-deriving new PTX -- correct by construction for every degenerate case, at some cost in raw throughput for that mode only. Geomean speedup over the kernel it replaces, on the DeepSeekV3-671b shapes swept by this kernel's own benchmark, on a GB200 with clocks locked (`nvidia-smi -i 0 -lgc 1965,1965`): ~1.06x combined across RCEIL and FLOOR. Narrower than the dim-0 replacement's margin, for two reasons: the RCEIL path here already had a competitively-tuned baseline to beat (unlike dim-0's fp32 path, which had none), and FLOOR's correctness-by-construction tradeoff pulls the combined average down from RCEIL's own margin. Five real correctness bugs were found and fixed while building and validating this replacement, all in degenerate (Inf/NaN/zero/subnormal) input handling that well-conditioned training data never exercises: * The RCEIL scale conversion used the hardware cvt op's `.satfinite` mode, which clamps +-Inf to the largest finite E8M0 byte instead of mapping it to the NaN sentinel byte -- an Inf/NaN block must invalidate its scale, not quantize as an ordinary large value. * The degenerate e==0 reciprocal was hardcoded to 2^126, the convention upstream PR pytorch#4725 flipped to 2^127 after the seed implementation this kernel started from was generated. * The degenerate e==255 (Inf/NaN) reciprocal returned 0.0 instead of NaN, silently zeroing an invalidated block's output instead of propagating NaN through it. * The fp32 kernel had no amax==0 special case at all, conflating a truly all-zero block (reciprocal should be 1.0) with a block whose amax merely rounds down to the smallest representable scale (reciprocal should be 2^127) -- both produce e==0. * The fp32 kernel's amax reduction (fmax/fmin) defaulted to NaN-quiet maximumNumber/minimumNumber semantics, silently dropping a lone NaN sharing a block with any finite value instead of propagating it. Validated bit-exact (atol=0, rtol=0) against the kernel it replaces across shapes, both dtypes, both scaling modes, blocked and plain scale output, with and without offs, and the full 18-case MXFP8 semantic contract (zero, Inf, NaN, subnormals, satfinite boundaries, dtype-rounding edge cases) -- the test that caught all five bugs above. The existing test and benchmark files needed no changes: `test_kernels.py` (1056 passed, 71 skipped; two unrelated pre-existing failures in test_row_major_with_jagged_rowwise_scales, confirmed present on the unmodified base commit in an isolated worktree) and `test_mxfp8_grouped_mm.py` (48 passed) both exercise this kernel through its unchanged public name and pass. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…aster one The generic, warp-specialized, TMA-pipelined kernel is replaced with two dtype-specific implementations with fixed occupancy and no pipeline, dispatched on `x.dtype` inside the same public function -- packed bf16x2 inline PTX for bf16; the hardware cvt.rp.ue8m0x2.f32 instruction used directly for fp32, in place of a generic TMA copy pipeline. Full feature parity with the kernel it replaces -- RCEIL/FLOOR, blocked and plain scale output, offs group validation, bf16 and fp32 -- except stage_count, which has no meaning here (no TMA pipeline to configure the stage count of) and is kept in the public signature purely for call-site parity, same precedent as the dim-0 (1x32) replacement (85c2581). No other file needed to change; quant.py's custom op already calls this file by the same name and forwards stage_count regardless of whether the callee uses it. FLOOR mode is not the performance-critical path (production uses RCEIL), so both dtypes reuse cute_utils.compute_scale_from_amax directly for it rather than hand-deriving new PTX -- correct by construction for every degenerate case, at some cost in raw throughput for that mode only. Geomean speedup over the kernel it replaces, on the DeepSeekV3-671b shapes swept by this kernel's own benchmark, on a GB200 with clocks locked (`nvidia-smi -i 0 -lgc 1965,1965`): ~1.06x combined across RCEIL and FLOOR. Narrower than the dim-0 replacement's margin, for two reasons: the RCEIL path here already had a competitively-tuned baseline to beat (unlike dim-0's fp32 path, which had none), and FLOOR's correctness-by-construction tradeoff pulls the combined average down from RCEIL's own margin. Five real correctness bugs were found and fixed while building and validating this replacement, all in degenerate (Inf/NaN/zero/subnormal) input handling that well-conditioned training data never exercises: * The RCEIL scale conversion used the hardware cvt op's `.satfinite` mode, which clamps +-Inf to the largest finite E8M0 byte instead of mapping it to the NaN sentinel byte -- an Inf/NaN block must invalidate its scale, not quantize as an ordinary large value. * The degenerate e==0 reciprocal was hardcoded to 2^126, the convention upstream PR pytorch#4725 flipped to 2^127 after the seed implementation this kernel started from was generated. * The degenerate e==255 (Inf/NaN) reciprocal returned 0.0 instead of NaN, silently zeroing an invalidated block's output instead of propagating NaN through it. * The fp32 kernel had no amax==0 special case at all, conflating a truly all-zero block (reciprocal should be 1.0) with a block whose amax merely rounds down to the smallest representable scale (reciprocal should be 2^127) -- both produce e==0. * The fp32 kernel's amax reduction (fmax/fmin) defaulted to NaN-quiet maximumNumber/minimumNumber semantics, silently dropping a lone NaN sharing a block with any finite value instead of propagating it. Validated bit-exact (atol=0, rtol=0) against the kernel it replaces across shapes, both dtypes, both scaling modes, blocked and plain scale output, with and without offs, and the full 18-case MXFP8 semantic contract (zero, Inf, NaN, subnormals, satfinite boundaries, dtype-rounding edge cases) -- the test that caught all five bugs above. The existing test and benchmark files needed no changes: `test_kernels.py` (1056 passed, 71 skipped; two unrelated pre-existing failures in test_row_major_with_jagged_rowwise_scales, confirmed present on the unmodified base commit in an isolated worktree) and `test_mxfp8_grouped_mm.py` (48 passed) both exercise this kernel through its unchanged public name and pass. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…aster one The generic, warp-specialized, TMA-pipelined kernel is replaced with two dtype-specific implementations with fixed occupancy and no pipeline, dispatched on `x.dtype` inside the same public function -- packed bf16x2 inline PTX for bf16; the hardware cvt.rp.ue8m0x2.f32 instruction used directly for fp32, in place of a generic TMA copy pipeline. Full feature parity with the kernel it replaces -- RCEIL/FLOOR, blocked and plain scale output, offs group validation, bf16 and fp32 -- except stage_count, which has no meaning here (no TMA pipeline to configure the stage count of). quant.py's custom op keeps stage_count in its public signature for API parity with the other cutedsl/flydsl quantize ops (same precedent already established for the FlyDSL backend there) but no longer forwards it into the kernel call, same precedent as the dim-0 (1x32) replacement (85c2581). FLOOR mode is not the performance-critical path (production uses RCEIL), so both dtypes reuse cute_utils.compute_scale_from_amax directly for it rather than hand-deriving new PTX -- correct by construction for every degenerate case, at some cost in raw throughput for that mode only. Geomean speedup over the kernel it replaces, on the DeepSeekV3-671b shapes swept by this kernel's own benchmark, on a GB200 with clocks locked (`nvidia-smi -i 0 -lgc 1965,1965`): ~1.06x combined across RCEIL and FLOOR. Narrower than the dim-0 replacement's margin, for two reasons: the RCEIL path here already had a competitively-tuned baseline to beat (unlike dim-0's fp32 path, which had none), and FLOOR's correctness-by-construction tradeoff pulls the combined average down from RCEIL's own margin. Five real correctness bugs were found and fixed while building and validating this replacement, all in degenerate (Inf/NaN/zero/subnormal) input handling that well-conditioned training data never exercises: * The RCEIL scale conversion used the hardware cvt op's `.satfinite` mode, which clamps +-Inf to the largest finite E8M0 byte instead of mapping it to the NaN sentinel byte -- an Inf/NaN block must invalidate its scale, not quantize as an ordinary large value. * The degenerate e==0 reciprocal was hardcoded to 2^126, the convention upstream PR pytorch#4725 flipped to 2^127 after the seed implementation this kernel started from was generated. * The degenerate e==255 (Inf/NaN) reciprocal returned 0.0 instead of NaN, silently zeroing an invalidated block's output instead of propagating NaN through it. * The fp32 kernel had no amax==0 special case at all, conflating a truly all-zero block (reciprocal should be 1.0) with a block whose amax merely rounds down to the smallest representable scale (reciprocal should be 2^127) -- both produce e==0. * The fp32 kernel's amax reduction (fmax/fmin) defaulted to NaN-quiet maximumNumber/minimumNumber semantics, silently dropping a lone NaN sharing a block with any finite value instead of propagating it. Validated bit-exact (atol=0, rtol=0) against the kernel it replaces across shapes, both dtypes, both scaling modes, blocked and plain scale output, with and without offs, and the full 18-case MXFP8 semantic contract (zero, Inf, NaN, subnormals, satfinite boundaries, dtype-rounding edge cases) -- the test that caught all five bugs above. The existing test and benchmark files needed no changes: `test_kernels.py` (1056 passed, 71 skipped; two unrelated pre-existing failures in test_row_major_with_jagged_rowwise_scales, confirmed present on the unmodified base commit in an isolated worktree) and `test_mxfp8_grouped_mm.py` (48 passed) both exercise this kernel through its unchanged public name and pass, both before and after the quant.py stage_count cleanup. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Here's the steps of quantization, with the respective options and pitfalls.
Compute the abs-max of the quantization tile
The main decision is what to do with NaNs: propagate them (one NaN "pollutes" the whole tile) or ignore them (amax is NaN only if the whole tile is NaN). CUDA and Triton default to ignore, PyTorch and CuTeDSL default to propagate. Here I opted to go for propagate, for a bunch of reasons:
(Note, an earlier version of this PR made the opposite choice and went for "ignore", but I changed my mind)
Convert the amax / fp8_max to a ue8m0 scale
The best approach seems to be bit-manipulation (or, on Blackwell GPUs, just relying on the built-in PTX, albeit with the correct modifiers).
Taking the reciprocal of the scale
NaNs must pass-through unchanged. And again there's the subnormal value (corresponding to 2^-127) which might need special care. A safe approach is to reinterpret this as 254 - x in uint8.
Converting the reciprocal back to a fp32
Pretty much the symmetrical problems: handling NaN, mapping 2^-127 to a subnormal, avoiding exp2 due to numerical issues (and slowness). And again the solution is bit-manipulation or PTX builtins.
Converting data to e4m3 or e5m2
This is pretty straightforward if we use the right builtins. One catch is that the floor mode needs to do clamping. It might be done automatically by the conversion if we use saturation, but if this isn't the case we need to do it manually.
I'd appreciate some discussion of the above decisions, so that we get to a large consensus. The one I'm most unsure about is the ignore-vs-propagate for NaNs.
I encoded this semantic on all the backends: torch (eager + compiled), CUDA C++, Triton, CuTeDSL. The FlyDSL changes are agent-authored and unreviewed!
I also added extensive testing for all the delicate edge cases that I found. In principle every change I did would now cause a test to fail if it were reverted.
I added some inline comments in this PR to highlight some of the above issues, but didn't do it with perfect coverage.