NVIDIA Model Optimizer

NVIDIA Model Optimizer

NVIDIA Model Optimizer 는 NVIDIA GPU에서 추론을 위해 모델을 최적화하도록 설계된 라이브러리입니다. LLM, VLM, diffusion 모델의 Post-Training Quantization(PTQ) 및 Quantization Aware Training(QAT) 도구를 포함합니다.

라이브러리는 다음으로 설치하는 것을 권장합니다.

출처: 문서

본문

pip install nvidia-modelopt

지원되는 ModelOpt 체크포인트 형식 (Supported ModelOpt checkpoint formats)

vLLM은 hf_quant_config.json 을 통해 ModelOpt 체크포인트를 감지하고 다음 quantization.quant_algo 값을 지원합니다.

  • FP8: per-tensor 가중치 스케일(+ 선택적 정적 활성화 스케일).
  • FP8_PER_CHANNEL_PER_TOKEN: per-channel 가중치 스케일과 동적 per-token 활성화 양자화.
  • FP8_PB_WO(ModelOpt는 fp8_pb_wo 를 생성할 수 있음): block-scaled FP8 weight-only(보통 128×128 블록).
  • NVFP4: ModelOpt NVFP4 체크포인트(quantization="modelopt_fp4" 사용).
  • W4A16_NVFP4: 16비트 활성화를 가진 weight-only ModelOpt NVFP4 체크포인트(quantization="modelopt_fp4" 사용).
  • MXFP8: ModelOpt MXFP8 체크포인트(quantization="modelopt_mxfp8" 사용).

참고: NVFP4 체크포인트의 경우 vLLM은 로드 시 현재 플랫폼에서 사용 가능한 백엔드(CUTLASS, FlashInfer, Marlin 등)에서 GEMM 커널을 자동으로 선택합니다. 지원되는 네이티브 FP4 GEMM 커널이 없는 GPU에서는 vLLM이 Marlin을 통한 weight-only(W4A16) 실행으로 폴백하고 경고를 로깅합니다. 이는 컴퓨트 집약적 워크로드에서 처리량을 줄일 수 있습니다. --linear-backend 를 사용해 자동 선택을 오버라이드하세요(이것은 deprecated된 VLLM_NVFP4_GEMM_BACKEND 환경 변수를 대체합니다). NVFP4 관련 값에는 cutlass, flashinfer_cutlass, flashinfer_cutedsl, flashinfer_trtllm, flashinfer_cudnn, marlin 이 있으며, Engine Arguments 페이지의 KernelConfigvllm serve --help=KernelConfig 에 표시됩니다. W4A16_NVFP4 의 경우 auto 는 현재 Marlin을 선택합니다. BF16 활성화 모델은 --linear-backend flashinfer_cutedsl 로 FlashInfer CuTe-DSL 백엔드를 명시적으로 선택할 수 있습니다.

참고: SM100 계열 GPU에서 BF16 활성화로 MXFP8 양자화된 모델의 경우 --linear-backend flashinfer_trtllm 을 사용해 FlashInfer의 TensorRT-LLM GEMM 백엔드를 선택하세요.

PTQ로 HuggingFace 모델 양자화 (Quantizing HuggingFace Models with PTQ)

Model Optimizer 저장소의 예시 스크립트를 사용해 HuggingFace 모델을 양자화할 수 있습니다. LLM PTQ의 기본 스크립트는 보통 examples/llm_ptq 디렉터리에 있습니다.

modelopt의 PTQ API로 모델을 양자화하는 예시입니다.

import modelopt.torch.quantization as mtq
from transformers import AutoModelForCausalLM

# Load the model from HuggingFace
model = AutoModelForCausalLM.from_pretrained("<path_or_model_id>")

# Select the quantization config, for example, FP8
config = mtq.FP8_DEFAULT_CFG

# Define a forward loop function for calibration
def forward_loop(model):
    for data in calib_set:
        model(data)

# PTQ with in-place replacement of quantized modules
model = mtq.quantize(model, config, forward_loop)

모델이 양자화된 후 export API를 사용해 양자화된 체크포인트로 내보낼 수 있습니다.

import torch
from modelopt.torch.export import export_hf_checkpoint

with torch.inference_mode():
    export_hf_checkpoint(
        model,  # The quantized model.
        export_dir,  # The directory where the exported files will be stored.
    )

양자화된 체크포인트는 그다음 vLLM으로 배포할 수 있습니다. 예를 들어 meta-llama/Llama-3.1-8B-Instruct 에서 파생된 FP8 양자화 체크포인트인 nvidia/Llama-3.1-8B-Instruct-FP8 를 vLLM으로 배포하는 코드입니다.

from vllm import LLM, SamplingParams

def main():
    model_id = "nvidia/Llama-3.1-8B-Instruct-FP8"

    # Ensure you specify quantization="modelopt" when loading the modelopt checkpoint
    llm = LLM(model=model_id, quantization="modelopt", trust_remote_code=True)

    sampling_params = SamplingParams(temperature=0.8, top_p=0.9)

    prompts = [
        "Hello, my name is",
        "The president of the United States is",
        "The capital of France is",
        "The future of AI is",
    ]

    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}")

if __name__ == "__main__":
    main()

OpenAI 호환 서버 실행 (Running the OpenAI-compatible server)

OpenAI 호환 API로 로컬 ModelOpt 체크포인트를 서빙하려면:

vllm serve <path_to_exported_checkpoint> \
  --quantization modelopt \
  --host 0.0.0.0 --port 8000

테스트 (로컬 체크포인트, Testing)

vLLM의 ModelOpt 단위 테스트는 로컬 체크포인트 경로로 게이트되며 CI에서 기본적으로 건너뜁니다. 로컬에서 테스트를 실행하려면:

export VLLM_TEST_MODELOPT_FP8_PC_PT_MODEL_PATH=<path_to_fp8_pc_pt_checkpoint>
export VLLM_TEST_MODELOPT_FP8_PB_WO_MODEL_PATH=<path_to_fp8_pb_wo_checkpoint>
pytest -q tests/quantization/test_modelopt.py

더 알아보기 (Learn more)