Merged
[feat] Support HiFloat8 current-tensor scaling training with torchao #551
[feat] Support HiFloat8 current-tensor scaling training with torchao #551
Merged
nancycyzlAdd on Aug 12
Total: 14 files changed+1488-25
@@ -29,6 +29,7 @@ SIG 例会:[sig-framework-adapter](https://meeting.osinfra.cn/cann?sig=sig-fra
29# 最新消息29# 最新消息
30 30 
31---31---
32+- [Aug. 2026]: 🚀 **支持 HiFloat8(HiF8)低精度训练**:新增 per-tensor 动态量化的 HiF8 训练后端,覆盖 Linear 与 MoE 专家层,在 Ascend 950 NPU 上进一步提升 DeepSeek-V4 等大模型的训练吞吐。
panchao-gitcode

精度对比跑的步数有点少,还是跑100step,然后通过training-log-visualization这个skill画下loss对比曲线

likedislike
nancycyzl
nancycyzl
Aug 13 Comments:
likedislike
32- [May. 2026]: 🚀 **[DeepSeek-V4-Pro 模型续训练支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图。33- [May. 2026]: 🚀 **[DeepSeek-V4-Pro 模型续训练支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图。
33- [May. 2026]: ⚠️ **配置系统重构**:master 分支对齐 torchtitan main 的 `config_registry.py` / `ConfigManager` 机制,模型训练使用 `--module` 和 `--config` 启动,不再通过 `--job.config_file` 加载 TOML。34- [May. 2026]: ⚠️ **配置系统重构**:master 分支对齐 torchtitan main 的 `config_registry.py` / `ConfigManager` 机制,模型训练使用 `--module` 和 `--config` 启动,不再通过 `--job.config_file` 加载 TOML。
34- [Apr. 2026]: 🚀 **[DeepSeek-V4-Flash 续训练 0day 支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图,开箱即优。35- [Apr. 2026]: 🚀 **[DeepSeek-V4-Flash 续训练 0day 支持](https://gitcode.com/cann/cann-recipes-train/blob/master/llm_pretrain/deepseekv4/README.md)**:基于纯FSDP + 大EP极简切分,使能AutoFuse特性,达成训练入图,开箱即优。
@@ -104,11 +105,16 @@ pip install -e .
104 </tr>105 </tr>
105 <!-- 训练精度 -->106 <!-- 训练精度 -->
106 <tr>107 <tr>
107- <td rowspan="2">训练精度</td>108+ <td rowspan="3">训练精度</td>
108 <td><a href="https://gitcode.com/cann/torchtitan-npu/blob/master/docs/feature_guides/low_precision_training.md">MxFP8 量化</a></td>109 <td><a href="https://gitcode.com/cann/torchtitan-npu/blob/master/docs/feature_guides/low_precision_training.md">MxFP8 量化</a></td>
109 <td>✅</td>110 <td>✅</td>
110 <td>✅ (Ascend 950)</td>111 <td>✅ (Ascend 950)</td>
111 </tr>112 </tr>
113+ <tr>
114+ <td><a href="https://gitcode.com/cann/torchtitan-npu/blob/master/docs/feature_guides/low_precision_training.md">HiFloat8 量化</a></td>
115+ <td>❌</td>
116+ <td>✅ (Ascend 950)</td>
117+ </tr>
112 <tr>118 <tr>
113 <td><a href="https://gitcode.com/cann/torchtitan-npu/blob/master/docs/feature_guides/fsdp_parameter_precision.md">FSDP 参数级精度保留</a></td>119 <td><a href="https://gitcode.com/cann/torchtitan-npu/blob/master/docs/feature_guides/fsdp_parameter_precision.md">FSDP 参数级精度保留</a></td>
114 <td>❌</td>120 <td>❌</td>
@@ -1,12 +1,14 @@
1-# 低精度训练特性(MXFP8)1+# 低精度训练特性(MXFP8 / HiF8)
2 2 
3在大规模语言模型的分布式训练中,矩阵乘法运算(GEMM)占据了绝大部分计算开销。传统的 BF16/FP16 混合精度训练虽然已大幅降低了显存占用,但在超大规模模型(如 DeepSeek-V3 671B)上仍面临计算效率瓶颈。低精度训练通过将线性层和 MoE 专家层的矩阵乘法降至 8-bit 浮点精度执行,在保持训练收敛性的前提下,显著提升计算吞吐并降低显存消耗。3在大规模语言模型的分布式训练中,矩阵乘法运算(GEMM)占据了绝大部分计算开销。传统的 BF16/FP16 混合精度训练虽然已大幅降低了显存占用,但在超大规模模型(如 DeepSeek-V3 671B)上仍面临计算效率瓶颈。低精度训练通过将线性层和 MoE 专家层的矩阵乘法降至 8-bit 浮点精度执行,在保持训练收敛性的前提下,显著提升计算吞吐并降低显存消耗。
4 4 
5本特性基于 [torchao](https://github.com/pytorch/ao) 的 MXFP8 训练框架,通过 NPU 侧的 monkey-patch 将 torchao 的 MXFP8 计算路径重定向至 `torch_npu` 原生算子,覆盖普通线性层(nn.Linear)和 MoE 专家层(Grouped MM)两大场景。5本特性基于 [torchao](https://github.com/pytorch/ao) 的 MXFP8 训练框架,通过 NPU 侧的 monkey-patch 将 torchao 的 MXFP8 计算路径重定向至 `torch_npu` 原生算子,覆盖普通线性层(nn.Linear)和 MoE 专家层(Grouped MM)两大场景。
6 6 
7+除 MXFP8 外,torchtitan-npu 还通过实验性插件子包 `torchtitan_npu/experiments/ao_npu/torchao_npu` 提供 HiF8(`torch_npu.hifloat8`)作为另一种 8-bit 精度训练路径,同样覆盖上述两大场景。与 MXFP8 的 per-block(e8m0 microscaling)量化不同,HiF8 是**纯 per-tensor** 动态量化:整个激活/权重张量只计算一个标量 scale。
8+ 
7## 硬件要求9## 硬件要求
8 10 
9-低精度训练特性仅支持 **Ascend 950 及更高架构**的 NPU 设备。系统在初始化时会通过 `torch_npu.npu.get_device_name()` 进行硬件检测,不满足要求时将抛出异常。11+低精度训练特性仅支持 **Ascend 950 及更高架构**的 NPU 设备。MXFP8 在初始化时会通过 `torch_npu.npu.get_device_name()` 进行硬件检测,不满足要求时将抛出异常;HiF8 当前未在 Python 层做显式硬件能力校验,不支持的硬件上会在实际调用 `torch_npu.npu_dynamic_quant`/`npu_quant_matmul` 等算子时由算子层报错。
10 12 
11## 实现原理13## 实现原理
12 14 
@@ -20,6 +22,17 @@
20| `torchtitan_npu/experiments/ao_npu/torchao_npu/patches/mx_linear.py` | 替换 torchao 的 `_to_mxfp8_then_scaled_mm`,将线性层 MXFP8 计算重定向至 NPU 算子 |22| `torchtitan_npu/experiments/ao_npu/torchao_npu/patches/mx_linear.py` | 替换 torchao 的 `_to_mxfp8_then_scaled_mm`,将线性层 MXFP8 计算重定向至 NPU 算子 |
21| `torchtitan_npu/experiments/ao_npu/torchao_npu/patches/mxfp8_grouped_mm.py` | 替换 torchao 的 `_to_mxfp8_then_scaled_grouped_mm`,将 MoE 分组矩阵乘法重定向至 NPU 算子 |23| `torchtitan_npu/experiments/ao_npu/torchao_npu/patches/mxfp8_grouped_mm.py` | 替换 torchao 的 `_to_mxfp8_then_scaled_grouped_mm`,将 MoE 分组矩阵乘法重定向至 NPU 算子 |
22 24 
25+### 整体架构(HiF8)
26+ 
27+HiF8 不复用上述 `MXFP8Converter` + patch 架构,而是接入 `torchao_npu` 已有的 **ParamSwap 参数级拦截框架**:`NpuQuantizeConverter`(把 `ParamSwapConfig` 转交给 `torchao.quantize_()`)→ `ParamSwapConfig`(prepare/convert 两步生命周期,wrap/unwrap `nn.Parameter`)→ `HiF8TrainingWeightWrapperTensor`(`__torch_function__` 拦截计算类 op)。相关代码主要分布在:
28+ 
29+| 文件路径 | 作用 |
30+| --- | --- |
31+| `torchtitan_npu/experiments/ao_npu/torchao_npu/quantization/quant_configs.py` | `HiF8QuantizeConfig`:per-tensor 量化配置,唯一字段 `elem_dtype` 锁定为 `torch_npu.hifloat8` |
32+| `torchtitan_npu/experiments/ao_npu/torchao_npu/wrapper_tensors/hif8_wrapper_tensor.py` | `HiF8TrainingWeightWrapperTensor`:拦截 `mm`/`matmul`/`grouped_mm`/`linear`/`addmm`,换成 HiF8 量化 kernel |
33+| `torchtitan_npu/experiments/ao_npu/torchao_npu/ops/hif8_ops.py` | `to_hif8_then_mm`/`to_hif8_then_grouped_mm`:per-tensor HiF8 量化的 Linear/Grouped MM 正反向实现 |
34+| `torchtitan_npu/experiments/ao_npu/torchao_npu/interfaces/torchtitan.py` | `NpuQuantizeConverter`:把 `ParamSwapConfig` 接入 torchtitan 的 `ModelConvertersContainer` |
35+ 
23### 线性层低精度36### 线性层低精度
24 37 
25`MXFP8Converter` 在转换阶段,通过 torchao 的 `quantize_` API 对模型中指定 FQN 的 `nn.Linear` 模块的权重进行包装(`MXFP8TrainingWeightWrapperTensor`)。在前向传播时,权重包装器的 `__torch_function__` 拦截矩阵乘法调用,进入 `_to_mxfp8_then_scaled_mm` 函数。38`MXFP8Converter` 在转换阶段,通过 torchao 的 `quantize_` API 对模型中指定 FQN 的 `nn.Linear` 模块的权重进行包装(`MXFP8TrainingWeightWrapperTensor`)。在前向传播时,权重包装器的 `__torch_function__` 拦截矩阵乘法调用,进入 `_to_mxfp8_then_scaled_mm` 函数。
@@ -29,6 +42,13 @@ NPU 侧通过 patch `torchao.prototype.mx_formats.mx_linear._to_mxfp8_then_scale
29- **前向传播**:使用 `torch_npu.npu_dynamic_mx_quant` 对激活和权重分别进行 per-block 量化(block size=32,沿 axis=-1 方向),每 32 个元素共享一个 e8m0 scale,再通过 `torch_npu.npu_quant_matmul` 执行 FP8 矩阵乘法,输出恢复为原始精度(BF16)。42- **前向传播**:使用 `torch_npu.npu_dynamic_mx_quant` 对激活和权重分别进行 per-block 量化(block size=32,沿 axis=-1 方向),每 32 个元素共享一个 e8m0 scale,再通过 `torch_npu.npu_quant_matmul` 执行 FP8 矩阵乘法,输出恢复为原始精度(BF16)。
30- **反向传播**:输入梯度(dx)和权重梯度(dw)的计算同样在 FP8 精度下完成,其中权重梯度使用 `npu_dynamic_mx_quant` 对权重沿 axis=-2 方向进行 per-block 量化。43- **反向传播**:输入梯度(dx)和权重梯度(dw)的计算同样在 FP8 精度下完成,其中权重梯度使用 `npu_dynamic_mx_quant` 对权重沿 axis=-2 方向进行 per-block 量化。
31 44 
45+### 线性层低精度(HiF8)
46+ 
47+`HiF8TrainingWeightWrapperTensor.__torch_function__` 拦截 `torch.nn.functional.linear`/`torch.addmm`/`torch.mm`/`torch.matmul`,转调用 `to_hif8_then_mm`:
48+ 
49+- **前向传播**:对激活和权重分别用 `torch_npu.npu_dynamic_quant(quant_mode="pertensor")` 量化为 HiF8 + 一个标量 scale,再用 `torch_npu.npu_quant_matmul` 计算,输出恢复为原始 BF16 精度。
50+- **反向传播**:直接复用前向已量化的激活/权重及其 scale(转置对 per-tensor scale 无影响)计算输入梯度和权重梯度,只对新出现的梯度现场量化一次,不需要重新量化激活/权重。
51+ 
32### MoE 专家层低精度52### MoE 专家层低精度
33 53 
34对于 MoE(Mixture of Experts)架构中的专家层,torchao 通过 `_to_mxfp8_then_scaled_grouped_mm` 函数调度分组矩阵乘法。54对于 MoE(Mixture of Experts)架构中的专家层,torchao 通过 `_to_mxfp8_then_scaled_grouped_mm` 函数调度分组矩阵乘法。
@@ -40,9 +60,18 @@ NPU 侧通过 patch `torchao.prototype.moe_training.mxfp8_grouped_mm._to_mxfp8_t
40 60 
41> **注意**:MoE 低精度功能依赖 `npu_gmm` converter 提供的分组矩阵乘法基础实现,因此在 converters 配置中 `npu_gmm` 必须位于 `MXFP8Converter` 之前。61> **注意**:MoE 低精度功能依赖 `npu_gmm` converter 提供的分组矩阵乘法基础实现,因此在 converters 配置中 `npu_gmm` 必须位于 `MXFP8Converter` 之前。
42 62 
63+### MoE 专家层低精度(HiF8)
64+ 
65+拦截 `torch._grouped_mm`,转调用 `to_hif8_then_grouped_mm`:
66+ 
67+- **前向传播**:激活/权重整体各量化出一个标量 scale,再用 `torch_npu.npu_grouped_matmul` 计算;scale 通过 `.reshape(1).expand(...)` 广播成算子要求的按 token/按专家长度的向量。
68+- **反向传播**:输入梯度复用前向对激活的量化结果;权重梯度两个 scale 都按专家数广播(而非 token 数),且需要对转置后的权重重新做一次量化,未复用前向的量化结果。
69+ 
70+> **注意**:MoE 场景下 HiF8 是纯 per-tensor 量化:同一次 forward/backward 里所有本地专家、所有 token 共享同一个标量 scale;同样依赖 `npu_gmm` converter 提供的分组矩阵乘法基础实现,因此在 converters 配置中 `npu_gmm` 必须位于 `NpuQuantizeConverter` 之前。
71+ 
43## 配置选项72## 配置选项
44 73 
45-低精度训练通过 `ModelConvertersContainer.Config` 的 `converters` 列表启用,使用上游 `MXFP8Converter.Config` 进行配置。74+低精度训练通过 `ModelConvertersContainer.Config` 的 `converters` 列表启用。MXFP8 使用上游 `MXFP8Converter.Config` 进行配置;HiF8 使用 `NpuQuantizeConverter.Config` 包一层 `ParamSwapConfig` 进行配置,不使用 `MXFP8Converter.Config`。
46 75 
47### MXFP8Converter 配置76### MXFP8Converter 配置
48 77 
@@ -51,12 +80,24 @@ NPU 侧通过 patch `torchao.prototype.moe_training.mxfp8_grouped_mm._to_mxfp8_t
51| `recipe_name` | str | `"mxfp8_rceil"` | 量化 recipe 名称。当前唯一可选值:`"mxfp8_rceil"`(MXFP8 动态量化,scale 计算采用 RCEIL 舍入模式)。 |80| `recipe_name` | str | `"mxfp8_rceil"` | 量化 recipe 名称。当前唯一可选值:`"mxfp8_rceil"`(MXFP8 动态量化,scale 计算采用 RCEIL 舍入模式)。 |
52| `fqns` | list[str] | [] | 需要启用 MXFP8 量化的模块全限定名(FQN)列表。匹配规则为子字符串包含,例如 `"moe.experts"` 将匹配所有 FQN 中包含该字符串的模块。留空表示不对任何模块启用 MXFP8。 |81| `fqns` | list[str] | [] | 需要启用 MXFP8 量化的模块全限定名(FQN)列表。匹配规则为子字符串包含,例如 `"moe.experts"` 将匹配所有 FQN 中包含该字符串的模块。留空表示不对任何模块启用 MXFP8。 |
53 82 
83+### HiF8 配置
84+ 
85+| 配置项 | 类型 | 默认值 | 说明 |
86+| --- | --- | --- | --- |
87+| `HiF8QuantizeConfig.elem_dtype` | `torch.dtype` | `torch_npu.hifloat8` | 唯一字段,`__post_init__` 强制锁定为该值,实际不可配置,仅为与 `MXQuantizeConfig` 等其他 config 接口保持一致 |
88+| `NpuQuantizeConverter.Config.filter_fn` | `(nn.Module, str) -> bool` | `_is_linear` | 模块级过滤器,决定哪些模块参与转换 |
89+| `ParamSwapConfig.params_filter_fn` | `(nn.Parameter, str) -> bool` | `_is_parameter` | 参数级过滤器,决定命中模块下的哪些参数被 wrap |
90+ 
91+`ParamSwapConfig` 的 `weight_config`/`activation_config` 必须都传且均为 `HiF8QuantizeConfig`,否则 `HiF8TrainingWeightWrapperTensor.__init__` 会抛出 `ValueError`。
92+ 
54### 环境变量配置93### 环境变量配置
55 94 
56| 环境变量 | 默认值 | 说明 |95| 环境变量 | 默认值 | 说明 |
57| --- | --- | --- |96| --- | --- | --- |
58| `MXFP8_DUAL_AXIS_FORWARD` | `1`(启用) | 控制 MXFP8 线性层和 MoE 专家层是否启用 forward dual-axis 量化(forward 阶段同时生成 backward 的量化数据),默认启用。设置为 `0` 或 `false` 可关闭,forward 回退到 single-axis 量化行为。无论 `MXFP8_DUAL_AXIS_FORWARD` 是否启用,Linear的 backward grad始终使用 dual-axis 量化。 |97| `MXFP8_DUAL_AXIS_FORWARD` | `1`(启用) | 控制 MXFP8 线性层和 MoE 专家层是否启用 forward dual-axis 量化(forward 阶段同时生成 backward 的量化数据),默认启用。设置为 `0` 或 `false` 可关闭,forward 回退到 single-axis 量化行为。无论 `MXFP8_DUAL_AXIS_FORWARD` 是否启用,Linear的 backward grad始终使用 dual-axis 量化。 |
59 98 
99+> HiF8 没有 dual-axis 量化机制(不区分 block/axis),不受 `MXFP8_DUAL_AXIS_FORWARD` 影响,也没有对应的环境变量。
100+ 
60### 配置示例101### 配置示例
61 102 
62在模型的 `config_registry.py` 中配置 `model_converters` 并添加 `MXFP8Converter`:103在模型的 `config_registry.py` 中配置 `model_converters` 并添加 `MXFP8Converter`:
@@ -98,16 +139,66 @@ model_converters = ModelConvertersContainer.Config(
98)139)
99```140```
100 141 
142+**示例:对指定线性层和 MoE 专家层启用 HiF8 低精度训练**
143+ 
144+```python
145+from torchtitan.protocols.model_converter import ModelConvertersContainer
146+ 
147+from torchtitan_npu.converters import get_model_converter_config
148+from torchtitan_npu.experiments.ao_npu.torchao_npu.configs import ParamSwapConfig
149+from torchtitan_npu.experiments.ao_npu.torchao_npu.interfaces.torchtitan import (
150+ NpuQuantizeConverter,
151+ is_attention,
152+ is_routed_expert,
153+ is_shared_expert,
154+)
155+from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.filters import (
156+ any_filter,
157+ match_fqn_suffix,
158+)
159+from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs import HiF8QuantizeConfig
160+ 
161+model_converters = ModelConvertersContainer.Config(
162+ converters=[
163+ # NPU 基础 converter(npu_gmm 必须在 NpuQuantizeConverter 之前)
164+ get_model_converter_config("npu_rms_norm"),
165+ get_model_converter_config("npu_moe_dispatch"),
166+ get_model_converter_config("npu_gmm"),
167+ get_model_converter_config("npu_rope"),
168+ get_model_converter_config("npu_smla"),
169+ get_model_converter_config("npu_mhc_pre"),
170+ # HiF8 低精度训练
171+ NpuQuantizeConverter.Config(
172+ base_config=ParamSwapConfig(
173+ weight_config=HiF8QuantizeConfig(),
174+ activation_config=HiF8QuantizeConfig(),
175+ ),
176+ filter_fn=any_filter(
177+ # Attention 线性层 + 共享专家 + 路由专家
178+ is_attention,
179+ is_shared_expert,
180+ is_routed_expert,
181+ match_fqn_suffix(".e_proj", ".h_proj"),
182+ ),
183+ ),
184+ ],
185+)
186+```
187+ 
188+参照 `torchtitan_npu/experiments/ao_npu/benchmarks/e2e/dsv4_flash_single_node/config_registry.py` 中的 `debug_deepseek_v4_flash_single_node_hif8_qat()`。
189+ 
101## 验证清单190## 验证清单
102 191 
1031. **确认 converter 生效**:启动日志中应出现以下关键字:1921. **确认 converter 生效**:启动日志中应出现以下关键字:
104 - `MXFP8 MoE training enabled`(来自上游 `MXFP8Converter.__init__`)193 - `MXFP8 MoE training enabled`(来自上游 `MXFP8Converter.__init__`)
105 - `Converted layers matching FQNS ... to use dynamic mxfp8_rceil quantization for grouped_mm and linear ops`(来自上游 `MXFP8Converter.convert`)194 - `Converted layers matching FQNS ... to use dynamic mxfp8_rceil quantization for grouped_mm and linear ops`(来自上游 `MXFP8Converter.convert`)
106-2. **确认模块替换数量**:日志中转换信息应与配置的 `fqns` 列表匹配。195+ - HiF8:`Parameter quantize active with base_config=ParamSwapConfig`(来自 `NpuQuantizeConverter.__init__`)及 `Applied parameter quantize wrapping (prepare step)`(来自 `NpuQuantizeConverter.convert`)
196+2. **确认模块替换数量**:MXFP8 日志中的转换信息应与配置的 `fqns` 列表匹配;HiF8 可在 `filter_fn`/`params_filter_fn` 命中范围内抽查若干参数,确认其 `.data` 类型为 `HiF8TrainingWeightWrapperTensor` 而非普通 tensor。
1073. **常见未生效场景排查**:1973. **常见未生效场景排查**:
108- - `converters` 顺序错误:`npu_gmm` 未放在 `MXFP8Converter` 之前,导致 MoE 专家层替换失败198+ - `converters` 顺序错误:`npu_gmm` 未放在 `MXFP8Converter`/`NpuQuantizeConverter` 之前,导致 MoE 专家层替换失败
109- - `fqns` 匹配不到目标模块:检查模块的 FQN 是否包含配置的子字符串(注意大小写敏感)199+ - `fqns`(MXFP8)/`filter_fn`(HiF8)匹配不到目标模块:检查模块的 FQN 是否符合配置的匹配条件(注意大小写敏感)
110- - 硬件不满足要求:日志报错 `MXFP8 is only supported on Ascend950 or higher architecture`200+ - 硬件不满足要求:MXFP8 日志报错 `MXFP8 is only supported on Ascend950 or higher architecture`;HiF8 未做提前校验,报错会发生在实际调用 NPU 算子时
201+ - HiF8 特有:`weight_config`/`activation_config` 未同时提供、或类型不一致,`HiF8TrainingWeightWrapperTensor` 构造时会抛出 `ValueError`
111 202 
112## CLI 启动方式203## CLI 启动方式
113 204 
@@ -5,11 +5,17 @@
5 5 
6"""E2E benchmark config for DSV4 Flash single-node QAT.6"""E2E benchmark config for DSV4 Flash single-node QAT.
7 7 
8-The launch script (``debug_deepseek_v4_single_node_qat.sh`` in this folder)8+The launch scripts in this folder (``debug_deepseek_v4_single_node_qat.sh``,
xuyujun
xuyujunxuyujunAug 14

run_train_A5_hif8 脚本没删啊?

likedislike
nancycyzl
nancycyzl
Aug 14 Comments:
likedislike
9-cds into this directory so the flat module name ``config_registry`` is9+``debug_deepseek_v4_single_node_qat_hif8.sh``) cd into this directory so the
10-importable as a top-level module by torchrun workers. Discovered by upstream10+flat module name ``config_registry`` is importable as a top-level module by
11-``ConfigManager`` via ``--module config_registry`` and11+torchrun workers. Discovered by upstream ``ConfigManager`` via
12-``--config debug_deepseek_v4_flash_single_node_qat``.12+``--module config_registry`` and one of:
13+- ``--config debug_deepseek_v4_flash_single_node_qat`` (MX for
14+ attention/shared-expert, Block FP8 for routed experts)
15+- ``--config debug_deepseek_v4_flash_single_node_mxfp8_qat`` (MX
16+ everywhere)
17+- ``--config debug_deepseek_v4_flash_single_node_hif8_qat`` (HiF8
18+ everywhere)
13 19 
14Note: ``torchao_npu`` is not a standalone package — it's a subpackage of20Note: ``torchao_npu`` is not a standalone package — it's a subpackage of
15``torchtitan_npu.experiments.ao_npu``, so all imports must use the full path21``torchtitan_npu.experiments.ao_npu``, so all imports must use the full path
@@ -19,6 +25,7 @@ Note: ``torchao_npu`` is not a standalone package — it's a subpackage of
19from dataclasses import replace25from dataclasses import replace
20 26 
21import torch27import torch
28+from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase
22from torchtitan.protocols.model_converter import ModelConvertersContainer29from torchtitan.protocols.model_converter import ModelConvertersContainer
23 30 
24from torchtitan_npu.config.configs import TrainerConfig31from torchtitan_npu.config.configs import TrainerConfig
@@ -35,6 +42,7 @@ from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.filters import (
35)42)
36from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs import (43from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs import (
37 BlockQuantizeConfig,44 BlockQuantizeConfig,
45+ HiF8QuantizeConfig,
38 MXQuantizeConfig,46 MXQuantizeConfig,
39)47)
40from torchtitan_npu.models.deepseek_v4.config_registry import (48from torchtitan_npu.models.deepseek_v4.config_registry import (
@@ -71,3 +79,63 @@ def debug_deepseek_v4_flash_single_node_qat() -> TrainerConfig:
71 ]79 ]
72 ),80 ),
73 )81 )
82+ 
83+ 
84+def _debug_deepseek_v4_flash_single_node_uniform_qat(
85+ quant_config_cls: type[FakeQuantizeConfigBase],
86+) -> TrainerConfig:
87+ """Shared body for the all-uniform-backend QAT configs (MXFP8, HiF8).
88+ 
89+ Both apply a single ``quant_config_cls`` to every target FQN (attention,
90+ shared experts, ``e_proj``/``h_proj``, and routed experts alike) via one
91+ ``NpuQuantizeConverter.Config`` -- differing only in the quantize config
92+ class.
93+ """
94+ base = debug_deepseek_v4_flash_single_node()
95+ return replace(
96+ base,
97+ model_converters=ModelConvertersContainer.Config(
98+ converters=base.model_converters.converters # noqa: RUF005
99+ + [
100+ NpuQuantizeConverter.Config(
101+ base_config=ParamSwapConfig(
102+ weight_config=quant_config_cls(),
103+ activation_config=quant_config_cls(),
104+ ),
105+ filter_fn=any_filter(
106+ is_attention,
107+ is_shared_expert,
108+ is_routed_expert,
109+ match_fqn_suffix(".e_proj", ".h_proj"),
110+ ),
111+ ),
112+ ]
113+ ),
114+ )
115+ 
116+ 
117+def debug_deepseek_v4_flash_single_node_mxfp8_qat() -> TrainerConfig:
118+ """All-MXFP8 counterpart of :func:`debug_deepseek_v4_flash_single_node_qat`.
119+ 
120+ Unlike ``debug_deepseek_v4_flash_single_node_qat``, which splits MX
121+ (attention/shared-expert) from Block FP8 (routed experts), this uses a
122+ single ``MXQuantizeConfig`` for every target FQN -- structurally
123+ identical to :func:`debug_deepseek_v4_flash_single_node_hif8_qat`, just
124+ with ``MXQuantizeConfig`` in place of ``HiF8QuantizeConfig``, so the two
125+ are directly comparable (same ParamSwap plumbing, only the backend
126+ differs).
127+ """
128+ return _debug_deepseek_v4_flash_single_node_uniform_qat(MXQuantizeConfig)
129+ 
130+ 
131+def debug_deepseek_v4_flash_single_node_hif8_qat() -> TrainerConfig:
132+ """HiF8 counterpart of :func:`debug_deepseek_v4_flash_single_node_qat`.
133+ 
134+ Unlike the MX/Block FP8 split above, HiF8 is a single per-tensor backend
135+ with no block-size/axis distinction, so one ``NpuQuantizeConverter.Config``
136+ covers attention, shared experts, ``e_proj``/``h_proj``, and routed
137+ experts alike -- mirroring the unified FQN target list the core
138+ ``HiF8Converter`` (``torchtitan_npu/converters/hif8.py`` on the
139+ ``dsv4-hif8`` branch) used for the same model.
140+ """
141+ return _debug_deepseek_v4_flash_single_node_uniform_qat(HiF8QuantizeConfig)
@@ -0,0 +1,134 @@
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+set -euo pipefail
8+ 
9+# E2E perf benchmark for DSV4 Flash single-node HiF8 QAT. See
10+# ./config_registry.py (debug_deepseek_v4_flash_single_node_hif8_qat) for the
11+# quantization rules.
12+#
13+# Override priority (low to high): env vars below < user CLI args.
14+# NGPU - forwarded to scripts/run_train.sh → torchrun --nproc_per_node (default 8)
15+# DATASET - torchtitan dataset registry key (default c4_test)
16+# DATASET_PATH - absolute path to the dataset folder (default ${REPO_ROOT}/tests/assets/c4_test)
17+# HF_ASSETS_PATH - tokenizer folder (default /DeepSeek-V4-Flash)
18+# OUTPUT_FOLDER - root for outputs (default ${SCRIPT_DIR}/outputs/<timestamp>)
19+# LOG_FILE - tee'd log path (default ${OUTPUT_FOLDER}/terminal_<timestamp>.log)
20+# WEIGHTS_PATH - checkpoint folder to load; empty = random init (default empty)
21+# ENABLE_UPDATE - "true" keeps the config-registry default lr; anything else sets lr=0 (default false)
22+# ENABLE_DETERMINISM - "true" enables --debug.{seed 42,deterministic,no_deterministic_warn_only} (default false)
23+ 
24+SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
25+REPO_ROOT=$(cd "${SCRIPT_DIR}/../../../../../.." && pwd)
26+TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
27+ 
28+DATASET="${DATASET:-c4_test}"
29+DATASET_PATH="${DATASET_PATH:-${REPO_ROOT}/tests/assets/c4_test}"
30+HF_ASSETS_PATH="${HF_ASSETS_PATH:-/DeepSeek-V4-Flash}"
31+OUTPUT_FOLDER="${OUTPUT_FOLDER:-${SCRIPT_DIR}/outputs/${TIMESTAMP}}"
32+LOG_FILE="${LOG_FILE:-${OUTPUT_FOLDER}/terminal_${TIMESTAMP}.log}"
33+WEIGHTS_PATH="${WEIGHTS_PATH:-}"
34+ENABLE_UPDATE="${ENABLE_UPDATE:-false}"
35+ENABLE_DETERMINISM="${ENABLE_DETERMINISM:-false}"
36+ 
37+EXTRA_ARGS=(
38+ # Paths
39+ --hf_assets_path "${HF_ASSETS_PATH}"
40+ --dump_folder "${OUTPUT_FOLDER}"
41+ # Checkpoint / compile
42+ --checkpoint.no_enable
43+ --compile.enable
44+ # Training
45+ --training.local_batch_size 1
46+ --training.global_batch_size 64
47+ --training.steps 10
48+ --lr_scheduler.warmup_steps 5
49+ # Profiling
50+ --profiling.enable_profiling
51+ --profiling.no_enable_online_parse
52+ --profiling.profile_ranks 0
53+ --profiling.profile_step_start 8
54+ --profiling.profile_step_end 9
55+ --profiling.profile_record_shapes
56+ --profiling.no_profile_with_memory
57+ --profiling.no_profile_with_stack
58+)
59+ 
60+if [ -n "${WEIGHTS_PATH}" ]; then
61+ EXTRA_ARGS+=(
62+ --checkpoint.enable
63+ --checkpoint.initial_load_path "${WEIGHTS_PATH}"
64+ --checkpoint.load_only
65+ )
66+fi
67+ 
68+if [ "${ENABLE_UPDATE}" != "true" ]; then
69+ EXTRA_ARGS+=(--optimizer.lr 0)
70+fi
71+ 
72+if [ "${ENABLE_DETERMINISM}" = "true" ]; then
73+ EXTRA_ARGS+=(
74+ --debug.seed 42
75+ --debug.deterministic
76+ --debug.no_deterministic_warn_only
77+ )
78+fi
79+ 
80+# User overrides must precede the dataloader:config subcommand — tyro applies
81+# flags to the directly preceding subcommand.
82+EXTRA_ARGS+=("$@")
83+ 
84+EXTRA_ARGS+=(
85+ dataloader:config
86+ --dataloader.dataset "${DATASET}"
87+ --dataloader.dataset_path "${DATASET_PATH}"
88+)
89+ 
90+INVOKE_DIR="$(pwd)"
91+cd "${SCRIPT_DIR}"
92+mkdir -p "${OUTPUT_FOLDER}"
93+ 
94+# Resolve the final compile state for the echo block (last occurrence wins).
95+COMPILE_RESOLVED=true
96+for arg in "$@"; do
97+ case "$arg" in
98+ --compile.enable) COMPILE_RESOLVED=true ;;
99+ --compile.no_enable) COMPILE_RESOLVED=false ;;
100+ --compile.no-enable) COMPILE_RESOLVED=false ;;
101+ esac
102+done
103+ 
104+{
105+ echo "==== Benchmark env vars ===="
106+ echo "Script Invoked From = ${INVOKE_DIR}"
107+ echo "Training Launched From = $(pwd)"
108+ echo "Training Launched At = ${TIMESTAMP}"
109+ echo "NGPU = ${NGPU:-8}"
110+ echo "MODULE = ${MODULE:-config_registry}"
111+ echo "CONFIG = ${CONFIG:-debug_deepseek_v4_flash_single_node_hif8_qat}"
112+ echo "DATASET = ${DATASET}"
113+ echo "DATASET_PATH = ${DATASET_PATH}"
114+ echo "HF_ASSETS_PATH = ${HF_ASSETS_PATH}"
115+ echo "OUTPUT_FOLDER = ${OUTPUT_FOLDER}"
116+ echo "LOG_FILE = ${LOG_FILE}"
117+ echo "WEIGHTS_PATH = ${WEIGHTS_PATH:-<empty (random init)>}"
118+ echo "ENABLE_UPDATE = ${ENABLE_UPDATE}"
119+ echo "ENABLE_DETERMINISM = ${ENABLE_DETERMINISM}"
120+ echo "REPO_ROOT = ${REPO_ROOT}"
121+ echo "SCRIPT_DIR = ${SCRIPT_DIR}"
122+ echo "PYTHONPATH = ${REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}"
123+ echo "ASCEND_LAUNCH_BLOCKING = ${ASCEND_LAUNCH_BLOCKING:-<unset (async launches)>}"
124+ echo "Compile Enabled = ${COMPILE_RESOLVED}"
125+ echo "============================"
126+ 
127+ # PYTHONPATH prepends REPO_ROOT so workers import this repo's torchtitan_npu.
128+ PYTHONPATH="${REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" \
129+ NGPU="${NGPU:-8}" \
130+ MODULE="${MODULE:-config_registry}" \
131+ CONFIG="${CONFIG:-debug_deepseek_v4_flash_single_node_hif8_qat}" \
132+ bash "${REPO_ROOT}/scripts/run_train.sh" \
133+ "${EXTRA_ARGS[@]}"
134+} 2>&1 | tee "${LOG_FILE}"
@@ -0,0 +1,323 @@
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 to_hif8_then_mm / to_hif8_then_grouped_mm.
7+ 
8+SQNR thresholds here are conservative placeholders. They are set low enough
9+to catch gross correctness bugs (wrong operand order, wrong scale broadcast,
10+transposed gradient, etc.) without being tuned to an actual measured
11+baseline; tighten them once real NPU numbers are available.
12+"""
13+ 
14+import pytest
15+import torch
16+from torchao.float8.float8_utils import compute_error
17+ 
18+from torchtitan_npu.experiments.ao_npu.torchao_npu.ops.hif8_ops import (
19+ to_hif8_then_grouped_mm,
20+ to_hif8_then_mm,
21+)
22+from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs import HiF8QuantizeConfig
23+ 
24+_SQNR_THRESHOLD = 12.0
25+ 
26+ 
27+def _npu_available():
28+ return hasattr(torch, "npu") and torch.npu.is_available()
29+ 
30+ 
31+# =========================================================================
32+# to_hif8_then_mm
33+# =========================================================================
34+ 
35+ 
36+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
37+@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
38+@pytest.mark.parametrize(
39+ "M, K, N",
40+ [
41+ (128, 64, 256),
42+ (256, 128, 128),
43+ (64, 256, 64),
44+ ],
45+)
46+def test_forward_shape_and_dtype(M, K, N, dtype):
47+ """Output shape and dtype match input expectations.
48+ 
49+ B is passed as a transposed column-major tensor, simulating the common
50+ pattern where a linear weight is stored as [N, K] and ``.T`` is applied.
51+ """
52+ cfg = HiF8QuantizeConfig()
53+ A = torch.randn(M, K, device="npu", dtype=dtype)
54+ weight = torch.randn(N, K, device="npu", dtype=dtype)
55+ B = weight.T # [K, N] with column-major strides
56+ 
57+ out = to_hif8_then_mm(A, B, cfg, cfg)
58+ 
59+ assert out.shape == (M, N), f"Expected ({M}, {N}), got {out.shape}"
60+ assert out.dtype == A.dtype, f"Expected {A.dtype}, got {out.dtype}"
61+ assert out.device.type == "npu"
62+ 
63+ 
64+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
65+@pytest.mark.parametrize("M, K, N", [(128, 64, 256), (256, 128, 128)])
66+def test_sqnr_forward(M, K, N):
67+ """HiF8 forward output has acceptable SQNR vs high-precision matmul."""
68+ torch.manual_seed(42)
69+ cfg = HiF8QuantizeConfig()
70+ A = torch.randn(M, K, device="npu", dtype=torch.bfloat16)
71+ weight = torch.randn(N, K, device="npu", dtype=torch.bfloat16)
72+ B = weight.T
73+ 
74+ out_ref = A @ B
75+ out_hif8 = to_hif8_then_mm(A, B, cfg, cfg)
76+ 
77+ sqnr = compute_error(out_ref.float(), out_hif8.float()).item()
78+ assert sqnr > _SQNR_THRESHOLD, f"Forward SQNR too low: {sqnr:.2f} dB"
79+ 
80+ 
81+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
82+@pytest.mark.parametrize("M, K, N", [(128, 64, 256), (256, 128, 128)])
83+def test_sqnr_gradients(M, K, N):
84+ """HiF8 backward gradients have acceptable SQNR vs high-precision backward.
85+ 
86+ Checks both dA (grad wrt A) and dB (grad wrt B).
87+ """
88+ torch.manual_seed(42)
89+ cfg = HiF8QuantizeConfig()
90+ A = torch.randn(M, K, device="npu", dtype=torch.bfloat16, requires_grad=True)
91+ weight = torch.randn(N, K, device="npu", dtype=torch.bfloat16)
92+ B = weight.T
93+ 
94+ A_ref = A.clone().detach().requires_grad_(True)
95+ B_ref = B.clone().detach().requires_grad_(True)
96+ out_ref = A_ref @ B_ref
97+ out_ref.sum().backward()
98+ 
99+ A_hif8 = A.clone().detach().requires_grad_(True)
100+ B_hif8 = B.clone().detach().requires_grad_(True)
101+ out_hif8 = to_hif8_then_mm(A_hif8, B_hif8, cfg, cfg)
102+ out_hif8.sum().backward()
103+ 
104+ sqnr_dA = compute_error(A_ref.grad.float(), A_hif8.grad.float()).item()
105+ assert sqnr_dA > _SQNR_THRESHOLD, f"dA SQNR too low: {sqnr_dA:.2f} dB"
106+ 
107+ sqnr_dB = compute_error(B_ref.grad.float(), B_hif8.grad.float()).item()
108+ assert sqnr_dB > _SQNR_THRESHOLD, f"dB SQNR too low: {sqnr_dB:.2f} dB"
109+ 
110+ 
111+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
112+def test_non_2d_input():
113+ """3D A + 2D B produce correct output; 1D B raises."""
114+ cfg = HiF8QuantizeConfig()
115+ A_3d = torch.randn(4, 32, 64, device="npu", dtype=torch.bfloat16)
116+ weight = torch.randn(128, 64, device="npu", dtype=torch.bfloat16)
117+ B = weight.T
118+ 
119+ out = to_hif8_then_mm(A_3d, B, cfg, cfg)
120+ assert out.shape == (4, 32, 128)
121+ 
122+ A = torch.randn(32, 64, device="npu", dtype=torch.bfloat16)
123+ B_1d = torch.randn(64, device="npu", dtype=torch.bfloat16)
124+ 
125+ with pytest.raises((AssertionError, RuntimeError)):
126+ to_hif8_then_mm(A, B_1d, cfg, cfg)
127+ 
128+ 
129+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
130+def test_contracting_dim_mismatch():
131+ """Mismatched contracting dimensions raise an error."""
132+ cfg = HiF8QuantizeConfig()
133+ A = torch.randn(32, 64, device="npu", dtype=torch.bfloat16)
134+ weight = torch.randn(64, 256, device="npu", dtype=torch.bfloat16)
135+ B = weight.T
136+ 
137+ with pytest.raises((AssertionError, RuntimeError)):
138+ to_hif8_then_mm(A, B, cfg, cfg)
139+ 
140+ 
141+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
142+def test_no_requires_grad():
143+ """Gradient tracking is not required on either operand."""
144+ cfg = HiF8QuantizeConfig()
145+ A = torch.randn(32, 64, device="npu", dtype=torch.bfloat16)
146+ weight = torch.randn(128, 64, device="npu", dtype=torch.bfloat16)
147+ B = weight.T
148+ 
149+ out = to_hif8_then_mm(A, B, cfg, cfg)
150+ assert out.shape == (32, 128)
151+ assert not out.requires_grad
152+ 
153+ 
154+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
155+def test_fp32_input_is_cast_to_bf16():
156+ """fp32 operands are internally cast to bf16 (npu_dynamic_quant requires bf16/fp16)."""
157+ cfg = HiF8QuantizeConfig()
158+ A = torch.randn(32, 64, device="npu", dtype=torch.float32)
159+ weight = torch.randn(128, 64, device="npu", dtype=torch.float32)
160+ B = weight.T
161+ 
162+ out = to_hif8_then_mm(A, B, cfg, cfg)
163+ assert out.dtype == torch.bfloat16, f"Expected bf16 (cast from fp32), got {out.dtype}"
164+ 
165+ 
166+# =========================================================================
167+# to_hif8_then_grouped_mm
168+# =========================================================================
169+ 
170+ 
171+def _group_list_from_sizes(group_sizes: list[int], device: str = "npu") -> torch.Tensor:
172+ """Build a cumsum group_list for the given per-group sizes."""
173+ gs = torch.tensor(group_sizes, dtype=torch.int32, device=device)
174+ return gs.cumsum(0)
175+ 
176+ 
177+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
178+@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
179+@pytest.mark.parametrize(
180+ "M, K, N, E, group_sizes",
181+ [
182+ (128, 64, 128, 2, [64, 64]),
183+ (192, 64, 64, 3, [64, 64, 64]),
184+ (128, 64, 64, 4, [32, 32, 32, 32]),
185+ ],
186+)
187+def test_grouped_forward_shape_and_dtype(M, K, N, E, group_sizes, dtype):
188+ """Output shape and dtype match expectations for grouped matmul."""
189+ cfg = HiF8QuantizeConfig()
190+ A = torch.randn(M, K, device="npu", dtype=dtype)
191+ B = torch.randn(E, K, N, device="npu", dtype=dtype)
192+ group_list = _group_list_from_sizes(group_sizes)
193+ 
194+ out = to_hif8_then_grouped_mm(A, B, group_list, cfg, cfg)
195+ 
196+ assert out.shape == (M, N), f"Expected ({M}, {N}), got {out.shape}"
197+ assert out.dtype == A.dtype, f"Expected {A.dtype}, got {out.dtype}"
198+ assert out.device.type == "npu"
199+ 
200+ 
201+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
202+@pytest.mark.parametrize("M, K, N, E, group_sizes", [(192, 64, 128, 3, [64, 64, 64])])
203+def test_grouped_sqnr_forward(M, K, N, E, group_sizes):
204+ """Grouped HiF8 forward output has acceptable SQNR."""
205+ torch.manual_seed(42)
206+ cfg = HiF8QuantizeConfig()
207+ A = torch.randn(M, K, device="npu", dtype=torch.bfloat16)
208+ B = torch.randn(E, K, N, device="npu", dtype=torch.bfloat16)
209+ group_list = _group_list_from_sizes(group_sizes)
210+ 
211+ # Reference: group-by-group high-precision matmul
212+ out_ref = []
213+ for i in range(E):
214+ s = group_list[i - 1].item() if i > 0 else 0
215+ e = group_list[i].item()
216+ out_ref.append(A[s:e] @ B[i])
217+ out_ref = torch.cat(out_ref, dim=0)
218+ 
219+ out_hif8 = to_hif8_then_grouped_mm(A, B, group_list, cfg, cfg)
220+ 
221+ sqnr = compute_error(out_ref.float(), out_hif8.float()).item()
222+ assert sqnr > _SQNR_THRESHOLD, f"Forward SQNR too low: {sqnr:.2f} dB"
223+ 
224+ 
225+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
226+@pytest.mark.parametrize("M, K, N, E, group_sizes", [(192, 64, 128, 3, [64, 64, 64])])
227+def test_grouped_sqnr_gradients(M, K, N, E, group_sizes):
228+ """Grouped HiF8 backward gradients have acceptable SQNR."""
229+ torch.manual_seed(42)
230+ cfg = HiF8QuantizeConfig()
231+ A = torch.randn(M, K, device="npu", dtype=torch.bfloat16, requires_grad=True)
232+ B = torch.randn(E, K, N, device="npu", dtype=torch.bfloat16, requires_grad=True)
233+ group_list = _group_list_from_sizes(group_sizes)
234+ 
235+ A_ref = A.clone().detach().requires_grad_(True)
236+ B_ref = B.clone().detach().requires_grad_(True)
237+ out_ref = []
238+ for i in range(E):
239+ s = group_list[i - 1].item() if i > 0 else 0
240+ e = group_list[i].item()
241+ out_ref.append(A_ref[s:e] @ B_ref[i])
242+ out_ref = torch.cat(out_ref, dim=0)
243+ out_ref.sum().backward()
244+ 
245+ A_hif8 = A.clone().detach().requires_grad_(True)
246+ B_hif8 = B.clone().detach().requires_grad_(True)
247+ out_hif8 = to_hif8_then_grouped_mm(A_hif8, B_hif8, group_list, cfg, cfg)
248+ out_hif8.sum().backward()
249+ 
250+ sqnr_dA = compute_error(A_ref.grad.float(), A_hif8.grad.float()).item()
251+ assert sqnr_dA > _SQNR_THRESHOLD, f"dA SQNR too low: {sqnr_dA:.2f} dB"
252+ 
253+ sqnr_dB = compute_error(B_ref.grad.float(), B_hif8.grad.float()).item()
254+ assert sqnr_dB > _SQNR_THRESHOLD, f"dB SQNR too low: {sqnr_dB:.2f} dB"
255+ 
256+ 
257+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
258+def test_grouped_non_2d_3d_input():
259+ """Non-2D A / non-3D B raise an error in grouped matmul."""
260+ cfg = HiF8QuantizeConfig()
261+ # A 3D (must be 2D)
262+ A_3d = torch.randn(4, 32, 64, device="npu", dtype=torch.bfloat16)
263+ B = torch.randn(2, 64, 128, device="npu", dtype=torch.bfloat16)
264+ group_list = torch.tensor([64, 128], dtype=torch.int32, device="npu")
265+ with pytest.raises((AssertionError, RuntimeError)):
266+ to_hif8_then_grouped_mm(A_3d, B, group_list, cfg, cfg)
267+ 
268+ # B 2D (must be 3D)
269+ A = torch.randn(64, 64, device="npu", dtype=torch.bfloat16)
270+ B_2d = torch.randn(64, 128, device="npu", dtype=torch.bfloat16)
271+ with pytest.raises((AssertionError, RuntimeError)):
272+ to_hif8_then_grouped_mm(A, B_2d, group_list, cfg, cfg)
273+ 
274+ 
275+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
276+def test_grouped_contracting_dim_mismatch():
277+ """Mismatched contracting dimensions raise an error in grouped matmul."""
278+ cfg = HiF8QuantizeConfig()
279+ A = torch.randn(64, 64, device="npu", dtype=torch.bfloat16)
280+ B = torch.randn(2, 128, 64, device="npu", dtype=torch.bfloat16)
281+ group_list = torch.tensor([32, 64], dtype=torch.int32, device="npu")
282+ with pytest.raises((AssertionError, RuntimeError)):
283+ to_hif8_then_grouped_mm(A, B, group_list, cfg, cfg)
284+ 
285+ 
286+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
287+def test_grouped_no_requires_grad():
288+ """Gradient tracking not required on grouped operands."""
289+ cfg = HiF8QuantizeConfig()
290+ A = torch.randn(128, 64, device="npu", dtype=torch.bfloat16)
291+ B = torch.randn(2, 64, 128, device="npu", dtype=torch.bfloat16)
292+ group_list = torch.tensor([64, 128], dtype=torch.int32, device="npu")
293+ 
294+ out = to_hif8_then_grouped_mm(A, B, group_list, cfg, cfg)
295+ assert out.shape == (128, 128)
296+ assert not out.requires_grad
297+ 
298+ 
299+@pytest.mark.skipif(not _npu_available(), reason="NPU not available")
300+@pytest.mark.parametrize("E", [2, 3, 5])
301+def test_grouped_scale_broadcast_tracks_weight_expert_count(E):
302+ """Scale broadcast width is derived from B.shape[0] (E), not any external state.
303+ 
304+ Regression guard for the design decision (see ops/hif8_ops.py module
305+ docstring) to read the expert count directly off the weight tensor's
306+ shape instead of depending on an external mutable dict -- sweep several
307+ values of E and confirm forward/backward run and produce finite,
308+ correctly-shaped gradients for each.
309+ """
310+ cfg = HiF8QuantizeConfig()
311+ M, K, N = 64, 32, 32
312+ A = torch.randn(M, K, device="npu", dtype=torch.bfloat16, requires_grad=True)
313+ B = torch.randn(E, K, N, device="npu", dtype=torch.bfloat16, requires_grad=True)
314+ base = M // E
315+ group_sizes = [base] * (E - 1) + [M - base * (E - 1)]
316+ group_list = _group_list_from_sizes(group_sizes)
317+ 
318+ out = to_hif8_then_grouped_mm(A, B, group_list, cfg, cfg)
319+ assert out.shape == (M, N)
320+ 
321+ out.sum().backward()
322+ assert A.grad is not None and torch.isfinite(A.grad.float()).all()
323+ assert B.grad is not None and B.grad.shape == B.shape and torch.isfinite(B.grad.float()).all()
@@ -14,7 +14,9 @@ pytest "$BASE/test_training.py" -s -v
14pytest "$BASE/wrapper_tensors/test_param_swap_transform.py" -s -v14pytest "$BASE/wrapper_tensors/test_param_swap_transform.py" -s -v
15pytest "$BASE/wrapper_tensors/test_wrapper_tensor.py" -s -v15pytest "$BASE/wrapper_tensors/test_wrapper_tensor.py" -s -v
16pytest "$BASE/wrapper_tensors/test_wrapper_ops.py" -s -v16pytest "$BASE/wrapper_tensors/test_wrapper_ops.py" -s -v
17+pytest "$BASE/wrapper_tensors/test_hif8_wrapper_tensor.py" -s -v
17pytest "$BASE/ops/test_mx_ops.py" -s -v18pytest "$BASE/ops/test_mx_ops.py" -s -v
18pytest "$BASE/ops/test_block_ops.py" -s -v19pytest "$BASE/ops/test_block_ops.py" -s -v
20+pytest "$BASE/ops/test_hif8_ops.py" -s -v
19 21 
20echo "all tests successful"22echo "all tests successful"
@@ -77,26 +77,26 @@ def test_config_infer_from_base_config(base_config, expected_weight_config, expe
77 77 
78 78 
79def test_config_rejects_invalid_weight_config():79def test_config_rejects_invalid_weight_config():
80- """Invalid (non-FP8, non-NPU-MX) weight configs should be rejected."""80+ """Invalid (non-FP8, non-NPU-MX, non-NPU-Block, non-NPU-HiF8) weight configs should be rejected."""
81 intx_config = IntxFakeQuantizeConfig(torch.int8, "per_channel")81 intx_config = IntxFakeQuantizeConfig(torch.int8, "per_channel")
82 with pytest.raises(82 with pytest.raises(
83 ValueError,83 ValueError,
84 match=(84 match=(
85- r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockQuantizeConfig` "85+ r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, `BlockQuantizeConfig`, or "
86- r"is supported for `weight_config` in ParamSwapConfig yet\.$"86+ r"`HiF8QuantizeConfig` is supported for `weight_config` in ParamSwapConfig yet\.$"
87 ),87 ),
88 ):88 ):
89 ParamSwapConfig(weight_config=intx_config, step="prepare")89 ParamSwapConfig(weight_config=intx_config, step="prepare")
90 90 
91 91 
92def test_config_rejects_invalid_activation_config():92def test_config_rejects_invalid_activation_config():
93- """Invalid (non-FP8, non-NPU-MX) activation configs should be rejected."""93+ """Invalid (non-FP8, non-NPU-MX, non-NPU-HiF8) activation configs should be rejected."""
94 weight_config = Float8FakeQuantizeConfig(dtype=torch.float8_e4m3fn, granularity=PerRow())94 weight_config = Float8FakeQuantizeConfig(dtype=torch.float8_e4m3fn, granularity=PerRow())
95 activation_config = IntxFakeQuantizeConfig(torch.int8, "per_channel")95 activation_config = IntxFakeQuantizeConfig(torch.int8, "per_channel")
96 with pytest.raises(96 with pytest.raises(
97 ValueError,97 ValueError,
98 match=(98 match=(
99- r"^Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` is supported for "99+ r"^Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `HiF8QuantizeConfig` is supported for "
100 r"`activation_config` in ParamSwapConfig yet\.$"100 r"`activation_config` in ParamSwapConfig yet\.$"
101 ),101 ),
102 ):102 ):
@@ -0,0 +1,376 @@
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 HiF8TrainingWeightWrapperTensor.
7+ 
8+Kept as a dedicated file (rather than folding entries into the shared
9+test_wrapper_tensor.py / test_wrapper_ops.py parametrize tables that cover
10+Base/Float8/MX/Block together) so this new backend's tests don't risk
11+touching those already-established, heavily-parametrized suites. Covers the
12+same behaviors those files check for the other backends: __init__
13+validation, subclass-preserving dispatch, deepcopy, FSDP hooks, and
14+end-to-end SQNR through an nn.Parameter + optimizer step.
15+ 
16+SQNR thresholds are conservative placeholders -- see test_hif8_ops.py's
17+module docstring for why.
18+"""
19+ 
20+import copy
21+ 
22+import pytest
23+import torch
24+import torch.nn.functional as F
25+from torch.distributed.fsdp import MixedPrecisionPolicy
26+from torchao.float8.float8_utils import compute_error
27+from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase
28+ 
29+from torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs import HiF8QuantizeConfig
30+from torchtitan_npu.experiments.ao_npu.torchao_npu.wrapper_tensors import HiF8TrainingWeightWrapperTensor
31+ 
32+from ..testing_utils import target_devices
33+ 
34+_SQNR_THRESHOLD = 12.0
35+ 
36+ 
37+# =========================================================================
38+# __init__
39+# =========================================================================
40+ 
41+ 
42+@pytest.mark.parametrize("device", target_devices)
43+def test_init_stores_attrs(device):
44+ w = torch.randn(64, 128, device=device)
45+ weight_config = HiF8QuantizeConfig()
46+ act_config = HiF8QuantizeConfig()
47+ wrapper = HiF8TrainingWeightWrapperTensor(w, weight_config=weight_config, activation_config=act_config)
48+ assert wrapper._data is w
49+ assert wrapper.weight_config is weight_config
50+ assert wrapper.activation_config is act_config
51+ 
52+ 
53+@pytest.mark.parametrize("device", target_devices)
54+def test_init_rejects_missing_weight_config(device):
55+ w = torch.randn(64, 128, device=device)
56+ with pytest.raises(ValueError, match=r"^`weight_config` is required for HiF8TrainingWeightWrapperTensor\.$"):
57+ HiF8TrainingWeightWrapperTensor(w, weight_config=None, activation_config=HiF8QuantizeConfig())
58+ 
59+ 
60+@pytest.mark.parametrize("device", target_devices)
61+def test_init_rejects_missing_activation_config(device):
62+ w = torch.randn(64, 128, device=device)
63+ with pytest.raises(ValueError, match=r"^`activation_config` is required for HiF8TrainingWeightWrapperTensor\.$"):
64+ HiF8TrainingWeightWrapperTensor(w, weight_config=HiF8QuantizeConfig(), activation_config=None)
65+ 
66+ 
67+@pytest.mark.parametrize("device", target_devices)
68+def test_init_rejects_wrong_type_weight_config(device):
69+ class DummyConfig(FakeQuantizeConfigBase):
70+ pass
71+ 
72+ w = torch.randn(64, 128, device=device)
73+ with pytest.raises(
74+ ValueError,
75+ match=r"^Only `HiF8QuantizeConfig` is supported for `weight_config` in HiF8TrainingWeightWrapperTensor\.$",
76+ ):
77+ HiF8TrainingWeightWrapperTensor(w, weight_config=DummyConfig(), activation_config=HiF8QuantizeConfig())
78+ 
79+ 
80+@pytest.mark.parametrize("device", target_devices)
81+def test_init_rejects_wrong_type_activation_config(device):
82+ class DummyConfig(FakeQuantizeConfigBase):
83+ pass
84+ 
85+ w = torch.randn(64, 128, device=device)
86+ with pytest.raises(
87+ ValueError,
88+ match=(
89+ r"^Only `HiF8QuantizeConfig` is supported for `activation_config` "
90+ r"in HiF8TrainingWeightWrapperTensor\.$"
91+ ),
92+ ):
93+ HiF8TrainingWeightWrapperTensor(w, weight_config=HiF8QuantizeConfig(), activation_config=DummyConfig())
94+ 
95+ 
96+# =========================================================================
97+# __torch_function__ dispatch: A must not be wrapped, B must be wrapped
98+# =========================================================================
99+ 
100+ 
101+@pytest.mark.parametrize("device", target_devices)
102+@pytest.mark.parametrize("func", [torch.mm, F.linear])
103+def test_torch_function_arg_a_is_wrapper(func, device):
104+ w = torch.randn(64, 128, device=device)
105+ w1 = HiF8TrainingWeightWrapperTensor(w, weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig())
106+ w2 = HiF8TrainingWeightWrapperTensor(w, weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig())
107+ with pytest.raises(AssertionError, match=r"^A should not be a HiF8TrainingWeightWrapperTensor$"):
108+ func(w1, w2)
109+ 
110+ 
111+@pytest.mark.parametrize("device", target_devices)
112+@pytest.mark.parametrize("func", [torch.addmm, F.linear])
113+def test_torch_function_arg_b_not_wrapper(func, device):
114+ bias = HiF8TrainingWeightWrapperTensor(
115+ torch.randn(128, device=device), weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig()
116+ )
117+ A = torch.randn(16, 64, device=device)
118+ B = torch.randn(64, 128, device=device)
119+ with pytest.raises(AssertionError, match=r"^B should be a HiF8TrainingWeightWrapperTensor$"):
120+ func(bias, A, B) if func is torch.addmm else func(A, B, bias)
121+ 
122+ 
123+@pytest.mark.parametrize("device", target_devices)
124+def test_torch_function_non_quantized_op_passes_through(device):
125+ """A non-matmul op (e.g. torch.add) is not intercepted for quantization."""
126+ w1 = torch.randn(64, 128, device=device)
127+ w2 = torch.randn(64, 128, device=device)
128+ wrapper = HiF8TrainingWeightWrapperTensor(
129+ w2.clone(), weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig()
130+ )
131+ result = torch.add(w1, wrapper)
132+ expected = torch.add(w1, w2)
133+ assert type(result) is torch.Tensor
134+ assert torch.equal(result, expected)
135+ 
136+ 
137+@pytest.mark.parametrize("device", target_devices)
138+def test_bias_bypass(device):
139+ """Wrapped bias is unconditionally bypassed (not quantized)."""
140+ A = torch.randn(32, 64, dtype=torch.bfloat16, device=device)
141+ w_wrapped = HiF8TrainingWeightWrapperTensor(
142+ torch.randn(128, 64, dtype=torch.bfloat16, device=device),
143+ weight_config=HiF8QuantizeConfig(),
144+ activation_config=HiF8QuantizeConfig(),
145+ )
146+ bias = torch.randn(128, dtype=torch.bfloat16, device=device)
147+ bias_wrapped = HiF8TrainingWeightWrapperTensor(
148+ bias, weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig()
149+ )
150+ out_wrapped = F.linear(A, w_wrapped, bias_wrapped)
151+ out_ref = F.linear(A, w_wrapped, bias)
152+ assert torch.equal(out_wrapped, out_ref), "bias should not be quantized"
153+ 
154+ 
155+# =========================================================================
156+# Subclass-preserving dispatch (representative subset -- full op list is
157+# already covered generically for BaseTrainingWeightWrapperTensor in
158+# test_wrapper_ops.py::test_wrapper_preserves_subclass)
159+# =========================================================================
160+ 
161+ 
162+@pytest.mark.parametrize("device", target_devices)
163+@pytest.mark.parametrize(
164+ "op_func",
165+ [
166+ lambda x: x[0],
167+ lambda x: x[0:2],
168+ lambda x: x.transpose(0, 1),
169+ lambda x: x.detach(),
170+ lambda x: x.clone(),
171+ ],
172+)
173+def test_preserves_subclass(op_func, device):
174+ weight_config = HiF8QuantizeConfig()
175+ act_config = HiF8QuantizeConfig()
176+ weight = torch.randn(4, 64, 128, device=device)
177+ wrapper = HiF8TrainingWeightWrapperTensor(weight, weight_config=weight_config, activation_config=act_config)
178+ 
179+ with torch._C.DisableTorchFunctionSubclass():
180+ result = op_func(wrapper)
181+ ref_result = op_func(wrapper._data)
182+ 
183+ assert isinstance(result, HiF8TrainingWeightWrapperTensor)
184+ assert result.weight_config is weight_config
185+ assert result.activation_config is act_config
186+ assert torch.equal(result._data, ref_result)
187+ 
188+ 
189+# =========================================================================
190+# deepcopy
191+# =========================================================================
192+ 
193+ 
194+@pytest.mark.parametrize("device", target_devices)
195+def test_deepcopy(device):
196+ weight_config = HiF8QuantizeConfig()
197+ act_config = HiF8QuantizeConfig()
198+ w = torch.randn(256, 128, dtype=torch.bfloat16, device=device)
199+ wrapper = HiF8TrainingWeightWrapperTensor(w, weight_config=weight_config, activation_config=act_config)
200+ 
201+ wrapper_copy = copy.deepcopy(wrapper)
202+ 
203+ assert wrapper_copy is not wrapper
204+ assert isinstance(wrapper_copy, HiF8TrainingWeightWrapperTensor)
205+ assert wrapper_copy._data is not wrapper._data
206+ assert torch.equal(wrapper_copy._data, wrapper._data)
207+ assert wrapper_copy.weight_config == wrapper.weight_config
208+ 
209+ 
210+# =========================================================================
211+# FSDP hooks (inherited unchanged from BaseTrainingWeightWrapperTensor --
212+# smoke-tested here for HiF8 specifically)
213+# =========================================================================
214+ 
215+ 
216+@pytest.mark.parametrize("param_dtype", [torch.float32, torch.bfloat16])
217+def test_fsdp_pre_all_gather(param_dtype):
218+ w = torch.randn(64, 128, dtype=torch.float32)
219+ wrapper = HiF8TrainingWeightWrapperTensor(
220+ w, weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig()
221+ )
222+ mp_policy = MixedPrecisionPolicy(param_dtype=param_dtype)
223+ 
224+ all_gather_inputs, metadata = wrapper.fsdp_pre_all_gather(None, None, None, None, mp_policy)
225+ (data,) = all_gather_inputs
226+ assert metadata == ()
227+ assert data.dtype == param_dtype
228+ assert torch.equal(data, w.to(param_dtype))
229+ 
230+ 
231+@pytest.mark.parametrize("device", target_devices)
232+def test_fsdp_post_all_gather_first_step(device):
233+ weight_config = HiF8QuantizeConfig()
234+ act_config = HiF8QuantizeConfig()
235+ w = torch.empty(64, 128, device="meta")
236+ wrapper = HiF8TrainingWeightWrapperTensor(w, weight_config=weight_config, activation_config=act_config)
237+ gathered = torch.empty(4, 64, 128, device=device)
238+ 
239+ result, inner_tensors = wrapper.fsdp_post_all_gather((gathered,), None, torch.float32, out=None)
240+ assert type(result) is HiF8TrainingWeightWrapperTensor
241+ assert result._data is gathered
242+ assert isinstance(inner_tensors, tuple)
243+ assert len(inner_tensors) == 1
244+ assert inner_tensors[0] is gathered
245+ assert result.weight_config is weight_config
246+ assert result.activation_config is act_config
247+ 
248+ 
249+# =========================================================================
250+# End-to-end SQNR through nn.Parameter + optimizer step
251+# =========================================================================
252+ 
253+ 
254+@pytest.mark.parametrize("device", target_devices)
255+@pytest.mark.parametrize(
256+ "call_fn, A_shape, w_shape, bias_shape, out_shape",
257+ [
258+ (lambda a, w, bias: torch.mm(a, w.T), (32, 1024), (2048, 1024), (), (32, 2048)),
259+ (lambda a, w, bias: F.linear(a, w), (32, 1024), (2048, 1024), (), (32, 2048)),
260+ (
261+ lambda a, w, bias: F.linear(a, w, bias),
262+ (32, 1024),
263+ (2048, 1024),
264+ (2048,),
265+ (32, 2048),
266+ ),
267+ (
268+ lambda a, w, bias: torch.matmul(a, w.T),
269+ (32, 1024),
270+ (2048, 1024),
271+ (),
272+ (32, 2048),
273+ ),
274+ (
275+ lambda a, w, bias: torch.addmm(bias, a, w.T),
276+ (32, 1024),
277+ (2048, 1024),
278+ (2048,),
279+ (32, 2048),
280+ ),
281+ (
282+ lambda a, w, bias: torch.addmm(bias, a, w.T, beta=2.0, alpha=0.5),
283+ (32, 1024),
284+ (2048, 1024),
285+ (2048,),
286+ (32, 2048),
287+ ),
288+ ],
289+)
290+def test_op_sqnr_and_training_step(call_fn, A_shape, w_shape, bias_shape, out_shape, device):
291+ """HiF8-quantized forward+backward+optimizer-step tracks a bf16 reference."""
292+ weight_config = HiF8QuantizeConfig()
293+ act_config = HiF8QuantizeConfig()
294+ 
295+ activation_tensor = torch.randn(*A_shape, device=device, dtype=torch.bfloat16)
296+ weight_tensor = torch.randn(*w_shape, device=device, dtype=torch.bfloat16)
297+ 
298+ activation = torch.nn.Parameter(activation_tensor.clone())
299+ weight = torch.nn.Parameter(
300+ HiF8TrainingWeightWrapperTensor(
301+ weight_tensor.clone(), activation_config=act_config, weight_config=weight_config
302+ )
303+ )
304+ bias = torch.nn.Parameter(torch.randn(bias_shape, device=device, dtype=torch.bfloat16))
305+ ref_bias = torch.nn.Parameter(bias.data.clone())
306+ 
307+ ref_activation = torch.nn.Parameter(activation_tensor.clone())
308+ ref_weight = torch.nn.Parameter(weight_tensor.clone())
309+ 
310+ learning_rate = 1
311+ opt_params = [weight, bias] if bias_shape else [weight]
312+ optimizer = torch.optim.SGD(opt_params, lr=learning_rate)
313+ out = call_fn(activation, weight, bias)
314+ 
315+ ref_opt_params = [ref_weight, ref_bias] if bias_shape else [ref_weight]
316+ ref_optimizer = torch.optim.SGD(ref_opt_params, lr=learning_rate)
317+ ref_out = call_fn(ref_activation, ref_weight, ref_bias)
318+ 
319+ assert out.shape == out_shape == ref_out.shape
320+ 
321+ sqnr = compute_error(out, ref_out)
322+ assert sqnr != float("inf"), "SQNR should be finite (quantization was applied)"
323+ assert sqnr > _SQNR_THRESHOLD, f"Forward SQNR too low ({sqnr:.1f} dB)"
324+ 
325+ target = torch.ones_like(out)
326+ loss = F.mse_loss(out, target)
327+ loss.backward()
328+ ref_loss = F.mse_loss(ref_out, target)
329+ ref_loss.backward()
330+ 
331+ assert activation.grad is not None
332+ activation_grad_sqnr = compute_error(activation.grad, ref_activation.grad)
333+ assert activation_grad_sqnr > _SQNR_THRESHOLD, f"Input grad SQNR too low ({activation_grad_sqnr:.1f} dB)"
334+ 
335+ assert weight.grad is not None
336+ weight_grad_sqnr = compute_error(weight.grad, ref_weight.grad)
337+ assert weight_grad_sqnr > _SQNR_THRESHOLD, f"Weight grad SQNR too low ({weight_grad_sqnr:.1f} dB)"
338+ 
339+ optimizer.step()
340+ ref_optimizer.step()
341+ 
342+ assert not torch.equal(weight_tensor, weight), "weight should be updated"
343+ new_weight_sqnr = compute_error(weight, ref_weight)
344+ assert new_weight_sqnr > _SQNR_THRESHOLD, f"New weight SQNR too low ({new_weight_sqnr:.1f} dB)"
345+ 
346+ 
347+@pytest.mark.parametrize("device", target_devices)
348+def test_op_grouped_mm_sqnr(device):
349+ """grouped_mm with HiF8-quantized weight produces reasonable forward+backward SQNR."""
350+ weight_config = HiF8QuantizeConfig()
351+ act_config = HiF8QuantizeConfig()
352+ 
353+ S, E, K, N = 16, 4, 1024, 2048 # total_tokens, experts, in_features, out_features
354+ 
355+ A = torch.randn(S, K, dtype=torch.bfloat16, requires_grad=True, device=device)
356+ w = torch.randn(E, N, K, dtype=torch.bfloat16, device=device)
357+ wrapper = HiF8TrainingWeightWrapperTensor(w, activation_config=act_config, weight_config=weight_config)
358+ param = torch.nn.Parameter(wrapper)
359+ 
360+ offs = torch.tensor([4, 8, 12, 16], dtype=torch.int32, device=device)
361+ A_ref = A.clone().detach().requires_grad_(True)
362+ w_ref = w.clone().detach().requires_grad_(True)
363+ ref_out = torch._grouped_mm(A_ref, w_ref.transpose(-2, -1), offs=offs)
364+ out = torch._grouped_mm(A, param.transpose(-2, -1), offs=offs)
365+ assert out.shape == (S, N)
366+ 
367+ sqnr = compute_error(out, ref_out)
368+ assert sqnr != float("inf"), "SQNR should be finite (quantization was applied)"
369+ assert sqnr > _SQNR_THRESHOLD, f"Forward SQNR too low ({sqnr:.1f} dB)"
370+ 
371+ ref_out.backward(torch.ones_like(ref_out))
372+ out.backward(torch.ones_like(out))
373+ assert A.grad is not None
374+ assert compute_error(A.grad, A_ref.grad) > _SQNR_THRESHOLD
375+ assert param.grad is not None
376+ assert compute_error(param.grad, w_ref.grad) > _SQNR_THRESHOLD
@@ -18,6 +18,7 @@ from torchao.quantization.transform_module import register_quantize_module_handl
18from .quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data18from .quantization.filters import ParameterFilterFn, _is_parameter, _is_parameter_with_wrapped_data
19from .quantization.quant_configs import (19from .quantization.quant_configs import (
20 BlockQuantizeConfig,20 BlockQuantizeConfig,
21+ HiF8QuantizeConfig,
21 MXQuantizeConfig,22 MXQuantizeConfig,
22)23)
23from .quantization.transform import (24from .quantization.transform import (
@@ -50,8 +51,10 @@ class ParamSwapConfig(QATConfig):
50 (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`),51 (:class:`~torchao.quantization.qat.fake_quantize_config.Float8FakeQuantizeConfig`),
51 NPU MX block-wise52 NPU MX block-wise
52 (:class:`~torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs.MXQuantizeConfig`),53 (:class:`~torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs.MXQuantizeConfig`),
53- and NPU Block FP854+ NPU Block FP8
54- (:class:`~torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs.BlockQuantizeConfig`).55+ (:class:`~torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs.BlockQuantizeConfig`),
56+ and NPU HiF8 per-tensor
57+ (:class:`~torchtitan_npu.experiments.ao_npu.torchao_npu.quantization.quant_configs.HiF8QuantizeConfig`).
55 """58 """
56 59 
57 def __init__(60 def __init__(
@@ -69,18 +72,18 @@ class ParamSwapConfig(QATConfig):
69 def __post_init__(self):72 def __post_init__(self):
70 torch._C._log_api_usage_once("torchao.prototype.param_swap.ParamSwapConfig")73 torch._C._log_api_usage_once("torchao.prototype.param_swap.ParamSwapConfig")
71 if self.activation_config is not None and not isinstance(74 if self.activation_config is not None and not isinstance(
72- self.activation_config, (Float8FakeQuantizeConfig, MXQuantizeConfig)75+ self.activation_config, Float8FakeQuantizeConfig | MXQuantizeConfig | HiF8QuantizeConfig
73 ):76 ):
74 raise ValueError(77 raise ValueError(
75- "Only `Float8FakeQuantizeConfig` or `MXQuantizeConfig` "78+ "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `HiF8QuantizeConfig` "
76 "is supported for `activation_config` in ParamSwapConfig yet."79 "is supported for `activation_config` in ParamSwapConfig yet."
77 )80 )
78 if self.weight_config is not None and not isinstance(81 if self.weight_config is not None and not isinstance(
79- self.weight_config, (Float8FakeQuantizeConfig, MXQuantizeConfig, BlockQuantizeConfig)82+ self.weight_config, Float8FakeQuantizeConfig | MXQuantizeConfig | BlockQuantizeConfig | HiF8QuantizeConfig
80 ):83 ):
81 raise ValueError(84 raise ValueError(
82- "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, or `BlockQuantizeConfig` "85+ "Only `Float8FakeQuantizeConfig`, `MXQuantizeConfig`, `BlockQuantizeConfig`, or "
83- "is supported for `weight_config` in ParamSwapConfig yet."86+ "`HiF8QuantizeConfig` is supported for `weight_config` in ParamSwapConfig yet."
84 )87 )
85 88 
86 super().__post_init__()89 super().__post_init__()
@@ -9,6 +9,10 @@ from .block_ops import (
9 to_block_fp8_then_mm,9 to_block_fp8_then_mm,
10)10)
11from .float8_ops import float8_rowwise_fake_quantize11from .float8_ops import float8_rowwise_fake_quantize
12+from .hif8_ops import (
13+ to_hif8_then_grouped_mm,
14+ to_hif8_then_mm,
15+)
12from .mx_ops import (16from .mx_ops import (
13 mxfp4_fake_quantize,17 mxfp4_fake_quantize,
14 to_mx_then_bmm,18 to_mx_then_bmm,
@@ -22,6 +26,8 @@ __all__ = [
22 "to_block_fp8_then_bmm",26 "to_block_fp8_then_bmm",
23 "to_block_fp8_then_grouped_mm",27 "to_block_fp8_then_grouped_mm",
24 "to_block_fp8_then_mm",28 "to_block_fp8_then_mm",
29+ "to_hif8_then_grouped_mm",
30+ "to_hif8_then_mm",
25 "to_mx_then_bmm",31 "to_mx_then_bmm",
26 "to_mx_then_grouped_mm",32 "to_mx_then_grouped_mm",
27 "to_mx_then_mm",33 "to_mx_then_mm",
@@ -0,0 +1,258 @@
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+"""
7+Per-tensor HiF8 (``torch_npu.hifloat8``) low-precision matmul ops for NPU.
8+"""
9+ 
10+import torch
11+import torch_npu
12+ 
13+from ..quantization.quant_configs import HiF8QuantizeConfig
14+ 
15+ 
16+def _ensure_bf16_or_fp16(t: torch.Tensor) -> torch.Tensor:
17+ """``npu_dynamic_quant``'s pertensor path only accepts bf16/fp16 input."""
18+ if t.dtype not in (torch.float16, torch.bfloat16):
19+ return t.to(torch.bfloat16)
20+ return t
21+ 
22+ 
23+# =========================================================================
24+# Real per-tensor HiF8 quantized matmul
25+# =========================================================================
26+ 
27+ 
28+class _HiF8QuantMM(torch.autograd.Function):
29+ """Per-tensor HiF8 quantized matrix multiply: ``A[M,K] @ B[K,N] = Y[M,N]``."""
30+ 
31+ @staticmethod
32+ # pyrefly: ignore [bad-override]
33+ def forward(
34+ ctx,
35+ A: torch.Tensor,
36+ B: torch.Tensor,
37+ config_A: HiF8QuantizeConfig,
38+ config_B: HiF8QuantizeConfig,
39+ ):
40+ assert A.ndim >= 2, f"A must be >=2D, got {A.ndim}D"
41+ assert B.ndim == 2, f"B must be 2D, got {B.ndim}D"
42+ assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"
43+ 
44+ A_flat = _ensure_bf16_or_fp16(A.reshape(-1, A.shape[-1]))
45+ B = _ensure_bf16_or_fp16(B)
46+ 
47+ A_q, A_s = torch_npu.npu_dynamic_quant(A_flat, dst_type=config_A.elem_dtype, quant_mode="pertensor")
48+ B_q, B_s = torch_npu.npu_dynamic_quant(B, dst_type=config_B.elem_dtype, quant_mode="pertensor")
49+ 
50+ Y = torch_npu.npu_quant_matmul(
51+ A_q,
52+ B_q,
53+ B_s,
54+ pertoken_scale=A_s,
55+ output_dtype=A_flat.dtype,
56+ x1_dtype=config_A.elem_dtype,
57+ x2_dtype=config_B.elem_dtype,
58+ )
59+ 
60+ if A.ndim != 2:
61+ Y = Y.reshape(*A.shape[:-1], *Y.shape[1:])
62+ 
63+ Y.requires_grad_(A.requires_grad or B.requires_grad)
64+ 
65+ ctx.save_for_backward(A_q, A_s, B_q, B_s)
66+ ctx.A_dtype = A_flat.dtype
67+ ctx.config_A = config_A
68+ ctx.config_B = config_B
69+ return Y
70+ 
71+ @staticmethod
72+ # pyrefly: ignore [bad-override]
73+ def backward(ctx, dY: torch.Tensor):
74+ A_q, A_s, B_q, B_s = ctx.saved_tensors
75+ A_dtype = ctx.A_dtype
76+ config_A = ctx.config_A
77+ config_B = ctx.config_B
78+ 
79+ dY_flat = _ensure_bf16_or_fp16(dY.reshape(-1, dY.shape[-1]))
80+ dY_q, dY_s = torch_npu.npu_dynamic_quant(dY_flat, dst_type=config_A.elem_dtype, quant_mode="pertensor")
81+ 
82+ # --- dgrad dA = dY @ B^T (contract over N) ---
83+ dA = torch_npu.npu_quant_matmul(
84+ dY_q,
85+ B_q.t(),
86+ B_s,
87+ pertoken_scale=dY_s,
88+ output_dtype=A_dtype,
89+ x1_dtype=config_A.elem_dtype,
90+ x2_dtype=config_B.elem_dtype,
91+ )
92+ 
93+ # --- wgrad dB = A^T @ dY (contract over M) ---
94+ dB = torch_npu.npu_quant_matmul(
95+ A_q.t(),
96+ dY_q,
97+ dY_s,
98+ pertoken_scale=A_s,
99+ output_dtype=A_dtype,
100+ x1_dtype=config_A.elem_dtype,
101+ x2_dtype=config_A.elem_dtype,
102+ )
103+ 
104+ if dY.ndim != 2:
105+ dA = dA.reshape(*dY.shape[:-1], *dA.shape[1:])
106+ 
107+ return dA, dB, None, None
108+ 
109+ 
110+def to_hif8_then_mm(
111+ A: torch.Tensor,
112+ B: torch.Tensor,
113+ config_A: HiF8QuantizeConfig,
114+ config_B: HiF8QuantizeConfig,
115+) -> torch.Tensor:
116+ """Per-tensor HiF8 quantized matrix multiply: ``A @ B``.
117+ 
118+ ``A`` can be n-dimensional (n >= 2); leading dimensions are flattened
119+ before quantization and restored in the output. ``B`` must be 2D.
120+ 
121+ Args:
122+ A: Shape ``(..., M, K)`` (n >= 2).
123+ B: Shape ``(K, N)``.
124+ config_A: Config for A's (and dY's) quantization.
125+ config_B: Config for B's quantization.
126+ 
127+ Returns:
128+ Output tensor, shape ``(..., M, N)``, dtype matching ``A``.
129+ """
130+ return _HiF8QuantMM.apply(A, B, config_A, config_B)
131+ 
132+ 
133+class _HiF8QuantGroupedMM(torch.autograd.Function):
134+ """Per-tensor HiF8 quantized grouped matmul: ``A[M,K] @ B[E,K,N] = Y[M,N]``."""
135+ 
136+ @staticmethod
137+ # pyrefly: ignore [bad-override]
138+ def forward(
139+ ctx,
140+ A: torch.Tensor,
141+ B: torch.Tensor,
142+ group_list: torch.Tensor,
143+ config_A: HiF8QuantizeConfig,
144+ config_B: HiF8QuantizeConfig,
145+ ):
146+ assert A.ndim == 2, f"A must be 2D, got {A.ndim}D"
147+ assert B.ndim == 3, f"B must be 3D, got {B.ndim}D"
148+ assert A.shape[-1] == B.shape[-2], f"contracting dim mismatch: A[-1]={A.shape[-1]} != B[-2]={B.shape[-2]}"
149+ 
150+ group_list = group_list.to(torch.int64)
151+ num_experts = B.shape[0]
152+ 
153+ A_c = _ensure_bf16_or_fp16(A)
154+ B_c = _ensure_bf16_or_fp16(B)
155+ 
156+ A_q, A_s = torch_npu.npu_dynamic_quant(A_c, dst_type=config_A.elem_dtype, quant_mode="pertensor")
157+ B_q, B_s = torch_npu.npu_dynamic_quant(B_c, dst_type=config_B.elem_dtype, quant_mode="pertensor")
158+ 
atomgit-botatomgit-bot

🟡 Medium Priority

_HiF8QuantGroupedMM.forward(第 153-154 行)和 .backward(第 194-195 行)对 A、B、dY、B_t 直接调用 npu_dynamic_quant,没有提前做 dtype 转换。

而 _HiF8QuantMM.forward/backward 中一致使用了 _ensure_bf16_or_fp16,该函数的文档(hif8_ops.py:17)明确说明 "npu_dynamic_quant's pertensor path only accepts bf16/fp16 input"。

两条路径共用同一个 npu_dynamic_quant(quant_mode="pertensor") 算子,但只有 Linear 路径做了防御性 dtype 转换,GroupedMM 路径未做。若输入为非 bf16/fp16 精度(如 fp32),GroupedMM 路径调用 npu_dynamic_quant 可能报错或产生未定义行为;即便当前 bf16 训练下不触发,这条不一致路径仍是潜在缺陷。

建议:在 _HiF8QuantGroupedMM.forward 中量化 A / B 前加 _ensure_bf16_or_fp16 转换;.backward 中量化 dY / B_t 前同样加上。同时注意 ctx.A_dtype(以及 output_dtype)应使用转换后的 dtype,与 _HiF8QuantMM 保持一致。

likedislike
Incorrect?
nancycyzl
nancycyzl
Aug 17 Comments:
likedislike

🟡 Medium Priority

_HiF8QuantMM.forward/backward 在调用 npu_dynamic_quant(quant_mode="pertensor") 之前使用 _ensure_bf16_or_fp16 将输入转换为 bf16/fp16,因为该算子的 pertensor 路径只接受 bf16/fp16 输入(见 _ensure_bf16_or_fp16 的文档字符串,hif8_ops.py:17)。

但 _HiF8QuantGroupedMM.forward(第 153-154 行)和 .backward(第 194-195 行)对 A、B、dY、B_t 直接调用 npu_dynamic_quant,没有任何 dtype 前置检查和转换。如果训练使用 fp32 或其他非 bf16/fp16 精度,npu_dynamic_quant 会报错或产生未定义行为。

在 bf16 混合精度训练的正常路径上此问题不会触发(因为张量已是 bf16),但防御性转换是 _ensure_bf16_or_fp16 存在的目的——即在 _HiF8QuantMM 中应用而在 _HiF8QuantGroupedMM 中缺失,这条不一致路径构成潜在运行时缺陷。

建议:在 _HiF8QuantGroupedMM.forward 中量化 A/B 前加 _ensure_bf16_or_fp16,在 .backward 中量化 dY/B_t 前同样加上。同时注意 ctx.A_dtype 应保存转换后的 dtype(与 _HiF8QuantMM 一致)。

likedislike
Incorrect?
nancycyzl
nancycyzl
Aug 17 Comments:
likedislike
159+ Y = torch_npu.npu_grouped_matmul(
160+ [A_q],
161+ [B_q],
162+ # group_type=0: scale (weight-role) broadcasts over experts.
163+ scale=[B_s.reshape(1).expand(num_experts).contiguous()],
164+ # group_type=0: per_token_scale (activation-role) broadcasts over tokens.
165+ per_token_scale=[A_s.reshape(1).expand(A.shape[0]).contiguous()],
166+ group_list=group_list,
167+ group_type=0,
168+ bias=None,
169+ split_item=3,
170+ output_dtype=A_c.dtype,
171+ group_list_type=0,
172+ x_dtype=config_A.elem_dtype,
173+ weight_dtype=config_B.elem_dtype,
174+ )[0]
175+ 
176+ Y.requires_grad_(A.requires_grad or B.requires_grad)
177+ 
178+ ctx.save_for_backward(A_q, A_s, B_c, group_list)
179+ ctx.A_dtype = A_c.dtype
180+ ctx.config_A = config_A
181+ ctx.config_B = config_B
182+ return Y
183+ 
184+ @staticmethod
185+ # pyrefly: ignore [bad-override]
186+ def backward(ctx, dY: torch.Tensor):
187+ A_q, A_s, B, group_list = ctx.saved_tensors
188+ A_dtype = ctx.A_dtype
189+ config_A = ctx.config_A
190+ config_B = ctx.config_B
191+ assert dY.ndim == 2, f"dY must be 2D, got {dY.ndim}D"
192+ 
193+ num_experts = B.shape[0]
194+ 
195+ # --- dgrad dA = dY @ B^T (group_type=0, contract over N) ---
196+ dY_c = _ensure_bf16_or_fp16(dY)
197+ B_t = B.transpose(-1, -2)
198+ dY_q, dY_s = torch_npu.npu_dynamic_quant(dY_c, dst_type=config_A.elem_dtype, quant_mode="pertensor")
199+ B_t_q, B_t_s = torch_npu.npu_dynamic_quant(B_t, dst_type=config_B.elem_dtype, quant_mode="pertensor")
200+ dA = torch_npu.npu_grouped_matmul(
201+ [dY_q],
202+ [B_t_q],
203+ bias=None,
204+ scale=[B_t_s.reshape(1).expand(num_experts).contiguous()],
205+ per_token_scale=[dY_s.reshape(1).expand(dY.shape[0]).contiguous()],
206+ group_list=group_list,
207+ group_type=0,
208+ split_item=3,
209+ output_dtype=A_dtype,
210+ group_list_type=0,
211+ x_dtype=config_A.elem_dtype,
212+ weight_dtype=config_B.elem_dtype,
213+ )[0]
214+ 
215+ # --- dweight dB = A^T @ dY (group_type=2, split-K: BOTH scales broadcast
216+ # over num_experts, not over token count
217+ dB = torch_npu.npu_grouped_matmul(
218+ [A_q.t()],
219+ [dY_q],
220+ scale=[dY_s.reshape(1).expand(num_experts).contiguous()],
221+ per_token_scale=[A_s.reshape(1).expand(num_experts).contiguous()],
222+ group_list=group_list,
223+ group_type=2,
224+ bias=None,
225+ split_item=3,
226+ output_dtype=A_dtype,
227+ group_list_type=0,
228+ x_dtype=config_A.elem_dtype,
229+ weight_dtype=config_A.elem_dtype,
230+ )[0]
231+ 
232+ return dA, dB, None, None, None
233+ 
234+ 
235+def to_hif8_then_grouped_mm(
236+ A: torch.Tensor,
237+ B: torch.Tensor,
238+ group_list: torch.Tensor,
239+ config_A: HiF8QuantizeConfig,
240+ config_B: HiF8QuantizeConfig,
241+) -> torch.Tensor:
242+ """Per-tensor HiF8 quantized grouped matmul: ``A[M,K] @ B[E,K,N] = Y[M,N]``.
243+ 
244+ Rows of ``A`` are partitioned into ``E`` groups via ``group_list``
245+ (cumsum offsets, length ``E``). Each slice ``A[group_list[i-1]:group_list[i]]``
246+ is multiplied by ``B[i]``. ``E`` is read from ``B.shape[0]``.
247+ 
248+ Args:
249+ A: Shape ``(M, K)``.
250+ B: Shape ``(E, K, N)``.
251+ group_list: Cumulative row offsets per group, shape ``(E,)``.
252+ config_A: Config for A's (and dY's) quantization.
253+ config_B: Config for B's quantization.
254+ 
255+ Returns:
256+ Output tensor, shape ``(M, N)``, dtype matching ``A``.
257+ """
258+ return _HiF8QuantGroupedMM.apply(A, B, group_list, config_A, config_B)
@@ -12,6 +12,7 @@ by both training-time wrapper tensors and future PTQ algorithms.
12from dataclasses import dataclass, field12from dataclasses import dataclass, field
13 13 
14import torch14import torch
15+import torch_npu
15from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase16from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase
16 17 
17NPU_SUPPORTED_ELEM_DTYPES = [18NPU_SUPPORTED_ELEM_DTYPES = [
@@ -102,3 +103,24 @@ class BlockQuantizeConfig(FakeQuantizeConfigBase):
102 f"mxfp4_fake_quantize_config.elem_dtype must be FP4 (torch.float4_e2m1fn_x2), "103 f"mxfp4_fake_quantize_config.elem_dtype must be FP4 (torch.float4_e2m1fn_x2), "
103 f"got {self.mxfp4_fake_quantize_config.elem_dtype}"104 f"got {self.mxfp4_fake_quantize_config.elem_dtype}"
104 )105 )
106+ 
107+ 
108+@dataclass
109+class HiF8QuantizeConfig(FakeQuantizeConfigBase):
110+ """
111+ Config for HiF8 (``torch_npu.hifloat8``) per-tensor low-precision training.
112+ 
113+ Unlike :class:`MXQuantizeConfig`/:class:`BlockQuantizeConfig`, the underlying
114+ kernel (``torch_npu.npu_dynamic_quant(..., quant_mode="pertensor")``) has no
115+ block size, rounding mode, or scale-algorithm knobs -- the whole tensor gets
116+ one dynamically-computed scalar scale. ``elem_dtype`` is kept as a field only
117+ for symmetry with the other configs and interface uniformity; it is locked to
118+ ``torch_npu.hifloat8``, the only dtype the kernel supports.
119+ """
120+ 
121+ elem_dtype: torch.dtype = torch_npu.hifloat8
122+ 
123+ def __post_init__(self):
124+ assert self.elem_dtype == torch_npu.hifloat8, (
125+ f"For HiF8, elem_dtype must be torch_npu.hifloat8, got {self.elem_dtype}"
126+ )
@@ -6,11 +6,13 @@
6from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor6from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor
7from .block_wrapper_tensor import BlockTrainingWeightWrapperTensor7from .block_wrapper_tensor import BlockTrainingWeightWrapperTensor
8from .float8_wrapper_tensor import Float8TrainingWeightWrapperTensor8from .float8_wrapper_tensor import Float8TrainingWeightWrapperTensor
9+from .hif8_wrapper_tensor import HiF8TrainingWeightWrapperTensor
9from .mx_wrapper_tensor import MXTrainingWeightWrapperTensor10from .mx_wrapper_tensor import MXTrainingWeightWrapperTensor
10 11 
11__all__ = [12__all__ = [
12 "BaseTrainingWeightWrapperTensor",13 "BaseTrainingWeightWrapperTensor",
13 "BlockTrainingWeightWrapperTensor",14 "BlockTrainingWeightWrapperTensor",
14 "Float8TrainingWeightWrapperTensor",15 "Float8TrainingWeightWrapperTensor",
16+ "HiF8TrainingWeightWrapperTensor",
15 "MXTrainingWeightWrapperTensor",17 "MXTrainingWeightWrapperTensor",
16]18]
@@ -0,0 +1,172 @@
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 ..ops import (
13+ to_hif8_then_grouped_mm,
14+ to_hif8_then_mm,
15+)
16+from ..quantization.quant_configs import HiF8QuantizeConfig
17+from ..quantization.transform import register_parameter_swap_handler
18+from .base_wrapper_tensor import BaseTrainingWeightWrapperTensor
19+ 
20+ 
21+class HiF8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):
22+ """Applies real per-tensor HiF8 quantized matmul on NPU.
23+ 
24+ Intercepts computation ops via :meth:`__torch_function__` and performs a
25+ real per-tensor HiF8 (``torch_npu.hifloat8``) quantized matmul using
26+ ``to_hif8_then_mm`` / ``to_hif8_then_grouped_mm``. Data stays in
27+ low-precision throughout the matmul, in contrast to fake-quantize wrappers
28+ which quantize then dequantize back to high precision before the matmul.
29+ 
30+ ``weight_config`` and ``activation_config`` must be set and equal (the
31+ underlying kernel always quantizes both operands to the same dtype).
32+ """
33+ 
34+ def __init__(
35+ self,
36+ tensor: torch.Tensor,
37+ weight_config: HiF8QuantizeConfig | None = None,
38+ activation_config: HiF8QuantizeConfig | None = None,
39+ ):
40+ if weight_config is None:
41+ raise ValueError(f"`weight_config` is required for {type(self).__name__}.")
42+ 
43+ if activation_config is None:
44+ raise ValueError(f"`activation_config` is required for {type(self).__name__}.")
45+ 
46+ if not isinstance(weight_config, HiF8QuantizeConfig):
47+ raise ValueError(f"Only `HiF8QuantizeConfig` is supported for `weight_config` in {type(self).__name__}.")
48+ 
49+ if not isinstance(activation_config, HiF8QuantizeConfig):
50+ raise ValueError(
51+ f"Only `HiF8QuantizeConfig` is supported for `activation_config` in {type(self).__name__}."
52+ )
53+ 
54+ if weight_config != activation_config:
55+ raise ValueError(
56+ f"`weight_config` and `activation_config` must be equal in {type(self).__name__}, "
57+ f"got weight_config={weight_config}, activation_config={activation_config}."
58+ )
59+ 
60+ super().__init__(tensor, weight_config=weight_config, activation_config=activation_config)
61+ 
62+ @classmethod
63+ def __torch_function__(cls, func, types, args=(), kwargs=None):
64+ if kwargs is None:
65+ kwargs = {}
66+ 
67+ if func in (torch.mm, torch.matmul):
panchao-gitcode

没有BMM吗?

likedislike
nancycyzl
nancycyzl
Aug 19 Comments:
likedislike
68+ return cls._hif8_mm(args, kwargs)
69+ 
70+ elif func is torch._grouped_mm:
71+ return cls._hif8_grouped_mm(args, kwargs)
72+ 
73+ elif func is torch.nn.functional.linear:
74+ return cls._hif8_linear(args, kwargs)
75+ 
76+ elif func is torch.addmm:
77+ return cls._hif8_addmm(args, kwargs)
78+ 
79+ else:
80+ with torch._C.DisableTorchFunctionSubclass():
81+ return func(*args, **kwargs)
82+ 
83+ # ------------------------------------------------------------------
84+ # Per-op helpers
85+ # ------------------------------------------------------------------
86+ 
87+ @classmethod
88+ def _hif8_mm(cls, args, kwargs):
89+ A, B = args[0], args[1]
90+ assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
91+ assert isinstance(B, cls), f"B should be a {cls.__name__}"
92+ 
93+ B_data = unwrap_weight(B)
94+ 
95+ with torch._C.DisableTorchFunctionSubclass():
96+ return to_hif8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore
97+ 
98+ @classmethod
99+ def _hif8_grouped_mm(cls, args, kwargs):
100+ A, B = args[0], args[1]
101+ assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
102+ assert isinstance(B, cls), f"B should be a {cls.__name__}"
103+ 
104+ group_list = args[2] if len(args) > 2 else kwargs.get("offs")
105+ B_data = unwrap_weight(B)
106+ 
107+ with torch._C.DisableTorchFunctionSubclass():
108+ return to_hif8_then_grouped_mm(A, B_data, group_list, B.activation_config, B.weight_config) # type: ignore
109+ 
110+ @classmethod
111+ def _hif8_linear(cls, args, kwargs):
112+ A, B = args[0], args[1]
113+ assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
114+ assert isinstance(B, cls), f"B should be a {cls.__name__}"
115+ 
116+ B_data = unwrap_weight(B)
117+ bias = args[2] if len(args) > 2 else kwargs.get("bias")
118+ 
119+ with torch._C.DisableTorchFunctionSubclass():
120+ result = to_hif8_then_mm(A, B_data.T, B.activation_config, B.weight_config) # type: ignore
121+ if bias is not None:
122+ result = result + bias
123+ return result
124+ 
125+ @classmethod
126+ def _hif8_addmm(cls, args, kwargs):
127+ # addmm(input, mat1, mat2, *, beta=1, alpha=1) -> beta * input + alpha * (mat1 @ mat2)
128+ bias, A, B = args[0], args[1], args[2]
129+ assert not isinstance(A, cls), f"A should not be a {cls.__name__}"
130+ assert isinstance(B, cls), f"B should be a {cls.__name__}"
131+ 
132+ beta = kwargs.get("beta", 1)
133+ alpha = kwargs.get("alpha", 1)
134+ B_data = unwrap_weight(B)
135+ 
136+ with torch._C.DisableTorchFunctionSubclass():
137+ matmul = to_hif8_then_mm(A, B_data, B.activation_config, B.weight_config) # type: ignore
138+ return beta * bias + alpha * matmul
139+ 
140+ 
141+@register_parameter_swap_handler(HiF8QuantizeConfig)
142+def _(
143+ module: nn.Module,
144+ param_fqn: str,
145+ param: nn.Parameter,
146+ extra_args: tuple[Any, ...] = (),
147+):
148+ from ..configs import ParamSwapConfig
149+ 
150+ config: ParamSwapConfig = extra_args[0]
151+ 
152+ if not isinstance(config, ParamSwapConfig):
153+ raise ValueError(f"extra_args[0] must be a ParamSwapConfig, got {type(config).__name__}.")
154+ 
155+ if config.activation_config is not None and not isinstance(config.activation_config, HiF8QuantizeConfig):
156+ raise ValueError(
157+ f"activation_config must be {HiF8QuantizeConfig.__name__}, got {type(config.activation_config).__name__}."
158+ )
159+ 
160+ if config.weight_config is not None and not isinstance(config.weight_config, HiF8QuantizeConfig):
161+ raise ValueError(
162+ f"weight_config must be {HiF8QuantizeConfig.__name__}, got {type(config.weight_config).__name__}."
163+ )
164+ 
165+ return nn.Parameter(
166+ data=HiF8TrainingWeightWrapperTensor(
167+ param.data,
168+ activation_config=config.activation_config,
169+ weight_config=config.weight_config,
170+ ),
171+ requires_grad=param.requires_grad,
172+ )