Chapter 36
ChatGLM3 Lora 实战
Notebooktransformers34 cells
ChatGLM3 Lora 实战
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("../data/alpaca_data_zh/")
dsIn [ ]python · cell 6
python
ds[:3]Step3 数据集预处理
In [ ]python · cell 8
python
tokenizer = AutoTokenizer.from_pretrained("d:/Pretrained_models/ZhipuAI/chatglm3-6b-base/", trust_remote_code=True)
tokenizerIn [ ]python · cell 9
python
tokenizer(tokenizer.eos_token), tokenizer.eos_token_idIn [ ]python · cell 10
python
def process_func(example):
MAX_LENGTH = 256
input_ids, attention_mask, labels = [], [], []
instruction = "\n".join([example["instruction"], example["input"]]).strip() # query
instruction = tokenizer.build_chat_input(instruction, history=[], role="user") # [gMASK]sop<|user|> \n query<|assistant|>
response = tokenizer("\n" + example["output"], add_special_tokens=False) # \n response, 缺少eos token
input_ids = instruction["input_ids"][0].numpy().tolist() + response["input_ids"] + [tokenizer.eos_token_id]
attention_mask = instruction["attention_mask"][0].numpy().tolist() + response["attention_mask"] + [1]
labels = [-100] * len(instruction["input_ids"][0].numpy().tolist()) + response["input_ids"] + [tokenizer.eos_token_id]
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 11
python
tokenized_ds = ds.map(process_func, remove_columns=ds.column_names)
tokenized_dsIn [ ]python · cell 12
python
tokenizer.decode(tokenized_ds[1]["input_ids"])In [ ]python · cell 13
python
tokenizer.decode(list(filter(lambda x: x != -100, tokenized_ds[1]["labels"])))Step4 创建模型
In [ ]python · cell 15
python
import torch
model = AutoModelForCausalLM.from_pretrained("d:/Pretrained_models/ZhipuAI/chatglm3-6b-base/", trust_remote_code=True, low_cpu_mem_usage=True,
torch_dtype=torch.bfloat16, device_map="auto", load_in_8bit=True)In [ ]python · cell 16
python
for name, param in model.named_parameters():
print(name, param.dtype)Lora
PEFT Step1 配置文件
In [ ]python · cell 19
python
from peft import LoraConfig, TaskType, get_peft_model, PeftModel
config = LoraConfig(target_modules=["query_key_value"])
configPEFT Step2 创建模型
In [ ]python · cell 21
python
model = get_peft_model(model, config)In [ ]python · cell 22
python
configIn [ ]python · cell 23
python
for name, parameter in model.named_parameters():
print(name)In [ ]python · cell 24
python
model.print_trainable_parameters()In [ ]python · cell 25
python
modelStep5 配置训练参数
In [ ]python · cell 27
python
args = TrainingArguments(
output_dir="./chatbot",
per_device_train_batch_size=2,
gradient_accumulation_steps=16,
logging_steps=10,
num_train_epochs=1,
learning_rate=1e-4,
remove_unused_columns=False
)Step6 创建训练器
In [ ]python · cell 29
python
trainer = Trainer(
model=model,
args=args,
tokenizer=tokenizer,
train_dataset=tokenized_ds.select(range(6000)),
data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),
)Step7 模型训练
In [ ]python · cell 31
python
trainer.train()Step8 模型推理
In [ ]python · cell 33
python
model.eval()
print(model.chat(tokenizer, "数学考试怎么考高分?", history=[])[0])In [ ]python · cell 34
python
