AWQ 양자화
AWQ 양자화
양자화 모델에 대한 우리의 추천 중 하나는 AutoAWQ와 함께 AWQ를 사용하는 거예요. AWQ는 Activation-aware Weight Quantization의 약자로, LLM 저비트(weight-only) 양자화를 위한 하드웨어 친화적인 접근 방식이에요.
출처: 문서
본문
⚠️ 주의: 이 페이지는 Qwen3 기준으로 업데이트 예정이에요.
양자화 모델에 대한 추천 중 하나는 AutoAWQ와 함께 AWQ를 사용하는 거예요.
AWQ는 Activation-aware Weight Quantization(활성화 인지 가중치 양자화)를 뜻하며, LLM 저비트 weight-only 양자화를 위한 하드웨어 친화적인 접근 방식이에요.
AutoAWQ는 4비트 양자화 모델을 위한 사용하기 쉬운 Python 라이브러리예요. AutoAWQ는 FP16 대비 모델을 3배 빨라지게 하고 메모리 요구량을 3배 줄여줘요. AutoAWQ는 LLM 양자화를 위한 AWQ 알고리즘을 구현해요.
이 문서에서는 양자화 모델을 Hugging Face transformers로 사용하는 방법과 나만의 모델을 양자화하는 방법을 보여드려요.
Hugging Face transformers로 AWQ 모델 사용하기
이제 transformers가 AutoAWQ를 공식 지원하므로, 양자화 모델을 transformers로 직접 사용할 수 있어요. 다음은 Qwen2.5-7B-Instruct-AWQ를 양자화 모델로 실행하는 아주 간단한 코드예요:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen2.5-7B-Instruct-AWQ"
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
prompt = "Give me a short introduction to large language models."
messages = [
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": prompt},
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
generated_ids = model.generate(
**model_inputs,
max_new_tokens=512,
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
vLLM으로 AWQ 모델 사용하기
vLLM이 AWQ를 지원하므로, 우리가 제공하는 AWQ 모델이나 AutoAWQ로 양자화한 모델을 vLLM과 직접 사용할 수 있어요. AWQ 모델에 성능 개선을 가져오는 최신 버전의 vLLM(vllm>=0.6.1)을 사용하는 것을 권장해요. 그렇지 않으면 성능이 잘 최적화되지 않을 수 있어요.
실제로 사용법은 vLLM의 기본 사용법과 동일해요. vLLM과 Qwen2.5-7B-Instruct-AWQ로 OpenAI-API 호환 API를 실행하는 간단한 예시를 제공할게요:
셸에서 다음을 실행해 OpenAI 호환 API 서비스를 시작하세요:
vllm serve Qwen/Qwen2.5-7B-Instruct-AWQ
그 다음 아래처럼 API를 호출할 수 있어요:
curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "Qwen/Qwen2.5-7B-Instruct-AWQ",
"messages": [
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": "Tell me something about large language models."}
],
"temperature": 0.7,
"top_p": 0.8,
"repetition_penalty": 1.05,
"max_tokens": 512
}'
또는 아래처럼 openai Python 패키지로 API 클라이언트를 사용할 수 있어요:
from openai import OpenAI
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
chat_response = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct-AWQ",
messages=[
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": "Tell me something about large language models."},
],
temperature=0.7,
top_p=0.8,
max_tokens=512,
extra_body={
"repetition_penalty": 1.05,
},
)
print("Chat response:", chat_response)
AutoAWQ로 나만의 모델 양자화하기
나만의 모델을 AWQ 양자화 모델로 만들고 싶다면 AutoAWQ를 사용하는 것을 권장해요.
pip install "autoawq<0.2.7"
Qwen2.5-7B를 기반으로 파인튜닝한 Qwen2.5-7B-finetuned라는 모델이 있고, 이를 Alpaca 같은 여러분만의 데이터셋으로 만들었다고 가정해 볼게요. 나만의 AWQ 양자화 모델을 만들려면 캘리브레이션에 훈련 데이터를 사용해야 해요. 아래에 실행할 간단한 데모를 제공할게요:
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer
# Specify paths and hyperparameters for quantization
model_path = "your_model_path"
quant_path = "your_quantized_model_path"
quant_config = { "zero_point": True, "q_group_size": 128, "w_bit": 4, "version": "GEMM" }
# Load your tokenizer and model with AutoAWQ
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoAWQForCausalLM.from_pretrained(model_path, device_map="auto", safetensors=True)
그 다음 캘리브레이션 데이터를 준비해야 해요. 샘플을 리스트에 넣기만 하면 되고, 각 샘플은 텍스트예요. 파인튜닝 데이터를 캘리브레이션에 직접 사용하므로 먼저 ChatML 템플릿으로 포맷해요. 예를 들어:
data = []
for msg in dataset:
text = tokenizer.apply_chat_template(msg, tokenize=False, add_generation_prompt=False)
data.append(text.strip())
여기서 각 msg는 아래와 같은 전형적인 채팅 메시지예요:
[
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": "Tell me who you are."},
{"role": "assistant", "content": "I am a large language model named Qwen..."}
]
그 다음 한 줄의 코드로 캘리브레이션 과정을 실행하세요:
model.quantize(tokenizer, quant_config=quant_config, calib_data=data)
마지막으로 양자화 모델을 저장하세요:
model.save_quantized(quant_path, safetensors=True, shard_size="4GB")
tokenizer.save_pretrained(quant_path)
이제 배포에 사용할 나만의 AWQ 양자화 모델을 얻을 수 있어요. 즐기세요!