Bits and Bytes

Bits and Bytes (BnB)

bits-and-bytes는 양자화에 대한 아주 빠르고 직관적인 접근 방식이에요. 로드하면서 동시에 양자화를 진행하죠. 다만 속도와 품질이 최적은 아니에요. 그래서 빠른 양자화와 즉석(on the fly)으로 모델을 로드할 때 유용해요.

출처: 문서

본문

transformers로 양자화하기

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

먼저 transformers와 필요한 모든 의존성을 설치해요.

!pip install -q -U bitsandbytes
!pip install -q -U git+https://github.com/huggingface/transformers.git
!pip install -q -U git+https://github.com/huggingface/peft.git
!pip install -q -U git+https://github.com/huggingface/accelerate.git

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

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

from huggingface_hub import login

login("read_token")

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

import torch
from transformers import BitsAndBytesConfig, AutoModelForCausalLM, AutoTokenizer

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

quantization_config = BitsAndBytesConfig(
    load_in_8bit=True
)

다른 방법들과 달리 BnB는 꽤 빠르고 효율적이에요. 미리 양자화할 필요도 없고, 바로(on the fly) 양자화할 수 있어요!

model = AutoModelForCausalLM.from_pretrained(pretrained_model_dir, quantization_config=quantization_config)
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir)

준비가 끝나면 모델을 다음과 같이 사용할 수 있어요:

conversation = [{"role": "user", "content": "Tell me a joke."}]

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

print(prompt)

inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
inputs.to("cuda:0")

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

print(response)

더 알아보기 (Learn more)