Bootstrap

书生·浦语大模型实战营:2.轻松玩转书生·浦语大模型趣味 Demo

基础作业:
  • 使用 InternLM-Chat-7B 模型生成 300 字的小故事(需截图)。
  • 熟悉 hugging face 下载功能,使用 huggingface_hub python 包,下载 InternLM-20B 的 config.json 文件到本地(需截图下载过程)。
进阶作业:
  • 完成浦语·灵笔的图文理解及创作部署(需截图)
  • 完成 Lagent 工具调用 Demo 创作部署(需截图)

InternLM-Chat-7B模型生成300字小故事demo

  • 预先准备
    • python环境依赖
      # 克隆InternStudio准备好的一个pytorch 2.0.1的环境
      conda create --name internlm-demo --clone=/root/share/conda_envs/internlm-base
      # 激活环境
      conda activate internlm-demo
      # 升级pip
      python -m pip install --upgrade pip
      pip install modelscope==1.9.5
      pip install transformers==4.35.2
      pip install streamlit==1.24.0
      pip install sentencepiece==0.1.99
      pip install accelerate==0.24.1
      
    • 模型下载
      # InternStudio 平台的 share 目录下已经为我们准备了全系列的 InternLM 模型,所以我们可以直接复制即可。
      mkdir -p /root/model/Shanghai_AI_Laboratory
      cp -r /root/share/temp/model_repos/internlm-chat-7b /root/model/Shanghai_AI_Laboratory
      
      -r选项表示递归地负值目录及其内容
      也可以已使用 modelscope 中的snapshot_download函数下载模型,第一个参数为模型名称,参数cache_dir为模型的下载路径。
      /root路径下新建目录model,在目录下新建download.py文件并在其中输入以下内容,粘贴代码后记得保存文件,并运行python /root/model/download.py执行下载,模型大小为 14 GB,下载模型大概需要 10~20 分钟。
      import torch
      from modelscope import snapshot_download, AutoModel, AutoTokenizer
      import os
      model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-chat-7b', cache_dir='/root/model', revision='v1.0.3')
      
    • 代码准备
      git clone https://gitee.com/internlm/InternLM.git
      
      InternLM/web_demo.py中29行和33行的模型更换为本地地址
      在这里插入图片描述
  • web demo运行
    输入以下命令:
streamlit run web_demo.py --server.address 127.0.0.1 --server.port 6006

需要将端口映射到本地,在本地浏览器输入http://127.0.0.1:6006即可。
在这里插入图片描述

配置本地端口:

由于服务器通常只暴露了用于安全远程登录的 SSH(Secure Shell)端口,如果需要访问服务器上运行的其他服务(如 web 应用)的特定端口,需要一种特殊的设置。我们可以通过使用SSH隧道的方法,将服务器上的这些特定端口映射到本地计算机的端口。这样做的步骤如下:

首先我们需要配置一下本地的 SSH Key ,我们这里以 Windows 为例。
步骤①:在本地机器上打开 Power Shell 终端。在终端中,运行以下命令来生成 SSH 密钥对:

ssh-keygen -t rsa

步骤②: 您将被提示选择密钥文件的保存位置,默认情况下是在 ~/.ssh/ 目录中。按 Enter 键接受默认值或输入自定义路径。
步骤③:公钥默认存储在 ~/.ssh/id_rsa.pub,复制该文件内的全部内容
步骤④:将公钥复制到剪贴板中,然后回到 InternStudio 控制台,点击配置 SSH Key
步骤⑤:将刚刚复制的公钥添加进入即可。
步骤⑥:在本地终端输入以下指令 .6006 是在服务器中打开的端口,而 33090 是根据开发机的端口进行更改。

ssh -CNg -L 6006:127.0.0.1:6006 [email protected] -p 33090

hugging face下载InternLM-20B的config.json

  • 首先安装依赖

    pip install -U huggingface_hub
    

    在这里插入图片描述

  • 新建python文件,填入以下代码,运行即可

    • resume-download:断点续下
    • local-dir:本地存储路径。(linux 环境下需要填写绝对路径)
    import os
    
    # 下载模型
    os.system('huggingface-cli download --resume-download internlm/internlm-chat-20b --local-dir your_path')
    

    以下内容将展示使用 huggingface_hub 下载模型中的部分文件

    import os 
    from huggingface_hub import hf_hub_download  # Load model directly 
    
    hf_hub_download(repo_id="internlm/internlm-20b", filename="config.json")
    

    我直接运行第二段代码,报错为:
    requests.exceptions.ProxyError: (MaxRetryError(“HTTPSConnectionPool(host=‘huggingface.co’, port=443): Max retries exceeded with url: /internlm/internlm-7b/resolve/main/config.json (Caused by ProxyError(‘Cannot connect to proxy.’, TimeoutError(‘timed out’)))”), ‘(Request ID: b2d767d6-ffed-4a00-a197-96eeb026b75d)’)

    于是打算采取镜像的方式,Huggingface镜像站:https://hf-mirror.com/

    HF_ENDPOINT=https://hf-mirror.com python your_script.py
    

    在这里插入图片描述
    在这里插入图片描述
    注意: 下载好的东西将默认放在~/.cache/huggingface/hub/文件夹下


浦语·灵笔的图文理解及创作部署

环境配置与之前一致,新的模型为internlm-xcomposer-7b,新的代码地址:

git clone https://gitee.com/internlm/InternLM-XComposer.git

Demo运行:

cd /root/code/InternLM-XComposer
python examples/web_demo.py  \
    --folder /root/model/Shanghai_AI_Laboratory/internlm-xcomposer-7b \
    --num_gpus 1 \
    --port 6006	

注意: 这里 num_gpus 1 是因为InternStudio平台对于 A100(1/4)*2 识别仍为一张显卡。但如果有小伙伴课后使用两张 3090 来运行此 demo,仍需将 num_gpus 设置为 2 。
在这里插入图片描述
在这里插入图片描述


Lagent 工具调用 Demo 创作部署

模型采用internlm-chat-7b,代码地址:

git clone https://gitee.com/internlm/lagent.git
pip install -e . # 源码安装

由于代码修改的地方比较多,大家直接将 /root/code/lagent/examples/react_web_demo.py 内容替换为以下代码

import copy
import os

import streamlit as st
from streamlit.logger import get_logger

from lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
from lagent.agents.react import ReAct
from lagent.llms import GPTAPI
from lagent.llms.huggingface import HFTransformerCasualLM


class SessionState:

    def init_state(self):
        """Initialize session state variables."""
        st.session_state['assistant'] = []
        st.session_state['user'] = []

        #action_list = [PythonInterpreter(), GoogleSearch()]
        action_list = [PythonInterpreter()]
        st.session_state['plugin_map'] = {
            action.name: action
            for action in action_list
        }
        st.session_state['model_map'] = {}
        st.session_state['model_selected'] = None
        st.session_state['plugin_actions'] = set()

    def clear_state(self):
        """Clear the existing session state."""
        st.session_state['assistant'] = []
        st.session_state['user'] = []
        st.session_state['model_selected'] = None
        if 'chatbot' in st.session_state:
            st.session_state['chatbot']._session_history = []


class StreamlitUI:

    def __init__(self, session_state: SessionState):
        self.init_streamlit()
        self.session_state = session_state

    def init_streamlit(self):
        """Initialize Streamlit's UI settings."""
        st.set_page_config(
            layout='wide',
            page_title='lagent-web',
            page_icon='./docs/imgs/lagent_icon.png')
        # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
        st.sidebar.title('模型控制')

    def setup_sidebar(self):
        """Setup the sidebar for model and plugin selection."""
        model_name = st.sidebar.selectbox(
            '模型选择:', options=['gpt-3.5-turbo','internlm'])
        if model_name != st.session_state['model_selected']:
            model = self.init_model(model_name)
            self.session_state.clear_state()
            st.session_state['model_selected'] = model_name
            if 'chatbot' in st.session_state:
                del st.session_state['chatbot']
        else:
            model = st.session_state['model_map'][model_name]

        plugin_name = st.sidebar.multiselect(
            '插件选择',
            options=list(st.session_state['plugin_map'].keys()),
            default=[list(st.session_state['plugin_map'].keys())[0]],
        )

        plugin_action = [
            st.session_state['plugin_map'][name] for name in plugin_name
        ]
        if 'chatbot' in st.session_state:
            st.session_state['chatbot']._action_executor = ActionExecutor(
                actions=plugin_action)
        if st.sidebar.button('清空对话', key='clear'):
            self.session_state.clear_state()
        uploaded_file = st.sidebar.file_uploader(
            '上传文件', type=['png', 'jpg', 'jpeg', 'mp4', 'mp3', 'wav'])
        return model_name, model, plugin_action, uploaded_file

    def init_model(self, option):
        """Initialize the model based on the selected option."""
        if option not in st.session_state['model_map']:
            if option.startswith('gpt'):
                st.session_state['model_map'][option] = GPTAPI(
                    model_type=option)
            else:
                st.session_state['model_map'][option] = HFTransformerCasualLM(
                    '/root/model/Shanghai_AI_Laboratory/internlm-chat-7b')
        return st.session_state['model_map'][option]

    def initialize_chatbot(self, model, plugin_action):
        """Initialize the chatbot with the given model and plugin actions."""
        return ReAct(
            llm=model, action_executor=ActionExecutor(actions=plugin_action))

    def render_user(self, prompt: str):
        with st.chat_message('user'):
            st.markdown(prompt)

    def render_assistant(self, agent_return):
        with st.chat_message('assistant'):
            for action in agent_return.actions:
                if (action):
                    self.render_action(action)
            st.markdown(agent_return.response)

    def render_action(self, action):
        with st.expander(action.type, expanded=True):
            st.markdown(
                "<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>插    件</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501
                + action.type + '</span></p>',
                unsafe_allow_html=True)
            st.markdown(
                "<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>思考步骤</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501
                + action.thought + '</span></p>',
                unsafe_allow_html=True)
            if (isinstance(action.args, dict) and 'text' in action.args):
                st.markdown(
                    "<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行内容</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501
                    unsafe_allow_html=True)
                st.markdown(action.args['text'])
            self.render_action_results(action)

    def render_action_results(self, action):
        """Render the results of action, including text, images, videos, and
        audios."""
        if (isinstance(action.result, dict)):
            st.markdown(
                "<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行结果</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501
                unsafe_allow_html=True)
            if 'text' in action.result:
                st.markdown(
                    "<p style='text-align: left;'>" + action.result['text'] +
                    '</p>',
                    unsafe_allow_html=True)
            if 'image' in action.result:
                image_path = action.result['image']
                image_data = open(image_path, 'rb').read()
                st.image(image_data, caption='Generated Image')
            if 'video' in action.result:
                video_data = action.result['video']
                video_data = open(video_data, 'rb').read()
                st.video(video_data)
            if 'audio' in action.result:
                audio_data = action.result['audio']
                audio_data = open(audio_data, 'rb').read()
                st.audio(audio_data)


def main():
    logger = get_logger(__name__)
    # Initialize Streamlit UI and setup sidebar
    if 'ui' not in st.session_state:
        session_state = SessionState()
        session_state.init_state()
        st.session_state['ui'] = StreamlitUI(session_state)

    else:
        st.set_page_config(
            layout='wide',
            page_title='lagent-web',
            page_icon='./docs/imgs/lagent_icon.png')
        # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
    model_name, model, plugin_action, uploaded_file = st.session_state[
        'ui'].setup_sidebar()

    # Initialize chatbot if it is not already initialized
    # or if the model has changed
    if 'chatbot' not in st.session_state or model != st.session_state[
            'chatbot']._llm:
        st.session_state['chatbot'] = st.session_state[
            'ui'].initialize_chatbot(model, plugin_action)

    for prompt, agent_return in zip(st.session_state['user'],
                                    st.session_state['assistant']):
        st.session_state['ui'].render_user(prompt)
        st.session_state['ui'].render_assistant(agent_return)
    # User input form at the bottom (this part will be at the bottom)
    # with st.form(key='my_form', clear_on_submit=True):

    if user_input := st.chat_input(''):
        st.session_state['ui'].render_user(user_input)
        st.session_state['user'].append(user_input)
        # Add file uploader to sidebar
        if uploaded_file:
            file_bytes = uploaded_file.read()
            file_type = uploaded_file.type
            if 'image' in file_type:
                st.image(file_bytes, caption='Uploaded Image')
            elif 'video' in file_type:
                st.video(file_bytes, caption='Uploaded Video')
            elif 'audio' in file_type:
                st.audio(file_bytes, caption='Uploaded Audio')
            # Save the file to a temporary location and get the path
            file_path = os.path.join(root_dir, uploaded_file.name)
            with open(file_path, 'wb') as tmpfile:
                tmpfile.write(file_bytes)
            st.write(f'File saved at: {file_path}')
            user_input = '我上传了一个图像,路径为: {file_path}. {user_input}'.format(
                file_path=file_path, user_input=user_input)
        agent_return = st.session_state['chatbot'].chat(user_input)
        st.session_state['assistant'].append(copy.deepcopy(agent_return))
        logger.info(agent_return.inner_steps)
        st.session_state['ui'].render_assistant(agent_return)


if __name__ == '__main__':
    root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    root_dir = os.path.join(root_dir, 'tmp_dir')
    os.makedirs(root_dir, exist_ok=True)
    main()

Demo运行:

streamlit run /root/code/lagent/examples/react_web_demo.py --server.address 127.0.0.1 --server.port 6006

在这里插入图片描述

;