量化指南#

模型量化是一种通过降低模型中权重和激活值的数据精度,从而减少模型大小和计算需求的技术,这样可以节省内存并提高推理速度。

vLLM Ascend 支持多种量化方法。本指南提供了使用不同量化工具以及在 vLLM Ascend 上运行量化模型的说明。

注意

您可以选择自行转换模型,或使用我们上传的量化模型。请参阅 https://www.modelscope.cn/models/vllm-ascend/Kimi-K2-Instruct-W8A8。在对模型进行量化之前,请确保有足够的可用内存。

量化工具#

vLLM Ascend 支持由两种主要工具量化的模型:ModelSlimLLM-Compressor

2. LLM-Compressor#

LLM-Compressor 是一个统一的压缩模型库,用于加速 vLLM 推理。

安装#

pip install llmcompressor

模型量化#

LLM-Compressor 提供了多种量化方案的示例。

密集模型量化#

为密集模型生成 W8A8 动态量化权重的示例:

# Navigate to LLM-Compressor examples directory
cd examples/quantization/llm-compressor

# Run quantization script
python3 w8a8_int8_dynamic.py
MoE 模型量化#

为 MoE 模型生成 W8A8 动态量化权重的示例:

# Navigate to LLM-Compressor examples directory
cd examples/quantization/llm-compressor

# Run quantization script
python3 w8a8_int8_dynamic_moe.py

更多内容,请参考 官方示例

LLM-Compressor 当前支持的量化类型:W8A8W8A8_DYNAMIC

运行量化模型#

一旦您拥有由 ModelSlim 生成的量化模型,您可以通过指定 --quantization ascend 参数来使用 vLLM Ascend 进行推理以启用量化功能。而对于由 LLM-Compressor 量化的模型,则无需添加此参数。

离线推理#

import torch

from vllm import LLM, SamplingParams

prompts = [
    "Hello, my name is",
    "The future of AI is",
]
# Set sampling parameters
sampling_params = SamplingParams(temperature=0.6, top_p=0.95, top_k=40)

llm = LLM(model="/path/to/your/quantized_model",
          max_model_len=4096,
          trust_remote_code=True,
          # Set appropriate TP and DP values
          tensor_parallel_size=2,
          data_parallel_size=1,
          # Set an unused port
          port=8000,
          # Set serving model name
          served_model_name="quantized_model",
          # Specify `quantization="ascend"` to enable quantization for models quantized by ModelSlim
          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}")

在线推理#

# Corresponding to offline inference
python -m vllm.entrypoints.api_server \
    --model /path/to/your/quantized_model \
    --max-model-len 4096 \
    --port 8000 \
    --tensor-parallel-size 2 \
    --data-parallel-size 1 \
    --served-model-name quantized_model \
    --trust-remote-code 

参考#