概述
在预训练模型的基础上,对所有参数进行微调。
原理
预训练任务类型
自回归语言模型是根据上文内容预测下一个可能的单词,就是常说的自左向右的语言模型任务,或者反过来也行,就是根据下文预测前面的单词。GPT 就是典型的自回归语言模型。
自回归语言模型预测
指令微调数据处理
指令、输入及输出
如图所示,下面的代码根据这个算法实现:
-1.目标:通过1预测2,通过2预测3,一直到cos。
-2.输入(指令+input)、输出label(目标值)
-3.前面的输入不需要预测,直接设置-100
def process_func(example):
MAX_LENGTH = 256 # 定义最大长度为256
input_ids, attention_mask, labels = [], [], [] # 初始化输入ID、注意力掩码和标签列表
# 对指令和输入进行编码,返回输入ID和注意力掩码(拼接指令和输入)
instruction = tokenizer("\n".join(["Human: " + example["instruction"], example["input"]]).strip() + "\n\nAssistant: ")
# 对输出进行编码,返回输出ID和注意力掩码
response = tokenizer(example["output"] + tokenizer.eos_token)
# 将指令和回应的输入ID合并(拼接输入和输出)
input_ids = instruction["input_ids"] + response["input_ids"]
# 将指令和回应的注意力掩码合并
attention_mask = instruction["attention_mask"] + response["attention_mask"]
# 标签列表的前半部分是指令的长度个-100(表示这些位置的标签是被忽略的),后半部分是回应的输入ID
labels = [-100] * len(instruction["input_ids"]) + response["input_ids"]
# 如果输入ID的长度大于最大长度,将其截断为最大长度
if len(input_ids) > MAX_LENGTH:
input_ids = input_ids[:MAX_LENGTH]
attention_mask = attention_mask[:MAX_LENGTH]
labels = labels[:MAX_LENGTH]
# 返回一个包含输入ID列表、注意力掩码列表和标签列表的字典
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"labels": labels
}
模型和数据集选择
- 目标:训练一个对话模型
- 模型:https://huggingface.co/Langboat/bloom-800m-zh
This model is based on bigscience/bloom-1b1.
We pruned its vocabulary from 250880 to 46145 with Chinese corpus to reduce GPU memory usage. So the total parameter is 800m now. - 数据集:https://huggingface.co/datasets/c-s-ale/alpaca-gpt4-data-zh
The data is intended and licensed for research use only. The dataset is CC BY NC 4.0 (allowing only non-commercial use) and models trained using the dataset should not be used outside of research purposes.
数据集格式
全量微调
1.导包:导入第三方库
2.加载数据集:例如,https://huggingface.co/datasets/c-s-ale/alpaca-gpt4-data-zh
3.数据预处理
4.创建模型:例如https://huggingface.co/Langboat/bloom-800m-zh
5.配置训练参数
6.创建训练器
7.模型训练
8.模型推理
# # 全量微调
# ## Step1 导入相关包
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForSeq2Seq, TrainingArguments, Trainer
# ## Step2 加载数据集
ds = Dataset.load_from_disk("data/alpaca_data_zh/")
tokenizer = AutoTokenizer.from_pretrained("Langboat/bloom-800m-zh")
# ## Step3 数据集预处理
## 对数据进行预处理,后面的列名没有用都去掉
tokenized_ds = ds.map(process_func, remove_columns=ds.column_names)
## 检查一下数据格式,知识部分是否符合我们的需求
tokenizer.decode(tokenized_ds[1]["input_ids"])
## 检查一下数据格式,目标值是否符合我们的需求
tokenizer.decode(list(filter(lambda x: x != -100, tokenized_ds[1]["labels"])))
# ## Step4 创建模型
model = AutoModelForCausalLM.from_pretrained("Langboat/bloom-800m-zh")
# ## Step5 配置训练参数
args = TrainingArguments(
output_dir="./tuningdata/boomtuning",
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
logging_steps=10,
num_train_epochs=1
)
# ## Step6 创建训练器
trainer = Trainer(
model=model,
args=args,
train_dataset=tokenized_ds,
data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True)
)
# ## Step7 模型训练
trainer.train()
# ## Step8 模型推理
from transformers import pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0)
ipt = "Human: {}\n{}".format("如何写好一首好诗?", "").strip() + "\n\nAssistant: "
pipe(ipt, max_length=256, do_sample=True, )