已合并
【Feature】【资料】适配【量化算子】类型精度比较 #628
【Feature】【资料】适配【量化算子】类型精度比较 #628
已合并
shuhuipeng创建于 5月8日
shuhuipeng
shuhuipeng
5月8日

int8类型的量化算子 精度对比修复总结

【背景】量化整形算子不能用二进制方法对比

1. 量化算子的特点

在深度学习模型中,量化是一种重要的模型压缩技术,特别是 int8 量化被广泛应用于:

  • 减少内存占用:int8 占用 1 字节,相比 float32 减少 75% 内存
  • 提高计算速度:NPU 对 int8 有专门的硬件加速
  • 保持模型精度:int8 量化对模型精度损失较小

2. 华为 NPU 量化算子

华为 NPU 提供了多个量化相关的算子:

  • npu_dynamic_quant - NPU 动态量化算子
  • npu_rms_norm_dynamic_quant - RMS Norm + 动态量化融合算子

这些算子的输出都是 torch.int8 类型。

3. 传统比较方法的局限性

对于整数类型,传统的精度检查方法使用 compare_bool_tensor:

def compare_bool_tensor(bench_output, device_output):
    error_nums = (bench_output != device_output).sum()
    error_rate = float(error_nums / bench_output.size)
    result = CompareConst.PASS if error_rate == 0 else CompareConst.ERROR
    return error_rate, result, ""

局限性:

  • ✅ 要求完全一致(error_rate 必须为 0)
  • ❌ 不允许任何误差
  • ❌ 不适用于量化算子的特性

1. 量化算子的本质特性

量化操作将浮点数转换为整数,这个过程本身就会引入不可避免的误差:

# 量化公式
quantized = clamp(round(x / scale), -128, 127)
scale = max(abs(x)) / 127

关键点:

  • round() 操作在边界值(如 0.5)处可能产生不同结果
  • 不同的计算路径会导致微小的浮点数差异
  • 这些差异在量化后可能表现为 ±1 的整数差异

4. 昇腾算子精度标准2.1

https://wiki.huawei.com/domains/68949/wiki/232736/WIKI202512119393889

标准明确规定 量化计算算子不比较二进制一致

由于不同计算类型算子(如整数运算与浮点运算)的误差特性存在本质差异,无法使用统一的阈值标准。因此,本标准根据算子的计算特性将其划分为非计算类、整数计算类、量化计算类、浮点计算类共四类(算子分类定义),并为每类算子制定了针对性的精度比对标准。

算子类别/误差度量 二进制一致
Bitwise Match
绝对误差
AE
最大相对误差
MARE
平均相对误差
MERE
均方根误差
RMSE
非计算类
搬移/Cast
✔ N/A N/A N/A N/A
整数计算
INT8/INT16/INT32
✔ ✔ N/A N/A N/A
量化计算
FLOAT4/FLOAT8/INT8
N/A ✔ ✔ ✔ ✔
浮点计算
FLOAT16/FLOAT32
N/A N/A ✔ ✔ ✔

量化计算类算子通过标准
量化类算子存在两种输出模式:量化结果输出(整型输出)或反量化结果输出(浮点输出)。
比对方法: 单标杆比对(整型输出) / 双标杆比对(浮点输出)。

输入类型 \ 输出类型 整型输出 (INT4/INT8/INT16 等) 浮点输出 (FLOAT4/FLOAT8/FLOAT16 等)
整型输入 (INT4/INT8 等) N/A 参考浮点精度标准
浮点输入 (FLOAT4/FLOAT8/FLOAT16 等) 绝对误差 ≤ 1 参考浮点精度标准

5、问题根因分析&&修复方法

1. 算法限制问题

  • 位置: python/msprobe/pytorch/api_accuracy_checker/compare/compare.py
  • 问题: 算法限制列表中包含了 np.int8,导致 int8 数据执行了二进制一致对比【量化类算子不执行二进制对比】

2. 比较算法引入: 输入类型是FLOAT 输出是整型的量化算子:使用最大绝对误差<=1的判定逻辑

修复方案

修复 1: 量化类的整形类算子不执行二进制对比

①添加量化类算子的配置文件quantization_api_list
文件: python\msprobe\pytorch\api_accuracy_checker\config.yaml

quantization_api_list: ["npu_rms_norm_dynamic_quant", "npu_dynamic_quant", "npu_quant_lightning_indexer"]

②、添加量化类算子的配置文件quantization_api_list
文件: python\msprobe\pytorch\api_accuracy_checker\common\config.py

    def validate(key, value):
        validators = {
       ····
            'quantization_api_list': list
        }
         ····
        if key == 'quantization_api_list':
            ACCCheckConfig.check_filter_list_config(key, value)
        return value

③、量化类算子不执行二进制比较 避免int8类型数据执行二进制
文件: python/msprobe/pytorch/api_accuracy_checker/compare/compare.py

# 修改前
        if bench_output.dtype in [bool, np.uint8, np.int8, np.int16, np.uint16, np.uint32, np.int32,
                                  np.int64, np.uint64]:
            message += f"Compare algorithm is not supported for {bench_output.dtype} data. " \
                       f"Only judged by Error Rate."
            err_rate, status, msg = compare_bool_tensor(bench_output, device_output)
            message += msg + "\n"
            compare_column.error_rate = err_rate
            return status, compare_column, message

# 修改后
        if bench_output.dtype in [bool, np.uint8, np.int8, np.int16, np.uint16, np.uint32, np.int32, np.int64, np.uint64]:
            # 输出为整型且为配置的量化算子,使用量化比较逻辑:最大绝对误差<=1的判定标准
            # 获取输入为浮点型且输出为整形的量化算子清单:配置在config.yaml里面
            quantization_api_list = msCheckerConfig.quantization_api_list
            if api_name in quantization_api_list:
                status, compare_column, message = self._compare_quantization_tensor(bench_output, device_output,                                                                 compare_column, npu_dtype)
                return status, compare_column, message
            err_rate, status, msg = compare_bool_tensor(bench_output, device_output)           
            message += f"Current {bench_output.dtype} data, only perform binary comparison."
            compare_column.error_rate = err_rate
            return status, compare_column, message

修复 2: 输入类型是FLOAT 输出是整型的量化算子:使用最大绝对误差<=1的判定逻辑

文件: python\msprobe\pytorch\api_accuracy_checker\compare\compare.py

    def _compare_quantization_tensor(self, bench_output, device_output, compare_column, dtype):
        """处理量化算子的比较逻辑,使用最大绝对误差<=1的判定标准"""
        message = ""
        # 使用最大绝对误差<=1的判定逻辑
        abs_err = get_abs_err(bench_output, device_output)
        max_abs_res, max_abs_status = get_max_abs_err(abs_err)
        
        compare_column.max_abs_err = max_abs_res
        
        if max_abs_res <= 1:
            message += f"Quantization type: Max abs error is {max_abs_res:.2f}, less than or equal to 1, consider as pass.\n"
            return CompareConst.PASS, compare_column, message
        else:
            message += f"Quantization type: Max abs error is {max_abs_res:.2f}, greater than 1, consider as error.\n"
            return CompareConst.ERROR, compare_column, message

完善后的精度比较逻辑

image.png

自验证报告

image.png

likedislike
Pull Request已成功合入, 合并人@ascend-robot
(感谢 shuhuipeng 的贡献)
ascend-robotascend-robot成员
5月8日 添加了label:stat/needs-squash
ascend-robot
ascend-robot成员
5月8日 评论:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here。
You can get sig-info at here


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
repo-Ascend/msprobe ✅ 贺坤坤, mnhdxnh (2/2) ✅ 贺坤坤 (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

shuhuipeng, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
ascend-robotascend-robot成员
5月8日 添加了label:ascend-cla/yes
ascend-robot
ascend-robot成员
5月8日 评论:

通过PR创建命令启动流水线PR-pipeline_msprobe失败:failure

likedislike
此处折叠了176条消息 查看更多
ascend-robot
ascend-robot成员
5月14日 评论:

Review Guide

This pull-request passes review.
Committers who wrote a comment of /approve are: 贺坤坤.
Reviewers who wrote a comment of /lgtm are: 贺坤坤, mnhdxnh.

likedislike
ascend-robotascend-robot成员
5月14日 合入了pull request
Kkun_8成员
5月18日 关联了issue:[Feature]: 针对整形int8量化算子, 二进制无法完全一致,是否可以不比较二进制
捡到宝。捡到宝。成员
6月18日 关联了issue:[Feature]: 支持量化类算子预检
ascend-robot
ascend-robot成员
6月18日 评论:

Pull Request 已合并或已关闭。

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

likedislike