使用 Hugging Face 微调模型

使用 Llama 3 进行微调

Francesca Donadoni

Curriculum Manager, DataCamp

完成微调需要哪些要素?

  1. 语言模型 + 分词器(如 LLama 模型:TinyLLama-v0)
  2. 训练数据集(Bitext 客服数据集)
  3. 训练参数
  4. 执行微调(来自 TRL 的 SFTTrainer)
  5. 评估基准或数据集

训练循环。训练需要训练参数、数据和模型,并生成微调后的模型。评估使用微调模型和评估数据集。

使用 Llama 3 进行微调

使用 Auto 类加载模型与分词器

model_name="Maykeye/TinyLLama-v0"

model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

tokenizer.pad_token = tokenizer.eos_token
1 https://huggingface.co/docs/transformers/main/en/model_doc/auto
使用 Llama 3 进行微调

用 TrainingArguments 定义训练参数

training_arguments = TrainingArguments(

per_device_train_batch_size=1,
learning_rate=2e-3,
max_grad_norm=0.3,
max_steps=200,
... gradient_accumulation_steps=2, save_steps=10,
)
1 https://huggingface.co/docs/transformers/v4.40.1/en/main_classes/trainer#transformers.TrainingArguments
使用 Llama 3 进行微调

如何用 SFTTrainer 配置训练

trainer = SFTTrainer(

model=model, tokenizer=tokenizer,
train_dataset=dataset, dataset_text_field='conversation',
max_seq_length=250,
args=training_arguments
)
使用 Llama 3 进行微调

解读 SFTTrainer 的微调结果

trainer.train()
TrainOutput(global_step=200, training_loss=1.9401231002807617,
            metrics={'train_runtime': 142.5501, 
                     'train_samples_per_second': 2.806,
                     'train_steps_per_second': 1.403, 
                     'total_flos': 1461265827840.0, 
                     'train_loss': 1.9401231002807617, 
                     'epoch': 2.0})
使用 Llama 3 进行微调

如何用 ROUGE-1 评估已训练模型

  • ROUGE-1:参考文本与生成文本的词重合率
import evaluate

rouge = evaluate.load('rouge')
predictions = ["hello there", "general kenobi"] references = ["hello there", "master yoda"]
results = rouge.compute(predictions=predictions, references=references) print(results)
{'rouge1': 0.5, 'rouge2': 0.5, 'rougeL': 0.5, 'rougeLsum': 0.5}
1 https://huggingface.co/spaces/evaluate-metric/rouge
使用 Llama 3 进行微调

如何使用 ROUGE-1 分数

  1. 使用 evaluation_dataset 中的验证集
def generate_predictions_and_reference(dataset):
    predictions = []
    references = []
    for row in dataset:
        inputs = tokenizer.encode(row["instruction"], return_tensors="pt")

outputs = model.generate(inputs)
decoded_outputs = tokenizer.decode(outputs[0, inputs.shape[1]:], skip_special_tokens = True)
references += [row["response"]] predictions += [decoded_outputs] return references, predictions
使用 Llama 3 进行微调

如何在验证集上运行 ROUGE-1

references, predictions = generate_predictions_and_reference(evaluation_dataset)
rouge = evaluate.load('rouge')
results = rouge.compute(predictions=predictions, references=references)
print(results)
使用 Llama 3 进行微调

微调 vs 未微调

微调后

{'rouge1': 0.22425812699023645,
 'rouge2': 0.039502543246449,
 'rougeL': 0.1501513006868983,
 'rougeLsum': 0.18685597710721613}

未微调

{'rouge1': 0.1310928764315105,
 'rouge2': 0.04581654122835097,
 'rougeL': 0.08415351421221628,
 'rougeLsum': 0.1224749866097021}
使用 Llama 3 进行微调

Passons à la pratique !

使用 Llama 3 进行微调

Preparing Video For Download...