Merged
[feat] unify TorchAO quantization converter for LI and metadata #800
zx1029Add on Sep 12
[feat] unify TorchAO quantization converter for LI and metadata #800
Merged
Total: 15 files changed+795-90
| @@ -145,12 +145,29 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \ | |||
| 145 | | `mix`(默认) | MXFP8 | Block FP8 | | 145 | | `mix`(默认) | MXFP8 | Block FP8 | |
| 146 | | `all_block_fp8` | Block FP8 | Block FP8 | | 146 | | `all_block_fp8` | Block FP8 | Block FP8 | |
| 147 | 147 | ||
| 148 | +LI Q/K 量化可通过以下参数单独选择,必须同时启用低精度训练: | ||
| 149 | + | ||
| 150 | +```bash | ||
| 151 | +--extension.quantization.enable-quantized-training \ | ||
| 152 | +--extension.quantization.li-quantization mxfp4 | ||
| 153 | +``` | ||
| 154 | + | ||
| 155 | +支持的 LI 量化类型及对应 CANN `quant_mode` 为: | ||
| 156 | + | ||
| 157 | +| `li-quantization` | CANN `quant_mode` | Q/K 量化方式 | | ||
| 158 | +| --- | ---: | --- | | ||
| 159 | +| `fp8` | 1 | FP8 per-token-head | | ||
| 160 | +| `mxfp8` | 3 | MXFP8 | | ||
| 161 | +| `mxfp4` | 5 | MXFP4 | | ||
| 162 | +| `hif8` | 4 | HiFloat8 per-tensor | | ||
| 163 | + | ||
| 148 | 量化相关 CLI 参数: | 164 | 量化相关 CLI 参数: |
| 149 | 165 | ||
| 150 | - `--extension.quantization.enable-quantized-training` 与 `--extension.quantization.no-enable-quantized-training`:选择低精度或高精度通路;默认使用高精度,只有显式传入 enable 开关才启用低精度。 | 166 | - `--extension.quantization.enable-quantized-training` 与 `--extension.quantization.no-enable-quantized-training`:选择低精度或高精度通路;默认使用高精度,只有显式传入 enable 开关才启用低精度。 |
| 151 | - `--extension.quantization.recipe`:选择 `all_mxfp8`、`mix` 或 `all_block_fp8`,默认使用 `mix`。 | 167 | - `--extension.quantization.recipe`:选择 `all_mxfp8`、`mix` 或 `all_block_fp8`,默认使用 `mix`。 |
| 152 | - `--extension.quantization.enable-mxfp4-qat` 与 `--extension.quantization.no-enable-mxfp4-qat`:控制 routed expert 的 Block FP8 weight 是否增加 MXFP4 QAT fake quant 数值约束,默认关闭,仅对包含 Block FP8 的 recipe 生效。该选项不是持久化 4-bit 参数训练,也不会把算子替换为原生 A8W4 GEMM。 | 168 | - `--extension.quantization.enable-mxfp4-qat` 与 `--extension.quantization.no-enable-mxfp4-qat`:控制 routed expert 的 Block FP8 weight 是否增加 MXFP4 QAT fake quant 数值约束,默认关闭,仅对包含 Block FP8 的 recipe 生效。该选项不是持久化 4-bit 参数训练,也不会把算子替换为原生 A8W4 GEMM。 |
| 153 | -- `--extension.quantization.dst-type-max`:MXFP4 fake quant 的目标数据类型最大值,默认 `0.0`,由数据类型自动推导。 | 169 | +- `--extension.quantization.li-quantization`:选择 LI Q/K 量化类型,可选 `mxfp4`、`mxfp8`、`fp8` 或 `hif8`;需要同时启用 `enable-quantized-training`。 |
| 170 | +- `--extension.quantization.dst-type-max`:量化目标数据类型最大值,用于 MXFP4 fake quant 和 HiF8 LI 量化时,默认值为 `0.0`;HiF8 支持 `0`、`15`、`56`、`224` 和 `32768`。 | ||
| 154 | - `--profiler.enable-profiling`:启用性能分析。 | 171 | - `--profiler.enable-profiling`:启用性能分析。 |
| 155 | - `USE_GOLDEN`:设为 `1` 时选择 golden attention override;默认使用 Ascend 融合算子路径。 | 172 | - `USE_GOLDEN`:设为 `1` 时选择 golden attention override;默认使用 Ascend 融合算子路径。 |
| 156 | 173 | ||
| @@ -3,10 +3,12 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -from torchao_npu.configs import ParamSwapConfig | 6 | +from torchao_npu.configs import ModuleSwapConfig, ParamSwapConfig, QuantLightningIndexerConfig |
| 7 | 7 | ||
| 8 | __all__ = [ | 8 | __all__ = [ |
| 9 | + "ModuleSwapConfig", | ||
| 9 | "ParamSwapConfig", | 10 | "ParamSwapConfig", |
| 11 | + "QuantLightningIndexerConfig", | ||
| 10 | ] | 12 | ] |
| 11 | 13 | ||
| 12 | 14 | ||
| @@ -5,8 +5,13 @@ | |||
| 5 | 5 | ||
| 6 | """Public quantization configurations for torchao-npu.""" | 6 | """Public quantization configurations for torchao-npu.""" |
| 7 | 7 | ||
| 8 | +from torchao_npu.configs.module_swap import ModuleSwapConfig | ||
| 9 | +from torchao_npu.configs.module_swap_configs import QuantLightningIndexerConfig, quant_mode_for_config | ||
| 8 | from torchao_npu.configs.param_swap import ParamSwapConfig | 10 | from torchao_npu.configs.param_swap import ParamSwapConfig |
| 9 | 11 | ||
| 10 | __all__ = [ | 12 | __all__ = [ |
| 13 | + "ModuleSwapConfig", | ||
| 11 | "ParamSwapConfig", | 14 | "ParamSwapConfig", |
| 15 | + "QuantLightningIndexerConfig", | ||
| 16 | + "quant_mode_for_config", | ||
| 12 | ] | 17 | ] |
| @@ -0,0 +1,26 @@ | |||
| 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 | +"""TorchAO module-level QAT configuration primitives.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["ModuleSwapConfig"] | ||
| 9 | + | ||
| 10 | +from dataclasses import dataclass | ||
| 11 | +from typing import ClassVar | ||
| 12 | + | ||
| 13 | +from torchao.quantization.qat import QATConfig, QATStep | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +@dataclass(kw_only=True, slots=True) | ||
| 17 | +class ModuleSwapConfig(QATConfig): | ||
| 18 | + """Base config for transforms which replace a module's forward behavior.""" | ||
| 19 | + | ||
| 20 | + base_config: ClassVar[None] = None | ||
| 21 | + activation_config: ClassVar[None] = None | ||
| 22 | + weight_config: ClassVar[None] = None | ||
| 23 | + step: QATStep = QATStep.PREPARE | ||
| 24 | + | ||
| 25 | + def __post_init__(self) -> None: | ||
| 26 | + self.step = QATStep(self.step) | ||
| @@ -0,0 +1,13 @@ | |||
| 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 | +"""Concrete module-swap quantization configs.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["QuantLightningIndexerConfig", "quant_mode_for_config"] | ||
| 9 | + | ||
| 10 | +from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import ( | ||
| 11 | + QuantLightningIndexerConfig, | ||
| 12 | + quant_mode_for_config, | ||
| 13 | +) | ||
| @@ -0,0 +1,95 @@ | |||
| 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 | +"""Unified quantized configuration for QuantLightningIndexerV2.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["QuantLightningIndexerConfig", "quant_mode_for_config"] | ||
| 9 | + | ||
| 10 | +from collections.abc import Callable | ||
| 11 | +from dataclasses import dataclass, field | ||
| 12 | +from types import MethodType | ||
| 13 | +from typing import Annotated | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | +import torch_npu | ||
| 17 | +import tyro | ||
| 18 | +from torchao.quantization.qat import QATStep | ||
| 19 | +from torchao.quantization.transform_module import register_quantize_module_handler | ||
| 20 | + | ||
| 21 | +from torchao_npu.configs.module_swap import ModuleSwapConfig | ||
| 22 | +from torchao_npu.quantization.quant_configs import FP8QuantizeConfig, HiF8QuantizeConfig, MXQuantizeConfig | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def _mxfp4_config() -> MXQuantizeConfig: | ||
| 26 | + return MXQuantizeConfig(elem_dtype=torch.float4_e2m1fn_x2) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +_LI_QUANT_MODE_TABLE = ( | ||
| 30 | + (FP8QuantizeConfig, torch.float8_e4m3fn, 1, "pertoken"), | ||
| 31 | + (MXQuantizeConfig, torch.float8_e4m3fn, 3, None), | ||
| 32 | + (HiF8QuantizeConfig, torch_npu.hifloat8, 4, "pertensor"), | ||
| 33 | + (MXQuantizeConfig, torch.float4_e2m1fn_x2, 5, None), | ||
| 34 | +) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def quant_mode_for_config(config: MXQuantizeConfig | HiF8QuantizeConfig | FP8QuantizeConfig) -> int: | ||
固定的量化配置组合建议移出功能支持代码,放在converter里。QuantLightningIndexerConfig的 ![]() ![]() zx1029 Sep 14 Comments: Sep 14 Comments: ![]() ![]() caoshuyang Sep 14 Comments: Sep 14 Comments: ![]() ![]() | |||
| 38 | + """Return the CANN LI quant mode for one Q/K quantization config.""" | ||
| 39 | + | ||
| 40 | + for config_type, elem_dtype, quant_mode, dynamic_quant_mode in _LI_QUANT_MODE_TABLE: | ||
| 41 | + if isinstance(config, config_type) and config.elem_dtype == elem_dtype: | ||
| 42 | + if dynamic_quant_mode is not None and config.quant_mode != dynamic_quant_mode: | ||
| 43 | + raise ValueError(f"LI quant_mode={quant_mode} requires dynamic quant_mode={dynamic_quant_mode!r}") | ||
| 44 | + return quant_mode | ||
| 45 | + if isinstance(config, MXQuantizeConfig): | ||
| 46 | + raise ValueError("QuantLightningIndexerConfig does not support this MX element dtype") | ||
| 47 | + raise TypeError(f"Unsupported LI quantization config: {type(config).__name__}") | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +@dataclass(kw_only=True, slots=True) | ||
| 51 | +class QuantLightningIndexerConfig(ModuleSwapConfig): | ||
| 52 | + """Q/K quantization strategy for QuantLightningIndexerV2. | ||
| 53 | + | ||
| 54 | + ``quant_mode`` follows the CANN contract: 1=FP8 per-token-head, 3=MXFP8, 4=HiFloat8, and | ||
| 55 | + 5=MXFP4. The converter supplies the mode-specific configs and host input | ||
| 56 | + adapter; standalone users must provide an input adapter explicitly. | ||
| 57 | + """ | ||
| 58 | + | ||
| 59 | + layout_q: str = "TND" | ||
| 60 | + layout_k: str = "TND" | ||
| 61 | + mask_mode: int = 3 | ||
| 62 | + cmp_ratio: int = 4 | ||
| 63 | + query_config: MXQuantizeConfig | HiF8QuantizeConfig | FP8QuantizeConfig = field(default_factory=_mxfp4_config) | ||
| 64 | + key_config: MXQuantizeConfig | HiF8QuantizeConfig | FP8QuantizeConfig = field(default_factory=_mxfp4_config) | ||
| 65 | + quant_mode: int = 5 | ||
建议去掉quant_mode。用户可以直接指定q、k量化配置。QuantLightningIndexerConfig在 ![]() ![]() | |||
| 66 | + input_adapter: Annotated[Callable | None, tyro.conf.Suppress] = field(default=None, repr=False, compare=False) | ||
| 67 | + | ||
| 68 | + def __post_init__(self) -> None: | ||
| 69 | + # ``slots=True`` recreates the dataclass class, so use an explicit | ||
| 70 | + # base call instead of zero-argument ``super()``. | ||
| 71 | + ModuleSwapConfig.__post_init__(self) | ||
| 72 | + if type(self.query_config) is not type(self.key_config): | ||
| 73 | + raise ValueError("query_config and key_config must use the same config type") | ||
| 74 | + if self.query_config.elem_dtype != self.key_config.elem_dtype: | ||
| 75 | + raise ValueError("query_config and key_config must use the same element dtype") | ||
| 76 | + expected_mode = quant_mode_for_config(self.query_config) | ||
| 77 | + if self.quant_mode != expected_mode: | ||
| 78 | + raise ValueError( | ||
| 79 | + f"quant_mode={self.quant_mode} does not match the selected quantization config; " | ||
| 80 | + f"expected {expected_mode}" | ||
| 81 | + ) | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +@register_quantize_module_handler(QuantLightningIndexerConfig) | ||
| 85 | +def _quant_lightning_indexer_transform(module, config: QuantLightningIndexerConfig): | ||
| 86 | + from torchao_npu.quantized_modules.lightning_indexer import quantized_lightning_indexer_forward | ||
| 87 | + | ||
| 88 | + if not hasattr(module, "_torchao_npu_original_forward"): | ||
| 89 | + module._torchao_npu_original_forward = module.forward | ||
| 90 | + if config.step == QATStep.PREPARE: | ||
| 91 | + module._torchao_npu_module_swap_config = config | ||
| 92 | + module.forward = MethodType(quantized_lightning_indexer_forward, module) | ||
| 93 | + else: | ||
| 94 | + module.forward = module._torchao_npu_original_forward | ||
| 95 | + return module | ||
| @@ -0,0 +1,111 @@ | |||
| 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 | +"""Quantized QuantLightningIndexerV2 operator bridge.""" | ||
| 7 | + | ||
| 8 | +__all__ = [ | ||
| 9 | + "quant_lightning_indexer", | ||
| 10 | + "quant_lightning_indexer_metadata", | ||
| 11 | + "quantize_lightning_indexer_input", | ||
| 12 | +] | ||
| 13 | + | ||
| 14 | +import cann_ops_transformer | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | +from torchao_npu.quantization.quant_configs import FP8QuantizeConfig, HiF8QuantizeConfig, MXQuantizeConfig | ||
| 18 | +from torchao_npu.quantization.quant_primitives.fp8 import fp8_quantize | ||
| 19 | +from torchao_npu.quantization.quant_primitives.hif8 import quantize_hifloat8 | ||
| 20 | +from torchao_npu.quantization.quant_primitives.mx import mx_quantize | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def quantize_lightning_indexer_input(value: torch.Tensor, config): | ||
| 24 | + """Quantize one LI Q/K input according to its TorchAO config.""" | ||
| 25 | + | ||
| 26 | + if isinstance(config, FP8QuantizeConfig): | ||
| 27 | + return fp8_quantize(value, config) | ||
| 28 | + if isinstance(config, MXQuantizeConfig): | ||
| 29 | + q_data, descale = mx_quantize(value, -1, config) | ||
| 30 | + # The LI quant_mode identifies packed FP4; CANN consumes uint8 storage. | ||
| 31 | + if config.elem_dtype is torch.float4_e2m1fn_x2: | ||
| 32 | + q_data = q_data.view(torch.uint8) | ||
| 33 | + return q_data, descale.view(torch.float8_e8m0fnu) | ||
| 34 | + if isinstance(config, HiF8QuantizeConfig): | ||
| 35 | + return quantize_hifloat8(value, config) | ||
| 36 | + raise TypeError(f"Unsupported QuantLightningIndexer quantization config: {type(config).__name__}") | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def quant_lightning_indexer_metadata( | ||
| 40 | + *, | ||
| 41 | + index_n_heads: int, | ||
| 42 | + index_head_dim: int, | ||
| 43 | + topk: int, | ||
| 44 | + quant_mode: int, | ||
| 45 | + layout_q: str, | ||
| 46 | + layout_k: str, | ||
| 47 | + mask_mode: int, | ||
| 48 | + cmp_ratio: int, | ||
| 49 | + cu_seqlens_q: torch.Tensor, | ||
| 50 | + cu_seqlens_k: torch.Tensor, | ||
| 51 | + cmp_residual_k: torch.Tensor, | ||
| 52 | +): | ||
| 53 | + """Build metadata paired with ``quant_lightning_indexer``.""" | ||
| 54 | + | ||
| 55 | + return cann_ops_transformer.quant_lightning_indexer_metadata( | ||
| 56 | + index_n_heads, | ||
| 57 | + 1, | ||
| 58 | + index_head_dim, | ||
| 59 | + topk, | ||
| 60 | + quant_mode, | ||
| 61 | + layout_q=layout_q, | ||
| 62 | + layout_k=layout_k, | ||
| 63 | + mask_mode=mask_mode, | ||
| 64 | + cmp_ratio=cmp_ratio, | ||
| 65 | + cu_seqlens_q=cu_seqlens_q, | ||
| 66 | + cu_seqlens_k=cu_seqlens_k, | ||
| 67 | + cmp_residual_k=cmp_residual_k, | ||
| 68 | + ) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def quant_lightning_indexer( | ||
| 72 | + q: torch.Tensor, | ||
单纯传参的冗余封装建议去掉。 ![]() ![]() | |||
| 73 | + k: torch.Tensor, | ||
| 74 | + w: torch.Tensor, | ||
| 75 | + q_config, | ||
| 76 | + k_config, | ||
| 77 | + *, | ||
| 78 | + topk: int, | ||
| 79 | + quant_mode: int, | ||
| 80 | + layout_q: str, | ||
| 81 | + layout_k: str, | ||
| 82 | + mask_mode: int, | ||
| 83 | + cmp_ratio: int, | ||
| 84 | + cu_seqlens_q: torch.Tensor, | ||
| 85 | + cu_seqlens_k: torch.Tensor, | ||
| 86 | + cmp_residual_k: torch.Tensor, | ||
| 87 | + metadata: torch.Tensor, | ||
| 88 | +): | ||
| 89 | + """Run QuantLightningIndexerV2 on packed TND quantized Q/K tensors.""" | ||
| 90 | + | ||
| 91 | + q_data, q_descale = quantize_lightning_indexer_input(q, q_config) | ||
| 92 | + k_data, k_descale = quantize_lightning_indexer_input(k, k_config) | ||
| 93 | + | ||
| 94 | + return cann_ops_transformer.quant_lightning_indexer( | ||
| 95 | + q_data, | ||
| 96 | + k_data, | ||
| 97 | + w, | ||
| 98 | + q_descale, | ||
| 99 | + k_descale, | ||
| 100 | + topk, | ||
| 101 | + quant_mode, | ||
| 102 | + cu_seqlens_q=cu_seqlens_q, | ||
| 103 | + cu_seqlens_k=cu_seqlens_k, | ||
| 104 | + cmp_residual_k=cmp_residual_k, | ||
| 105 | + metadata=metadata, | ||
| 106 | + layout_q=layout_q, | ||
| 107 | + layout_k=layout_k, | ||
| 108 | + mask_mode=mask_mode, | ||
| 109 | + cmp_ratio=cmp_ratio, | ||
| 110 | + return_value=0, | ||
| 111 | + ) | ||
| @@ -13,6 +13,7 @@ import warnings | |||
| 13 | from dataclasses import dataclass, field | 13 | from dataclasses import dataclass, field |
| 14 | 14 | ||
| 15 | import torch | 15 | import torch |
| 16 | +import torch_npu | ||
| 16 | from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase | 17 | from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase |
| 17 | 18 | ||
| 18 | from torchao_npu.quantization import _NPU_DTYPE_DICT | 19 | from torchao_npu.quantization import _NPU_DTYPE_DICT |
| @@ -22,6 +23,7 @@ NPU_SUPPORTED_ELEM_DTYPES = [ | |||
| 22 | torch.float8_e5m2, | 23 | torch.float8_e5m2, |
| 23 | torch.float4_e2m1fn_x2, | 24 | torch.float4_e2m1fn_x2, |
| 24 | ] | 25 | ] |
| 26 | +_DYNAMIC_QUANT_MODES = frozenset(("pertoken", "pertensor", "perchannel")) | ||
| 25 | 27 | ||
| 26 | 28 | ||
| 27 | @dataclass | 29 | @dataclass |
| @@ -89,6 +91,41 @@ class MXQuantizeConfig(FakeQuantizeConfigBase): | |||
| 89 | ) | 91 | ) |
| 90 | 92 | ||
| 91 | 93 | ||
| 94 | +@dataclass | ||
| 95 | +class FP8QuantizeConfig(FakeQuantizeConfigBase): | ||
| 96 | + """E4M3FN dynamic quantization configuration.""" | ||
| 97 | + | ||
| 98 | + elem_dtype: torch.dtype = torch.float8_e4m3fn | ||
| 99 | + quant_mode: str = "pertoken" | ||
| 100 | + | ||
| 101 | + @property | ||
| 102 | + def npu_elem_dtype(self) -> int: | ||
| 103 | + return _NPU_DTYPE_DICT[self.elem_dtype] | ||
| 104 | + | ||
| 105 | + def __post_init__(self): | ||
| 106 | + if self.elem_dtype is not torch.float8_e4m3fn: | ||
| 107 | + raise ValueError("FP8QuantizeConfig only supports torch.float8_e4m3fn") | ||
| 108 | + if self.quant_mode not in _DYNAMIC_QUANT_MODES: | ||
| 109 | + raise ValueError(f"FP8QuantizeConfig quant_mode must be one of {_DYNAMIC_QUANT_MODES}") | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +@dataclass | ||
| 113 | +class HiF8QuantizeConfig(FakeQuantizeConfigBase): | ||
| 114 | + """HiFloat8 dynamic quantization configuration.""" | ||
| 115 | + | ||
| 116 | + elem_dtype: object = torch_npu.hifloat8 | ||
| 117 | + dst_type_max: float = 0.0 | ||
| 118 | + quant_mode: str = "pertensor" | ||
| 119 | + | ||
| 120 | + def __post_init__(self): | ||
| 121 | + if self.elem_dtype != torch_npu.hifloat8: | ||
| 122 | + raise ValueError("HiF8QuantizeConfig requires torch_npu.hifloat8") | ||
| 123 | + if self.quant_mode not in _DYNAMIC_QUANT_MODES: | ||
| 124 | + raise ValueError(f"HiF8QuantizeConfig quant_mode must be one of {_DYNAMIC_QUANT_MODES}") | ||
| 125 | + if self.dst_type_max not in (0.0, 15.0, 56.0, 224.0, 32768.0): | ||
| 126 | + raise ValueError("HiF8QuantizeConfig dst_type_max must be one of 0, 15, 56, 224, or 32768") | ||
| 127 | + | ||
| 128 | + | ||
| 92 | @dataclass | 129 | @dataclass |
| 93 | class BlockMXQuantizeConfig(MXQuantizeConfig): | 130 | class BlockMXQuantizeConfig(MXQuantizeConfig): |
| 94 | """ | 131 | """ |
| @@ -159,4 +196,4 @@ class BlockMXQuantizeConfig(MXQuantizeConfig): | |||
| 159 | 196 | ||
| 160 | 197 | ||
| 161 | # Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True). | 198 | # Safe-unpickling allowlist: DCP loads checkpoints with torch.load(weights_only=True). |
| 162 | -torch.serialization.add_safe_globals([MXQuantizeConfig, BlockMXQuantizeConfig]) | 199 | +torch.serialization.add_safe_globals([MXQuantizeConfig, BlockMXQuantizeConfig, HiF8QuantizeConfig, FP8QuantizeConfig]) |
| @@ -0,0 +1,36 @@ | |||
| 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 | +"""FP8 per-token-head quantization with FP32 dequantization scales.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["fp8_quantize"] | ||
| 9 | + | ||
| 10 | +import torch | ||
| 11 | +import torch_npu | ||
| 12 | + | ||
| 13 | +from torchao_npu.quantization.quant_configs import FP8QuantizeConfig | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def fp8_quantize( | ||
| 17 | + tensor: torch.Tensor, | ||
| 18 | + config: FP8QuantizeConfig, | ||
| 19 | +) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 20 | + """Quantize each last-axis vector independently to E4M3FN. | ||
| 21 | + | ||
| 22 | + For TND / BSND inputs, return FP8 data with the input shape and FP32 | ||
| 23 | + descales shaped TN / BSN. Reconstruction is ``data.float() * | ||
| 24 | + descale.unsqueeze(-1)``. DynamicQuant reduces the last axis, so each | ||
| 25 | + token/head gets its own scale without flattening or mixing heads. | ||
| 26 | + Scale calculation and zero-vector handling follow the fused NPU kernel. | ||
| 27 | + """ | ||
| 28 | + if tensor.dtype not in (torch.float16, torch.bfloat16): | ||
| 29 | + raise ValueError("NPU FP8 DynamicQuant requires float16 or bfloat16 input") | ||
| 30 | + if tensor.ndim < 2: | ||
| 31 | + raise ValueError("NPU FP8 DynamicQuant requires input with at least two dimensions") | ||
| 32 | + return torch_npu.npu_dynamic_quant( | ||
torch_npu.npu_dynamic_quant是否跟npu_dynamic_mx_quant一样对输入张量的内存连续性有要求?是否会在输入不满足要求的情况下触发额外的内存操作。 ![]() ![]() | |||
| 33 | + tensor, | ||
| 34 | + dst_type=config.npu_elem_dtype, | ||
| 35 | + quant_mode=config.quant_mode, | ||
| 36 | + ) | ||
| @@ -0,0 +1,27 @@ | |||
| 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 | +"""HiFloat8 quantization primitive.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["quantize_hifloat8"] | ||
| 9 | + | ||
| 10 | +import torch | ||
| 11 | +import torch_npu | ||
| 12 | + | ||
| 13 | +from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def quantize_hifloat8(value: torch.Tensor, config: HiF8QuantizeConfig): | ||
原子级量化操作建议放到experiments/torchao-npu/torchao_npu/quantization/quant_primitives下,与mx量化、block_mx量化保持一致 ![]() ![]() 与其他两种fp8使用相同的算子,接受相同的配置。在HiF8QuantizeConfig合并到FP8QuantizeConfig之后,fp8_quantize的功能完全覆盖quantize_hifloat8,可以考虑删除该函数。 ![]() ![]() | |||
| 17 | + """Quantize a tensor to HiFloat8 with a float32 scale.""" | ||
| 18 | + | ||
| 19 | + if value.dtype not in (torch.float16, torch.bfloat16): | ||
| 20 | + value = value.to(torch.bfloat16) | ||
| 21 | + q_data, descale = torch_npu.npu_dynamic_quant( | ||
| 22 | + value, | ||
| 23 | + dst_type=config.elem_dtype, | ||
| 24 | + dst_type_max=config.dst_type_max, | ||
| 25 | + quant_mode=config.quant_mode, | ||
| 26 | + ) | ||
| 27 | + return q_data, descale.to(torch.float32) | ||
| @@ -0,0 +1,58 @@ | |||
| 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 | +"""TorchAO-NPU QuantLightningIndexer module behavior.""" | ||
| 7 | + | ||
| 8 | +__all__ = [ | ||
| 9 | + "QuantizedLightningIndexerInputs", | ||
| 10 | + "quantized_lightning_indexer_forward", | ||
| 11 | +] | ||
| 12 | + | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | +from torchao_npu.ops.li_ops import quant_lightning_indexer | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@dataclass(frozen=True, slots=True) | ||
| 21 | +class QuantizedLightningIndexerInputs: | ||
| 22 | + """Host-normalized inputs consumed by the quantized LI kernel.""" | ||
| 23 | + | ||
| 24 | + query: torch.Tensor | ||
| 25 | + key: torch.Tensor | ||
| 26 | + weights: torch.Tensor | ||
| 27 | + topk: int | ||
| 28 | + metadata: torch.Tensor | ||
| 29 | + cu_seqlens_q: torch.Tensor | ||
| 30 | + cu_seqlens_k: torch.Tensor | ||
| 31 | + cmp_residual_k: torch.Tensor | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def quantized_lightning_indexer_forward(self, idx_q, idx_k, idx_w, *, attention_masks): | ||
| 35 | + """Run the quantized LI kernel using a host-provided input adapter.""" | ||
| 36 | + | ||
| 37 | + config = self._torchao_npu_module_swap_config | ||
| 38 | + if config.input_adapter is None: | ||
| 39 | + raise RuntimeError("Quantized LI requires a host input adapter") | ||
| 40 | + inputs = config.input_adapter(self, idx_q, idx_k, idx_w, attention_masks) | ||
| 41 | + sparse_indices, _ = quant_lightning_indexer( | ||
| 42 | + inputs.query, | ||
| 43 | + inputs.key, | ||
| 44 | + inputs.weights, | ||
| 45 | + config.query_config, | ||
| 46 | + config.key_config, | ||
| 47 | + topk=inputs.topk, | ||
| 48 | + quant_mode=config.quant_mode, | ||
| 49 | + layout_q=config.layout_q, | ||
| 50 | + layout_k=config.layout_k, | ||
| 51 | + mask_mode=config.mask_mode, | ||
| 52 | + cmp_ratio=config.cmp_ratio, | ||
| 53 | + cu_seqlens_q=inputs.cu_seqlens_q, | ||
| 54 | + cu_seqlens_k=inputs.cu_seqlens_k, | ||
| 55 | + cmp_residual_k=inputs.cmp_residual_k, | ||
| 56 | + metadata=inputs.metadata, | ||
| 57 | + ) | ||
| 58 | + return sparse_indices.reshape(idx_q.shape[0], idx_q.shape[1], 1, -1) | ||
| @@ -0,0 +1,67 @@ | |||
| 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 | +"""TorchAO-NPU QuantLightningIndexer metadata implementation.""" | ||
| 7 | + | ||
| 8 | +__all__ = [ | ||
| 9 | + "QuantizedLightningIndexerMetadata", | ||
| 10 | + "QuantizedLightningIndexerMetadataConfig", | ||
| 11 | +] | ||
| 12 | + | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | +from torchao_npu.ops.li_ops import quant_lightning_indexer_metadata | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@dataclass(kw_only=True, slots=True) | ||
| 21 | +class QuantizedLightningIndexerMetadataConfig: | ||
| 22 | + """Quantized LI metadata parameters supplied by the host integration.""" | ||
建议在 ![]() ![]() zx1029 Sep 14 Comments: Sep 14 Comments: ![]() ![]() caoshuyang Sep 14 Comments: Sep 14 Comments: ![]() ![]() | |||
| 23 | + | ||
| 24 | + index_n_heads: int | ||
| 25 | + index_head_dim: int | ||
| 26 | + index_topk: int | ||
| 27 | + layout_q: str | ||
| 28 | + layout_k: str | ||
| 29 | + mask_mode: int | ||
| 30 | + cmp_ratio: int | ||
| 31 | + quant_mode: int = 5 | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +class QuantizedLightningIndexerMetadata: | ||
| 35 | + """Build quantized LI metadata from explicit varlen kernel inputs. | ||
| 36 | + | ||
| 37 | + The host integration owns its metadata container and plan mutation. This | ||
| 38 | + class only owns the quantized kernel call and has no dependency on host | ||
| 39 | + model or metadata container types. | ||
| 40 | + """ | ||
| 41 | + | ||
| 42 | + Config = QuantizedLightningIndexerMetadataConfig | ||
| 43 | + | ||
| 44 | + def __init__(self, config: QuantizedLightningIndexerMetadataConfig): | ||
| 45 | + self.config = config | ||
| 46 | + | ||
| 47 | + def __call__( | ||
| 48 | + self, | ||
| 49 | + *, | ||
| 50 | + cu_seqlens_q: torch.Tensor, | ||
| 51 | + cu_seqlens_k: torch.Tensor, | ||
| 52 | + cmp_residual_k: torch.Tensor, | ||
| 53 | + ) -> torch.Tensor: | ||
| 54 | + cfg = self.config | ||
| 55 | + return quant_lightning_indexer_metadata( | ||
| 56 | + index_n_heads=cfg.index_n_heads, | ||
| 57 | + index_head_dim=cfg.index_head_dim, | ||
| 58 | + topk=cfg.index_topk, | ||
| 59 | + quant_mode=cfg.quant_mode, | ||
| 60 | + layout_q=cfg.layout_q, | ||
| 61 | + layout_k=cfg.layout_k, | ||
| 62 | + mask_mode=cfg.mask_mode, | ||
| 63 | + cmp_ratio=cfg.cmp_ratio, | ||
| 64 | + cu_seqlens_q=cu_seqlens_q, | ||
| 65 | + cu_seqlens_k=cu_seqlens_k, | ||
| 66 | + cmp_residual_k=cmp_residual_k, | ||
| 67 | + ) | ||
| @@ -7,8 +7,9 @@ | |||
| 7 | 7 | ||
| 8 | TorchTitan builds models from a tree of ``Module.Config`` objects. Quantization | 8 | TorchTitan builds models from a tree of ``Module.Config`` objects. Quantization |
| 9 | must therefore be expressed in that tree before the model is built: a converter | 9 | must therefore be expressed in that tree before the model is built: a converter |
| 10 | -replaces selected configs with configs whose modules install the torchao-npu | 10 | +replaces selected configs with configs whose modules install torchao-npu |
| 11 | -parameter wrappers in ``__init__``. This keeps the wrappers in place before | 11 | +parameter wrappers or module-level QAT behavior in ``__init__``. This keeps |
| 12 | +the transforms in place before | ||
| 12 | TP/EP/FSDP and optimizer construction without modifying TorchTitan's trainer. | 13 | TP/EP/FSDP and optimizer construction without modifying TorchTitan's trainer. |
| 13 | 14 | ||
| 14 | Only this adapter lives in ``torchtitan_npu``. Quantization configs, parameter | 15 | Only this adapter lives in ``torchtitan_npu``. Quantization configs, parameter |
| @@ -15,6 +15,7 @@ from torchtitan.config import TrainingConfig as _BaseTrainingConfig | |||
| 15 | from torchtitan.tools.profiler import Profiler as _BaseProfiler | 15 | from torchtitan.tools.profiler import Profiler as _BaseProfiler |
| 16 | 16 | ||
| 17 | QuantizationRecipe = Literal["all_mxfp8", "mix", "all_block_fp8"] | 17 | QuantizationRecipe = Literal["all_mxfp8", "mix", "all_block_fp8"] |
| 18 | +LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] | ||
| 18 | 19 | ||
| 19 | 20 | ||
| 20 | @dataclass(frozen=True, slots=True) | 21 | @dataclass(frozen=True, slots=True) |
| @@ -110,8 +111,18 @@ class QuantizationExtensionConfig: | |||
| 110 | enable_quantized_training: bool = False | 111 | enable_quantized_training: bool = False |
| 111 | recipe: QuantizationRecipe = "mix" | 112 | recipe: QuantizationRecipe = "mix" |
| 112 | enable_mxfp4_qat: bool = False | 113 | enable_mxfp4_qat: bool = False |
| 114 | + li_quantization: LIQuantization | None = None | ||
同样的改名,并在doc中补充使用说明 ![]() ![]() | |||
| 115 | + """LI Q/K format. | ||
| 116 | + | ||
| 117 | + MXFP4/MXFP8 use MX block scales, FP8 uses per-token-head scales, and HiF8 | ||
| 118 | + uses per-tensor scales. | ||
| 119 | + """ | ||
| 113 | dst_type_max: float = 0.0 | 120 | dst_type_max: float = 0.0 |
| 114 | 121 | ||
| 122 | + def validate(self) -> None: | ||
这里的校验是不是在通过 TrainerEx 启动训练时不会生效? 对应torchtitan_npu/extensions/trainer.py:59-74
这个时候如果配置enable_quantized_training = False li_quantization = "fp8",也不会执行validate内的校验吧 ![]() ![]() | |||
| 123 | + if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): | ||
| 124 | + raise ValueError("li_quantization must be None or one of: mxfp4, mxfp8, fp8, hif8") | ||
| 125 | + | ||
| 115 | 126 | ||
| 116 | @dataclass(kw_only=True, slots=True) | 127 | @dataclass(kw_only=True, slots=True) |
| 117 | class ExtensionConfig: | 128 | class ExtensionConfig: |
| @@ -18,22 +18,13 @@ from torchtitan.config.configurable import Configurable | |||
| 18 | 18 | ||
| 19 | @dataclass(kw_only=True, slots=True) | 19 | @dataclass(kw_only=True, slots=True) |
| 20 | class LightningIndexerKernelConfig: | 20 | class LightningIndexerKernelConfig: |
| 21 | - """DSV4 LI contract shared by metadata and kernel callers. | 21 | + """LI kernel contract shared by metadata and kernel callers.""" |
| 22 | - | ||
| 23 | - The current DSV4 implementation supports only the ratio-4 TND contract. | ||
| 24 | - """ | ||
| 25 | 22 | ||
| 26 | layout_q: str = "TND" | 23 | layout_q: str = "TND" |
| 27 | layout_k: str = "TND" | 24 | layout_k: str = "TND" |
| 28 | mask_mode: int = 3 | 25 | mask_mode: int = 3 |
| 29 | cmp_ratio: int = 4 | 26 | cmp_ratio: int = 4 |
| 30 | 27 | ||
| 31 | - def __post_init__(self) -> None: | ||
| 32 | - if (self.layout_q, self.layout_k, self.mask_mode, self.cmp_ratio) != ("TND", "TND", 3, 4): | ||
| 33 | - raise ValueError( | ||
| 34 | - "DeepSeek-V4 LightningIndexer supports only layout_q='TND', layout_k='TND', mask_mode=3, cmp_ratio=4" | ||
| 35 | - ) | ||
| 36 | - | ||
| 37 | 28 | ||
| 38 | class MetadataExtension(Configurable): | 29 | class MetadataExtension(Configurable): |
| 39 | """The default identity post-process of the built attention masks.""" | 30 | """The default identity post-process of the built attention masks.""" |


仍然不建议定义ModuleSwapConfig这个基类,因为一个module的权重很可能不止一个,也可能一个都没有。其接受的激活也可能不止一个。因此 ModuleSwapConfig中的activation_config和 weight_config很可能不具有可复用性。建议直接定义QuantLightningIndexerConfig然后提供quantize_需要的handler。