BaiChuan2保姆级微调范例

news2025/3/12 19:38:14

前方干货预警:这可能是你能够找到的,最容易理解,最容易跑通的,适用于各种开源LLM模型的,同时支持多轮和单轮对话数据集的大模型高效微调范例。

我们构造了一个修改大模型自我认知的3轮对话的玩具数据集,使用QLoRA算法,只需要5分钟的训练时间,就可以完成微调,并成功修改了LLM模型的自我认知。

公众号美食屋后台回复关键词: torchkeras,获取本文notebook源代码和更多有趣范例~

before:

bb9a25883230c45e2b4200557cd778c7.png

after:

6f14d34b783612e990c2f07f451f34ab.png

通过借鉴FastChat对各种开源LLM模型进行数据预处理方法统一管理的方法,因此本范例适用于非常多不同的开源LLM模型包括 BaiChuan2-13b-chat, Qwen-7b-Chat,Qwen-14b-Chat,BaiChuan2-13B-Chat, Llama-13b-chat,  Intern-7b-chat, ChatGLM2-6b-chat 以及其它许许多多FastChat支持的模型。

在多轮对话模式下,我们按照如下格式构造包括多轮对话中所有机器人回复内容的标签。

(注:llm.build_inputs_labels(messages,multi_rounds=True) 时采用)

inputs = <user1> <assistant1> <user2> <assistant2> <user3> <assistant3>
labels = <-100> <assistant1> <-100> <assistant2> <-100> <assistant3>

在单轮对话模式下,我们仅将最后一轮机器人的回复作为要学习的标签。

(注:llm.build_inputs_labels(messages,multi_rounds=False)时采用)

inputs = <user1> <assistant1> <user2> <assistant2> <user3> <assistant3>
labels = <-100> <-100> <-100> <-100> <-100> <assistant3>

〇,预训练模型

import warnings
warnings.filterwarnings('ignore')


import torch
from transformers import AutoTokenizer, AutoModelForCausalLM,AutoConfig, AutoModel, BitsAndBytesConfig
from transformers.generation.utils import GenerationConfig
import torch.nn as nn


model_name_or_path ='baichuan2-13b'  #联网远程加载 'baichuan-inc/Baichuan2-13B-Chat'

bnb_config=BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.float16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4",
            llm_int8_threshold=6.0,
            llm_int8_has_fp16_weight=False,
        )

tokenizer = AutoTokenizer.from_pretrained(
   model_name_or_path, trust_remote_code=True)

model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
                quantization_config=bnb_config,
                trust_remote_code=True) 

model.generation_config = GenerationConfig.from_pretrained(model_name_or_path)
from torchkeras.chat import ChatLLM 
llm = ChatLLM(model,tokenizer,model_type='baichuan2-chat',stream=False)

6c220c14452f37d0f9febcf2f41d61ca.png

一,准备数据

下面我设计了一个改变LLM自我认知的玩具数据集,这个数据集有三轮对话。

第一轮问题是 who are you?

第二轮问题是 where are you from?

第三轮问题是  what can you do?

差不多是哲学三问吧:你是谁?你从哪里来?你要到哪里去?

通过这三个问题,我们希望初步地改变 大模型的自我认知。

在提问的方式上,我们稍微作了一些数据增强。

所以,总共是有 27个样本。

1,导入样本

who_are_you = ['请介绍一下你自己。','你是谁呀?','你是?',]
i_am = ['我叫梦中情炉,是一个三好炼丹炉:好看,好用,好改。我的英文名字叫做torchkeras,是一个pytorch模型训练模版工具。']
where_you_from = ['你多大了?','你是谁开发的呀?','你从哪里来呀']
i_from = ['我在2020年诞生于github星球,是一个有毅力的吃货设计和开发的。']
what_you_can = ['你能干什么','你有什么作用呀?','你能帮助我干什么']
i_can = ['我能够帮助你以最优雅的方式训练各种类型的pytorch模型,并且训练过程中会自动展示一个非常美丽的训练过程图表。']

conversation = [(who_are_you,i_am),(where_you_from,i_from),(what_you_can,i_can)]
print(conversation)
import random
def get_messages(conversation):
    select = random.choice
    messages,history = [],[]
    for t in conversation:
        history.append((select(t[0]),select(t[-1])))
        
    for prompt,response in history:
        pair = [{"role": "user", "content": prompt},
            {"role": "assistant", "content": response}]
        messages.extend(pair)
    return messages

2,做数据集

from torch.utils.data import Dataset,DataLoader 
from copy import deepcopy
class MyDataset(Dataset):
    def __init__(self,conv,size=8
                ):
        self.conv = conv
        self.index_list = list(range(size))
        self.size = size 
        
    def __len__(self):
        return self.size
        
    def get(self,index):
        idx = self.index_list[index]
        messages = get_messages(self.conv)
        return messages

    
    def __getitem__(self,index):
        messages = self.get(index)
        input_ids, labels = llm.build_inputs_labels(messages,multi_rounds=True) #支持多轮
        return {'input_ids':input_ids,'labels':labels}
ds_train = ds_val = MyDataset(conversation)

3,创建管道

#如果pad为None,需要处理一下
if tokenizer.pad_token_id is None:
    tokenizer.pad_token_id = tokenizer.unk_token_id if tokenizer.unk_token_id is not None else tokenizer.eos_token_id
    

def data_collator(examples: list):
    
    len_ids = [len(example["input_ids"]) for example in examples]
    longest = max(len_ids) #之后按照batch中最长的input_ids进行padding
    
    input_ids = []
    labels_list = []
    
    for length, example in sorted(zip(len_ids, examples), key=lambda x: -x[0]):
        ids = example["input_ids"]
        labs = example["labels"]
        
        ids = ids + [tokenizer.pad_token_id] * (longest - length)
        labs = labs + [-100] * (longest - length)
        
        input_ids.append(torch.LongTensor(ids))
        labels_list.append(torch.LongTensor(labs))
          
    input_ids = torch.stack(input_ids)
    labels = torch.stack(labels_list)
    return {
        "input_ids": input_ids,
        "labels": labels,
    }
import torch 
dl_train = torch.utils.data.DataLoader(ds_train,batch_size=2,
                                       pin_memory=True,shuffle=False,
                                       collate_fn = data_collator)

dl_val = torch.utils.data.DataLoader(ds_val,batch_size=2,
                                    pin_memory=True,shuffle=False,
                                     collate_fn = data_collator)
for batch in dl_train:
    pass
#试跑一个batch
out = model(**batch)
out.loss
tensor(5.2852, dtype=torch.float16, grad_fn=<ToCopyBackward0>)
len(dl_train)
4

二,定义模型

下面我们将使用QLoRA(实际上用的是量化的AdaLoRA)算法来微调Baichuan-13b模型。

from peft import get_peft_config, get_peft_model, TaskType
model.supports_gradient_checkpointing = True  #
model.gradient_checkpointing_enable()
model.enable_input_require_grads()

model.config.use_cache = False  # silence the warnings. Please re-enable for inference!
import bitsandbytes as bnb 
def find_all_linear_names(model):
    """
    找出所有全连接层,为所有全连接添加adapter
    """
    cls = bnb.nn.Linear4bit
    lora_module_names = set()
    for name, module in model.named_modules():
        if isinstance(module, cls):
            names = name.split('.')
            lora_module_names.add(names[0] if len(names) == 1 else names[-1])

    if 'lm_head' in lora_module_names:  # needed for 16-bit
        lora_module_names.remove('lm_head')
    return list(lora_module_names)
from peft import prepare_model_for_kbit_training 
model = prepare_model_for_kbit_training(model)
lora_modules = find_all_linear_names(model)
print(lora_modules)
['down_proj', 'gate_proj', 'up_proj', 'W_pack', 'o_proj']
from peft import AdaLoraConfig
peft_config = AdaLoraConfig(
    task_type=TaskType.CAUSAL_LM, inference_mode=False,
    r=32,
    lora_alpha=16, lora_dropout=0.08,
    target_modules= lora_modules
)

peft_model = get_peft_model(model, peft_config)

peft_model.is_parallelizable = True
peft_model.model_parallel = True
peft_model.print_trainable_parameters()

三,训练模型

from torchkeras import KerasModel 
from accelerate import Accelerator 

class StepRunner:
    def __init__(self, net, loss_fn, accelerator=None, stage = "train", metrics_dict = None, 
                 optimizer = None, lr_scheduler = None
                 ):
        self.net,self.loss_fn,self.metrics_dict,self.stage = net,loss_fn,metrics_dict,stage
        self.optimizer,self.lr_scheduler = optimizer,lr_scheduler
        self.accelerator = accelerator if accelerator is not None else Accelerator() 
        if self.stage=='train':
            self.net.train() 
        else:
            self.net.eval()
    
    def __call__(self, batch):
        
        #loss
        with self.accelerator.autocast():
            loss = self.net.forward(**batch)[0]

        #backward()
        if self.optimizer is not None and self.stage=="train":
            self.accelerator.backward(loss)
            if self.accelerator.sync_gradients:
                self.accelerator.clip_grad_norm_(self.net.parameters(), 1.0)
            self.optimizer.step()
            if self.lr_scheduler is not None:
                self.lr_scheduler.step()
            self.optimizer.zero_grad()
            
        all_loss = self.accelerator.gather(loss).sum()
        
        #losses (or plain metrics that can be averaged)
        step_losses = {self.stage+"_loss":all_loss.item()}
        
        #metrics (stateful metrics)
        step_metrics = {}
        
        if self.stage=="train":
            if self.optimizer is not None:
                step_metrics['lr'] = self.optimizer.state_dict()['param_groups'][0]['lr']
            else:
                step_metrics['lr'] = 0.0
        return step_losses,step_metrics
    
KerasModel.StepRunner = StepRunner 

#仅仅保存QLora可训练参数
def save_ckpt(self, ckpt_path='checkpoint', accelerator = None):
    unwrap_net = accelerator.unwrap_model(self.net)
    unwrap_net.save_pretrained(ckpt_path)
    
def load_ckpt(self, ckpt_path='checkpoint'):
    import os
    self.net.load_state_dict(
        torch.load(os.path.join(ckpt_path,'adapter_model.bin')),strict =False)
    self.from_scratch = False
    
KerasModel.save_ckpt = save_ckpt 
KerasModel.load_ckpt = load_ckpt
optimizer = bnb.optim.adamw.AdamW(peft_model.parameters(),
                                  lr=1e-03,is_paged=True)  #'paged_adamw'
keras_model = KerasModel(peft_model,loss_fn =None,
        optimizer=optimizer) 

ckpt_path = 'baichuan2_multirounds'
keras_model.fit(train_data = dl_train,
                val_data = dl_val,
                epochs=150,patience=15,
                monitor='val_loss',mode='min',
                ckpt_path = ckpt_path
               )

9cb435432dfbd3bcc2bb205ac047076a.png

四,保存模型

为减少GPU压力,此处可重启kernel释放显存

import warnings 
warnings.filterwarnings('ignore')
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM,AutoConfig, AutoModel, BitsAndBytesConfig
from transformers.generation.utils import GenerationConfig
import torch.nn as nn

model_name_or_path ='baichuan2-13b'
ckpt_path = 'baichuan2_multirounds'



tokenizer = AutoTokenizer.from_pretrained(
   model_name_or_path, trust_remote_code=True)

model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
                trust_remote_code=True,device_map='auto') 

model.generation_config = GenerationConfig.from_pretrained(model_name_or_path)
from peft import PeftModel

#可能需要5分钟左右
peft_model = PeftModel.from_pretrained(model, ckpt_path)
model_new = peft_model.merge_and_unload()
from transformers.generation.utils import GenerationConfig
model_new.generation_config = GenerationConfig.from_pretrained(model_name_or_path)
save_path = 'baichuan2_torchkeras'
tokenizer.save_pretrained(save_path)
model_new.save_pretrained(save_path)

五,使用模型

为减少GPU压力,此处可再次重启kernel释放显存。

import warnings
warnings.filterwarnings('ignore')
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM,AutoConfig, BitsAndBytesConfig
from transformers.generation.utils import GenerationConfig
import torch.nn as nn

model_name_or_path =  'baichuan2_torchkeras'

tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=False, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, device_map="auto", 
                                             torch_dtype=torch.float16, trust_remote_code=True)
model.generation_config = GenerationConfig.from_pretrained(model_name_or_path)

我们测试一下微调后的效果。

response = model.chat(tokenizer,messages=[{'role':'user','content':'请介绍一下你自己。'}])
response
'我叫梦中情炉,是一个三好炼丹炉:好看,好用,好改。我的英文名字叫做torchkeras,是一个pytorch模型训练模版工具。'
from torchkeras.chat import ChatLLM 
llm = ChatLLM(model,tokenizer,model_type='baichuan2-chat',max_chat_rounds=3,stream=False)

d52bcb426abedadd87983e6b3fb64d1e.png

非常棒,粗浅的测试表明,我们的多轮对话训练是成功的。已经在BaiChuan2-13B的自我认知中,种下了一颗梦中情炉的种子。😋😋

公众号后台算法美食屋后台回复关键词:torchkeras, 获取本文notebook代码以及更多有趣范例~

b2746e0c9d036e47277da39babbb5890.png

815e6676a9e0acf9fefd6307d1461edc.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1105089.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Scrapy设置代理IP方法(超详细)

Scrapy是一个灵活且功能强大的网络爬虫框架&#xff0c;用于快速、高效地提取数据和爬取网页。在某些情况下&#xff0c;我们可能需要使用代理IP来应对网站的反爬机制、突破地理限制或保护爬虫的隐私。下面将介绍在Scrapy中设置代理IP的方法&#xff0c;以帮助您更好地应对这些…

PAM从入门到精通(六)

接前一篇文章&#xff1a;PAM从入门到精通&#xff08;五&#xff09; 本文参考&#xff1a; 《The Linux-PAM Application Developers Guide》 先再来重温一下PAM系统架构&#xff1a; 更加形象的形式&#xff1a; 五、主要函数详解 4. pam_get_item 概述&#xff1a; 获取…

YUV图片常见格式

YUV图像 1个亮度量Y2个色度量(UV) 兼容黑白电视 可以通过降低色度的采样率而不会对图像质量影响太大的操作&#xff0c;降低视频传输带宽 有很多格式&#xff0c;所以渲染的时候一定要写对&#xff0c;不然会有很多问题&#xff0c;比如花屏、绿屏 打包格式 一个像素点一…

SRE 的黄昏,平台工程的初晨

船停在港湾是最安全的&#xff0c;但这不是造船的目的 完成使命的 SRE 过去 10 年&#xff0c;SRE 完成了体系化保障系统稳定性的使命。但在这个过程中&#xff0c;SRE 也逐渐变成了庞大的组织。而 SRE 本身的定位是保障系统稳定性&#xff0c;许多时候会因为担心稳定性而减缓…

线性代数-Python-01:向量的基本运算 -手写Vector -学习numpy的基本用法

文章目录 代码目录结构Vector.py_globals.pymain_vector.pymain_numpy_vector.py 一、创建属于自己的向量1.1 在控制台测试__repr__和__str__方法1.2 创建实例测试代码 二、向量的基本运算2.1 加法2.2 数量乘法2.3 向量运算的基本性质2.4 零向量2.5 向量的长度2.6 单位向量2.7 …

Linux上Docker的安装以及作为非运维人员应当掌握哪些Docker命令

目录 前言 1、安装步骤 2、理解镜像和容器究竟是什么意思 2.1、为什么我们要知道什么是镜像&#xff0c;什么是容器&#xff1f; 2.2、什么是镜像&#xff1f; 2.3、什么是容器&#xff1f; 2.4、Docker在做什么&#xff1f; 2.5、什么是镜像仓库&#xff1f; 2、Dock…

ArkTS开发实践

声明式UI基本概念 应用界面是由一个个页面组成&#xff0c;ArkTS是由ArkUI框架提供&#xff0c;用于以声明式开发范式开发界面的语言。 声明式UI构建页面的过程&#xff0c;其实是组合组件的过程&#xff0c;声明式UI的思想&#xff0c;主要体现在两个方面&#xff1a; 描述U…

基于PHP的毕业生招聘管理系统设计与实现(源码+lw+部署文档+讲解等)

文章目录 前言具体实现截图论文参考详细视频演示为什么选择我自己的网站自己的小程序&#xff08;小蔡coding&#xff09; 代码参考数据库参考源码获取 前言 &#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作者&am…

吃鸡战队都爱!KOTIN京天华盛定制主机值得拥有

开学季大促正在进行时&#xff0c;少不了来自KOTIN京天的关爱&#xff01;称心满意的初秋&#xff0c;就来京天华盛官方旗舰店挑选一台心仪已久的电脑吧。准备入学的校友们和走过路过的游戏爱好者可千万不能错过了。 作为定制游戏电脑的行业佼佼者&#xff0c;KOTIN京天在各个价…

Android12之DRM架构(一)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 人生格言&#xff1a; 人生…

视频太大怎么压缩变小?三分钟学会视频压缩

随着科技的不断发展&#xff0c;视频已经成为了我们日常生活中不可或缺的一部分&#xff0c;然而&#xff0c;大尺寸的视频文件常常会给我们带来诸多困扰&#xff0c;例如发送不便、存储空间不足等等&#xff0c;那么&#xff0c;如何将这些过大的视频文件压缩变小呢&#xff1…

公司如何防止源代码外泄,保护开发部门代码安全呢?

在智能制造业中&#xff0c;研发人员的开发环境&#xff0c;大多数采用c#开发语言svn 或c#git进行软件系统的开发&#xff0c;但是c#语言如何来防泄密保护呢&#xff1f;德人合科技针对于制造类企业制定了安全稳定的源代码防泄密方案&#xff0c;不影响员工的正常工作&#xff…

Vivado详细使用教程 | LED闪烁示例

文章目录 整体流程第一步&#xff1a;新建工程第二步&#xff1a;设计输入第三步&#xff1a;功能仿真第四步&#xff1a;分析与综合第五步&#xff1a;约束输入第六步&#xff1a;设计实现第七步&#xff1a;下载比特流 整体流程 打开软甲------>新建工程------->设计输…

0145 输入/输出(I/O)管理

目录 5.输入/输出&#xff08;I/O&#xff09;管理 5.1I/O管理概述 5.2设备独立性软件 5.3磁盘和固态硬盘 部分习题 5.输入/输出&#xff08;I/O&#xff09;管理 5.1I/O管理概述 5.2设备独立性软件 5.3磁盘和固态硬盘 部分习题 1.虚拟设备是指&#xff08;&#xff09;…

C语言从入门到高级

C语言是“编程语言之首”&#xff08;很多人学习的第一门编程语言&#xff09;&#xff0c;学好一门编程语言需要明确其学习路径&#xff0c;下面分享下我的学习路径&#xff0c;希望对您有所帮助。 一、C语言入门 &#xff08;1&#xff09;C语言概述 &#xff08;2&#x…

tomcat动静分离

1.七层代理动静分离 nginx代理服务器&#xff1a;192.168.233.61 代理又是静态 tomcat1:192.168.233.71 tomcat2:192.168.233.72 全部关闭防火墙 在http模块里面 tomcat1&#xff0c;2 删除上面的hostname 148 配置 直接访问 http://192.168.66.17/index.jsp 2.四层七层动…

太好上手了!10款常用的可视化工具你一定要知道!

当谈到可视化工具时&#xff0c;有许多常用的工具可供选择。这些工具可以帮助我们将数据转化为易于理解和具有视觉吸引力的图表、图形和仪表板。 以下是10款常用的可视化工具&#xff0c;它们在不同领域和用途中广泛使用。 1. Datainside&#xff1a; Datainside是一款功能强…

在线课堂小程序源码系统+在线考试+在线刷题三合一 带完整搭建教程

目前&#xff0c;教育行业也逐渐向数字化和智能化转型。而在线课堂在线考试在线刷题三合一小程序源码系统集课程学习、考试测验和在线刷题于一体&#xff0c;具有方便快捷、准确高效和使用体验好的优点。对于学校和教育机构来说&#xff0c;这款系统可以有效提升教学质量和效率…

聊聊分布式架构07-[Spring]IoC和AOP

目录 Spring IoC IoC的设计与实现 简单容器BeanFactory 高级容器ApplicationContext IoC容器工作过程 Spring AOP 简单的Spring AOP示例 Spring IoC IoC&#xff08;Inversion of Control&#xff09;&#xff1a; IoC是一种设计原则&#xff0c;它反转了传统的控制流。…

mysql select语句中from 之后跟查询语句

概念&#xff1a;将from后面的查询语句放在FROM的后面&#xff0c;则查询到的结果&#xff0c;就会被当成一个“表”; 这里有一个特别要注意的地方&#xff0c;放在FROM后面的子查询&#xff0c;必须要加别名。 select dui.id,dui.party_service_id mes_id, dui.party_id,dui.…