Hub 文件

在 Hugging Face Hub 上使用 🤗 Transformers

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

在 Hugging Face 使用 🤗 Transformers

🤗 transformers 是一個由 Hugging Face 和社群維護的庫,用於 Pytorch、TensorFlow 和 JAX 的最先進機器學習。它提供了數千個預訓練模型,可以在文字、視覺和音訊等不同模態上執行任務。我們有些偏心,但我們真的很喜歡 🤗 transformers

在 Hub 中探索 🤗 Transformers

Hub 中有超過 630,000 個 transformers 模型,你可以透過在模型頁面左側進行篩選來找到它們。

你可以找到適用於許多不同任務的模型:

你可以直接在瀏覽器中試用這些模型,無需下載即可進行測試,這得益於瀏覽器內建小部件!

Transformers 倉庫檔案

一個 Transformers 模型倉庫通常包含模型檔案和預處理器檔案。

模型

  • config.json 檔案儲存模型的架構細節,例如隱藏層數量、詞彙量大小、注意力頭數量、每個頭的維度等。這些元資料是模型的藍圖。

  • model.safetensors 檔案儲存模型的預訓練層和權重。對於大型模型,safetensors 檔案會分片以限制載入所需的記憶體量。瀏覽 model.safetensors.index.json 檔案以檢視模型權重從哪個 safetensors 檔案載入。

    {
    "metadata": {
      "total_size": 16060522496
    },
    "weight_map": {
      "lm_head.weight": "model-00004-of-00004.safetensors",
      "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
      ...
      }
    }

    你也可以透過點選模型卡片上的 ↗ 按鈕來視覺化此對映。

    Safetensors 是一種更安全、更快的序列化格式——與 pickle 相比——用於儲存模型權重。你可能會遇到以 binpthckpt 等格式序列化的權重,但 safetensors 作為更好的替代方案,在模型生態系統中越來越受青睞。

  • 模型還可能有一個 generation_config.json 檔案,其中儲存瞭如何生成文字的詳細資訊,例如是否取樣、取樣的頂部令牌、溫度以及用於開始和停止生成的特殊令牌。

預處理器

  • tokenizer_config.json 檔案儲存模型新增的特殊令牌。這些特殊令牌向模型指示許多資訊,例如句子的開頭、聊天模板的特定格式或指示影像。此檔案還顯示模型可以接受的最大輸入序列長度、預處理器類及其返回的輸出。
  • tokenizer.json 檔案儲存模型學習到的詞彙表。
  • special_tokens_map.json 是特殊令牌的對映。例如,在 Llama 3.1-8B-Instruct 中,字串開始令牌是 "<|begin_of_text|>"

對於其他模態,tokenizer_config.json 檔案被 preprocessor_config.json 替換。

使用現有模型

所有 transformer 模型都只需一行程式碼即可使用!根據你的使用方式,你可以使用高階 API 中的 pipeline 函式,或者使用 AutoModel 獲得更多控制。

# With pipeline, just specify the task and the model id from the Hub.
from transformers import pipeline
pipe = pipeline("text-generation", model="distilbert/distilgpt2")

# If you want more control, you will need to define the tokenizer and model.
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")

你還可以從特定版本(基於提交雜湊、標籤名或分支)載入模型,如下所示:

model = AutoModel.from_pretrained(
    "julien-c/EsperBERTo-small", revision="v2.0.1"  # tag name, or branch name, or commit hash
)

如果你想了解如何載入特定模型,可以點選“在 Transformers 中使用”,它會為你提供一個可載入的工作程式碼片段!如果需要有關模型架構的更多資訊,你還可以點選程式碼片段底部的“閱讀模型文件”。

分享你的模型

要了解所有關於使用 transformers 分享模型的資訊,請參閱官方文件中的分享模型指南。

transformers 中的許多類,例如模型和分詞器,都具有 push_to_hub 方法,可以輕鬆地將檔案上傳到倉庫。

# Pushing model to your own account
model.push_to_hub("my-awesome-model")

# Pushing your tokenizer
tokenizer.push_to_hub("my-awesome-model")

# Pushing all things after training
trainer.push_to_hub()

你可以做的事情還有很多,因此我們建議你查閱分享模型指南。

額外資源

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.