양자화로 모델을 더 작게 만들기

Llama 3 미세 조정(Fine-Tuning)

Francesca Donadoni

Curriculum Manager, DataCamp

양자화란?

 

  • 모델 정밀도 축소
  • 32비트 부동소수점에서:
    • 8비트 정수
    • 4비트 정수
  • 양자화 인지 학습

추상 블록.jpg

Llama 3 미세 조정(Fine-Tuning)

양자화의 종류

 

  • 가중치 양자화: 가중치 정밀도 축소
  • 활성화 양자화: 활성화 값 정밀도 축소
  • 학습 후 양자화: 학습 후 모델 정밀도 축소
Llama 3 미세 조정(Fine-Tuning)

bitsandbytes로 양자화 구성

from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(
  • 정밀도 설정 (load_in_4_bit, load_in_8_bit)
    load_in_4bit=True,
  • 양자화 유형 설정 ('fp4' 4비트 float, 'nf4' 정규화 4비트 float)
    bnb_4bit_quant_type="nf4",
  • 연산 정밀도 설정 (32비트 float 또는 16비트 bfloat)
    bnb_4bit_compute_dtype=torch.bfloat16)
Llama 3 미세 조정(Fine-Tuning)

양자화로 모델 로드

from transformers import BitsAndBytesConfig, AutoModelForCausalLM

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)

model = AutoModelForCausalLM.from_pretrained( "nvidia/Llama3-ChatQA-1.5-8B",
quantization_config=bnb_config
)
Llama 3 미세 조정(Fine-Tuning)

양자화된 모델 사용

promptstr = """System: You are a helpful chatbot who answers questions about planets.
User: Explain the history of Mars
Assistant: """

inputs = tokenizer.encode(promptstr, return_tensors="pt")
outputs = model.generate(inputs, max_length=200)
decoded_outputs = tokenizer.decode(outputs[0, inputs.shape[1]:], skip_special_tokens = True)
print(decoded_outputs)
Here is a brief history of Mars:
- 4.6 billion years ago: Mars formed as part of the solar system.
- 3.8 billion years ago: Mars had a thick atmosphere and liquid water on its surface.
- 3.8 billion years ago to 3.5 billion years ago: Mars lost its magnetic field and atmosphere, 
and became a cold, dry planet.
- 3.5 billion years ago to present: Mars has been cold and dry, with a thin atmosphere.
Llama 3 미세 조정(Fine-Tuning)

양자화된 모델 파인튜닝

  • 완전 양자화는 파인튜닝을 지원하지 않음
  • LoRA 적용
trainer = SFTTrainer(
    model=model,

peft_config=peft_config,
train_dataset=ds, max_seq_length=250, dataset_text_field='conversation', tokenizer=tokenizer, args=training_arguments
)
trainer.train()
Llama 3 미세 조정(Fine-Tuning)

Vamos praticar!

Llama 3 미세 조정(Fine-Tuning)

Preparing Video For Download...