本节课由d2l-ai-solutions-manual开源项目负责人宋志学大佬为我们讲解,大佬先简单介绍了lnternLM大模型的一些特点和优点,后面就手把手带我们从0到1在书生浦语平台上跑通了三个有趣的小demo.话不多说,让我们开始吧!(本文部分内容引自课程项目文档,这里给出链接tutorial/helloworld/hello_world.md at main · InternLM/tutorial (github.com)
1 大模型及 InternLM 模型简介
1.1 什么是大模型?
大模型通常指的是机器学习或人工智能领域中参数数量巨大、拥有庞大计算能力和参数规模的模型。这些模型利用大量数据进行训练,并且拥有数十亿甚至数千亿个参数。大模型的出现和发展得益于增长的数据量、计算能力的提升以及算法优化等因素。这些模型在各种任务中展现出惊人的性能,比如自然语言处理、计算机视觉、语音识别等。这种模型通常采用深度神经网络结构,如 Transformer、BERT、GPT( Generative Pre-trained Transformer )等。大模型的优势在于其能够捕捉和理解数据中更为复杂、抽象的特征和关系。通过大规模参数的学习,它们可以提高在各种任务上的泛化能力,并在未经过大量特定领域数据训练的情况下实现较好的表现。然而,大模型也面临着一些挑战,比如巨大的计算资源需求、高昂的训练成本、对大规模数据的依赖以及模型的可解释性等问题。因此,大模型的应用和发展也需要在性能、成本和道德等多个方面进行权衡和考量。
1.2 InternLM 模型全链条开源
InternLM 是一个开源的轻量级训练框架,旨在支持大模型训练而无需大量的依赖。通过单一的代码库,它支持在拥有数千个 GPU 的大型集群上进行预训练,并在单个 GPU 上进行微调,同时实现了卓越的性能优化。在 1024 个 GPU 上训练时,InternLM 可以实现近 90% 的加速效率。
基于 InternLM 训练框架,上海人工智能实验室已经发布了两个开源的预训练模型:InternLM-7B 和 InternLM-20B。
Lagent 是一个轻量级、开源的基于大语言模型的智能体(agent)框架,支持用户快速地将一个大语言模型转变为多种类型的智能体,并提供了一些典型工具为大语言模型赋能。通过 Lagent 框架可以更好的发挥 InternLM 的全部性能。
Lagent 框架图
浦语·灵笔是基于书生·浦语大语言模型研发的视觉-语言大模型,提供出色的图文理解和创作能力,结合了视觉和语言的先进技术,能够实现图像到文本、文本到图像的双向转换。使用浦语·灵笔大模型可以轻松的创作一篇图文推文,也能够轻松识别一张图片中的物体,并生成对应的文本描述。
上述提到的所有模型,都会带领大家一起体验哦!欢迎大家来给 InternLM: https://github.com/InternLM/InternLM/ 点点 star 哦!
2. 环境配置
2.1 pip 换源
临时使用镜像源安装,如下所示: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
pip config set global.index-url https://mirrors.cernet.edu.cn/pypi/web/simple
如果您的 pip 默认源的网络连接较差,临时使用镜像源升级 pip:
python -m pip install -i https://mirrors.cernet.edu.cn/pypi/web/simple --upgrade pip
2.2 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
生成该文件之后再修改。
快速配置
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
2.3 配置本地端口
由于服务器通常只暴露了用于安全远程登录的 SSH(Secure Shell)端口,如果需要访问服务器上运行的其他服务(如 web 应用)的特定端口,需要一种特殊的设置。我们可以通过使用SSH隧道的方法,将服务器上的这些特定端口映射到本地计算机的端口。这样做的步骤如下:
首先我们需要配置一下本地的 SSH Key
,我们这里以 Windows
为例。
步骤①:在本地机器上打开 Power Shell
终端。在终端中,运行以下命令来生成 SSH 密钥对:
ssh-keygen -t rsa
步骤②: 您将被提示选择密钥文件的保存位置,默认情况下是在 ~/.ssh/
目录中。按 Enter
键接受默认值或输入自定义路径。
步骤③:公钥默认存储在 ~/.ssh/id_rsa.pub
,可以通过系统自带的 cat
工具查看文件内容:
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
是根据开发机的端口进行更改。:
ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p 33090
3.模型下载
3.1Hugging Face
使用 Hugging Face 官方提供的 huggingface-cli
命令行工具。安装依赖:
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
下载模型中的部分文件
import os
from huggingface_hub import hf_hub_download # Load model directly
hf_hub_download(repo_id="internlm/internlm-7b", filename="config.json")
3.2 ModelScope
使用 modelscope
中的 snapshot_download
函数下载模型,第一个参数为模型名称,参数 cache_dir
为模型的下载路径。
注意:cache_dir
最好为绝对路径。
安装依赖:
pip install modelscope==1.9.5
pip install transformers==4.35.2
在当前目录下新建 python 文件,填入以下代码,运行即可。
import torch
from modelscope import snapshot_download, AutoModel, AutoTokenizer
import os
model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-chat-7b', cache_dir='your path', revision='master')
3.3OpenXLab
OpenXLab 可以通过指定模型仓库的地址,以及需要下载的文件的名称,文件所需下载的位置等,直接下载模型权重文件。
使用python脚本下载模型首先要安装依赖,安装代码如下:pip install -U openxlab
安装完成后使用 download 函数导入模型中心的模型。
from openxlab.model import download
download(model_repo='OpenLMLab/InternLM-7b', model_name='InternLM-7b', output='your local path')
4.作业展示
4.1使用 InternLM-Chat-7B 模型生成 300 字的小故事
部分代码
@st.cache_resource
def load_model():
model = (
AutoModelForCausalLM.from_pretrained("/root/model/Shanghai_AI_Laboratory/internlm-chat-7b", trust_remote_code=True)
.to(torch.bfloat16)
.cuda()
)
tokenizer = AutoTokenizer.from_pretrained("/root/model/Shanghai_AI_Laboratory/internlm-chat-7b", trust_remote_code=True)
return model, tokenizer
def prepare_generation_config():
with st.sidebar:
max_length = st.slider("Max Length", min_value=32, max_value=2048, value=2048)
top_p = st.slider("Top P", 0.0, 1.0, 0.8, step=0.01)
temperature = st.slider("Temperature", 0.0, 1.0, 0.7, step=0.01)
st.button("Clear Chat History", on_click=on_btn_click)
generation_config = GenerationConfig(max_length=max_length, top_p=top_p, temperature=temperature)
4.2熟悉 hugging face 下载功能,使用 huggingface_hub
python 包,下载 InternLM-20B
的 config.json 文件到本地
4.3 完成浦语·灵笔的图文理解及创作部署
def get_urls(caption, exclude):
headers = {'Content-Type': 'application/json'}
json_data = {'caption': caption, 'exclude': exclude, 'need_idxs': True}
response = requests.post('https://lingbi.openxlab.org.cn/image/similar',
headers=headers,
json=json_data)
urls = response.json()['data']['image_urls']
idx = response.json()['data']['indices']
return urls, idx
class Demo_UI:
def __init__(self, folder, num_gpus=1):
self.llm_model = AutoModel.from_pretrained(folder, trust_remote_code=True).cuda().eval()
if num_gpus > 1:
from accelerate import dispatch_model
device_map = auto_configure_device_map(args.num_gpus)
self.llm_model = dispatch_model(self.llm_model, device_map=device_map)
tokenizer = AutoTokenizer.from_pretrained(folder, trust_remote_code=True)
self.llm_model.internlm_tokenizer = tokenizer
self.llm_model.tokenizer = tokenizer
#self.llm_model.eval().to('cuda')
self.device = 'cuda'
print(f" load model done: ", type(self.llm_model))