关于人工智能:使用-LoRA-和-Hugging-Face-高效训练大语言模型

6次阅读

共计 9674 个字符,预计需要花费 25 分钟才能阅读完成。

在本文中,咱们将展现如何应用 大语言模型低秩适配 (Low-Rank Adaptation of Large Language Models,LoRA) 技术在单 GPU 上微调 110 亿参数的 FLAN-T5 XXL 模型。在此过程中,咱们会应用到 Hugging Face 的 Transformers、Accelerate 和 PEFT 库。

通过本文,你会学到:

  1. 如何搭建开发环境
  2. 如何加载并筹备数据集
  3. 如何应用 LoRA 和 bnb (即 bitsandbytes) int-8 微调 T5
  4. 如何评估 LoRA FLAN-T5 并将其用于推理
  5. 如何比拟不同计划的性价比

另外,你能够 点击这里 在线查看此博文对应的 Jupyter Notebook。

疾速入门: 轻量化微调 (Parameter Efficient Fine-Tuning,PEFT)

PEFT 是 Hugging Face 的一个新的开源库。应用 PEFT 库,无需微调模型的全副参数,即可高效地将预训练语言模型 (Pre-trained Language Model,PLM) 适配到各种上游利用。PEFT 目前反对以下几种办法:

  • LoRA: LORA: LOW-RANK ADAPTATION OF LARGE LANGUAGE MODELS
  • Prefix Tuning: P-Tuning v2: Prompt Tuning Can Be Comparable to Fine-tuning Universally Across Scales and Tasks
  • P-Tuning: GPT Understands, Too
  • Prompt Tuning: The Power of Scale for Parameter-Efficient Prompt Tuning

留神: 本教程是在 g5.2xlarge AWS EC2 实例上创立和运行的,该实例蕴含 1 个 NVIDIA A10G

1. 搭建开发环境

在本例中,咱们应用 AWS 预置的 PyTorch 深度学习 AMI,其已装置了正确的 CUDA 驱动程序和 PyTorch。在此基础上,咱们还须要装置一些 Hugging Face 库,包含 transformers 和 datasets。运行上面的代码就可装置所有须要的包。

# install Hugging Face Libraries
!pip install git+https://github.com/huggingface/peft.git
!pip install "transformers==4.27.1" "datasets==2.9.0" "accelerate==0.17.1" "evaluate==0.4.0" "bitsandbytes==0.37.1" loralib --upgrade --quiet
# install additional dependencies needed for training
!pip install rouge-score tensorboard py7zr

2. 加载并筹备数据集

这里,咱们应用 samsum 数据集,该数据集蕴含大概 16k 个含摘要的聊天类对话数据。这些对话由精通英语的语言学家制作。

{
  "id": "13818513",
  "summary": "Amanda baked cookies and will bring Jerry some tomorrow.",
  "dialogue": "Amanda: I baked cookies. Do you want some?\r\nJerry: Sure!\r\nAmanda: I'll bring you tomorrow :-)"
}

咱们应用 🤗 Datasets 库中的 load_dataset() 办法来加载 samsum 数据集。

from datasets import load_dataset

# Load dataset from the hub
dataset = load_dataset("samsum")

print(f"Train dataset size: {len(dataset['train'])}")
print(f"Test dataset size: {len(dataset['test'])}")

# Train dataset size: 14732
# Test dataset size: 819

为了训练模型,咱们要用 🤗 Transformers Tokenizer 将输出文本转换为词元 ID。如果你须要理解这一方面的常识,请移步 Hugging Face 课程的 第 6 章

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

model_id="google/flan-t5-xxl"

# Load tokenizer of FLAN-t5-XL
tokenizer = AutoTokenizer.from_pretrained(model_id)

在开始训练之前,咱们还须要对数据进行预处理。生成式文本摘要属于文本生成工作。咱们将文本输出给模型,模型会输入摘要。咱们须要理解输出和输入文本的长度信息,以利于咱们高效地批量解决这些数据。

from datasets import concatenate_datasets
import numpy as np
# The maximum total input sequence length after tokenization.
# Sequences longer than this will be truncated, sequences shorter will be padded.
tokenized_inputs = concatenate_datasets([dataset["train"], dataset["test"]]).map(lambda x: tokenizer(x["dialogue"], truncation=True), batched=True, remove_columns=["dialogue", "summary"])
input_lenghts = [len(x) for x in tokenized_inputs["input_ids"]]
# take 85 percentile of max length for better utilization
max_source_length = int(np.percentile(input_lenghts, 85))
print(f"Max source length: {max_source_length}")

# The maximum total sequence length for target text after tokenization.
# Sequences longer than this will be truncated, sequences shorter will be padded."tokenized_targets = concatenate_datasets([dataset["train"], dataset["test"]]).map(lambda x: tokenizer(x["summary"], truncation=True), batched=True, remove_columns=["dialogue","summary"])
target_lenghts = [len(x) for x in tokenized_targets["input_ids"]]
# take 90 percentile of max length for better utilization
max_target_length = int(np.percentile(target_lenghts, 90))
print(f"Max target length: {max_target_length}")

咱们将在训练前对立对数据集进行预处理并将预处理后的数据集保留到磁盘。你能够在本地机器或 CPU 上运行此步骤并将其上传到 Hugging Face Hub。

def preprocess_function(sample,padding="max_length"):
    # add prefix to the input for t5
    inputs = ["summarize:" + item for item in sample["dialogue"]]

    # tokenize inputs
    model_inputs = tokenizer(inputs, max_length=max_source_length, padding=padding, truncation=True)

    # Tokenize targets with the `text_target` keyword argument
    labels = tokenizer(text_target=sample["summary"], max_length=max_target_length, padding=padding, truncation=True)

    # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
    # padding in the loss.
    if padding == "max_length":
        labels["input_ids"] = [[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
        ]

    model_inputs["labels"] = labels["input_ids"]
    return model_inputs

tokenized_dataset = dataset.map(preprocess_function, batched=True, remove_columns=["dialogue", "summary", "id"])
print(f"Keys of tokenized dataset: {list(tokenized_dataset['train'].features)}")

# save datasets to disk for later easy loading
tokenized_dataset["train"].save_to_disk("data/train")
tokenized_dataset["test"].save_to_disk("data/eval")

3. 应用 LoRA 和 bnb int-8 微调 T5

除了 LoRA 技术,咱们还应用 bitsanbytes LLM.int8() 把解冻的 LLM 量化为 int8。这使咱们可能将 FLAN-T5 XXL 所需的内存升高到约四分之一。

训练的第一步是加载模型。咱们应用 philschmid/flan-t5-xxl-sharded-fp16 模型,它是 google/flan-t5-xxl 的分片版。分片能够让咱们在加载模型时不耗尽内存。

from transformers import AutoModelForSeq2SeqLM

# huggingface hub model id
model_id = "philschmid/flan-t5-xxl-sharded-fp16"

# load model from the hub
model = AutoModelForSeq2SeqLM.from_pretrained(model_id, load_in_8bit=True, device_map="auto")

当初,咱们能够应用 peft 为 LoRA int-8 训练作筹备了。

from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, TaskType

# Define LoRA Config
lora_config = LoraConfig(
 r=16,
 lora_alpha=32,
 target_modules=["q", "v"],
 lora_dropout=0.05,
 bias="none",
 task_type=TaskType.SEQ_2_SEQ_LM
)
# prepare int-8 model for training
model = prepare_model_for_int8_training(model)

# add LoRA adaptor
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()

# trainable params: 18874368 || all params: 11154206720 || trainable%: 0.16921300163961817

如你所见,这里咱们只训练了模型参数的 0.16%!这个微小的内存增益让咱们安心地微调模型,而不必放心内存问题。

接下来须要创立一个 DataCollator,负责对输出和标签进行填充,咱们应用 🤗 Transformers 库中的 DataCollatorForSeq2Seq 来实现这一环节。

from transformers import DataCollatorForSeq2Seq

# we want to ignore tokenizer pad token in the loss
label_pad_token_id = -100
# Data collator
data_collator = DataCollatorForSeq2Seq(
    tokenizer,
    model=model,
    label_pad_token_id=label_pad_token_id,
    pad_to_multiple_of=8
)

最初一步是定义训练超参 (TrainingArguments)。

from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments

output_dir="lora-flan-t5-xxl"

# Define training args
training_args = Seq2SeqTrainingArguments(
    output_dir=output_dir,
        auto_find_batch_size=True,
    learning_rate=1e-3, # higher learning rate
    num_train_epochs=5,
    logging_dir=f"{output_dir}/logs",
    logging_strategy="steps",
    logging_steps=500,
    save_strategy="no",
    report_to="tensorboard",
)

# Create Trainer instance
trainer = Seq2SeqTrainer(
    model=model,
    args=training_args,
    data_collator=data_collator,
    train_dataset=tokenized_dataset["train"],
)
model.config.use_cache = False # silence the warnings. Please re-enable for inference!

运行上面的代码,开始训练模型。请留神,对于 T5,出于收敛稳定性考量,某些层咱们仍放弃 float32 精度。

# train model
trainer.train()

训练耗时约 10 小时 36 分钟,训练 10 小时的老本约为 13.22 美元 。相比之下,如果 在 FLAN-T5-XXL 上进行全模型微调 10 个小时,咱们须要 8 个 A100 40GB,老本约为 322 美元。

咱们能够将模型保留下来以用于前面的推理和评估。咱们临时将其保留到磁盘,但你也能够应用 model.push_to_hub 办法将其上传到 Hugging Face Hub。

# Save our LoRA model & tokenizer results
peft_model_id="results"
trainer.model.save_pretrained(peft_model_id)
tokenizer.save_pretrained(peft_model_id)
# if you want to save the base model to call
# trainer.model.base_model.save_pretrained(peft_model_id)

最初生成的 LoRA checkpoint 文件很小,仅需 84MB 就蕴含了从 samsum 数据集上学到的所有常识。

4. 应用 LoRA FLAN-T5 进行评估和推理

咱们将应用 evaluate 库来评估 rogue 分数。咱们能够应用 PEFTtransformers 来对 FLAN-T5 XXL 模型进行推理。对 FLAN-T5 XXL 模型,咱们至多须要 18GB 的​​ GPU 显存。

import torch
from peft import PeftModel, PeftConfig
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

# Load peft config for pre-trained checkpoint etc.
peft_model_id = "results"
config = PeftConfig.from_pretrained(peft_model_id)

# load base LLM model and tokenizer
model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path, load_in_8bit=True, device_map={"":0})
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)

# Load the Lora model
model = PeftModel.from_pretrained(model, peft_model_id, device_map={"":0})
model.eval()

print("Peft model loaded")

咱们用测试数据集中的一个随机样本来试试摘要成果。

from datasets import load_dataset
from random import randrange

# Load dataset from the hub and get a sample
dataset = load_dataset("samsum")
sample = dataset['test'][randrange(len(dataset["test"]))]

input_ids = tokenizer(sample["dialogue"], return_tensors="pt", truncation=True).input_ids.cuda()
# with torch.inference_mode():
outputs = model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=True, top_p=0.9)
print(f"input sentence: {sample['dialogue']}\n{'---'* 20}")

print(f"summary:\n{tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0]}")

不错!咱们的模型无效!当初,让咱们认真看看,并应用 test 集中的全副数据对其进行评估。为此,咱们须要实现一些工具函数来帮忙生成摘要并将其与相应的参考摘要组合到一起。评估摘要工作最罕用的指标是 rogue_score),它的全称是 Recall-Oriented Understudy for Gisting Evaluation。与罕用的准确率指标不同,它将生成的摘要与一组参考摘要进行比拟。

import evaluate
import numpy as np
from datasets import load_from_disk
from tqdm import tqdm

# Metric
metric = evaluate.load("rouge")

def evaluate_peft_model(sample,max_target_length=50):
    # generate summary
    outputs = model.generate(input_ids=sample["input_ids"].unsqueeze(0).cuda(), do_sample=True, top_p=0.9, max_new_tokens=max_target_length)
    prediction = tokenizer.decode(outputs[0].detach().cpu().numpy(), skip_special_tokens=True)
    # decode eval sample
    # Replace -100 in the labels as we can't decode them.
    labels = np.where(sample['labels']!= -100, sample['labels'], tokenizer.pad_token_id)
    labels = tokenizer.decode(labels, skip_special_tokens=True)

    # Some simple post-processing
    return prediction, labels

# load test dataset from distk
test_dataset = load_from_disk("data/eval/").with_format("torch")

# run predictions
# this can take ~45 minutes
predictions, references = [], []
for sample in tqdm(test_dataset):
    p,l = evaluate_peft_model(sample)
    predictions.append(p)
    references.append(l)

# compute metric
rogue = metric.compute(predictions=predictions, references=references, use_stemmer=True)

# print results
print(f"Rogue1: {rogue['rouge1']* 100:2f}%")
print(f"rouge2: {rogue['rouge2']* 100:2f}%")
print(f"rougeL: {rogue['rougeL']* 100:2f}%")
print(f"rougeLsum: {rogue['rougeLsum']* 100:2f}%")

# Rogue1: 50.386161%
# rouge2: 24.842412%
# rougeL: 41.370130%
# rougeLsum: 41.394230%

咱们 PEFT 微调后的 FLAN-T5-XXL 在测试集上获得了 50.38% 的 rogue1 分数。相比之下,flan-t5-base 的全模型微调取得了 47.23 的 rouge1 分数。rouge1 分数进步了 3%

令人难以置信的是,咱们的 LoRA checkpoint 只有 84MB,而且性能比对更小的模型进行全模型微调后的 checkpoint 更好。

你能够 点击这里 在线查看此博文对应的 Jupyter Notebook。


英文原文: https://www.philschmid.de/fine-tune-flan-t5-peft

原文作者:Philipp Schmid

译者: Matrix Yao (姚伟峰),英特尔深度学习工程师,工作方向为 transformer-family 模型在各模态数据上的利用及大规模模型的训练推理。

排版 / 审校: zhongdongy (阿东)

正文完
 0