Thu nhỏ mô hình bằng lượng tử hóa

Fine-Tuning với Llama 3

Francesca Donadoni

Curriculum Manager, DataCamp

Lượng tử hóa là gì?

 

  • Giảm độ chính xác của mô hình
  • Từ float 32-bit sang:
    • số nguyên 8-bit
    • số nguyên 4-bit
  • Huấn luyện nhận biết lượng tử hóa

khối trừu tượng.jpg

Fine-Tuning với Llama 3

Các loại lượng tử hóa

 

  • Lượng tử hóa trọng số: giảm độ chính xác của trọng số
  • Lượng tử hóa kích hoạt: giảm độ chính xác của giá trị kích hoạt
  • Lượng tử hóa sau huấn luyện: giảm độ chính xác sau khi huấn luyện
Fine-Tuning với Llama 3

Cấu hình lượng tử hóa với bitsandbytes

from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(
  • đặt độ chính xác (load_in_4_bit, load_in_8_bit)
    load_in_4bit=True,
  • đặt kiểu lượng tử hóa ('fp4' tức float 4-bit, 'nf4' tức float 4-bit chuẩn hóa)
    bnb_4bit_quant_type="nf4",
  • đặt độ chính xác tính toán (float 32-bit hoặc bfloat 16-bit)
    bnb_4bit_compute_dtype=torch.bfloat16)
Fine-Tuning với Llama 3

Tải mô hình với lượng tử hóa

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
)
Fine-Tuning với Llama 3

Dùng mô hình đã lượng tử hóa

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.
Fine-Tuning với Llama 3

Tinh chỉnh mô hình đã lượng tử hóa

  • Lượng tử hóa đầy đủ không hỗ trợ tinh chỉnh
  • Thích ứng 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()
Fine-Tuning với Llama 3

Vamos praticar!

Fine-Tuning với Llama 3

Preparing Video For Download...