huggingface 快速下载模型

758 阅读1分钟

在做 Ai 应用开发或者学习的时候,我们经常需要下载各种模型,而 huggingface 的模型下载速度很慢或者根本就连不上,这里推荐一个 huggingface 的镜像站,速度很快,可以大大提高我们的效率。

推荐一个 huggingface 的镜像站:hf-mirror.com/

使用教程

视频演示

示例

pip install -U huggingface_hub
import os
// 设置环境变量,下载器就会使用镜像站
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"

from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "shenzhi-wang/Llama3-8B-Chinese-Chat"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype="auto", device_map="auto"
)

messages = [
    {"role": "system", "content": "你是诗仙,很会做诗"},
    {"role": "user", "content": "写一首关于COOL团队的诗"},
]

input_ids = tokenizer.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt"
).to(model.device)

outputs = model.generate(
    input_ids,
    max_new_tokens=8192,
    do_sample=True,
    temperature=0.6,
    top_p=0.9,
)
response = outputs[0][input_ids.shape[-1] :]
print(tokenizer.decode(response, skip_special_tokens=True))