BitsAndBytes
BitsAndBytes (4비트)
모델을 양자화할 때 흔히 거치는 불편한 절차가 있어요. 바로 교정(calibration) 인데, 양자화된 모델을 입력 데이터로 맞춰보는 과정이죠. BitsAndBytes는 이 교정 과정을 없애면서도 메모리 사용을 줄이고 성능을 높여주는 양자화 방법이에요. 정확도를 크게 희생하지 않으면서 말이죠.
시작하기 (Installation)
먼저 BitsAndBytes를 설치합니다.
pip install bitsandbytes>=0.49.2
vLLM은 모델의 config 파일을 읽어 실행 중 양자화(in-flight quantization) 와 사전 양자화된 체크포인트(pre-quantized checkpoint) 를 모두 지원해요.
Hugging Face에서 bitsandbytes 양자화 모델을 찾을 수 있고, 보통 이런 저장소들은 quantization_config 섹션을 포함한 config.json 파일을 갖고 있습니다.
사전 양자화된 체크포인트 읽기 (Read quantized checkpoint)
사전 양자화된 체크포인트의 경우, vLLM이 config 파일에서 양자화 방식을 자동으로 추론하기 때문에 quantization 인자를 명시적으로 지정할 필요가 없어요.
from vllm import LLM
import torch
# unsloth/tinyllama-bnb-4bit is a pre-quantized checkpoint.
model_id = "unsloth/tinyllama-bnb-4bit"
llm = LLM(
model=model_id,
dtype=torch.bfloat16,
trust_remote_code=True,
)
여기서 unsloth/tinyllama-bnb-4bit는 사전 양자화된 체크포인트예요. 별도 quantization 지정 없이도 vLLM이 알아서 처리합니다.
실행 중 양자화: 4비트로 로드하기 (Inflight quantization)
BitsAndBytes로 실행 중 4비트 양자화를 하려면 quantization 인자를 명시적으로 지정해야 해요.
from vllm import LLM
import torch
model_id = "huggyllama/llama-7b"
llm = LLM(
model=model_id,
dtype=torch.bfloat16,
trust_remote_code=True,
quantization="bitsandbytes",
)
사전 양자화된 체크포인트와 달리, 원래 FP16 모델을 그대로 4비트로 바꿔 로드하려면 quantization="bitsandbytes"를 꼭 넣어야 합니다.
OpenAI 호환 서버 (OpenAI Compatible Server)
4비트 실행 중 양자화를 위해 모델 인자에 다음을 추가하면 돼요.
--quantization bitsandbytes
이렇게 하면 OpenAI 호환 서버(vllm serve)로 bitsandbytes 4비트 양자화를 동작시킬 수 있어요.
핵심 요약
| 상황 | quantization 지정 여부 |
|---|---|
| 사전 양자화된 체크포인트 | 불필요 (config에서 자동 감지) |
| 실행 중 4비트 양자화 | 필요 (bitsandbytes 명시) |