11 对话模型微调

2024-08-30 23:28
文章标签 模型 微调 对话

本文主要是介绍11 对话模型微调,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

提问:其实我一直觉的数据是最费事的一个,现在都是使用别人的数据,如果对于实际场景中那么我们该如何获取处理数据呢!

1 数据处理;

2 模型选择,调参数;

数据

llm-wizard/alpaca-gpt4-data-zh · Datasets at HF Mirror

模型

魔搭社区

1 数据

Instruction: 问题

input: 输入部分,辅助解读问题  

output: 问题的答案

数据怎么处理呢:

  1. 我们加个前缀"Human"+《instruction》+《input》:这个我为输入部分;
  2. -100 通常用于表示忽略某个位置的损失计算。我们只对回答部分做损失计算;
  3. 这样就把输入回答拼接在一起了,然后只对回答部分计算损失;

2 模型 

        "BLOOM" 是一个由 BigScience 联盟开发的大规模多语言预训练语言模型。"BLOOM" 模型的设计目的是为了能够理解和生成多种语言的文本,包括但不限于英语、汉语等。"1.4B" 这个后缀通常指的是模型的参数量,即这个版本的 BLOOM 模型拥有大约 14 亿个参数。

关于您提到的 "Bloom预训练生成模型-中文-1.4B",这可能是指一个专为中文优化的 BLOOM 模型变体,其参数量为 14 亿。这样的模型在处理中文文本时应该会有较好的表现,因为它经过了大量的中文语料训练,能够捕捉到中文语言的特性和结构。

模型的参数:1.3B,

占用内存:1.3B * 4 = 5.2G B 

训练: 5.2GB * 4 = 21GB;

GPU 低于21G那就别玩了!

我的 NVIDIA英伟达Tesla L40S 48GB;

 batchsize = 32, 不能玩了;只能为8;

2.1 全参数训练

from datasets import Dataset
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForSeq2Seq, TrainingArguments, Trainer# 日志
from transformers import DataCollatorWithPadding
from transformers.trainer_callback import TrainerCallback
import matplotlib.pyplot as pltds = Dataset.load_from_disk("../data/")
ds
# 分词
tokenizer = AutoTokenizer.from_pretrained("../bloom-model/")
tokenizerdef process_func(example):MAX_LENGTH = 256input_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}tokenized_ds = ds.map(process_func, remove_columns=ds.column_names)
tokenized_dsprint(tokenizer.decode(tokenized_ds[1]["input_ids"]))
print()
print(tokenizer.decode(list(filter(lambda x: x != -100, tokenized_ds[1]["labels"])))
)sum([param.numel() for param in model.parameters()]) / 1000000000# 自定义回调类,用于在训练过程中打印损失
model = AutoModelForCausalLM.from_pretrained("../bloom-model/")class PrintLossCallback(TrainerCallback):def __init__(self):self.losses = []self.steps = []def on_log(self, args, state, control, logs=None, **kwargs):# 打印训练过程中的日志信息try:if logs is not None:print(f"Step {state.global_step}: Loss={logs['loss']:.4f}, Learning Rate={logs['learning_rate']:.6f}")self.losses.append(logs['loss'])self.steps.append(state.global_step)except Exception as e :print(f'on_log error {e}')def plot_losses(self):plt.figure(figsize=(10, 5))plt.plot(self.steps, self.losses, label='Training Loss')plt.xlabel('Steps')plt.ylabel('Loss')plt.title('Training Loss Over Time')plt.legend()plt.show()args = TrainingArguments(output_dir="./chatbot",per_device_train_batch_size=8,gradient_accumulation_steps=8,logging_steps=10,num_train_epochs=2
)
plot_losses_callback = PrintLossCallback()
trainer = Trainer(model=model,args=args,tokenizer=tokenizer,train_dataset=tokenized_ds,data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),callbacks=[plot_losses_callback]  # 注册自定义回调
)if torch.cuda.is_available():trainer.model = trainer.model.to("cuda")
# 训练模型
trainer.train()

 过程很慢!

 2.2 Prompt-Tuning

安装依赖: installed peft-0.12.0

在Prompt Tuning方法中,主要改变的是输入结构而不是直接调整模型本身的参数。

         Prompt-Tuning 高效微调只会训练新增的Prompt的表示层,模型的其余参数全部固定;

        新增的 Prompt 内容可以分为 Hard Prompt 和 Soft Prompt 两类;

        Soft prompt 通常指的是一种较为宽泛或模糊的提示,允许模型在生成结果时有更大的自由度,通常用于启发模型进行创造性的生成;

        Hard prompt 是一种更为具体和明确的提示,要求模型按照给定的信息生成精确的结果,通常用于需要模型提供准确答案的任务;

        Soft Prompt 在 peft 中一般是随机初始化prompt的文本内容,而 Hard prompt 则一般需要设置具体的提示文本内容;

from datasets import Dataset
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DataCollatorForSeq2Seq, TrainingArguments, Trainerds = Dataset.load_from_disk("../data/")
dstokenizer = AutoTokenizer.from_pretrained("../bloom-model/")
tokenizer
def process_func(example):MAX_LENGTH = 256input_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}tokenized_ds = ds.map(process_func, remove_columns=ds.column_names)
tokenized_dsfrom transformers import DataCollatorWithPadding
from transformers.trainer_callback import TrainerCallback
import matplotlib.pyplot as pltfrom peft import PromptTuningConfig, get_peft_model, TaskType, PromptTuningInit# Soft Prompt
# config = PromptTuningConfig(task_type=TaskType.CAUSAL_LM, num_virtual_tokens=10)
# config
# Hard Prompt
config = PromptTuningConfig(task_type=TaskType.CAUSAL_LM,prompt_tuning_init=PromptTuningInit.TEXT,prompt_tuning_init_text="下面是一段人与机器人的对话。",num_virtual_tokens=len(tokenizer("下面是一段人与机器人的对话。")["input_ids"]),tokenizer_name_or_path="../bloom-model/")
configclass PrintLossCallback(TrainerCallback):def __init__(self):self.losses = []self.steps = []def on_log(self, args, state, control, logs=None, **kwargs):# 打印训练过程中的日志信息try:if logs is not None:print(f"Step {state.global_step}: Loss={logs['loss']:.4f}, Learning Rate={logs['learning_rate']:.6f}")self.losses.append(logs['loss'])self.steps.append(state.global_step)except Exception as e :print(f'on_log error {e}')def plot_losses(self):plt.figure(figsize=(10, 5))plt.plot(self.steps, self.losses, label='Training Loss')plt.xlabel('Steps')plt.ylabel('Loss')plt.title('Training Loss Over Time')plt.legend()plt.show()args = TrainingArguments(output_dir="./chatbot_prompt",per_device_train_batch_size=8,gradient_accumulation_steps=8,logging_steps=10,num_train_epochs=1,#save_steps=20,
)
plot_losses_callback = PrintLossCallback()
trainer = Trainer(model=model,args=args,tokenizer=tokenizer,train_dataset=tokenized_ds,data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),callbacks=[plot_losses_callback]  # 注册自定义回调
)if torch.cuda.is_available():trainer.model = trainer.model.to("cuda")
# 训练模型
trainer.train()

效果没有全调参数好,收敛也很慢! 

2.3 推理

model.save_pretrained(args.output_dir)
from peft import PeftModel
# 在一个jupyter文件中,如果前面已经加载了模型,并对模型做了一定修改,则需要重新加载原始模型
model = AutoModelForCausalLM.from_pretrained("../bloom-model/")
peft_model = PeftModel.from_pretrained(model=model, model_id="./chatbot_prompt/")peft_model = peft_model.cuda()
ipt = tokenizer("Human: {}\n{}".format("考试有哪些技巧?", "").strip() + "\n\nAssistant: ", return_tensors="pt").to(peft_model.device)
print(tokenizer.decode(peft_model.generate(**ipt, max_length=128, do_sample=True)[0], skip_special_tokens=True))

这篇关于11 对话模型微调的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1122235

相关文章

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

Pytorch微调BERT实现命名实体识别

《Pytorch微调BERT实现命名实体识别》命名实体识别(NER)是自然语言处理(NLP)中的一项关键任务,它涉及识别和分类文本中的关键实体,BERT是一种强大的语言表示模型,在各种NLP任务中显著... 目录环境准备加载预训练BERT模型准备数据集标记与对齐微调 BERT最后总结环境准备在继续之前,确

Spring AI与DeepSeek实战一之快速打造智能对话应用

《SpringAI与DeepSeek实战一之快速打造智能对话应用》本文详细介绍了如何通过SpringAI框架集成DeepSeek大模型,实现普通对话和流式对话功能,步骤包括申请API-KEY、项目搭... 目录一、概述二、申请DeepSeek的API-KEY三、项目搭建3.1. 开发环境要求3.2. mav

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav