赞
踩
进入页面,点击“创建开发机”,然后选择默认镜像即可
创建成功后,可以看到开发机的页面
点击Terminal可以进入开发机终端,首先要输入bash
命令。这里我输入了echo $SHELL
得到的结果是/bin/bash
,说明shell的解释器是bash
,并不是为了切换解释器。猜测是因为多个人同时使用机子,使用bash,可以刷新bash的工作环境,防止别人以及自己之前的命令影响工作环境。
在每次进入开发机后,输入conda create --name internlm-demo --clone =/root/share/conda_envs/internlm-base
命令,创建conda环境。但目前最新的教程版本https://github.com/InternLM/tutorial/blob/main/helloworld/hello_world.md
中是让使用一个脚本来创建环境,速度较慢。感觉还是教程中提供的方式更好一些。
接着,自然是执行conda activate internlm-demo
激活该环境。
然后,还需要安装一些环境需要的包
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
首先,将模型拷贝到一个新的文件夹中(原目录已经存在在机子中,并且使用python可以访问目录下的文件,不太理解为什么还需要拷贝一次,猜测是方便查找自己的模型路径,因为/root/share/temp/model_repos下有两个文件,怕搞混)
mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-chat-7b /root/model/Shanghai_AI_Laboratory
首先进入/root
目录下,创建code
目录,然后进入该目录下,执行git clone https://gitee.com/internlm/InternLM.git
将对应代码拷贝到该目录下。由于是直接从git仓库中拷贝过来,我们可以切换版本和教程对应,这样就能保证我们按照教程中执行代码一定能成功。
cd InternLM
git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17
我们可以在 /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}")
然后在终端执行python /root/code/InternLM/cli_demo.py
即可使用该模型,并体验其对话能力。在执行代码时会等待模型加载,期间会逐渐增加显存的使用量:
然后我们便可以和模型进行交互,发现该模型表现还可以,能够成功区分鲁迅和周树人,似乎这个问题困扰了ChatGPT很久。由于我们是使用input
进行交互的,如果输入一些非字符串类型的东西,例如退格之类的,这会导致报错:
首先对/root/code/InternLM/web_demo.py
的29 行和 33 行代码进行修改,将模型的路径切换为本地对应的路径,即/root/model/Shanghai_AI_Laboratory/internlm-chat-7b
。
接着,进入开发机的VScode,在其terminal下输入conda activate internlm-demo
先激活对应环境,然后将开发机的端口和本地的6006端口进行映射。
在我们平常使用的vscode中进行端口映射非常简单,但是在开发机中,首先需要配置好公钥私钥,首先在本地机生成一个公钥,在cmd中执行ssh-keygen -t rsa
,生成的公钥所在的路径会在cmd中显示:
然后,我们将公钥的内容拷贝到平台上。然后在本地执行命令ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p 33090
,将对本地6006端口映射到ssh.intern-ai.org.cn的33090端口。
最后,在开发机中执行ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p 33090
,即可在开发机中运行起应用,我们只需要在浏览器输入localhost:6006
即可访问,并且会发现地址会变:
这里,图片没有显示出来,不知道是服务器中本身就没有图片,还是有其它问题影响到了。
即对应开发机创建,如果开发机创建已经完成,则可以跳过这一步
和上一章的模型拷贝相同
在/root/code
下拷贝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
即可。
执行样例:
计算简单的加法(可能需要工具),其会调用PythonInterpreter生成代码,然后使用FinishAction解释代码得到答案:
询问出生日期(只需要知识,不需要工具):其会通过自己的知识得到一个答案,并且让答案转为代码的形式,又让另一个工具解释该代码。
询问知识问题(只需要知识,不需要工具),表现很差:
总的来说,似乎这种流程没有什么问题,就应该是先解析成代码,再解释代码。但是某些问题并不需要代码,所以在执行该流程前,应当判断需不需要这个流程。
执行该Demo,需要A100(1/4) * 2,因此,需要先创建一个对应的开发机。
创建好开发机后,第一步仍然是创建环境/root/share/install_conda_env_internlm_base.sh xcomposer-demo
,然后执行conda activate xcomposer-demo
激活环境。
然后执行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
如果/root
下没有code
目录,还是要在/root
下创建code
目录,然后执行:
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
由于huggingface可能无法直接访问,因此使用镜像网站来解决,首先将下载命令封装成一个py文件 d.py:
from huggingface_hub import hf_hub_download
hf_hub_download(repo_id="internlm/internlm-chat-20b", filename="config.json")
然后执行HF_ENDPOINT=https://hf-mirror.com python d.py
即可。
非常感谢InternLM带来的教程,不仅提供了免费的算力,还有这么良心详细的教程,真的能学到了很多。一步步跟下来,基本上都能成功,甚至只出现了一次报错。只是,目前跟下来,能够知道怎么搭建一些东西了,但是其中的一些原理还是不太清楚,例如agent内部到底怎么实现的,大模型加载的时候似乎加载了多个文件,好像和传统的模型不太一样等等。希望后面教程能够讲述到一些细节。但总的来说,真的觉得非常棒,给InternLM点赞!!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。