kar7mp5
[LLM 양자화] Large Language Model Quantization(Llama, Gemma) 본문
[LLM 양자화] Large Language Model Quantization(Llama, Gemma)
kar7mp5 2024. 8. 6. 00:47௹ 양자화 필요성
많은 메모리 요구로 인해 LLM 모델들은 양자화(Quantization)가 필수적이다.
보통 local 컴퓨터에서 Llama
는 8b 모델을 Gemma
는 7b 모델을 이용한다.
여기서 8b
는 80억 개 7b
는 70억 개 변수 사용을 의미한다. 때문에 메모리가 부족한 것이고, 양자화가 필요한 이유다.
௹ 필자 컴퓨터 사양
Memory(RAM) | 32GiB |
GPU | Nvidia 3050 |
௹ 양자화 이전
다음은 beomi/gemma-ko-7b
모델을 사용한 예제이다.
hugging face
에 들어가서 로그인하고 인증받은 token
으로 로그인하면 된다.
https://huggingface.co/beomi/gemma-ko-7b
beomi/gemma-ko-7b · Hugging Face
Gemma-Ko Update @ 2024.03.08: First release of Gemma-Ko 7B model Original Gemma Model Page: Gemma This model card corresponds to the 7B base version of the Gemma-Ko model. Resources and Technical Documentation: Terms of Use: Terms Citation @misc {gemma_ko_
huggingface.co
Hugging face
에 로그인하는 코드이다.
from huggingface_hub import notebook_login
notebook_login()
gemma-ko-7b
모델을 load하는 코드이다.
아래 코드를 실행하면 메모리는 다음과 같고 에러가 발생하였다.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed, BitsAndBytesConfig
set_seed(1234)
# Identify the checkpoint to use
model_checkpoint = "beomi/gemma-ko-7b"
# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
# Load the model with GPU
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
device_map="cuda"
)
주어진 text에 대한 답변을 추론하는 코드이다.
# Example text for the model to process
text = "파이썬으로 bfs 코드 작성해줘"
inputs = tokenizer(text, return_tensors="pt").to("cuda")
# Generate output
with torch.no_grad():
outputs = model.generate(inputs["input_ids"], max_length=150)
# Decode the output to text
decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded_output)
௹ 양자화 이후
위와 같은 문제가 발생하지 않도록 양자화(Quantization)을 적용해보겠다.
Hugging face
에 로그인하는 코드이다.
from huggingface_hub import notebook_login
notebook_login()
gemma-ko-7b
모델을 load하는 코드이다.
이번에 필자와 같거나 보다 좋은 컴퓨터 사양이라면 정상 작동할 것이다.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed, BitsAndBytesConfig
set_seed(1234)
# Identify the checkpoint to use
model_checkpoint = "beomi/gemma-ko-7b"
# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
# Define the BitsAndBytesConfig for 8-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
bnb_8bit_compute_dtype=torch.float16,
bnb_8bit_use_double_quant=False
)
# Load the model with 8-bit quantization and move it to GPU
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
quantization_config=bnb_config,
device_map="cuda"
)
추가된 코드는 다음과 같고 8bit로 양자화하여 load한다.
구체적으로 BitsAndBytesConfig
parameter에 대해 궁금하다면, 다음 hugging face transformer docs를 참고하면 된다.
# Define the BitsAndBytesConfig for 8-bit quantization <------------- 추가된 코드
bnb_config = BitsAndBytesConfig( # |
load_in_8bit=True, # |
bnb_8bit_compute_dtype=torch.float16, # |
bnb_8bit_use_double_quant=False # |
) # <----
# Load the model with 8-bit quantization and move it to GPU
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
quantization_config=bnb_config, # <-------- 추가된 코드
device_map="cuda"
)
주어진 text에 대한 답변을 추론하는 코드이고 다음과 같은 답변을 얻을 수 있다.
# Example text for the model to process
text = "파이썬으로 bfs 코드 작성해줘"
inputs = tokenizer(text, return_tensors="pt").to("cuda")
# Generate output
with torch.no_grad():
outputs = model.generate(inputs["input_ids"], max_length=150)
# Decode the output to text
decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded_output)
Result:
파이썬으로 bfs 코드 작성해줘야하는데요 bfs 코드 작성하는 방법좀 알려주세요 ㅠㅠ