任务概览
使用Hugging Face平台、魔搭社区平台(可选)和魔乐社区平台(可选)下载文档中提到的模型(至少需要下载config.json文件、model.safetensors.index.json文件)
任务完成流程:
1. 先打开github codespaces
2. 选择Jupyter Notebook,点击Use this template
3. 在界面下方的终端(terminal)安装以下依赖,便于模型运行。
# 安装transformers
pip install transformers==4.38
pip install sentencepiece==0.1.99
pip install einops==0.8.0
pip install protobuf==5.27.2
pip install accelerate==0.33.0
4. 下载internlm2_5-7b-chat的配置文件
考虑到个人GitHub CodeSpace硬盘空间有限(32GB可用),而7B的模型相对较大,这里我们先演示如何下载模型文件夹的特定文件。 考虑到CodeSpace平台上默认的用户权限不是root权限,这里为方便演示直接在工作区创建文件,即 /workspaces/codespaces-jupyter 目录
以下载模型的配置文件为例,先新建一个hf_download_josn.py 文件
touch hf_download_josn.py
在这个文件中,粘贴以下代码
import os
from huggingface_hub import hf_hub_download
# 指定模型标识符
repo_id = "internlm/internlm2_5-7b"
# 指定要下载的文件列表
files_to_download = [
{"filename": "config.json"},
{"filename": "model.safetensors.index.json"}
]
# 创建一个目录来存放下载的文件
local_dir = f"{repo_id.split('/')[1]}"
os.makedirs(local_dir, exist_ok=True)
# 遍历文件列表并下载每个文件
for file_info in files_to_download:
file_path = hf_hub_download(
repo_id=repo_id,
filename=file_info["filename"],
local_dir=local_dir
)
print(f"{file_info['filename']} file downloaded to: {file_path}")
运行该文件(注意文件目录请在该文件所在目录下运行该文件)
python hf_download_josn.py
可以看到,已经从Hugging Face上下载了相应配置文件
5. 下载internlm2_5-chat-1_8b并打印示例输出
那么如果我们需想要下载一个完整的模型文件怎么办呢?创建一个python文件用于下载internlm2_5-1_8B模型并运行。下载速度跟网速和模型参数量大小相关联,如果网速较慢的小伙伴可以只尝试下载1.8b模型对应的config.json文件以及其他配置文件。
touch hf_download_1_8_demo.py
注意到在CodeSpace平台上是没有GPU资源的,因此我们Python代码中只使用CPU进行推理,我们需要修改跟CUDA有关的API,在hf_download_1_8_demo.py文件中粘贴以下内容:
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2_5-1_8b", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("internlm/internlm2_5-1_8b", torch_dtype=torch.float16, trust_remote_code=True)
model = model.eval()
inputs = tokenizer(["A beautiful flower"], return_tensors="pt")
gen_kwargs = {
"max_length": 128,
"top_p": 0.8,
"temperature": 0.8,
"do_sample": True,
"repetition_penalty": 1.0
}
# 以下内容可选,如果解除注释等待一段时间后可以看到模型输出
# output = model.generate(**inputs, **gen_kwargs)
# output = tokenizer.decode(output[0].tolist(), skip_special_tokens=True)
# print(output)
运行 python 文件
python hf_download_1_8_demo.py
等待几分钟后,会在控制台返回模型生成的结果(解除注释后)