Closed
[RFC] 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练 #117
NIKI1205Add on  Sep 9Closed at  Oct 20
NIKI1205
NIKI1205
Sep 9 Create

Thanks for sending a requirement! Please fill in the following template to help quickly solve your problem.

Background / 背景信息

HiF8 低精度训练支持

概述

简介

本提案在 torchtitan-npu 已有的低精度训练框架基础上,新增 HiF8(torch_npu.hifloat8)作为一种新的量化后端,使 DeepSeek-V4 等大模型的普通线性层(nn.Linear)与 MoE 专家层(Grouped MM)能够在 Ascend 950 NPU 上使用 HiF8 精度进行训练。

本次实现基于当前 master 的代码架构进行适配。HiF8 与已有的 MX、Block FP8、Float8 row-wise 一样,复用 torchao_npu 已有的低精度训练能力,并适配当前 master 的配置和插件机制。

核心思路:

  • 新增 HiF8QuantizeConfig,作为 HiF8 低精度训练的量化配置。
  • 新增 HiF8 Training Weight Wrapper,通过参数级 tensor-subclass 拦截方式,将匹配参数的计算替换为 HiF8 计算。
  • 新增 HiF8 ops:使用 torch_npu.npu_dynamic_quant(quant_mode="pertensor") + torch_npu.npu_quant_matmul / npu_grouped_matmul 实现真正的 per-tensor HiF8 量化矩乘(Linear)与分组矩乘(MoE)。
  • Linear 层与 MoE 专家层的 HiF8 量化统一都是 per-tensor 动态量化(区别于已有 MXFP8/Block FP8 的 per-block 量化)。
  • 在当前 master 的配置架构下接入 DeepSeek-V4 HiF8 训练配置。

主要组件:

组件 路径 职责
量化配置 experiments/torchao-npu/torchao_npu/configs.py HiF8QuantizeConfig:HiF8 量化配置,elem_dtype 锁定为 torch_npu.hifloat8
参数级拦截 Wrapper experiments/torchao-npu/torchao_npu/wrapper_tensors/hif8_wrapper_tensor.py HiF8TrainingWeightWrapperTensor:通过 __torch_function__ 拦截 mm / matmul / grouped_mm / linear / addmm 等计算并替换为真实 HiF8 kernel
HiF8 量化 kernel experiments/torchao-npu/torchao_npu/ops/hif8_ops.py HiF8MMFunction / HiF8GroupedMMFunction:完成 per-tensor HiF8 量化的 Linear / Grouped MM 正反向
TorchTitan 接口 experiments/torchao-npu/torchao_npu/interfaces/torchtitan.py 复用 NpuQuantizeConverter,把 ParamSwapConfig 接入 TorchTitan 模型转换流程
Config 接入 torchtitan_npu/models/deepseek_v4/config_registry.py 在当前 master 的 DeepSeek-V4 config 中接入 HiF8 current-tensor scaling 配置

动机

背景

在大规模语言模型的分布式训练中,矩阵乘法运算占据了绝大部分计算开销。传统的 BF16/FP16 混合精度训练虽然已大幅降低了显存占用,但在超大规模模型(如 DeepSeek-V4)上仍面临以下瓶颈:

  • 计算吞吐受限:BF16 矩阵乘无法充分利用 NPU 的 FP8 专用计算单元(Cube Core),导致硬件算力未完全释放。
  • 显存带宽压力:BF16 参数的显存占用是 FP8 的两倍,在超大模型场景下成为训练速度的关键瓶颈。
  • 通信开销:BF16 梯度/参数的通信量是 FP8 的两倍,在多卡/多节点训练中影响扩展效率。

torchtitan-npu 已经通过 torchao_npu 支持 MX 与 Block FP8 低精度训练来缓解上述瓶颈。在此基础上,Ascend 950 NPU 同时原生支持 HiF8(torch_npu.hifloat8)这一种 per-tensor 动态量化格式。本提案在 MX/Block FP8 之外,把 HiF8 kernel 接入现有 torchao_npu 低精度训练框架,作为另一种可选的 8-bit 精度训练路径。

为什么复用 ParamSwap 参数级拦截框架

torchtitan-npu 的 torchao_npu 子包已经为 MX/Block FP8 建好了一整套“配置 → Converter → torchao quantize_() → 参数级 tensor-subclass 拦截”链路(ParamSwapConfig + NpuQuantizeConverter + BaseTrainingWeightWrapperTensor)。HiF8 要解决的问题(“用另一种量化 dtype/kernel 替换 Linear 与 grouped-mm 里的矩乘”)和 MX/Block FP8 完全同构,差别只在于:

  • 量化粒度是 per-tensor,不是 per-block(无 block_size/round_mode/scale_alg 等 block 相关配置项)。
  • 底层 kernel 换成 torch_npu.npu_dynamic_quant(quant_mode="pertensor") + npu_quant_matmul/npu_grouped_matmul,而不是 MX 系列 kernel。

这两点差异可以用“新增一个 FakeQuantizeConfigBase 子类 + 新增一个 BaseTrainingWeightWrapperTensor 子类”来表达:

  • NpuQuantizeConverter 本身只是把 base_config(ParamSwapConfig 实例)转交给 torchao.quantize_(),与具体量化算法无关,天然对 HiF8 复用。
  • ParamSwapConfig 的 prepare/convert 两步流程(wrap 参数 → 训练 → unwrap 参数)也与具体量化算法无关,只需要把 HiF8QuantizeConfig 加入其 __post_init__ 的合法类型白名单。
  • 真正 HiF8 特有的逻辑(per-tensor 量化 kernel、__torch_function__ 拦截哪些 op)完全封装在 HiF8QuantizeConfig + HiF8TrainingWeightWrapperTensor + hif8_ops.py 三个新文件里,通过 register_parameter_swap_handler 这个类型 → handler 的注册表机制接入,不需要碰 NpuQuantizeConverter/ParamSwapConfig 的既有逻辑,也不需要任何全局可变状态。

与现有方案对比

方案 优势 劣势
接入 ParamSwap 框架,新增 HiF8QuantizeConfig/HiF8TrainingWeightWrapperTensor(本提案采用) 复用 NpuQuantizeConverter/ParamSwapConfig 现成的 prepare/convert 生命周期、FQN 过滤器、FSDP2 支持;HiF8 与 MX/Block FP8 通过同一 ParamSwapConfig 混合/替换配置,无需全局状态;新增代码只有独立的 config/wrapper/kernel 三个文件 依赖 torchao 的 QATConfig/tensor-subclass 拦截机制,其行为演进需要跟随 torchao 版本
直接在模型/训练代码里调用 HiF8 算子(无 Converter/wrapper) 无需理解 torchao 拦截机制 与 torchtitan 上游的 ModelConvertersContainer 配置体系脱节,无法复用 FQN 匹配、quantize_() 等基础设施

核心设计

架构

训练启动(TrainerEx quantization extension,recipe="all_hif8")
    │
    ▼
NpuQuantizeConverter 根据 recipe 构造 HiF8 ParamSwapConfig
    │
    └── ParamSwapConfig(weight_config=HiF8QuantizeConfig(),activation_config=HiF8QuantizeConfig(),)
    │
    ▼
NpuQuantizeConverter 遍历模型 config tree
    ├── Linear.Config
    ├── BatchedLinear.Config
    └── GroupedExperts.Config
    │
    ▼
filter_fn 按 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.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,))
(权重被替换成 wrapper tensor 子类, 训练循环里其余代码无感知)
        │
        ▼
训练前向/反向:nn.Linear(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._grouped_mm                                              → to_hif8_then_grouped_mm(x, weight, offs, ...)
                        └──  torch_npu.npu_dynamic_quant(quant_mode="pertensor" )
                                 + torch_npu.npu_quant_matmul /torch_npu.npu_grouped_matmul
                                 ← experiments/torchao-npu/torchao_npu/ops/hif8_ops.py

关键设计决策

决策 选择 理由
是否新增 Converter 不新增;复用已有的 NpuQuantizeConverter HiF8 只是 ParamSwapConfig 的又一种 weight_config/activation_config 取值,Converter 层逻辑与具体量化算法无关
量化粒度 Linear、MoE grouped MM 统一用 per-tensor 量化 统一 per-tensor 为后续引入 delayed-tensor scaling 做铺垫(详见「为什么使用 per-tensor scaling」)
参数级拦截 vs 模块级替换 沿用 ParamSwap 现有设计:wrap nn.Parameter.data,不替换 nn.Linear 模块本身 与 MX/Block FP8 共用同一套 BaseTrainingWeightWrapperTensor 基础设施,不需要为 HiF8 单独实现这些机制
weight_config/activation_config 是否可分别配置 HiF8TrainingWeightWrapperTensor.__init__ 强制二者都必须提供且相等 底层 kernel(npu_dynamic_quant/npu_quant_matmul)始终把两个操作数量化到同一 dtype,允许二者不一致没有实际意义,提前用 ValueError 拦截配置错误

Design / 设计方案(选填)

详细设计

1. 量化配置:HiF8QuantizeConfig

experiments/torchao-npu/torchao_npu/quantization/quant_configs.py 新增:

@dataclass
class HiF8QuantizeConfig(FakeQuantizeConfigBase):
    elem_dtype: torch.dtype = torch_npu.hifloat8

    def __post_init__(self):
        assert self.elem_dtype == torch_npu.hifloat8, (
            f"For HiF8, elem_dtype must be torch_npu.hifloat8, got {self.elem_dtype}"
        )

与 MXQuantizeConfig/BlockQuantizeConfig 相比,没有 block_size/round_mode/scale_alg/dst_type_max 等字段。底层 npu_dynamic_quant(quant_mode="pertensor") 没有这些旋钮,整个张量只算一个动态标量 scale。elem_dtype 字段只是为了与其他 config 保持接口一致,实际被 __post_init__ 锁死为唯一取值。

experiments/torchao-npu/torchao_npu/configs.py 里的 ParamSwapConfig.__post_init__ 相应把 HiF8QuantizeConfig 加入 activation_config/weight_config 的合法类型白名单。

2. 参数级拦截:HiF8TrainingWeightWrapperTensor

experiments/torchao-npu/torchao_npu/wrapper_tensors/hif8_wrapper_tensor.py 新增 HiF8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor):

  • 构造时要求 weight_config/activation_config 都必须是 HiF8QuantizeConfig 且相等,否则 raise ValueError。

  • 重写 __torch_function__,处理 5 个计算类 op,其余透传给基类(基类会关闭拦截、下沉到 __torch_dispatch__ 保持 wrapper 身份不变):

    • torch.mm/torch.matmul → _hif8_mm:直接调用 to_hif8_then_mm(A, B_data, ...)。
    • torch._grouped_mm → _hif8_grouped_mm:从参数里取 offs,调用 to_hif8_then_grouped_mm(A, B_data, offs, ...)。
    • torch.nn.functional.linear → _hif8_linear:权重需要 .T 后再传给 to_hif8_then_mm(nn.Linear 权重是 [out, in] 布局),bias 可选。
    • torch.addmm → _hif8_addmm:bias 必需且在参数最前,权重不转置。
  • 文件末尾用 @register_parameter_swap_handler(HiF8QuantizeConfig) 注册一个函数:接收 (module, param_fqn, param, extra_args),从 extra_args[0](ParamSwapConfig)取出 weight_config/activation_config,构造 HiF8TrainingWeightWrapperTensor 包裹原参数,返回新的 nn.Parameter。这一步把 HiF8 接入了 ParamSwapConfig 的 prepare 阶段(_param_swap_config_transform 按 type(config.weight_config) 查表分派到这个 handler)。

3. HiF8 量化 Kernel:hif8_ops.py

experiments/torchao-npu/torchao_npu/ops/hif8_ops.py 实现两个 torch.autograd.Function:

  • _HiF8QuantMM:前向把 A/B 各自 npu_dynamic_quant(quant_mode="pertensor") 量化为 HiF8 + 标量 scale,再用 npu_quant_matmul 计算,并把量化后的 A_q/A_s/B_q/B_s 一并存入 ctx 供反向复用;反向直接复用这四个已量化的 tensor(B_q.t() 做转置即可参与输入梯度 dA 的计算,因为 per-tensor scale 是整张量共享的标量,不受转置影响),不需要重新量化 A/B,只对新出现的梯度 dY 现场量化一次。
  • _HiF8QuantGroupedMM:前向把 A/B 各自量化后用 npu_grouped_matmul 计算,ctx 里保存量化后的 A_q/A_s,配上未量化的原始 B;反向中 A_q/A_s 直接复用、dY 现场量化,B 侧需要对 B.transpose(-1, -2) 重新做一次 npu_dynamic_quant 得到 B_t_q/B_t_s 供计算输入梯度 dA 使用。

4. 接入 Converter 链路

NpuQuantizeConverter 负责在模型构建前遍历 config tree,将匹配的 Linear.Config/BatchedLinear.Config/GroupedExperts.Config 替换为对应的 NpuQuantizedModule.Config,模块实例化时再通过 torchao.quantize_() 应用 ParamSwapConfig。

对 HiF8 而言,仍然复用已有的 NpuQuantizeConverter,只是把 weight_config/activation_config 换成 HiF8QuantizeConfig():

def _hif8_param_swap() -> ParamSwapConfig:
    hif8_config = HiF8QuantizeConfig()
    return ParamSwapConfig(
        weight_config=hif8_config,
        activation_config=hif8_config,
    )

HiF8 通过 all_hif8 recipe 接入:

if recipe == "all_hif8":
    return [
        _quantization_converter(
            _hif8_param_swap(),
            any_config_filter(dense_filter, is_routed_expert),
            ...
        )
    ]

相比旧 master,本次主要调整 NpuQuantizeConverter 的接入时机和配置方式;ParamSwapConfig、HiF8TrainingWeightWrapperTensor 及 HiF8 kernel 的实现保持不变。

配置与使用

依赖版本

组件 版本要求
torchtitan-npu master
torchao v0.17.0
torch_npu 支持 npu_dynamic_quant(dst_type=torch_npu.hifloat8, quant_mode="pertensor")、npu_quant_matmul、npu_grouped_matmul 等算子的版本,与 CANN 版本匹配
NPU 硬件 Ascend 950(提供 hifloat8 硬件支持)

配置方式

当前 master 通过 TrainerEx quantization extension 的 recipe 配置低精度训练。

HiF8 使用 all_hif8 recipe:

recipe = "all_hif8"

all_hif8 内部构造:

ParamSwapConfig(
    weight_config=HiF8QuantizeConfig(),
    activation_config=HiF8QuantizeConfig(),
)

并通过 NpuQuantizeConverter 将 HiF8 配置应用到匹配的 Linear / routed expert config。

与旧 master 中直接在 config_registry.py 的 model_converters 中追加 NpuQuantizeConverter.Config 相比,本次只调整配置接入方式,HiF8 的 quantization config、wrapper 和 kernel 实现保持不变。

HiF8QuantizeConfig 配置项

配置项 类型 默认值 说明
elem_dtype torch.dtype torch_npu.hifloat8 唯一字段,且 __post_init__ 强制锁定为该值,实际不可配置,保留只是为了与 MXQuantizeConfig/BlockQuantizeConfig 接口一致

ParamSwapConfig 相关字段(weight_config/activation_config/params_filter_fn)沿用已有定义,HiF8 场景下 weight_config/activation_config 必须都传且相等,否则 HiF8TrainingWeightWrapperTensor.__init__ 会 raise ValueError。

验证清单

  1. 单元测试:experiments/torchao-npu/tests/ops/test_hif8_ops.py 覆盖 _HiF8QuantMM/_HiF8QuantGroupedMM 正反向的数值正确性;experiments/torchao-npu/tests/wrapper_tensors/test_hif8_wrapper_tensor.py 覆盖 __torch_function__ 拦截逻辑与 register_parameter_swap_handler 接入;对应 quantization config 测试覆盖 HiF8QuantizeConfig/ParamSwapConfig 的配置校验。
  2. 确认 all_hif8 recipe 生效:启动 HiF8 配置后,NpuQuantizeConverter 能够匹配目标 Linear.Config / BatchedLinear.Config / GroupedExperts.Config 并完成 config replacement。
  3. 确认命中的模块/参数:模型实例化后抽查对应 Linear / routed expert,确认目标参数进入 HiF8 wrapper 计算路径。
  4. 数值/性能验证:参照仓库 premerge-accuracy-check skill,对比 HiF8 与 BF16/MXFP8 基线的 loss、grad_norm 曲线。

兼容性

与 torchtitan / torchao 上游的兼容性

HiF8QuantizeConfig/HiF8TrainingWeightWrapperTensor 不修改上游代码,完全依托 torchao 的 QATConfig/quantize_()/tensor-subclass(__torch_function__/__torch_dispatch__)机制。当前 master 通过配置级 override,在模型 build 前由 NpuQuantizeConverter 对匹配的 config 进行替换,并在模块实例化过程中安装 torchao-npu wrapper。这些是 torchao_npu 已有基础设施承担的兼容性面,HiF8 本身不引入新的上游依赖点。

与 MX / Block FP8 / Float8 的关系

四者(MX、Block FP8、Float8 row-wise、HiF8)仍然通过各自的 quantization config 区分实现,彼此独立、不互斥。HiF8 仍然使用 ParamSwapConfig(weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig()) 接入参数级 wrapper;当前 master 通过 recipe 统一组织不同低精度训练方案,HiF8 对应 all_hif8 recipe。

与 NPU 硬件的兼容性

硬件 支持状态
Ascend 950 ✅ 完全支持
Ascend 910B/C ❌ 不支持(无 npu_dynamic_quant/hifloat8 相关算子支持)

风险与缓解

风险 影响 缓解措施
torchao QATConfig/tensor-subclass 拦截机制变更 ParamSwapConfig/BaseTrainingWeightWrapperTensor 的既有假设失效,MX/Block FP8/HiF8 三条路径同时受影响 在 CI 中增加 torchao 版本兼容性测试;HiF8 与 MX/Block FP8 共用同一基础设施,风险发生时影响面已知且可统一排查
NPU 算子精度差异 per-tensor HiF8 使用低精度训练,可能导致训练 loss 偏离 提供精度对比工具,与 BF16 基线对照
内存开销 HiF8 量化不减少显存占用(权重仍以原始精度存储,仅计算时量化) 明确说明当前为计算精度优化,非显存优化
likedislike
NIKI1205NIKI1205
Sep 9 Modify description of issue
NIKI1205NIKI1205
Sep 9 Change title to "[Requirement|需求建议]: 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练", originally titled "[Requirement|需求建议]: ".
NIKI1205NIKI1205
Sep 9 Change title to "[RFC]: 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练", originally titled "[Requirement|需求建议]: 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练".
NIKI1205NIKI1205
Sep 9 Change title to "[RFC] 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练", originally titled "[RFC]: 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练".
NIKI1205NIKI1205
Sep 9 Associated pull request
hanboyou
hanboyouCollaborators
Sep 9 Comments:

感谢提出RFC,欢迎贡献torchtitan-npu!

likedislike
hanboyou
hanboyouCollaborators
Oct 20 Comments:

感谢提案。经核对当前 origin/master,通过 TorchAO 接入 HiF8 的能力已经落地在 experiments/torchao-npu/:

  • 量化配置:torchao_npu/quantization/quant_configs.py 中的 HiF8QuantizeConfig(elem_dtype = torch_npu.hifloat8,per-tensor 动态量化)。
  • HiF8 算子:torchao_npu/ops/hif8_ops.py,按方案使用 torch_npu.npu_dynamic_quant(quant_mode="pertensor") + npu_quant_matmul / npu_grouped_matmul 实现 Linear 与 MoE 分组矩乘。
  • Wrapper:torchao_npu/wrapper_tensors/hif8_wrapper_tensor.py;量化原语:torchao_npu/quantization/quant_primitives/hif8.py。
  • DeepSeek-V4 接入:torchao_npu/configs/module_swap_configs/deepseek_v4/... 与 configs/param_swap.py。
  • 测试:tests/ops/test_hif8_ops.py、tests/wrapper_tensors/test_hif8_wrapper_tensor.py、tests/configs/test_param_swap.py 等。

关联 MR #765 已关闭且未合入,该能力已以当前结构落地。按已完成关闭。

likedislike
hanboyouhanboyouCollaborators
Oct 20 Close issue
刘原辰刘原辰Collaborators
Oct 31 Assign NIKI1205 as responsible person
刘原辰刘原辰Collaborators
Oct 31 Associated pull request
刘原辰刘原辰Collaborators
Oct 31 Deleted associated pull request: 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练
刘原辰
刘原辰Collaborators
Oct 31 Comments:
CANN-robotCANN-robotCollaborators
Oct 31 Added label: resolved