量化指南#
模型量化是一种通过降低模型中权重和激活值的数值精度来减小模型大小和计算需求的技术,从而节省内存并提高推理速度。
从 0.9.0rc2 版本开始,vLLM Ascend 实验性地支持了量化功能。用户可以通过指定 --quantization ascend 来启用量化功能。目前,只有 Qwen 和 DeepSeek 系列模型经过了充分测试。未来我们将支持更多量化算法和模型。
安装 ModelSlim#
要量化模型,您应该安装 ModelSlim,它是 Ascend 的压缩和加速工具。它是一款面向加速的亲和性压缩工具,以压缩为核心技术,并基于 Ascend 平台构建。
安装 ModelSlim
# The branch(br_release_MindStudio_8.1.RC2_TR5_20260624) has been verified
git clone -b br_release_MindStudio_8.1.RC2_TR5_20260624 https://gitcode.com/Ascend/msit/tree/master
cd msit/msmodelslim
bash install.sh
pip install accelerate
量化模型#
注意
您可以选择自己转换模型,或者使用我们上传的量化模型。请参见 https://www.modelscope.cn/models/vllm-ascend/Kimi-K2-Instruct-W8A8。此转换过程需要较大的 CPU 内存,请确保 RAM 大小超过 2 TB。
适配和修改#
生成 W8A8 权重#
cd example/DeepSeek
export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
export PYTORCH_NPU_ALLOC_CONF=expandable_segments:False
export MODEL_PATH="/root/.cache/Kimi-K2-Instruct"
export SAVE_PATH="/root/.cache/Kimi-K2-Instruct-W8A8"
python3 quant_deepseek_w8a8.py --model_path $MODEL_PATH --save_path $SAVE_PATH --batch_size 4
这是除 safetensors 之外所有转换后的模型文件
.
|-- config.json
|-- configuration.json
|-- configuration_deepseek.py
|-- generation_config.json
|-- modeling_deepseek.py
|-- quant_model_description.json
|-- quant_model_weight_w8a8_dynamic.safetensors.index.json
|-- tiktoken.model
|-- tokenization_kimi.py
`-- tokenizer_config.json
运行模型#
现在,您可以使用 vLLM Ascend 运行量化模型。在线和离线推理的示例如下所示:
离线推理#
import torch
from vllm import LLM, SamplingParams
prompts = [
"Hello, my name is",
"The future of AI is",
]
sampling_params = SamplingParams(temperature=0.6, top_p=0.95, top_k=40)
llm = LLM(model="{quantized_model_save_path}",
max_model_len=2048,
trust_remote_code=True,
# Enable quantization by specifying `quantization="ascend"`
quantization="ascend")
outputs = llm.generate(prompts, sampling_params)
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
在线推理#
通过指定 --quantization ascend 来启用量化,更多详细信息,请参阅 DeepSeek-V3-W8A8 教程。
常见问题解答#
1. 如何解决 KeyError “xxx.layers.0.self_attn.q_proj.weight”?#
首先,请确保您将 ascend 指定为量化方法。其次,检查您的模型是否由 br_release_MindStudio_8.1.RC2_TR5_20260624 ModelSlim 版本转换。最后,如果仍然不起作用,请提交一个 issue。也许需要适配一些新模型。
2. 如何解决错误 “Could not locate the configuration_deepseek.py”?#
请使用 br_release_MindStudio_8.1.RC2_TR5_20260624 ModelSlim 转换 DeepSeek 系列模型,该版本已修复了缺失 configuration_deepseek.py 的错误。