Merged
[feat] Support Deepseek v4 HiFloat8 current-tensor scaling training through TorchAO #925
[feat] Support Deepseek v4 HiFloat8 current-tensor scaling training through TorchAO #925
Merged
nancycyzlAdd on Sep 23
nancycyzl
nancycyzl
Sep 23

描述

本提案在 torchtitan-npu 已有的低精度训练框架基础上,新增 HiF8(torch_npu.hifloat8)作为一种新的量化后端,采用 current/constant tensor scaling(CTS:每次调用都通过 npu_dynamic_quant 现算 scale,不做任何跨 step、跨调用的 scale 持久化),使 DeepSeek-V4 系列模型的普通线性层(nn.Linear / BatchedLinear)与 MoE 专家层(Grouped MM)能够在 Ascend NPU 上使用 HiF8 精度进行训练。

本次实现落在实验性插件子包 experiments/torchao-npu/ 里。HiF8 与已有的 MX、Block FP8、Float8 row-wise 一样,只是 ParamSwapConfig.weight_config/activation_config 可以取的又一种值,复用同一套 NpuQuantizeConverter → torchao.quantize_() → 参数级 tensor-subclass 拦截 链路;训练脚本只需通过 --extension.quantization.recipe all_hif8 切换 recipe,模型代码无需改动。

HiF8QuantizeConfig 同时也是 Lightning Indexer(LI)Q/K 量化沿用的配置类(quant_mode 可以是 pertoken/pertensor/perchannel),dense/MoE 这条链路只使用 quant_mode="pertensor" 的场景,并在 HiF8TrainingWeightWrapperTensor 构造时显式校验这一点,避免把非 per-tensor 配置误接到这条只支持单一标量 scale 的链路上。

实现逻辑

训练启动(TrainerEx quantization extension,recipe="all_hif8")
    │
    ▼
NpuQuantizeConverter 根据 recipe 构造 HiF8 ParamSwapConfig
    │
    └── _hif8_param_swap() → ParamSwapConfig(weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig())
    │   ← interfaces/torchao_converter.py
    ▼
NpuQuantizeConverter 遍历模型 config tree
    ├── Linear.Config
    ├── BatchedLinear.Config      (attention 中的 batched 投影,走 BMM 路径)
    └── GroupedExperts.Config     (MoE routed experts,走 GroupedMM 路径)
    │
    ▼
filter_fn = any_config_filter(dense_filter, filters["routed_expert"]) 按 config/FQN 匹配目标模块
    │
    ▼
将匹配的 config 替换为 NpuQuantizedModule.Config
    │
    ▼
模型构建时实例化 NpuQuantizedModule
    │
    └── torchao.quantize_(module, base_config=ParamSwapConfig(...))
        │
        ▼
register_quantize_module_handler(ParamSwapConfig) 注册的
_param_swap_config_transform                                              ← experiments/torchao-npu/torchao_npu/configs/param_swap.py
        │ (QATStep.PREPARE)
        ├── handler = _PARAM_SWAP_QUANTIZE_CONFIG_HANDLER[type(config.weight_config)]
        │   = register_parameter_swap_handler(HiF8QuantizeConfig) 注册的函数
        │ ← experiments/torchao-npu/torchao_npu/wrapper_tensors/hif8_wrapper_tensor.py
        ▼
_replace_params_with_custom_fn_if_matches_filter(module, handler, config.params_filter_fn, extra_args=(config,))
(params_filter_fn 默认 _is_parameter;extra_args 把 config 传给 handler,供其取出 weight_config / activation_config)
        │
        ▼
module.weight = nn.Parameter(
    HiF8TrainingWeightWrapperTensor(weight, weight_config, activation_config))
(构造时校验 weight_config == activation_config 且 quant_mode == "pertensor";权重被替换成 wrapper tensor 子类,训练循环里其余代码无感知)
        │
        ▼
训练前向/反向:nn.Linear(x, weight) / torch.bmm(x, weight) / grouped_mm(x, weight, offs)
        │
        └── HiF8TrainingWeightWrapperTensor.__torch_function__ 拦截
                ├── F.linear / torch.addmm / torch.mm / torch.matmul → to_hif8_then_mm(x, weight, ...)
                ├── torch.bmm                                        → to_hif8_then_bmm(x, weight, ...)
                └── torch._grouped_mm                                → to_hif8_then_grouped_mm(x, weight, offs, ...)
                        │  ← experiments/torchao-npu/torchao_npu/ops/hif8_ops.py
                        ▼
                    quantize_hifloat8_pertensor(tensor, config)        ← experiments/torchao-npu/torchao_npu/quantization/quant_primitives/hif8.py
                        │
                        ▼
                    torch_npu.npu_dynamic_quant(quant_mode="pertensor")
                    + torch_npu.npu_quant_matmul / torch_npu.npu_grouped_matmul

类型

Checklist

如何测试

使用--extension.quantization.recipe all_hif8

4k 性能结果:

metric                         mxfp8_4k        hif8_cts_4k    rel diff (b-a)/a
---------------------------------------------------------------------------------------
loss                            11.60767          11.58098             -0.23%
grad_norm                      151.95404         143.65409             -5.46%
memory                          54.44000          53.35571             -1.99%
tps                           1921.71429        1984.42857              3.26%
tflops                         167.31524         172.78810              3.27%
mfu                             34.42762          35.55286              3.27%
elapsed_time_per_step           17.05300          16.51400             -3.16%

8k 性能结果:

metric                         mxfp8_8k          hif8_cts_8k    rel diff (b-a)/a
----------------------------------------------------------------------------------------
loss                            11.42677          11.38635             -0.35%
grad_norm                      162.14048         193.44850             19.31%
memory                          77.01000          75.49000             -1.97%
tps                           2273.42857        2346.71429              3.22%
tflops                         200.92571         207.39476              3.22%
mfu                             41.34238          42.67381              3.22%
elapsed_time_per_step           28.82671          27.92757             -3.12%
likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for nancycyzl's contribution.)
nancycyzlnancycyzl
Sep 23 Created pull request, commit a7c42678
atomgit-bot
atomgit-botCollaborators
Sep 23 Comments:

变更摘要

本变更在 experiments/torchao-npu/ 插件子包中新增 HiF8(torch_npu.hifloat8)量化后端,采用 current/constant tensor scaling(CTS,每次调用通过 npu_dynamic_quant 现算 scale,不持久化跨 step 的 scale),使 DeepSeek-V4 系列模型的普通线性层与 MoE 专家层可在 Ascend NPU 上以 HiF8 精度训练。HiF8 作为 ParamSwapConfig.weight_config/activation_config 的又一种取值,复用既有 NpuQuantizeConverter → torchao.quantize_() → 参数级 tensor-subclass 拦截链路;训练侧通过新增 recipe all_hif8 切换,模型代码无需改动。

主要改动

  • 新增 all_hif8 recipe 与配置类型: 在 interfaces/torchao_converter.py 的 _SUPPORTED_RECIPES 与 torchtitan_npu/config/configs.py 的 QuantizationRecipe 中加入 all_hif8,并在 _recipe_converters 中新增分支,用 _hif8_param_swap() 构造 ParamSwapConfig,经 any_config_filter(dense_filter, filters["routed_expert"]) 匹配 dense 与 routed expert 模块。
  • 新增 HiF8 量化算子与量化原语: 新增 ops/hif8_ops.py,提供 to_hif8_then_mm、to_hif8_then_bmm、to_hif8_then_grouped_mm 三个基于 torch.autograd.Function 的算子(分别走 npu_quant_matmul/npu_grouped_matmul);新增 quantize_hifloat8_pertensor,通过降序 stride 置换避免非稠密输入的隐式拷贝,并断言 quant_mode == "pertensor"。
  • 新增 HiF8 参数包装张量: 新增 HiF8TrainingWeightWrapperTensor,在 __torch_function__ 中拦截 F.linear/torch.addmm/torch.mm/torch.matmul/torch.bmm/torch._grouped_mm 分派到对应算子,构造时校验 weight_config/activation_config 均为 HiF8QuantizeConfig、quant_mode == "pertensor" 且二者相等,并注册 register_parameter_swap_handler 完成参数替换。
  • 扩展 ParamSwapConfig 与 HiF8QuantizeConfig 校验/文档: ParamSwapConfig 接受 HiF8QuantizeConfig 作为 weight/activation 配置(更新相应报错文案),HiF8QuantizeConfig 补充说明其同时服务 Lightning Indexer Q/K 量化与 dense/MoE per-tensor 链路两种调用场景。
  • 新增选择性激活检查点的保存算子开关: 在 interfaces/torchao_converter.py 中新增 _save_quant_codes_under_selective_ac(HIF8_SAVE_QUANT_CODES)与 _save_block_ops_under_selective_ac(KIWI_SAVE_BLOCK_OPS),通过包装 torchtitan 的 _get_default_save_ops 将量化 GEMM 算子或 attention/mHC/MoE-routing 算子加入 selective-AC 保存列表,默认关闭。
likedislike
Incorrect?
atomgit-bot
atomgit-botCollaborators
Sep 23 Comments:

代码审查

✅ 未发现问题

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
Sep 23 Added label: stat/needs-squash
CANN-robotCANN-robotCollaborators
Sep 23 Added label: cann-cla/yes
160 messages are collapsed here。 See more
刘原辰刘原辰Collaborators
Oct 31 Associated issue: [RFC] HiF8 delayed scaling 在 torchtitan-npu 中的实现方案——基于延迟历史幅度统计的动态量化缩放
CANN-robot
CANN-robotCollaborators
Oct 31 Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike
刘原辰刘原辰Collaborators
Oct 31 Deleted associated issue: [RFC] HiF8 delayed scaling 在 torchtitan-npu 中的实现方案——基于延迟历史幅度统计的动态量化缩放
刘原辰刘原辰Collaborators
Oct 31 Associated issue: [RFC] 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练
CANN-robot
CANN-robotCollaborators
Oct 31 Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike