Merged
[refactor]optimize quant ops calling to avoid aclnnContiguous_TransposeAiCore_Transpose with best efforts #750
[refactor]optimize quant ops calling to avoid aclnnContiguous_TransposeAiCore_Transpose with best efforts #750
Merged
caoshuyangAdd on Sep 8
Total: 20 files changed+708-456
@@ -89,6 +89,7 @@ venv/
89ENV/89ENV/
90env.bak/90env.bak/
91venv.bak/91venv.bak/
92+.vscode/
92 93 
93# Spyder project settings94# Spyder project settings
94.spyderproject95.spyderproject
@@ -3,8 +3,15 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-from .configs import ParamSwapConfig6+from torchao_npu.configs import ParamSwapConfig
7 7 
8__all__ = [8__all__ = [
9 "ParamSwapConfig",9 "ParamSwapConfig",
10]10]
11+ 
12+ 
13+def normalize_dim(dim: int, ndim: int) -> int:
14+ """Return ``dim`` as a non-negative index into an ``ndim``-D tensor."""
15+ if not -ndim <= dim < ndim:
16+ raise IndexError(f"dim {dim} out of range for {ndim}D tensor")
17+ return dim % ndim
@@ -5,7 +5,7 @@
5 5 
6"""Public quantization configurations for torchao-npu."""6"""Public quantization configurations for torchao-npu."""
7 7 
8-from .param_swap import ParamSwapConfig8+from torchao_npu.configs.param_swap import ParamSwapConfig
9 9 
10__all__ = [10__all__ = [
11 "ParamSwapConfig",11 "ParamSwapConfig",
@@ -15,12 +15,12 @@ from torchao.quantization.qat.fake_quantize_config import (
15from torchao.quantization.quant_api import Float8DynamicActivationFloat8WeightConfig15from torchao.quantization.quant_api import Float8DynamicActivationFloat8WeightConfig
16from torchao.quantization.transform_module import register_quantize_module_handler16from torchao.quantization.transform_module import register_quantize_module_handler
17 17 
18-from ..quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data18+from torchao_npu.quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data
19-from ..quantization.quant_configs import (19+from torchao_npu.quantization.quant_configs import (
20- BlockQuantizeConfig,20+ BlockMXQuantizeConfig,
21 MXQuantizeConfig,21 MXQuantizeConfig,
22)22)
atomgit-bot

🟡 Medium Priority

changed line:本 diff 将 BlockQuantizeConfig/Block FP8 系列统一改名为 BlockMXQuantizeConfig/Block MX(见 param_swap.py L19-22 及本 PR 中 quant_configs.py、wrapper_tensors 的同名重构),param_swap.py 的导入也随之切换为新类名。

affected behavior/contract:该重构是一次“单向”改名——同属本 PR 改动的 quant_configs.py 中已删除 BlockQuantizeConfig(当前只导出 MXQuantizeConfig/BlockMXQuantizeConfig),wrapper_tensors/init.py 也只导出 BlockMXTrainingWeightWrapperTensor,但未被本 PR 触碰的 tests/test_wrapper_storage_delegation.py 仍然在 L22/L27 等处 from torchao_npu.quantization.quant_configs import BlockQuantizeConfig、from torchao_npu.wrapper_tensors import BlockTrainingWeightWrapperTensor,并在两条用例参数化列表中直接构造 BlockQuantizeConfig()。

failure mode:任意 pytest 收集到该测试模块时即触发 ImportError: cannot import name 'BlockQuantizeConfig' / BlockTrainingWeightWrapperTensor,该文件内两条测试(untyped-storage 委托、data_ptr 委托)全部无法运行,CI 失败。

suggested fix:将测试文件中两处旧符号替换为 BlockMXQuantizeConfig 与 BlockMXTrainingWeightWrapperTensor(用例中 weight/activation 构造参数同步改为新类型);若担心外部兼容性,可在 quant_configs.py / wrapper_tensors/init.py 保留向后兼容别名。注意新 BlockMXQuantizeConfig 构造时无 mxfp4_fake_quantize_config、FP8 默认 scale_alg=0,行为与旧 BlockQuantizeConfig() 默认一致,替换安全。

建议:把 tests/test_wrapper_storage_delegation.py 中对 BlockQuantizeConfig/BlockTrainingWeightWrapperTensor 的导入与构造更新为 BlockMXQuantizeConfig/BlockMXTrainingWeightWrapperTensor(或在删除旧类处保留兼容别名),并跑一遍该测试文件验证导入与用例。

likedislike
Incorrect?
caoshuyang
caoshuyang
Sep 8 Comments:
likedislike
23-from ..quantization.transform import (23+from torchao_npu.quantization.transform import (
24 _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER,24 _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER,
25 _replace_params_with_custom_fn_if_matches_filter,25 _replace_params_with_custom_fn_if_matches_filter,
26 unwrap_param,26 unwrap_param,
@@ -50,8 +50,8 @@ class ParamSwapConfig(QATConfig):
50 (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`),50 (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`),
51 NPU MX block-wise51 NPU MX block-wise
52 (:class:`~torchao_npu.quantization.quant_configs.MXQuantizeConfig`),52 (:class:`~torchao_npu.quantization.quant_configs.MXQuantizeConfig`),
53- and NPU Block FP853+ and NPU Block MX
54- (:class:`~torchao_npu.quantization.quant_configs.BlockQuantizeConfig`).54+ (:class:`~torchao_npu.quantization.quant_configs.BlockMXQuantizeConfig`).
55 """55 """
56 56 
57 def __init__(57 def __init__(
@@ -68,18 +68,21 @@ class ParamSwapConfig(QATConfig):
68 68 
69 def __post_init__(self):69 def __post_init__(self):
70 torch._C._log_api_usage_once("torchao.prototype.param_swap.ParamSwapConfig")70 torch._C._log_api_usage_once("torchao.prototype.param_swap.ParamSwapConfig")
71- if self.activation_config is not None and not isinstance(71+ if self.activation_config is not None and type(self.activation_config) not in (
72- self.activation_config, (Float8FakeQuantizeConfig, MXQuantizeConfig)72+ Float8FakeQuantizeConfig,
73+ MXQuantizeConfig,
73 ):74 ):
74 raise ValueError(75 raise ValueError(
75 "Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` "76 "Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` "
76 "is supported for `activation_config` in ParamSwapConfig yet."77 "is supported for `activation_config` in ParamSwapConfig yet."
77 )78 )
78- if self.weight_config is not None and not isinstance(79+ if self.weight_config is not None and type(self.weight_config) not in (
79- self.weight_config, (Float8FakeQuantizeConfig, MXQuantizeConfig, BlockQuantizeConfig)80+ Float8FakeQuantizeConfig,
81+ MXQuantizeConfig,
82+ BlockMXQuantizeConfig,
80 ):83 ):
81 raise ValueError(84 raise ValueError(
82- "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockQuantizeConfig` "85+ "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockMXQuantizeConfig` "
83 "is supported for `weight_config` in ParamSwapConfig yet."86 "is supported for `weight_config` in ParamSwapConfig yet."
84 )87 )
85 88 
@@ -118,7 +121,7 @@ def _param_swap_config_transform(
118 121 
119 # Handlers are registered as an import side effect of the wrapper tensor modules;122 # Handlers are registered as an import side effect of the wrapper tensor modules;
120 # importing them here populates the registry `_PARAM_SWAP_QUANTIZE_CONFIG_HANDLER` read below.123 # importing them here populates the registry `_PARAM_SWAP_QUANTIZE_CONFIG_HANDLER` read below.
121- from .. import wrapper_tensors # noqa: F401124+ import torchao_npu.wrapper_tensors # noqa: F401
122 125 
123 if config.step == QATStep.PREPARE:126 if config.step == QATStep.PREPARE:
124 assert config.weight_config is not None127 assert config.weight_config is not None
@@ -8,7 +8,7 @@
8Import ops from their concrete submodules; each submodule declares its8Import ops from their concrete submodules; each submodule declares its
9public surface via ``__all__``:9public surface via ``__all__``:
10 10 
11-- :mod:`torchao_npu.ops.block_ops` — Block FP8 matmul ops11+- :mod:`torchao_npu.ops.block_mx_ops` — Block MX matmul ops
12- :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization12- :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization
13- :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops13- :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops
14"""14"""
Rexperiments/torchao-npu/torchao_npu/ops/block_ops.py→experiments/torchao-npu/torchao_npu/ops/block_mx_ops.py+88-109
@@ -3,9 +3,9 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-"""Block FP8 low-precision matmul ops for NPU.6+"""Block MX low-precision matmul ops for NPU.
7 7 
8-Quantization scheme (non-grouped ``to_block_fp8_then_mm``):8+Quantization scheme (non-grouped ``to_block_mx_then_mm``):
9- A (activation): ``npu_dynamic_mx_quant_with_dual_axis``9- A (activation): ``npu_dynamic_mx_quant_with_dual_axis``
10 - s1 = per-32-group scale along dim -1 (``A_s1``)10 - s1 = per-32-group scale along dim -1 (``A_s1``)
11 - s2 = per-32-group scale along dim -2 (``A_s2``)11 - s2 = per-32-group scale along dim -2 (``A_s2``)
@@ -13,7 +13,7 @@ Quantization scheme (non-grouped ``to_block_fp8_then_mm``):
13 - s1 = per-32-group scale along dim -1 (``B_s1``)13 - s1 = per-32-group scale along dim -1 (``B_s1``)
14 - s2 = per-32-group scale along dim -2 (``B_s2``)14 - s2 = per-32-group scale along dim -2 (``B_s2``)
15 15 
16-Quantization scheme (grouped ``to_block_fp8_then_grouped_mm``):16+Quantization scheme (grouped ``to_block_mx_then_grouped_mm``):
17- A (activation), K-dim: ``npu_dynamic_mx_quant(axis=-1)``17- A (activation), K-dim: ``npu_dynamic_mx_quant(axis=-1)``
18- A (activation), M-dim: ``npu_grouped_dynamic_mx_quant``18- A (activation), M-dim: ``npu_grouped_dynamic_mx_quant``
19- B (weight): ``npu_dynamic_block_mx_quant``19- B (weight): ``npu_dynamic_block_mx_quant``
@@ -24,23 +24,22 @@ Quantization scheme (grouped ``to_block_fp8_then_grouped_mm``):
24import torch24import torch
25import torch_npu25import torch_npu
26 26 
27-from ..quantization.quant_configs import (27+from torchao_npu.quantization.quant_configs import (
28- BlockQuantizeConfig,28+ BlockMXQuantizeConfig,
29 MXQuantizeConfig,29 MXQuantizeConfig,
30)30)
31-from ..quantization.quant_primitives.block_fp8 import (31+from torchao_npu.quantization.quant_primitives.block_mx import block_mx_quantize
32- block_fp8_mxfp4_fake_quantize,32+from torchao_npu.quantization.quant_primitives.mx import mx_quantize, mx_quantize_dual_axis
33-)
34 33 
35__all__ = [34__all__ = [
36- "to_block_fp8_then_bmm",35+ "to_block_mx_then_bmm",
37- "to_block_fp8_then_grouped_mm",36+ "to_block_mx_then_grouped_mm",
38- "to_block_fp8_then_mm",37+ "to_block_mx_then_mm",
39]38]
40 39 
41 40 
42-class _BlockFP8QuantMM(torch.autograd.Function):41+class _BlockMXQuantMM(torch.autograd.Function):
43- """Block FP8 matrix multiply: ``A[M,K] @ B[K,N] = Y[M,N]``.42+ """Block MX matrix multiply: ``A[M,K] @ B[K,N] = Y[M,N]``.
44 43 
45 Forward:44 Forward:
46 1. ``A_q1, A_s1, A_q2, A_s2 = npu_dynamic_mx_quant_with_dual_axis(A, **config_A)``45 1. ``A_q1, A_s1, A_q2, A_s2 = npu_dynamic_mx_quant_with_dual_axis(A, **config_A)``
@@ -69,7 +68,7 @@ class _BlockFP8QuantMM(torch.autograd.Function):
69 A: torch.Tensor,68 A: torch.Tensor,
70 B: torch.Tensor,69 B: torch.Tensor,
71 config_A: MXQuantizeConfig,70 config_A: MXQuantizeConfig,
72- config_B: BlockQuantizeConfig,71+ config_B: BlockMXQuantizeConfig,
73 ):72 ):
74 assert A.ndim >= 2, f"A must be >=2D, got {A.ndim}D"73 assert A.ndim >= 2, f"A must be >=2D, got {A.ndim}D"
75 assert A.shape[-2] % config_A.block_size == 0, (74 assert A.shape[-2] % config_A.block_size == 0, (
@@ -80,18 +79,12 @@ class _BlockFP8QuantMM(torch.autograd.Function):
80 79 
81 # --- Step 1: quantize A with dual-axis MX quant ---80 # --- Step 1: quantize A with dual-axis MX quant ---
82 # Flatten leading dims inside the quant call (like MXfp8MM uses view_as_n_dim)81 # Flatten leading dims inside the quant call (like MXfp8MM uses view_as_n_dim)
83- A_q1, A_s1, A_q2, A_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(82+ A_q1, A_s1, A_q2, A_s2 = mx_quantize_dual_axis(A.reshape(-1, A.shape[-1]), config_A)
84- A.reshape(-1, A.shape[-1]),
85- round_mode=config_A.round_mode,
86- dst_type=config_A.elem_dtype,
87- scale_alg=config_A.scale_alg,
88- dst_type_max=config_A.dst_type_max,
89- )
90 83 
91- # --- Step 2: block FP8 quantize B (with optional mxfp4 fake-quant pre-pass) ---84+ # --- Step 2: block MX quantize B (with optional mxfp4 fake-quant pre-pass) ---
92 # B [K, N] → B_s1 (N-dim scale) [K, ceil(ceil(N/32)/2), 2]85 # B [K, N] → B_s1 (N-dim scale) [K, ceil(ceil(N/32)/2), 2]
93 # → B_s2 (K-dim scale) [ceil(ceil(K/32)/2), N, 2]86 # → B_s2 (K-dim scale) [ceil(ceil(K/32)/2), N, 2]
94- B_q, B_s1, B_s2 = block_fp8_mxfp4_fake_quantize(B, axis=-2, config=config_B)87+ B_q, B_s1, B_s2 = block_mx_quantize(B, config=config_B, axis=-2)
95 88 
96 # --- Step 3: low-precision matmul, contracting over K ---89 # --- Step 3: low-precision matmul, contracting over K ---
97 # x1 = A_q1 [M, K] → pertoken_scale = A_s1 [M, ceil(ceil(K/32)/2), 2]90 # x1 = A_q1 [M, K] → pertoken_scale = A_s1 [M, ceil(ceil(K/32)/2), 2]
@@ -102,8 +95,10 @@ class _BlockFP8QuantMM(torch.autograd.Function):
102 B_s2,95 B_s2,
103 pertoken_scale=A_s1,96 pertoken_scale=A_s1,
104 output_dtype=A.dtype,97 output_dtype=A.dtype,
105- scale_dtype=torch_npu.float8_e8m0fnu,98+ scale_dtype=config_B.npu_scale_dtype,
106- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,99+ pertoken_scale_dtype=config_A.npu_scale_dtype,
100+ x1_dtype=config_A.npu_matmul_dtype,
101+ x2_dtype=config_B.npu_matmul_dtype,
107 group_sizes=[1, 1, config_B.block_size],102 group_sizes=[1, 1, config_B.block_size],
108 )103 )
109 104 
@@ -127,13 +122,7 @@ class _BlockFP8QuantMM(torch.autograd.Function):
127 122 
128 # --- Step 1: quantize dY with dual-axis MX quant ---123 # --- Step 1: quantize dY with dual-axis MX quant ---
129 # Flatten leading dims inside the quant call (like MXfp8MM)124 # Flatten leading dims inside the quant call (like MXfp8MM)
130- dY_q1, dY_s1, dY_q2, dY_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(125+ dY_q1, dY_s1, dY_q2, dY_s2 = mx_quantize_dual_axis(dY.reshape(-1, dY.shape[-1]), config_A)
131- dY.reshape(-1, dY.shape[-1]),
132- round_mode=config_A.round_mode,
133- dst_type=config_A.elem_dtype,
134- scale_alg=config_A.scale_alg,
135- dst_type_max=config_A.dst_type_max,
136- )
137 126 
138 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---127 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---
139 # x1 = dY_q1 [M, N] → pertoken_scale = dY_s1 [M, ceil(ceil(N/32)/2), 2]128 # x1 = dY_q1 [M, N] → pertoken_scale = dY_s1 [M, ceil(ceil(N/32)/2), 2]
@@ -144,8 +133,10 @@ class _BlockFP8QuantMM(torch.autograd.Function):
144 B_s1.transpose(0, 1),133 B_s1.transpose(0, 1),
145 pertoken_scale=dY_s1,134 pertoken_scale=dY_s1,
146 output_dtype=A_dtype,135 output_dtype=A_dtype,
147- scale_dtype=torch_npu.float8_e8m0fnu,136+ scale_dtype=config_B.npu_scale_dtype,
148- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,137+ pertoken_scale_dtype=config_A.npu_scale_dtype,
138+ x1_dtype=config_A.npu_matmul_dtype,
139+ x2_dtype=config_B.npu_matmul_dtype,
149 group_sizes=[1, 1, config_B.block_size],140 group_sizes=[1, 1, config_B.block_size],
150 )141 )
151 142 
@@ -159,8 +150,10 @@ class _BlockFP8QuantMM(torch.autograd.Function):
159 dY_s2,150 dY_s2,
160 pertoken_scale=A_s2.transpose(0, 1),151 pertoken_scale=A_s2.transpose(0, 1),
161 output_dtype=A_dtype,152 output_dtype=A_dtype,
162- scale_dtype=torch_npu.float8_e8m0fnu,153+ scale_dtype=config_A.npu_scale_dtype,
163- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,154+ pertoken_scale_dtype=config_A.npu_scale_dtype,
155+ x1_dtype=config_A.npu_matmul_dtype,
156+ x2_dtype=config_A.npu_matmul_dtype,
164 group_sizes=[1, 1, config_B.block_size],157 group_sizes=[1, 1, config_B.block_size],
165 )158 )
166 159 
@@ -171,19 +164,19 @@ class _BlockFP8QuantMM(torch.autograd.Function):
171 return dA, dB, None, None164 return dA, dB, None, None
172 165 
173 166 
174-def to_block_fp8_then_mm(167+def to_block_mx_then_mm(
175 A: torch.Tensor,168 A: torch.Tensor,
176 B: torch.Tensor,169 B: torch.Tensor,
177 config_A: MXQuantizeConfig,170 config_A: MXQuantizeConfig,
178- config_B: BlockQuantizeConfig,171+ config_B: BlockMXQuantizeConfig,
179) -> torch.Tensor:172) -> torch.Tensor:
180- """Block FP8 matrix multiply: ``A @ B`` with mixed-format quantization.173+ """Block MX matrix multiply: ``A @ B`` with mixed-format quantization.
181 174 
182 Quantization scheme:175 Quantization scheme:
183 - A: ``npu_dynamic_mx_quant_with_dual_axis`` (params from ``config_A``)176 - A: ``npu_dynamic_mx_quant_with_dual_axis`` (params from ``config_A``)
184 - B: ``npu_dynamic_block_mx_quant``, 32×32 blocks (params from ``config_B``)177 - B: ``npu_dynamic_block_mx_quant``, 32×32 blocks (params from ``config_B``)
185 178 
186- See ``_BlockFP8QuantMM`` for details of the three GEMMs.179+ See ``_BlockMXQuantMM`` for details of the three GEMMs.
187 180 
188 Args:181 Args:
189 A: Shape ``(M, K)``.182 A: Shape ``(M, K)``.
@@ -194,11 +187,11 @@ def to_block_fp8_then_mm(
194 Returns:187 Returns:
195 Output tensor, shape ``(M, N)``, dtype matching ``A``.188 Output tensor, shape ``(M, N)``, dtype matching ``A``.
196 """189 """
197- return _BlockFP8QuantMM.apply(A, B, config_A, config_B)190+ return _BlockMXQuantMM.apply(A, B, config_A, config_B)
198 191 
199 192 
200-class _BlockFP8QuantGroupedMM(torch.autograd.Function):193+class _BlockMXQuantGroupedMM(torch.autograd.Function):
201- """Block FP8 grouped matmul: ``A[M,K] @ B[E,K,N] = Y[M,N]``.194+ """Block MX grouped matmul: ``A[M,K] @ B[E,K,N] = Y[M,N]``.
202 195 
203 Rows of ``A`` are partitioned into ``E`` groups via ``group_list``196 Rows of ``A`` are partitioned into ``E`` groups via ``group_list``
204 (cumsum offsets, length ``E``). Each slice ``A[group_list[i-1]:group_list[i]]``197 (cumsum offsets, length ``E``). Each slice ``A[group_list[i-1]:group_list[i]]``
@@ -248,7 +241,7 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
248 B: torch.Tensor,241 B: torch.Tensor,
249 group_list: torch.Tensor,242 group_list: torch.Tensor,
250 config_A: MXQuantizeConfig,243 config_A: MXQuantizeConfig,
251- config_B: BlockQuantizeConfig,244+ config_B: BlockMXQuantizeConfig,
252 ):245 ):
253 assert A.ndim == 2, f"A must be 2D, got {A.ndim}D"246 assert A.ndim == 2, f"A must be 2D, got {A.ndim}D"
254 assert B.ndim == 3, f"B must be 3D, got {B.ndim}D"247 assert B.ndim == 3, f"B must be 3D, got {B.ndim}D"
@@ -256,15 +249,7 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
256 249 
257 # --- Step 1: quantize A along K-dim (contracting dim for forward) ---250 # --- Step 1: quantize A along K-dim (contracting dim for forward) ---
258 # A [M, K] → A_s1 (K-dim scale) [M, ceil(ceil(K/32)/2), 2]251 # A [M, K] → A_s1 (K-dim scale) [M, ceil(ceil(K/32)/2), 2]
259- A_q1, A_s1 = torch_npu.npu_dynamic_mx_quant(252+ A_q1, A_s1 = mx_quantize(A, -1, config_A)
260- A,
261- axis=-1,
262- round_mode=config_A.round_mode,
263- dst_type=config_A.elem_dtype,
264- block_size=config_A.block_size,
265- scale_alg=config_A.scale_alg,
266- dst_type_max=config_A.dst_type_max,
267- )
268 253 
269 # --- Step 2: quantize A along M-dim with grouped quant (zero boundaries) ---254 # --- Step 2: quantize A along M-dim with grouped quant (zero boundaries) ---
270 # A [M, K] → A_s2 (M-dim scale) [M//64 + E, K, 2]255 # A [M, K] → A_s2 (M-dim scale) [M//64 + E, K, 2]
@@ -272,15 +257,15 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
272 A,257 A,
273 group_list.to(torch.int32),258 group_list.to(torch.int32),
274 round_mode=config_A.round_mode,259 round_mode=config_A.round_mode,
275- dst_type=config_A.elem_dtype,260+ dst_type=config_A.npu_elem_dtype,
276 blocksize=config_A.block_size,261 blocksize=config_A.block_size,
277 scale_alg=config_A.scale_alg,262 scale_alg=config_A.scale_alg,
278 )263 )
279 264 
280- # --- Step 3: block FP8 quantize B (with optional mxfp4 fake-quant pre-pass) ---265+ # --- Step 3: block MX quantize B (with optional mxfp4 fake-quant pre-pass) ---
281 # B [E, K, N] → B_s1 (N-dim scale) [E, K, ceil(ceil(N/32)/2), 2]266 # B [E, K, N] → B_s1 (N-dim scale) [E, K, ceil(ceil(N/32)/2), 2]
282 # → B_s2 (K-dim scale) [E, ceil(ceil(K/32)/2), N, 2]267 # → B_s2 (K-dim scale) [E, ceil(ceil(K/32)/2), N, 2]
283- B_q, B_s1, B_s2 = block_fp8_mxfp4_fake_quantize(B, axis=-2, config=config_B)268+ B_q, B_s1, B_s2 = block_mx_quantize(B, config=config_B, axis=-2)
284 269 
285 # --- Step 4: grouped low-precision matmul, group_type=0 (contract over K) ---270 # --- Step 4: grouped low-precision matmul, group_type=0 (contract over K) ---
286 # x = A_q1 [M, K] → per_token_scale = A_s1 [M, ceil(K/64), 2]271 # x = A_q1 [M, K] → per_token_scale = A_s1 [M, ceil(K/64), 2]
@@ -294,8 +279,10 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
294 group_type=0,279 group_type=0,
295 output_dtype=A.dtype,280 output_dtype=A.dtype,
296 group_list_type=0,281 group_list_type=0,
297- scale_dtype=torch_npu.float8_e8m0fnu,282+ scale_dtype=config_B.npu_scale_dtype,
298- per_token_scale_dtype=torch_npu.float8_e8m0fnu,283+ per_token_scale_dtype=config_A.npu_scale_dtype,
284+ x_dtype=config_A.npu_matmul_dtype,
285+ weight_dtype=config_B.npu_matmul_dtype,
299 split_item=3,286 split_item=3,
300 )[0]287 )[0]
301 288 
@@ -312,19 +299,12 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
312 A_q2, A_s2, B_q, B_s1, group_list = ctx.saved_tensors299 A_q2, A_s2, B_q, B_s1, group_list = ctx.saved_tensors
313 A_dtype = ctx.A_dtype300 A_dtype = ctx.A_dtype
314 config_A = ctx.config_A301 config_A = ctx.config_A
302+ config_B = ctx.config_B
315 assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D"303 assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D"
316 304 
317 # --- Step 1: quantize dY along N-dim (for dgrad) ---305 # --- Step 1: quantize dY along N-dim (for dgrad) ---
318 # dY [M, N] → dY_s1 (N-dim scale) [M, ceil(ceil(N/32)/2), 2]306 # dY [M, N] → dY_s1 (N-dim scale) [M, ceil(ceil(N/32)/2), 2]
319- dY_q1, dY_s1 = torch_npu.npu_dynamic_mx_quant(307+ dY_q1, dY_s1 = mx_quantize(dY, -1, config_A)
320- dY,
321- axis=-1,
322- round_mode=config_A.round_mode,
323- dst_type=config_A.elem_dtype,
324- block_size=config_A.block_size,
325- scale_alg=config_A.scale_alg,
326- dst_type_max=config_A.dst_type_max,
327- )
328 308 
329 # --- Step 2: quantize dY along M-dim with grouped quant (zero boundaries) ---309 # --- Step 2: quantize dY along M-dim with grouped quant (zero boundaries) ---
330 # dY [M, N] → dY_s2 (M-dim scale) [M//64 + E, N, 2]310 # dY [M, N] → dY_s2 (M-dim scale) [M//64 + E, N, 2]
@@ -332,7 +312,7 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
332 dY,312 dY,
333 group_list.to(torch.int32),313 group_list.to(torch.int32),
334 round_mode=config_A.round_mode,314 round_mode=config_A.round_mode,
335- dst_type=config_A.elem_dtype,315+ dst_type=config_A.npu_elem_dtype,
336 blocksize=config_A.block_size,316 blocksize=config_A.block_size,
337 scale_alg=config_A.scale_alg,317 scale_alg=config_A.scale_alg,
338 )318 )
@@ -349,8 +329,10 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
349 group_type=0,329 group_type=0,
350 output_dtype=A_dtype,330 output_dtype=A_dtype,
351 group_list_type=0,331 group_list_type=0,
352- scale_dtype=torch_npu.float8_e8m0fnu,332+ scale_dtype=config_B.npu_scale_dtype,
353- per_token_scale_dtype=torch_npu.float8_e8m0fnu,333+ per_token_scale_dtype=config_A.npu_scale_dtype,
334+ x_dtype=config_A.npu_matmul_dtype,
335+ weight_dtype=config_B.npu_matmul_dtype,
354 split_item=3,336 split_item=3,
355 )[0]337 )[0]
356 338 
@@ -369,22 +351,25 @@ class _BlockFP8QuantGroupedMM(torch.autograd.Function):
369 group_type=2,351 group_type=2,
370 output_dtype=A_dtype,352 output_dtype=A_dtype,
371 group_list_type=0,353 group_list_type=0,
372- scale_dtype=torch_npu.float8_e8m0fnu,354+ # wgrad: the weight operand is dY_q2, quantized with config_A
373- per_token_scale_dtype=torch_npu.float8_e8m0fnu,355+ scale_dtype=config_A.npu_scale_dtype,
356+ per_token_scale_dtype=config_A.npu_scale_dtype,
357+ x_dtype=config_A.npu_matmul_dtype,
358+ weight_dtype=config_A.npu_matmul_dtype,
374 split_item=3,359 split_item=3,
375 )[0]360 )[0]
376 361 
377 return dA, dB, None, None, None362 return dA, dB, None, None, None
378 363 
379 364 
380-def to_block_fp8_then_grouped_mm(365+def to_block_mx_then_grouped_mm(
381 A: torch.Tensor,366 A: torch.Tensor,
382 B: torch.Tensor,367 B: torch.Tensor,
383 group_list: torch.Tensor,368 group_list: torch.Tensor,
384 config_A: MXQuantizeConfig,369 config_A: MXQuantizeConfig,
385- config_B: BlockQuantizeConfig,370+ config_B: BlockMXQuantizeConfig,
386) -> torch.Tensor:371) -> torch.Tensor:
387- """Block FP8 grouped matrix multiply with mixed-format quantization.372+ """Block MX grouped matrix multiply with mixed-format quantization.
388 373 
389 ``A`` is a 2D tensor ``(M, K)`` whose rows are partitioned among374 ``A`` is a 2D tensor ``(M, K)`` whose rows are partitioned among
390 ``E`` groups via ``group_list`` (cumsum offsets, length ``E``).375 ``E`` groups via ``group_list`` (cumsum offsets, length ``E``).
@@ -397,7 +382,7 @@ def to_block_fp8_then_grouped_mm(
397 - A along M-dim: ``npu_grouped_dynamic_mx_quant`` (params from ``config_A``)382 - A along M-dim: ``npu_grouped_dynamic_mx_quant`` (params from ``config_A``)
398 - B: ``npu_dynamic_block_mx_quant``, 32×32 blocks (params from ``config_B``)383 - B: ``npu_dynamic_block_mx_quant``, 32×32 blocks (params from ``config_B``)
399 384 
400- See ``_BlockFP8QuantGroupedMM`` for details of the three GEMMs.385+ See ``_BlockMXQuantGroupedMM`` for details of the three GEMMs.
401 386 
402 Args:387 Args:
403 A: Input tensor, shape ``(M, K)``.388 A: Input tensor, shape ``(M, K)``.
@@ -410,16 +395,16 @@ def to_block_fp8_then_grouped_mm(
410 Returns:395 Returns:
411 Output tensor, shape ``(M, N)``, dtype matching ``A``.396 Output tensor, shape ``(M, N)``, dtype matching ``A``.
412 """397 """
413- return _BlockFP8QuantGroupedMM.apply(A, B, group_list, config_A, config_B)398+ return _BlockMXQuantGroupedMM.apply(A, B, group_list, config_A, config_B)
414 399 
415 400 
416-class _BlockFP8QuantBMM(torch.autograd.Function):401+class _BlockMXQuantBMM(torch.autograd.Function):
417- """Block FP8 batched matmul: ``A[B,M,K] @ B[B,K,N] = Y[B,M,N]``.402+ """Block MX batched matmul: ``A[B,M,K] @ B[B,K,N] = Y[B,M,N]``.
418 403 
419 Both operands are 3D and share the leading batch dimension. The forward404 Both operands are 3D and share the leading batch dimension. The forward
420 dual-axis quantizes ``A`` (params from ``config_A``) and block quantizes405 dual-axis quantizes ``A`` (params from ``config_A``) and block quantizes
421 ``B`` in 32×32 blocks (params from ``config_B``, via406 ``B`` in 32×32 blocks (params from ``config_B``, via
422- ``block_fp8_mxfp4_fake_quantize``), then performs the low-precision matmul407+ ``block_mx_quantize``), then performs the low-precision matmul
423 contracting over K. The backward reuses the forward-quantized ``A_q2/A_s2``408 contracting over K. The backward reuses the forward-quantized ``A_q2/A_s2``
424 and ``B_q/B_s1`` transposed and only quantizes ``dY`` fresh.409 and ``B_q/B_s1`` transposed and only quantizes ``dY`` fresh.
425 """410 """
@@ -430,7 +415,7 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
430 A: torch.Tensor,415 A: torch.Tensor,
431 B: torch.Tensor,416 B: torch.Tensor,
432 config_A: MXQuantizeConfig,417 config_A: MXQuantizeConfig,
433- config_B: BlockQuantizeConfig,418+ config_B: BlockMXQuantizeConfig,
434 ):419 ):
435 assert A.ndim == 3, f"A must be 3D, got {A.ndim}D"420 assert A.ndim == 3, f"A must be 3D, got {A.ndim}D"
436 assert B.ndim == 3, f"B must be 3D, got {B.ndim}D"421 assert B.ndim == 3, f"B must be 3D, got {B.ndim}D"
@@ -447,16 +432,10 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
447 )432 )
448 433 
449 # --- Step 1: dual-axis MX quantize A (left operand) ---434 # --- Step 1: dual-axis MX quantize A (left operand) ---
450- A_q1, A_s1, A_q2, A_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(435+ A_q1, A_s1, A_q2, A_s2 = mx_quantize_dual_axis(A, config_A)
451- A,
452- round_mode=config_A.round_mode,
453- dst_type=config_A.elem_dtype,
454- scale_alg=config_A.scale_alg,
455- dst_type_max=config_A.dst_type_max,
456- )
457 436 
458- # --- Step 2: block FP8 quantize B (right operand, optional mxfp4 pre-pass) ---437+ # --- Step 2: block MX quantize B (right operand, optional mxfp4 pre-pass) ---
459- B_q, B_s1, B_s2 = block_fp8_mxfp4_fake_quantize(B, axis=-2, config=config_B)438+ B_q, B_s1, B_s2 = block_mx_quantize(B, config=config_B, axis=-2)
460 439 
461 # --- Step 3: low-precision batched matmul, contracting over K ---440 # --- Step 3: low-precision batched matmul, contracting over K ---
462 Y = torch_npu.npu_quant_matmul(441 Y = torch_npu.npu_quant_matmul(
@@ -465,8 +444,10 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
465 B_s2,444 B_s2,
466 pertoken_scale=A_s1,445 pertoken_scale=A_s1,
467 output_dtype=A.dtype,446 output_dtype=A.dtype,
468- scale_dtype=torch_npu.float8_e8m0fnu,447+ scale_dtype=config_B.npu_scale_dtype,
469- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,448+ pertoken_scale_dtype=config_A.npu_scale_dtype,
449+ x1_dtype=config_A.npu_matmul_dtype,
450+ x2_dtype=config_B.npu_matmul_dtype,
470 group_sizes=[1, 1, config_B.block_size],451 group_sizes=[1, 1, config_B.block_size],
471 )452 )
472 453 
@@ -484,13 +465,7 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
484 config_B = ctx.config_B465 config_B = ctx.config_B
485 466 
486 # --- Step 1: dual-axis MX quantize dY ---467 # --- Step 1: dual-axis MX quantize dY ---
487- dY_q1, dY_s1, dY_q2, dY_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(468+ dY_q1, dY_s1, dY_q2, dY_s2 = mx_quantize_dual_axis(dY, config_A)
488- dY,
489- round_mode=config_A.round_mode,
490- dst_type=config_A.elem_dtype,
491- scale_alg=config_A.scale_alg,
492- dst_type_max=config_A.dst_type_max,
493- )
494 469 
495 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---470 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---
496 dA = torch_npu.npu_quant_matmul(471 dA = torch_npu.npu_quant_matmul(
@@ -499,8 +474,10 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
499 B_s1.transpose(-2, -3),474 B_s1.transpose(-2, -3),
500 pertoken_scale=dY_s1,475 pertoken_scale=dY_s1,
501 output_dtype=A_dtype,476 output_dtype=A_dtype,
502- scale_dtype=torch_npu.float8_e8m0fnu,477+ scale_dtype=config_B.npu_scale_dtype,
503- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,478+ pertoken_scale_dtype=config_A.npu_scale_dtype,
479+ x1_dtype=config_A.npu_matmul_dtype,
480+ x2_dtype=config_B.npu_matmul_dtype,
504 group_sizes=[1, 1, config_B.block_size],481 group_sizes=[1, 1, config_B.block_size],
505 )482 )
506 483 
@@ -511,33 +488,35 @@ class _BlockFP8QuantBMM(torch.autograd.Function):
511 dY_s2,488 dY_s2,
512 pertoken_scale=A_s2.transpose(-2, -3),489 pertoken_scale=A_s2.transpose(-2, -3),
513 output_dtype=A_dtype,490 output_dtype=A_dtype,
514- scale_dtype=torch_npu.float8_e8m0fnu,491+ scale_dtype=config_A.npu_scale_dtype,
515- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,492+ pertoken_scale_dtype=config_A.npu_scale_dtype,
493+ x1_dtype=config_A.npu_matmul_dtype,
494+ x2_dtype=config_A.npu_matmul_dtype,
516 group_sizes=[1, 1, config_B.block_size],495 group_sizes=[1, 1, config_B.block_size],
517 )496 )
518 497 
519 return dA, dB, None, None498 return dA, dB, None, None
520 499 
521 500 
522-def to_block_fp8_then_bmm(501+def to_block_mx_then_bmm(
523 A: torch.Tensor,502 A: torch.Tensor,
524 B: torch.Tensor,503 B: torch.Tensor,
525 config_A: MXQuantizeConfig,504 config_A: MXQuantizeConfig,
526- config_B: BlockQuantizeConfig,505+ config_B: BlockMXQuantizeConfig,
527) -> torch.Tensor:506) -> torch.Tensor:
528- """Block FP8 batched matmul: ``A[B,M,K] @ B[B,K,N] = Y[B,M,N]``.507+ """Block MX batched matmul: ``A[B,M,K] @ B[B,K,N] = Y[B,M,N]``.
529 508 
530 Both operands are 3D and must share the leading batch dimension.509 Both operands are 3D and must share the leading batch dimension.
531 Quantization configs are drawn from ``config_A`` (MX, for A and dY) and510 Quantization configs are drawn from ``config_A`` (MX, for A and dY) and
532- ``config_B`` (Block FP8, for B).511+ ``config_B`` (Block MX, for B).
533 512 
534 Args:513 Args:
535 A: Shape ``(B, M, K)``.514 A: Shape ``(B, M, K)``.
536 B: Shape ``(B, K, N)``.515 B: Shape ``(B, K, N)``.
537 config_A: MX config for A's quantization.516 config_A: MX config for A's quantization.
538- config_B: Block FP8 config for B's quantization.517+ config_B: Block MX config for B's quantization.
539 518 
540 Returns:519 Returns:
541 Output tensor, shape ``(B, M, N)``, dtype matching ``A``.520 Output tensor, shape ``(B, M, N)``, dtype matching ``A``.
542 """521 """
543- return _BlockFP8QuantBMM.apply(A, B, config_A, config_B)522+ return _BlockMXQuantBMM.apply(A, B, config_A, config_B)
@@ -6,8 +6,12 @@
6import torch6import torch
7import torch_npu7import torch_npu
8 8 
9-from ..quantization.quant_configs import MXQuantizeConfig9+from torchao_npu.quantization.quant_configs import MXQuantizeConfig
10-from ..quantization.quant_primitives.mx import mxfp4_dequantize10+from torchao_npu.quantization.quant_primitives.mx import (
11+ mx_quantize,
12+ mx_quantize_dual_axis,
13+ mxfp4_dequantize,
14+)
11 15 
12__all__ = [16__all__ = [
13 "mxfp4_fake_quantize",17 "mxfp4_fake_quantize",
@@ -18,22 +22,6 @@ __all__ = [
18]22]
19 23 
20 24 
21-def _to_npu_dtype_override(dtype: torch.dtype) -> int | None:
22- """Return NPU dtype int for ``x1_dtype``/``x2_dtype``, or ``None`` to omit.
23- 
24- ``npu_quant_matmul``'s ``x1_dtype``/``x2_dtype`` parameters must only be
25- passed for dtypes where the tensor's storage dtype differs from its logical
26- dtype. ``float4_e2m1fn_x2`` is stored as ``uint8`` (two FP4 values per
27- byte), so the kernel needs the explicit hint ``torch_npu.float4_e2m1fn_x2``.
28- Standard FP8 types (``float8_e4m3fn``, ``float8_e5m2``) are natively
29- represented by the tensor's dtype and **must not** be passed — doing so
30- causes a ``RuntimeError`` under ``torch.compile``'s fake-tensor tracing.
31- """
32- if dtype == torch.float4_e2m1fn_x2:
33- return torch_npu.float4_e2m1fn_x2
34- return None
35- 
36- 
37class MXFP4FakeQuantize(torch.autograd.Function):25class MXFP4FakeQuantize(torch.autograd.Function):
38 """MX FP4 fake quantize via autograd.Function.26 """MX FP4 fake quantize via autograd.Function.
39 27 
@@ -48,7 +36,7 @@ class MXFP4FakeQuantize(torch.autograd.Function):
48 def forward(ctx, hp: torch.Tensor, config: MXQuantizeConfig, axis: int = -1): # pyrefly: ignore [bad-override]36 def forward(ctx, hp: torch.Tensor, config: MXQuantizeConfig, axis: int = -1): # pyrefly: ignore [bad-override]
49 weight_mx, w_scale = torch_npu.npu_dynamic_mx_quant(37 weight_mx, w_scale = torch_npu.npu_dynamic_mx_quant(
50 hp,38 hp,
51- dst_type=torch_npu.float4_e2m1fn_x2,39+ dst_type=config.npu_elem_dtype,
52 axis=axis,40 axis=axis,
53 block_size=config.block_size,41 block_size=config.block_size,
54 round_mode=config.round_mode,42 round_mode=config.round_mode,
@@ -75,6 +63,9 @@ def mxfp4_fake_quantize(
75 axis: int = -1,63 axis: int = -1,
76) -> torch.Tensor:64) -> torch.Tensor:
77 """Thin wrapper around ``MXFP4FakeQuantize.apply``."""65 """Thin wrapper around ``MXFP4FakeQuantize.apply``."""
66+ assert config.elem_dtype is torch.float4_e2m1fn_x2, (
67+ f"mxfp4_fake_quantize only supports elem_dtype=torch.float4_e2m1fn_x2, got {config.elem_dtype}"
68+ )
78 return MXFP4FakeQuantize.apply(hp, config, axis)69 return MXFP4FakeQuantize.apply(hp, config, axis)
79 70 
80 71 
@@ -153,20 +144,10 @@ class _MXQuantMM(torch.autograd.Function):
153 assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"144 assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"
154 145 
155 # --- Step 1: quantize A with dual-axis MX quant ---146 # --- Step 1: quantize A with dual-axis MX quant ---
156- A_q1, A_s1, A_q2, A_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(147+ A_q1, A_s1, A_q2, A_s2 = mx_quantize_dual_axis(A.reshape(-1, A.shape[-1]), config_A)
157- A.reshape(-1, A.shape[-1]),
158- round_mode=config_A.round_mode,
159- dst_type=config_A.elem_dtype,
160- scale_alg=config_A.scale_alg,
161- )
162 148 
163 # --- Step 2: quantize B with dual-axis MX quant ---149 # --- Step 2: quantize B with dual-axis MX quant ---
164- B_q1, B_s1, B_q2, B_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(150+ B_q1, B_s1, B_q2, B_s2 = mx_quantize_dual_axis(B, config_B)
165- B,
166- round_mode=config_B.round_mode,
167- dst_type=config_B.elem_dtype,
168- scale_alg=config_B.scale_alg,
169- )
170 151 
171 # --- Step 3: low-precision matmul, contracting over K ---152 # --- Step 3: low-precision matmul, contracting over K ---
172 Y = torch_npu.npu_quant_matmul(153 Y = torch_npu.npu_quant_matmul(
@@ -176,10 +157,10 @@ class _MXQuantMM(torch.autograd.Function):
176 pertoken_scale=A_s1,157 pertoken_scale=A_s1,
177 output_dtype=A.dtype,158 output_dtype=A.dtype,
178 group_sizes=[1, 1, config_A.block_size],159 group_sizes=[1, 1, config_A.block_size],
179- scale_dtype=torch_npu.float8_e8m0fnu,160+ scale_dtype=config_B.npu_scale_dtype,
180- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,161+ pertoken_scale_dtype=config_A.npu_scale_dtype,
181- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),162+ x1_dtype=config_A.npu_matmul_dtype,
182- x2_dtype=_to_npu_dtype_override(config_B.elem_dtype),163+ x2_dtype=config_B.npu_matmul_dtype,
183 )164 )
184 165 
185 if A.ndim != 2:166 if A.ndim != 2:
@@ -201,12 +182,7 @@ class _MXQuantMM(torch.autograd.Function):
201 config_B = ctx.config_B182 config_B = ctx.config_B
202 183 
203 # --- Step 1: quantize dY with dual-axis MX quant ---184 # --- Step 1: quantize dY with dual-axis MX quant ---
204- dY_q1, dY_s1, dY_q2, dY_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(185+ dY_q1, dY_s1, dY_q2, dY_s2 = mx_quantize_dual_axis(dY.reshape(-1, dY.shape[-1]), config_A)
205- dY.reshape(-1, dY.shape[-1]),
206- round_mode=config_A.round_mode,
207- dst_type=config_A.elem_dtype,
208- scale_alg=config_A.scale_alg,
209- )
210 186 
211 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---187 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---
212 dA = torch_npu.npu_quant_matmul(188 dA = torch_npu.npu_quant_matmul(
@@ -216,10 +192,10 @@ class _MXQuantMM(torch.autograd.Function):
216 pertoken_scale=dY_s1,192 pertoken_scale=dY_s1,
217 output_dtype=A_dtype,193 output_dtype=A_dtype,
218 group_sizes=[1, 1, config_A.block_size],194 group_sizes=[1, 1, config_A.block_size],
219- scale_dtype=torch_npu.float8_e8m0fnu,195+ scale_dtype=config_B.npu_scale_dtype,
220- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,196+ pertoken_scale_dtype=config_A.npu_scale_dtype,
221- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),197+ x1_dtype=config_A.npu_matmul_dtype,
222- x2_dtype=_to_npu_dtype_override(config_B.elem_dtype),198+ x2_dtype=config_B.npu_matmul_dtype,
223 )199 )
224 200 
225 # --- Step 3: wgrad dB = A^T @ dY (contract over M) ---201 # --- Step 3: wgrad dB = A^T @ dY (contract over M) ---
@@ -230,10 +206,10 @@ class _MXQuantMM(torch.autograd.Function):
230 pertoken_scale=A_s2.transpose(0, 1),206 pertoken_scale=A_s2.transpose(0, 1),
231 output_dtype=A_dtype,207 output_dtype=A_dtype,
232 group_sizes=[1, 1, config_A.block_size],208 group_sizes=[1, 1, config_A.block_size],
233- scale_dtype=torch_npu.float8_e8m0fnu,209+ scale_dtype=config_A.npu_scale_dtype,
234- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,210+ pertoken_scale_dtype=config_A.npu_scale_dtype,
235- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),211+ x1_dtype=config_A.npu_matmul_dtype,
236- x2_dtype=_to_npu_dtype_override(config_A.elem_dtype),212+ x2_dtype=config_A.npu_matmul_dtype,
237 )213 )
238 214 
239 if dY.ndim != 2:215 if dY.ndim != 2:
@@ -285,32 +261,20 @@ class _MXQuantGroupedMM(torch.autograd.Function):
285 assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"261 assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"
286 262 
287 # --- Step 1: quantize A along K-dim (contracting dim for forward) ---263 # --- Step 1: quantize A along K-dim (contracting dim for forward) ---
288- A_q1, A_s1 = torch_npu.npu_dynamic_mx_quant(264+ A_q1, A_s1 = mx_quantize(A, -1, config_A)
289- A,
290- axis=-1,
291- round_mode=config_A.round_mode,
292- dst_type=config_A.elem_dtype,
293- block_size=config_A.block_size,
294- scale_alg=config_A.scale_alg,
295- )
296 265 
297 # --- Step 2: quantize A along M-dim with grouped quant (zero boundaries) ---266 # --- Step 2: quantize A along M-dim with grouped quant (zero boundaries) ---
298 A_q2, A_s2 = torch_npu.npu_grouped_dynamic_mx_quant(267 A_q2, A_s2 = torch_npu.npu_grouped_dynamic_mx_quant(
299 A,268 A,
300 group_list.to(torch.int32),269 group_list.to(torch.int32),
301 round_mode=config_A.round_mode,270 round_mode=config_A.round_mode,
302- dst_type=config_A.elem_dtype,271+ dst_type=config_A.npu_elem_dtype,
303 blocksize=config_A.block_size,272 blocksize=config_A.block_size,
304 scale_alg=config_A.scale_alg,273 scale_alg=config_A.scale_alg,
305 )274 )
306 275 
307 # --- Step 3: dual-axis quantize B (q1/s1 = N-dim, q2/s2 = K-dim) ---276 # --- Step 3: dual-axis quantize B (q1/s1 = N-dim, q2/s2 = K-dim) ---
308- B_q1, B_s1, B_q2, B_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(277+ B_q1, B_s1, B_q2, B_s2 = mx_quantize_dual_axis(B, config_B)
309- B,
310- round_mode=config_B.round_mode,
311- dst_type=config_B.elem_dtype,
312- scale_alg=config_B.scale_alg,
313- )
314 278 
315 # --- Step 4: grouped low-precision matmul, group_type=0 (contract over K) ---279 # --- Step 4: grouped low-precision matmul, group_type=0 (contract over K) ---
316 Y = torch_npu.npu_grouped_matmul(280 Y = torch_npu.npu_grouped_matmul(
@@ -322,8 +286,8 @@ class _MXQuantGroupedMM(torch.autograd.Function):
322 group_type=0,286 group_type=0,
323 output_dtype=A.dtype,287 output_dtype=A.dtype,
324 group_list_type=0,288 group_list_type=0,
325- scale_dtype=torch_npu.float8_e8m0fnu,289+ scale_dtype=config_B.npu_scale_dtype,
326- per_token_scale_dtype=torch_npu.float8_e8m0fnu,290+ per_token_scale_dtype=config_A.npu_scale_dtype,
327 split_item=3,291 split_item=3,
328 )[0]292 )[0]
329 293 
@@ -344,21 +308,14 @@ class _MXQuantGroupedMM(torch.autograd.Function):
344 assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D"308 assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D"
345 309 
346 # --- Step 1: quantize dY along N-dim (for dgrad) ---310 # --- Step 1: quantize dY along N-dim (for dgrad) ---
347- dY_q1, dY_s1 = torch_npu.npu_dynamic_mx_quant(311+ dY_q1, dY_s1 = mx_quantize(dY, -1, config_A)
348- dY,
349- axis=-1,
350- round_mode=config_A.round_mode,
351- dst_type=config_A.elem_dtype,
352- block_size=config_A.block_size,
353- scale_alg=config_A.scale_alg,
354- )
355 312 
356 # --- Step 2: quantize dY along M-dim with grouped quant (zero boundaries) ---313 # --- Step 2: quantize dY along M-dim with grouped quant (zero boundaries) ---
357 dY_q2, dY_s2 = torch_npu.npu_grouped_dynamic_mx_quant(314 dY_q2, dY_s2 = torch_npu.npu_grouped_dynamic_mx_quant(
358 dY,315 dY,
359 group_list.to(torch.int32),316 group_list.to(torch.int32),
360 round_mode=config_A.round_mode,317 round_mode=config_A.round_mode,
361- dst_type=config_A.elem_dtype,318+ dst_type=config_A.npu_elem_dtype,
362 blocksize=config_A.block_size,319 blocksize=config_A.block_size,
363 scale_alg=config_A.scale_alg,320 scale_alg=config_A.scale_alg,
364 )321 )
@@ -373,8 +330,8 @@ class _MXQuantGroupedMM(torch.autograd.Function):
373 group_type=0,330 group_type=0,
374 output_dtype=A_dtype,331 output_dtype=A_dtype,
375 group_list_type=0,332 group_list_type=0,
376- scale_dtype=torch_npu.float8_e8m0fnu,333+ scale_dtype=config_B.npu_scale_dtype,
377- per_token_scale_dtype=torch_npu.float8_e8m0fnu,334+ per_token_scale_dtype=config_A.npu_scale_dtype,
378 split_item=3,335 split_item=3,
379 )[0]336 )[0]
380 337 
@@ -388,8 +345,8 @@ class _MXQuantGroupedMM(torch.autograd.Function):
388 group_type=2,345 group_type=2,
389 output_dtype=A_dtype,346 output_dtype=A_dtype,
390 group_list_type=0,347 group_list_type=0,
391- scale_dtype=torch_npu.float8_e8m0fnu,348+ scale_dtype=config_A.npu_scale_dtype,
392- per_token_scale_dtype=torch_npu.float8_e8m0fnu,349+ per_token_scale_dtype=config_A.npu_scale_dtype,
393 split_item=3,350 split_item=3,
394 )[0]351 )[0]
395 352 
@@ -454,20 +411,10 @@ class _MXQuantBMM(torch.autograd.Function):
454 )411 )
455 412 
456 # --- Step 1: dual-axis quantize A (left operand) ---413 # --- Step 1: dual-axis quantize A (left operand) ---
457- A_q1, A_s1, A_q2, A_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(414+ A_q1, A_s1, A_q2, A_s2 = mx_quantize_dual_axis(A, config_A)
458- A,
459- round_mode=config_A.round_mode,
460- dst_type=config_A.elem_dtype,
461- scale_alg=config_A.scale_alg,
462- )
463 415 
464 # --- Step 2: dual-axis quantize B (right operand) ---416 # --- Step 2: dual-axis quantize B (right operand) ---
465- B_q1, B_s1, B_q2, B_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(417+ B_q1, B_s1, B_q2, B_s2 = mx_quantize_dual_axis(B, config_B)
466- B,
467- round_mode=config_B.round_mode,
468- dst_type=config_B.elem_dtype,
469- scale_alg=config_B.scale_alg,
470- )
471 418 
472 # --- Step 3: low-precision batched matmul, contracting over K ---419 # --- Step 3: low-precision batched matmul, contracting over K ---
473 Y = torch_npu.npu_quant_matmul(420 Y = torch_npu.npu_quant_matmul(
@@ -477,10 +424,10 @@ class _MXQuantBMM(torch.autograd.Function):
477 pertoken_scale=A_s1,424 pertoken_scale=A_s1,
478 output_dtype=A.dtype,425 output_dtype=A.dtype,
479 group_sizes=[1, 1, config_A.block_size],426 group_sizes=[1, 1, config_A.block_size],
480- scale_dtype=torch_npu.float8_e8m0fnu,427+ scale_dtype=config_B.npu_scale_dtype,
481- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,428+ pertoken_scale_dtype=config_A.npu_scale_dtype,
482- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),429+ x1_dtype=config_A.npu_matmul_dtype,
483- x2_dtype=_to_npu_dtype_override(config_B.elem_dtype),430+ x2_dtype=config_B.npu_matmul_dtype,
484 )431 )
485 432 
486 ctx.save_for_backward(A_q2, A_s2, B_q1, B_s1)433 ctx.save_for_backward(A_q2, A_s2, B_q1, B_s1)
@@ -497,12 +444,7 @@ class _MXQuantBMM(torch.autograd.Function):
497 config_B = ctx.config_B444 config_B = ctx.config_B
498 445 
499 # --- Step 1: quantize dY with dual-axis MX quant ---446 # --- Step 1: quantize dY with dual-axis MX quant ---
500- dY_q1, dY_s1, dY_q2, dY_s2 = torch_npu.npu_dynamic_mx_quant_with_dual_axis(447+ dY_q1, dY_s1, dY_q2, dY_s2 = mx_quantize_dual_axis(dY, config_A)
501- dY,
502- round_mode=config_A.round_mode,
503- dst_type=config_A.elem_dtype,
504- scale_alg=config_A.scale_alg,
505- )
506 448 
507 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---449 # --- Step 2: dgrad dA = dY @ B^T (contract over N) ---
508 dA = torch_npu.npu_quant_matmul(450 dA = torch_npu.npu_quant_matmul(
@@ -512,10 +454,10 @@ class _MXQuantBMM(torch.autograd.Function):
512 pertoken_scale=dY_s1,454 pertoken_scale=dY_s1,
513 output_dtype=A_dtype,455 output_dtype=A_dtype,
514 group_sizes=[1, 1, config_A.block_size],456 group_sizes=[1, 1, config_A.block_size],
515- scale_dtype=torch_npu.float8_e8m0fnu,457+ scale_dtype=config_B.npu_scale_dtype,
516- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,458+ pertoken_scale_dtype=config_A.npu_scale_dtype,
517- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),459+ x1_dtype=config_A.npu_matmul_dtype,
518- x2_dtype=_to_npu_dtype_override(config_B.elem_dtype),460+ x2_dtype=config_B.npu_matmul_dtype,
519 )461 )
520 462 
521 # --- Step 3: wgrad dB = A^T @ dY (contract over M) ---463 # --- Step 3: wgrad dB = A^T @ dY (contract over M) ---
@@ -526,10 +468,10 @@ class _MXQuantBMM(torch.autograd.Function):
526 pertoken_scale=A_s2.transpose(-2, -3),468 pertoken_scale=A_s2.transpose(-2, -3),
527 output_dtype=A_dtype,469 output_dtype=A_dtype,
528 group_sizes=[1, 1, config_A.block_size],470 group_sizes=[1, 1, config_A.block_size],
529- scale_dtype=torch_npu.float8_e8m0fnu,471+ scale_dtype=config_A.npu_scale_dtype,
530- pertoken_scale_dtype=torch_npu.float8_e8m0fnu,472+ pertoken_scale_dtype=config_A.npu_scale_dtype,
531- x1_dtype=_to_npu_dtype_override(config_A.elem_dtype),473+ x1_dtype=config_A.npu_matmul_dtype,
532- x2_dtype=_to_npu_dtype_override(config_A.elem_dtype),474+ x2_dtype=config_A.npu_matmul_dtype,
533 )475 )
534 476 
535 return dA, dB, None, None477 return dA, dB, None, None
@@ -4,3 +4,18 @@
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6"""Quantization configurations, filters, and parameter transforms."""6"""Quantization configurations, filters, and parameter transforms."""
7+ 
8+from types import MappingProxyType
9+ 
10+import torch
11+import torch_npu
12+ 
13+# torch dtype -> torch_npu dtype accepted by the NPU quant ops.
14+_NPU_DTYPE_DICT = MappingProxyType(
15+ {
16+ torch.float8_e4m3fn: torch_npu.float8_e4m3fn,
17+ torch.float8_e5m2: torch_npu.float8_e5m2,
18+ torch.float8_e8m0fnu: torch_npu.float8_e8m0fnu,
19+ torch.float4_e2m1fn_x2: torch_npu.float4_e2m1fn_x2,
wanghui0

支持更多数据格式与transpose冗余消除是两个特性, 建议分两笔提交,保持提交的单一功能性。

likedislike
caoshuyang
caoshuyang
Sep 9 Comments:
likedislike
20+ }
21+)
@@ -56,14 +56,14 @@ def _is_parameter(param: nn.Parameter, fqn: str) -> bool:
56 Default filter for parameter-level recursion: returns True for all56 Default filter for parameter-level recursion: returns True for all
57 ``nn.Parameter`` not already wrapped.57 ``nn.Parameter`` not already wrapped.
58 """58 """
59- from ..wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor59+ from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
60 60 
61 return isinstance(param, nn.Parameter) and not isinstance(param.data, BaseTrainingWeightWrapperTensor)61 return isinstance(param, nn.Parameter) and not isinstance(param.data, BaseTrainingWeightWrapperTensor)
62 62 
63 63 
64def _is_parameter_with_wrapped_data(param: nn.Parameter, fqn: str) -> bool:64def _is_parameter_with_wrapped_data(param: nn.Parameter, fqn: str) -> bool:
65 """Filter for the convert step, identifying Parameters with wrapped data."""65 """Filter for the convert step, identifying Parameters with wrapped data."""
66- from ..wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor66+ from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
67 67 
68 return isinstance(param, nn.Parameter) and isinstance(param.data, BaseTrainingWeightWrapperTensor)68 return isinstance(param, nn.Parameter) and isinstance(param.data, BaseTrainingWeightWrapperTensor)
69 69 
@@ -9,11 +9,14 @@ These are standalone dataclasses (no parent ``QATConfig`` machinery) consumed
9by both training-time wrapper tensors and future PTQ algorithms.9by both training-time wrapper tensors and future PTQ algorithms.
10"""10"""
11 11 
12+import warnings
12from dataclasses import dataclass, field13from dataclasses import dataclass, field
13 14 
14import torch15import torch
15from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase16from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase
16 17 
18+from torchao_npu.quantization import _NPU_DTYPE_DICT
19+ 
17NPU_SUPPORTED_ELEM_DTYPES = [20NPU_SUPPORTED_ELEM_DTYPES = [
18 torch.float8_e4m3fn,21 torch.float8_e4m3fn,
19 torch.float8_e5m2,22 torch.float8_e5m2,
@@ -48,6 +51,27 @@ class MXQuantizeConfig(FakeQuantizeConfigBase):
48 # Required by NPU ops like npu_dynamic_mx_quant for FP4 quantization.51 # Required by NPU ops like npu_dynamic_mx_quant for FP4 quantization.
49 dst_type_max: float = 0.052 dst_type_max: float = 0.0
50 53 
54+ @property
55+ def scale_dtype(self) -> torch.dtype:
56+ return torch.float8_e8m0fnu
57+ 
58+ # ``dst_type`` token the NPU quant ops expect; they do not accept
59+ # ``torch.float4_e2m1fn_x2``.
60+ @property
61+ def npu_elem_dtype(self) -> int:
62+ return _NPU_DTYPE_DICT[self.elem_dtype]
63+ 
64+ # For ``npu_quant_matmul``'s ``x1_dtype``/``x2_dtype``: only FP4 (stored as
65+ # uint8) needs the explicit hint; FP8 dtypes must not be passed -- doing so
66+ # causes a RuntimeError under ``torch.compile``'s fake-tensor tracing.
67+ @property
68+ def npu_matmul_dtype(self) -> int | None:
69+ return self.npu_elem_dtype if self.elem_dtype is torch.float4_e2m1fn_x2 else None
70+ 
71+ @property
72+ def npu_scale_dtype(self) -> int:
73+ return _NPU_DTYPE_DICT[self.scale_dtype]
74+ 
51 def __post_init__(self):75 def __post_init__(self):
52 assert self.block_size == 32, f"For MX formats, the block_size must be 32, block_size={self.block_size} passed."76 assert self.block_size == 32, f"For MX formats, the block_size must be 32, block_size={self.block_size} passed."
53 77 
@@ -55,54 +79,84 @@ class MXQuantizeConfig(FakeQuantizeConfigBase):
55 f"elem_dtype must be one of {NPU_SUPPORTED_ELEM_DTYPES}, got {self.elem_dtype}"79 f"elem_dtype must be one of {NPU_SUPPORTED_ELEM_DTYPES}, got {self.elem_dtype}"
56 )80 )
57 81 
82+ is_fp4 = self.elem_dtype is torch.float4_e2m1fn_x2
58 if self.scale_alg is None:83 if self.scale_alg is None:
59- is_fp4 = self.elem_dtype in (torch.float4_e2m1fn_x2,)
60 self.scale_alg = 2 if is_fp4 else 184 self.scale_alg = 2 if is_fp4 else 1
61 85 
86+ if is_fp4:
87+ assert self.scale_alg in (0, 2), (
88+ f"{type(self).__name__} only supports scale_alg=0 or 2 for FP4, got {self.scale_alg}"
89+ )
90+ 
62 91 
63@dataclass92@dataclass
64-class BlockQuantizeConfig(FakeQuantizeConfigBase):93+class BlockMXQuantizeConfig(MXQuantizeConfig):
atomgit-bot

🟡 Medium Priority

建议:同步更新 experiments/torchao-npu/tests/test_wrapper_storage_delegation.py, 将 BlockQuantizeConfig 换成 BlockMXQuantizeConfig、BlockTrainingWeightWrapperTensor 换成 BlockMXTrainingWeightWrapperTensor; 或在 quant_configs.py 与 wrapper_tensors/init.py 中为旧名称添加 BlockQuantizeConfig = BlockMXQuantizeConfig 之类的兼容别名后再删除。

likedislike
Incorrect?
caoshuyang
caoshuyang
Sep 8 Comments:
likedislike
65 """94 """
66- Config for block FP8 low-precision training.95+ Config for block MX low-precision training.
67 96 
68- Most fields are constrained to a single value by the underlying kernels;97+ Extends :class:`MXQuantizeConfig`, inheriting its fields and ``npu_*``
69- :meth:`__post_init__` enforces these invariants so misconfiguration fails98+ properties.
70- fast instead of erroring deep inside the op.99+ 
100+ - Without ``mxfp4_fake_quantize_config``, the accepted values follow
101+ :class:`MXQuantizeConfig` except ``scale_alg`` for FP8: the block MX
102+ kernel only supports 0 (the inferred default; MX would infer 1). FP4
103+ keeps the inherited MX constraint (0 or 2, ``None`` infers 2).
104+ - When ``mxfp4_fake_quantize_config`` is set, the nested config's
105+ ``elem_dtype`` must be FP4 and this config's ``elem_dtype`` must be FP8;
106+ the fused FP4-to-block-MX kernel only consumes ``elem_dtype`` (its
107+ ``dst_type``), so ``dst_type_max`` and ``round_mode`` are ignored (with
108+ a warning when set to non-default values). ``scale_alg`` is not consumed
109+ either, but still follows the FP8 constraint above.
71 """110 """
72 111 
73- # Block size. Must be 32.112+ # When set, apply MXFP4 fake-quant to weights before the block MX matmul.
74- block_size: int = 32
75- 
76- # Target dtype for the quantized data. Either float8_e4m3fn or float8_e5m2.
77- elem_dtype: torch.dtype = torch.float8_e4m3fn
78- 
79- # Rounding mode. Must be "rint".
80- round_mode: str = field(default="rint", compare=False)
81- 
82- # Scale calculation algorithm. Must be 0.
83- scale_alg: int = field(default=0, compare=False)
84- 
85- # Maximum value of the target dtype. Must be 0.0 (auto-inferred from elem_dtype).
86- dst_type_max: float = 0.0
87- 
88- # When set, apply MXFP4 fake-quant to weights before the block FP8 matmul.
89 mxfp4_fake_quantize_config: MXQuantizeConfig | None = None113 mxfp4_fake_quantize_config: MXQuantizeConfig | None = None
90 114 
91 def __post_init__(self):115 def __post_init__(self):
92- # Kernel only supports block_size=32.116+ # Mode invariants first: the branches below rely on mxfp4 mode
93- assert self.block_size == 32, f"For block FP8, the block_size must be 32, block_size={self.block_size} passed."117+ # implying an FP8 ``elem_dtype``.
94- assert self.elem_dtype in (torch.float8_e4m3fn, torch.float8_e5m2), (
95- f"For block FP8, elem_dtype must be torch.float8_e4m3fn or torch.float8_e5m2, got {self.elem_dtype}"
96- )
97- assert self.round_mode == "rint", f"For block FP8, round_mode must be 'rint', got '{self.round_mode}'"
98- assert self.scale_alg == 0, f"For block FP8, scale_alg must be 0, got {self.scale_alg}"
99- assert self.dst_type_max == 0.0, f"For block FP8, dst_type_max must be 0.0, got {self.dst_type_max}"
100 if self.mxfp4_fake_quantize_config is not None:118 if self.mxfp4_fake_quantize_config is not None:
101 assert self.mxfp4_fake_quantize_config.elem_dtype == torch.float4_e2m1fn_x2, (119 assert self.mxfp4_fake_quantize_config.elem_dtype == torch.float4_e2m1fn_x2, (
102 f"mxfp4_fake_quantize_config.elem_dtype must be FP4 (torch.float4_e2m1fn_x2), "120 f"mxfp4_fake_quantize_config.elem_dtype must be FP4 (torch.float4_e2m1fn_x2), "
103 f"got {self.mxfp4_fake_quantize_config.elem_dtype}"121 f"got {self.mxfp4_fake_quantize_config.elem_dtype}"
104 )122 )
105 123 
124+ assert self.elem_dtype in (torch.float8_e4m3fn, torch.float8_e5m2), (
125+ f"When fake quantization is enabled, elem_dtype must be torch.float8_e4m3fn or torch.float8_e5m2, "
126+ f"got {self.elem_dtype}"
127+ )
128+ 
129+ if not (self.dst_type_max == 0 and self.round_mode == "rint"):
130+ warnings.warn(
131+ "When fake quantization is enabled, ``dst_type_max`` and ``round_mode`` of "
132+ "BlockMXQuantizeConfig are ignored.",
133+ stacklevel=2,
134+ )
135+ 
136+ if self.elem_dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
137+ # FP8: the block MX kernel only supports scale_alg=0, so the
138+ # inference differs from the parent's (which would pick 1). The
139+ # mxfp4 fake-quantization path does not consume ``scale_alg``, but
140+ # the same check and normalization apply there so the field's
141+ # semantics do not depend on the mode. Must run before
142+ # ``super().__post_init__()`` to pre-empt its None -> 1 inference.
143+ assert self.scale_alg is None or self.scale_alg == 0, (
144+ f"BlockMXQuantizeConfig only supports scale_alg=0 for FP8, got {self.scale_alg}"
145+ )
146+ self.scale_alg = 0
147+ 
148+ super().__post_init__()
149+ 
150+ if self.mxfp4_fake_quantize_config is None:
151+ if self.elem_dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
152+ assert self.scale_alg == 0, (
153+ f"BlockMXQuantizeConfig only supports scale_alg=0 for FP8, got {self.scale_alg}"
154+ )
155+ else:
156+ assert self.scale_alg in (0, 2), (
157+ f"BlockMXQuantizeConfig only supports scale_alg=0 or 2 for FP4, got {self.scale_alg}"
158+ )
159+ 
106 160 
107# Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True).161# Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True).
108-torch.serialization.add_safe_globals([MXQuantizeConfig, BlockQuantizeConfig])162+torch.serialization.add_safe_globals([MXQuantizeConfig, BlockMXQuantizeConfig])
@@ -1,125 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2-#
3-# This source code is licensed under the BSD-style license found in the
4-# LICENSE file in the root directory of this source tree.
5- 
6-"""Block FP8 low-level primitives for NPU.
7- 
8-These are pure tensor helpers (no autograd, no matmul) used by higher-level
9-ops in :mod:`torchao_npu.ops.block_ops`
10-(e.g., ``_BlockFP8QuantMM.forward`` calls
11-:func:`block_fp8_mxfp4_fake_quantize`).
12-"""
13- 
14-import importlib
15- 
16-import torch
17-import torch_npu
18- 
19-from ..quant_configs import BlockQuantizeConfig
20- 
21-importlib.import_module("cann_ops_nn.ops")
22- 
23- 
24-def block_fp8_mxfp4_fake_quantize(
25- tensor: torch.Tensor,
26- axis: int,
27- config: BlockQuantizeConfig,
28-) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
29- """Apply MXFP4 fake quantization, then block FP8 quantize a matmul operand.
30- 
31- Returns the quantized tensor and the two scale tensors produced by
32- ``npu_dynamic_block_mx_quant``.
33- """
34- if config.mxfp4_fake_quantize_config is not None:
35- # Lazy import to avoid circular dependency: ops.mx_ops imports
36- # quant_primitives.mx (for mxfp4_dequantize), and quant_primitives.block_fp8
37- # imports ops.mx_ops (for mxfp4_fake_quantize). Loading mxfp4_fake_quantize
38- # lazily breaks the cycle.
39- from ...ops.mx_ops import mxfp4_fake_quantize
40- 
41- tensor = mxfp4_fake_quantize(
42- tensor,
43- config.mxfp4_fake_quantize_config,
44- axis=axis,
45- )
46- return torch_npu.npu_dynamic_block_mx_quant(
47- tensor,
48- dst_type=config.elem_dtype,
49- scale_alg=config.scale_alg,
50- dst_type_max=config.dst_type_max,
51- )
52- 
53- 
54-def block_fp8_quantize(
55- tensor: torch.Tensor,
56- axis: int,
57- config: BlockQuantizeConfig,
58-) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
59- """Apply mxfp4 fake-quant (optional) then block FP8 quantize the right operand of matmul.
60- 
61- When ``mxfp4_fake_quantize_config`` is set, the MXFP4 quantized tensor is
62- converted directly to block FP8 via the fused kernel
63- ``npu_mx_to_block_mx_quant`` (with a transpose workaround since the fused
64- kernel requires packing along the last dimension).
65- 
66- Returns the quantized tensor and the two scale tensors produced by
67- ``npu_dynamic_block_mx_quant`` or the fused kernel.
68- """
69- if config.mxfp4_fake_quantize_config is not None:
70- fq_cfg = config.mxfp4_fake_quantize_config
71- 
72- if axis == -1:
73- # MXFP4 quant + fused op directly (packing already on last dim)
74- fp4_tensor, mxscale = torch_npu.npu_dynamic_mx_quant(
75- tensor,
76- axis=-1,
77- dst_type=torch_npu.float4_e2m1fn_x2,
78- block_size=fq_cfg.block_size,
79- round_mode=fq_cfg.round_mode,
80- scale_alg=fq_cfg.scale_alg,
81- dst_type_max=fq_cfg.dst_type_max,
82- )
83- return torch.ops.cann_ops_nn.mx_to_block_mx_quant.default(
84- fp4_tensor,
85- mxscale,
86- dst_type=config.elem_dtype,
87- x_type=torch_npu.float4_e2m1fn_x2,
88- )
89- 
90- elif axis == -2:
91- # Transpose so K-dim becomes last, fused op, then swap + transpose back
92- tensor_p = tensor.transpose(-2, -1)
93- 
94- fp4_tensor, mxscale = torch_npu.npu_dynamic_mx_quant(
95- tensor_p,
96- axis=-1,
97- dst_type=torch_npu.float4_e2m1fn_x2,
98- block_size=fq_cfg.block_size,
99- round_mode=fq_cfg.round_mode,
100- scale_alg=fq_cfg.scale_alg,
101- dst_type_max=fq_cfg.dst_type_max,
102- )
103- 
104- B_q_p, B_s1_p, B_s2_p = torch.ops.cann_ops_nn.mx_to_block_mx_quant.default(
105- fp4_tensor,
106- mxscale,
107- dst_type=config.elem_dtype,
108- x_type=torch_npu.float4_e2m1fn_x2,
109- )
110- 
111- B_q = B_q_p.transpose(-2, -1)
112- B_s1 = B_s2_p.transpose(-3, -2)
113- B_s2 = B_s1_p.transpose(-3, -2)
114- return B_q, B_s1, B_s2
115- 
116- else:
117- raise ValueError(f"Only axis=-1 and axis=-2 are supported, got axis={axis}")
118- 
119- # No mxfp4: direct block FP8 quant
120- return torch_npu.npu_dynamic_block_mx_quant(
121- tensor,
122- dst_type=config.elem_dtype,
123- scale_alg=config.scale_alg,
124- dst_type_max=config.dst_type_max,
125- )
@@ -0,0 +1,190 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Block MX low-level primitives for NPU.
7+ 
8+Pure tensor helpers (no autograd, no matmul) used by the ops in
9+:mod:`torchao_npu.ops.block_mx_ops`.
10+"""
11+ 
12+import importlib
13+ 
14+import torch
15+import torch_npu
16+ 
17+from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig
18+ 
19+importlib.import_module("cann_ops_nn")
20+ 
21+ 
22+def block_mx_quantize(
23+ tensor: torch.Tensor,
24+ config: BlockMXQuantizeConfig,
25+ axis: int | None = None,
26+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
27+ """Apply block MX quantization to ``tensor``, inserting an MXFP4
28+ fake-quantization when ``config.mxfp4_fake_quantize_config`` is set.
29+ 
30+ A real transpose (the ``Contiguous/Transpose`` copy the NPU ops insert for
31+ non-dense input) is avoided with best effort, but stays inevitable when:
32+ 
33+ - ``tensor`` is not a pure permutation view (e.g. an ``as_strided`` view with gaps);
34+ - restoring density would cross the leading / trailing-two-dims boundary,
35+ which would change the quantized 32x32 blocks;
36+ - ``axis`` is not the innermost-contiguous of the two trailing dims --
37+ mxfp4-fake-quantization path only.
38+ 
39+ Returns:
40+ ``(q, s1, s2)``: the quantized tensor and the dim -1 / dim -2 scales,
41+ shaped as ``npu_dynamic_block_mx_quant`` would produce for ``tensor``.
42+ Exception: direct FP4 on a transposed layout packs ``q`` along dim -2
43+ instead of dim -1 -- equivalent under the low-precision matmul, not
44+ byte-identical to the raw op.
45+ """
46+ 
47+ assert tensor.ndim >= 2, f"tensor must be at least 2D, got {tensor.ndim}D"
48+ 
49+ if config.mxfp4_fake_quantize_config is not None:
50+ assert axis is not None, "``axis`` must be set when MXFP4 fake-quantization is enabled."
51+ return _mxfp4_fake_quantize_then_block_mx_quantize(tensor, config, axis)
52+ else:
53+ return _direct_block_mx_quantize(tensor, config)
54+ 
55+ 
56+def _mxfp4_fake_quantize_then_block_mx_quantize(
57+ tensor: torch.Tensor,
58+ config: BlockMXQuantizeConfig,
59+ axis: int,
60+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
61+ """MXFP4 fake-quantize ``tensor`` along ``axis``, then convert to block MX.
62+ 
63+ The fused ``mx_to_block_mx_quant`` kernel only accepts an mxfp4 tensor
64+ packed along the last dim, so ``axis`` is permuted there and back.
65+ """
66+ 
67+ mxfp4_config = config.mxfp4_fake_quantize_config
68+ assert mxfp4_config is not None, "config.mxfp4_fake_quantize_config must be set, None passed."
69+ 
70+ assert axis in (-2, -1, tensor.ndim - 2, tensor.ndim - 1), (
71+ f"axis must point to one of the last two dims, got axis={axis} for ndim={tensor.ndim}"
72+ )
73+ 
74+ # ``axis`` must land at -1; whether that reverses [-2, -1] decides the swap.
75+ swap = axis in (-2, tensor.ndim - 2)
76+ tensor_f, perm_indices = _to_block_quant_layout(tensor, swap)
77+ 
78+ fp4_tensor, mxscale = torch_npu.npu_dynamic_mx_quant(
79+ tensor_f,
80+ axis=-1,
81+ dst_type=mxfp4_config.npu_elem_dtype,
82+ block_size=mxfp4_config.block_size,
83+ round_mode=mxfp4_config.round_mode,
84+ scale_alg=mxfp4_config.scale_alg,
85+ dst_type_max=mxfp4_config.dst_type_max,
86+ )
87+ 
88+ q_p, s1_p, s2_p = torch.ops.cann_ops_nn.mx_to_block_mx_quant(
89+ fp4_tensor,
90+ mxscale,
91+ dst_type=config.npu_elem_dtype,
92+ x_type=mxfp4_config.npu_elem_dtype,
93+ )
94+ 
95+ return _from_block_quant_layout(tensor, perm_indices, q_p, s1_p, s2_p)
96+ 
97+ 
98+def _direct_block_mx_quantize(
99+ tensor: torch.Tensor,
100+ config: BlockMXQuantizeConfig,
101+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
102+ """Block MX quantize the two trailing dims of ``tensor`` in 32x32 blocks.
103+ 
104+ ``npu_dynamic_block_mx_quant`` returns ``(q, s1, s2)``, ``s1`` along dim -1
105+ and ``s2`` along dim -2. For FP4, ``q`` packs two values per byte along the
106+ innermost-contiguous quant dim: a dense input matches the raw op
107+ byte-for-byte, a swapped layout gives a transposed-packed ``q`` -- the same
108+ values, consumable by the matmuls (which detect transposed packed weights),
109+ but not the raw op's byte layout. Scales are unaffected.
110+ """
111+ 
112+ # Descending stride puts the innermost-contiguous quant dim at -1; whether
113+ # that reverses [-2, -1] decides the swap.
114+ swap = tensor.stride(-1) > tensor.stride(-2)
115+ tensor_f, perm_indices = _to_block_quant_layout(tensor, swap)
116+ 
117+ q_p, s1_p, s2_p = torch_npu.npu_dynamic_block_mx_quant(
118+ tensor_f,
119+ dst_type=config.npu_elem_dtype,
120+ scale_alg=config.scale_alg,
121+ dst_type_max=config.dst_type_max,
122+ )
123+ # FP4 comes back as uint8 with the last dim halved; relabel it. No-op for FP8.
124+ q_p = q_p.view(config.elem_dtype)
125+ 
126+ return _from_block_quant_layout(tensor, perm_indices, q_p, s1_p, s2_p)
127+ 
128+ 
129+def _to_block_quant_layout(tensor: torch.Tensor, swap: bool) -> tuple[torch.Tensor, list[int]]:
130+ """Permute ``tensor`` into the dense 2D/3D layout the block MX kernels need.
131+ 
132+ The kernels have no stride handling, so for non-dense input they silently
133+ insert a ``Contiguous/Transpose`` copy. To avoid it we permute within two
134+ parts only -- the leading dims, and the two quant dims -- since moving a dim
135+ across that boundary would change which 32x32 blocks are quantized. A pure
136+ permutation view becomes dense and no copy happens; otherwise the kernel
137+ copies internally, no worse than being called directly. Ranks above 3 are
138+ flattened to 3D, free when the permuted tensor is dense.
139+ 
140+ Returns:
141+ ``(tensor_f, perm_indices)``, the latter to be handed to
142+ :func:`_from_block_quant_layout`.
143+ """
144+ 
145+ # Leading dims: outermost-first by stride. Quant dims: reversed iff ``swap``.
146+ strides = tensor.stride()
147+ lead = sorted(range(tensor.ndim - 2), key=lambda d: strides[d], reverse=True)
148+ quant_order = [tensor.ndim - 1, tensor.ndim - 2] if swap else [tensor.ndim - 2, tensor.ndim - 1]
149+ perm_indices = [*lead, *quant_order]
150+ 
151+ tensor_p = tensor.permute(perm_indices)
152+ tensor_f = tensor_p.reshape(-1, *tensor_p.shape[-2:]) if tensor.ndim > 3 else tensor_p
153+ return tensor_f, perm_indices
154+ 
155+ 
156+def _from_block_quant_layout(
157+ tensor: torch.Tensor,
158+ perm_indices: list[int],
159+ q_p: torch.Tensor,
160+ s1_p: torch.Tensor,
161+ s2_p: torch.Tensor,
162+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
163+ """Invert :func:`_to_block_quant_layout` on a kernel's ``(q, s1, s2)``.
164+ 
165+ Takes the ``tensor`` and ``perm_indices`` passed to and returned by it; the
166+ swap is read back from ``perm_indices``, so the two share one contract.
167+ """
168+ 
169+ shape_p = [tensor.shape[i] for i in perm_indices]
170+ 
171+ if tensor.ndim > 3:
172+ # ``q_p``'s last dim is halved for FP4, so it is taken from ``q_p`` itself.
173+ q_p = q_p.reshape(*shape_p[:-1], q_p.shape[-1])
174+ s1_p = s1_p.reshape(*shape_p[:-2], *s1_p.shape[1:])
175+ s2_p = s2_p.reshape(*shape_p[:-2], *s2_p.shape[1:])
176+ 
177+ # Inverse permutation, with the scales' trailing pack dim appended.
178+ perm_back_indices = [0] * tensor.ndim
179+ for j, p in enumerate(perm_indices):
180+ perm_back_indices[p] = j
181+ 
182+ q = q_p.permute(perm_back_indices)
183+ s1 = s1_p.permute([*perm_back_indices, tensor.ndim])
184+ s2 = s2_p.permute([*perm_back_indices, tensor.ndim])
185+ 
186+ # The kernel's s1 is along the permuted -1. If that dim is the original -2,
187+ # swap so s1 tracks the original -1 and s2 the original -2.
188+ if perm_indices[-1] == tensor.ndim - 2:
189+ s1, s2 = s2, s1
190+ return q, s1, s2
@@ -13,6 +13,193 @@ ops in :mod:`torchao_npu.ops.mx_ops`
13import functools13import functools
14 14 
15import torch15import torch
16+import torch_npu
17+ 
18+from torchao_npu import normalize_dim
19+from torchao_npu.quantization.quant_configs import MXQuantizeConfig
20+ 
21+ 
22+def mx_quantize(
23+ tensor: torch.Tensor,
24+ axis: int,
25+ config: MXQuantizeConfig,
26+) -> tuple[torch.Tensor, torch.Tensor]:
27+ """MX quantize ``tensor`` along ``axis``, avoiding a real transpose when possible.
28+ 
29+ ``npu_dynamic_mx_quant`` requires dense (``is_contiguous()``) input and,
30+ given a non-dense tensor, silently inserts a ``Contiguous/Transpose`` copy
31+ before quantizing -- even when the quant axis is already contiguous in
32+ memory (the op checks ``is_contiguous()`` on the whole tensor, not per-axis).
33+ This is an inherent limitation of the underlying operator; the kernel has no
34+ stride handling, so it can only consume a dense layout.
35+ 
36+ How a real transpose can be avoided: if the quant axis is the innermost-contiguous
37+ dimension (``stride(axis) == 1``) and ``tensor`` is not already dense, it is
38+ a pure permutation view. We then reorder dims so the quant axis lands at -1
39+ (a view, no copy), quantize along -1 (now dense, so no transpose fires), and
40+ permute both outputs back to the original layout.
41+ 
42+ When a real transpose is inevitable, no view can make the tensor dense and
43+ the raw op performs a real copy internally. (We still permute the outputs
44+ back, so the result is correct regardless.) This happens when any of:
45+ 
46+ - the quant axis is strided (``stride(axis) != 1``);
47+ - the tensor is not a pure permutation view, so the permuted tensor stays
48+ non-dense.
49+ 
50+ A dense input is nevertheless quantized as-is: ``npu_dynamic_mx_quant``
51+ only inserts the transposing copy for a non-dense tensor.
52+ 
53+ Warning:
54+ The transpose-avoiding optimization assumes every dim has a positive
55+ stride; it does not consider tensors with a stride-0 dim (e.g. a
56+ broadcast dim) yet.
57+ 
58+ Args:
59+ tensor: Tensor to quantize, shape ``(..., K, ...)``.
60+ axis: Dimension to quantize along.
61+ config: MX quantization parameters.
62+ 
63+ Returns:
64+ ``(y, scale)``; ``y`` has the same shape/dtype as ``tensor`` and
65+ ``scale`` the same shape ``npu_dynamic_mx_quant`` would produce.
66+ """
67+ 
68+ axis = normalize_dim(axis, tensor.ndim)
69+ 
70+ # Call the raw op directly
71+ # 1) tensor.stride(axis) != 1:
72+ # a quant axis that isn't innermost-contiguous, a real transpose in inevitable.
73+ # 2) tensor.stride(axis) == 1 and tensor.is_contiguous():
74+ # dense input, ``npu_dynamic_mx_quant`` does not insert a ``Contiguous/Transpose`` copy.
75+ #
76+ # The two conditions combined are simplied as below.
77+ if tensor.stride(axis) != 1 or tensor.is_contiguous():
78+ y, scale = torch_npu.npu_dynamic_mx_quant(
79+ tensor,
80+ axis=axis,
81+ dst_type=config.npu_elem_dtype,
82+ block_size=config.block_size,
83+ round_mode=config.round_mode,
84+ scale_alg=config.scale_alg,
85+ dst_type_max=config.dst_type_max,
86+ )
87+ return y.view(config.elem_dtype), scale
88+ 
89+ else:
90+ # Non-dense, innermost-contiguous quant axis: permute it to -1.
91+ # ``stride(axis) == 1`` here, so ordering the other dims by descending
92+ # stride and appending ``axis`` reproduces the dense layout (a pure view)
93+ # whenever the tensor is a pure permutation view. Appending ``axis``
94+ # explicitly -- instead of relying on a descending-stride sort to place
95+ # it last -- keeps the quant axis at -1 even when another dim ties on
96+ # stride 1, e.g. a size-1 dim.
97+ perm_indices = sorted(
98+ (d for d in range(tensor.ndim) if d != axis),
99+ key=lambda d: tensor.stride(d),
100+ reverse=True,
101+ )
102+ perm_indices.append(axis)
103+ tensor_p = tensor.permute(perm_indices)
104+ 
105+ y_p, scale_p = torch_npu.npu_dynamic_mx_quant(
106+ tensor_p,
107+ axis=-1,
108+ dst_type=config.npu_elem_dtype,
109+ block_size=config.block_size,
110+ round_mode=config.round_mode,
111+ scale_alg=config.scale_alg,
112+ dst_type_max=config.dst_type_max,
113+ )
114+ y_p = y_p.view(config.elem_dtype)
115+ 
116+ # Inverse permutation: y_p dim j corresponds to tensor dim perm_indices[j].
117+ perm_back_indices = [0] * tensor.ndim
118+ for j, p in enumerate(perm_indices):
119+ perm_back_indices[p] = j
120+ y = y_p.permute(perm_back_indices)
121+ 
122+ # scale_p has tensor.ndim+1 dims: the non-axis dims (in permuted order),
123+ # then the block dim, then the trailing pack-2 dim. The inverse
124+ # permutation already maps the quant axis to the block slot, so just
125+ # append tensor.ndim to restore the canonical layout, [.. axis .., block, .. , 2].
126+ perm_back_indices.append(tensor.ndim)
127+ scale = scale_p.permute(perm_back_indices)
128+ 
129+ return y, scale
130+ 
131+ 
132+def mx_quantize_dual_axis(
133+ tensor: torch.Tensor,
134+ config: MXQuantizeConfig,
135+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
136+ """MX quantize ``tensor`` along its two trailing dims, avoiding real transposes when possible.
137+ 
138+ ``npu_dynamic_mx_quant_with_dual_axis`` quantizes the two trailing dims of a
139+ dense tensor and returns ``(y1, s1, y2, s2)`` (``y1``/``s1`` along dim -1,
140+ ``y2``/``s2`` along dim -2). Given a non-dense tensor it silently inserts a
141+ ``Contiguous/Transpose`` copy before quantizing, because the kernel has no
142+ stride handling and can only consume a dense layout. This is an inherent
143+ limitation of the underlying operator.
144+ 
145+ How a real transpose can be avoided: the dims fall into two parts -- the two
146+ quant dims (-2, -1) and the leading dims. Crossing a dim between parts would
147+ quantize a different pair and change the semantics, so we only permute within
148+ each part. We permute each part by descending stride and quantize the result;
149+ this reproduces the raw op exactly (the op only ever quantizes the trailing
150+ two dims). When the two quant dims are the two innermost dims the permutation
151+ is dense, so no copy is needed; otherwise the op copies internally, no worse
152+ than calling it directly. If the op quantized the two dims in the opposite
153+ order, we swap ``q1``/``q2`` so the result matches the raw op.
154+ 
155+ Args:
156+ tensor: Tensor to quantize, shape ``(..., row, col)`` (``ndim >= 2``).
157+ config: MX quantization parameters.
158+ 
159+ Returns:
160+ ``(y1, s1, y2, s2)`` with the same shapes ``npu_dynamic_mx_quant_with_dual_axis``
161+ would produce for ``tensor``.
162+ """
163+ # Permute each part so that, within each part, the strides run descending.
164+ strides = tensor.stride()
165+ # Part 1 (leading dims): order them by stride so they run outermost-first.
166+ lead = sorted(range(tensor.ndim - 2), key=lambda d: strides[d], reverse=True)
167+ # Part 2 (the two quant dims): order them descending so the innermost one
168+ # lands at -1. Whether this reverses the original [-2, -1] decides the swap.
169+ swap = strides[tensor.ndim - 1] > strides[tensor.ndim - 2]
170+ quant_order = [tensor.ndim - 2, tensor.ndim - 1] if not swap else [tensor.ndim - 1, tensor.ndim - 2]
171+ perm_indices = [*lead, *quant_order]
172+ tensor_p = tensor.permute(perm_indices)
173+ 
174+ y1_p, s1_p, y2_p, s2_p = torch_npu.npu_dynamic_mx_quant_with_dual_axis(
175+ tensor_p,
176+ round_mode=config.round_mode,
177+ dst_type=config.npu_elem_dtype,
178+ scale_alg=config.scale_alg,
179+ dst_type_max=config.dst_type_max,
180+ )
181+ y1_p = y1_p.view(config.elem_dtype)
182+ y2_p = y2_p.view(config.elem_dtype)
183+ 
184+ # Inverse permutation of the tensor dims. Applying it to any op output --
185+ # appending the extra block/pack dim for a scale -- returns the tensor to the
186+ # original layout.
187+ perm_back_indices = [0] * tensor.ndim
188+ for j, p in enumerate(perm_indices):
189+ perm_back_indices[p] = j
190+ 
191+ y1 = y1_p.permute(perm_back_indices)
192+ y2 = y2_p.permute(perm_back_indices)
193+ s1 = s1_p.permute([*perm_back_indices, tensor.ndim])
194+ s2 = s2_p.permute([*perm_back_indices, tensor.ndim])
195+ 
196+ # The op's q1 is along tensor_p's -1. When the two quant dims were permuted
197+ # in the opposite order, that dim is the original -2: swap the outputs so q1
198+ # tracks the original -1 (and q2 the original -2).
199+ if swap:
200+ y1, y2 = y2, y1
201+ s1, s2 = s2, s1
202+ return y1, s1, y2, s2
16 203 
17 204 
18def mxfp4_dequantize(205def mxfp4_dequantize(
@@ -10,7 +10,7 @@ from typing import Any
10from torch import nn10from torch import nn
11from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase11from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase
12 12 
13-from .filters import ParameterFilterFn, _is_parameter13+from torchao_npu.quantization.filters import ParameterFilterFn, _is_parameter
14 14 
15"""15"""
16Registry mapping a :class:`FakeQuantizeConfigBase` type to a handler that16Registry mapping a :class:`FakeQuantizeConfigBase` type to a handler that
@@ -50,7 +50,7 @@ def unwrap_param(
50 param: nn.Parameter,50 param: nn.Parameter,
51 extra_args: tuple[Any, ...] = (),51 extra_args: tuple[Any, ...] = (),
52):52):
53- from ..wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor53+ from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
54 54 
55 # ``unwrap_param`` is invoked with parameters already wrapped by55 # ``unwrap_param`` is invoked with parameters already wrapped by
56 # ``BaseTrainingWeightWrapperTensor`` (the convert step pairs with56 # ``BaseTrainingWeightWrapperTensor`` (the convert step pairs with
@@ -3,14 +3,14 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor6+from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
7-from .block_wrapper_tensor import BlockTrainingWeightWrapperTensor7+from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor
8-from .float8_wrapper_tensor import Float8TrainingWeightWrapperTensor8+from torchao_npu.wrapper_tensors.float8_wrapper_tensor import Float8TrainingWeightWrapperTensor
9-from .mx_wrapper_tensor import MXTrainingWeightWrapperTensor9+from torchao_npu.wrapper_tensors.mx_wrapper_tensor import MXTrainingWeightWrapperTensor
10 10 
11__all__ = [11__all__ = [
12 "BaseTrainingWeightWrapperTensor",12 "BaseTrainingWeightWrapperTensor",
13- "BlockTrainingWeightWrapperTensor",13+ "BlockMXTrainingWeightWrapperTensor",
14 "Float8TrainingWeightWrapperTensor",14 "Float8TrainingWeightWrapperTensor",
15 "MXTrainingWeightWrapperTensor",15 "MXTrainingWeightWrapperTensor",
16]16]
@@ -11,7 +11,6 @@
11# This source code is licensed under the BSD 3-Clause license found in the11# This source code is licensed under the BSD 3-Clause license found in the
12# LICENSE file in the root directory of this source tree.12# LICENSE file in the root directory of this source tree.
13 13 
14- 
15import copy14import copy
16from collections.abc import Callable, Iterable15from collections.abc import Callable, Iterable
17from typing import Any16from typing import Any
@@ -278,13 +277,13 @@ class BaseTrainingWeightWrapperTensor(TorchAOBaseTensor):
278 weight_config=tensor_attributes["weight_config"],277 weight_config=tensor_attributes["weight_config"],
279 )278 )
280 279 
281- def requires_grad_(self, mode: bool = True):280+ def requires_grad_(self, requires_grad: bool = True):
282 # requires_grad_ bypasses both __torch_function__ and __torch_dispatch__,281 # requires_grad_ bypasses both __torch_function__ and __torch_dispatch__,
283 # so it only sets the flag on the wrapper. Need to keep _data in sync, otherwise282 # so it only sets the flag on the wrapper. Need to keep _data in sync, otherwise
284 # Dynamo sees _data.requires_grad=False and may drop custom autograd.Function283 # Dynamo sees _data.requires_grad=False and may drop custom autograd.Function
285 # backward during tracing, causing eager/compile gradient mismatches.284 # backward during tracing, causing eager/compile gradient mismatches.
286- super().requires_grad_(mode)285+ super().requires_grad_(requires_grad)
287- self._data.requires_grad_(mode)286+ self._data.requires_grad_(requires_grad)
288 return self287 return self
289 288 
290 def to_tensor(self) -> torch.Tensor:289 def to_tensor(self) -> torch.Tensor:
Rexperiments/torchao-npu/torchao_npu/wrapper_tensors/block_wrapper_tensor.py→experiments/torchao-npu/torchao_npu/wrapper_tensors/block_mx_wrapper_tensor.py+39-39
@@ -9,33 +9,33 @@ import torch
9from torch import nn9from torch import nn
10from torchao.prototype.moe_training.utils import unwrap_weight10from torchao.prototype.moe_training.utils import unwrap_weight
11 11 
12-from ..ops.block_ops import (12+from torchao_npu.ops.block_mx_ops import (
13- to_block_fp8_then_bmm,13+ to_block_mx_then_bmm,
14- to_block_fp8_then_grouped_mm,14+ to_block_mx_then_grouped_mm,
15- to_block_fp8_then_mm,15+ to_block_mx_then_mm,
16)16)
17-from ..quantization.quant_configs import (17+from torchao_npu.quantization.quant_configs import (
18- BlockQuantizeConfig,18+ BlockMXQuantizeConfig,
19 MXQuantizeConfig,19 MXQuantizeConfig,
20)20)
21-from ..quantization.transform import register_parameter_swap_handler21+from torchao_npu.quantization.transform import register_parameter_swap_handler
22-from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor22+from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
23 23 
24 24 
25-class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):25+class BlockMXTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
26- """Applies block FP8 quantized matmul on NPU.26+ """Applies block MX quantized matmul on NPU.
27 27 
28- Performs a **real** block FP8 matmul using28+ Performs a **real** block MX matmul using
29- ``to_block_fp8_then_mm`` / ``to_block_fp8_then_grouped_mm``.29+ ``to_block_mx_then_mm`` / ``to_block_mx_then_grouped_mm``.
30 30 
31 When ``weight_config.mxfp4_fake_quantize_config`` is set, weights are31 When ``weight_config.mxfp4_fake_quantize_config`` is set, weights are
32- pre-quantized to MXFP4 before the block FP8 matmul.32+ pre-quantized to MXFP4 before the block MX matmul.
33 """33 """
34 34 
35 def __init__(35 def __init__(
36 self,36 self,
37 tensor: torch.Tensor,37 tensor: torch.Tensor,
38- weight_config: BlockQuantizeConfig | None = None,38+ weight_config: BlockMXQuantizeConfig | None = None,
39 activation_config: MXQuantizeConfig | None = None,39 activation_config: MXQuantizeConfig | None = None,
40 ):40 ):
41 if weight_config is None:41 if weight_config is None:
@@ -44,10 +44,10 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
44 if activation_config is None:44 if activation_config is None:
45 raise ValueError(f"`activation_config` is required for {type(self).__name__}.")45 raise ValueError(f"`activation_config` is required for {type(self).__name__}.")
46 46 
47- if not isinstance(weight_config, BlockQuantizeConfig):47+ if type(weight_config) is not BlockMXQuantizeConfig:
48- raise ValueError(f"Only `BlockQuantizeConfig` is supported for `weight_config` in {type(self).__name__}.")48+ raise ValueError(f"Only `BlockMXQuantizeConfig` is supported for `weight_config` in {type(self).__name__}.")
49 49 
50- if not isinstance(activation_config, MXQuantizeConfig):50+ if type(activation_config) is not MXQuantizeConfig:
51 raise ValueError(f"Only `MXQuantizeConfig` is supported for `activation_config` in {type(self).__name__}.")51 raise ValueError(f"Only `MXQuantizeConfig` is supported for `activation_config` in {type(self).__name__}.")
52 52 
53 super().__init__(tensor, weight_config=weight_config, activation_config=activation_config)53 super().__init__(tensor, weight_config=weight_config, activation_config=activation_config)
@@ -59,23 +59,23 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
59 59 
60 if func in (torch.mm, torch.matmul):60 if func in (torch.mm, torch.matmul):
61 # 2D matmul: A @ B where B is the wrapped weight [K, N]61 # 2D matmul: A @ B where B is the wrapped weight [K, N]
62- return cls._block_fp8_mm(args, kwargs)62+ return cls._block_mx_mm(args, kwargs)
63 63 
64 elif func is torch._grouped_mm:64 elif func is torch._grouped_mm:
65 # Grouped matmul: A @ B[E,K,N] with offs=group_list65 # Grouped matmul: A @ B[E,K,N] with offs=group_list
66- return cls._block_fp8_grouped_mm(args, kwargs)66+ return cls._block_mx_grouped_mm(args, kwargs)
67 67 
68 elif func is torch.nn.functional.linear:68 elif func is torch.nn.functional.linear:
69 # Linear: A @ weight.T + bias, weight is [N, K]69 # Linear: A @ weight.T + bias, weight is [N, K]
70- return cls._block_fp8_linear(args, kwargs)70+ return cls._block_mx_linear(args, kwargs)
71 71 
72 elif func is torch.addmm:72 elif func is torch.addmm:
73 # addmm: bias + A @ B where B is the wrapped weight73 # addmm: bias + A @ B where B is the wrapped weight
74- return cls._block_fp8_addmm(args, kwargs)74+ return cls._block_mx_addmm(args, kwargs)
75 75 
76 elif func is torch.bmm:76 elif func is torch.bmm:
77 # bmm: A @ B where both are 3D and B is the wrapped weight77 # bmm: A @ B where both are 3D and B is the wrapped weight
78- return cls._block_fp8_bmm(args, kwargs)78+ return cls._block_mx_bmm(args, kwargs)
79 79 
80 else:80 else:
81 with torch._C.DisableTorchFunctionSubclass():81 with torch._C.DisableTorchFunctionSubclass():
@@ -86,7 +86,7 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
86 # ------------------------------------------------------------------86 # ------------------------------------------------------------------
87 87 
88 @classmethod88 @classmethod
89- def _block_fp8_mm(cls, args, kwargs):89+ def _block_mx_mm(cls, args, kwargs):
90 A, B = args[0], args[1]90 A, B = args[0], args[1]
91 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"91 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
92 assert isinstance(B, cls), f"B should be a {cls.__name__}"92 assert isinstance(B, cls), f"B should be a {cls.__name__}"
@@ -94,10 +94,10 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
94 B_data = unwrap_weight(B)94 B_data = unwrap_weight(B)
95 95 
96 with torch._C.DisableTorchFunctionSubclass():96 with torch._C.DisableTorchFunctionSubclass():
97- return to_block_fp8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore97+ return to_block_mx_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore
98 98 
99 @classmethod99 @classmethod
100- def _block_fp8_grouped_mm(cls, args, kwargs):100+ def _block_mx_grouped_mm(cls, args, kwargs):
101 A, B = args[0], args[1]101 A, B = args[0], args[1]
102 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"102 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
103 assert isinstance(B, cls), f"B should be a {cls.__name__}"103 assert isinstance(B, cls), f"B should be a {cls.__name__}"
@@ -106,10 +106,10 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
106 B_data = unwrap_weight(B)106 B_data = unwrap_weight(B)
107 107 
108 with torch._C.DisableTorchFunctionSubclass():108 with torch._C.DisableTorchFunctionSubclass():
109- return to_block_fp8_then_grouped_mm(A, B_data, group_list, B.activation_config, B.weight_config) # type: ignore109+ return to_block_mx_then_grouped_mm(A, B_data, group_list, B.activation_config, B.weight_config) # type: ignore
110 110 
111 @classmethod111 @classmethod
112- def _block_fp8_linear(cls, args, kwargs):112+ def _block_mx_linear(cls, args, kwargs):
113 # F.linear(A, weight, bias) — weight is [N, K], A @ weight.T + bias113 # F.linear(A, weight, bias) — weight is [N, K], A @ weight.T + bias
114 A, B = args[0], args[1]114 A, B = args[0], args[1]
115 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"115 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
@@ -119,13 +119,13 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
119 bias = args[2] if len(args) > 2 else kwargs.get("bias")119 bias = args[2] if len(args) > 2 else kwargs.get("bias")
120 120 
121 with torch._C.DisableTorchFunctionSubclass():121 with torch._C.DisableTorchFunctionSubclass():
122- result = to_block_fp8_then_mm(A, B_data.T, B.activation_config, B.weight_config) # type: ignore122+ result = to_block_mx_then_mm(A, B_data.T, B.activation_config, B.weight_config) # type: ignore
123 if bias is not None:123 if bias is not None:
124 result = result + bias124 result = result + bias
125 return result125 return result
126 126 
127 @classmethod127 @classmethod
128- def _block_fp8_addmm(cls, args, kwargs):128+ def _block_mx_addmm(cls, args, kwargs):
129 # addmm(bias, A, B) — bias + A @ B129 # addmm(bias, A, B) — bias + A @ B
130 bias, A, B = args[0], args[1], args[2]130 bias, A, B = args[0], args[1], args[2]
131 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"131 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
@@ -134,12 +134,12 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
134 B_data = unwrap_weight(B)134 B_data = unwrap_weight(B)
135 135 
136 with torch._C.DisableTorchFunctionSubclass():136 with torch._C.DisableTorchFunctionSubclass():
137- result = to_block_fp8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore137+ result = to_block_mx_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore
138 result = result + bias138 result = result + bias
139 return result139 return result
140 140 
141 @classmethod141 @classmethod
142- def _block_fp8_bmm(cls, args, kwargs):142+ def _block_mx_bmm(cls, args, kwargs):
143 # bmm(A, B) — both 3D batched matmul, B is the wrapped weight143 # bmm(A, B) — both 3D batched matmul, B is the wrapped weight
144 A, B = args[0], args[1]144 A, B = args[0], args[1]
145 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"145 assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
@@ -148,35 +148,35 @@ class BlockTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
148 B_data = unwrap_weight(B)148 B_data = unwrap_weight(B)
149 149 
150 with torch._C.DisableTorchFunctionSubclass():150 with torch._C.DisableTorchFunctionSubclass():
151- return to_block_fp8_then_bmm(A, B_data, B.activation_config, B.weight_config) # type: ignore151+ return to_block_mx_then_bmm(A, B_data, B.activation_config, B.weight_config) # type: ignore
152 152 
153 153 
154-@register_parameter_swap_handler(BlockQuantizeConfig)154+@register_parameter_swap_handler(BlockMXQuantizeConfig)
155def _(155def _(
156 module: nn.Module,156 module: nn.Module,
157 param_fqn: str,157 param_fqn: str,
158 param: nn.Parameter,158 param: nn.Parameter,
159 extra_args: tuple[Any, ...] = (),159 extra_args: tuple[Any, ...] = (),
160):160):
161- from ..configs import ParamSwapConfig161+ from torchao_npu.configs import ParamSwapConfig
162 162 
163 config: ParamSwapConfig = extra_args[0]163 config: ParamSwapConfig = extra_args[0]
164 164 
165 if not isinstance(config, ParamSwapConfig):165 if not isinstance(config, ParamSwapConfig):
166 raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.")166 raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.")
167 167 
168- if config.activation_config is not None and not isinstance(config.activation_config, MXQuantizeConfig):168+ if config.activation_config is not None and type(config.activation_config) is not MXQuantizeConfig:
169 raise ValueError(169 raise ValueError(
170 f"activation_config must be {MXQuantizeConfig.__name__}, got {type(config.activation_config).__name__}."170 f"activation_config must be {MXQuantizeConfig.__name__}, got {type(config.activation_config).__name__}."
171 )171 )
172 172 
173- if config.weight_config is not None and not isinstance(config.weight_config, BlockQuantizeConfig):173+ if config.weight_config is not None and type(config.weight_config) is not BlockMXQuantizeConfig:
174 raise ValueError(174 raise ValueError(
175- f"weight_config must be {BlockQuantizeConfig.__name__}, got {type(config.weight_config).__name__}."175+ f"weight_config must be {BlockMXQuantizeConfig.__name__}, got {type(config.weight_config).__name__}."
176 )176 )
177 177 
178 return nn.Parameter(178 return nn.Parameter(
179- data=BlockTrainingWeightWrapperTensor(179+ data=BlockMXTrainingWeightWrapperTensor(
180 param.data,180 param.data,
181 activation_config=config.activation_config,181 activation_config=config.activation_config,
182 weight_config=config.weight_config,182 weight_config=config.weight_config,
@@ -186,4 +186,4 @@ def _(
186 186 
187 187 
188# Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True).188# Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True).
189-torch.serialization.add_safe_globals([BlockTrainingWeightWrapperTensor])189+torch.serialization.add_safe_globals([BlockMXTrainingWeightWrapperTensor])
@@ -15,9 +15,9 @@ from torchao.quantization.qat.fake_quantize_config import (
15)15)
16from torchao.utils import TorchAOBaseTensor16from torchao.utils import TorchAOBaseTensor
17 17 
18-from ..ops.float8_ops import float8_rowwise_fake_quantize18+from torchao_npu.ops.float8_ops import float8_rowwise_fake_quantize
19-from ..quantization.transform import register_parameter_swap_handler19+from torchao_npu.quantization.transform import register_parameter_swap_handler
20-from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor20+from torchao_npu.wrapper_tensors import BaseTrainingWeightWrapperTensor
21 21 
22 22 
23class Float8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):23class Float8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
@@ -151,7 +151,7 @@ def _(
151 param: nn.Parameter,151 param: nn.Parameter,
152 extra_args: tuple[Any, ...] = (),152 extra_args: tuple[Any, ...] = (),
153):153):
154- from ..configs import ParamSwapConfig154+ from torchao_npu.configs import ParamSwapConfig
155 155 
156 config: ParamSwapConfig = extra_args[0]156 config: ParamSwapConfig = extra_args[0]
157 157 
@@ -9,14 +9,14 @@ import torch
9from torch import nn9from torch import nn
10from torchao.prototype.moe_training.utils import unwrap_weight10from torchao.prototype.moe_training.utils import unwrap_weight
11 11 
12-from ..ops.mx_ops import (12+from torchao_npu.ops.mx_ops import (
13 to_mx_then_bmm,13 to_mx_then_bmm,
14 to_mx_then_grouped_mm,14 to_mx_then_grouped_mm,
15 to_mx_then_mm,15 to_mx_then_mm,
16)16)
17-from ..quantization.quant_configs import MXQuantizeConfig17+from torchao_npu.quantization.quant_configs import MXQuantizeConfig
18-from ..quantization.transform import register_parameter_swap_handler18+from torchao_npu.quantization.transform import register_parameter_swap_handler
19-from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor19+from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor
20 20 
21 21 
22class MXTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):22class MXTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
@@ -43,10 +43,10 @@ class MXTrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
43 if activation_config is None:43 if activation_config is None:
44 raise ValueError(f"`activation_config` is required for {type(self).__name__}.")44 raise ValueError(f"`activation_config` is required for {type(self).__name__}.")
45 45 
46- if not isinstance(weight_config, MXQuantizeConfig):46+ if type(weight_config) is not MXQuantizeConfig:
47 raise ValueError(f"Only `MXQuantizeConfig` is supported for `weight_config` in {type(self).__name__}.")47 raise ValueError(f"Only `MXQuantizeConfig` is supported for `weight_config` in {type(self).__name__}.")
48 48 
49- if not isinstance(activation_config, MXQuantizeConfig):49+ if type(activation_config) is not MXQuantizeConfig:
50 raise ValueError(f"Only `MXQuantizeConfig` is supported for `activation_config` in {type(self).__name__}.")50 raise ValueError(f"Only `MXQuantizeConfig` is supported for `activation_config` in {type(self).__name__}.")
51 51 
52 if weight_config != activation_config:52 if weight_config != activation_config:
@@ -155,19 +155,19 @@ def _(
155 param: nn.Parameter,155 param: nn.Parameter,
156 extra_args: tuple[Any, ...] = (),156 extra_args: tuple[Any, ...] = (),
157):157):
158- from ..configs import ParamSwapConfig158+ from torchao_npu.configs import ParamSwapConfig
159 159 
160 config: ParamSwapConfig = extra_args[0]160 config: ParamSwapConfig = extra_args[0]
161 161 
162 if not isinstance(config, ParamSwapConfig):162 if not isinstance(config, ParamSwapConfig):
163 raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.")163 raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.")
164 164 
165- if config.activation_config is not None and not isinstance(config.activation_config, MXQuantizeConfig):165+ if config.activation_config is not None and type(config.activation_config) is not MXQuantizeConfig:
166 raise ValueError(166 raise ValueError(
167 f"activation_config must be {MXQuantizeConfig.__name__}, got {type(config.activation_config).__name__}."167 f"activation_config must be {MXQuantizeConfig.__name__}, got {type(config.activation_config).__name__}."
168 )168 )
169 169 
170- if config.weight_config is not None and not isinstance(config.weight_config, MXQuantizeConfig):170+ if config.weight_config is not None and type(config.weight_config) is not MXQuantizeConfig:
171 raise ValueError(171 raise ValueError(
172 f"weight_config must be {MXQuantizeConfig.__name__}, got {type(config.weight_config).__name__}."172 f"weight_config must be {MXQuantizeConfig.__name__}, got {type(config.weight_config).__name__}."
173 )173 )
@@ -26,7 +26,7 @@ import tyro
26from torchao.core.config import AOBaseConfig # noqa: TC00226from torchao.core.config import AOBaseConfig # noqa: TC002
27from torchao.quantization.quant_api import quantize_27from torchao.quantization.quant_api import quantize_
28from torchao_npu.configs import ParamSwapConfig28from torchao_npu.configs import ParamSwapConfig
29-from torchao_npu.quantization.quant_configs import BlockQuantizeConfig, MXQuantizeConfig29+from torchao_npu.quantization.quant_configs import BlockMXQuantizeConfig, MXQuantizeConfig
30from torchtitan.components.quantization import QuantizationConverter30from torchtitan.components.quantization import QuantizationConverter
31from torchtitan.config import derive31from torchtitan.config import derive
32from torchtitan.models.common.linear import Linear32from torchtitan.models.common.linear import Linear
@@ -228,7 +228,7 @@ def _block_fp8_param_swap(
228 dst_type_max=dst_type_max,228 dst_type_max=dst_type_max,
229 )229 )
230 return ParamSwapConfig(230 return ParamSwapConfig(
231- weight_config=BlockQuantizeConfig(231+ weight_config=BlockMXQuantizeConfig(
232 mxfp4_fake_quantize_config=mxfp4_config,232 mxfp4_fake_quantize_config=mxfp4_config,
233 ),233 ),
234 activation_config=MXQuantizeConfig(),234 activation_config=MXQuantizeConfig(),