文章目录
前言
一、大模型基座
二、大模型部署
1. LLM部署环境查询
2. Llama2部署
3. Llama2+QLoRA微调
4.Llama2+LangChain外挂知识库
总结
参考说明
前言
LLM基座官方文档如下(科学上网):
-
Llama:
_Github: [https://github.com/ymcui/Chinese-LLaMA-Alpaca-2](https://github.com/ymcui/Chinese-LLaMA-Alpaca-2 "https://github.com/ymcui/Chinese-LLaMA-Alpaca-2")_ _Huggingface: [https://huggingface.co/meta-llama](https://huggingface.co/meta-llama "https://huggingface.co/meta-llama")_
-
ChatGLM
_Github: [https://github.com/THUDM/ChatGLM3](https://github.com/THUDM/ChatGLM3 "https://github.com/THUDM/ChatGLM3")_ _Huggingface: [https://huggingface.co/THUDM](https://huggingface.co/THUDM "https://huggingface.co/THUDM")_
-
Baichuan
_Github: [https://github.com/baichuan-inc](https://github.com/baichuan-inc "https://github.com/baichuan-inc")_ _Huggingface:_ [https://huggingface.co/baichuan-inc](https://huggingface.co/baichuan-inc "https://huggingface.co/baichuan-inc")
-
Qwen
_Github:_ [https://github.com/QwenLM](https://github.com/QwenLM " https://github.com/QwenLM") _Huggingface:_ [baichuan-inc (Baichuan Intelligent Technology) (huggingface.co)](https://huggingface.co/baichuan-inc "baichuan-inc (Baichuan Intelligent Technology) (huggingface.co)")
提示:以下是本篇文章正文内容,下面案例可供参考
一、大模型基座
面LLM岗大概率会cue的内容,详见文章大模型升级与设计之道:ChatGLM、LLAMA、Baichuan及LLM结构解析 - 知乎 (zhihu.com)
该文章从原理、性能、差异、迭代版本系统地介绍了现在较受欢迎的LLM(目前ChatGLM4、Baichuan3已闭源):
二、大模型部署(以Llama2为例)
1. LLM部署环境查询
1.1. 查看服务器GPU显存及占用
# 每0.5s刷新一次
!wathch -d -n 0.5 nvidia-smi
1.2. 模型部署所需显存查询
# 1.2.1 安装依赖包
!pip install accelerate transformers
# 1.2.2 查看RicardoLee/Llama2-chat-13B-Chinese-50W显存(网络层单层最大显存、推理显存、训练显存)
!accelerate estimate-memory RicardoLee/Llama2-chat-13B-Chinese-50W
# 1.2.3 也可以点击在线测试链接
https://huggingface.co/spaces/hf-accelerate/model-memory-usage
2. Llama2部署
2.1. 本地部署
# 2.1.1 执行git lfs install
curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash
sudo apt-get install git-lfs
# 2.1.2 克隆模型到服务器(Llama2-chat-13B-Chinese-50W)
git clone https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W
### 如果遇到模型大文件无法下载,通过wget从huggingface上下载
wget https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W/resolve/main/pytorch_model-00001-of-00003.bin
wget https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W/resolve/main/pytorch_model-00002-of-00003.bin
wget https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W/resolve/main/pytorch_model-00003-of-00003.bin
2.2 网页可视化(下载并部署gradio)
从这个链接里:https://github.com/ymcui/Chinese-LLaMA-Alpaca/blob/main/scripts/inference/gradio_demo.py
里的gradio_demo.py和requirements.txt下载到服务器
# 2.2.1 安装依赖
!pip install -r requirements.txt
# 2.2.2 把gradio.py里59、60、61行注释掉
!pip install gradio
# 2.2.3 安装其他依赖包
!pip install bitsandbytes accelerate scipy
# 2.2.4 cd Llama2路径
!python gradio_demo.py --base_model /root/autodl-tmp/Llama2-chat-13B-Chinese-50W --tokenizer_path /root/autodl-tmp/Llama2-chat-13B-Chinese-50W --gpus 0
Llama2部署可视化
3. Llama2+QLoRA微调
3.1. 数据预处理
# 3.1.1 下载BelleGroup提供的50w条中文数据(注意数据量有点大)
wget https://huggingface.co/datasets/BelleGroup/train_0.5M_CN/resolve/main/Belle_open_source_0.5M.json
# 3.1.2 新建split_json.py文件,粘贴如下代码
import random,json
def write_txt(file_path,datas):
with open(file_path,"w",encoding="utf8") as f:
for d in datas:
f.write(json.dumps(d,ensure_ascii=False)+"\n")
f.close()
with open("/root/autodl-tmp/Belle_open_source_0.5M.json","r",encoding="utf8") as f:
lines=f.readlines()
#拼接数据
changed_data=[]
for l in lines:
l=json.loads(l)
changed_data.append({"text":"### Human: "+l["instruction"]+" ### Assistant: "+l["output"]})
#从拼好后的数据中,随机选出1000条,作为训练数据
#为了省钱 和 演示使用,我们只用1000条,生产环境至少要使用全部50w条
r_changed_data=random.sample(changed_data, 1000)
#写到json中,root根据需求自行修改
write_txt("/root/autodl-tmp/Belle_open_source_0.5M_changed_test.json",r_changed_data)
# 3.1.3 新建终端运行split_json.py,切分数据集为json格式
!python split_json.py
3.2. 运行微调文件
# 3.2.1 安装依赖
!pip install -q huggingface_hub
!pip install -q -U trl transformers accelerate peft
!pip install -q -U datasets bitsandbytes einops wandb
# 3.2.2 运行微调文件
# (1)导入相关包
from datasets import load_dataset
import torch,einops
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer, TrainingArguments
from peft import LoraConfig
from trl import SFTTrainer
# (2)加载python split_json.py拼接好之后的1000条数据
dataset = load_dataset("json",data_files="/root/autodl-tmp/Belle_open_source_0.5M_changed_test.json",split="train")
# (3)模型配置
base_model_name ="/root/autodl-tmp/Llama2-chat-13B-Chinese-50W" # 路径需要根据模型部署路径修改
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, #在4bit上,进行量化
bnb_4bit_use_double_quant=True, # 嵌套量化,每个参数可以多节省0.4位
bnb_4bit_quant_type="nf4", #NF4(normalized float)或纯FP4量化 博客说推荐NF4
bnb_4bit_compute_dtype=torch.float16)
# (4)QloRA微调参数配置
peft_config = LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=64,
bias="none",
task_type="CAUSAL_LM",
)
# (5)加载部署好的本地模型(Llama)
base_model = AutoModelForCausalLM.from_pretrained(
base_model_name,#本地模型名称
quantization_config=bnb_config,#上面本地模型的配置
device_map=device_map,#使用GPU的编号
trust_remote_code=True,
use_auth_token=True
)
base_model.config.use_cache = False
base_model.config.pretraining_tp = 1
# (6)长文本拆分成最小的单元词(即token)
tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
# (7)训练参数配置
output_dir = "./results"
training_args = TrainingArguments(
report_to="wandb",
output_dir=output_dir, #训练后输出目录
per_device_train_batch_size=4, #每个GPU的批处理数据量
gradient_accumulation_steps=4, #在执行反向传播/更新过程之前,要累积其梯度的更新步骤数
learning_rate=2e-4, #超参、初始学习率。太大模型不稳定,太小则模型不能收敛
logging_steps=10, #两个日志记录之间的更新步骤数
max_steps=100 #要执行的训练步骤总数
)
max_seq_length = 512
#TrainingArguments 的参数详解:https://blog.csdn.net/qq_33293040/article/details/117376382
trainer = SFTTrainer(
model=base_model,
train_dataset=dataset,
peft_config=peft_config,
dataset_text_field="text",
max_seq_length=max_seq_length,
tokenizer=tokenizer,
args=training_args,
)
# (8)运行程序,进行微调
trainer.train()
# (9)保存模型
import os
output_dir = os.path.join(output_dir, "final_checkpoint")
trainer.model.save_pretrained(output_dir)
3.3. 执行代码合并
新建merge_model.py的文件,把下面的代码粘贴进去, 然后然后执行上述合并代码,进行合并。终端运行python merge_model.py。
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
#设置原来本地模型的地址
model_name_or_path = '/root/autodl-tmp/Llama2-chat-13B-Chinese-50W'
#设置微调后模型的地址,就是上面的那个地址
adapter_name_or_path = '/root/autodl-tmp/results/final_checkpoint'
#设置合并后模型的导出地址
save_path = '/root/autodl-tmp/new_model'
tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path,
trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
model_name_or_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
torch_dtype=torch.float16,
device_map='auto'
)
print("load model success")
model = PeftModel.from_pretrained(model, adapter_name_or_path)
print("load adapter success")
model = model.merge_and_unload()
print("merge success")
tokenizer.save_pretrained(save_path)
model.save_pretrained(save_path)
print("save done.")
4.Llama2+LangChain外挂知识库
4.1. 安装依赖库
!pip install -U langchain unstructured nltk sentence_transformers faiss-gpu
4.2. 外挂知识库 & 向量存储 & 问题/向量检索
# 4.2.0 导包
from langchain.document_loaders import UnstructuredFileLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
# 4.2.1 加载外部知识库
filepath="/root/autodl-tmp/knowledge.txt"
loader=UnstructuredFileLoader(filepath) # 把带格式的文本,读取为无格式的纯文本
docs=loader.load()
print(docs) # 返回的是一个列表,列表中的元素是Document类型
# 4.2.2 对读取的文档进行chunk
text_splitter=RecursiveCharacterTextSplitter(chunk_size=20,chunk_overlap=10)
docs=text_splitter.split_documents(docs)
# 4.2.3 下载并部署embedding模型
执行:git lfs install
执行:git clone https://huggingface.co/GanymedeNil/text2vec-large-chinese
如果有大文件下载不下来,执行
wget https://huggingface.co/GanymedeNil/text2vec-large-chinese/resolve/main/pytorch_model.bin
wget https://huggingface.co/GanymedeNil/text2vec-large-chinese/resolve/main/model.safetensors
# 4.2.4 使用text2vec-large-chinese模型,对上面chunk后的doc进行embedding。然后使用FAISS存储到向量数据库
import os
embeddings=HuggingFaceEmbeddings(model_name="/root/autodl-tmp/text2vec-large-chinese", model_kwargs={'device': 'cuda'})
if os.path.exists("/root/autodl-tmp/my_faiss_store.faiss")==False:
vector_store=FAISS.from_documents(docs,embeddings)
else:
vector_store=FAISS.load_local("/root/autodl-tmp/my_faiss_store.faiss",embeddings=embeddings)
#注意:如果修改了知识库(knowledge.txt)里的内容,则需要把原来的 my_faiss_store.faiss 删除后,重新生成向量库。
# 4.2.5 加载模型
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
#先做tokenizer
tokenizer = AutoTokenizer.from_pretrained('/root/autodl-tmp/Llama2-chat-13B-Chinese-50W',trust_remote_code=True)
#加载本地基础模型
base_model = AutoModelForCausalLM.from_pretrained(
"/root/autodl-tmp/Llama2-chat-13B-Chinese-50W",
torch_dtype=torch.float16,
device_map='auto',
trust_remote_code=True
)
model=base_model.eval()
#4.2.6 向量检索:通过用户问句,到向量库中,匹配相似度高的文本
query="小白的父亲是谁?"
docs=vector_store.similarity_search(query)#计算相似度,并把相似度高的chunk放在前面
context=[doc.page_content for doc in docs]#提取chunk的文本内容
print(context)
# 4.2.7 构造prompt_template
my_input="\n".join(context)
prompt=f"已知:\n{my_input}\n请回答:{query}"
print(prompt)
# 4.2.8 把prompt输入模型进行预测
inputs = tokenizer([f"Human:{prompt}\nAssistant:"], return_tensors="pt")
input_ids = inputs["input_ids"].to('cuda')
generate_input = {
"input_ids":input_ids,
"max_new_tokens":1024,
"do_sample":True,
"top_k":50,
"top_p":0.95,
"temperature":0.3,
"repetition_penalty":1.3
}
generate_ids = model.generate(**generate_input)
new_tokens = tokenizer.decode(generate_ids[0], skip_special_tokens=True)
print("new_tokens",new_tokens)
推理结果:
总结
章节一引用《大模型升级与设计之道:ChatGLM、LLAMA、Baichuan及LLM结构解析》一文,该文章从原理、性能、差异、迭代版本系统地介绍了现在较受欢迎的LLM(目前ChatGLM4、Baichuan3已闭源)。
章节二以Llama2举例,演示了从部署环境查询、到模型部署、再到微调、最后到LangChain外挂知识库实现向量检索增强(RAG)的流程。
掌握本文流程、学习框架,后续大模型业务均可在其基础上进行延伸,其它LLM模型部署demo在前言部分的官方开源文档亦可查询。
如何学习大模型 AI ?
由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。
但是具体到个人,只能说是:
“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。
这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。
我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。
我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。点击下方蓝色字 即可免费领取↓↓↓
**读者福利 |**
👉2024最新《AGI大模型学习资源包》免费分享 **(安全链接,放心点击)**
第一阶段(10天):初阶应用
该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。
- 大模型 AI 能干什么?
- 大模型是怎样获得「智能」的?
- 用好 AI 的核心心法
- 大模型应用业务架构
- 大模型应用技术架构
- 代码示例:向 GPT-3.5 灌入新知识
- 提示工程的意义和核心思想
- Prompt 典型构成
- 指令调优方法论
- 思维链和思维树
- Prompt 攻击和防范
- …
第二阶段(30天):高阶应用
该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。
- 为什么要做 RAG
- 搭建一个简单的 ChatPDF
- 检索的基础概念
- 什么是向量表示(Embeddings)
- 向量数据库与向量检索
- 基于向量检索的 RAG
- 搭建 RAG 系统的扩展知识
- 混合检索与 RAG-Fusion 简介
- 向量模型本地部署
- …
第三阶段(30天):模型训练
恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。
到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?
- 为什么要做 RAG
- 什么是模型
- 什么是模型训练
- 求解器 & 损失函数简介
- 小实验2:手写一个简单的神经网络并训练它
- 什么是训练/预训练/微调/轻量化微调
- Transformer结构简介
- 轻量化微调
- 实验数据集的构建
- …
第四阶段(20天):商业闭环
对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。
- 硬件选型
- 带你了解全球大模型
- 使用国产大模型服务
- 搭建 OpenAI 代理
- 热身:基于阿里云 PAI 部署 Stable Diffusion
- 在本地计算机运行大模型
- 大模型的私有化部署
- 基于 vLLM 部署大模型
- 案例:如何优雅地在阿里云私有部署开源大模型
- 部署一套开源 LLM 项目
- 内容安全
- 互联网信息服务算法备案
- …
学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。
如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。
这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费
】或点击下方蓝色字 即可免费领取↓↓↓
**读者福利 |**
👉2024最新版CSDN大礼包:《AGI大模型学习资源包》免费分享 **(安全链接,放心点击)**
)** **(安全链接,放心点击)**