当前位置:   article > 正文

书生·浦语:大模型全链路开源体系(二)——InternLM、Lagent、浦语·灵笔Demo调用_interlm web-demo

interlm web-demo

一、准备工作:

1、环境配置:

pip、conda换源

pip临时换源

  1. pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple some-package
  2. # 这里的“https://mirrors.cernet.edu.cn/pypi/web/simple”是所换的源,“some-package”是你需要安装的包

设置pip默认源,避免每次下载依赖包都要加上一长串的国内源

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

conda换源:

镜像站提供了 Anaconda 仓库与第三方源(conda-forge、msys2、pytorch 等),各系统都可以通过修改用户目录下的 .condarc 文件来使用镜像站。

不同系统下的 .condarc 目录如下:

  • Linux${HOME}/.condarc
  • macOS${HOME}/.condarc
  • WindowsC:\Users\<YourUserName>\.condarc

注意:

  • Windows 用户无法直接创建名为 .condarc 的文件,可先执行 conda config --set show_channel_urls yes 生成该文件之后再修改。
  1. cat <<'EOF' > ~/.condarc
  2. channels:
  3. - defaults
  4. show_channel_urls: true
  5. default_channels:
  6. - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  7. - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  8. - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
  9. custom_channels:
  10. conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  11. pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  12. EOF

更多详细内容可移步至 MirrorZ Help 查看

2、模型下载:

Huggingface:

使用 Hugging Face 官方提供的 huggingface-cli 命令行工具。安装依赖:

pip install -U huggingface_hub

 安装好依赖包之后,执行以下代码:

  1. import os
  2. from huggingface_hub import hf_hub_download # Load model directly
  3. # 下载模型
  4. os.system('huggingface-cli download --resume-download internlm/internlm-chat-7b --local-dir your_path')
  5. # resume-download:断点续下(断网也可继续下载)
  6. # local-dir:本地存储路径。(linux 环境下需要填写绝对路径)
  7. hf_hub_download(repo_id="internlm/internlm-7b", filename="config.json")
  8. # repo_id: 模型的名称
  9. # filename: 下载的文件名称

ModelScope:

安装依赖:

  1. pip install modelscope==1.9.5
  2. pip install transformers==4.35.2

安装完成后:

  1. import torch
  2. from modelscope import snapshot_download, AutoModel, AutoTokenizer
  3. import os
  4. model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-chat-7b', cache_dir='your path', revision='master')
  5. # cache_dir:最好写成绝对路径

 OpenXLAB:

安装依赖:

pip install -U openxlab

执行代码:

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

二、InternLM智能对话 Demo:

1、准备硬件设备:显卡

目前显卡比较短缺,各位大佬各显神通吧,这里以 InternStudio 为例

2、进入开发机配置环境:

进入 conda 环境之后,使用以下命令从本地克隆一个已有的 pytorch 2.0.1 的环境,运行时间可能比较长,耐心等待

  1. bash # 请每次使用 jupyter lab 打开终端时务必先执行 bash 命令进入 bash 中
  2. conda create --name internlm-demo --clone=/root/share/conda_envs/internlm-base

然后用下面命令激活虚拟环境,并安装所需环境:

  1. conda activate internlm-demo
  2. ————————————————————————————demo所需的环境依赖
  3. # 升级pip
  4. python -m pip install --upgrade pip
  5. pip install modelscope==1.9.5
  6. pip install transformers==4.35.2
  7. pip install streamlit==1.24.0
  8. pip install sentencepiece==0.1.99
  9. pip install accelerate==0.24.1

 3、模型下载:

根据之前介绍的模型下载的三种方式都可以实现模型的下载,但是速度相对较慢,这里我使用的是InternStudio 平台的 share 目录下已经为我们准备好的 InternLM 模型。

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

4、代码准备:

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

  1. cd /root/code
  2. git clone https://gitee.com/internlm/InternLM.git
  3. ## 切换 commit 版本,可以让大家更好的复现
  4. cd InternLM
  5. git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17

将 /root/code/InternLM/web_demo.py 中 29 行和 33 行的模型更换为本地的 /root/model/Shanghai_AI_Laboratory/internlm-chat-7b。 

5、运行:

(1)终端运行:

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

  1. import torch
  2. from transformers import AutoTokenizer, AutoModelForCausalLM
  3. model_name_or_path = "/root/model/Shanghai_AI_Laboratory/internlm-chat-7b"
  4. tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)
  5. model = AutoModelForCausalLM.from_pretrained(model_name_or_path, trust_remote_code=True, torch_dtype=torch.bfloat16, device_map='auto')
  6. model = model.eval()
  7. system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语).
  8. - InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.
  9. - InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.
  10. """
  11. messages = [(system_prompt, '')]
  12. print("=============Welcome to InternLM chatbot, type 'exit' to exit.=============")
  13. while True:
  14. input_text = input("User >>> ")
  15. input_text = input_text.replace(' ', '')
  16. if input_text == "exit":
  17. break
  18. response, history = model.chat(tokenizer, input_text, history=messages)
  19. messages.append((input_text, response))
  20. print(f"robot >>> {response}")

 然后在终端运行:python /root/code/InternLM/cli_demo.py  即可

(2)web运行:

运行 /root/code/InternLM 目录下的 web_demo.py 文件,输入以下命令后,l利用SSH密钥将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。

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

 

三、Lagent智能工具demo调用:

1、环境准备:

Lagent所需环境和InternLM环境一直,若运行环境已经安装好依赖包可直接跳过:

  1. # 升级pip
  2. python -m pip install --upgrade pip
  3. pip install modelscope==1.9.5
  4. pip install transformers==4.35.2
  5. pip install streamlit==1.24.0
  6. pip install sentencepiece==0.1.99
  7. pip install accelerate==0.24.1

 2、模型下载:

Lagnet是智能体构建的工具,基础模型可以直接使用InterLM模型,无需重复下载。

3、代码准备:

切换路径到 /root/code 克隆 lagent 仓库,并通过 pip install -e . 源码安装 Lagent

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

将 /root/code/lagent/examples/react_web_demo.py 内容替换为以下代码:

  1. import copy
  2. import os
  3. import streamlit as st
  4. from streamlit.logger import get_logger
  5. from lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
  6. from lagent.agents.react import ReAct
  7. from lagent.llms import GPTAPI
  8. from lagent.llms.huggingface import HFTransformerCasualLM
  9. class SessionState:
  10. def init_state(self):
  11. """Initialize session state variables."""
  12. st.session_state['assistant'] = []
  13. st.session_state['user'] = []
  14. #action_list = [PythonInterpreter(), GoogleSearch()]
  15. action_list = [PythonInterpreter()]
  16. st.session_state['plugin_map'] = {
  17. action.name: action
  18. for action in action_list
  19. }
  20. st.session_state['model_map'] = {}
  21. st.session_state['model_selected'] = None
  22. st.session_state['plugin_actions'] = set()
  23. def clear_state(self):
  24. """Clear the existing session state."""
  25. st.session_state['assistant'] = []
  26. st.session_state['user'] = []
  27. st.session_state['model_selected'] = None
  28. if 'chatbot' in st.session_state:
  29. st.session_state['chatbot']._session_history = []
  30. class StreamlitUI:
  31. def __init__(self, session_state: SessionState):
  32. self.init_streamlit()
  33. self.session_state = session_state
  34. def init_streamlit(self):
  35. """Initialize Streamlit's UI settings."""
  36. st.set_page_config(
  37. layout='wide',
  38. page_title='lagent-web',
  39. page_icon='./docs/imgs/lagent_icon.png')
  40. # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
  41. st.sidebar.title('模型控制')
  42. def setup_sidebar(self):
  43. """Setup the sidebar for model and plugin selection."""
  44. model_name = st.sidebar.selectbox(
  45. '模型选择:', options=['gpt-3.5-turbo','internlm'])
  46. if model_name != st.session_state['model_selected']:
  47. model = self.init_model(model_name)
  48. self.session_state.clear_state()
  49. st.session_state['model_selected'] = model_name
  50. if 'chatbot' in st.session_state:
  51. del st.session_state['chatbot']
  52. else:
  53. model = st.session_state['model_map'][model_name]
  54. plugin_name = st.sidebar.multiselect(
  55. '插件选择',
  56. options=list(st.session_state['plugin_map'].keys()),
  57. default=[list(st.session_state['plugin_map'].keys())[0]],
  58. )
  59. plugin_action = [
  60. st.session_state['plugin_map'][name] for name in plugin_name
  61. ]
  62. if 'chatbot' in st.session_state:
  63. st.session_state['chatbot']._action_executor = ActionExecutor(
  64. actions=plugin_action)
  65. if st.sidebar.button('清空对话', key='clear'):
  66. self.session_state.clear_state()
  67. uploaded_file = st.sidebar.file_uploader(
  68. '上传文件', type=['png', 'jpg', 'jpeg', 'mp4', 'mp3', 'wav'])
  69. return model_name, model, plugin_action, uploaded_file
  70. def init_model(self, option):
  71. """Initialize the model based on the selected option."""
  72. if option not in st.session_state['model_map']:
  73. if option.startswith('gpt'):
  74. st.session_state['model_map'][option] = GPTAPI(
  75. model_type=option)
  76. else:
  77. st.session_state['model_map'][option] = HFTransformerCasualLM(
  78. '/root/model/Shanghai_AI_Laboratory/internlm-chat-7b')
  79. return st.session_state['model_map'][option]
  80. def initialize_chatbot(self, model, plugin_action):
  81. """Initialize the chatbot with the given model and plugin actions."""
  82. return ReAct(
  83. llm=model, action_executor=ActionExecutor(actions=plugin_action))
  84. def render_user(self, prompt: str):
  85. with st.chat_message('user'):
  86. st.markdown(prompt)
  87. def render_assistant(self, agent_return):
  88. with st.chat_message('assistant'):
  89. for action in agent_return.actions:
  90. if (action):
  91. self.render_action(action)
  92. st.markdown(agent_return.response)
  93. def render_action(self, action):
  94. with st.expander(action.type, expanded=True):
  95. st.markdown(
  96. "<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
  97. + action.type + '</span></p>',
  98. unsafe_allow_html=True)
  99. st.markdown(
  100. "<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
  101. + action.thought + '</span></p>',
  102. unsafe_allow_html=True)
  103. if (isinstance(action.args, dict) and 'text' in action.args):
  104. st.markdown(
  105. "<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
  106. unsafe_allow_html=True)
  107. st.markdown(action.args['text'])
  108. self.render_action_results(action)
  109. def render_action_results(self, action):
  110. """Render the results of action, including text, images, videos, and
  111. audios."""
  112. if (isinstance(action.result, dict)):
  113. st.markdown(
  114. "<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
  115. unsafe_allow_html=True)
  116. if 'text' in action.result:
  117. st.markdown(
  118. "<p style='text-align: left;'>" + action.result['text'] +
  119. '</p>',
  120. unsafe_allow_html=True)
  121. if 'image' in action.result:
  122. image_path = action.result['image']
  123. image_data = open(image_path, 'rb').read()
  124. st.image(image_data, caption='Generated Image')
  125. if 'video' in action.result:
  126. video_data = action.result['video']
  127. video_data = open(video_data, 'rb').read()
  128. st.video(video_data)
  129. if 'audio' in action.result:
  130. audio_data = action.result['audio']
  131. audio_data = open(audio_data, 'rb').read()
  132. st.audio(audio_data)
  133. def main():
  134. logger = get_logger(__name__)
  135. # Initialize Streamlit UI and setup sidebar
  136. if 'ui' not in st.session_state:
  137. session_state = SessionState()
  138. session_state.init_state()
  139. st.session_state['ui'] = StreamlitUI(session_state)
  140. else:
  141. st.set_page_config(
  142. layout='wide',
  143. page_title='lagent-web',
  144. page_icon='./docs/imgs/lagent_icon.png')
  145. # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
  146. model_name, model, plugin_action, uploaded_file = st.session_state[
  147. 'ui'].setup_sidebar()
  148. # Initialize chatbot if it is not already initialized
  149. # or if the model has changed
  150. if 'chatbot' not in st.session_state or model != st.session_state[
  151. 'chatbot']._llm:
  152. st.session_state['chatbot'] = st.session_state[
  153. 'ui'].initialize_chatbot(model, plugin_action)
  154. for prompt, agent_return in zip(st.session_state['user'],
  155. st.session_state['assistant']):
  156. st.session_state['ui'].render_user(prompt)
  157. st.session_state['ui'].render_assistant(agent_return)
  158. # User input form at the bottom (this part will be at the bottom)
  159. # with st.form(key='my_form', clear_on_submit=True):
  160. if user_input := st.chat_input(''):
  161. st.session_state['ui'].render_user(user_input)
  162. st.session_state['user'].append(user_input)
  163. # Add file uploader to sidebar
  164. if uploaded_file:
  165. file_bytes = uploaded_file.read()
  166. file_type = uploaded_file.type
  167. if 'image' in file_type:
  168. st.image(file_bytes, caption='Uploaded Image')
  169. elif 'video' in file_type:
  170. st.video(file_bytes, caption='Uploaded Video')
  171. elif 'audio' in file_type:
  172. st.audio(file_bytes, caption='Uploaded Audio')
  173. # Save the file to a temporary location and get the path
  174. file_path = os.path.join(root_dir, uploaded_file.name)
  175. with open(file_path, 'wb') as tmpfile:
  176. tmpfile.write(file_bytes)
  177. st.write(f'File saved at: {file_path}')
  178. user_input = '我上传了一个图像,路径为: {file_path}. {user_input}'.format(
  179. file_path=file_path, user_input=user_input)
  180. agent_return = st.session_state['chatbot'].chat(user_input)
  181. st.session_state['assistant'].append(copy.deepcopy(agent_return))
  182. logger.info(agent_return.inner_steps)
  183. st.session_state['ui'].render_assistant(agent_return)
  184. if __name__ == '__main__':
  185. root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  186. root_dir = os.path.join(root_dir, 'tmp_dir')
  187. os.makedirs(root_dir, exist_ok=True)
  188. main()

4、web demo运行:

同样,建立ssh远程连接,在浏览器输入 http://127.0.0.1:6006 即可。

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

 

确实厉害,连MBA的题目都能轻松应对。

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

1、基础配置:

和之前两个demo一样的流程,从环境配置到模型下载

  1. # 进入 conda 环境之后,使用以下命令从本地克隆一个已有的pytorch 2.0.1 的环境
  2. conda create --name xcomposer-demo --clone=/root/share/conda_envs/internlm-base
  3. # 激活环境
  4. conda activate xcomposer-demo
  5. #安装依赖:
  6. pip install transformers==4.33.1
  7. pip install timm==0.4.12
  8. pip install sentencepiece==0.1.99
  9. pip install gradio==3.44.4
  10. pip install markdown2==2.4.10
  11. pip install xlsxwriter==3.1.2
  12. pip install einops accelerate
  13. # 模型下载:
  14. mkdir -p /root/model/Shanghai_AI_Laboratory
  15. cp -r /root/share/temp/model_repos/internlm-xcomposer-7b /root/model/Shanghai_AI_Laboratory

2、代码准备:

又是老朋友了

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

3、运行web demo:

 终端运行以下代码,同样是在完成ssh连接之后:

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

 num_gpus 指的是使用gpu的数量,vgpu-smi可以查看gpu的使用情况

五、SSH远程服务连接:

这里只是简单的介绍以下本次demo调用中使用的demo配置,具体可以看博客:ssh用法及命令_ssh命令大全-CSDN博客

1、在本地机器上打开 Power Shell 终端。在终端中,运行以下命令来生成 SSH 密钥对:

  1. ssh-keygen -t rsa
  2. ##-t表示类型选项,这里采用rsa加密算法

2、按 Enter 键接受默认值或输入自定义路径 ,默认情况下是在 ~/.ssh/ 目录中。(其中有一个提示是要求设置私钥口令passphrase,不设置则为空,这里看心情吧,如果不放心私钥的安全可以设置一下)执行结束以后会在 /home/当前用户 目录下生成一个 .ssh 文件夹,其中包含私钥文件 id_rsa 和公钥文件 id_rsa.pub

3、通过系统自带的 cat 工具查看文件内容:

  1. cat ~\.ssh\id_rsa.pub
  2. # ~ 是用户主目录的简写,.ssh 是SSH配置文件的默认存储目录,id_rsa.pub 是 SSH 公钥文件的默认名称。所以,cat ~\.ssh\id_rsa.pub 的意思是查看用户主目录下的 .ssh 目录中的 id_rsa.pub 文件的内容。

 4、将公钥复制到剪贴板中,然后回到 InternStudio 控制台,点击配置 SSH Key。

 

在本

ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p 33090

地终端输入以下指令 .6006 是在服务器中打开的端口,而 33090 是根据开发机的端口进行更改

注意:再这些操作中可能会出现多次warning,个人经验是只要没报错就继续运行。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/199934
推荐阅读
相关标签
  

闽ICP备14008679号