양자화

양자화 (Quantization)

양자화는 모델 정밀도를 더 작은 메모리 풋프린트와 맞바꿔, 대형 모델을 더 다양한 디바이스에서 실행할 수 있게 해 줍니다.

: 양자화를 시작하려면 LLM Compressor 을 참고하세요. 이것은 FP8, INT8, INT4 및 기타 양자화 형식을 지원하는 vLLM 배포용 모델 최적화 라이브러리입니다.

출처: 문서

본문

지원되는 양자화 형식

vLLM이 지원하는 양자화 형식은 다음과 같습니다.

양자화별 선형 백엔드 선택 (Selecting Linear Backends per Quantization)

--linear-backend 는 모든 양자화된 선형 레이어에 하나의 백엔드를 선택합니다. 둘 이상의 선형 양자화 방식을 사용하는 혼합 정밀도 모델에서는 linear_backend_per_quant 로 개별 방식의 백엔드를 오버라이드할 수 있어요.

vllm serve <model> \
  --linear-backend cutlass \
  --kernel-config '{"linear_backend_per_quant":{"nvfp4_w4a16":"humming"}}'

여기서 NVFP4 W4A16 선형 레이어는 Humming을 사용하고, 다른 모든 양자화된 선형 레이어는 CUTLASS를 사용합니다. per-quantization 오버라이드는 --linear-backend 보다 우선합니다. 오버라이드가 없는 방식은 전역 설정을 계속 사용하는데, auto 일 때의 자동 선택도 포함합니다.

지원 하드웨어 (Supported Hardware)

아래 표는 vLLM에서 다양한 양자화 구현과 다양한 하드웨어 플랫폼의 호환성을 보여줍니다.

구현 Volta Turing Ampere Ada Hopper AMD GPU Intel GPU x86 CPU Arm CPU
AWQ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
GPTQ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
Marlin (GPTQ/AWQ/FP8/FP4) ✅︎* ✅︎ ✅︎ ✅︎
llm-compressor INT8 (W8A8) ✅︎ ✅︎ ✅︎ ✅︎ ✅︎ ✅︎
llm-compressor INT8 (W4A8) ✅︎ ✅︎
llm-compressor 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-Inference Recommended Models and Features 문서를 참고하세요.

참고: 이 호환성 차트는 vLLM이 다양한 하드웨어 플랫폼과 양자화 방법에 대한 지원을 계속 발전시키고 확장함에 따라 변경될 수 있습니다. 최신 하드웨어 지원 및 양자화 방법 정보는 vllm/model_executor/layers/quantization 을 참고하거나 vLLM 개발 팀과 상의하세요.

트리 밖 양자화 플러그인 (Out-of-Tree Quantization Plugins)

vLLM은 @register_quantization_config 데코레이터로 커스텀한 트리 밖 양자화 방법을 등록하는 것을 지원합니다. 이를 통해 vLLM 코드베이스를 수정하지 않고 자체 양자화 방식을 구현하고 사용할 수 있어요.

커스텀 양자화 방법 등록 (Registering a Custom Quantization Method)

커스텀 양자화 방법을 등록하려면 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() 지원되는 활성화 dtype 목록을 반환합니다(예: torch.float16).
get_min_capability() 최소 GPU 컴퓨트 캐퍼빌리티를 반환합니다(예: Ampere는 80, 제한 없음은 -1).
get_config_filenames() 모델 디렉터리에서 검색할 구성 파일명 목록을 반환합니다.
from_config(config) 모델의 양자화 구성 dict에서 구성을 만드는 클래스 메서드입니다.
get_quant_method(layer, prefix) 주어진 레이어의 양자화 메서드를 반환하거나, 건너뛰려면 None 을 반환합니다.
양자화된 선형 메서드 구현 (Implementing a Quantized Linear Method)

선형 레이어의 경우 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 메서드 구현 (Implementing a Quantized MoE Method)

Mixture of Experts(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.pyFp8MoEMethod 같은 기존 구현을 참고하세요.

플러그인 사용 (Using the Plugin)

등록 후 커스텀 양자화 방법을 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")

플러그인 시스템에 대한 자세한 내용은 Plugin System 문서 를 참고하세요.

더 알아보기 (Learn more)