【InternLM 大模型实战】第二课

轻松玩转书生·浦语大模型趣味Demo

  • 大模型及InternLM大模型介绍
    • 大模型特点
    • InternLM-chat-7B 智能对话 Demo
      • 介绍
      • 特点
    • Lagent介绍
    • InternLM-xcomposer-7B 介绍
    • 通用环境
      • pip、conda换源
      • 模型下载
  • InternLM-chat-7B 智能对话 Demo
    • 准备工作
      • 1、在internstudio平台上创建开发机
      • 2、激活conda环境
      • 3、模型下载
      • 4、代码准备
    • 运行
      • 1、终端运行
  • Lagent 智能体工具调用Demo
    • 准备工作
      • 环境准备
      • 模型下载
      • Lagent安装
      • 修改代码
    • 运行
      • Demo运行
  • 浦语·灵笔图文理解创作 Demo
    • 准备工作
      • 环境准备
      • 模型下载
      • 代码准备
    • 运行
      • Demo运行

大模型及InternLM大模型介绍

大模型定义:人工智能领域中参数量巨大,拥有庞大计算能力和参数规模的模型

大模型特点

1、利用大量数据进行训练
2、拥有数十亿设置千亿个参数
3、模型在各种任务中展现出惊人的性能

InternLM是上海人工智能实验室发布的一个开源的轻量级训练框架,旨在支持大模型训练而不需要大量的依赖,目前开源的模型有InternLM-7B和InternLM-20B
Lagent是一个轻量级,开源的智能体框架,和InternLM配合使用能发挥更好的性能
浦语灵笔是基于书生浦语大模型语言研发的视觉语言大模型,其具备优秀的图文理解和创作能力,可以轻松创作一篇图文并茂的推文

InternLM-chat-7B 智能对话 Demo

介绍

InternLM支持在数千个GPU集群上进行训练,并在单个GPU上进行微调并保持卓越的性能优化。在1024个GPU上训练时,可以实现近90%的加速效率

特点

利用数万亿的高质量token进行训练,建立了一个强大的知识库
支持8k token的上下文窗口长度,使得输入序列更长并增强了推理能力

Lagent介绍

Lagent是一个轻量级,开源的大语言模型的智能体框架,用户可以快速地将一个大语言模型转变成多种类型的智能体,并提供了一些典型工具为大语言模型赋能
【InternLM 大模型实战】第二课_第1张图片

InternLM-xcomposer-7B 介绍

优势:
1、为用户打造图文并茂的专属文章
2、设计了高效的训练策略,为模型注入海量的多模态概念和知识数据,赋予其强大的图文理解和对话能力

通用环境

pip、conda换源

pip 换源设置pip默认镜像源

python -m pip install --upgrade pip
pip config set global.index-url https://mirrors.cernet.edu.cn/pypi/web/simple

conda快速换源

cat <<'EOF' > ~/.condarc
channels:
  - defaults:
show_channel_urls: true
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msy2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrrors.tuna.tsinghua.edu.cn/cloud
EOF

模型下载

使用hugging face下载工具huggingface-cli下载模型

pip install -U huggingface_hub
huggingface-cli download --resume-download internlm/internlm-chat-7b --local-dir your_path

也可以使用openxlab下载

import openxlab.model import download
download(model_repo='OpenLMLab/InternLM-7b',model_name='InternLM-7b',output='your local path')

还可以使用modelscope来下载模型

pip install modelscope
pip install transformers
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')

InternLM-chat-7B 智能对话 Demo

准备工作

1、在internstudio平台上创建开发机

【InternLM 大模型实战】第二课_第2张图片
进入刚创建的开发机
在这里插入图片描述

2、激活conda环境

bash # 请每次使用 jupyter lab 打开终端时务必先执行 bash 命令进入 bash 中
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

可用一下命令查看现在conda有多少个虚拟环境

conda info -*

3、模型下载

由于使用modelscope下载模型很慢要十几分钟,因此直接复制internstudio准备好的模型

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-chat-7b /root/model/Shanghai_AI_Laboratory

4、代码准备

在 /root 路径下新建 code 目录,然后切换路径, clone 代码

cd /root/code
git clone https://gitee.com/internlm/InternLM.git

切换到commit版本

cd InternLM
git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17

将 /root/code/InternLM/web_demo.py中 29 行和 33 行的模型更换为本地的 /root/model/Shanghai_AI_Laboratory/internlm-chat-7b。
【InternLM 大模型实战】第二课_第3张图片

运行

1、终端运行

我们可以在 /root/code/InternLM 目录下新建一个 cli_demo.py 文件,将以下代码填入其中:

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM


model_name_or_path = "/root/model/Shanghai_AI_Laboratory/internlm-chat-7b"

tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, trust_remote_code=True, torch_dtype=torch.bfloat16, device_map='auto')
model = model.eval()

system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语).
- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.
- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.
"""

messages = [(system_prompt, '')]

print("=============Welcome to InternLM chatbot, type 'exit' to exit.=============")

while True:
    input_text = input("User  >>> ")
    input_text.replace(' ', '')
    if input_text == "exit":
        break
    response, history = model.chat(tokenizer, input_text, history=messages)
    messages.append((input_text, response))
    print(f"robot >>> {response}")

然后在终端运行以下命令,即可体验 InternLM-Chat-7B 模型的对话能力。对话效果如下所示:

python /root/code/InternLM/cli_demo.py

【InternLM 大模型实战】第二课_第4张图片

2、web demo运行
我们切换到 VScode 中,运行 /root/code/InternLM 目录下的 web_demo.py 文件,输入以下命令后,将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。

bash
conda activate internlm-demo  # 首次进入 vscode 会默认是 base 环境,所以首先切换环境
cd /root/code/InternLM
streamlit run web_demo.py --server.address 127.0.0.1 --server.port 6006

注意:要在浏览器打开http://127.0.0.1:6006页面后,模型才会加载。在加载完模型之后,就可以与 InternLM-Chat-7B 进行对话了
【InternLM 大模型实战】第二课_第5张图片

Lagent 智能体工具调用Demo

准备工作

环境准备

和前面一样

模型下载

和前面一样

Lagent安装

cd /root/code
git clone https://gitee.com/internlm/lagent.git
cd /root/code/lagent
git checkout 511b03889010c4811b1701abb153e02b8e94fb5e # 尽量保证和教程commit版本一致
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(
                "

插 件:" # noqa E501 + action.type + '

'
, unsafe_allow_html=True) st.markdown( "

思考步骤:" # noqa E501 + action.thought + '

'
, unsafe_allow_html=True) if (isinstance(action.args, dict) and 'text' in action.args): st.markdown( "

执行内容:

"
, # 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( "

执行结果:

"
, # noqa E501 unsafe_allow_html=True) if 'text' in action.result: st.markdown( "

" + action.result['text'] + '

'
, 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

将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。

我们在 Web 页面选择 InternLM 模型,等待模型加载完毕后,输入数学问题 已知 2x+3=10,求x ,此时 InternLM-Chat-7B 模型理解题意生成解此题的 Python 代码,Lagent 调度送入 Python 代码解释器求出该问题的解。
【InternLM 大模型实战】第二课_第6张图片

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

准备工作

环境准备

创建一台开发机,选择A100(1/4)*2配置
创建虚拟环境

conda create --name xcomposer-demo --clone=/root/share/conda_envs/internlm-base

conda activate xcomposer-demo

# 安装 transformers、gradio 等依赖包
pip install transformers==4.33.1 timm==0.4.12 sentencepiece==0.1.99 gradio==3.44.4 markdown2==2.4.10 xlsxwriter==3.1.2 einops accelerate

模型下载

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-xcomposer-7b /root/model/Shanghai_AI_Laboratory

代码准备

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

运行

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

将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。我们以又见敦煌为提示词,体验图文创作的功能
【InternLM 大模型实战】第二课_第7张图片
也可以体验一下xcomposer图片理解的能力
【InternLM 大模型实战】第二课_第8张图片

你可能感兴趣的:(AI,大模型,python,人工智能,python)