…Python ref / FlyDSL (#3212)
* feat(fp4): align E8M0 scale to OCP standard + add NV ROUND_UP mode
Change fp4_f32_to_e8m0_scale to OCP standard (floor_pow2(amax/4)),
add fp4_f32_to_e8m0_scale_roundup for NV/DSv4/FlashInfer ceil_pow2(amax/6).
Extend quant_mxfp4 with three round modes aligned to Quark:
0=RoundDown (OCP), 1=RoundUp (NV), 2=Even (Quark).
Default quant_mxfp4_hip round_mode=0 routes to
dynamic_per_group_scaled_quant_fp4.
* fix(test_quant_mxfp4): pass round_mode=2 for Even round tests
Tests comparing against ref_quant_mxfp4_even_round now explicitly
request round_mode=2 (Even) since round_mode=0 changed to RoundDown.
* doc(fp4_quant_utils): clarify NaN/Inf → E8M0 0xFF behavior
* feat(quant): default MXFP4 block scale to NV ROUND_UP, add MxFp4RoundMode
Switch FP4 (E2M1) per-1x32 block-scale rounding default to
ceil_pow2(amax/6) (torchao RCEIL / NV ROUND_UP / DSv4 Pro / FlashInfer)
on HIP, Python ref, and FlyDSL fp4 paths. New MxFp4RoundMode IntEnum
exposes all four modes (RoundDown / RoundUp / Even / Ceil); values
match the C++ enum 1:1 so existing int callers are unchanged. Adds
4-mode coverage in test_quant_mxfp4. End-to-end sweep on
test_moe_2stage: 0/530 strict-accuracy failures vs 181/530 under the
OCP-aligned baseline (max logits_diff 0.0035 vs 0.046).
Co-authored-by: Cursor <[email protected]>
* refactor(quant): rename MxFp4RoundMode -> MxScaleRoundMode (alias kept)
The four rounding formulas (FLOOR / RCEIL / CEIL / EVEN) are
dtype-agnostic across the MX format family (mxfp4 / mxfp6 / mxfp8 /
mxint8) -- PyTorch torchao's ScaleCalculationMode is shared across
all elem_dtype values for the same reason. Rename the enum on both
the C++ side (csrc/kernels/quant_mxfp4.cu) and the Python side
(aiter/ops/quant.py) so future mx kernels can reuse it. Keep
MxFp4RoundMode as a Python alias so existing callers
(``from aiter.ops.quant import MxFp4RoundMode``) continue to work
unchanged.
C++ ABI is unaffected: the enum is only used inside the kernel and
the pybind entry already accepts a bare int.
Co-authored-by: Cursor <[email protected]>
* refactor(quant): move MxScaleRoundMode to fp4_quant_utils.h for reuse
The enum is dtype-agnostic (FLOOR / RCEIL / CEIL / EVEN apply to all
MX formats), so future mxfp6 / mxfp8 / mxint8 kernels can now reuse
it directly via ``#include "fp4_quant_utils.h"`` instead of either
redefining their own copy or transitively pulling in quant_mxfp4.cu.
No behaviour change: the enum body and integer values are identical;
the C++ kernel rebuilds cleanly and op_tests/test_quant_mxfp4 passes
93/93 (0 regressions).
Co-authored-by: Cursor <[email protected]>
* fix(test_quant_mxfp4): restrict default round_modes to [2] on non-gfx950
CI on MI300X (gfx942) was failing in shard 4 because the new mode 0 / 1 / 3
byte-level coverage compares the kernel output against a CPU Python ref.
On gfx942 the kernel takes the ``even_round_e2m1`` SW fallback path, while
the Python ref uses ``fp32_to_e2m1_rha``. The two are algorithmically
identical, but GPU fp32 vs CPU fp32 can disagree by <=1 ULP at the FP4
round thresholds (5.0 / 3.5 / 2.5 / 1.75 / 1.25 / 0.75 / 0.25), which is
enough to break ``torch.equal`` even though the rounded result is correct.
Mode 2 (Even) is unaffected: the +0x200000 mantissa bump moves amax away
from those thresholds, and it was the only mode validated on gfx942 before
this PR. Keep it as the default on non-gfx950 GPUs so CI stays green.
The full 4-mode sweep is preserved on gfx950 (HW builtin v_cvt_pk_f4_*
does exact RNE, byte-equal across all 4 modes), and users can still opt in
on gfx942 with ``--round_mode 0 1 2 3``.
Co-authored-by: Cursor <[email protected]>
* fix fp4 in gfx942
* refactor(flydsl): extract FP4/FP8 quant IR builders into quant_utils.py
The FlyDSL ``silu_and_mul_fq`` and ``mixed_moe_gemm_2stage`` kernels both
inline the same three IR-builder snippets:
- ``f32 -> fp4 (e2m1)`` round-to-nearest-even conversion
- FP4 NV ROUND_UP block scale: ``ceil_pow2(amax / 6)``
- FP8 legacy Group D 1.5-threshold round-up block scale
Move them into ``aiter/ops/flydsl/kernels/quant_utils.py`` and rewrite the
two kernels as thin callers. The helpers emit identical MLIR/LLVM IR (MLIR
const-folds the duplicated constants), so the bit-level quant output is
unchanged.
Validated on gfx950 (mi355):
- test_flydsl_swiglu_fused_fp4_quant_matches_reference: PASS (byte-level
vs ``per_1x32_f4_quant`` Python ref)
- test_flydsl_{stage1,stage2,e2e}_a4w4: 3/3 PASS
Net diff: 2 callers -105 lines, +1 new helper module +151 lines, +34 lines
in caller imports.
Co-authored-by: Cursor <[email protected]>
* refactor(flydsl/quant_utils): generic emit_mx_e8m0_scale with mode + dtype dispatch
Mirrors PyTorch torchao's ``to_mx(scaling_mode, elem_dtype)`` design 1:1:
the four E8M0 rounding modes (FLOOR / RCEIL / CEIL / EVEN) are
dtype-agnostic across the MX format family (mxfp4 / mxfp6 / mxfp8 /
mxint8) and only ``target_max_pow2`` / ``max_pos`` / ``mbits`` constants
differ between dtypes.
New surface:
- ``MxScaleRoundMode`` ``IntEnum`` (re-defined here so the FlyDSL build
path stays self-contained; values match the HIP-side enum and
``aiter.ops.quant.MxScaleRoundMode`` 1:1, with a runtime parity assert
passing on import)
- ``MxDtype`` ``IntEnum`` (FP4_E2M1 / FP8_E4M3; FP8_E5M2 / FP6_* reserved)
- ``emit_mx_e8m0_scale(local_max, *, mode, dtype)`` -- generic entry
point, all four modes implemented for both supported dtypes
Kept for callers / git history:
- ``emit_fp4_e8m0_scale_round_up(local_max)`` -- thin alias for
``emit_mx_e8m0_scale(mode=RoundUp, dtype=FP4_E2M1)`` (BC; existing
FlyDSL fp4 callers keep working unchanged)
- ``emit_fp8_e8m0_scale_round_up_legacy(local_max, *, headroom_i32)`` --
unchanged; aiter-specific Group D 1.5-threshold round-up that is *not*
part of the torchao 4-mode family. Migrating it to
``emit_mx_e8m0_scale(mode=RoundUp, dtype=FP8_E4M3)`` (NV
TransformerEngine / DeepSeek-V3.1 ``scale_fmt=ue8m0`` semantics) is a
follow-up PR.
- ``emit_f32_to_e2m1`` -- unchanged.
Validated on gfx950 (mi355) via cache-miss rebuild of FlyDSL kernels:
- test_flydsl_swiglu_fused_fp4_quant_matches_reference: PASS (byte-
level vs ``per_1x32_f4_quant`` Python ref)
- test_flydsl_{stage1, stage2, e2e}_a4w4: 3/3 PASS
The emit_fp4_e8m0_scale_round_up wrapper produces IR identical to the
prior implementation since RoundUp/FP4_E2M1 dispatches to the same four
arith ops as before.
Co-authored-by: Cursor <[email protected]>
* refactor(fp4_utils): generic f32_to_mx_e8m0_scale with mode + dtype dispatch
CPU-side counterpart of the FlyDSL ``emit_mx_e8m0_scale(local_max, mode,
dtype)`` IR builder. Mirrors PyTorch torchao's ``to_mx(scaling_mode,
elem_dtype)`` 1:1: the four E8M0 rounding modes (FLOOR / RCEIL / CEIL /
EVEN) are dtype-agnostic across the MX format family (mxfp4 / mxfp6 /
mxfp8 / mxint8) and only ``target_max_pow2`` / ``max_pos`` / ``mbits``
constants differ between dtypes.
New surface:
- ``MxScaleRoundMode`` ``IntEnum`` (re-defined here to avoid a circular
import with ``aiter.ops.quant``; values match the HIP-side enum,
``aiter.ops.quant.MxScaleRoundMode``, and the FlyDSL
``aiter.ops.flydsl.kernels.quant_utils.MxScaleRoundMode`` 1:1)
- ``MxDtype`` ``IntEnum`` (FP4_E2M1 / FP8_E4M3; FP8_E5M2 / FP6_* reserved)
- ``f32_to_mx_e8m0_scale(amax, *, mode, dtype)`` -- generic CPU torch ref,
all four modes implemented for both supported dtypes
- ``_f32_to_e8m0_floor_impl`` / ``_f32_to_e8m0_ceil_impl`` -- low-level
primitives shared by the generic dispatcher and legacy wrappers
Kept for callers / git history (now thin wrappers around the primitives):
- ``f32_to_e8m0(x)`` -- caller passes ``amax / divisor``
- ``f32_to_e8m0_ceil(x)`` -- caller passes ``amax / divisor``
- ``f32_to_e8m0_floor`` (alias of ``f32_to_e8m0``)
- ``f32_to_e8m0_rceil(amax, max_pos=6.0)``
- ``f32_to_e8m0_torchao_ceil(amax, max_pow2=4.0)``
- ``f32_to_e8m0_even(amax, max_pow2=4.0)``
These produce byte-identical output to the prior implementations:
existing callers in ``aiter.ops.quant.per_1x32_f4_quant`` and
``op_tests/test_activation.py`` keep working unchanged.
Validated on gfx950 (mi355):
- 4-layer enum parity (HIP / aiter.ops.quant / fp4_utils / FlyDSL
quant_utils) verified at runtime
- 5 legacy wrapper paths byte-equal vs the new generic entry point
across both FP4_E2M1 and FP8_E4M3 dtype configs
- test_quant_mxfp4: 92 PASS / 0 FAIL / 2 SKIP (unchanged from prior
commits)
- Invalid mode and invalid dtype both raise ValueError with helpful
messages
Future work: align FlyDSL FP8 path's Group D 1.5-threshold helper to
``mode=RoundUp, dtype=FP8_E4M3`` (NV TransformerEngine MXFP8 / DeepSeek-
V3.1 ``scale_fmt=ue8m0``) -- the infrastructure is now in place.
Co-authored-by: Cursor <[email protected]>
* refactor(quant): unify MxScaleRoundMode + MxDtype to a single source of truth
Before this commit the same ``MxScaleRoundMode`` IntEnum was independently
defined three times (``aiter.ops.quant``, ``aiter.utility.fp4_utils``,
``aiter.ops.flydsl.kernels.quant_utils``) with parallel runtime parity
asserts to keep the four integer values in sync; ``MxDtype`` was defined
twice. The duplication was a workaround for a circular import:
``aiter.ops.quant`` already imports ``aiter.utility.fp4_utils``, so neither
side could re-use the other's enum.
This commit introduces ``aiter.utility.mx_types`` as the single source of
truth. It depends only on ``enum.IntEnum`` and is safe to import from any
layer:
C++ HIP enum (csrc/include/fp4_quant_utils.h::MxScaleRoundMode)
| (manual sync, values 0..3 -- documented invariant)
v
aiter.utility.mx_types <-- single Python source of truth
^ ^ ^
| | |
aiter.utility aiter.ops.quant aiter.ops.flydsl.kernels
.fp4_utils (BC alias kept: .quant_utils
MxFp4RoundMode =
MxScaleRoundMode)
After this commit ``MxScaleRoundMode`` is genuinely a single class object
across all four import paths (verified by class-identity ``is``-comparison,
not just integer-value equality). Removing the duplicates also drops the
runtime parity assert chain.
Validated on gfx950 (mi355):
- Same class identity across all 4 import paths
- test_quant_mxfp4: 92 PASS / 0 FAIL
- test_flydsl_swiglu_fused_fp4_quant_matches_reference: PASS
- test_flydsl_{stage1,stage2,e2e}_a4w4: 3/3 PASS
- quant_mxfp4_hip(round_mode=int / new enum / MxFp4RoundMode alias)
byte-equal across all 4 modes
Co-authored-by: Cursor <[email protected]>
* refactor(fp4_quant_utils.h): generic fp_f32_to_e8m0_scale<mode, dtype> template
C++ analogue of the Python ``aiter.utility.fp4_utils.f32_to_mx_e8m0_scale``
and FlyDSL ``emit_mx_e8m0_scale`` 4-mode dispatchers, mirroring PyTorch
torchao's ``to_mx(scaling_mode, elem_dtype)`` 1:1.
New surface:
- ``MxDtype`` enum (FP4_E2M1 / FP8_E4M3) -- 1:1 with
``aiter.utility.mx_types.MxDtype``
- ``MxDtypeConfig<dtype>`` template specializations holding dtype-specific
``target_max_pow2`` / ``max_pos`` / ``inv_max_pos`` / ``inv_max_pow2`` /
``mbits`` / ``even_val_to_add`` constants
- ``fp_f32_to_e8m0_scale<rmode, dtype>(amax)`` -- single generic template
implementing all four formulas via ``if constexpr``; default
``rmode=RoundUp, dtype=FP4_E2M1`` matches the existing default. Both
template parameters are compile-time constants (selected by the
caller's switch over runtime ``round_mode``), so the branch is fully
resolved before codegen -- no runtime dispatch overhead.
Existing ``fp4_f32_to_e8m0_scale`` / ``_roundup`` / ``_ocp`` / ``_ceil``
helpers are now thin aliases wrapping the generic template; their
signatures and IR output are unchanged, so all callers
(``csrc/kernels/quant_kernels.cu``, ``csrc/kernels/quant_mxfp4.cu``) keep
working.
New helper ``fp4_f32_to_e8m0_scale_even`` -- previously the EVEN formula
was inlined in ``quant_mxfp4.cu``'s template kernel; the standalone helper
makes it reusable for future MXFP4 callers (e.g. extending
``dynamic_per_group_scaled_quant_kernel`` to all four modes). The inline
EVEN path in ``quant_mxfp4.cu`` is left as-is in this commit to keep the
scope minimal.
Validated on gfx950 (mi355) via ``rm -f module_quant.so && python
op_tests/test_quant_mxfp4.py``: 92 PASS / 0 FAIL across all four modes
(RoundDown / RoundUp / Even / Ceil) and both bf16 / fp16 inputs --
unchanged from prior commits. Future MXFP8 callers can reach the
RCEIL formula directly via
``fp_f32_to_e8m0_scale<RoundUp, FP8_E4M3>(amax)`` (= NV TransformerEngine
MXFP8, NV cuBLAS Blackwell, DeepSeek-V3.1 ``scale_fmt=ue8m0``).
Co-authored-by: Cursor <[email protected]>
* refactor(quant): rename csrc/include/fp4_quant_utils.h -> mx_quant_utils.h
The header now hosts the dtype-agnostic ``MxScaleRoundMode`` /
``MxDtype`` enums, the ``MxDtypeConfig<dtype>`` constants, and the
generic ``fp_f32_to_e8m0_scale<rmode, dtype>`` template that supports
the whole MX format family (mxfp4 / mxfp6 / mxfp8 / mxint8). The old
``fp4_*`` name was a leftover from when only fp4 was implemented.
The new name parallels the Python side's ``aiter/utility/mx_types.py``
and the FlyDSL ``aiter/ops/flydsl/kernels/quant_utils.py``: all three
use the ``mx_`` prefix to denote MX-format-family code.
Mechanical rename only -- no logic changes:
- csrc/include/fp4_quant_utils.h -> csrc/include/mx_quant_utils.h
(git-detected rename, file content unchanged)
- 6 ``#include "fp4_quant_utils.h"`` -> ``#include "mx_quant_utils.h"``
in csrc/kernels/{activation,dsv4_rotate,fused_qk_rmsnorm_group,
quant,quant_mxfp4,rmsnorm}_*.cu
- 3 Python docstring path references updated in aiter/utility/mx_types.py,
aiter/ops/flydsl/kernels/quant_utils.py, aiter/utility/fp4_utils.py
- 1 inline comment in csrc/kernels/quant_mxfp4.cu
Validated on gfx950 (mi355): ``rm -f module_quant.so && python
op_tests/test_quant_mxfp4.py`` -> 92 PASS / 0 FAIL across all four
MxScaleRoundMode values and both bf16 / fp16 inputs (unchanged).
The internal documentation file ``csrc/kernels/quant.md`` (untracked)
still references the old name in a few places; it will be updated
along with the next quant.md revision.
Co-authored-by: Cursor <[email protected]>
* refactor(quant): expose MxScaleRoundMode + MxDtype via pybind11 (single C++ source)
The C++ ``enum class MxScaleRoundMode`` / ``MxDtype`` definitions in
``csrc/include/mx_quant_utils.h`` are now exported to Python via
pybind11 in ``rocm_ops.hpp::AITER_CORE_PYBIND``, mirroring the existing
pattern used by ``ActivationType`` / ``QuantType``. Python's
``aiter.utility.mx_types`` imports them through aiter's JIT loader so all
three Python layers (``aiter.utility.fp4_utils``, ``aiter.ops.quant``,
``aiter.ops.flydsl.kernels.quant_utils``) end up with the **same**
``MxScaleRoundMode`` / ``MxDtype`` class object as the HIP kernels --
verified by class-identity ``is``-comparison across all four import
paths. The previous three independent Python ``IntEnum`` re-definitions
are now removed.
Changes:
- csrc/include/rocm_ops.hpp: ``#include "mx_quant_utils.h"`` and add
``pybind11::enum_<MxScaleRoundMode>`` / ``pybind11::enum_<MxDtype>``
registration with ``implicitly_convertible<int>``
- aiter/jit/utils/torch_guard.py: list ``_MxScaleRoundMode`` /
``_MxDtype`` in NONE_WRAPPED_OP so the @compile_ops decorator skips
torch.library.infer_schema (matches existing pattern for
``_ActivationType`` / ``_QuantType``)
- aiter/utility/mx_types.py: rewrite as @compile_ops thin loader,
extract enum class via ``type(_factory(0))``
- aiter/utility/fp4_utils.py / aiter/ops/quant.py /
aiter/ops/flydsl/kernels/quant_utils.py: drop local ``IntEnum``
re-definitions; ``from .mx_types import ...`` is unchanged
BC fix: pybind11 enum classes do **not** auto-compare equal to ``int``
(unlike ``IntEnum``: ``MxScaleRoundMode.RoundUp == 1`` was True for
IntEnum but False for pybind enum). All ``if mode == MxScaleRoundMode.X``
comparisons in the three Python layers now go through ``int(...)`` on
both sides; the same normalisation applies to ``_DTYPE_CFG`` dict keys.
``int(round_mode)`` cast still works as before, ``isinstance(x, int)``
checks now return ``False`` for the pybind enum (was True for IntEnum) --
no internal aiter code path relies on the latter.
Validated on gfx950 (mi355) after ``rm -rf aiter/jit/build/module_aiter_core
aiter/jit/module_aiter_core.so`` to force full hipcc rebuild:
- 4-layer class identity (``aiter.utility.{mx_types,fp4_utils}`` /
``aiter.ops.quant`` / ``aiter.ops.flydsl.kernels.quant_utils``) all
refer to the same pybind class object (``is``-comparison)
- test_quant_mxfp4: 92 PASS / 0 FAIL (4 modes via bare-int and pybind
enum dispatch byte-equal)
- test_flydsl_swiglu_fused_fp4_quant_matches_reference: PASS
- test_flydsl_{stage1,stage2,e2e}_a4w4: 3/3 PASS
Co-authored-by: Cursor <[email protected]>
* feat(quant): add MxDtype::FP8_E4M3_FNUZ for AMD gfx942 hardware FP8
AMD gfx942 (MI300 family) uses FP8 e4m3fnuz, which has a different
exponent bias (8 vs 7 for OCP / NVIDIA H100 / gfx950 e4m3fn). This
shifts max_normal from 448 down to 240 and the largest power-of-2
target from 256 (= 2^8) down to 128 (= 2^7). The four MX scale
rounding modes apply identically -- only the dtype-specific constants
change -- so we just add a new ``MxDtype::FP8_E4M3_FNUZ`` enum value
and a matching ``MxDtypeConfig`` template specialization; the generic
``fp_f32_to_e8m0_scale<rmode, dtype>`` automatically picks the right
constants at compile time.
Mirrors PyTorch's ``torch.float8_e4m3fnuz`` distinction (introduced
when ROCm needed a hardware FP8 format predating the OCP MX
specification).
Changes:
- csrc/include/mx_quant_utils.h: add ``MxDtype::FP8_E4M3_FNUZ`` enum
value, ``MxDtypeConfig<FP8_E4M3_FNUZ>`` specialization
(target_max_pow2=7, max_pos=240, mbits=3, even_val_to_add=0x80000)
- csrc/include/rocm_ops.hpp: pybind11 binding ``.value("FP8_E4M3_FNUZ",
aiter::MxDtype::FP8_E4M3_FNUZ)``
- aiter/utility/fp4_utils.py: ``_DTYPE_CFG`` adds ``FP8_E4M3_FNUZ``
entry ``(7, 240.0, 3)``
- aiter/ops/flydsl/kernels/quant_utils.py: ``_DTYPE_CFG`` adds
``FP8_E4M3_FNUZ`` entry ``(7, 0x3B888889, 3)`` # 1/240.0 fp32 bits
Drive-by fix in the same dict: corrected the FP8_E4M3 reciprocal hex
in flydsl/quant_utils.py from ``0x3B125641`` (incorrect) to
``0x3B124925`` (= fp32 bit pattern of 1.0/448.0). The dict entry was
not yet consumed by any FlyDSL caller (FP8 path still uses the legacy
1.5-threshold helper), so this fix is a forward-looking correctness
patch with no observable behavior change.
Validated on gfx950 (mi355) after forced module_aiter_core rebuild:
- MxDtype.FP8_E4M3_FNUZ = 2 visible from Python via mx_types pybind
binding; ``f32_to_mx_e8m0_scale(amax, mode=RoundUp,
dtype=FP8_E4M3_FNUZ)`` returns the expected
``ceil_pow2(amax / 240)`` for amax in {100, 240, 240+epsilon, 480}
-> {0.5, 1.0, 2.0, 2.0}
- test_quant_mxfp4: 92 PASS / 0 FAIL (FP4 path unchanged)
- test_flydsl_swiglu_fused_fp4_quant_matches_reference + a4w4
stage1/stage2/e2e: 4 PASSED (FP4 path unchanged)
Co-authored-by: Cursor <[email protected]>
* docs(quant): de-duplicate 4-mode docstrings; reference MxScaleRoundMode
Three Python entry points (``f32_to_mx_e8m0_scale``, ``emit_mx_e8m0_scale``,
``per_1x32_f4_quant`` / ``quant_mxfp4_hip``) were each carrying the same
~12-line description of the four MxScaleRoundMode formulas (FLOOR /
RCEIL / CEIL / EVEN), with cross-stack mapping to torchao / NV / DSv4 /
Quark naming. After making :class:`MxScaleRoundMode` the single source
of truth via the pybind11 binding (commit 0e1d493) and centralising
the C++-side docs in ``csrc/include/mx_quant_utils.h`` plus the
cross-stack table in ``csrc/kernels/quant.md``, those four function
docstrings only need to point at the canonical reference.
Replace the four duplicated mode lists with a one-paragraph "see
:class:\`MxScaleRoundMode\` and ``csrc/kernels/quant.md``" pointer;
keep the function-specific behaviour notes (e.g. ``Even`` mode's
gfx950 HW builtin vs gfx942 SW fallback distinction in
``quant_mxfp4_hip``).
Pure docstring cleanup: net -31 lines, no logic / runtime change.
Co-authored-by: Cursor <[email protected]>
* docs(flydsl/quant_utils): trim redundant compile-time note from emit_mx_e8m0_scale
Remove duplicate FlyDSL compile-time branching explanation already covered
by the central MxScaleRoundMode / quant.md documentation.
Co-authored-by: Cursor <[email protected]>
* docs(quant): drop quant.md references from MX scale mode comments
Point docstrings at MxScaleRoundMode and inline cross-stack naming instead
of linking to the local quant.md notes file.
Co-authored-by: Cursor <[email protected]>
* fix(flydsl): remove dead IR constants after quant_utils refactor
Drop unused E8M0/FP4 scale literals left in silu_and_mul_fq after moving
scale and f32->fp4 emission to shared quant_utils helpers (ruff F841).
Co-authored-by: Cursor <[email protected]>
* fix(flydsl): keep mx_types as single source via lazy pybind enum loading
The previous attempt duplicated MODE_*/DTYPE_* int constants inside
quant_utils.py to avoid triggering module_aiter_core JIT during wheel
PREBUILD_KERNELS. That worked but spread the C++ enum values across two
Python files.
Refactor mx_types.py instead: expose JIT-free MxScaleRoundModeInt /
MxDtypeInt mirror classes alongside the pybind11 MxScaleRoundMode /
MxDtype enums, and load the pybind enums lazily via PEP 562 module
__getattr__. Importing mx_types is now JIT-free; FlyDSL imports only
the int mirrors so wheel PREBUILD remains safe, and the lazy loader
asserts int values match the pybind enum on first attribute access to
catch C++/Python drift.
Co-authored-by: Cursor <[email protected]>
* feat(flydsl): align MXFP8 to NV ROUND_UP, unify FP4/FP8 scale call sites
Migrate the FlyDSL MXFP8 path in silu_and_mul_fq and mixed_moe_gemm_2stage
from the legacy aiter Group D round_pow2_1.5 formula to the industry
default NV ROUND_UP / torchao RCEIL formula (ceil_pow2(amax / max_pos)),
matching the HIP / CPU FP8 paths and NV TransformerEngine MXFP8.
The FP8 element dtype is now selected by HW arch via get_hip_arch():
gfx942 ships e4m3fnuz (max_pos=240), gfx950+ ships OCP e4m3fn (max_pos=448).
The previous legacy formula hardcoded headroom=8 (i.e. max_pow2=256), which
saturated frequently on gfx942 (240 < 256).
FP4 and FP8 now share a single emit_mx_e8m0_scale call site -- only the
``dtype`` parameter differs. The legacy emit_fp4_e8m0_scale_round_up and
emit_fp8_e8m0_scale_round_up_legacy helpers, plus the headroom plumbing
(_fp_headroom / _c_headroom_i32 / _c8_i32) are removed.
Also harden emit_mx_e8m0_scale with a minsi(0xFF) upper clamp so
pathological inputs (denormal / fp32 inf carry) cannot overflow the u8
storage byte.
This is a numerical change for the FP8 path: per-block scales differ
from the legacy formula (sweep results may shift slightly for a8w4).
Co-authored-by: Cursor <[email protected]>
* feat(flydsl): align qk_norm_rope_quant E8M0 path to NV ROUND_UP
Migrate the e8m0 scale path in flydsl_qk_norm_rope_quant from the legacy
round_pow2_1.5(amax) / 2^7 formula to the industry default NV ROUND_UP /
torchao RCEIL ceil_pow2(amax / max_pos) formula via the shared
emit_mx_e8m0_scale helper. The fp32 scale path (rstd-cancellation
algebra) is unchanged.
The FP8 element dtype is now selected by HW arch via get_hip_arch():
gfx942 -> e4m3fnuz (max_pos=240), gfx950+ -> OCP e4m3fn (max_pos=448).
Previously the kernel hardcoded headroom=7 (sized for e4m3fnuz/240),
which was 1 bit too tight on gfx950 and over-clipped the fp8 dynamic
range there. The shared helper picks the right max_pos per dtype.
Update the torch reference in op_tests/test_flydsl_qk_norm_rope_quant.py
to use the same NV ROUND_UP formula (amax * inv_max_pos_f32 mirrors the
kernel exactly, avoiding 1-ULP drift from amax / max_pos).
Co-authored-by: Cursor <[email protected]>
* fix(quant): mxfp4_quant_moe_sort_kernel FP8 e8m0 used wrong formula
The FP8 branch in mxfp4_quant_moe_sort_kernel computed:
row_scale = aiter::fp4_f32_to_e8m0_scale(absMax) * (1 / floor_pow2(FP8_MAX))
= ceil_pow2(absMax / 6) / 256 (gfx950, FP8_MAX=448)
= ceil_pow2(absMax / 6) / 128 (gfx942, FP8_MAX=240)
which mistakenly applies the FP4 helper (max_pos=6) and patches it with
1/floor_pow2(FP8_MAX). The resulting `factor * absMax = 1 / row_scale * absMax`
ranges 1.8x-3.4x of FP8_MAX across realistic amax values, so the kernel was
over-scaling and saturating ~34% of elements on a representative bf16 input
(max abs error 4.50, mean 0.264).
Switch the FP8 branch to the correct NV ROUND_UP formula via the generic
helper:
row_scale = aiter::fp_f32_to_e8m0_scale<RoundUp, FP8_E4M3{_FNUZ}>(absMax)
= ceil_pow2(absMax / max_pos)
which gives `factor * absMax <= max_pos` by construction (no saturation).
The HW FP8 element dtype is selected at compile time via __gfx942__:
gfx942 -> e4m3fnuz (max_pos=240), gfx950+ -> OCP e4m3fn (max_pos=448).
After fix on the same bf16 input: max abs error 0.25 (18x better), mean
0.027 (9.78x better), saturated elements 0.30% (was 33.74%).
The FP4 branch is also routed through the generic helper for symmetry;
it expands to the same code as the previous fp4_f32_to_e8m0_scale call,
so MXFP4 outputs remain byte-exact (verified via test_moe_sorting_mxfp4).
Co-authored-by: Cursor <[email protected]>
* fix(flydsl): _mx_dtype unbound in FlyDSL AOT trace of stage1 quant kernels
Wheel build_aiter_wheels broke with `name '_mx_dtype' is not defined` on
~12 stage1 fp4/fp8-quant kernel variants during FlyDSL AOT
(`mxfp4_quant_moe_sort_kernel` / `mixed_moe_gemm_2stage` `_moe_gemm1_body`
and `silu_and_mul_fq_kernel`).
Root cause: I split the ``_mx_dtype`` assignment across an
``if/elif/else`` block. FlyDSL's AOT trace path appears to inspect the
nested ``store_pair`` closure cell before all branches of the outer
if/elif/else have executed, so on the path the trace takes the cell can
be unbound. The original ``_fp_headroom`` plumbing this commit is
replacing used a single-statement ternary and was always bound at
definition time, which avoided this.
Restore the same single-statement ternary pattern. The bf16 (no-quant)
fallback dtype is FP4_E2M1 as a placeholder; the call site is guarded
by ``const_expr(_need_quant)`` so the placeholder is never observed.
Verified by re-running ``PREBUILD_KERNELS=1 GPU_ARCHS=gfx950 python
setup.py bdist_wheel`` in the build container: MOE: 0 failed, GEMM: 0
failed (the only remaining failures are the pre-existing chunk_gdn_h
``Cannot re-initialize CUDA in forked subprocess`` issue, unrelated).
Co-authored-by: Cursor <[email protected]>
* refactor(quant): drop unused FP4 BC scale aliases, route pure-FP4 callers through default helper
Drops the legacy thin-wrapper surface that was only kept for back-compat
during the MX-format unification work, and consolidates pure-FP4 / pure-
RoundUp call sites onto the single named helper
``fp4_f32_to_e8m0_scale`` (= ``fp_f32_to_e8m0_scale<RoundUp, FP4_E2M1>``).
Removed (no remaining callers in-tree):
C++ (csrc/include/mx_quant_utils.h):
- ``fp4_f32_to_e8m0_scale_roundup``
- ``fp4_f32_to_e8m0_scale_ocp``
- ``fp4_f32_to_e8m0_scale_ceil``
- ``fp4_f32_to_e8m0_scale_even``
Python (aiter/utility/fp4_utils.py):
- ``f32_to_e8m0`` / ``f32_to_e8m0_floor`` / ``f32_to_e8m0_ceil``
- ``f32_to_e8m0_rceil`` / ``f32_to_e8m0_even``
- ``f32_to_e8m0_torchao_ceil``
Retained as the single MXFP4 default convenience entry on both sides:
- C++ ``aiter::fp4_f32_to_e8m0_scale(amax)``
- Py ``aiter.utility.fp4_utils.fp4_f32_to_e8m0_scale(amax)``
Both are 1-line forwarders to the generic
``fp_f32_to_e8m0_scale<rmode, dtype>`` (C++) /
``f32_to_mx_e8m0_scale(mode, dtype)`` (Python) so future default-mode
changes are a one-line edit.
Call site policy:
* Pure FP4 / RoundUp sites use ``fp4_f32_to_e8m0_scale`` (9 sites in
``dsv4_rotate_quant.cu``, ``quant_kernels.cu``,
``activation_kernels.cu``, ``fused_qk_rmsnorm_group_quant.cu``,
``rmsnorm_quant_kernels.cu``, ``op_tests/test_activation.py``).
* Multi-mode dispatch in ``quant_mxfp4.cu`` (4-mode switch) keeps the
explicit ``<rmode, FP4_E2M1>`` form so the four branches stay
visually parallel.
* FP8 sibling branches in ``quant_kernels.cu``
(``mxfp4_quant_moe_sort_kernel``) keep the explicit
``<RoundUp, kHwFp8Dtype>`` form (no fixed FP8 alias).
``aiter/ops/quant.py::per_1x32_f4_quant`` migrated from the per-mode
``f32_to_e8m0_floor/_rceil/_even/_torchao_ceil`` BC helpers to the
unified ``f32_to_mx_e8m0_scale(mode, dtype=FP4_E2M1)`` so all four
rounding modes route through one code path; the existing
``MxScaleRoundMode`` validation behavior is preserved (re-raises with
the same caller-visible message via ``raise ... from e``).
Validated locally on mi355 (gfx950): 92/92 PASS in
``op_tests/test_quant_mxfp4.py`` across all four rounding modes and
both bf16/fp16 inputs; ``op_tests/test_activation.py`` MXFP4 paths
unchanged (byte-exact).
Co-authored-by: Cursor <[email protected]>
* refactor(quant): centralize MX scale round_mode default across all stacks
Add MX_DEFAULT_ROUND_MODE (Python) and kDefaultMxScaleRoundMode (C++) so
changing the project-wide default only requires editing two constants in
lockstep. A runtime drift check (pybind11 m.attr + __getattr__ guard) and
an explicit test_default_round_mode_drift() prevent silent divergence.
* fix(quant): remove unused _M imports flagged by ruff F401
After switching call sites to _DEFAULT_MODE, the MxScaleRoundModeInt
alias _M is no longer referenced in three FlyDSL kernel files.
* fix(quant): route per_1x32_f8_scale_f8_quant fp8 ref through MX_DEFAULT_ROUND_MODE
The fp8 reference computed its e8m0 scale via the legacy
fp4_utils.f32_to_e8m0(amax / floor_pow2(max)) primitive, which bypassed
the centralized MX_DEFAULT_ROUND_MODE and diverged from the RoundUp HIP
kernel by one exponent on ~1/8 of groups (test_moe_sorting_mxfp4.py
--quant-dtype fp8: "hip mxfp8 out" off by +8/byte). Route it through
f32_to_mx_e8m0_scale(mode=MX_DEFAULT_ROUND_MODE, dtype=FP8_E4M3{,_FNUZ})
so the reference honors the project-wide default and matches the kernel
(arch-aware dtype mirrors the kernel's #if __gfx942__ selection).
Co-authored-by: Cursor <[email protected]>
* fix(quant): honor MX_DEFAULT_ROUND_MODE in quant_mxfp4_hip fast-path + qk_norm e8m0 ref
Two spots still hard-coded RoundUp instead of reading the centralized
default, so flipping MX_DEFAULT_ROUND_MODE / kDefaultMxScaleRoundMode in
lockstep did not fully propagate:
- quant_mxfp4_hip routed to the per_1x32_f4_quant_hip fast path on
`round_mode == RoundUp`, but that path derives its scale via
fp_f32_to_e8m0_scale<kDefaultMxScaleRoundMode>. Compare against
MX_DEFAULT_ROUND_MODE so the routing stays correct if the default
changes; non-default modes fall through to the explicit 4-way dispatch.
- test_flydsl_qk_norm_rope_quant._e8m0_encode_ref hard-coded the RoundUp
encoding. Delegate to the shared CPU helper
fp4_utils.f32_to_mx_e8m0_scale(mode=MX_DEFAULT_ROUND_MODE, dtype=FP8_E4M3)
so the test follows the project default through the same single source the
HIP / FlyDSL kernels mirror.
Verified by flipping the default to RoundDown and back: test_quant_mxfp4
(+drift), test_moe_sorting_mxfp4 (fp4/fp8), test_activation and
test_flydsl_qk_norm_rope_quant all pass under both defaults.
Co-authored-by: Cursor <[email protected]>
* revert: restore 10 unrelated files to main (drop stray non-ASCII->ASCII edits)
These files carry no MXFP4/MXFP8 round-mode work; the local pre-commit hook
(.git/hooks/pre-commit) rewrote their comments/strings via
`iconv -t ascii//TRANSLIT` (em-dash, arrows, box-drawing chars, etc.) and
bumped the copyright year while they were merged. Restore them verbatim to
main with --no-verify so the PR diff only contains the quant round-mode
changes (committing normally would let the hook re-mangle them).
Co-authored-by: Cursor <[email protected]>
* make fp4_utils AOT-safe
* fix format
---------
Co-authored-by: Cursor <[email protected]>
Motivation
Technical Details
Test Plan
Test Result
Submission Checklist