GPTQ

GPTQ

GPTQ는 GPU 추론에 최적화된 양자화 포맷이에요. 캘리브레이션 데이터셋(calibration dataset)을 사용해서 양자화 품질을 개선해요.

출처: 문서

본문

AutoGPTQ로 양자화하기

짧은 데모로 Mistral 7B를 양자화해 볼게요.

먼저 auto-gptq를 설치해요. 이걸로 GPTQ 모델을 쉽게 양자화하고 추론할 수 있어요.

!pip install auto-gptq --no-build-isolation

설치가 끝나면 양자화할 모델을 다운로드할 수 있어요. 먼저 모델 접근 권한을 얻기 위해 읽기 전용 액세스 토큰으로 로그인할게요.

Note: 먼저 해당 리포지토리의 이용 약관에 동의해야 해요.

from huggingface_hub import login

login("read_token")

이제 준비가 끝났으니 모델을 로드하고 양자화할 수 있어요! 여기서는 모델을 4비트로 양자화할 거예요.

from transformers import AutoTokenizer
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
import logging

pretrained_model_dir = "mistralai/Mistral-7B-Instruct-v0.3"
quantized_model_dir = "mistral_gptq_quant"

tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir, use_fast=True)

examples = [
    tokenizer(
        "auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on the GPTQ algorithm."
    )
]

quantize_config = BaseQuantizeConfig(
    bits=4,  # quantize model to 4-bit
    group_size=128,  # it is recommended to set the value to 128
    desc_act=False,  # set to False can significantly speed up inference but the perplexity may be slightly bad, feel free to change
)

model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_dir, quantize_config)

# quantize model, the examples should be list of dict whose keys can only be "input_ids" and "attention_mask"
model.quantize(examples)

이제 모델이 양자화됐으니, 나중에 공유하거나 다시 로드할 수 있도록 저장할게요. GPTQ로 양자화하는 것은 시간과 리소스가 꽤 들기 때문에, 항상 저장해 두는 걸 권장해요.

model.save_quantized(quantized_model_dir)

tokenizer.save_pretrained(quantized_model_dir)

model.save_quantized(quantized_model_dir, use_safetensors=True)

모델이 GPTQ 4비트 정밀도로 양자화되어 저장됐어요!

auto-gptq로 추론을 위해 다시 로드할 수도 있어요:

model = AutoGPTQForCausalLM.from_quantized(quantized_model_dir, device="cuda:0") # loads quantized model to the first GPU
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir)

conversation = [{"role": "user", "content": "How are you today?"}]

prompt = tokenizer.apply_chat_template(
            conversation=conversation,
            tokenize=False,
            add_generation_prompt=True,
)

inputs = tokenizer(prompt, return_tensors="pt")
inputs.to("cuda:0") # loads tensors to the first GPU

outputs = model.generate(**inputs, max_new_tokens=32)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)

print(response)

더 알아보기 (Learn more)