当前位置:   article > 正文

大模型学习路线(1)——大模型基座 & 大模型部署

大模型基座

文章目录

前言

一、大模型基座

二、大模型部署

1. LLM部署环境查询 

2. Llama2部署

3. Llama2+QLoRA微调

4.Llama2+LangChain外挂知识库

总结

参考说明


前言

LLM基座官方文档如下(科学上网):

  1. Llama:

             Github: https://github.com/ymcui/Chinese-LLaMA-Alpaca-2

            Huggingface: https://huggingface.co/meta-llama

  2. ChatGLM

             Github: https://github.com/THUDM/ChatGLM3

            Huggingface: https://huggingface.co/THUDM

  3. Baichuan

             Github: https://github.com/baichuan-inc

            Huggingface: https://huggingface.co/baichuan-inc

  4. Qwen

             Github: https://github.com/QwenLM

            Huggingface: baichuan-inc (Baichuan Intelligent Technology) (huggingface.co)


提示:以下是本篇文章正文内容,下面案例可供参考

一、大模型基座

面LLM岗大概率会cue的内容,详见文章大模型升级与设计之道:ChatGLM、LLAMA、Baichuan及LLM结构解析 - 知乎 (zhihu.com)

该文章从原理、性能、差异、迭代版本系统地介绍了现在较受欢迎的LLM(目前ChatGLM4、Baichuan3已闭源):

二、大模型部署(以Llama2为例)

1. LLM部署环境查询 

1.1. 查看服务器GPU显存及占用

  1. # 每0.5s刷新一次
  2. !wathch -d -n 0.5 nvidia-smi

1.2. 模型部署所需显存查询

  1. # 1.2.1 安装依赖包
  2. !pip install accelerate transformers
  1. # 1.2.2 查看RicardoLee/Llama2-chat-13B-Chinese-50W显存(网络层单层最大显存、推理显存、训练显存)
  2. !accelerate estimate-memory RicardoLee/Llama2-chat-13B-Chinese-50W

  1. # 1.2.3 也可以点击在线测试链接
  2. https://huggingface.co/spaces/hf-accelerate/model-memory-usage

2. Llama2部署

2.1. 本地部署

  1. # 2.1.1 执行git lfs install
  2. curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash
  3. sudo apt-get install git-lfs
  4. # 2.1.2 克隆模型到服务器(Llama2-chat-13B-Chinese-50W)
  5. git clone https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W
  6. ### 如果遇到模型大文件无法下载,通过wget从huggingface上下载
  7. wget https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W/resolve/main/pytorch_model-00001-of-00003.bin
  8. wget https://huggingface.co/RicardoLee/Llama2-chat-13B-Chinese-50W/resolve/main/pytorch_model-00002-of-00003.bin
  9. 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下载到服务器

  1. # 2.2.1 安装依赖
  2. !pip install -r requirements.txt
  3. # 2.2.2 把gradio.py里59、60、61行注释掉
  4. !pip install gradio
  5. # 2.2.3 安装其他依赖包
  6. !pip install bitsandbytes accelerate scipy
  7. # 2.2.4 cd Llama2路径
  8. !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. 数据预处理

  1. # 3.1.1 下载BelleGroup提供的50w条中文数据(注意数据量有点大)
  2. wget https://huggingface.co/datasets/BelleGroup/train_0.5M_CN/resolve/main/Belle_open_source_0.5M.json
  3. # 3.1.2 新建split_json.py文件,粘贴如下代码
  4. import random,json
  5. def write_txt(file_path,datas):
  6. with open(file_path,"w",encoding="utf8") as f:
  7. for d in datas:
  8. f.write(json.dumps(d,ensure_ascii=False)+"\n")
  9. f.close()
  10. with open("/root/autodl-tmp/Belle_open_source_0.5M.json","r",encoding="utf8") as f:
  11. lines=f.readlines()
  12. #拼接数据
  13. changed_data=[]
  14. for l in lines:
  15. l=json.loads(l)
  16. changed_data.append({"text":"### Human: "+l["instruction"]+" ### Assistant: "+l["output"]})
  17. #从拼好后的数据中,随机选出1000条,作为训练数据
  18. #为了省钱 和 演示使用,我们只用1000条,生产环境至少要使用全部50w条
  19. r_changed_data=random.sample(changed_data, 1000)
  20. #写到json中,root根据需求自行修改
  21. write_txt("/root/autodl-tmp/Belle_open_source_0.5M_changed_test.json",r_changed_data)
  22. # 3.1.3 新建终端运行split_json.py,切分数据集为json格式
  23. !python split_json.py

3.2. 运行微调文件

  1. # 3.2.1 安装依赖
  2. !pip install -q huggingface_hub
  3. !pip install -q -U trl transformers accelerate peft
  4. !pip install -q -U datasets bitsandbytes einops wandb
  5. # 3.2.2 运行微调文件
  6. # (1)导入相关包
  7. from datasets import load_dataset
  8. import torch,einops
  9. from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer, TrainingArguments
  10. from peft import LoraConfig
  11. from trl import SFTTrainer
  12. # (2)加载python split_json.py拼接好之后的1000条数据
  13. dataset = load_dataset("json",data_files="/root/autodl-tmp/Belle_open_source_0.5M_changed_test.json",split="train")
  14. # (3)模型配置
  15. base_model_name ="/root/autodl-tmp/Llama2-chat-13B-Chinese-50W" # 路径需要根据模型部署路径修改
  16. bnb_config = BitsAndBytesConfig(
  17. load_in_4bit=True, #在4bit上,进行量化
  18. bnb_4bit_use_double_quant=True, # 嵌套量化,每个参数可以多节省0.4位
  19. bnb_4bit_quant_type="nf4", #NF4(normalized float)或纯FP4量化 博客说推荐NF4
  20. bnb_4bit_compute_dtype=torch.float16)
  21. # (4)QloRA微调参数配置
  22. peft_config = LoraConfig(
  23. lora_alpha=16,
  24. lora_dropout=0.1,
  25. r=64,
  26. bias="none",
  27. task_type="CAUSAL_LM",
  28. )
  29. # (5)加载部署好的本地模型(Llama)
  30. base_model = AutoModelForCausalLM.from_pretrained(
  31. base_model_name,#本地模型名称
  32. quantization_config=bnb_config,#上面本地模型的配置
  33. device_map=device_map,#使用GPU的编号
  34. trust_remote_code=True,
  35. use_auth_token=True
  36. )
  37. base_model.config.use_cache = False
  38. base_model.config.pretraining_tp = 1
  39. # (6)长文本拆分成最小的单元词(即token)
  40. tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True)
  41. tokenizer.pad_token = tokenizer.eos_token
  42. # (7)训练参数配置
  43. output_dir = "./results"
  44. training_args = TrainingArguments(
  45. report_to="wandb",
  46. output_dir=output_dir, #训练后输出目录
  47. per_device_train_batch_size=4, #每个GPU的批处理数据量
  48. gradient_accumulation_steps=4, #在执行反向传播/更新过程之前,要累积其梯度的更新步骤数
  49. learning_rate=2e-4, #超参、初始学习率。太大模型不稳定,太小则模型不能收敛
  50. logging_steps=10, #两个日志记录之间的更新步骤数
  51. max_steps=100 #要执行的训练步骤总数
  52. )
  53. max_seq_length = 512
  54. #TrainingArguments 的参数详解:https://blog.csdn.net/qq_33293040/article/details/117376382
  55. trainer = SFTTrainer(
  56. model=base_model,
  57. train_dataset=dataset,
  58. peft_config=peft_config,
  59. dataset_text_field="text",
  60. max_seq_length=max_seq_length,
  61. tokenizer=tokenizer,
  62. args=training_args,
  63. )
  64. # (8)运行程序,进行微调
  65. trainer.train()
  66. # (9)保存模型
  67. import os
  68. output_dir = os.path.join(output_dir, "final_checkpoint")
  69. trainer.model.save_pretrained(output_dir)

3.3. 执行代码合并

新建merge_model.py的文件,把下面的代码粘贴进去, 然后然后执行上述合并代码,进行合并。终端运行python merge_model.py。

  1. from peft import PeftModel
  2. from transformers import AutoModelForCausalLM, AutoTokenizer
  3. import torch
  4. #设置原来本地模型的地址
  5. model_name_or_path = '/root/autodl-tmp/Llama2-chat-13B-Chinese-50W'
  6. #设置微调后模型的地址,就是上面的那个地址
  7. adapter_name_or_path = '/root/autodl-tmp/results/final_checkpoint'
  8. #设置合并后模型的导出地址
  9. save_path = '/root/autodl-tmp/new_model'
  10. tokenizer = AutoTokenizer.from_pretrained(
  11. model_name_or_path,
  12. trust_remote_code=True
  13. )
  14. model = AutoModelForCausalLM.from_pretrained(
  15. model_name_or_path,
  16. trust_remote_code=True,
  17. low_cpu_mem_usage=True,
  18. torch_dtype=torch.float16,
  19. device_map='auto'
  20. )
  21. print("load model success")
  22. model = PeftModel.from_pretrained(model, adapter_name_or_path)
  23. print("load adapter success")
  24. model = model.merge_and_unload()
  25. print("merge success")
  26. tokenizer.save_pretrained(save_path)
  27. model.save_pretrained(save_path)
  28. print("save done.")

4.Llama2+LangChain外挂知识库

4.1. 安装依赖库

!pip install -U langchain unstructured nltk sentence_transformers faiss-gpu

4.2. 外挂知识库 & 向量存储 & 问题/向量检索

  1. # 4.2.0 导包
  2. from langchain.document_loaders import UnstructuredFileLoader
  3. from langchain.text_splitter import RecursiveCharacterTextSplitter
  4. from langchain.embeddings.huggingface import HuggingFaceEmbeddings
  5. from langchain.vectorstores import FAISS
  6. # 4.2.1 加载外部知识库
  7. filepath="/root/autodl-tmp/knowledge.txt"
  8. loader=UnstructuredFileLoader(filepath) # 把带格式的文本,读取为无格式的纯文本
  9. docs=loader.load()
  10. print(docs) # 返回的是一个列表,列表中的元素是Document类型
  11. # 4.2.2 对读取的文档进行chunk
  12. text_splitter=RecursiveCharacterTextSplitter(chunk_size=20,chunk_overlap=10)
  13. docs=text_splitter.split_documents(docs)
  14. # 4.2.3 下载并部署embedding模型
  15. 执行:git lfs install
  16. 执行:git clone https://huggingface.co/GanymedeNil/text2vec-large-chinese
  17. 如果有大文件下载不下来,执行
  18. wget https://huggingface.co/GanymedeNil/text2vec-large-chinese/resolve/main/pytorch_model.bin
  19. wget https://huggingface.co/GanymedeNil/text2vec-large-chinese/resolve/main/model.safetensors
  20. # 4.2.4 使用text2vec-large-chinese模型,对上面chunk后的doc进行embedding。然后使用FAISS存储到向量数据库
  21. import os
  22. embeddings=HuggingFaceEmbeddings(model_name="/root/autodl-tmp/text2vec-large-chinese", model_kwargs={'device': 'cuda'})
  23. if os.path.exists("/root/autodl-tmp/my_faiss_store.faiss")==False:
  24. vector_store=FAISS.from_documents(docs,embeddings)
  25. else:
  26. vector_store=FAISS.load_local("/root/autodl-tmp/my_faiss_store.faiss",embeddings=embeddings)
  27. #注意:如果修改了知识库(knowledge.txt)里的内容,则需要把原来的 my_faiss_store.faiss 删除后,重新生成向量库。
  1. # 4.2.5 加载模型
  2. import torch
  3. from transformers import AutoTokenizer, AutoModelForCausalLM
  4. #先做tokenizer
  5. tokenizer = AutoTokenizer.from_pretrained('/root/autodl-tmp/Llama2-chat-13B-Chinese-50W',trust_remote_code=True)
  6. #加载本地基础模型
  7. base_model = AutoModelForCausalLM.from_pretrained(
  8. "/root/autodl-tmp/Llama2-chat-13B-Chinese-50W",
  9. torch_dtype=torch.float16,
  10. device_map='auto',
  11. trust_remote_code=True
  12. )
  13. model=base_model.eval()
  14. #4.2.6 向量检索:通过用户问句,到向量库中,匹配相似度高的文本
  15. query="小白的父亲是谁?"
  16. docs=vector_store.similarity_search(query)#计算相似度,并把相似度高的chunk放在前面
  17. context=[doc.page_content for doc in docs]#提取chunk的文本内容
  18. print(context)
  19. # 4.2.7 构造prompt_template
  20. my_input="\n".join(context)
  21. prompt=f"已知:\n{my_input}\n请回答:{query}"
  22. print(prompt)
  23. # 4.2.8 把prompt输入模型进行预测
  24. inputs = tokenizer([f"Human:{prompt}\nAssistant:"], return_tensors="pt")
  25. input_ids = inputs["input_ids"].to('cuda')
  26. generate_input = {
  27. "input_ids":input_ids,
  28. "max_new_tokens":1024,
  29. "do_sample":True,
  30. "top_k":50,
  31. "top_p":0.95,
  32. "temperature":0.3,
  33. "repetition_penalty":1.3
  34. }
  35. generate_ids = model.generate(**generate_input)
  36. new_tokens = tokenizer.decode(generate_ids[0], skip_special_tokens=True)
  37. print("new_tokens",new_tokens)

推理结果:


总结

        章节一引用《大模型升级与设计之道:ChatGLM、LLAMA、Baichuan及LLM结构解析》一文,该文章从原理、性能、差异、迭代版本系统地介绍了现在较受欢迎的LLM(目前ChatGLM4、Baichuan3已闭源)。

        章节二以Llama2举例,演示了从部署环境查询、到模型部署、再到微调、最后到LangChain外挂知识库实现向量检索增强(RAG)的流程。

        掌握本文流程、学习框架,后续大模型业务均可在其基础上进行延伸,其它LLM模型部署demo在前言部分的官方开源文档亦可查询。


参考说明

Llama2部署教程链接:

在Linux下部署Llama2超详细教程(适合零基础小白)_哔哩哔哩_bilibiliicon-default.png?t=N7T8https://www.bilibili.com/video/BV1n8411U7wh/?vd_source=96d014ce5151b64ab88132f7cbe77d5e

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/887224
推荐阅读
相关标签
  

闽ICP备14008679号