首页 > 其他分享 >Ziya-LLaMA-13B 模型在GPU 上部署

Ziya-LLaMA-13B 模型在GPU 上部署

时间:2023-09-04 11:44:55浏览次数:57  
标签:Ziya llama 13B LLaMA https gr

Ziya-LLaMA-13B 模型在GPU 上部署

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

1. 部署准备

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

1.2 python环境

cpm_kernels==1.0.11
gradio==3.34.0
huggingface-hub==0.16.4
Pillow==9.5.0
torch-1.12.1+cu113-cp38-cp38-linux_x86_64.whl    (https://download.pytorch.org/whl/torch/)
tqdm==4.64.1
transformers==4.31.0
accelerate==0.20.3

1.3 模型下载

2 . 模型部署

首先说明一下项目的文件系统目录

-llama-13B
-llama-13B-convert
-ziya_v1.1_delta
-ziya_v1.1
-apply_delta.py
-convert_llama_weights_to_hf.py
-launch.py
-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下载即可。

llama-13B为llama原始参数存放的目录, 原始模型权重不太好下载,可以不用管

llama-13B-convert为转换成huggingface形式的参数存放的目录, 可以直接从网上找转化好的模型权重数据

https://huggingface.co/decapoda-research/llama-13b-hf/tree/main
https://pan.baidu.com/s/1Y7YWdFWX1Yzy2Yuujp8Tqg?pwd=1p5n#list/path=%2FLLaMA(1)%2Fllama-13b

ziya_v1.1_delta为huggingface上的权重文件
https://huggingface.co/IDEA-CCNL/Ziya-LLaMA-13B-v1.1/tree/main

2.1 llama-13B权重转换(如直接下载转化好的模型权重数据,该步骤可省略)

首先第一步需要将llama-13B的原始权重转换成huggingface的权重形式,使用convert_llama_weights_to_hf.py脚本进行转换,转换代码如下:

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权重。

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在官方代码的基础上增加了一些参数和优化内容。

import gradio as gr
import os
import gc
import torch


from transformers import AutoTokenizer
os.environ['CUDA_VISIBLE_DEVICES'] = "0,1"
from utils import SteamGenerationMixin


class MindBot(object):
    def __init__(self):
        model_path = './ziya_v1.1'
        self.model = SteamGenerationMixin.from_pretrained(model_path, device_map='auto').half()
        self.model.eval()

        self.tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)

    def build_prompt(self, instruction, history, human='<human>', bot='<bot>'):
        pmt = ''
        if len(history) > 0:
            for line in history:
                pmt += f'{human}: {line[0].strip()}\n{bot}: {line[1]}\n'
        pmt += f'{human}: {instruction.strip()}\n{bot}: \n'
        return pmt

    def interaction(
        self,
        instruction,
        history,
        max_new_tokens,
        temperature,
        top_p,
        max_memory=1024
    ):

        prompt = self.build_prompt(instruction, history)
        input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
        if input_ids.shape[1] > max_memory:
            input_ids = input_ids[:, -max_memory:]

        prompt_len = input_ids.shape[1]
        # stream generation method
        try:
            tmp = history.copy()
            output = ''
            with torch.no_grad():
                for generation_output in self.model.stream_generate(
                    input_ids.cuda(),
                    max_new_tokens=max_new_tokens,
                    do_sample=True,
                    top_p=top_p,
                    temperature=temperature,
                    repetition_penalty=1.,
                    eos_token_id=2,
                    bos_token_id=1,
                    pad_token_id=0
                ):
                    s = generation_output[0][prompt_len:]
                    output = self.tokenizer.decode(s, skip_special_tokens=True)
                    # output = output.replace('\n', '<br>')
                    output = output.replace('\n', '\n\n')
                    tmp.append((instruction, output))
                    yield  '', tmp
                    tmp.pop()
                    # gc.collect()
                    # torch.cuda.empty_cache()
                history.append((instruction, output))
                print('input -----> \n', prompt)
                print('output -------> \n', output)
                print('history: ======> \n', history)
        except torch.cuda.OutOfMemoryError:
            gc.collect()
            torch.cuda.empty_cache()
            self.model.empty_cache()
            history.append((instruction, "【显存不足,请清理历史信息后再重试】"))
        return "", history

    def chat(self):

        with gr.Blocks(title='IDEA MindBot', css=".bgcolor {color: white !important; background: #FFA500 !important;}") as demo:
            with gr.Row():
                gr.Column(scale=0.25)
                with gr.Column(scale=0.5):
                    gr.Markdown("<center><h1>IDEA Ziya</h1></center>")
                    gr.Markdown("<center>姜子牙通用大模型V1.1是基于LLaMa的130亿参数的大规模预训练模型,具备翻译,编程,文本分类,信息抽取,摘要,文案生成,常识问答和数学计算等能力。目前姜子牙通用大模型已完成大规模预训练、多任务有监督微调和人类反馈学习三阶段的训练过程。</center>")
                gr.Column(scale=0.25)
            with gr.Row():
                gr.Column(scale=0.25)
                with gr.Column(scale=0.5):
                    chatbot = gr.Chatbot(label='Ziya').style(height=500)
                    msg = gr.Textbox(label="Input")
                # gr.Column(scale=0.25)
                with gr.Column(scale=0.25):
                    max_new_tokens = gr.Slider(0, 2048, value=1024, step=1.0, label="Max_new_tokens", interactive=True)
                    top_p = gr.Slider(0, 1, value=0.85, step=0.01, label="Top P", interactive=True)
                    temperature = gr.Slider(0, 1, value=0.8, step=0.01, label="Temperature", interactive=True)
            with gr.Row():
                gr.Column(scale=0.25)
                with gr.Column(scale=0.25):
                    clear = gr.Button("Clear")
                with gr.Column(scale=0.25):
                    submit = gr.Button("Submit")
                gr.Column(scale=0.25)

            msg.submit(self.interaction, [msg, chatbot,max_new_tokens,top_p,temperature], [msg, chatbot])
            clear.click(lambda: None, None, chatbot, queue=False)
            submit.click(self.interaction, [msg, chatbot,max_new_tokens,top_p,temperature], [msg, chatbot])
        return demo.queue(concurrency_count=10).launch(share=True,server_name="127.0.0.1", server_port=7886)


if __name__ == '__main__':
    mind_bot = MindBot()
    mind_bot.chat()


2张A10 响应还是有点慢
2张A10 显存都快爆掉了

FAQ:

RuntimeError: Failed to import transformers.models.clipseg.modeling_clipseg because of the following error (look up to see its traceback):
/usr/local/lib/python3.8/dist-packages/transformer_engine_extensions.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN2at4_ops5zeros4callEN3c108ArrayRefINS2_6SymIntEEENS2_8optionalINS2_10ScalarTypeEEENS6_INS2_6LayoutEEENS6_INS2_6DeviceEEENS6_IbEE

pip uninstall transformer-engine 可解决

参考文档:

https://github.com/ChaosWang666/Ziya-LLaMA-13B-deployment
https://welearnnlp.blog.csdn.net/article/details/131125481

https://www.cnblogs.com/Flat-White/p/17048075.html
https://download.pytorch.org/whl/cu113
https://download.pytorch.org/whl/torch/
https://download.pytorch.org/whl/torchvision/

标签:Ziya,llama,13B,LLaMA,https,gr
From: https://www.cnblogs.com/michaelcjl/p/17676513.html

相关文章

  • 微调llama2模型教程:创建自己的Python代码生成器
    本文将演示如何使用PEFT、QLoRa和Huggingface对新的lama-2进行微调,生成自己的代码生成器。所以本文将重点展示如何定制自己的llama2,进行快速训练,以完成特定任务。 https://avoid.overfit.cn/post/9794c9eef1df4e55adf514b3d727ee3b......
  • 亲自跑 llama2的 微调代码
    https://www.kaggle.com/zhangbo2008/train-llama2-best效果图: 这周周末在家会录制这套流程的运行的视频,有需要的老铁可以关注一下.......
  • 轻松玩转70亿参数大模型!借助Walrus在AWS上部署Llama2
    Llama2是Meta的下一代开源大语言模型。它是一系列经过预训练和微调的模型,参数范围从70亿到700亿个。MetaLlama2可免费用于研究和商业用途并且提供了一系列具有不同大小和功能的模型,因此一经发布备受关注。在(之前的文章)中,我们详细地介绍了Llama2的使用和优势以及FAQ。......
  • 轻松玩转70亿参数大模型!借助Walrus在AWS上部署Llama2
    Llama2是Meta的下一代开源大语言模型。它是一系列经过预训练和微调的模型,参数范围从70亿到700亿个。MetaLlama2可免费用于研究和商业用途并且提供了一系列具有不同大小和功能的模型,因此一经发布备受关注。在之前的文章中,我们详细地介绍了Llama2的使用和优势以及FAQ。......
  • 使用 DPO 微调 Llama 2
    简介基于人类反馈的强化学习(ReinforcementLearningfromHumanFeedback,RLHF)事实上已成为GPT-4或Claude等LLM训练的最后一步,它可以确保语言模型的输出符合人类在闲聊或安全性等方面的期望。然而,它也给NLP引入了一些RL相关的复杂性:既要构建一个好的奖励函数,并训......
  • 大模型入门(八)—— Llama2论文简读
    一、背景介绍大语言模型(LLM)作为功能强大的人工智能助手展现出了巨大的前景,它们擅长完成需要跨领域专业知识的复杂推理任务,包括编程和创意写作等专业领域。它们通过简单直观的聊天界面与人类互动,让大预言模型快速地被推广。大语言模型的模型架构和训练方法相对比......
  • LangChain + Streamlit + Llama:将对话式AI引入本地机器
    推荐:使用NSDT场景编辑器助你快速搭建可二次编辑的3D应用场景什么是LLMS?大型语言模型(LLM)是指能够生成与人类语言非常相似的文本并以自然方式理解提示的机器学习模型。这些模型使用包括书籍、文章、网站和其他来源在内的广泛数据集进行训练。通过分析数据中的统计模式,LLM可以预......
  • 在树莓派中跑迷你Llama2中文模型
      OpenAI的Karpathy利用周末搞了一个迷你Llama2项目llama2.c用500行C语言实现无任何依赖项的推理程序,此项目在github发布以来衍生出了基于各种语言的迷你Llama推理实现llama2.go、llama2.java、llama2.py等等;  但该项目原本的模型并不支持中文,最近正好看到一个基于llama2的中......
  • 利用text-generation-webui快速搭建chatGLM2-6b/LLAMA2-7B-chat大模型运行环境
    text-generation-webui 是一个基于Gradio的LLMWebUI开源项目,可以利用其快速搭建各种文本生成的大模型环境。一、安装text-generation-webui的readme其实已写得相当详细了,这里就不再重复,只说1个可能存在的坑:安装peft安装卡住requirements.txt中有一些依赖项,需要访问gith......
  • Meta即将推出开源代码生成平台Code Llama,挑战OpenAI和google
    您的关注是对我最大的支持......