Langchain-Chatchat项目:1.2-Baichuan2项目整体介绍

langchain,chatchat,项目,baichuan2,整体,介绍 · 浏览次数 : 74

小编点评

ip1 slots=8ip2 slots=8ip3 slots=8ip4 slots=8....4.轻量化微调 from peft import AutoPeftModelForCausalLMmodel = AutoPeftModelForCausalLM.from_pretrained(\"output\", trust_remote_code=True)四.其它1.对Baichuan1的推理优化迁移到Baichuan2 import torchimport osori_model_dir = 'your Baichuan 2 model directory'# To avoid overwriting the original model, it's best to save the converted model to another directory before replacing itnew_model_dir = 'your normalized lm_head weight Baichuan 2 model directory'model = torch.load(os.path.join(ori_model_dir, 'pytorch_model.bin'))lm_head_w = model['lm_head.weight']lm_head_w = torch.nn.functional.normalize(lm_head_w)model['lm_head.weight'] = lm_head_wtorch.save(model, os.path.join(new_model_dir, 'pytorch_model.bin'))2.中间Checkpoints # C-Eval C_Eval_loss_w = model['c_eval.loss.w'] # MMLU MMLU_loss_w = model['mllu.loss.w'] # CMMLU CMMLU_loss_w = model['cmllu.loss.w']

正文

  由百川智能推出的新一代开源大语言模型,采用2.6万亿Tokens的高质量语料训练,在多个权威的中文、英文和多语言的通用、领域benchmark上取得同尺寸最佳的效果,发布包含有7B、13B的Base和经过PPO训练的Chat版本,并提供了Chat版本的4bits量化。

一.Baichuan2模型
  Baichuan2模型在通用、法律、医疗、数学、代码和多语言翻译六个领域的中英文和多语言权威数据集上对模型进行了广泛测试。

二.模型推理
1.Chat模型

>>> import torch>>> from transformers import AutoModelForCausalLM, AutoTokenizer>>> from transformers.generation.utils import GenerationConfig>>> tokenizer = AutoTokenizer.from_pretrained("baichuan-inc/Baichuan2-13B-Chat", use_fast=False, trust_remote_code=True)>>> model = AutoModelForCausalLM.from_pretrained("baichuan-inc/Baichuan2-13B-Chat", device_map="auto", torch_dtype=torch.bfloat16, trust_remote_code=True)>>> model.generation_config = GenerationConfig.from_pretrained("baichuan-inc/Baichuan2-13B-Chat")>>> messages = []>>> messages.append({"role""user""content""解释一下“温故而知新”"})>>> response = model.chat(tokenizer, messages)>>> print(response)"温故而知新"是一句中国古代的成语,出自《论语·为政》篇。这句话的意思是:通过回顾过去,我们可以发现新的知识和理解。换句话说,学习历史和经验可以让我们更好地理解现在和未来。这句话鼓励我们在学习和生活中不断地回顾和反思过去的经验,从而获得新的启示和成长。通过重温旧的知识和经历,我们可以发现新的观点和理解,从而更好地应对不断变化的世界和挑战。
复制

2.Base模型

>>> from transformers import AutoModelForCausalLM, AutoTokenizer>>> tokenizer = AutoTokenizer.from_pretrained("baichuan-inc/Baichuan2-13B-Base", trust_remote_code=True)>>> model = AutoModelForCausalLM.from_pretrained("baichuan-inc/Baichuan2-13B-Base", device_map="auto", trust_remote_code=True)>>> inputs = tokenizer('登鹳雀楼->王之涣\n夜雨寄北->', return_tensors='pt')>>> inputs = inputs.to('cuda:0')>>> pred = model.generate(**inputs, max_new_tokens=64, repetition_penalty=1.1)>>> print(tokenizer.decode(pred.cpu()[0], skip_special_tokens=True))登鹳雀楼->王之涣夜雨寄北->李商隐
复制

3.命令行工具方式和网页demo方式

python cli_demo.pystreamlit run web_demo.py
复制

三.模型微调
1.依赖安装
  如需使用LoRA等轻量级微调方法需额外安装peft,如需使用xFormers进行训练加速需额外安装xFormers,如下所示:

git clone https://github.com/baichuan-inc/Baichuan2.gitcd Baichuan2/fine-tunepip install -r requirements.txt
复制

2.单机训练
  下面是一个微调Baichuan2-7B-Base的单机训练例子,训练数据data/belle_chat_ramdon_10k.json来自multiturn_chat_0.8M采样出的1万条,如下所示:

hostfile=""deepspeed --hostfile=$hostfile fine-tune.py  \    --report_to "none" \    --data_path "data/belle_chat_ramdon_10k.json" \    --model_name_or_path "baichuan-inc/Baichuan2-7B-Base" \    --output_dir "output" \    --model_max_length 512 \    --num_train_epochs 4 \    --per_device_train_batch_size 16 \    --gradient_accumulation_steps 1 \    --save_strategy epoch \    --learning_rate 2e-5 \    --lr_scheduler_type constant \    --adam_beta1 0.9 \    --adam_beta2 0.98 \    --adam_epsilon 1e-8 \    --max_grad_norm 1.0 \    --weight_decay 1e-4 \    --warmup_ratio 0.0 \    --logging_steps 1 \    --gradient_checkpointing True \    --deepspeed ds_config.json \    --bf16 True \    --tf32 True
复制

3.多机训练
  多机训练只需要给一下hostfile,同时在训练脚本里面指定hosftfile的路径:

hostfile="/path/to/hostfile"deepspeed --hostfile=$hostfile fine-tune.py  \    --report_to "none" \    --data_path "data/belle_chat_ramdon_10k.json" \    --model_name_or_path "baichuan-inc/Baichuan2-7B-Base" \    --output_dir "output" \    --model_max_length 512 \    --num_train_epochs 4 \    --per_device_train_batch_size 16 \    --gradient_accumulation_steps 1 \    --save_strategy epoch \    --learning_rate 2e-5 \    --lr_scheduler_type constant \    --adam_beta1 0.9 \    --adam_beta2 0.98 \    --adam_epsilon 1e-8 \    --max_grad_norm 1.0 \    --weight_decay 1e-4 \    --warmup_ratio 0.0 \    --logging_steps 1 \    --gradient_checkpointing True \    --deepspeed ds_config.json \    --bf16 True \    --tf32 True
复制

  其中,hostfile内容如下所示:

ip1 slots=8ip2 slots=8ip3 slots=8ip4 slots=8....
复制

4.轻量化微调
  如需使用仅需在上面的脚本中加入参数--use_lora True,LoRA具体的配置可见fine-tune.py脚本。使用LoRA微调后可以使用下面的命令加载模型:

from peft import AutoPeftModelForCausalLMmodel = AutoPeftModelForCausalLM.from_pretrained("output", trust_remote_code=True)
复制

四.其它
1.对Baichuan1的推理优化迁移到Baichuan2
  用户只需要利用以下脚本离线对Baichuan2模型的最后一层lm_head做归一化,并替换掉lm_head.weight即可。替换完后,就可以像对Baichuan1模型一样对转换后的模型做编译优化等工作:

import torchimport osori_model_dir = 'your Baichuan 2 model directory'# To avoid overwriting the original model, it's best to save the converted model to another directory before replacing itnew_model_dir = 'your normalized lm_head weight Baichuan 2 model directory'model = torch.load(os.path.join(ori_model_dir, 'pytorch_model.bin'))lm_head_w = model['lm_head.weight']lm_head_w = torch.nn.functional.normalize(lm_head_w)model['lm_head.weight'] = lm_head_wtorch.save(model, os.path.join(new_model_dir, 'pytorch_model.bin'))
复制

2.中间Checkpoints
  下图给出了这些checkpoints在C-Eval、MMLU、CMMLU三个benchmark上的效果变化:

参考文献:
[1]https://github.com/baichuan-inc/Baichuan2
[2]baichuan-inc:https://huggingface.co/baichuan-inc
[3]https://huggingface.co/baichuan-inc/Baichuan2-7B-Intermediate-Checkpoints
[4]Baichuan 2: Open Large-scale Language Models:https://arxiv.org/abs/2309.10305

与Langchain-Chatchat项目:1.2-Baichuan2项目整体介绍相似的内容:

Langchain-Chatchat项目:1.2-Baichuan2项目整体介绍

由百川智能推出的新一代开源大语言模型,采用2.6万亿Tokens的高质量语料训练,在多个权威的中文、英文和多语言的通用、领域benchmark上取得同尺寸最佳的效果,发布包含有7B、13B的Base和经过PPO训练的Chat版本,并提供了Chat版本的4bits量化。 一.Baichuan2模型 B

Langchain-Chatchat项目:2.1-通过GPT2模型来检索NebulaGraph

在官方例子中给出了通过chain = NebulaGraphQAChain.from_llm(ChatOpenAI(temperature=0), graph=graph, verbose=True)来检索NebulaGraph图数据库。本文介绍了通过GPT2替换ChatOpenAI的思路和实现,暂

Langchain-Chatchat项目:1.1-ChatGLM2项目整体介绍

ChatGLM2-6B是开源中英双语对话模型ChatGLM-6B的第2代版本,引入新的特性包括更长的上下文(基于FlashAttention技术,将基座模型的上下文长度由ChatGLM-6B的2K扩展到了32K,并在对话阶段使用8K的上下文长度训练);更高效的推理(基于Multi-QueryAtte

Langchain-Chatchat项目:1-整体介绍

基于Langchain与ChatGLM等语言模型的本地知识库问答应用实现。项目中默认LLM模型改为THUDM/chatglm2-6b[2],默认Embedding模型改为moka-ai/m3e-base[3]。 一.项目介绍 1.实现原理 本项目实现原理如下图所示,过程包括加载文件->读取文本->文

Langchain-Chatchat项目:3-Langchain计算器工具Agent思路和实现

本文主要讨论Langchain-Chatchat项目中自定义Agent问答的思路和实现。以"计算器工具"为例,简单理解就是通过LLM识别应该使用的工具类型,然后交给相应的工具(也是LLM模型)来解决问题。一个LLM模型可以充当不同的角色,要把结构化的Prompt模板写好,充分利用LLM的Zero/O

拆解LangChain的大模型记忆方案

之前我们聊过如何使用LangChain给LLM(大模型)装上记忆,里面提到对话链ConversationChain和MessagesPlaceholder,可以简化安装记忆的流程。下文来拆解基于LangChain的大模型记忆方案。

LangChain转换链:让数据处理更精准

在开发AI Agent(智能体)时,我们经常需要对输入数据进行预处理,这样可以更好地利用LLM。LangChain提供了一个强大的工具——转换链(TransformChain),它可以帮我们轻松实现这一任务。

5分钟了解LangChain的路由链

路由链(RouterChain)是由LLM根据输入的Prompt去选择具体的某个链。路由链中一般会存在多个Prompt,Prompt结合LLM决定下一步选择哪个链。

5分钟明白LangChain 的输出解析器和链

本文介绍 LangChain 的输出解析器OutputParser的使用,和基于LangChain的LCEL构建链。 1. 输出解析器OutputParser 1.1、为什么需要OutputParser 常规的使用LangChain构建LLM应用的流程是:Prompt 输入、调用LLM 、LLM输出

Langchain 与 LlamaIndex:LLM 应用开发框架的比较与使用建议

Langchain 和 Llamaindex 是两种广泛使用的主流 LLM 应用开发框架。两者有什么不同?我们该如何使用?以下我根据各类资料和相关文档做了初步选型。 一、Langchain 1. 适用场景 (1)需要构建灵活、可扩展的通用应用程序。 (2)需要复杂的工作流程支持。 (3)需要复杂的交