大模型部署实战(一)——Ziya-LLaMA-13B

[复制链接]
查看998 | 回复0 | 2023-8-11 12:38:06 | 显示全部楼层 |阅读模式

   ❤️觉得内容不错的话,欢迎点赞收藏加关注,后续会继续输入更多优质内容❤️  
   有问题欢迎大家加关注私戳或者评论(包括但不限于NLP算法相关,linux学习相关,读研读博相关......)  
博主原文链接:https://www.yourmetaverse.cn/llm/188/
6.10日更新增加了模型量化模型,现在的模型只需要一张A100(40GB显卡即可推理)


   (封面图由文心一格生成)  大模型部署实战(一)——Ziya-LLaMA-13B

Ziya-LLaMA-13B是IDEA-CCNL基于LLaMa的130亿参数的大规模预训练模型,具备翻译,编程,文本分类,信息抽取,摘要,文案生成,常识问答和数学计算等能力。目前姜子牙通用大模型已完成大规模预训练、多任务有监督微调和人类反馈学习三阶段的训练过程。本文主要用于Ziya-LLaMA-13B的本地部署。
在线体验地址:


  • 博主自己部署的地址:http://www.yourmetaverse.cn:39000/
  • 官方部署的地址:https://modelscope.cn/studios/Fengshenbang/Ziya_LLaMA_13B_v1_online/summary
本文所使用的代码详见:https://github.com/ChaosWang666/Ziya-LLaMA-13B-deployment
1. 部署准备

1.1 硬件环境

显卡最低显存为54GB,可以为一张A100(80GB)或者两张A100(40GB)。
6.10日更新增加了模型量化模型,现在的模型只需要一张A100(40GB显卡即可推理)
1.2 python环境

  1. cpm_kernels==1.0.11
  2. gradio==3.34.0
  3. huggingface_hub==0.15.1
  4. Pillow==9.5.0
  5. torch==1.12.1+cu113
  6. tqdm==4.64.1
  7. transformers==4.29.2
  8. accelerate==0.17.1
复制代码
1.3 模型下载



  • (1)llama-13B原始参数下载
    原始参数可以通过下面网址下载。
    https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform
  • (2)Ziya-LLaMA-13B-v1.1 delta参数下载
    delta参数进入下面网页下载。
    https://huggingface.co/IDEA-CCNL/Ziya-LLaMA-13B-v1.1/tree/main
  • (3)相关代码下载
    进入下面网页下载llama权重转hf权重脚本。
    https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py
    进入下面网页下载llama权重转Ziya-LLaMA-13B权重脚本。
    https://github.com/IDEA-CCNL/Fengshenbang-LM/blob/main/fengshen/utils/apply_delta.py
2. 模型部署

首先说明一下项目的文件系统目录
  1. -llama-13B
  2. -llama-13B-convert
  3. -ziya_v1.1_delta
  4. -ziya_v1.1
  5. -apply_delta.py
  6. -convert_llama_weights_to_hf.py
  7. -launch.py
  8. -utils.py
复制代码
其中llama-13B为llama原始参数存放的目录,llama-13B-convert为转换成huggingface形式的参数存放的目录,ziya_v1.1_delta为huggingface上的权重文件,ziya_v1.1为最终转换后的权重文件。launch.py为本地化部署文件,详见后续章节,utils.py为官方给的文件,直接从https://modelscope.cn/studios/Fengshenbang/Ziya_LLaMA_13B_v1_online/files下载即可。
2.1 llama-13B权重转换

首先第一步需要将llama-13B的原始权重转换成huggingface的权重形式,使用convert_llama_weights_to_hf.py脚本进行转换,转换代码如下:
  1. python convert_llama_weights_to_hf.py --input_dir $你的llama-13B路径 --model_size 13B --output_dir $你的llama-13B模型转换后的路径
复制代码
2.2 结合基础的llama权重和Ziya-LLaMA-13B delta权重得到Ziya-LLaMA-13B权重

使用如下代码得到最终的Ziya-LLaMA-13B权重。
  1. python -m apply_delta --base $你的llama-13B模型转换后的路径 --target $你的最终权重存储路径 --delta $你下载的Ziya-LLaMA-13B权重路径
复制代码
2.3 模型部署

使用下面这段代码进行模型部署。该代码修改自https://modelscope.cn/studios/Fengshenbang/Ziya_LLaMA_13B_v1_online/files
在官方代码的基础上增加了一些参数和优化内容。
  1. import gradio as gr
  2. import os
  3. import gc
  4. import torch
  5. from transformers import BitsAndBytesConfig, AutoTokenizer
  6. #指定环境的GPU,我的环境是2张A100(40GB)显卡,于是我设置了两张卡,也可以一张80GB的A100
  7. #设置模型量化之后可以使用单张A100进行推理
  8. os.environ['CUDA_VISIBLE_DEVICES'] = "0"
  9. #这个utils文件直接下载官方给的文件即可
  10. from utils import SteamGenerationMixin
  11. class MindBot(object):
  12.     def __init__(self):
  13.             #这个model_path为你本地的模型路径
  14.         model_path = './ziya_v1.1'
  15.         # 模型单精度推理的模型加载
  16.         self.model = SteamGenerationMixin.from_pretrained(model_path, device_map='auto').half()
  17.         # 模型量化推理的模型加载
  18.         #self.model = SteamGenerationMixin.from_pretrained(model_path, device_map='auto',quantization_config=BitsAndBytesConfig(load_in_4bit=True))
  19.         self.model.eval()
  20.         
  21.         self.tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
  22.    
  23.     def build_prompt(self, instruction, history, human='<human>', bot='<bot>'):
  24.         pmt = ''
  25.         if len(history) > 0:
  26.             for line in history:
  27.                 pmt += f'{human}: {line[0].strip()}\n{bot}: {line[1]}\n'
  28.         pmt += f'{human}: {instruction.strip()}\n{bot}: \n'
  29.         return pmt
  30.    
  31.     def interaction(
  32.         self,
  33.         instruction,
  34.         history,
  35.         max_new_tokens,
  36.         temperature,
  37.         top_p,
  38.         max_memory=1024
  39.     ):
  40.                
  41.         prompt = self.build_prompt(instruction, history)
  42.         input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
  43.         if input_ids.shape[1] > max_memory:
  44.             input_ids = input_ids[:, -max_memory:]
  45.             
  46.         prompt_len = input_ids.shape[1]
  47.         # stream generation method
  48.         try:
  49.             tmp = history.copy()
  50.             output = ''
  51.             with torch.no_grad():
  52.                 for generation_output in self.model.stream_generate(
  53.                     input_ids.cuda(),
  54.                     max_new_tokens=max_new_tokens,
  55.                     do_sample=True,
  56.                     top_p=top_p,
  57.                     temperature=temperature,
  58.                     repetition_penalty=1.,
  59.                     eos_token_id=2,
  60.                     bos_token_id=1,
  61.                     pad_token_id=0
  62.                 ):
  63.                     s = generation_output[0][prompt_len:]
  64.                     output = self.tokenizer.decode(s, skip_special_tokens=True)
  65.                     # output = output.replace('\n', '<br>')
  66.                     output = output.replace('\n', '\n\n')
  67.                     tmp.append((instruction, output))
  68.                     yield  '', tmp
  69.                     tmp.pop()
  70.                     # gc.collect()
  71.                     # torch.cuda.empty_cache()
  72.                 history.append((instruction, output))
  73.                 print('input -----> \n', prompt)
  74.                 print('output -------> \n', output)
  75.                 print('history: ======> \n', history)
  76.         except torch.cuda.OutOfMemoryError:
  77.             gc.collect()
  78.             torch.cuda.empty_cache()
  79.             self.model.empty_cache()
  80.             history.append((instruction, "【显存不足,请清理历史信息后再重试】"))
  81.         return "", history
  82.         
  83.     def chat(self):
  84.         
  85.         with gr.Blocks(title='IDEA MindBot', css=".bgcolor {color: white !important; background: #FFA500 !important;}") as demo:
  86.             with gr.Row():
  87.                 gr.Column(scale=0.25)
  88.                 with gr.Column(scale=0.5):
  89.                     gr.Markdown("<center><h1>IDEA Ziya</h1></center>")
  90.                     gr.Markdown("<center>姜子牙通用大模型V1.1是基于LLaMa的130亿参数的大规模预训练模型,具备翻译,编程,文本分类,信息抽取,摘要,文案生成,常识问答和数学计算等能力。目前姜子牙通用大模型已完成大规模预训练、多任务有监督微调和人类反馈学习三阶段的训练过程。</center>")
  91.                 gr.Column(scale=0.25)
  92.             with gr.Row():
  93.                 gr.Column(scale=0.25)
  94.                 with gr.Column(scale=0.5):
  95.                     chatbot = gr.Chatbot(label='Ziya').style(height=500)
  96.                     msg = gr.Textbox(label="Input")
  97.                 # gr.Column(scale=0.25)
  98.                 with gr.Column(scale=0.25):
  99.                     max_new_tokens = gr.Slider(0, 2048, value=1024, step=1.0, label="Max_new_tokens", interactive=True)
  100.                     top_p = gr.Slider(0, 1, value=0.85, step=0.01, label="Top P", interactive=True)
  101.                     temperature = gr.Slider(0, 1, value=0.8, step=0.01, label="Temperature", interactive=True)
  102.             with gr.Row():
  103.                 gr.Column(scale=0.25)
  104.                 with gr.Column(scale=0.25):
  105.                     clear = gr.Button("Clear")
  106.                 with gr.Column(scale=0.25):
  107.                     submit = gr.Button("Submit")
  108.                 gr.Column(scale=0.25)
  109.                
  110.             msg.submit(self.interaction, [msg, chatbot,max_new_tokens,top_p,temperature], [msg, chatbot])
  111.             clear.click(lambda: None, None, chatbot, queue=False)
  112.             submit.click(self.interaction, [msg, chatbot,max_new_tokens,top_p,temperature], [msg, chatbot])
  113.         return demo.queue(concurrency_count=10).launch(share=False,server_name="127.0.0.1", server_port=7886)
  114.         
  115. if __name__ == '__main__':
  116.     mind_bot = MindBot()
  117.     mind_bot.chat()
复制代码
该代码中需要修改的地方已经在代码块上标出。
全面内容见github https://github.com/ChaosWang666/Ziya-LLaMA-13B-deployment

   ❤️觉得内容不错的话,欢迎点赞收藏加关注,后续会继续输入更多优质内容❤️  
   有问题欢迎大家加关注私戳或者评论(包括但不限于NLP算法相关,linux学习相关,读研读博相关......)  

来源:https://blog.csdn.net/qq_41667743/article/details/131125481
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则