书生·浦语大模型图文对话Demo搭建

刺骨的言语ヽ痛彻心扉 2024-04-20 11:50 142阅读 0赞

前言

本节我们先来搭建几个Demo来感受一下书生浦语大模型

InternLM-Chat-7B 智能对话 Demo

我们将使用 InternStudio 中的 A100(1/4) 机器和 InternLM-Chat-7B 模型部署一个智能对话 Demo

环境准备

在 InternStudio 平台中选择 A100(1/4) 的配置,如下图所示镜像选择 Cuda11.7-conda,如下图所示:
在这里插入图片描述
接下来打开刚刚租用服务器的进入开发机,并且打开其中的终端开始环境配置、模型下载和运行 demo。
在这里插入图片描述
进入开发机后,在页面的左上角可以切换 JupyterLab、终端和 VScode,并在终端输入 bash 命令,进入 conda 环境。如下图所示:

在这里插入图片描述
进入 conda 环境之后,使用以下命令从本地克隆一个已有的 pytorch 2.0.1 的环境

  1. bash # 请每次使用 jupyter lab 打开终端时务必先执行 bash 命令进入 bash 中
  2. bash /root/share/install_conda_env_internlm_base.sh internlm-demo # 执行该脚本文件来安装项目实验环境

然后使用以下命令激活环境

  1. conda activate internlm-demo

并在环境中安装运行 demo 所需要的依赖。

  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

模型下载

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

-r 选项表示递归地复制目录及其内容

也可以使用 modelscope 中的 snapshot_download 函数下载模型,第一个参数为模型名称,参数 cache_dir 为模型的下载路径。

在 /root 路径下新建目录 model,在目录下新建 download.py 文件并在其中输入以下内容,粘贴代码后记得保存文件,如下图所示。并运行 python /root/model/download.py 执行下载,模型大小为 14 GB,下载模型大概需要 10~20 分钟

  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='/root/model', revision='v1.0.3')

注意:使用 pwd 命令可以查看当前的路径,JupyterLab 左侧目录栏显示为 /root/ 下的路径。

在这里插入图片描述

代码准备

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

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

切换 commit 版本,与教程 commit 版本保持一致,可以让大家更好的复现。

  1. cd InternLM
  2. git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17

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

在这里插入图片描述

终端运行

我们可以在 /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 >>> {
  21. response}")

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

  1. python /root/code/InternLM/cli_demo.py

在这里插入图片描述

web demo 运行

我们切换到 VScode 中,运行 /root/code/InternLM 目录下的 web_demo.py 文件,输入以下命令后,查看本教程配置本地端口后,将端口映射到本地。在本地浏览器输入 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

在这里插入图片描述
注意:要在浏览器打开 http://127.0.0.1:6006 页面后,模型才会加载,如下图所示:
在这里插入图片描述
在加载完模型之后,就可以与 InternLM-Chat-7B 进行对话了,如下图所示:

在这里插入图片描述

Lagent 智能体工具调用 Demo

我们将使用 InternStudio 中的 A100(1/4) 机器、InternLM-Chat-7B 模型和 Lagent 框架部署一个智能工具调用 Demo。

Lagent 是一个轻量级、开源的基于大语言模型的智能体(agent)框架,支持用户快速地将一个大语言模型转变为多种类型的智能体,并提供了一些典型工具为大语言模型赋能。通过 Lagent 框架可以更好的发挥 InternLM 的全部性能。

下面我们就开始动手实现!

环境准备

选择和第一个 InternLM 一样的镜像环境,运行以下命令安装依赖,如果上一个 InternLM-Chat-7B 已经配置好环境不需要重复安装.

  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

模型下载

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

-r 选项表示递归地复制目录及其内容

也可以在 /root/model 路径下新建 download.py 文件并在其中输入以下内容,并运行 python /root/model/download.py 执行下载,模型大小为 14 GB,下载模型大概需要 10~20 分钟

  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='/root/model', revision='v1.0.3')

Lagent 安装

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

Demo 运行

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

用同样的方法我们依然切换到 VScode 页面,运行成功后,查看本教程配置本地端口后,将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。

我们在 Web 页面选择 InternLM 模型,等待模型加载完毕后,输入数学问题 已知 2x+3=10,求x ,此时 InternLM-Chat-7B 模型理解题意生成解此题的 Python 代码,Lagent 调度送入 Python 代码解释器求出该问题的解。
在这里插入图片描述

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

我们将使用 InternStudio 中的 A100(1/4) * 2 机器和 internlm-xcomposer-7b 模型部署一个图文理解创作 Demo 。

环境准备

首先在 InternStudio 上选择 A100(1/4)*2 的配置。如下图所示:
在这里插入图片描述

接下来打开刚刚租用服务器的 进入开发机,并在终端输入 bash 命令,进入 conda 环境,接下来就是安装依赖。

进入 conda 环境之后,使用以下命令从本地克隆一个已有的pytorch 2.0.1 的环境

  1. /root/share/install_conda_env_internlm_base.sh xcomposer-demo

然后使用以下命令激活环境

  1. conda activate xcomposer-demo

接下来运行以下命令,安装 transformers、gradio 等依赖包。请严格安装以下版本安装!

  1. 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 模型,所以我们可以直接复制即可。使用如下命令复制:

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

-r 选项表示递归地复制目录及其内容

也可以安装 modelscope,下载模型的老朋友了

  1. pip install modelscope==1.9.5

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

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

代码准备

在 /root/code目录 git clone InternLM-XComposer 仓库的代码

  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 版本一致

Demo 运行

在终端运行以下代码:

  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 1 是因为InternStudio平台对于 A100(1/4)*2 识别仍为一张显卡。但如果有小伙伴课后使用两张 3090 来运行此 demo,仍需将 num_gpus 设置为 2 。

将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 即可。我们以又见敦煌为提示词,体验图文创作的功能,如下图所示:
在这里插入图片描述

接下来,我们可以体验一下图片理解的能力,如下所示~
在这里插入图片描述

通用环境配置

pip、conda 换源

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

pip 换源

临时使用镜像源安装,如下所示:some-package 为你需要安装的包名

  1. pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple some-package

设置pip默认镜像源,升级 pip 到最新的版本 (>=10.0.0) 后进行配置,如下所示:

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

如果您的 pip 默认源的网络连接较差,临时使用镜像源升级 pip:

  1. python -m pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple --upgrade pip

conda 换源

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

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

  • Linux: ${HOME}/.condarc
  • macOS: ${HOME}/.condarc
  • Windows: C:\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

配置本地端口

由于服务器通常只暴露了用于安全远程登录的 SSH(Secure Shell)端口,如果需要访问服务器上运行的其他服务(如 web 应用)的特定端口,需要一种特殊的设置。我们可以通过使用SSH隧道的方法,将服务器上的这些特定端口映射到本地计算机的端口。这样做的步骤如下:

首先我们需要配置一下本地的 SSH Key ,我们这里以 Windows 为例。

步骤①:在本地机器上打开 Power Shell 终端。在终端中,运行以下命令来生成 SSH 密钥对:(如下图所示)

  1. ssh-keygen -t rsa

在这里插入图片描述

步骤②: 您将被提示选择密钥文件的保存位置,默认情况下是在 ~/.ssh/ 目录中。按 Enter 键接受默认值或输入自定义路径。

步骤③:公钥默认存储在 ~/.ssh/id_rsa.pub,可以通过系统自带的 cat 工具查看文件内容:(如下图所示)

  1. cat ~\.ssh\id_rsa.pub

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

在这里插入图片描述

步骤④:将公钥复制到剪贴板中,然后回到 InternStudio 控制台,点击配置 SSH Key。如下图所示:

在这里插入图片描述

步骤⑤:将刚刚复制的公钥添加进入即可。

在这里插入图片描述

步骤⑥:在本地终端输入以下指令 .6006 是在服务器中打开的端口,而 33090 是根据开发机的端口进行更改。如下图所示:

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

在这里插入图片描述

模型下载

以下下载模型的操作不建议大家在开发机进行哦,在开发机下载模型会占用开发机的大量带宽和内存,下载等待的时间也会比较长,不利于大家学习。大家可以在自己的本地电脑尝试哦~

Hugging Face

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

  1. pip install -U huggingface_hub

然后新建 python 文件,填入以下代码,运行即可。

  • resume-download:断点续下
  • local-dir:本地存储路径。(linux 环境下需要填写绝对路径)

    import os

    下载模型

    os.system(‘huggingface-cli download —resume-download internlm/internlm-chat-7b —local-dir your_path’)

以下内容将展示使用 huggingface_hub 下载模型中的部分文件

  1. import os
  2. from huggingface_hub import hf_hub_download # Load model directly
  3. hf_hub_download(repo_id="internlm/internlm-7b", filename="config.json")
ModelScope

使用 modelscope 中的 snapshot_download 函数下载模型,第一个参数为模型名称,参数 cache_dir 为模型的下载路径。

注意:cache_dir 最好为绝对路径。

安装依赖:

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

在当前目录下新建 python 文件,填入以下代码,运行即可。

  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')
OpenXLab

OpenXLab 可以通过指定模型仓库的地址,以及需要下载的文件的名称,文件所需下载的位置等,直接下载模型权重文件。

使用python脚本下载模型首先要安装依赖,安装代码如下:pip install -U openxlab 安装完成后使用 download 函数导入模型中心的模型。

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

作者其他不相干的专栏,也来看看:

  • Prometheus+Grafana 实践派

Prometheus来自CNCF的产品,云原生时代监控产品; Grafana是一款开源的指标可视化工具,拥有大量的插件和图表工具来查询,展示您的指标,本专栏从基础知识开始学习,逐渐进阶,最终实现企业级统一监控目标

  • Loki + Tempo

一步步学习Grafana家族的轻量型聚合日志框架-Loki,链路追踪框架-Tempo

  • Spring Boot 3.x

Spring Boot 具有 Spring 一切优秀特性,Spring 能做的事,Spring Boot 都可以做,本专栏将全面介绍Spring Boot特性,继而对其进行全面的源码分析,不再犀牛望月,Spring Boot 版本:3.x

  • Spring Security

使用Spring Security版本5.7.2

  • Spring Boot Admin2

SBA2 源码解析

  • 阿提小作

作者平时心血来潮开发的小系统,都在运行玩了一段时间后停了

等等,还有其他很多

发表评论

表情:
评论列表 (有 0 条评论,142人围观)

还没有评论,来说两句吧...

相关阅读

    相关 快速一个直播Demo

    [为什么80%的码农都做不了架构师?>>> ][80_] ![hot3.png][] 缘由 最近帮朋友看一个直播网站的源码,发现这份直播源码借助 阿里云 、腾讯云这些大