Chapter 22
生成式对话机器人
Notebooktransformers24 cells
生成式对话机器人
Step1 导入相关包
In [ ]python · cell 3
python
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForSeq2Seq, TrainingArguments, TrainerStep2 加载数据集
In [ ]python · cell 5
python
ds = Dataset.load_from_disk("./alpaca_data_zh/")
dsIn [ ]python · cell 6
python
ds[:3]Step3 数据集预处理
In [ ]python · cell 8
python
tokenizer = AutoTokenizer.from_pretrained("Langboat/bloom-389m-zh")
tokenizerIn [ ]python · cell 9
python
def process_func(example):
MAX_LENGTH = 256
input_ids, attention_mask, labels = [], [], []
instruction = tokenizer("\n".join(["Human: " + example["instruction"], example["input"]]).strip() + "\n\nAssistant: ")
response = tokenizer(example["output"] + tokenizer.eos_token)
input_ids = instruction["input_ids"] + response["input_ids"]
attention_mask = instruction["attention_mask"] + response["attention_mask"]
labels = [-100] * len(instruction["input_ids"]) + response["input_ids"]
if len(input_ids) > MAX_LENGTH:
input_ids = input_ids[:MAX_LENGTH]
attention_mask = attention_mask[:MAX_LENGTH]
labels = labels[:MAX_LENGTH]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"labels": labels
}In [ ]python · cell 10
python
tokenized_ds = ds.map(process_func, remove_columns=ds.column_names)
tokenized_dsIn [ ]python · cell 11
python
tokenizer.decode(tokenized_ds[1]["input_ids"])In [ ]python · cell 12
python
tokenizer.decode(list(filter(lambda x: x != -100, tokenized_ds[1]["labels"])))Step4 创建模型
In [ ]python · cell 14
python
model = AutoModelForCausalLM.from_pretrained("Langboat/bloom-389m-zh")Step5 配置训练参数
In [ ]python · cell 16
python
args = TrainingArguments(
output_dir="./chatbot",
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
logging_steps=10,
num_train_epochs=2
)Step6 创建训练器
In [ ]python · cell 18
python
trainer = Trainer(
model=model,
args=args,
tokenizer=tokenizer,
train_dataset=tokenized_ds,
data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True)
)Step7 模型训练
In [ ]python · cell 20
python
trainer.train()Step8 模型推理
In [ ]python · cell 22
python
from transformers import pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0)In [ ]python · cell 23
python
ipt = "Human: {}\n{}".format("考试有哪些技巧?", "").strip() + "\n\nAssistant: "
pipe(ipt, max_length=256, do_sample=True, )In [ ]python · cell 24
python
