量子化でモデルを小さくする

Llama 3 のファインチューニング

Francesca Donadoni

Curriculum Manager, DataCamp

量子化とは?

 

  • モデル精度の低減
  • 32-bit 浮動小数点から:
    • 8-bit 整数
    • 4-bit 整数
  • 量子化対応学習(QAT)

抽象ブロック.jpg

Llama 3 のファインチューニング

量子化の種類

 

  • 重みの量子化: 重みの精度を下げる
  • 活性化の量子化: 活性化値の精度を下げる
  • 学習後量子化: 学習後に精度を下げる
Llama 3 のファインチューニング

bitsandbytes での量子化設定

from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(
  • 精度を設定(load_in_4_bit, load_in_8_bit)
    load_in_4bit=True,
  • 量子化タイプを設定('fp4'=4-bit float、'nf4'=正規化 4-bit float)
    bnb_4bit_quant_type="nf4",
  • 計算精度を設定(32-bit float または 16-bit bfloat)
    bnb_4bit_compute_dtype=torch.bfloat16)
Llama 3 のファインチューニング

量子化付きでモデルを読み込む

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 のファインチューニング

量子化モデルの使用

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 のファインチューニング

量子化モデルの微調整

  • フル量子化は微調整をサポートしない
  • 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 のファインチューニング

Passons à la pratique !

Llama 3 のファインチューニング

Preparing Video For Download...