昇腾社区首页
中文
注册
开发者
下载

W8A8

简介

此量化方式对权重和激活值均进行量化,将高位浮点数转为8 bit,减少模型权重的体积。使用int8格式的数据进行计算,可以减少MatMul算子计算量,以提升推理性能。

量化后权重目录结构:

├─ config.json
├─ configuration.json
├─ generation_config.json
├─ quant_model_description.json
├─ quant_model_weight_w8a8.safetensors
└─ tokenizer.json
  • 量化输出包含:权重文件quant_model_weight_w8a8.safetensors和权重描述文件quant_model_description.json。
  • 目录中的其余文件为推理时所需的配置文件,不同模型略有差异。

以下展示了量化后权重描述文件quant_model_description.json中的部分内容:

1
2
3
4
5
6
7
{
  "model.layers.0.self_attn.q_proj.weight": "W8A8",
  "model.layers.0.self_attn.q_proj.input_scale": "W8A8",
  "model.layers.0.self_attn.q_proj.input_offset": "W8A8",
  "model.layers.0.self_attn.q_proj.quant_bias": "W8A8",
  "model.layers.0.self_attn.q_proj.deq_scale": "W8A8"
}

量化后的MatMul权重新增input_scale、input_offset、quant_bias和deq_scale。其中input_scale和input_offset用于对激活值进行量化。MatMul使用量化后的激活值和量化权重进行计算。quant_bias和deq_scale用于对MatMul的计算结果进行反量化。

图1 量化权重推理时流程

此量化方式支持量化float16或bfloat16类型的原始权重。

表1 float16权重量化后dtype及shape信息(假设原始权重的shape为[n, k])

Tensor信息

weight

input_scale

input_offset

quant_bias

deq_scale

dtype

int8

float16

float16

int32

int64

shape

[n, k]

[1]

[1]

[n]

[n]

表2 bfloat16权重量化后dtype及shape信息(假设原始权重的shape为[n, k])

Tensor信息

weight

input_scale

input_offset

quant_bias

deq_scale

dtype

int8

bfloat16

bfloat16

int32

float32

shape

[n, k]

[1]

[1]

[n]

[n]

生成权重

  1. 请参见msModelSlim工具,安装msModelSlim工具。
  2. 使用msModelSlim工具生成量化权重。

    以Qwen2-7B为例,安装msModelSlim工具后,可以使用如下命令快速生成一份W8A8量化权重:

    msmodelslim quant --model_path {浮点权重路径} --save_path {W8A8量化权重路径} --device npu --model_type Qwen2-7B --quant_type w8a8 --trust_remote_code True

上述命令是msModelSlim工具的一个最佳实践,如需了解更多量化参数配置,请参考msModelSlim工具文档。

执行推理

以Qwen2-7B-W8A8为例,您可以使用以下指令执行对话测试,推理内容为"What's deep learning?",最长输出20个token。

1
2
cd ${ATB_SPEED_HOME_PATH}
torchrun --master_port 12350 -m examples.run_pa --model_path {w8a8量化权重路径}