用量化讓模型更小

使用 Llama 3 進行微調

Francesca Donadoni

Curriculum Manager, DataCamp

什麼是量化?

 

  • 降低模型精度
  • 32 位元浮點改為:
    • 8 位元整數
    • 4 位元整數
  • 量化感知訓練

抽象方塊

使用 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 位元浮點、'nf4' 為正規化 4 位元浮點)
    bnb_4bit_quant_type="nf4",
  • 設定運算精度(32 位元 float 或 16 位元 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 進行微調

一起來練習吧!

使用 Llama 3 進行微調

Preparing Video For Download...