Closed
[RFC] 通过 TorchAO 支持 DeepSeek-V4 模型的 HiFloat8 训练 #92
nancycyzlAdd on Jul 31Closed at Oct 7
Aug 3 Assign nancycyzl as responsible person
张德鹏
Aug 3 Comments:
Aug 3 Comments:
需求已收到,我们可以在本周的sig例会上详细讨论下这个需求的方案


caoshuyang
Aug 4 Comments:
Aug 4 Comments:
- HiFloat8与MXFP8完全不同,不应该藏在MXFP8Converter下面打patch。这样破坏了MXFP8Converter的语义。MXFP8Converter 是上游torchtitan的专为标准MXFP8格式训练做的converter。新增的格式应考虑用不同的converter。
- HiFloat8作为NPU上的独有格式,没有适配上游的需求,可以考虑单独新增代码。
- NpuQauntizeConverter在torchao_npu已经有一个实现,应该直接复用。
- HiFloat8只是一种新的8bit浮点格式,需要考虑能够直接在上游torchao的moe_training的Float8训练的支持里,直接传入hifloat8格式。如果该路径可行,可以考虑在patch里轻量化实现。


Aug 4 Modify description of issue
张德鹏
Aug 5 Comments:
Aug 5 Comments:
sig会议已经评审,评审结论如下:
- torchtitan-npu 支持使用 torchao 进行 HiFloat8 Current-Tensor Scaling 训练
(1) 后续HiF8 需要放在AO目录下,目录当前不合理,hif8.py / Linear / GMM等放在experiments/ao_npu/torchao_npu目录
(2) 当前实现框架是嵌入到mxfp8中,不合理;建议针对上游的fp8 进行patch流程进行处理;
(3) 当前只拦截实现了MM/GMM实现了低精度,后续需要补充BMM,add mm 等算子拦截处理;
(4) 后续分阶段考虑通信等性能问题


Aug 11 Modify description of issue
Aug 11 Modify description of issue
Aug 12 Associated pull request
Oct 7 changed custom state from 待办的 to 已验收
Oct 7 Close issue
Oct 7 Added label: resolved
Oct 31 Deleted associated pull request: [feat] Support HiFloat8 current-tensor scaling training with torchao
Oct 31 Deleted associated pull request: [feat] Support HiFloat8 current-tensor scaling training with torchao
HiF8 低精度训练支持
概述
简介
本提案在 torchtitan-npu 已有的低精度训练框架基础上,新增 HiF8(
torch_npu.hifloat8)作为一种新的量化后端,使 DeepSeek-V4 等大模型的普通线性层(nn.Linear)与 MoE 专家层(Grouped MM)能够在 Ascend 950 NPU 上使用 HiF8 精度进行训练。本次实现落在实验性插件子包
torchtitan_npu/experiments/ao_npu/里。HiF8 与已有的 MX、Block FP8、Float8 row-wise 一样,只是ParamSwapConfig.weight_config/activation_config可以取的又一种值,复用同一套NpuQuantizeConverter → torchao.quantize_() → 参数级 tensor-subclass 拦截链路。核心思路:
HiF8QuantizeConfig(FakeQuantizeConfigBase的叶子 dataclass),作为ParamSwapConfig.weight_config/activation_config的可选取值之一。HiF8TrainingWeightWrapperTensor(BaseTrainingWeightWrapperTensor的子类),通过register_parameter_swap_handler(HiF8QuantizeConfig)注册进参数级 handler 表;ParamSwapConfig在 prepare 阶段遇到HiF8QuantizeConfig时,用这个 wrapper 类型替换匹配参数的.data。hif8_ops.py:_HiF8QuantMM/_HiF8QuantGroupedMM两个torch.autograd.Function,用torch_npu.npu_dynamic_quant(quant_mode="pertensor")+torch_npu.npu_quant_matmul/npu_grouped_matmul实现真正的 per-tensor HiF8 量化矩乘(Linear)与分组矩乘(MoE)。HiF8TrainingWeightWrapperTensor.__torch_function__拦截到torch.mm/torch.matmul/torch._grouped_mm/F.linear/torch.addmm时调用它们。主要组件:
torchtitan_npu/experiments/ao_npu/torchao_npu/quantization/quant_configs.pyHiF8QuantizeConfig(FakeQuantizeConfigBase叶子 dataclass),唯一字段elem_dtype锁定为torch_npu.hifloat8torchtitan_npu/experiments/ao_npu/torchao_npu/wrapper_tensors/hif8_wrapper_tensor.pyHiF8TrainingWeightWrapperTensor:通过__torch_function__拦截mm/matmul/grouped_mm/linear/addmm,换成真实 HiF8 量化 kernel;同文件内register_parameter_swap_handler(HiF8QuantizeConfig)把它接入ParamSwapConfig的 prepare 流程torchtitan_npu/experiments/ao_npu/torchao_npu/ops/hif8_ops.py_HiF8QuantMM/_HiF8QuantGroupedMM(torch.autograd.Function)+ 对外的to_hif8_then_mm/to_hif8_then_grouped_mm:per-tensor HiF8 量化的 Linear/Grouped MM 正反向实现torchtitan_npu/experiments/ao_npu/torchao_npu/interfaces/torchtitan.pyNpuQuantizeConverter:把ParamSwapConfig作为base_config转交给torchao.quantize_();HiF8QuantizeConfig直接复用这条既有链路,无需新增 Convertertorchtitan_npu/experiments/ao_npu/torchao_npu/configs.pyParamSwapConfig.__post_init__的合法类型白名单加入HiF8QuantizeConfigtorchtitan_npu/experiments/ao_npu/benchmarks/e2e/dsv4_flash_single_node/config_registry.pydebug_deepseek_v4_flash_single_node_hif8_qat(),与新增的..._mxfp8_qat()结构完全对称,仅weight_config/activation_config换成HiF8QuantizeConfig动机
背景
在大规模语言模型的分布式训练中,矩阵乘法运算占据了绝大部分计算开销。传统的 BF16/FP16 混合精度训练虽然已大幅降低了显存占用,但在超大规模模型(如 DeepSeek-V4)上仍面临以下瓶颈:
torchtitan-npu 已经通过
torchao_npu的 ParamSwap 框架支持 MX 与 Block FP8 低精度训练来缓解上述瓶颈。在此基础上,Ascend 950 NPU 同时原生支持 HiF8(torch_npu.hifloat8)这一种 per-tensor 动态量化格式。本提案在 MX/Block FP8 之外,把 HiF8 kernel 接入同一套 ParamSwap 框架,作为另一种可选的 8-bit 精度训练路径。为什么使用 per-tensor scaling
_HiF8QuantMM(Linear)和_HiF8QuantGroupedMM(MoE grouped GEMM)统一都是 per-tensor 量化:整个激活/权重张量只算一个标量 scale。除了这是 HiF8 硬件/算子(npu_dynamic_quant(quant_mode="pertensor"))原生支持的量化模式之外,选择 per-tensor 粒度也是在为后续引入 delayed-tensor scaling 做铺垫:A/B,反向新出现的梯度dY,以及_HiF8QuantGroupedMM反向里对转置权重的重新量化),都要先根据它这一步的真实数值算出 scale,再执行量化。前向已量化的结果会缓存给反向复用,减少了重复量化的次数,但每一次真正发生的量化仍然依赖当前数据,必须等数据就绪才能算出 scale,排在真正的 matmul 之前,会打断计算流水线。为什么复用 ParamSwap 参数级拦截框架
torchtitan-npu 的
torchao_npu子包已经为 MX/Block FP8 建好了一整套"配置 → Converter → torchaoquantize_()→ 参数级 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的既有逻辑,也不需要任何全局可变状态。与现有方案对比
HiF8QuantizeConfig/HiF8TrainingWeightWrapperTensor(本提案采用)NpuQuantizeConverter/ParamSwapConfig现成的 prepare/convert 生命周期、FQN 过滤器、FSDP2 支持;HiF8 与 MX/Block FP8 通过同一ParamSwapConfig混合/替换配置,无需全局状态;新增代码只有独立的 config/wrapper/kernel 三个文件torchao的QATConfig/tensor-subclass 拦截机制,其行为演进需要跟随torchao版本ModelConvertersContainer配置体系脱节,无法复用 FQN 匹配、quantize_()等基础设施核心设计
架构
关键设计决策
NpuQuantizeConverterParamSwapConfig的又一种weight_config/activation_config取值,Converter 层逻辑与具体量化算法无关nn.Parameter.data,不替换nn.Linear模块本身BaseTrainingWeightWrapperTensor基础设施,不需要为 HiF8 单独实现这些机制weight_config/activation_config是否可分别配置HiF8TrainingWeightWrapperTensor.__init__强制二者都必须提供且相等npu_dynamic_quant/npu_quant_matmul)始终把两个操作数量化到同一 dtype,允许二者不一致没有实际意义,提前用ValueError拦截配置错误详细设计
1. 量化配置:
HiF8QuantizeConfigtorchtitan_npu/experiments/ao_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__锁死为唯一取值。torchtitan_npu/experiments/ao_npu/torchao_npu/configs.py里的ParamSwapConfig.__post_init__相应把HiF8QuantizeConfig加入activation_config/weight_config的合法类型白名单。2. 参数级拦截:
HiF8TrainingWeightWrapperTensortorchtitan_npu/experiments/ao_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.pytorchtitan_npu/experiments/ao_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(torchtitan_npu/experiments/ao_npu/torchao_npu/interfaces/torchtitan.py,已有实现,本次不改)负责把ParamSwapConfig转交给torchao.quantize_(model, base_config, filter_fn)。对 HiF8 而言,使用方式与已有的 MX/Block FP8 完全一致,只是把weight_config/activation_config换成HiF8QuantizeConfig()实例:NpuQuantizeConverter.Config( base_config=ParamSwapConfig( weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig(), ), filter_fn=any_filter(is_attention, is_shared_expert, is_routed_expert, match_fqn_suffix(".e_proj", ".h_proj")), )配置与使用
依赖版本
masterv0.17.0npu_dynamic_quant(dst_type=torch_npu.hifloat8, quant_mode="pertensor")、npu_quant_matmul、npu_grouped_matmul等算子的版本,与 CANN 版本匹配hifloat8硬件支持)配置方式
在模型的
config_registry.py中,给model_converters追加一个NpuQuantizeConverter.Config,base_config用ParamSwapConfig(weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig())。以torchtitan_npu/experiments/ao_npu/benchmarks/e2e/dsv4_flash_single_node/config_registry.py中新增的debug_deepseek_v4_flash_single_node_hif8_qat()为例:def debug_deepseek_v4_flash_single_node_hif8_qat() -> TrainerConfig: base = debug_deepseek_v4_flash_single_node() return replace( base, model_converters=ModelConvertersContainer.Config( converters=base.model_converters.converters + [ NpuQuantizeConverter.Config( base_config=ParamSwapConfig( weight_config=HiF8QuantizeConfig(), activation_config=HiF8QuantizeConfig(), ), filter_fn=any_filter( is_attention, is_shared_expert, is_routed_expert, match_fqn_suffix(".e_proj", ".h_proj"), ), ), ] ), )该函数与同文件新增的
debug_deepseek_v4_flash_single_node_mxfp8_qat()(全量 MX)结构完全对称,只有weight_config/activation_config的 config 类型不同,方便做 HiF8 vs MXFP8 的对照实验。HiF8QuantizeConfig配置项elem_dtypetorch.dtypetorch_npu.hifloat8__post_init__强制锁定为该值,实际不可配置,保留只是为了与MXQuantizeConfig/BlockQuantizeConfig接口一致ParamSwapConfig相关字段(weight_config/activation_config/params_filter_fn)沿用已有定义,HiF8 场景下weight_config/activation_config必须都传且相等,否则HiF8TrainingWeightWrapperTensor.__init__会raise ValueError。验证清单
torchtitan_npu/experiments/ao_npu/tests/ops/test_hif8_ops.py覆盖_HiF8QuantMM/_HiF8QuantGroupedMM正反向的数值正确性;tests/wrapper_tensors/test_hif8_wrapper_tensor.py覆盖__torch_function__拦截逻辑与register_parameter_swap_handler接入;tests/test_param_swap_config.py覆盖ParamSwapConfig对HiF8QuantizeConfig的类型校验。三者均已纳入tests/test_everything.sh。Parameter quantize active with base_config=ParamSwapConfig(来自NpuQuantizeConverter.__init__)及Applied parameter quantize wrapping (prepare step)(来自NpuQuantizeConverter.convert)。filter_fn/params_filter_fn命中范围内抽查若干参数,确认其.data类型为HiF8TrainingWeightWrapperTensor而非普通 tensor。premerge-accuracy-checkskill,对比 HiF8 与 BF16/MXFP8 基线的 loss、grad_norm 曲线。兼容性
与 torchtitan / torchao 上游的兼容性
HiF8QuantizeConfig/HiF8TrainingWeightWrapperTensor不修改上游代码,完全依托torchao的QATConfig/quantize_()/tensor-subclass(__torch_function__/__torch_dispatch__)机制与 torchtitan 的ModelConvertersContainer/QuantizationConverter协议。这些是torchao_npu已有基础设施承担的兼容性面,HiF8 本身不引入新的上游依赖点。与 MX / Block FP8 / Float8 的关系
四者(MX、Block FP8、Float8 row-wise、HiF8)都是
ParamSwapConfig.weight_config/activation_config的可选取值,通过_PARAM_SWAP_QUANTIZE_CONFIG_HANDLER类型 → handler 注册表区分实现,彼此独立、不互斥。同一个模型可以给不同NpuQuantizeConverter.Config(不同filter_fn命中的 FQN 范围)配不同的量化 backend,如 attention/shared-expert 用 MX、routed experts 用 Block FP8,比如debug_deepseek_v4_flash_single_node_qat()已是这种混合配置的实例。与 NPU 硬件的兼容性
npu_dynamic_quant/hifloat8相关算子支持)风险与缓解
QATConfig/tensor-subclass 拦截机制变更ParamSwapConfig/BaseTrainingWeightWrapperTensor的既有假设失效,MX/Block FP8/HiF8 三条路径同时受影响