赞
踩
大模型通常指的是人工智能领域中参数数量巨大、拥有庞大计算能力和参数规模的模型。
大模型的特点及应用:利用大量数据进行训练;拥有数十亿甚至数千亿个参数;模型在各种任务中展现出惊人的性能。
本节将介绍如何使用 InternStudio中的 A100(1/4)GPU和 InternLM-Chat-7B 模型部署一个智能对话 Demo。
在 InternStudio 平台中选择 A100(1/4) 的配置,镜像选择 Cuda11.7-conda,如下图所示:
接下来进入开发机,并且打开其中的终端开始环境配置、模型下载和运行 demo。
首先,在终端输入 bash 命令,进入 conda 环境,然后使用以下命令从本地克隆一个已有的 pytorch 2.0.1 的环境:
bash # 请每次使用 jupyter lab 打开终端时务必先执行 bash 命令进入 bash 中
/root/share/install_conda_env_internlm_base.sh internlm-demo
然后使用以下命令激活环境:
conda activate internlm-demo
并在环境中安装运行 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 选项表示递归地复制目录及其内容
首先 clone 代码,在 /root 路径下新建 code 目录,然后切换路径, clone 代码:
mkdir -p /root/code/
cd /root/code
git clone https://gitee.com/internlm/InternLM.git
切换 commit 版本,与教程 commit 版本保持一致:
cd InternLM
git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17
将 /root/code/InternLM/web_demo.py
中 29 行和 33 行的模型更换为本地的 /root/model/Shanghai_AI_Laboratory/internlm-chat-7b
,记得保存文件!
首先切换为VSCode模式,在 /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 = 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-demo
环境,在终端运行以下命令:
python /root/code/InternLM/cli_demo.py
,即可体验 InternLM-Chat-7B 模型的对话能力。对话效果如下所示:
首先运行 /root/code/InternLM
目录下的 web_demo.py
文件,输入以下命令:
cd /root/code/InternLM
streamlit run web_demo.py --server.address 127.0.0.1 --server.port 6006
。然后,根据教程5.2节配置本地端口,将端口映射到本地。最后,在本地浏览器输入 http://127.0.0.1:6006 ,模型开始加载,在加载完模型之后,就可以与 InternLM-Chat-7B 进行对话了,如下图所示:
本节将介绍如何使用 InternStudio中的 A100(1/4)GPU、InternLM-Chat-7B 模型和Lagent 框架部署一个智能工具调用 Demo。
环境和模型已经在2.2和2.3节准备好了!
首先切换路径到 /root/code
克隆 lagent
仓库,并通过 pip install -e .
源码安装 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( "<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()
streamlit run /root/code/lagent/examples/react_web_demo.py --server.address 127.0.0.1 --server.port 6006
采用与2.6节相同的方案,然后在本地浏览器输入 http://127.0.0.1:6006
,选择 InternLM 模型加载。 输入数学问题 已知 2x+3=10,求x
, 此时 InternLM-Chat-7B 模型理解题意生成解此题的 Python 代码,Lagent 调度送入 Python 代码解释器求出该问题的解
,如下图所示:
本节将介绍如何使用 InternStudio中的 A100(1/4)* 2的机器和 InternLM-Xcomposer-7B 模型部署一个图文理解创作 Demo。
进入开发机,并在终端输入 bash 命令,进入 conda 环境,接下来就是安装依赖,使用以下命令从本地克隆一个已有的pytorch 2.0.1 的环境:
/root/share/install_conda_env_internlm_base.sh xcomposer-demo
然后使用以下命令激活环境:
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
InternStudio平台的 share 目录下已经准备了全系列的 InternLM 模型,所以直接复制即可。使用如下命令复制:
mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-xcomposer-7b /root/model/Shanghai_AI_Laboratory
在 /root/code
目录下 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 版本一致
在终端运行以下代码:
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 加载wep页面。输入星链新闻稿,一开始使用的edge浏览器,web界面只出现延迟,结果加载不出来:
终端出现以下错误提示:
按错误提示修改,仍然加载不出来输出,终端出现Could not create share link. Please check your internet connection or our status page: https://status.gradio.app.
错误提示,百度这句话,运行chmod +x /root/.local/lib/python3.10/site-packages/gradio/frpc_linux_amd64_v0.2
命令,好了终端无报错了,但是仍然加载不出来输出。**会不会是浏览器问题,因为有其他人成功!**更换chrome浏览器,成功!图文并茂文章创作如下所示:
多模态对话图文理解,如下所示:
临时使用镜像源安装,如下所示:some-package 为你需要安装的包名
pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple some-package
设置pip默认镜像源,升级 pip 到最新的版本 (>=10.0.0) 后进行配置,如下所示:
python -m pip install --upgrade pip
# 若默认源的网络连接较差,采用:
# python -m pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple --upgrade pip
pip config set global.index-url https://mirrors.cernet.edu.cn/pypi/web/simple
各系统都可以通过修改用户目录下的 .condarc 文件来使用镜像站,不同系统下的 .condarc 目录如下:
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/msys2
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
EOF
注意:Windows系统下先执行conda config --set show_channel_urls yes
生成.condarc
文件之后再修改。
使用 Hugging Face 官方提供的 huggingface-cli 命令行工具。安装依赖:
pip install -U huggingface_hub
利用以下命令下载:
huggingface-cli download --resume-download internlm/internlm-chat-7b --local-dir your_path
其中 resume-download:断点续下, local-dir:本地存储绝对路径。
基础作业2:熟悉 hugging face 下载功能,使用 huggingface_hub python 包,下载 InternLM-20B 的 config.json 文件到本地:
首先下载huggingface_hub包,如下图所示:
然后把下载文件的代码写到download.py文件中,如下图所示:
利用huggingface的镜像,执行HF_ENDPOINT=https://hf-mirror.com python download.py
,如下图所示:
成功下载!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。