跳到内容

量化

量化通过牺牲模型精度来换取更小的内存占用,从而允许在更广泛的设备上运行大型模型。

提示

若要开始使用量化,请参阅 LLM Compressor。这是一个用于优化 vLLM 部署模型的库,支持 FP8、INT8、INT4 及其他量化格式。

以下是 vLLM 支持的量化格式

支持的硬件

下表显示了 vLLM 中各种量化实现与不同硬件平台的兼容性

实现 Volta Turing Ampere Ada Hopper AMD GPU Intel GPU x86 CPU
AWQ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
GPTQ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
Marlin (GPTQ/AWQ/FP8/FP4) ✅︎* ✅︎ ✅︎ ✅︎
INT8 (W8A8) ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
FP8 (W8A8) ✅︎ ✅︎ ✅︎
bitsandbytes ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
DeepSpeedFP ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
GGUF ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
  • Volta 指代 SM 7.0,Turing 指代 SM 7.5,Ampere 指代 SM 8.0/8.6,Ada 指代 SM 8.9,Hopper 指代 SM 9.0。
  • ✅︎ 表示该量化方法在指定硬件上受支持。
  • ❌ 表示该量化方法在指定硬件上不受支持。
  • 所有 Intel Gaudi 量化支持已迁移至 vLLM-Gaudi
  • *Turing 架构不支持 Marlin MXFP4。

注意

有关 Google TPU 量化支持的信息,请参阅 TPU 推理推荐模型和特性文档。

注意

随着 vLLM 的不断发展并扩展其对不同硬件平台和量化方法的支持,此兼容性表可能会有所变动。

有关硬件支持和量化方法的最新信息,请参阅 vllm/model_executor/layers/quantization 或咨询 vLLM 开发团队。

树外(Out-of-Tree)量化插件

vLLM 支持使用 @register_quantization_config 装饰器注册自定义的树外量化方法。这允许你在不修改 vLLM 代码库的情况下实现并使用自己的量化方案。

注册自定义量化方法

要注册自定义量化方法,请创建一个继承自 QuantizationConfig 的类,并使用 @register_quantization_config 对其进行装饰。get_quant_method 会根据层类型分发到相应的量化方法。

import torch
from vllm.model_executor.layers.quantization import (
    register_quantization_config,
)
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig,
    QuantizeMethodBase,
)
from vllm.model_executor.layers.linear import LinearBase
from vllm.model_executor.layers.fused_moe import FusedMoE

@register_quantization_config("my_quant")
class MyQuantConfig(QuantizationConfig):
    """Custom quantization config."""

    def get_name(self) -> str:
        return "my_quant"

    def get_supported_act_dtypes(self) -> list:
        return [torch.float16, torch.bfloat16]

    @classmethod
    def get_min_capability(cls) -> int:
        # Minimum GPU compute capability, -1 for no restriction
        return -1

    @staticmethod
    def get_config_filenames() -> list[str]:
        # Config files to search for in model directory
        return []

    @classmethod
    def from_config(cls, config: dict) -> "MyQuantConfig":
        # Create config from model's quantization config
        return cls()

    def get_quant_method(
        self, layer: torch.nn.Module, prefix: str
    ) -> QuantizeMethodBase | None:
        # Dispatch based on layer type
        # NOTE: you only need to implement methods you care about
        if isinstance(layer, LinearBase):
            return MyQuantLinearMethod()
        elif isinstance(layer, FusedMoE):
            return MyQuantMoEMethod(layer.moe_config)
        return None

必需的 QuantizationConfig 方法

你的自定义 QuantizationConfig 子类必须实现这些抽象方法:

方法 描述
get_name() 返回量化方法的名称。
get_supported_act_dtypes() 返回支持的激活数据类型列表(例如 torch.float16)。
get_min_capability() 返回最低 GPU 计算能力(例如 Ampere 架构返回 80,无限制返回 -1)。
get_config_filenames() 返回要在模型目录中搜索的配置文件名列表。
from_config(config) 类方法,用于从模型的量化配置字典中创建配置对象。
get_quant_method(layer, prefix) 返回给定层的量化方法,若返回 None 则跳过。

实现量化线性层方法

对于线性层,需从 get_quant_method 返回一个 QuantizeMethodBase 子类。你可以继承 UnquantizedLinearMethod 作为起点。

from vllm.model_executor.layers.linear import UnquantizedLinearMethod

class MyQuantLinearMethod(UnquantizedLinearMethod):
    """Custom quantization method for linear layers."""

    def create_weights(
        self, layer: torch.nn.Module, *weight_args, **extra_weight_attrs
    ):
        # Create quantized weights for the layer
        ...

    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
        bias: torch.Tensor | None = None,
    ) -> torch.Tensor:
        # Apply custom quantization logic here
        ...

实现量化 MoE 方法

对于混合专家 (MoE) 模型,需从 get_quant_method 返回一个 FusedMoEMethodBase 子类。你可以使用 UnquantizedFusedMoEMethod 来跳过 MoE 量化。

from vllm.model_executor.layers.fused_moe.layer import UnquantizedFusedMoEMethod
from vllm.model_executor.layers.fused_moe.fused_moe_method_base import (
    FusedMoEMethodBase,
)
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig

class MyQuantMoEMethod(FusedMoEMethodBase):
    """Custom quantization method for MoE layers."""

    def create_weights(
        self,
        layer: torch.nn.Module,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        # Create quantized weights for the MoE layer
        ...

    def apply(
        self,
        layer: torch.nn.Module,
        router: "FusedMoERouter",
        x: torch.Tensor,
        router_logits: torch.Tensor,
    ) -> torch.Tensor:
        # Apply MoE computation with quantized weights
        ...

    def get_fused_moe_quant_config(
        self, layer: torch.nn.Module
    ) -> FusedMoEQuantConfig | None:
        # Return the MoE quantization configuration
        ...

请参考 vllm/model_executor/layers/quantization/fp8.py 中现有的实现,例如 Fp8MoEMethod

使用插件

注册完成后,你就可以在 vLLM 中使用自定义的量化方法了。

# Register your quantization method (import the module containing your config)
import my_quant_plugin

from vllm import LLM

# Use the custom quantization method
llm = LLM(model="your-model", quantization="my_quant")

有关插件系统的更多信息,请参阅插件系统文档