通过量化缩小模型

使用 Llama 3 进行微调

Francesca Donadoni

Curriculum Manager, DataCamp

什么是量化?

 

  • 降低模型精度
  • 32 位浮点改为:
    • 8 位整数
    • 4 位整数
  • 量化感知训练

抽象方块.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 位浮点,"nf4" 归一化 4 位浮点)
    bnb_4bit_quant_type="nf4",
  • 设置计算精度(32 位浮点或 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 进行微调

Passons à la pratique !

使用 Llama 3 进行微调

Preparing Video For Download...