书生大模型实战营第四期-入门岛-4. maas课程任务
任务一、模型下载
任务内容
使用Hugging Face平台、魔搭社区平台(可选)和魔乐社区平台(可选)下载文档中提到的模型(至少需要下载config.json文件、model.safetensors.index.json文件),请在必要的步骤以及结果当中截图。
作业过程
下载internlm2_5-7b-chat的配置文件
新建一个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}")
下载internlm2_5-chat-1_8b并打印示例输出
创建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