书生·浦语(InternLM)-openLesson-2-学习笔记

目录

一 前言

二 环境信息

三 InternLM2-Chat-7B 对话 Demo

1、下载大模型到本地

2、下载InternLM框架

3、demo脚本修改

4、运行demo

5、浏览器访问本地大模型

四 Lagent 智能体工具调用 Demo

1、Lagent 安装

2、修改代码

3、Demo 运行

4、Demo 效果演示

五 浦语·灵笔图文理解创作 Demo

六 Hugging Face下载步骤

七 课程链接


一 前言

本人学习过程中使用的平台为:UCloud-8C64G-TeslaP40。

相比于课程提供的配套平台主要限制在于GPU,Tesla P40不支持FP16、不支持INT4,虽然支持INIT8运算,但是就目前的经验来看P40的INT8对于triton编程的支持情况存在一些问题。同时缺少配套的cuda等环境,缺少相关的镜像文件,这些倒不算什么问题,就是麻烦了一些。

不同平台带来的差异对前四节课程影响较小,第 5 节课程-LMDeploy 大模型量化部署实践,模型转8bit成功,但是P40推理时失败,最终还是使用了InternStudio的A100 (1/4)才完成第五节课的作业,将会在第5节课程的笔记中给出P40的详细报错信息,欢迎大家一起探讨。

本人使用的模型为InternLM2,与课程链接中使用的模型InternLM存在版本差异,经过实践主要是模型调用时的对话模板配置差异。笔记会按照InternLM2版本的模型记录操作步骤,会将对话模板配置差异进行说明。

二 环境信息

按照本文结尾课程链接中的环境要求配置,注意cuda、torch、python版本要匹配

三 InternLM2-Chat-7B 对话 Demo

1、下载大模型到本地

git clone https://huggingface.co/internlm/internlm2-chat-7b

模型bin文件较大,下载会比较慢,下载完成后如下:

2、下载InternLM框架

用于进行模型的调用(下方地址匹配internlm2-chat-7b)

https://github.com/InternLM/InternLM

注意:课程链接中附上的地址可能对应的是internlm-chat-7b,和internlm2-chat-7b的对话模板存在差异,框架和模型版本不匹配可能会导致自动输出等问题。

3、demo脚本修改

demo脚本路径为:InternLM/chat/web_demo.py

修改脚本中的模型路径为第1步中下载好的模型路径:

4、运行demo

streamlit run chat/web_demo.py --server.port 6066

若想后台运行:

nohup streamlit run chat/web_demo.py --server.port 6066 >> run_web_demo.log &

注意

1.要在InternLM这一级目录执行,而不是InternLM/chat/下,否则脚本会找不到相对路径下的图片资源,导致报错。

2.如果命令中包含--server.address 127.0.0.1,是无法通过外网访问的,即使云服务防火墙已经放开限制。如果只想本地访问,应加上该参数。

5、浏览器访问本地大模型

四 Lagent 智能体工具调用 Demo

本人一开始用的模型如上是internlm2-chat-7b,使用最新的Lagent框架,发现与课程链接中的模型版本和框架版本均存在差异,且连课程链接中的脚本都没有了。

尝试之后能够成功运行demo,但是demo界面上的控件与课程中差别很大并且有一些地址比如大模型IP地址是必传项,默认配置无法正常返回结果。

由于本人目前还是初学者,打算先把流程走一遍,因此没有再投入下去看源码找原因。模型换回internlm-chat-7b,且lagent版本同课程中保持一致,最终完成了该作业。如果有感兴趣的小伙伴遇到同样的问题欢迎一起探讨,或者等一段时间看看是不是会有更稳定的版本出来。

1、Lagent 安装

cd /root/code
git clone https://gitee.com/internlm/lagent.git
cd /root/code/lagent
git checkout 511b03889010c4811b1701abb153e02b8e94fb5e # 尽量保证和教程commit版本一致
pip install -e . # 源码安装

2、修改代码

由于代码修改的地方比较多,大家直接将 /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()

3、Demo 运行

streamlit run examples/react_web_demo.py --server.port 6006

4、Demo 效果演示

我在简单测试这个demo的时候发现刷新界面后重选模型会重复往显存加载,占满显存后告警:WARNING:root:Some parameters are on the meta device device because they were offloaded to the cpu.估计是脚本还有一些地方需要优化。

五 浦语·灵笔图文理解创作 Demo

1、模型下载

下载internlm-xcomposer-7b模型

git clone https://huggingface.co/internlm/internlm-xcomposer-7b

或者安装 modelscope,再下载模型

pip install modelscope==1.9.5

新建 download.py 文件并在其中输入以下内容,并运行 python download.py 执行下载

import torch
from modelscope import snapshot_download, AutoModel, AutoTokenizer
import os
model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-xcomposer-7b', cache_dir='/root/model', revision='master')

4.3 代码准备

git clone InternLM-XComposer 仓库的代码,路径请自行修改

cd /root/code
git clone https://gitee.com/internlm/InternLM-XComposer.git
cd /root/code/InternLM-XComposer
git checkout 3e8c79051a1356b9c388a6447867355c0634932d  # 最好保证和教程的 commit 版本一致

4.4 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


六 Hugging Face下载步骤

七 课程链接

https://github.com/InternLM/tutorial/blob/main/helloworld/hello_world.md
轻松玩转书生·浦语大模型趣味Demo_哔哩哔哩_bilibili
 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值