Modelscope魔搭社区模型的下载与加载
ModelScope库的使用要求python版本为3.8及以上。
·
ModelScope库的使用要求python版本为3.8及以上。
在下载前,请先通过如下命令安装ModelScope:
pip install modelscope
如果已经安装过ModelScope,但是需要升级使用新版发布的Library,可以使用:
pip install modelscope --upgrade
以“LLM-Research/Llama-3.2-1B-Instruct”模型为例:
一、使用Git下载模型
首先确保 lfs 已经被正确安装
git lfs install
通过 git clone命令将 ModelScope 的模型仓库下载到指定目录。
git clone https://www.modelscope.cn/LLM-Research/Llama-3.2-1B-Instruct.git
二、加载模型
Windows缓存目录为:C:\Users\<用户名>\.cache\modelscope\hub
首次运行:会从 ModelScope 服务器下载模型到缓存目录
后续运行:直接加载本地缓存模型
1、使用ModelScope pipeline加载模型
import torch
from modelscope import pipeline
model_id = "LLM-Research/Llama-3.2-1B-Instruct"
pipe = pipeline(
"text-generation", # 任务类型
model=model_id, # 模型标识
torch_dtype=torch.bfloat16, # 计算精度(节省显存)
device_map="auto" # 自动选择GPU/CPU
)
messages = [
{"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
{"role": "user", "content": "who are you?"}
]
outputs = pipe(
messages,
max_new_tokens=256,
)
print(outputs)
print(outputs["message"]["content"])
2、使用AutoModel+ AutoTokenizer加载模型
from modelscope import AutoModelForCausalLM, AutoTokenizer
model_name = "LLM-Research/Llama-3.2-1B-Instruct"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
3、直接加载本地模型
from modelscope import AutoModelForCausalLM, AutoTokenizer
model_name = "./Llama-3.2-1B-Instruct" # 本地路径
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
更多推荐




所有评论(0)