如何從 Hugging Face 使用和下載模型到本地端:完整指南
日期:2024-06-25 04:03:14
介紹如何從 Hugging Face 下載模型到本地端的完整指南,包括環境設置、模型選擇及使用教學。
設置環境
確保你的開發環境中安裝了 Git 和 Git LFS。
還沒裝可以參考Git LFS教學文>>
Git LFS 介紹:為何需要它
Linux Git LFS安裝教學+Unable to locate package git lfs解決方法
此文章也有發表在Medium上 >>
選擇模型
我們以這個Repo為例子: shenzhi-wang/Llama3–8B Chinese Chat
這個Model我上次在LangChain RAG 打造個人化 Llama3 Flask Chatbot 網站的Ollama中文模型使用推薦也有提過,真的非常好用,很推薦。
作法一
這做法比較不建議。
前往Files and versions
把想要的檔案Download下來
這個作法只建議給檔案很少的模型使用 Ex. 一個.GGUF,
如果你的Model有好幾個拆分檔案你會按到崩潰,如下圖所示。
作法二
Clone repository到本地
用Git clone把Repo下載到本地
這個命令也是用來Clone模型,但是通過設置 GIT_LFS_SKIP_SMUDGE=1
,它只會下載模型文件的指針而不是實際的大型文件。這樣做可以節省頻寬,當你確定需要使用特定文件時再完全下載。
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/shenzhi-wang/Llama3-8B-Chinese-Chat
- 可以把模型給 pull 下來了
這個命令 git lfs pull --include="*.safetensors"
是用來從 Git LFS(Large File Storage)服務中下載指定擴展名為 .safetensors 的大型文件:
git lfs pull
: 這是 Git LFS 的命令,用於從遠程存儲庫下載大型文件。--include="*.safetensors"
: 這個選項指定了你希望下載的文件擴展名模式。
它表示你希望下載所有以 .safetensors 結尾的文件。
Hugging Face 本地模型使用教學
- Model Card 查看
Model Card 裡面常常會有範例可以看,像我的 shenzhi-wang/Llama3–8B Chinese Chat 裡面就有 Usage 示範。
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": "user", "content": "写一首诗吧"},
]
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))
裡面最重要的一行就是model_id
,
請你把model_id位置改成你下載在本地端的路徑。
model_id = "xxx/YourLocation"
大功告成🥰
到這裡你就學會以下:
- 把HuggingFace模型下載到本地
- 如何使用下載到本地的Model
喜歡 Weiberson 的文章嗎?在這裡留下你的評論!本留言區支援 Markdown 語法。