양자화(quantization)
양자화
1. 모델학습에 필요한 메모리 크기
딥러닝 모델의 파라미터 1개는 4byte며, Optimizer는 모델의 4배, Gradient는 모델의 1배 메모리가 필요하다. 1B 모델의 경우 파라미터만 4 x 10억 = 40억Byte = 4GB 메모리가 필요하며 훈련을 위해서는 Optimizer(4 x 4 = 16GB)
Gradient(4 x 1 = 4GB) 총 24GB의 메모리가 필요하다.
따라서 모델 크기 x 24를 하면 모델 훈련에 필요한 총 메모리 크기를 구할 수 있다.
LG EXAONE 3.0 모델은 크기가 7.8B인데, 훈련을 위해서 약 187.2GB 메모리가 필요하다.
2. 양자화
32byte(4byte) 파라미터를 8bit(1byte, 1/4), 4bit(0.5byte, 1/8)로 줄이는것이 양자화다.
따라서 7.8B 모델에 4bit 양자화를 적용시키면 23.4GB 까지 메모리 사용을 줄일 수 있다.
3. 코드
transformers 라이브러리의 BitsAndBytesConfig를 통한 4bit 양자화 예시
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch
model_name = "LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct"
# BitsAndBytesConfig 객체를 생성
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16
)
generation_model = AutoModelForCausalLM.from_pretrained(
model_name,
trust_remote_code=True,
quantization_config=quantization_config,
device_map="auto"
)
Leave a comment