Merged
[feat] Support Deepseek v4 HiFloat8 current-tensor scaling training through TorchAO #925
nancycyzlAdd on Sep 23
[feat] Support Deepseek v4 HiFloat8 current-tensor scaling training through TorchAO #925
Merged
Total: 16 files changed+1507-25
| @@ -29,6 +29,7 @@ SIG 例会:[sig-framework-adapter](https://meeting.osinfra.cn/cann?sig=sig-fra | |||
| 29 | # 最新消息 | 29 | # 最新消息 |
| 30 | 30 | ||
| 31 | --- | 31 | --- |
| 32 | +- [Sep. 2026]: 🚀 **基于torchao_npu的DeepSeek-V4模型HiFloat8(HiF8)current-tensor scaling训练支持**。 | ||
| 32 | - [Aug. 2026]: 🚀 **master分支完成override插件机制解耦重构。** | 33 | - [Aug. 2026]: 🚀 **master分支完成override插件机制解耦重构。** |
| 33 | - [Aug. 2026]: 🚀 **基于torchao_npu的DeepSeek-V4模型原生FP8训练/QAT训练支持**。 | 34 | - [Aug. 2026]: 🚀 **基于torchao_npu的DeepSeek-V4模型原生FP8训练/QAT训练支持**。 |
| 34 | - [May. 2026]: 🚀 **[DeepSeek-V4-Pro 模型续训练支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图。 | 35 | - [May. 2026]: 🚀 **[DeepSeek-V4-Pro 模型续训练支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图。 |
| @@ -141,11 +141,13 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \ | |||
| 141 | | 参数 | 选项 | 用途 | | 141 | | 参数 | 选项 | 用途 | |
| 142 | | --- | --- | --- | | 142 | | --- | --- | --- | |
| 143 | | `enable-quantized-training` | `--enable-quantized-training` / `--no-enable-quantized-training` | 启用或关闭低精度训练,默认关闭。 | | 143 | | `enable-quantized-training` | `--enable-quantized-training` / `--no-enable-quantized-training` | 启用或关闭低精度训练,默认关闭。 | |
| 144 | -| `recipe` | `all_mxfp8`、`mix`、`all_block_fp8` | 选择全 MXFP8、混合 MXFP8/Block FP8 或全 Block FP8。 | | 144 | +| `recipe` | `all_mxfp8`、`mix`、`all_block_fp8`、`all_hif8` | 选择全 MXFP8、混合 MXFP8/Block FP8、全 Block FP8 或全 HiF8。 | |
| 145 | | `enable-mxfp4-qat` | `--enable-mxfp4-qat` / `--no-enable-mxfp4-qat` | 为 routed expert 启用或关闭 MXFP4 QAT 约束,默认关闭。 | | 145 | | `enable-mxfp4-qat` | `--enable-mxfp4-qat` / `--no-enable-mxfp4-qat` | 为 routed expert 启用或关闭 MXFP4 QAT 约束,默认关闭。 | |
| 146 | | `li-quantization` | `fp8`、`mxfp8`、`mxfp4`、`hif8` | 选择 DeepSeek-V4 LI Q/K 的量化类型,默认不启用。 | | 146 | | `li-quantization` | `fp8`、`mxfp8`、`mxfp4`、`hif8` | 选择 DeepSeek-V4 LI Q/K 的量化类型,默认不启用。 | |
| 147 | | `kv-norm-quantization.format` | `mxfp8` | 启用 DeepSeek-V4 KV Cache 的 MXFP8 量化。 | | 147 | | `kv-norm-quantization.format` | `mxfp8` | 启用 DeepSeek-V4 KV Cache 的 MXFP8 量化。 | |
| 148 | | `enable-fsdp-prequantize` | `--enable-fsdp-prequantize` / `--no-enable-fsdp-prequantize` | 在 FSDP all-gather 前预量化 Block FP8 权重,减少通信量,默认关闭。 | | 148 | | `enable-fsdp-prequantize` | `--enable-fsdp-prequantize` / `--no-enable-fsdp-prequantize` | 在 FSDP all-gather 前预量化 Block FP8 权重,减少通信量,默认关闭。 | |
| 149 | +| `enable-hif8-save-quant-codes` | `--enable-hif8-save-quant-codes` / `--no-enable-hif8-save-quant-codes` | 把 HiF8 量化矩乘算子(`npu_quantize`/`npu_dynamic_quant`/`npu_grouped_matmul`/`npu_quant_matmul`)结果保留在 selective activation checkpointing 保存边界内,backward 不再重新推导;仅在 `recipe=all_hif8` 时生效,默认关闭。 | | ||
| 150 | +| `save-block-ops-level` | `0`-`3`(默认 `0`) | 把 attention / mHC / MoE-routing 相关 NPU 自定义算子加入 selective activation checkpointing 的 MUST_SAVE 列表,用显存换取 backward 更少重复计算。 | | ||
| 149 | 151 | ||
| 150 | ### DeepSeek-V4.1 TorchAO-NPU 低精度训练 | 152 | ### DeepSeek-V4.1 TorchAO-NPU 低精度训练 |
| 151 | 153 | ||
| @@ -0,0 +1,44 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +# A5 wrapper around the common DeepSeek-V4 Flash CPT launcher. Keep the shared | ||
| 8 | +# model, training, and parallelism defaults in the A3 script; this entrypoint | ||
| 9 | +# only supplies A5-specific runtime, quantization, and recompute settings. | ||
| 10 | +# Append CLI arguments to override the defaults below: | ||
| 11 | +# ./examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_hif8.sh --training.steps 5 | ||
| 12 | + | ||
| 13 | +set -euo pipefail | ||
| 14 | + | ||
| 15 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 16 | + | ||
| 17 | +# Use the command line `npu-smi info -t topo` to query the CPU affinity of the | ||
| 18 | +# NPU cards for configuration. | ||
| 19 | +export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" | ||
| 20 | + | ||
| 21 | +# A5-only fused ops; USE_GOLDEN=1 keeps the pure reference list. | ||
| 22 | +if [[ "${USE_GOLDEN:-0}" != "1" ]]; then | ||
| 23 | + export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \ | ||
| 24 | + torchtitan_npu.override.common.swiglu_group.asc \ | ||
| 25 | + torchtitan_npu.override.common.swiglu_group.asc_shared_experts}" | ||
| 26 | +fi | ||
| 27 | + | ||
| 28 | +# HiF8 (current tensor scaling) quantized training. | ||
| 29 | +# Append --extension.quantization.no-enable-quantized-training for BF16 | ||
| 30 | +# training. | ||
| 31 | + | ||
| 32 | +QUANTIZATION_ARGS=( | ||
| 33 | + --extension.quantization.enable-quantized-training | ||
| 34 | + --extension.quantization.recipe all_hif8 | ||
| 35 | + --extension.quantization.li-quantization hif8 | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | +# Tyro treats activation-checkpoint:selective as a subcommand, so it must be | ||
| 39 | +# the final token after all regular options and override targets. | ||
| 40 | +bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | ||
| 41 | + "${QUANTIZATION_ARGS[@]}" \ | ||
| 42 | + --debug.moe-force-load-balance \ | ||
| 43 | + "$@" \ | ||
| 44 | + activation-checkpoint:selective | ||
| @@ -9,11 +9,14 @@ from torchao.quantization import Float8DynamicActivationFloat8WeightConfig | |||
| 9 | from torchao.quantization.granularity import PerRow | 9 | from torchao.quantization.granularity import PerRow |
| 10 | from torchao.quantization.qat import IntxFakeQuantizeConfig, QATStep | 10 | from torchao.quantization.qat import IntxFakeQuantizeConfig, QATStep |
| 11 | from torchao.quantization.qat.fake_quantize_config import Float8FakeQuantizeConfig | 11 | from torchao.quantization.qat.fake_quantize_config import Float8FakeQuantizeConfig |
| 12 | +from torchao.quantization.quant_api import quantize_ | ||
| 12 | from torchao_npu.configs import ParamSwapConfig | 13 | from torchao_npu.configs import ParamSwapConfig |
| 13 | from torchao_npu.quantization.quant_configs import ( | 14 | from torchao_npu.quantization.quant_configs import ( |
| 14 | BlockMXQuantizeConfig, | 15 | BlockMXQuantizeConfig, |
| 16 | + HiF8QuantizeConfig, | ||
| 15 | MXQuantizeConfig, | 17 | MXQuantizeConfig, |
| 16 | ) | 18 | ) |
| 19 | +from torchao_npu.wrapper_tensors import HiF8TrainingWeightWrapperTensor | ||
| 17 | 20 | ||
| 18 | 21 | ||
| 19 | def test_prepare_registers_swap_handlers_without_explicit_wrapper_import(): | 22 | def test_prepare_registers_swap_handlers_without_explicit_wrapper_import(): |
| @@ -109,26 +112,26 @@ def test_config_infer_from_base_config(base_config, expected_weight_config, expe | |||
| 109 | 112 | ||
| 110 | 113 | ||
| 111 | def test_config_rejects_invalid_weight_config(): | 114 | def test_config_rejects_invalid_weight_config(): |
| 112 | - """Invalid (non-FP8, non-NPU-MX) weight configs should be rejected.""" | 115 | + """Invalid (non-FP8, non-NPU-MX, non-HiF8) weight configs should be rejected.""" |
| 113 | intx_config = IntxFakeQuantizeConfig(torch.int8, "per_channel") | 116 | intx_config = IntxFakeQuantizeConfig(torch.int8, "per_channel") |
| 114 | with pytest.raises( | 117 | with pytest.raises( |
| 115 | ValueError, | 118 | ValueError, |
| 116 | match=( | 119 | match=( |
| 117 | - r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockMXQuantizeConfig` " | 120 | + r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, `BlockMXQuantizeConfig`, or " |
| 118 | - r"is supported for `weight_config` in ParamSwapConfig yet\.$" | 121 | + r"`HiF8QuantizeConfig` is supported for `weight_config` in ParamSwapConfig yet\.$" |
| 119 | ), | 122 | ), |
| 120 | ): | 123 | ): |
| 121 | ParamSwapConfig(weight_config=intx_config, step="prepare") | 124 | ParamSwapConfig(weight_config=intx_config, step="prepare") |
| 122 | 125 | ||
| 123 | 126 | ||
| 124 | def test_config_rejects_invalid_activation_config(): | 127 | def test_config_rejects_invalid_activation_config(): |
| 125 | - """Invalid (non-FP8, non-NPU-MX) activation configs should be rejected.""" | 128 | + """Invalid (non-FP8, non-NPU-MX, non-HiF8) activation configs should be rejected.""" |
| 126 | weight_config = Float8FakeQuantizeConfig(dtype=torch.float8_e4m3fn, granularity=PerRow()) | 129 | weight_config = Float8FakeQuantizeConfig(dtype=torch.float8_e4m3fn, granularity=PerRow()) |
| 127 | activation_config = IntxFakeQuantizeConfig(torch.int8, "per_channel") | 130 | activation_config = IntxFakeQuantizeConfig(torch.int8, "per_channel") |
| 128 | with pytest.raises( | 131 | with pytest.raises( |
| 129 | ValueError, | 132 | ValueError, |
| 130 | match=( | 133 | match=( |
| 131 | - r"^Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` is supported for " | 134 | + r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `HiF8QuantizeConfig` is supported for " |
| 132 | r"`activation_config` in ParamSwapConfig yet\.$" | 135 | r"`activation_config` in ParamSwapConfig yet\.$" |
| 133 | ), | 136 | ), |
| 134 | ): | 137 | ): |
| @@ -202,6 +205,44 @@ def test_config_accepts_block_weight_with_mx_activation(): | |||
| 202 | assert qat_config.activation_config is act_config | 205 | assert qat_config.activation_config is act_config |
| 203 | 206 | ||
| 204 | 207 | ||
| 208 | +def test_param_swap_accepts_hif8_for_weight_and_activation(): | ||
| 209 | + """HiF8QuantizeConfig should be accepted for both weight and activation.""" | ||
| 210 | + weight_config = HiF8QuantizeConfig() | ||
| 211 | + activation_config = HiF8QuantizeConfig() | ||
| 212 | + | ||
| 213 | + config = ParamSwapConfig( | ||
| 214 | + weight_config=weight_config, | ||
| 215 | + activation_config=activation_config, | ||
| 216 | + step=QATStep.PREPARE, | ||
| 217 | + ) | ||
| 218 | + | ||
| 219 | + assert config.weight_config is weight_config | ||
| 220 | + assert config.activation_config is activation_config | ||
| 221 | + assert config.step == QATStep.PREPARE | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +def test_hif8_config_rejects_non_hif8_dtype(): | ||
| 225 | + with pytest.raises(ValueError, match=r"HiF8QuantizeConfig requires torch_npu\.hifloat8"): | ||
| 226 | + HiF8QuantizeConfig(elem_dtype=torch.float8_e4m3fn) | ||
| 227 | + | ||
| 228 | + | ||
| 229 | +def test_quantize_prepares_hif8_parameter_wrapper(): | ||
| 230 | + config = HiF8QuantizeConfig() | ||
| 231 | + module = torch.nn.Linear(64, 128) | ||
| 232 | + quantize_config = ParamSwapConfig( | ||
| 233 | + weight_config=config, | ||
| 234 | + activation_config=config, | ||
| 235 | + step=QATStep.PREPARE, | ||
| 236 | + ) | ||
| 237 | + | ||
| 238 | + quantize_(module, quantize_config) | ||
| 239 | + | ||
| 240 | + assert isinstance(module.weight, torch.nn.Parameter) | ||
| 241 | + assert isinstance(module.weight, HiF8TrainingWeightWrapperTensor) | ||
| 242 | + assert module.weight.weight_config is config | ||
| 243 | + assert module.weight.activation_config is config | ||
| 244 | + | ||
| 245 | + | ||
| 205 | # ========================================================================= | 246 | # ========================================================================= |
| 206 | # Test configs in the convert step | 247 | # Test configs in the convert step |
| 207 | # ========================================================================= | 248 | # ========================================================================= |
| @@ -24,9 +24,11 @@ import torch_npu # noqa: F401 | |||
| 24 | from torchao_npu.ops.block_mx_ops import ( | 24 | from torchao_npu.ops.block_mx_ops import ( |
| 25 | to_block_mx_then_mm, | 25 | to_block_mx_then_mm, |
| 26 | ) | 26 | ) |
| 27 | +from torchao_npu.ops.hif8_ops import to_hif8_then_bmm, to_hif8_then_mm | ||
| 27 | from torchao_npu.ops.mx_ops import to_mx_then_mm | 28 | from torchao_npu.ops.mx_ops import to_mx_then_mm |
| 28 | from torchao_npu.quantization.quant_configs import ( | 29 | from torchao_npu.quantization.quant_configs import ( |
| 29 | BlockMXQuantizeConfig, | 30 | BlockMXQuantizeConfig, |
| 31 | + HiF8QuantizeConfig, | ||
| 30 | MXQuantizeConfig, | 32 | MXQuantizeConfig, |
| 31 | ) | 33 | ) |
| 32 | 34 | ||
| @@ -151,3 +153,63 @@ def test_block_mx_with_mxfp4_compile(m, k, n): | |||
| 151 | 153 | ||
| 152 | model = BlockMXMMModel(config_a, config_b).npu() | 154 | model = BlockMXMMModel(config_a, config_b).npu() |
| 153 | _compile_and_assert_output(model, a, b, expected_shape=(m, n)) | 155 | _compile_and_assert_output(model, a, b, expected_shape=(m, n)) |
| 156 | + | ||
| 157 | + | ||
| 158 | +# ============================================================================ | ||
| 159 | +# HiF8 quantized matmul (to_hif8_then_mm / to_hif8_then_bmm) | ||
| 160 | +# ============================================================================ | ||
| 161 | + | ||
| 162 | + | ||
| 163 | +class HiF8MMModel(torch.nn.Module): | ||
| 164 | + def __init__(self, config_a, config_b): | ||
| 165 | + super().__init__() | ||
| 166 | + self.config_a = config_a | ||
| 167 | + self.config_b = config_b | ||
| 168 | + | ||
| 169 | + def forward(self, a, b): | ||
| 170 | + return to_hif8_then_mm(a, b, self.config_a, self.config_b) | ||
| 171 | + | ||
| 172 | + | ||
| 173 | +@pytest.mark.parametrize( | ||
| 174 | + "m, k, n", | ||
| 175 | + [ | ||
| 176 | + (2048, 4096, 2048), | ||
| 177 | + (4096, 2048, 4096), | ||
| 178 | + ], | ||
| 179 | +) | ||
| 180 | +def test_hif8_matmul_compile(m, k, n): | ||
| 181 | + """``to_hif8_then_mm`` works under torch.compile.""" | ||
| 182 | + torch.manual_seed(42) | ||
| 183 | + a = torch.randn(m, k, device="npu", dtype=torch.bfloat16) | ||
| 184 | + b = torch.randn(k, n, device="npu", dtype=torch.bfloat16) | ||
| 185 | + config = HiF8QuantizeConfig() | ||
| 186 | + | ||
| 187 | + model = HiF8MMModel(config, config).npu() | ||
| 188 | + _compile_and_assert_output(model, a, b, expected_shape=(m, n)) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +class HiF8BMMModel(torch.nn.Module): | ||
| 192 | + def __init__(self, config_a, config_b): | ||
| 193 | + super().__init__() | ||
| 194 | + self.config_a = config_a | ||
| 195 | + self.config_b = config_b | ||
| 196 | + | ||
| 197 | + def forward(self, a, b): | ||
| 198 | + return to_hif8_then_bmm(a, b, self.config_a, self.config_b) | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def test_hif8_bmm_compile_with_transposed_activation(): | ||
| 202 | + """``to_hif8_then_bmm`` works under ``torch.compile`` when the activation is | ||
| 203 | + a non-contiguous permutation view -- the ``BatchedLinear`` layout that | ||
| 204 | + ``quantize_hifloat8``'s transpose-avoidance path (descending-stride | ||
| 205 | + permute, no ``is_contiguous()`` guard) targets. | ||
| 206 | + """ | ||
| 207 | + torch.manual_seed(42) | ||
| 208 | + T, H, K, N = 512, 8, 512, 512 | ||
| 209 | + base = torch.randn(T, H, K, device="npu", dtype=torch.bfloat16) | ||
| 210 | + a = base.transpose(0, 1) # non-contiguous view: [H, T, K] | ||
| 211 | + b = torch.randn(H, K, N, device="npu", dtype=torch.bfloat16) | ||
| 212 | + config = HiF8QuantizeConfig() | ||
| 213 | + | ||
| 214 | + model = HiF8BMMModel(config, config).npu() | ||
| 215 | + _compile_and_assert_output(model, a, b, expected_shape=(H, T, N)) | ||
| @@ -0,0 +1,320 @@ | |||
| 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 | +"""NPU tests for the per-tensor HiF8 MM and Grouped MM kernels.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +import torch_npu | ||
| 11 | +from torchao.float8.float8_utils import compute_error | ||
| 12 | +from torchao_npu.ops.hif8_ops import ( | ||
| 13 | + to_hif8_then_bmm, | ||
| 14 | + to_hif8_then_grouped_mm, | ||
| 15 | + to_hif8_then_mm, | ||
| 16 | +) | ||
| 17 | +from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | ||
| 18 | + | ||
| 19 | +_SQNR_THRESHOLD = 12.0 | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def _group_list(group_sizes: list[int]) -> torch.Tensor: | ||
| 23 | + return torch.tensor(group_sizes, dtype=torch.int32, device="npu").cumsum(0) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _sqnr(reference: torch.Tensor, actual: torch.Tensor) -> float: | ||
| 27 | + return compute_error(reference.float(), actual.float()).item() | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +@pytest.mark.parametrize( | ||
| 31 | + ("dtype", "shape"), | ||
| 32 | + [ | ||
| 33 | + pytest.param(torch.bfloat16, (128, 64, 256), id="bf16"), | ||
| 34 | + pytest.param(torch.float16, (64, 128, 128), id="fp16"), | ||
| 35 | + ], | ||
| 36 | +) | ||
| 37 | +def test_mm_forward_preserves_shape_and_dtype(dtype, shape): | ||
| 38 | + M, K, N = shape | ||
| 39 | + config = HiF8QuantizeConfig() | ||
| 40 | + activation = torch.randn(M, K, device="npu", dtype=dtype) | ||
| 41 | + weight = torch.randn(N, K, device="npu", dtype=dtype) | ||
| 42 | + | ||
| 43 | + output = to_hif8_then_mm(activation, weight.T, config, config) | ||
| 44 | + | ||
| 45 | + assert output.shape == (M, N) | ||
| 46 | + assert output.dtype == dtype | ||
| 47 | + assert output.device.type == "npu" | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def test_mm_forward_and_backward_match_independent_dense_reference(): | ||
| 51 | + torch.manual_seed(42) | ||
| 52 | + config = HiF8QuantizeConfig() | ||
| 53 | + activation = torch.randn(128, 64, device="npu", dtype=torch.bfloat16) | ||
| 54 | + weight = torch.randn(256, 64, device="npu", dtype=torch.bfloat16) | ||
| 55 | + | ||
| 56 | + activation_ref = activation.detach().clone().requires_grad_() | ||
| 57 | + weight_ref = weight.detach().T.clone().requires_grad_() | ||
| 58 | + reference = activation_ref @ weight_ref | ||
| 59 | + reference.sum().backward() | ||
| 60 | + | ||
| 61 | + activation_hif8 = activation.detach().clone().requires_grad_() | ||
| 62 | + weight_hif8 = weight.detach().T.clone().requires_grad_() | ||
| 63 | + actual = to_hif8_then_mm(activation_hif8, weight_hif8, config, config) | ||
| 64 | + actual.sum().backward() | ||
| 65 | + | ||
| 66 | + assert _sqnr(reference, actual) > _SQNR_THRESHOLD | ||
| 67 | + assert _sqnr(activation_ref.grad, activation_hif8.grad) > _SQNR_THRESHOLD | ||
| 68 | + assert _sqnr(weight_ref.grad, weight_hif8.grad) > _SQNR_THRESHOLD | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def test_mm_quantizes_transposed_weight_view_without_extra_copy(): | ||
| 72 | + """``quantize_hifloat8``'s permute-avoids-copy path must be bit-identical. | ||
| 73 | + | ||
| 74 | + ``weight.t()`` (no ``.contiguous()``) is exactly the layout a plain | ||
| 75 | + ``nn.Linear`` weight hits once transposed to ``[K, N]`` for the matmul. | ||
| 76 | + Per-tensor quantization is elementwise under one scalar scale, so | ||
| 77 | + quantizing the transposed view (dense base permuted, codes permuted back) | ||
| 78 | + must give the same bytes as quantizing an explicitly materialized | ||
| 79 | + contiguous copy of the same values. | ||
| 80 | + """ | ||
| 81 | + torch.manual_seed(5) | ||
| 82 | + config = HiF8QuantizeConfig() | ||
| 83 | + activation = torch.randn(32, 64, device="npu", dtype=torch.bfloat16) | ||
| 84 | + weight = torch.randn(128, 64, device="npu", dtype=torch.bfloat16) # nn.Linear layout [N, K] | ||
| 85 | + | ||
| 86 | + def _run(make_weight_KN): | ||
| 87 | + act = activation.detach().clone().requires_grad_() | ||
| 88 | + w = make_weight_KN().requires_grad_() | ||
| 89 | + out = to_hif8_then_mm(act, w, config, config) | ||
| 90 | + out.sum().backward() | ||
| 91 | + return out.detach(), act.grad, w.grad | ||
| 92 | + | ||
| 93 | + contiguous_result = _run(lambda: weight.detach().clone().t().contiguous()) | ||
| 94 | + view_result = _run(lambda: weight.detach().clone().t()) | ||
| 95 | + | ||
| 96 | + assert torch.equal(view_result[0], contiguous_result[0]), "forward is not bit-identical" | ||
| 97 | + assert torch.equal(view_result[1], contiguous_result[1]), "dA is not bit-identical" | ||
| 98 | + assert torch.equal(view_result[2], contiguous_result[2]), "dB is not bit-identical" | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def test_mm_supports_leading_dimensions_and_casts_fp32(): | ||
| 102 | + config = HiF8QuantizeConfig() | ||
| 103 | + activation = torch.randn(4, 32, 64, device="npu", dtype=torch.float32) | ||
| 104 | + weight = torch.randn(128, 64, device="npu", dtype=torch.float32) | ||
| 105 | + | ||
| 106 | + output = to_hif8_then_mm(activation, weight.T, config, config) | ||
| 107 | + | ||
| 108 | + assert output.shape == (4, 32, 128) | ||
| 109 | + assert output.dtype == torch.bfloat16 | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +@pytest.mark.parametrize( | ||
| 113 | + "shapes", | ||
| 114 | + [ | ||
| 115 | + pytest.param(((32, 64), (64,)), id="one-dimensional-weight"), | ||
| 116 | + pytest.param(((32, 64), (128, 32)), id="contracting-dimension"), | ||
| 117 | + ], | ||
| 118 | +) | ||
| 119 | +def test_mm_rejects_invalid_shapes(shapes): | ||
| 120 | + config = HiF8QuantizeConfig() | ||
| 121 | + activation = torch.randn(*shapes[0], device="npu", dtype=torch.bfloat16) | ||
| 122 | + weight = torch.randn(*shapes[1], device="npu", dtype=torch.bfloat16) | ||
| 123 | + | ||
| 124 | + with pytest.raises((AssertionError, RuntimeError)): | ||
| 125 | + to_hif8_then_mm(activation, weight, config, config) | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def test_grouped_mm_forward_and_backward_match_independent_reference(): | ||
| 129 | + torch.manual_seed(42) | ||
| 130 | + config = HiF8QuantizeConfig() | ||
| 131 | + group_sizes = [32, 64, 32] | ||
| 132 | + group_list = _group_list(group_sizes) | ||
| 133 | + activation = torch.randn(128, 64, device="npu", dtype=torch.bfloat16) | ||
| 134 | + weight = torch.randn(3, 64, 128, device="npu", dtype=torch.bfloat16) | ||
| 135 | + | ||
| 136 | + activation_ref = activation.detach().clone().requires_grad_() | ||
| 137 | + weight_ref = weight.detach().clone().requires_grad_() | ||
| 138 | + reference_parts = [] | ||
| 139 | + start = 0 | ||
| 140 | + for expert, size in enumerate(group_sizes): | ||
| 141 | + end = start + size | ||
| 142 | + reference_parts.append(activation_ref[start:end] @ weight_ref[expert]) | ||
| 143 | + start = end | ||
| 144 | + reference = torch.cat(reference_parts) | ||
| 145 | + reference.sum().backward() | ||
| 146 | + | ||
| 147 | + activation_hif8 = activation.detach().clone().requires_grad_() | ||
| 148 | + weight_hif8 = weight.detach().clone().requires_grad_() | ||
| 149 | + actual = to_hif8_then_grouped_mm(activation_hif8, weight_hif8, group_list, config, config) | ||
| 150 | + actual.sum().backward() | ||
| 151 | + | ||
| 152 | + assert actual.shape == (128, 128) | ||
| 153 | + assert _sqnr(reference, actual) > _SQNR_THRESHOLD | ||
| 154 | + assert _sqnr(activation_ref.grad, activation_hif8.grad) > _SQNR_THRESHOLD | ||
| 155 | + assert _sqnr(weight_ref.grad, weight_hif8.grad) > _SQNR_THRESHOLD | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +@pytest.mark.parametrize( | ||
| 159 | + "shapes", | ||
| 160 | + [ | ||
| 161 | + pytest.param(((4, 32, 64), (2, 64, 128)), id="three-dimensional-input"), | ||
| 162 | + pytest.param(((64, 64), (64, 128)), id="two-dimensional-weight"), | ||
| 163 | + pytest.param(((64, 64), (2, 128, 64)), id="contracting-dimension"), | ||
| 164 | + ], | ||
| 165 | +) | ||
| 166 | +def test_grouped_mm_rejects_invalid_shapes(shapes): | ||
| 167 | + config = HiF8QuantizeConfig() | ||
| 168 | + activation = torch.randn(*shapes[0], device="npu", dtype=torch.bfloat16) | ||
| 169 | + weight = torch.randn(*shapes[1], device="npu", dtype=torch.bfloat16) | ||
| 170 | + group_list = _group_list([32, 64]) | ||
| 171 | + | ||
| 172 | + with pytest.raises((AssertionError, RuntimeError)): | ||
| 173 | + to_hif8_then_grouped_mm(activation, weight, group_list, config, config) | ||
| 174 | + | ||
| 175 | + | ||
| 176 | +@pytest.mark.parametrize( | ||
| 177 | + ("dtype", "shape"), | ||
| 178 | + [ | ||
| 179 | + pytest.param(torch.bfloat16, (8, 128, 64, 256), id="bf16"), | ||
| 180 | + pytest.param(torch.float16, (4, 64, 128, 128), id="fp16"), | ||
| 181 | + ], | ||
| 182 | +) | ||
| 183 | +def test_bmm_forward_preserves_shape_and_dtype(dtype, shape): | ||
| 184 | + batch, M, K, N = shape | ||
| 185 | + config = HiF8QuantizeConfig() | ||
| 186 | + activation = torch.randn(batch, M, K, device="npu", dtype=dtype) | ||
| 187 | + weight = torch.randn(batch, K, N, device="npu", dtype=dtype) | ||
| 188 | + | ||
| 189 | + output = to_hif8_then_bmm(activation, weight, config, config) | ||
| 190 | + | ||
| 191 | + assert output.shape == (batch, M, N) | ||
| 192 | + assert output.dtype == dtype | ||
| 193 | + assert output.device.type == "npu" | ||
| 194 | + | ||
| 195 | + | ||
| 196 | +def test_bmm_forward_and_backward_match_independent_dense_reference(): | ||
| 197 | + torch.manual_seed(42) | ||
| 198 | + config = HiF8QuantizeConfig() | ||
| 199 | + activation = torch.randn(6, 128, 64, device="npu", dtype=torch.bfloat16) | ||
| 200 | + weight = torch.randn(6, 64, 256, device="npu", dtype=torch.bfloat16) | ||
| 201 | + | ||
| 202 | + activation_ref = activation.detach().clone().requires_grad_() | ||
| 203 | + weight_ref = weight.detach().clone().requires_grad_() | ||
| 204 | + reference = torch.bmm(activation_ref, weight_ref) | ||
| 205 | + reference.sum().backward() | ||
| 206 | + | ||
| 207 | + activation_hif8 = activation.detach().clone().requires_grad_() | ||
| 208 | + weight_hif8 = weight.detach().clone().requires_grad_() | ||
| 209 | + actual = to_hif8_then_bmm(activation_hif8, weight_hif8, config, config) | ||
| 210 | + actual.sum().backward() | ||
| 211 | + | ||
| 212 | + assert actual.shape == (6, 128, 256) | ||
| 213 | + assert _sqnr(reference, actual) > _SQNR_THRESHOLD | ||
| 214 | + assert _sqnr(activation_ref.grad, activation_hif8.grad) > _SQNR_THRESHOLD | ||
| 215 | + assert _sqnr(weight_ref.grad, weight_hif8.grad) > _SQNR_THRESHOLD | ||
| 216 | + | ||
| 217 | + | ||
| 218 | +def test_bmm_quantizes_transposed_activation_view_without_extra_copy(): | ||
| 219 | + """``quantize_hifloat8``'s permute-avoids-copy path must be | ||
| 220 | + bit-identical for BMM's activation operand. | ||
| 221 | + | ||
| 222 | + The operand is exactly what ``BatchedLinear.forward`` builds: a | ||
| 223 | + ``[T, H, K]`` contiguous tensor viewed as ``[H, T, K]``. Per-tensor | ||
| 224 | + quantization is elementwise under one scalar scale, so quantizing that | ||
| 225 | + transposed view (dense base permuted, codes permuted back) must give the | ||
| 226 | + same bytes as quantizing an explicitly materialized contiguous copy of | ||
| 227 | + the same values. | ||
| 228 | + """ | ||
| 229 | + torch.manual_seed(7) | ||
| 230 | + T, H, K, N = 64, 4, 128, 96 | ||
| 231 | + config = HiF8QuantizeConfig() | ||
| 232 | + x_THK = torch.randn(T, H, K, device="npu", dtype=torch.bfloat16) | ||
| 233 | + weight = torch.randn(H, K, N, device="npu", dtype=torch.bfloat16) | ||
| 234 | + | ||
| 235 | + def _run(make_activation): | ||
| 236 | + activation = make_activation().requires_grad_() | ||
| 237 | + w = weight.detach().clone().requires_grad_() | ||
| 238 | + out = to_hif8_then_bmm(activation, w, config, config) | ||
| 239 | + out.sum().backward() | ||
| 240 | + return out.detach(), activation.grad, w.grad | ||
| 241 | + | ||
| 242 | + contiguous_result = _run(lambda: x_THK.detach().clone().transpose(0, 1).contiguous()) | ||
| 243 | + view_result = _run(lambda: x_THK.detach().clone().transpose(0, 1)) | ||
| 244 | + | ||
| 245 | + assert torch.equal(view_result[0], contiguous_result[0]), "forward is not bit-identical" | ||
| 246 | + assert torch.equal(view_result[1], contiguous_result[1]), "dA is not bit-identical" | ||
| 247 | + assert torch.equal(view_result[2], contiguous_result[2]), "dB is not bit-identical" | ||
| 248 | + | ||
| 249 | + | ||
| 250 | +@pytest.mark.parametrize( | ||
| 251 | + "shapes", | ||
| 252 | + [ | ||
| 253 | + pytest.param(((32, 64), (32, 64, 128)), id="two-dimensional-input"), | ||
| 254 | + pytest.param(((2, 32, 64), (3, 64, 128)), id="batch-dimension"), | ||
| 255 | + pytest.param(((2, 32, 64), (2, 128, 64)), id="contracting-dimension"), | ||
| 256 | + ], | ||
| 257 | +) | ||
| 258 | +def test_bmm_rejects_invalid_shapes(shapes): | ||
| 259 | + config = HiF8QuantizeConfig() | ||
| 260 | + activation = torch.randn(*shapes[0], device="npu", dtype=torch.bfloat16) | ||
| 261 | + weight = torch.randn(*shapes[1], device="npu", dtype=torch.bfloat16) | ||
| 262 | + | ||
| 263 | + with pytest.raises((AssertionError, RuntimeError)): | ||
| 264 | + to_hif8_then_bmm(activation, weight, config, config) | ||
| 265 | + | ||
| 266 | + | ||
| 267 | +@pytest.mark.parametrize("num_experts", [2, 3, 5], ids=lambda value: f"experts-{value}") | ||
| 268 | +def test_grouped_mm_uses_weight_expert_count_for_scale_broadcast(num_experts): | ||
| 269 | + config = HiF8QuantizeConfig() | ||
| 270 | + num_tokens, K, N = 64, 32, 32 | ||
| 271 | + base = num_tokens // num_experts | ||
| 272 | + group_sizes = [base] * (num_experts - 1) + [num_tokens - base * (num_experts - 1)] | ||
| 273 | + group_list = _group_list(group_sizes) | ||
| 274 | + activation = torch.randn(num_tokens, K, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 275 | + weight = torch.randn(num_experts, K, N, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 276 | + | ||
| 277 | + output = to_hif8_then_grouped_mm(activation, weight, group_list, config, config) | ||
| 278 | + output.sum().backward() | ||
| 279 | + | ||
| 280 | + assert output.shape == (num_tokens, N) | ||
| 281 | + assert torch.isfinite(activation.grad.float()).all() | ||
| 282 | + assert weight.grad is not None | ||
| 283 | + assert weight.grad.shape == weight.shape | ||
| 284 | + assert torch.isfinite(weight.grad.float()).all() | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +# ========================================================================= | ||
| 288 | +# Current/constant tensor scaling (CTS) | ||
| 289 | +# ========================================================================= | ||
| 290 | + | ||
| 291 | + | ||
| 292 | +def _count_calls(monkeypatch, target, name): | ||
| 293 | + """Wrap ``torch_npu.<name>`` with a call counter; still calls the real op.""" | ||
| 294 | + calls = {"n": 0} | ||
| 295 | + real = getattr(target, name) | ||
| 296 | + | ||
| 297 | + def spy(*args, **kwargs): | ||
| 298 | + calls["n"] += 1 | ||
| 299 | + return real(*args, **kwargs) | ||
| 300 | + | ||
| 301 | + monkeypatch.setattr(target, name, spy) | ||
| 302 | + return calls | ||
| 303 | + | ||
| 304 | + | ||
| 305 | +def test_quantize_always_recomputes_scale_via_dynamic_quant(monkeypatch): | ||
| 306 | + """Every call quantizes via npu_dynamic_quant; npu_quantize (static-scale | ||
| 307 | + quantize) is never used -- there is no persisted scale to reuse. | ||
| 308 | + """ | ||
| 309 | + config = HiF8QuantizeConfig() | ||
| 310 | + activation = torch.randn(32, 64, device="npu", dtype=torch.bfloat16) | ||
| 311 | + weight = torch.randn(128, 64, device="npu", dtype=torch.bfloat16) | ||
| 312 | + | ||
| 313 | + dynamic_calls = _count_calls(monkeypatch, torch_npu, "npu_dynamic_quant") | ||
| 314 | + static_calls = _count_calls(monkeypatch, torch_npu, "npu_quantize") | ||
| 315 | + | ||
| 316 | + for _ in range(3): | ||
| 317 | + to_hif8_then_mm(activation, weight.T, config, config) | ||
| 318 | + | ||
| 319 | + assert dynamic_calls["n"] == 3 * 2 | ||
| 320 | + assert static_calls["n"] == 0 | ||
| @@ -0,0 +1,249 @@ | |||
| 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 | +"""Tests for the HiF8 parameter wrapper and its operation dispatch.""" | ||
| 7 | + | ||
| 8 | +import copy | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | +import torch | ||
| 12 | +import torch.nn.functional as F | ||
| 13 | +from torchao.float8.float8_utils import compute_error | ||
| 14 | +from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase | ||
| 15 | +from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | ||
| 16 | +from torchao_npu.wrapper_tensors import HiF8TrainingWeightWrapperTensor | ||
| 17 | + | ||
| 18 | +from ..testing_utils import target_devices | ||
| 19 | + | ||
| 20 | +_SQNR_THRESHOLD = 12.0 | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _config() -> HiF8QuantizeConfig: | ||
| 24 | + return HiF8QuantizeConfig() | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def _wrapper(shape, device="cpu", *, dtype=torch.float32): | ||
| 28 | + config = _config() | ||
| 29 | + return HiF8TrainingWeightWrapperTensor( | ||
| 30 | + torch.randn(*shape, device=device, dtype=dtype), | ||
| 31 | + weight_config=config, | ||
| 32 | + activation_config=config, | ||
| 33 | + ) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +@pytest.mark.parametrize("device", target_devices, ids=lambda value: str(value)) | ||
| 37 | +def test_init_stores_data_and_configs(device): | ||
| 38 | + weight_config = _config() | ||
| 39 | + activation_config = _config() | ||
| 40 | + data = torch.randn(64, 128, device=device) | ||
| 41 | + | ||
| 42 | + wrapper = HiF8TrainingWeightWrapperTensor( | ||
| 43 | + data, | ||
| 44 | + weight_config=weight_config, | ||
| 45 | + activation_config=activation_config, | ||
| 46 | + ) | ||
| 47 | + | ||
| 48 | + assert getattr(wrapper, "_data") is data # noqa: B009 | ||
| 49 | + assert wrapper.weight_config is weight_config | ||
| 50 | + assert wrapper.activation_config is activation_config | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def test_init_rejects_missing_or_wrong_config(): | ||
| 54 | + data = torch.randn(64, 128) | ||
| 55 | + config = _config() | ||
| 56 | + | ||
| 57 | + with pytest.raises(ValueError, match=r"^`weight_config` is required"): | ||
| 58 | + HiF8TrainingWeightWrapperTensor(data, weight_config=None, activation_config=config) | ||
| 59 | + with pytest.raises(ValueError, match=r"^`activation_config` is required"): | ||
| 60 | + HiF8TrainingWeightWrapperTensor(data, weight_config=config, activation_config=None) | ||
| 61 | + | ||
| 62 | + class DummyConfig(FakeQuantizeConfigBase): | ||
| 63 | + pass | ||
| 64 | + | ||
| 65 | + with pytest.raises(ValueError, match=r"^Only `HiF8QuantizeConfig` is supported"): | ||
| 66 | + HiF8TrainingWeightWrapperTensor(data, weight_config=DummyConfig(), activation_config=config) | ||
| 67 | + with pytest.raises(ValueError, match=r"^Only `HiF8QuantizeConfig` is supported"): | ||
| 68 | + HiF8TrainingWeightWrapperTensor(data, weight_config=config, activation_config=DummyConfig()) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def test_init_rejects_non_pertensor_quant_mode(): | ||
| 72 | + """HiF8QuantizeConfig also serves Lightning Indexer Q/K quantization, | ||
| 73 | + where quant_mode may be non-"pertensor" -- this wrapper's per-expert | ||
| 74 | + scale broadcast and backward-reuse-via-transpose scheme only hold for a | ||
| 75 | + single scalar scale, so a non-"pertensor" config must be rejected here | ||
| 76 | + rather than silently mishandled. | ||
| 77 | + """ | ||
| 78 | + data = torch.randn(64, 128) | ||
| 79 | + pertoken_config = HiF8QuantizeConfig(quant_mode="pertoken") | ||
| 80 | + pertensor_config = _config() | ||
| 81 | + | ||
| 82 | + with pytest.raises(ValueError, match=r"weight_config.quant_mode.*must be 'pertensor'"): | ||
| 83 | + HiF8TrainingWeightWrapperTensor(data, weight_config=pertoken_config, activation_config=pertoken_config) | ||
| 84 | + with pytest.raises(ValueError, match=r"activation_config.quant_mode.*must be 'pertensor'"): | ||
| 85 | + HiF8TrainingWeightWrapperTensor(data, weight_config=pertensor_config, activation_config=pertoken_config) | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +@pytest.mark.parametrize("device", target_devices, ids=lambda value: str(value)) | ||
| 89 | +def test_non_quantized_operation_preserves_plain_tensor_result(device): | ||
| 90 | + plain = torch.randn(64, 128, device=device) | ||
| 91 | + wrapped = _wrapper((64, 128), device) | ||
| 92 | + | ||
| 93 | + actual = torch.add(plain, wrapped) | ||
| 94 | + expected = torch.add(plain, getattr(wrapped, "_data")) # noqa: B009 | ||
| 95 | + | ||
| 96 | + assert isinstance(actual, torch.Tensor) | ||
| 97 | + assert not isinstance(actual, HiF8TrainingWeightWrapperTensor) | ||
| 98 | + torch.testing.assert_close(actual, expected) | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +@pytest.mark.parametrize("operation", ["select", "transpose", "detach", "clone"]) | ||
| 102 | +def test_metadata_operations_preserve_wrapper(operation): | ||
| 103 | + weight = _wrapper((4, 64, 128)) | ||
| 104 | + | ||
| 105 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 106 | + if operation == "select": | ||
| 107 | + actual = weight[0] | ||
| 108 | + expected = getattr(weight, "_data")[0] # noqa: B009 | ||
| 109 | + elif operation == "transpose": | ||
| 110 | + actual = weight.transpose(0, 1) | ||
| 111 | + expected = getattr(weight, "_data").transpose(0, 1) # noqa: B009 | ||
| 112 | + elif operation == "detach": | ||
| 113 | + actual = weight.detach() | ||
| 114 | + expected = getattr(weight, "_data").detach() # noqa: B009 | ||
| 115 | + else: | ||
| 116 | + actual = weight.clone() | ||
| 117 | + expected = getattr(weight, "_data").clone() # noqa: B009 | ||
| 118 | + | ||
| 119 | + assert isinstance(actual, HiF8TrainingWeightWrapperTensor) | ||
| 120 | + assert actual.weight_config is weight.weight_config | ||
| 121 | + assert actual.activation_config is weight.activation_config | ||
| 122 | + torch.testing.assert_close(getattr(actual, "_data"), expected) # noqa: B009 | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +@pytest.mark.parametrize("operation", [torch.mm, F.linear]) | ||
| 126 | +def test_dispatch_rejects_wrapped_activation(operation): | ||
| 127 | + weight = _wrapper((64, 128)) | ||
| 128 | + | ||
| 129 | + with pytest.raises(AssertionError, match=r"^A should not be a HiF8TrainingWeightWrapperTensor$"): | ||
| 130 | + operation(weight, weight) | ||
| 131 | + | ||
| 132 | + | ||
| 133 | +@pytest.mark.parametrize("operation", [torch.addmm, F.linear]) | ||
| 134 | +def test_dispatch_rejects_unwrapped_weight(operation): | ||
| 135 | + activation = torch.randn(16, 64) | ||
| 136 | + weight = torch.randn(64, 128) | ||
| 137 | + wrapped_bias = _wrapper((128,)) | ||
| 138 | + | ||
| 139 | + with pytest.raises(AssertionError, match=r"^B should be a HiF8TrainingWeightWrapperTensor$"): | ||
| 140 | + if operation is torch.addmm: | ||
| 141 | + operation(wrapped_bias, activation, weight) | ||
| 142 | + else: | ||
| 143 | + operation(activation, weight, wrapped_bias) | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +@pytest.mark.parametrize( | ||
| 147 | + "operation", | ||
| 148 | + [ | ||
| 149 | + pytest.param(lambda activation, weight, bias: torch.mm(activation, weight.T), id="mm"), | ||
| 150 | + pytest.param(lambda activation, weight, bias: torch.matmul(activation, weight.T), id="matmul"), | ||
| 151 | + pytest.param(lambda activation, weight, bias: F.linear(activation, weight, bias), id="linear"), | ||
| 152 | + pytest.param(lambda activation, weight, bias: torch.addmm(bias, activation, weight.T), id="addmm"), | ||
| 153 | + pytest.param( | ||
| 154 | + lambda activation, weight, bias: torch.addmm(bias, activation, weight.T, beta=2.0, alpha=0.5), | ||
| 155 | + id="addmm-scaled", | ||
| 156 | + ), | ||
| 157 | + ], | ||
| 158 | +) | ||
| 159 | +def test_mm_dispatch_forward_backward_matches_dense_reference(operation): | ||
| 160 | + config = _config() | ||
| 161 | + activation_data = torch.randn(32, 1024, device="npu", dtype=torch.bfloat16) | ||
| 162 | + weight_data = torch.randn(2048, 1024, device="npu", dtype=torch.bfloat16) | ||
| 163 | + bias_data = torch.randn(2048, device="npu", dtype=torch.bfloat16) | ||
| 164 | + | ||
| 165 | + activation = torch.nn.Parameter(activation_data.clone()) | ||
| 166 | + weight = torch.nn.Parameter( | ||
| 167 | + HiF8TrainingWeightWrapperTensor( | ||
| 168 | + weight_data.clone(), | ||
| 169 | + weight_config=config, | ||
| 170 | + activation_config=config, | ||
| 171 | + ) | ||
| 172 | + ) | ||
| 173 | + bias = torch.nn.Parameter(bias_data.clone()) | ||
| 174 | + actual = operation(activation, weight, bias) | ||
| 175 | + actual.sum().backward() | ||
| 176 | + | ||
| 177 | + activation_ref = torch.nn.Parameter(activation_data.clone()) | ||
| 178 | + weight_ref = torch.nn.Parameter(weight_data.clone()) | ||
| 179 | + bias_ref = torch.nn.Parameter(bias_data.clone()) | ||
| 180 | + expected = operation(activation_ref, weight_ref, bias_ref) | ||
| 181 | + expected.sum().backward() | ||
| 182 | + | ||
| 183 | + assert actual.shape == expected.shape | ||
| 184 | + assert compute_error(actual, expected) > _SQNR_THRESHOLD | ||
| 185 | + assert compute_error(activation.grad, activation_ref.grad) > _SQNR_THRESHOLD | ||
| 186 | + assert compute_error(weight.grad, weight_ref.grad) > _SQNR_THRESHOLD | ||
| 187 | + | ||
| 188 | + | ||
| 189 | +def test_bmm_dispatch_forward_backward_matches_dense_reference(): | ||
| 190 | + config = _config() | ||
| 191 | + activation_data = torch.randn(8, 32, 1024, device="npu", dtype=torch.bfloat16) | ||
| 192 | + weight_data = torch.randn(8, 1024, 2048, device="npu", dtype=torch.bfloat16) | ||
| 193 | + | ||
| 194 | + activation = torch.nn.Parameter(activation_data.clone()) | ||
| 195 | + weight = torch.nn.Parameter( | ||
| 196 | + HiF8TrainingWeightWrapperTensor( | ||
| 197 | + weight_data.clone(), | ||
| 198 | + weight_config=config, | ||
| 199 | + activation_config=config, | ||
| 200 | + ) | ||
| 201 | + ) | ||
| 202 | + actual = torch.bmm(activation, weight) | ||
| 203 | + actual.sum().backward() | ||
| 204 | + | ||
| 205 | + activation_ref = torch.nn.Parameter(activation_data.clone()) | ||
| 206 | + weight_ref = torch.nn.Parameter(weight_data.clone()) | ||
| 207 | + expected = torch.bmm(activation_ref, weight_ref) | ||
| 208 | + expected.sum().backward() | ||
| 209 | + | ||
| 210 | + assert actual.shape == expected.shape | ||
| 211 | + assert compute_error(actual, expected) > _SQNR_THRESHOLD | ||
| 212 | + assert compute_error(activation.grad, activation_ref.grad) > _SQNR_THRESHOLD | ||
| 213 | + assert compute_error(weight.grad, weight_ref.grad) > _SQNR_THRESHOLD | ||
| 214 | + | ||
| 215 | + | ||
| 216 | +def test_grouped_mm_dispatch_matches_dense_reference(): | ||
| 217 | + config = _config() | ||
| 218 | + num_tokens, num_experts, K, N = 16, 4, 1024, 2048 | ||
| 219 | + activation = torch.randn(num_tokens, K, device="npu", dtype=torch.bfloat16, requires_grad=True) | ||
| 220 | + weight_data = torch.randn(num_experts, N, K, device="npu", dtype=torch.bfloat16) | ||
| 221 | + weight = torch.nn.Parameter( | ||
| 222 | + HiF8TrainingWeightWrapperTensor(weight_data, weight_config=config, activation_config=config) | ||
| 223 | + ) | ||
| 224 | + offsets = torch.tensor([4, 8, 12, 16], dtype=torch.int32, device="npu") | ||
| 225 | + | ||
| 226 | + actual = torch._grouped_mm(activation, weight.transpose(-2, -1), offs=offsets) | ||
| 227 | + actual.sum().backward() | ||
| 228 | + | ||
| 229 | + activation_ref = activation.detach().clone().requires_grad_() | ||
| 230 | + weight_ref = weight_data.detach().clone().requires_grad_() | ||
| 231 | + expected = torch._grouped_mm(activation_ref, weight_ref.transpose(-2, -1), offs=offsets) | ||
| 232 | + expected.sum().backward() | ||
| 233 | + | ||
| 234 | + assert actual.shape == (num_tokens, N) | ||
| 235 | + assert compute_error(actual, expected) > _SQNR_THRESHOLD | ||
| 236 | + assert compute_error(activation.grad, activation_ref.grad) > _SQNR_THRESHOLD | ||
| 237 | + assert compute_error(weight.grad, weight_ref.grad) > _SQNR_THRESHOLD | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +@pytest.mark.parametrize("device", target_devices, ids=lambda value: str(value)) | ||
| 241 | +def test_deepcopy_preserves_wrapper_contract(device): | ||
| 242 | + wrapper = _wrapper((64, 128), device, dtype=torch.bfloat16) | ||
| 243 | + copied = copy.deepcopy(wrapper) | ||
| 244 | + | ||
| 245 | + assert isinstance(copied, HiF8TrainingWeightWrapperTensor) | ||
| 246 | + assert getattr(copied, "_data") is not getattr(wrapper, "_data") # noqa: B009 | ||
| 247 | + assert copied.weight_config == wrapper.weight_config | ||
| 248 | + assert copied.activation_config == wrapper.activation_config | ||
| 249 | + torch.testing.assert_close(getattr(copied, "_data"), getattr(wrapper, "_data")) # noqa: B009 | ||
| @@ -18,6 +18,7 @@ from torchao.quantization.transform_module import register_quantize_module_handl | |||
| 18 | from torchao_npu.quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data | 18 | from torchao_npu.quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data |
| 19 | from torchao_npu.quantization.quant_configs import ( | 19 | from torchao_npu.quantization.quant_configs import ( |
| 20 | BlockMXQuantizeConfig, | 20 | BlockMXQuantizeConfig, |
| 21 | + HiF8QuantizeConfig, | ||
| 21 | MXQuantizeConfig, | 22 | MXQuantizeConfig, |
| 22 | ) | 23 | ) |
| 23 | from torchao_npu.quantization.transform import ( | 24 | from torchao_npu.quantization.transform import ( |
| @@ -51,8 +52,10 @@ class ParamSwapConfig(QATConfig): | |||
| 51 | (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`), | 52 | (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`), |
| 52 | NPU MX block-wise | 53 | NPU MX block-wise |
| 53 | (:class:`~torchao_npu.quantization.quant_configs.MXQuantizeConfig`), | 54 | (:class:`~torchao_npu.quantization.quant_configs.MXQuantizeConfig`), |
| 54 | - and NPU Block MX | 55 | + NPU Block MX |
| 55 | - (:class:`~torchao_npu.quantization.quant_configs.BlockMXQuantizeConfig`). | 56 | + (:class:`~torchao_npu.quantization.quant_configs.BlockMXQuantizeConfig`), |
| 57 | + and NPU HiF8 per-tensor | ||
| 58 | + (:class:`~torchao_npu.quantization.quant_configs.HiF8QuantizeConfig`). | ||
| 56 | """ | 59 | """ |
| 57 | 60 | ||
| 58 | def __init__( | 61 | def __init__( |
| @@ -72,19 +75,21 @@ class ParamSwapConfig(QATConfig): | |||
| 72 | if self.activation_config is not None and type(self.activation_config) not in ( | 75 | if self.activation_config is not None and type(self.activation_config) not in ( |
| 73 | Float8FakeQuantizeConfig, | 76 | Float8FakeQuantizeConfig, |
| 74 | MXQuantizeConfig, | 77 | MXQuantizeConfig, |
| 78 | + HiF8QuantizeConfig, | ||
| 75 | ): | 79 | ): |
| 76 | raise ValueError( | 80 | raise ValueError( |
| 77 | - "Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` " | 81 | + "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `HiF8QuantizeConfig` " |
| 78 | "is supported for `activation_config` in ParamSwapConfig yet." | 82 | "is supported for `activation_config` in ParamSwapConfig yet." |
| 79 | ) | 83 | ) |
| 80 | if self.weight_config is not None and type(self.weight_config) not in ( | 84 | if self.weight_config is not None and type(self.weight_config) not in ( |
| 81 | Float8FakeQuantizeConfig, | 85 | Float8FakeQuantizeConfig, |
| 82 | MXQuantizeConfig, | 86 | MXQuantizeConfig, |
| 83 | BlockMXQuantizeConfig, | 87 | BlockMXQuantizeConfig, |
| 88 | + HiF8QuantizeConfig, | ||
| 84 | ): | 89 | ): |
| 85 | raise ValueError( | 90 | raise ValueError( |
| 86 | - "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockMXQuantizeConfig` " | 91 | + "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, `BlockMXQuantizeConfig`, or " |
| 87 | - "is supported for `weight_config` in ParamSwapConfig yet." | 92 | + "`HiF8QuantizeConfig` is supported for `weight_config` in ParamSwapConfig yet." |
| 88 | ) | 93 | ) |
| 89 | 94 | ||
| 90 | super().__post_init__() | 95 | super().__post_init__() |
| @@ -10,5 +10,6 @@ public surface via ``__all__``: | |||
| 10 | 10 | ||
| 11 | - :mod:`torchao_npu.ops.block_mx_ops` — Block MX matmul ops | 11 | - :mod:`torchao_npu.ops.block_mx_ops` — Block MX matmul ops |
| 12 | - :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization | 12 | - :mod:`torchao_npu.ops.float8_ops` — FP8 row-wise fake quantization |
| 13 | +- :mod:`torchao_npu.ops.hif8_ops` — Per-tensor HiF8 matmul ops (current/constant tensor scaling) | ||
| 13 | - :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops | 14 | - :mod:`torchao_npu.ops.mx_ops` — MX (FP8/FP4) matmul and (de)quantization ops |
| 14 | """ | 15 | """ |
| @@ -0,0 +1,357 @@ | |||
| 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 | +"""Per-tensor HiF8 low-precision matmul operators for NPU. | ||
| 7 | + | ||
| 8 | +Current/constant tensor scaling (CTS) only: every quantize call recomputes | ||
| 9 | +its scale fresh via ``torch_npu.npu_dynamic_quant``. There is no persistent | ||
| 10 | +per-parameter scale state and no delayed/windowed scaling. | ||
| 11 | +""" | ||
| 12 | + | ||
| 13 | +import torch | ||
| 14 | +import torch_npu | ||
| 15 | + | ||
| 16 | +from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | ||
| 17 | +from torchao_npu.quantization.quant_primitives.hif8 import quantize_hifloat8 | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def _ensure_bf16_or_fp16(t: torch.Tensor) -> torch.Tensor: | ||
| 21 | + """``npu_dynamic_quant``'s per-tensor path accepts bf16/fp16 inputs.""" | ||
| 22 | + if t.dtype not in (torch.float16, torch.bfloat16): | ||
| 23 | + return t.to(torch.bfloat16) | ||
| 24 | + return t | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def _per_expert_scale(scale: torch.Tensor, num_experts: int) -> torch.Tensor: | ||
| 28 | + """Per-tensor ``scale`` as one ``npu_grouped_matmul`` scale-list entry.""" | ||
| 29 | + return scale.reshape(1).expand(num_experts).contiguous() | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def _per_expert_scale_product(a: torch.Tensor, b: torch.Tensor, num_experts: int) -> torch.Tensor: | ||
| 33 | + """``a * b`` (both per-tensor) as one ``npu_grouped_matmul`` scale entry. | ||
| 34 | + | ||
| 35 | + ``(a * b).expand(E).contiguous()`` costs a multiply plus a copy; the | ||
| 36 | + broadcasting multiply below writes the E-long contiguous result in a | ||
| 37 | + single kernel and is bit-identical (every lane is the same scalar | ||
| 38 | + product of the same two fp32 values). | ||
| 39 | + """ | ||
| 40 | + return a.reshape(1).expand(num_experts) * b.reshape(1) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +class _HiF8QuantMM(torch.autograd.Function): | ||
| 44 | + """Per-tensor HiF8 matrix multiply: ``A[M,K] @ B[K,N] = Y[M,N]``.""" | ||
| 45 | + | ||
| 46 | + @staticmethod | ||
| 47 | + # pyrefly: ignore [bad-override] | ||
| 48 | + def forward( | ||
| 49 | + ctx, | ||
| 50 | + A: torch.Tensor, | ||
| 51 | + B: torch.Tensor, | ||
| 52 | + config_A: HiF8QuantizeConfig, | ||
| 53 | + config_B: HiF8QuantizeConfig, | ||
| 54 | + ): | ||
| 55 | + assert A.ndim >= 2, f"A must be >=2D, got {A.ndim}D" | ||
| 56 | + assert B.ndim == 2, f"B must be 2D, got {B.ndim}D" | ||
| 57 | + assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}" | ||
| 58 | + | ||
| 59 | + A_flat = _ensure_bf16_or_fp16(A.reshape(-1, A.shape[-1])) | ||
| 60 | + | ||
| 61 | + A_q, A_s = quantize_hifloat8(A_flat, config_A) | ||
| 62 | + B_q, B_s = quantize_hifloat8(B, config_B) | ||
| 63 | + | ||
| 64 | + Y = torch_npu.npu_quant_matmul( | ||
| 65 | + A_q, | ||
| 66 | + B_q, | ||
| 67 | + B_s, | ||
| 68 | + pertoken_scale=A_s, | ||
| 69 | + output_dtype=A_flat.dtype, | ||
| 70 | + x1_dtype=config_A.elem_dtype, | ||
| 71 | + x2_dtype=config_B.elem_dtype, | ||
| 72 | + ) | ||
| 73 | + | ||
| 74 | + if A.ndim != 2: | ||
| 75 | + Y = Y.reshape(*A.shape[:-1], *Y.shape[1:]) | ||
| 76 | + | ||
| 77 | + Y.requires_grad_(A.requires_grad or B.requires_grad) | ||
| 78 | + | ||
| 79 | + ctx.save_for_backward(A_q, A_s, B_q, B_s) | ||
| 80 | + ctx.A_dtype = A_flat.dtype | ||
| 81 | + ctx.config_A = config_A | ||
| 82 | + ctx.config_B = config_B | ||
| 83 | + return Y | ||
| 84 | + | ||
| 85 | + @staticmethod | ||
| 86 | + # pyrefly: ignore [bad-override] | ||
| 87 | + def backward(ctx, dY: torch.Tensor): | ||
| 88 | + A_q, A_s, B_q, B_s = ctx.saved_tensors | ||
| 89 | + A_dtype = ctx.A_dtype | ||
| 90 | + config_A = ctx.config_A | ||
| 91 | + config_B = ctx.config_B | ||
| 92 | + | ||
| 93 | + dY_q, dY_s = quantize_hifloat8(dY.reshape(-1, dY.shape[-1]), config_A) | ||
| 94 | + | ||
| 95 | + dA = torch_npu.npu_quant_matmul( | ||
| 96 | + dY_q, | ||
| 97 | + B_q.t(), | ||
| 98 | + B_s, | ||
| 99 | + pertoken_scale=dY_s, | ||
| 100 | + output_dtype=A_dtype, | ||
| 101 | + x1_dtype=config_A.elem_dtype, | ||
| 102 | + x2_dtype=config_B.elem_dtype, | ||
| 103 | + ) | ||
| 104 | + | ||
| 105 | + dB = torch_npu.npu_quant_matmul( | ||
| 106 | + A_q.t(), | ||
| 107 | + dY_q, | ||
| 108 | + dY_s, | ||
| 109 | + pertoken_scale=A_s, | ||
| 110 | + output_dtype=A_dtype, | ||
| 111 | + x1_dtype=config_A.elem_dtype, | ||
| 112 | + x2_dtype=config_A.elem_dtype, | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + if dY.ndim != 2: | ||
| 116 | + dA = dA.reshape(*dY.shape[:-1], *dA.shape[1:]) | ||
| 117 | + | ||
| 118 | + return dA, dB, None, None | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def to_hif8_then_mm( | ||
| 122 | + A: torch.Tensor, | ||
| 123 | + B: torch.Tensor, | ||
| 124 | + config_A: HiF8QuantizeConfig, | ||
| 125 | + config_B: HiF8QuantizeConfig, | ||
| 126 | +) -> torch.Tensor: | ||
| 127 | + """Run per-tensor HiF8 matrix multiplication ``A @ B``. | ||
| 128 | + | ||
| 129 | + ``A`` may have leading dimensions; they are flattened during the | ||
| 130 | + operation and restored in the result. ``B`` must be two-dimensional. | ||
| 131 | + """ | ||
| 132 | + return _HiF8QuantMM.apply(A, B, config_A, config_B) | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +class _HiF8QuantGroupedMM(torch.autograd.Function): | ||
| 136 | + """Per-tensor HiF8 grouped matmul: ``A[M,K] @ B[E,K,N] = Y[M,N]``.""" | ||
| 137 | + | ||
| 138 | + @staticmethod | ||
| 139 | + # pyrefly: ignore [bad-override] | ||
| 140 | + def forward( | ||
| 141 | + ctx, | ||
| 142 | + A: torch.Tensor, | ||
| 143 | + B: torch.Tensor, | ||
| 144 | + group_list: torch.Tensor, | ||
| 145 | + config_A: HiF8QuantizeConfig, | ||
| 146 | + config_B: HiF8QuantizeConfig, | ||
| 147 | + ): | ||
| 148 | + assert A.ndim == 2, f"A must be 2D, got {A.ndim}D" | ||
| 149 | + assert B.ndim == 3, f"B must be 3D, got {B.ndim}D" | ||
| 150 | + assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}" | ||
| 151 | + | ||
| 152 | + group_list = group_list.to(torch.int64) | ||
| 153 | + num_experts = B.shape[0] | ||
| 154 | + | ||
| 155 | + A_c = _ensure_bf16_or_fp16(A) | ||
| 156 | + B_dtype = B.dtype | ||
| 157 | + | ||
| 158 | + A_q, A_s = quantize_hifloat8(A_c, config_A) | ||
| 159 | + B_q, B_s = quantize_hifloat8(B, config_B) | ||
| 160 | + | ||
| 161 | + # scale slot: [E], the per-tensor weight scale broadcast per expert, | ||
| 162 | + # times the activation's per-tensor scale. | ||
| 163 | + fwd_scale = _per_expert_scale_product(A_s, B_s, num_experts) | ||
| 164 | + | ||
| 165 | + Y = torch_npu.npu_grouped_matmul( | ||
| 166 | + [A_q], | ||
| 167 | + [B_q], | ||
| 168 | + scale=[fwd_scale], | ||
| 169 | + per_token_scale=None, | ||
| 170 | + group_list=group_list, | ||
| 171 | + group_type=0, | ||
| 172 | + bias=None, | ||
| 173 | + split_item=3, | ||
| 174 | + output_dtype=A_c.dtype, | ||
| 175 | + group_list_type=0, | ||
| 176 | + x_dtype=config_A.elem_dtype, | ||
| 177 | + weight_dtype=config_B.elem_dtype, | ||
| 178 | + )[0] | ||
| 179 | + | ||
| 180 | + Y.requires_grad_(A.requires_grad or B.requires_grad) | ||
| 181 | + | ||
| 182 | + ctx.B_dtype = B_dtype | ||
| 183 | + ctx.save_for_backward(A_q, A_s, B_q, B_s, group_list) | ||
| 184 | + ctx.A_dtype = A_c.dtype | ||
| 185 | + ctx.config_A = config_A | ||
| 186 | + ctx.config_B = config_B | ||
| 187 | + return Y | ||
| 188 | + | ||
| 189 | + @staticmethod | ||
| 190 | + # pyrefly: ignore [bad-override] | ||
| 191 | + def backward(ctx, dY: torch.Tensor): | ||
| 192 | + A_q, A_s, B_q, B_s, group_list = ctx.saved_tensors | ||
| 193 | + A_dtype = ctx.A_dtype | ||
| 194 | + config_A = ctx.config_A | ||
| 195 | + config_B = ctx.config_B | ||
| 196 | + assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D" | ||
| 197 | + | ||
| 198 | + num_experts = B_q.shape[0] | ||
| 199 | + | ||
| 200 | + dY_q, dY_s = quantize_hifloat8(dY, config_A) | ||
| 201 | + | ||
| 202 | + # B's per-tensor scale is unchanged by transpose (a single global | ||
| 203 | + # scalar), so B_q's transpose is reused directly instead of | ||
| 204 | + # re-quantizing B_t. | ||
| 205 | + B_t_q = B_q.transpose(-1, -2) | ||
| 206 | + B_t_s = B_s | ||
| 207 | + | ||
| 208 | + dgrad_scale = _per_expert_scale_product(dY_s, B_t_s, num_experts) | ||
| 209 | + | ||
| 210 | + dA = torch_npu.npu_grouped_matmul( | ||
| 211 | + [dY_q], | ||
| 212 | + [B_t_q], | ||
| 213 | + bias=None, | ||
| 214 | + scale=[dgrad_scale], | ||
| 215 | + per_token_scale=None, | ||
| 216 | + group_list=group_list, | ||
| 217 | + group_type=0, | ||
| 218 | + split_item=3, | ||
| 219 | + output_dtype=A_dtype, | ||
| 220 | + group_list_type=0, | ||
| 221 | + x_dtype=config_A.elem_dtype, | ||
| 222 | + weight_dtype=config_B.elem_dtype, | ||
| 223 | + )[0] | ||
| 224 | + | ||
| 225 | + wgrad_scale = _per_expert_scale(dY_s, num_experts) | ||
| 226 | + wgrad_pertoken = _per_expert_scale(A_s, num_experts) | ||
| 227 | + | ||
| 228 | + dB = torch_npu.npu_grouped_matmul( | ||
| 229 | + [A_q.t()], | ||
| 230 | + [dY_q], | ||
| 231 | + scale=[wgrad_scale], | ||
| 232 | + per_token_scale=[wgrad_pertoken], | ||
| 233 | + group_list=group_list, | ||
| 234 | + group_type=2, | ||
| 235 | + bias=None, | ||
| 236 | + split_item=3, | ||
| 237 | + output_dtype=A_dtype, | ||
| 238 | + group_list_type=0, | ||
| 239 | + x_dtype=config_A.elem_dtype, | ||
| 240 | + weight_dtype=config_A.elem_dtype, | ||
| 241 | + )[0] | ||
| 242 | + | ||
| 243 | + if dB.dtype != ctx.B_dtype: | ||
| 244 | + dB = dB.to(ctx.B_dtype) | ||
| 245 | + return dA, dB, None, None, None | ||
| 246 | + | ||
| 247 | + | ||
| 248 | +def to_hif8_then_grouped_mm( | ||
| 249 | + A: torch.Tensor, | ||
| 250 | + B: torch.Tensor, | ||
| 251 | + group_list: torch.Tensor, | ||
| 252 | + config_A: HiF8QuantizeConfig, | ||
| 253 | + config_B: HiF8QuantizeConfig, | ||
| 254 | +) -> torch.Tensor: | ||
| 255 | + """Run per-tensor HiF8 grouped matmul ``A @ B``. | ||
| 256 | + | ||
| 257 | + ``group_list`` contains cumulative row offsets for the expert groups. | ||
| 258 | + """ | ||
| 259 | + return _HiF8QuantGroupedMM.apply(A, B, group_list, config_A, config_B) | ||
| 260 | + | ||
| 261 | + | ||
| 262 | +class _HiF8QuantBMM(torch.autograd.Function): | ||
| 263 | + """Per-tensor HiF8 batched matmul: ``A[b,M,K] @ B[b,K,N] = Y[b,M,N]``. | ||
| 264 | + | ||
| 265 | + Both operands are 3D and share the leading batch dimension. Forward | ||
| 266 | + per-tensor quantizes both operands and runs the low-precision batched | ||
| 267 | + matmul contracting over K. Backward reuses the forward-quantized | ||
| 268 | + ``A_q/B_q`` transposed and only quantizes ``dY`` fresh -- the same scheme | ||
| 269 | + as :class:`_HiF8QuantMM`. | ||
| 270 | + """ | ||
| 271 | + | ||
| 272 | + @staticmethod | ||
| 273 | + # pyrefly: ignore [bad-override] | ||
| 274 | + def forward( | ||
| 275 | + ctx, | ||
| 276 | + A: torch.Tensor, | ||
| 277 | + B: torch.Tensor, | ||
| 278 | + config_A: HiF8QuantizeConfig, | ||
| 279 | + config_B: HiF8QuantizeConfig, | ||
| 280 | + ): | ||
| 281 | + assert A.ndim == 3, f"A must be 3D, got {A.ndim}D" | ||
| 282 | + assert B.ndim == 3, f"B must be 3D, got {B.ndim}D" | ||
| 283 | + assert A.shape[0] == B.shape[0], f"batch dim mismatch: A[0]={A.shape[0]} != B[0]={B.shape[0]}" | ||
| 284 | + assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}" | ||
| 285 | + | ||
| 286 | + A_c = _ensure_bf16_or_fp16(A) | ||
| 287 | + | ||
| 288 | + A_q, A_s = quantize_hifloat8(A_c, config_A) | ||
| 289 | + B_q, B_s = quantize_hifloat8(B, config_B) | ||
| 290 | + | ||
| 291 | + Y = torch_npu.npu_quant_matmul( | ||
| 292 | + A_q, | ||
| 293 | + B_q, | ||
| 294 | + B_s, | ||
| 295 | + pertoken_scale=A_s, | ||
| 296 | + output_dtype=A_c.dtype, | ||
| 297 | + x1_dtype=config_A.elem_dtype, | ||
| 298 | + x2_dtype=config_B.elem_dtype, | ||
| 299 | + ) | ||
| 300 | + | ||
| 301 | + Y.requires_grad_(A.requires_grad or B.requires_grad) | ||
| 302 | + | ||
| 303 | + ctx.save_for_backward(A_q, A_s, B_q, B_s) | ||
| 304 | + ctx.A_dtype = A_c.dtype | ||
| 305 | + ctx.config_A = config_A | ||
| 306 | + ctx.config_B = config_B | ||
| 307 | + return Y | ||
| 308 | + | ||
| 309 | + @staticmethod | ||
| 310 | + # pyrefly: ignore [bad-override] | ||
| 311 | + def backward(ctx, dY: torch.Tensor): | ||
| 312 | + A_q, A_s, B_q, B_s = ctx.saved_tensors | ||
| 313 | + A_dtype = ctx.A_dtype | ||
| 314 | + config_A = ctx.config_A | ||
| 315 | + config_B = ctx.config_B | ||
| 316 | + assert dY.ndim == 3, f"dY must be 3D, got {dY.ndim}D" | ||
| 317 | + | ||
| 318 | + dY_q, dY_s = quantize_hifloat8(dY, config_A) | ||
| 319 | + | ||
| 320 | + # dgrad dA = dY @ B^T (contract over N) | ||
| 321 | + dA = torch_npu.npu_quant_matmul( | ||
| 322 | + dY_q, | ||
| 323 | + B_q.transpose(-1, -2), | ||
| 324 | + B_s, | ||
| 325 | + pertoken_scale=dY_s, | ||
| 326 | + output_dtype=A_dtype, | ||
| 327 | + x1_dtype=config_A.elem_dtype, | ||
| 328 | + x2_dtype=config_B.elem_dtype, | ||
| 329 | + ) | ||
| 330 | + | ||
| 331 | + # wgrad dB = A^T @ dY (contract over M) | ||
| 332 | + dB = torch_npu.npu_quant_matmul( | ||
| 333 | + A_q.transpose(-1, -2), | ||
| 334 | + dY_q, | ||
| 335 | + dY_s, | ||
| 336 | + pertoken_scale=A_s, | ||
| 337 | + output_dtype=A_dtype, | ||
| 338 | + x1_dtype=config_A.elem_dtype, | ||
| 339 | + x2_dtype=config_A.elem_dtype, | ||
| 340 | + ) | ||
| 341 | + | ||
| 342 | + return dA, dB, None, None | ||
| 343 | + | ||
| 344 | + | ||
| 345 | +def to_hif8_then_bmm( | ||
| 346 | + A: torch.Tensor, | ||
| 347 | + B: torch.Tensor, | ||
| 348 | + config_A: HiF8QuantizeConfig, | ||
| 349 | + config_B: HiF8QuantizeConfig, | ||
| 350 | +) -> torch.Tensor: | ||
| 351 | + """Run per-tensor HiF8 batched matmul ``A @ B``. | ||
| 352 | + | ||
| 353 | + Both operands must be 3D and share the leading batch dimension. | ||
| 354 | + Quantization configs are drawn from ``config_A`` (for A and dY) and | ||
| 355 | + ``config_B`` (for B). | ||
| 356 | + """ | ||
| 357 | + return _HiF8QuantBMM.apply(A, B, config_A, config_B) | ||
| @@ -108,7 +108,16 @@ class FP8QuantizeConfig(FakeQuantizeConfigBase): | |||
| 108 | 108 | ||
| 109 | @dataclass | 109 | @dataclass |
| 110 | class HiF8QuantizeConfig(FakeQuantizeConfigBase): | 110 | class HiF8QuantizeConfig(FakeQuantizeConfigBase): |
| 111 | - """HiFloat8 dynamic quantization configuration.""" | 111 | + """HiFloat8 dynamic quantization configuration. |
| 112 | + | ||
| 113 | + Serves two call sites: | ||
| 114 | + | ||
| 115 | + - Lightning Indexer Q/K quantization (:mod:`torchao_npu.ops.li_ops`). | ||
| 116 | + - Dense/MoE weight+activation matmul quantization | ||
| 117 | + (:mod:`torchao_npu.ops.hif8_ops`, current/constant tensor scaling: the | ||
| 118 | + scale is recomputed fresh via ``npu_dynamic_quant`` on every call, no | ||
| 119 | + persisted per-parameter state). | ||
| 120 | + """ | ||
| 112 | 121 | ||
| 113 | elem_dtype: object = torch_npu.hifloat8 | 122 | elem_dtype: object = torch_npu.hifloat8 |
| 114 | dst_type_max: float = 0.0 | 123 | dst_type_max: float = 0.0 |
| @@ -3,7 +3,7 @@ | |||
| 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 | -"""HiFloat8 quantization primitive.""" | 6 | +"""HiFloat8 quantization primitives.""" |
| 7 | 7 | ||
| 8 | __all__ = ["quantize_hifloat8"] | 8 | __all__ = ["quantize_hifloat8"] |
| 9 | 9 | ||
| @@ -13,15 +13,34 @@ import torch_npu | |||
| 13 | from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | 13 | from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig |
| 14 | 14 | ||
| 15 | 15 | ||
| 16 | -def quantize_hifloat8(value: torch.Tensor, config: HiF8QuantizeConfig): | 16 | +def quantize_hifloat8(tensor: torch.Tensor, config: HiF8QuantizeConfig) -> tuple[torch.Tensor, torch.Tensor]: |
| 17 | - """Quantize a tensor to HiFloat8 with a float32 scale.""" | 17 | + """Quantize a tensor to HiFloat8 with a float32 scale. Requires |
| 18 | + ``quant_mode == "pertensor"``: its single scalar scale is permutation- | ||
| 19 | + invariant, so quantizing on a dense (descending-stride) view instead of | ||
| 20 | + whatever layout the tensor arrived in avoids the implicit | ||
| 21 | + ``Contiguous``/``Transpose`` copy ``npu_dynamic_quant`` does internally | ||
| 22 | + for a non-dense input -- without an ``is_contiguous()`` check, which | ||
| 23 | + would evaluate as a guard under ``torch.compile``. ``pertoken``/ | ||
| 24 | + ``perchannel`` reduce over a specific axis, which permuting would | ||
| 25 | + silently change, hence the check below. | ||
| 26 | + """ | ||
| 27 | + if config.quant_mode != "pertensor": | ||
| 28 | + raise ValueError(f"quantize_hifloat8 requires quant_mode='pertensor', got {config.quant_mode!r}.") | ||
| 18 | 29 | ||
| 19 | - if value.dtype not in (torch.float16, torch.bfloat16): | 30 | + if tensor.dtype not in (torch.float16, torch.bfloat16): |
| 20 | - value = value.to(torch.bfloat16) | 31 | + tensor = tensor.to(torch.bfloat16) |
| 21 | - q_data, descale = torch_npu.npu_dynamic_quant( | 32 | + |
| 22 | - value, | 33 | + perm_indices = sorted(range(tensor.ndim), key=lambda d: tensor.stride(d), reverse=True) |
| 23 | - dst_type=config.elem_dtype, | 34 | + tensor_p = tensor.permute(perm_indices) |
| 24 | - dst_type_max=config.dst_type_max, | 35 | + |
| 25 | - quant_mode=config.quant_mode, | 36 | + y_p, scale = torch_npu.npu_dynamic_quant( |
| 37 | + tensor_p, dst_type=config.elem_dtype, dst_type_max=config.dst_type_max, quant_mode=config.quant_mode | ||
| 26 | ) | 38 | ) |
| 27 | - return q_data, descale.to(torch.float32) | 39 | + |
| 40 | + # Inverse permutation: y_p dim j corresponds to tensor dim perm_indices[j]. | ||
| 41 | + perm_back_indices = [0] * tensor.ndim | ||
| 42 | + for j, p in enumerate(perm_indices): | ||
| 43 | + perm_back_indices[p] = j | ||
| 44 | + y = y_p.permute(perm_back_indices) | ||
| 45 | + | ||
| 46 | + return y, scale.to(torch.float32) | ||
| @@ -6,11 +6,13 @@ | |||
| 6 | from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor | 6 | from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor |
| 7 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor | 7 | from torchao_npu.wrapper_tensors.block_mx_wrapper_tensor import BlockMXTrainingWeightWrapperTensor |
| 8 | from torchao_npu.wrapper_tensors.float8_wrapper_tensor import Float8TrainingWeightWrapperTensor | 8 | from torchao_npu.wrapper_tensors.float8_wrapper_tensor import Float8TrainingWeightWrapperTensor |
| 9 | +from torchao_npu.wrapper_tensors.hif8_wrapper_tensor import HiF8TrainingWeightWrapperTensor | ||
| 9 | from torchao_npu.wrapper_tensors.mx_wrapper_tensor import MXTrainingWeightWrapperTensor | 10 | from torchao_npu.wrapper_tensors.mx_wrapper_tensor import MXTrainingWeightWrapperTensor |
| 10 | 11 | ||
| 11 | __all__ = [ | 12 | __all__ = [ |
| 12 | "BaseTrainingWeightWrapperTensor", | 13 | "BaseTrainingWeightWrapperTensor", |
| 13 | "BlockMXTrainingWeightWrapperTensor", | 14 | "BlockMXTrainingWeightWrapperTensor", |
| 14 | "Float8TrainingWeightWrapperTensor", | 15 | "Float8TrainingWeightWrapperTensor", |
| 16 | + "HiF8TrainingWeightWrapperTensor", | ||
| 15 | "MXTrainingWeightWrapperTensor", | 17 | "MXTrainingWeightWrapperTensor", |
| 16 | ] | 18 | ] |
| @@ -0,0 +1,198 @@ | |||
| 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 | +from typing import Any | ||
| 7 | + | ||
| 8 | +import torch | ||
| 9 | +from torch import nn | ||
| 10 | +from torchao.prototype.moe_training.utils import unwrap_weight | ||
| 11 | + | ||
| 12 | +from torchao_npu.ops.hif8_ops import to_hif8_then_bmm, to_hif8_then_grouped_mm, to_hif8_then_mm | ||
| 13 | +from torchao_npu.quantization.quant_configs import HiF8QuantizeConfig | ||
| 14 | +from torchao_npu.quantization.transform import register_parameter_swap_handler | ||
| 15 | +from torchao_npu.wrapper_tensors.base_wrapper_tensor import BaseTrainingWeightWrapperTensor | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class HiF8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor): | ||
| 19 | + """Applies real per-tensor HiF8 quantized matmul on NPU.""" | ||
| 20 | + | ||
| 21 | + weight_config: HiF8QuantizeConfig | ||
| 22 | + activation_config: HiF8QuantizeConfig | ||
| 23 | + | ||
| 24 | + def __init__( | ||
| 25 | + self, | ||
| 26 | + tensor: torch.Tensor, | ||
| 27 | + weight_config: HiF8QuantizeConfig | None = None, | ||
| 28 | + activation_config: HiF8QuantizeConfig | None = None, | ||
| 29 | + ): | ||
| 30 | + if weight_config is None: | ||
| 31 | + raise ValueError(f"`weight_config` is required for {type(self).__name__}.") | ||
| 32 | + | ||
| 33 | + if activation_config is None: | ||
| 34 | + raise ValueError(f"`activation_config` is required for {type(self).__name__}.") | ||
| 35 | + | ||
| 36 | + if not isinstance(weight_config, HiF8QuantizeConfig): | ||
| 37 | + raise ValueError(f"Only `HiF8QuantizeConfig` is supported for `weight_config` in {type(self).__name__}.") | ||
| 38 | + | ||
| 39 | + if not isinstance(activation_config, HiF8QuantizeConfig): | ||
| 40 | + raise ValueError( | ||
| 41 | + f"Only `HiF8QuantizeConfig` is supported for `activation_config` in {type(self).__name__}." | ||
| 42 | + ) | ||
| 43 | + | ||
| 44 | + if weight_config.quant_mode != "pertensor": | ||
| 45 | + raise ValueError( | ||
| 46 | + f"`weight_config.quant_mode` must be 'pertensor' for {type(self).__name__}, " | ||
| 47 | + f"got {weight_config.quant_mode!r}." | ||
| 48 | + ) | ||
| 49 | + | ||
| 50 | + if activation_config.quant_mode != "pertensor": | ||
| 51 | + raise ValueError( | ||
| 52 | + f"`activation_config.quant_mode` must be 'pertensor' for {type(self).__name__}, " | ||
| 53 | + f"got {activation_config.quant_mode!r}." | ||
| 54 | + ) | ||
| 55 | + | ||
| 56 | + if weight_config != activation_config: | ||
| 57 | + raise ValueError( | ||
| 58 | + f"`weight_config` and `activation_config` must be equal in {type(self).__name__}, " | ||
| 59 | + f"got weight_config={weight_config}, activation_config={activation_config}." | ||
| 60 | + ) | ||
| 61 | + | ||
| 62 | + super().__init__( | ||
| 63 | + tensor, | ||
| 64 | + weight_config=weight_config, | ||
| 65 | + activation_config=activation_config, | ||
| 66 | + ) | ||
| 67 | + | ||
| 68 | + @classmethod | ||
| 69 | + def __torch_function__(cls, func, types, args=(), kwargs=None): | ||
| 70 | + if kwargs is None: | ||
| 71 | + kwargs = {} | ||
| 72 | + | ||
| 73 | + if func in (torch.mm, torch.matmul): | ||
| 74 | + return cls._hif8_mm(args, kwargs) | ||
| 75 | + | ||
| 76 | + if func is torch._grouped_mm: | ||
| 77 | + return cls._hif8_grouped_mm(args, kwargs) | ||
| 78 | + | ||
| 79 | + if func is torch.nn.functional.linear: | ||
| 80 | + return cls._hif8_linear(args, kwargs) | ||
| 81 | + | ||
| 82 | + if func is torch.addmm: | ||
| 83 | + return cls._hif8_addmm(args, kwargs) | ||
| 84 | + | ||
| 85 | + if func is torch.bmm: | ||
| 86 | + return cls._hif8_bmm(args, kwargs) | ||
| 87 | + | ||
| 88 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 89 | + return func(*args, **kwargs) | ||
| 90 | + | ||
| 91 | + @classmethod | ||
| 92 | + def _hif8_mm(cls, args, kwargs): | ||
| 93 | + A, B = args[0], args[1] | ||
| 94 | + assert not isinstance(A, cls), f"A should not be a {cls.__name__}" | ||
| 95 | + assert isinstance(B, cls), f"B should be a {cls.__name__}" | ||
| 96 | + | ||
| 97 | + B_data = unwrap_weight(B) | ||
| 98 | + | ||
| 99 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 100 | + return to_hif8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore | ||
| 101 | + | ||
| 102 | + @classmethod | ||
| 103 | + def _hif8_bmm(cls, args, kwargs): | ||
| 104 | + A, B = args[0], args[1] | ||
| 105 | + assert not isinstance(A, cls), f"A should not be a {cls.__name__}" | ||
| 106 | + assert isinstance(B, cls), f"B should be a {cls.__name__}" | ||
| 107 | + | ||
| 108 | + B_data = unwrap_weight(B) | ||
| 109 | + | ||
| 110 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 111 | + return to_hif8_then_bmm(A, B_data, B.activation_config, B.weight_config) # type: ignore | ||
| 112 | + | ||
| 113 | + @classmethod | ||
| 114 | + def _hif8_grouped_mm(cls, args, kwargs): | ||
| 115 | + A, B = args[0], args[1] | ||
| 116 | + assert not isinstance(A, cls), f"A should not be a {cls.__name__}" | ||
| 117 | + assert isinstance(B, cls), f"B should be a {cls.__name__}" | ||
| 118 | + | ||
| 119 | + group_list = args[2] if len(args) > 2 else kwargs.get("offs") | ||
| 120 | + B_data = unwrap_weight(B) | ||
| 121 | + | ||
| 122 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 123 | + return to_hif8_then_grouped_mm( | ||
| 124 | + A, | ||
| 125 | + B_data, | ||
| 126 | + group_list, | ||
| 127 | + B.activation_config, # type: ignore | ||
| 128 | + B.weight_config, # type: ignore | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + @classmethod | ||
| 132 | + def _hif8_linear(cls, args, kwargs): | ||
| 133 | + A, B = args[0], args[1] | ||
| 134 | + assert not isinstance(A, cls), f"A should not be a {cls.__name__}" | ||
| 135 | + assert isinstance(B, cls), f"B should be a {cls.__name__}" | ||
| 136 | + | ||
| 137 | + B_data = unwrap_weight(B) | ||
| 138 | + bias = args[2] if len(args) > 2 else kwargs.get("bias") | ||
| 139 | + | ||
| 140 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 141 | + result = to_hif8_then_mm(A, B_data.T, B.activation_config, B.weight_config) # type: ignore | ||
| 142 | + if bias is not None: | ||
| 143 | + result = result + bias | ||
| 144 | + return result | ||
| 145 | + | ||
| 146 | + @classmethod | ||
| 147 | + def _hif8_addmm(cls, args, kwargs): | ||
| 148 | + # addmm(input, mat1, mat2, *, beta=1, alpha=1) -> beta * input + alpha * (mat1 @ mat2) | ||
| 149 | + bias, A, B = args[0], args[1], args[2] | ||
| 150 | + assert not isinstance(A, cls), f"A should not be a {cls.__name__}" | ||
| 151 | + assert isinstance(B, cls), f"B should be a {cls.__name__}" | ||
| 152 | + | ||
| 153 | + beta = kwargs.get("beta", 1) | ||
| 154 | + alpha = kwargs.get("alpha", 1) | ||
| 155 | + B_data = unwrap_weight(B) | ||
| 156 | + | ||
| 157 | + with torch._C.DisableTorchFunctionSubclass(): | ||
| 158 | + matmul = to_hif8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore | ||
| 159 | + if beta == 1 and alpha == 1: | ||
| 160 | + # addmm's default scaling: skip two multiply-by-one kernels | ||
| 161 | + # over the full [M, N] result (x * 1 is the identity for every | ||
| 162 | + # IEEE value, so this is bit-identical). | ||
| 163 | + return bias + matmul | ||
| 164 | + return beta * bias + alpha * matmul | ||
| 165 | + | ||
| 166 | + | ||
| 167 | +@register_parameter_swap_handler(HiF8QuantizeConfig) | ||
| 168 | +def _( | ||
| 169 | + module: nn.Module, | ||
| 170 | + param_fqn: str, | ||
| 171 | + param: nn.Parameter, | ||
| 172 | + extra_args: tuple[Any, ...] = (), | ||
| 173 | +): | ||
| 174 | + from ..configs import ParamSwapConfig | ||
| 175 | + | ||
| 176 | + config: ParamSwapConfig = extra_args[0] | ||
| 177 | + | ||
| 178 | + if not isinstance(config, ParamSwapConfig): | ||
| 179 | + raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.") | ||
| 180 | + | ||
| 181 | + if config.activation_config is not None and not isinstance(config.activation_config, HiF8QuantizeConfig): | ||
| 182 | + raise ValueError( | ||
| 183 | + f"activation_config must be {HiF8QuantizeConfig.__name__}, got {type(config.activation_config).__name__}." | ||
| 184 | + ) | ||
| 185 | + | ||
| 186 | + if config.weight_config is not None and not isinstance(config.weight_config, HiF8QuantizeConfig): | ||
| 187 | + raise ValueError( | ||
| 188 | + f"weight_config must be {HiF8QuantizeConfig.__name__}, got {type(config.weight_config).__name__}." | ||
| 189 | + ) | ||
| 190 | + | ||
| 191 | + return nn.Parameter( | ||
| 192 | + data=HiF8TrainingWeightWrapperTensor( | ||
| 193 | + param.data, | ||
| 194 | + activation_config=config.activation_config, | ||
| 195 | + weight_config=config.weight_config, | ||
| 196 | + ), | ||
| 197 | + requires_grad=param.requires_grad, | ||
| 198 | + ) | ||
| @@ -502,7 +502,7 @@ _MODEL_TYPE_BY_MODEL_NAME: dict[str, _ModelType] = { | |||
| 502 | } | 502 | } |
| 503 | 503 | ||
| 504 | 504 | ||
| 505 | -_SUPPORTED_RECIPES = ("all_mxfp8", "mix", "all_block_fp8") | 505 | +_SUPPORTED_RECIPES = ("all_mxfp8", "all_hif8", "mix", "all_block_fp8") |
| 506 | 506 | ||
| 507 | 507 | ||
| 508 | def _model_type_for_spec(model_spec: ModelSpec) -> _ModelType: | 508 | def _model_type_for_spec(model_spec: ModelSpec) -> _ModelType: |
| @@ -656,6 +656,155 @@ def _block_fp8_param_swap( | |||
| 656 | ) | 656 | ) |
| 657 | 657 | ||
| 658 | 658 | ||
| 659 | +# extension.quantization.enable-hif8-save-quant-codes ops added to the | ||
| 660 | +# selective-AC save list. | ||
| 661 | +_QUANT_CODE_SAVE_OPS = ( | ||
| 662 | + "npu.npu_quantize.default", | ||
| 663 | + "npu.npu_dynamic_quant.default", | ||
| 664 | + "npu.npu_grouped_matmul.default", | ||
| 665 | + "npu.npu_quant_matmul.default", | ||
| 666 | +) | ||
| 667 | + | ||
| 668 | +_AC_QUANT_CODES_PATCHED = [False] | ||
| 669 | + | ||
| 670 | + | ||
| 671 | +def _save_quant_codes_under_selective_ac(enable: bool) -> None: | ||
| 672 | + """extension.quantization.enable-hif8-save-quant-codes: keep the quantized | ||
| 673 | + matmul's operands and result across the selective-AC boundary instead of | ||
| 674 | + re-deriving them in the backward. | ||
| 675 | + | ||
| 676 | + Must be called at model-setup time, before parallelization wraps the | ||
| 677 | + blocks: torchtitan reads ``_get_default_save_ops`` when it installs | ||
| 678 | + activation checkpointing. | ||
| 679 | + """ | ||
| 680 | + if not enable or _AC_QUANT_CODES_PATCHED[0]: | ||
| 681 | + return | ||
| 682 | + try: | ||
| 683 | + from torchtitan.distributed import activation_checkpoint as ac | ||
| 684 | + except ImportError: | ||
| 685 | + return | ||
| 686 | + _AC_QUANT_CODES_PATCHED[0] = True | ||
| 687 | + orig = ac._get_default_save_ops | ||
| 688 | + | ||
| 689 | + def _get_default_save_ops(): | ||
| 690 | + ops = orig() | ||
| 691 | + added, missing = [], [] | ||
| 692 | + for path in _QUANT_CODE_SAVE_OPS: | ||
| 693 | + obj = torch.ops | ||
| 694 | + try: | ||
| 695 | + for part in path.split("."): | ||
| 696 | + obj = getattr(obj, part) | ||
| 697 | + except (AttributeError, RuntimeError): | ||
| 698 | + missing.append(path) | ||
| 699 | + continue | ||
| 700 | + ops.add(obj) | ||
| 701 | + added.append(path) | ||
| 702 | + logger.info( | ||
| 703 | + "enable_hif8_save_quant_codes: added %s to the selective-AC save list%s", | ||
| 704 | + ", ".join(added) or "nothing", | ||
| 705 | + f" (not registered: {', '.join(missing)})" if missing else "", | ||
| 706 | + ) | ||
| 707 | + return ops | ||
| 708 | + | ||
| 709 | + ac._get_default_save_ops = _get_default_save_ops | ||
| 710 | + | ||
| 711 | + | ||
| 712 | +_AC_BLOCK_OPS_PATCHED = [False] | ||
| 713 | + | ||
| 714 | +# extension.quantization.save-block-ops-level levels -> the transformer-block ops | ||
| 715 | +# added to the selective-AC save list, grouped by the module they belong to | ||
| 716 | +# and ordered by critical-path ms per saved GiB (best first). | ||
| 717 | +_BLOCK_SAVE_OPS = ( | ||
| 718 | + # 1: attention | ||
| 719 | + (1, "cann_ops_transformer.sparse_flash_mla.default"), | ||
| 720 | + (1, "cann_ops_transformer.lightning_indexer.default"), | ||
| 721 | + # 2: mHC | ||
| 722 | + (2, "npu.npu_mhc_pre.default"), | ||
| 723 | + (2, "cann_ops_transformer.mhc_post.default"), | ||
| 724 | + (2, "npu.npu_mhc_sinkhorn.default"), | ||
| 725 | + # 3: MoE routing | ||
| 726 | + (3, "npu.npu_moe_token_permute.default"), | ||
| 727 | + (3, "torchtitan_npu.npu_moe_re_routing.default"), | ||
| 728 | + (3, "torchtitan_npu.npu_moe_token_unpermute.default"), | ||
| 729 | +) | ||
| 730 | + | ||
| 731 | + | ||
| 732 | +def _resolve_torch_op(path: str): | ||
| 733 | + """``torch.ops`` lookup by dotted path, or None if not registered yet.""" | ||
| 734 | + obj = torch.ops | ||
| 735 | + try: | ||
| 736 | + for part in path.split("."): | ||
| 737 | + obj = getattr(obj, part) | ||
| 738 | + except (AttributeError, RuntimeError): | ||
| 739 | + return None | ||
| 740 | + return obj | ||
| 741 | + | ||
| 742 | + | ||
| 743 | +def _save_block_ops_under_selective_ac(level: int) -> None: | ||
| 744 | + """extension.quantization.save-block-ops-level: keep the attention / mHC / | ||
| 745 | + MoE-routing results across the selective-AC boundary instead of | ||
| 746 | + re-deriving them in the backward. | ||
| 747 | + | ||
| 748 | + torchtitan's ``_get_default_save_ops()`` doesn't know about custom NPU | ||
| 749 | + ops, so the min-cut partitioner always recomputes them. ``_BLOCK_SAVE_OPS`` | ||
| 750 | + orders them best-first by profiled win, an upper bound rather than a | ||
| 751 | + guarantee -- a recomputed kernel off the critical path may already be | ||
| 752 | + overlapped. | ||
| 753 | + | ||
| 754 | + NOT bit-exact (forward and recompute don't compile to the same fused | ||
| 755 | + kernel), so this needs a loss A/B before being trusted. | ||
| 756 | + | ||
| 757 | + Resolution is deferred to call time (inside the returned closure, not | ||
| 758 | + at patch time) because some ops register only once model modules have | ||
| 759 | + imported ``cann_ops_transformer``. | ||
| 760 | + """ | ||
| 761 | + if level <= 0 or _AC_BLOCK_OPS_PATCHED[0]: | ||
| 762 | + return | ||
| 763 | + try: | ||
| 764 | + from torchtitan.distributed import activation_checkpoint as ac | ||
| 765 | + except ImportError: | ||
| 766 | + return | ||
| 767 | + wanted = tuple(path for lvl, path in _BLOCK_SAVE_OPS if lvl <= level) | ||
| 768 | + if not wanted: | ||
| 769 | + return | ||
| 770 | + _AC_BLOCK_OPS_PATCHED[0] = True | ||
| 771 | + orig = ac._get_default_save_ops | ||
| 772 | + | ||
| 773 | + def _get_default_save_ops(): | ||
| 774 | + ops = orig() | ||
| 775 | + added, missing = [], [] | ||
| 776 | + for path in wanted: | ||
| 777 | + op = _resolve_torch_op(path) | ||
| 778 | + if op is None: | ||
| 779 | + # Not registered in this build/config (e.g. the lightning | ||
| 780 | + # indexer is off for this model). A miss is a lost | ||
| 781 | + # optimization, never a correctness problem. | ||
| 782 | + missing.append(path) | ||
| 783 | + else: | ||
| 784 | + ops.add(op) | ||
| 785 | + added.append(path) | ||
| 786 | + logger.info( | ||
| 787 | + "save_block_ops_level=%d: added %s to the selective-AC save list%s", | ||
| 788 | + level, | ||
| 789 | + ", ".join(added) or "nothing", | ||
| 790 | + f" (not registered: {', '.join(missing)})" if missing else "", | ||
| 791 | + ) | ||
| 792 | + return ops | ||
| 793 | + | ||
| 794 | + ac._get_default_save_ops = _get_default_save_ops | ||
| 795 | + | ||
| 796 | + | ||
| 797 | +def _hif8_param_swap(save_quant_codes: bool) -> ParamSwapConfig: | ||
| 798 | + # Current/constant tensor scaling only: every quantize call recomputes | ||
| 799 | + # its scale via npu_dynamic_quant, no persisted per-parameter state. | ||
| 800 | + hif8_config = HiF8QuantizeConfig() | ||
| 801 | + _save_quant_codes_under_selective_ac(save_quant_codes) | ||
| 802 | + return ParamSwapConfig( | ||
| 803 | + weight_config=hif8_config, | ||
| 804 | + activation_config=hif8_config, | ||
| 805 | + ) | ||
| 806 | + | ||
| 807 | + | ||
| 659 | def _quantization_converter( | 808 | def _quantization_converter( |
| 660 | base_config: AOBaseConfig | None, | 809 | base_config: AOBaseConfig | None, |
| 661 | filter_fn: ConfigFilterFn | None = None, | 810 | filter_fn: ConfigFilterFn | None = None, |
| @@ -685,6 +834,7 @@ def _recipe_converters( | |||
| 685 | li_quantization: LIQuantization | None = None, | 834 | li_quantization: LIQuantization | None = None, |
| 686 | li_kernel_config: LightningIndexerKernelConfig | None = None, | 835 | li_kernel_config: LightningIndexerKernelConfig | None = None, |
| 687 | kv_norm_quantization: KVNormQuantizationConfig | None = None, | 836 | kv_norm_quantization: KVNormQuantizationConfig | None = None, |
| 837 | + enable_hif8_save_quant_codes: bool = False, | ||
| 688 | ) -> list[QuantizationConverter.Config]: | 838 | ) -> list[QuantizationConverter.Config]: |
| 689 | converters: list[QuantizationConverter.Config] | 839 | converters: list[QuantizationConverter.Config] |
| 690 | try: | 840 | try: |
| @@ -702,6 +852,15 @@ def _recipe_converters( | |||
| 702 | ) | 852 | ) |
| 703 | ] | 853 | ] |
| 704 | 854 | ||
| 855 | + elif recipe == "all_hif8": | ||
| 856 | + converters = [ | ||
| 857 | + _quantization_converter( | ||
| 858 | + _hif8_param_swap(enable_hif8_save_quant_codes), | ||
| 859 | + any_config_filter(dense_filter, filters["routed_expert"]), | ||
| 860 | + model_compile_enabled=model_compile_enabled, | ||
| 861 | + ) | ||
| 862 | + ] | ||
| 863 | + | ||
| 705 | else: | 864 | else: |
| 706 | routed_config = _block_fp8_param_swap( | 865 | routed_config = _block_fp8_param_swap( |
| 707 | enable_mxfp4_qat=enable_mxfp4_qat, | 866 | enable_mxfp4_qat=enable_mxfp4_qat, |
| @@ -827,6 +986,11 @@ def apply_quantization_converter( | |||
| 827 | 986 | ||
| 828 | if model_spec is None: | 987 | if model_spec is None: |
| 829 | raise ValueError("TorchAO-NPU quantization requires model_spec to be configured") | 988 | raise ValueError("TorchAO-NPU quantization requires model_spec to be configured") |
| 989 | + # Recipe-independent, so it is installed here rather than in | ||
| 990 | + # _hif8_param_swap: these are block ops, not quantized ops, and MXFP8 wants | ||
| 991 | + # them saved just as much as HiF8 does. Off by default -- at level 0 | ||
| 992 | + # nothing is patched and the partition is the one we ship today. | ||
| 993 | + _save_block_ops_under_selective_ac(quantization_config.save_block_ops_level) | ||
| 830 | if not quantization_config.enable_quantized_training: | 994 | if not quantization_config.enable_quantized_training: |
| 831 | return model_spec | 995 | return model_spec |
| 832 | quantization_config.validate() | 996 | quantization_config.validate() |
| @@ -848,6 +1012,7 @@ def apply_quantization_converter( | |||
| 848 | li_quantization=quantization_config.li_quantization, | 1012 | li_quantization=quantization_config.li_quantization, |
| 849 | li_kernel_config=li_kernel_config, | 1013 | li_kernel_config=li_kernel_config, |
| 850 | kv_norm_quantization=quantization_config.kv_norm_quantization, | 1014 | kv_norm_quantization=quantization_config.kv_norm_quantization, |
| 1015 | + enable_hif8_save_quant_codes=quantization_config.enable_hif8_save_quant_codes, | ||
| 851 | ) | 1016 | ) |
| 852 | validate_converter_order(converters) | 1017 | validate_converter_order(converters) |
| 853 | 1018 | ||
| @@ -14,7 +14,7 @@ from torchtitan.components.optimizer import OptimizersContainer, ParamGroupConfi | |||
| 14 | from torchtitan.config import TrainingConfig as _BaseTrainingConfig | 14 | 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", "all_hif8", "mix", "all_block_fp8"] |
| 18 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] | 18 | LIQuantization = Literal["mxfp4", "mxfp8", "fp8", "hif8"] |
| 19 | KVNormQuantization = Literal["mxfp8"] | 19 | KVNormQuantization = Literal["mxfp8"] |
| 20 | 20 | ||
| @@ -155,6 +155,13 @@ class QuantizationExtensionConfig: | |||
| 155 | dst_type_max: float = 0.0 | 155 | dst_type_max: float = 0.0 |
| 156 | enable_fsdp_prequantize: bool = False | 156 | enable_fsdp_prequantize: bool = False |
| 157 | kv_norm_quantization: KVNormQuantizationConfig = field(default_factory=KVNormQuantizationConfig) | 157 | kv_norm_quantization: KVNormQuantizationConfig = field(default_factory=KVNormQuantizationConfig) |
| 158 | + enable_hif8_save_quant_codes: bool = False | ||
| 159 | + """Keep HiF8's quantized operands and result across the | ||
| 160 | + selective-AC boundary instead of re-deriving them in the backward. Off | ||
| 161 | + by default (bit-identical to not patching the save list at all).""" | ||
| 162 | + save_block_ops_level: int = 0 | ||
| 163 | + """Add attention/mHC/MoE-routing NPU ops to the selective-AC MUST_SAVE | ||
| 164 | + list (1-3, cumulative; recipe-independent). Off (0) by default.""" | ||
| 158 | 165 | ||
| 159 | def validate(self) -> None: | 166 | def validate(self) -> None: |
| 160 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): | 167 | if self.li_quantization not in (None, "mxfp4", "mxfp8", "fp8", "hif8"): |
npu_dynamic_quant应该仅支持fp16、bf16,对于fp32其他格式需要先转化成bf16