huggingface/transformers — 完整教學
本文針對的版本:v5.9.0(2026-05-20),主分支
main;以高層架構與實務應用為主,不深入模型實作細節。
1. 專案定位
Hugging Face Transformers 是當前 AI 生態系最重要的 model-definition framework (模型定義框架),定位上扮演三個角色:
- SOTA 模型的標準入口:超過 475 個官方支援模型架構 (model architecture)、>1M pretrained checkpoints (預訓練權重)。
- 跨框架黏合層:原生支援 PyTorch 2.4+,並維持與 TensorFlow / JAX / Flax 的相容路徑;同時對接 vLLM、SGLang、TGI、llama.cpp、MLX 等下游 inference (推論) 引擎。
- Research → Production 轉接器:以
one model, one file為核心哲學 — 每個模型自包成一個modeling_*.py,不做共享抽象,方便研究者快速 fork / 改寫,又因 API 一致而能無痛 deploy。
與 Transformers 不競爭的位置:它不是 neural net building blocks (神經網路積木);要做自訂 architecture,請改用
torch.nn+ Accelerate (HF 訓練加速器)。
2. 安裝指南
2.1 環境需求
- Python 3.10+
- PyTorch 2.4+(或 TensorFlow 2.16+ / JAX 0.4+)
- 建議 GPU:NVIDIA CUDA 12+ 或 Apple MPS (Metal Performance Shaders)
2.2 標準安裝(推薦 uv)
1# 建立虛擬環境
2uv venv .venv && source .venv/bin/activate
3
4# 安裝(含 PyTorch backend)
5uv pip install "transformers[torch]"
6
7# 或:純 pip
8pip install "transformers[torch]"
2.3 開發版安裝(追主線)
1git clone --depth 1 https://github.com/huggingface/transformers.git
2cd transformers
3uv pip install -e ".[torch,dev]"
2.4 Optional extras(依需求加裝)
| Extra | 用途 |
|---|---|
transformers[torch] | PyTorch backend(最常用) |
transformers[sentencepiece] | SentencePiece tokenizer (Llama / T5 系列) |
transformers[audio] | 音訊處理(librosa, soundfile) |
transformers[vision] | 視覺處理(Pillow, opencv) |
transformers[serving] | transformers serve HTTP server |
transformers[quality] | ruff / black / isort 開發工具 |
2.5 第一個範例(30 秒驗證安裝)
1from transformers import pipeline
2pipe = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")
3print(pipe("Hello", max_new_tokens=20)[0]["generated_text"])
3. 核心架構
3.1 三層 API 結構
Transformers 提供三層遞減抽象度的 API,使用者依需求挑層級:
flowchart TB
User["使用者程式 (User Code)"]
Pipeline["pipeline() — 高階一行 API"]
Auto["AutoModel* / AutoTokenizer — 中階自動選型"]
Concrete["具體模型類 (e.g. LlamaForCausalLM) — 低階完整控制"]
Hub["huggingface_hub
模型權重 / config / tokenizer"]
Backend["PyTorch / JAX / TF backend"]
User --> Pipeline
User --> Auto
User --> Concrete
Pipeline --> Auto
Auto --> Concrete
Concrete --> Hub
Concrete --> Backend
style Pipeline fill:#dff,stroke:#0aa
style Auto fill:#fdf,stroke:#a0a
style Concrete fill:#ffd,stroke:#aa0
抽象層級對照:
| 層 | 範例 | 適用情境 |
|---|---|---|
| 高階 | pipeline("text-generation", model="Qwen/Qwen2.5") | demo、prototype、單次推論 |
| 中階 | AutoModelForCausalLM.from_pretrained(...) + AutoTokenizer.from_pretrained(...) | 多次推論、custom batching |
| 低階 | LlamaForCausalLM(config) + 手動 forward | 訓練、研究、改 architecture |
3.2 套件目錄結構
flowchart LR
Root["src/transformers/"]
Models["models/
(475 個模型)"]
Pipelines["pipelines/
20+ 個 task pipeline"]
Tokenization["tokenization modules
+ tokenization_mistral_common"]
Generation["generation/
(beam search / sampling / KV cache)"]
Trainer["trainer + training_args
Trainer + DeepSpeed/FSDP"]
Quantizers["quantizers/
bnb/GPTQ/AWQ/FP8/torchao"]
Integrations["integrations/
(WandB, Accelerate, PEFT...)"]
Utils["utils/
(loading, sharding, hub)"]
Root --> Models
Root --> Pipelines
Root --> Tokenization
Root --> Generation
Root --> Trainer
Root --> Quantizers
Root --> Integrations
Root --> Utils
重點目錄解讀:
models/— 每個模型一個 sub-package(如models/llama/),內含configuration_*.py/modeling_*.py/tokenization_*.py/processing_*.py,互不共享程式碼。pipelines/— task 導向:text_generation/automatic_speech_recognition/image_classification/visual_question_answering/mask_generation等 20+ 種。generation/— 包含continuous_batching/(v5 新增的連續批次推論)、beam search、各種 sampling。quantizers/— 量化後端統一介面,支援 bitsandbytes / GPTQ / AWQ / FP8 / torchao。
3.3 推論資料流(典型 LLM 例)
sequenceDiagram
autonumber
participant U as User
participant P as pipeline()
participant T as Tokenizer
participant M as Model (PyTorch)
participant G as Generation Mixin
participant K as KV Cache
U->>P: pipe("Hello")
P->>T: encode("Hello") -> input_ids
P->>M: forward(input_ids)
M->>G: generate(...) loop
loop 每個 token
G->>M: forward(last_token, past_kv)
M->>K: append new K/V
G->>G: sampling / beam selection
end
G-->>P: output_ids
P->>T: decode(output_ids) -> text
P-->>U: [{"generated_text": "..."}]
4. Helper Scripts / 重要工具
Transformers 提供多個官方 CLI 與工具:
| 工具 | 用途 | 範例 |
|---|---|---|
transformers chat <model> | 終端機直接和模型對話 | transformers chat Qwen/Qwen2.5-0.5B-Instruct |
transformers serve | 開啟 OpenAI-compatible HTTP server | transformers serve --model Qwen/Qwen2.5 |
transformers-cli convert | 將舊版 checkpoint 轉新格式 | 模型發布者用 |
examples/pytorch/ | 各 task 的訓練 script 範本 | run_clm.py / run_glue.py 等 |
benchmark/ & benchmark_v2/ | 跑性能基準 | CI 用 |
注意:
transformers serve為輕量級 dev server,production 請改用 vLLM / TGI / SGLang。
5. 應用場景
5.1 文字 (Text)
- LLM 推論:Llama / Qwen / DeepSeek / Gemma / GLM / Mistral / Phi
- Classification:BERT / RoBERTa / DeBERTa fine-tuning
- Translation / Summarization:T5 / BART / mBART
- Embedding:sentence-transformers 底層即 Transformers
5.2 視覺 (Vision)
- Classification:ViT / DINOv2 / ConvNeXt
- Detection:DETR / RT-DETR / RF-DETR / YOLOS
- Segmentation:SAM / Mask2Former / DepthAnything
- Generation:Stable Diffusion 文字編碼器走 Transformers
5.3 音訊 (Audio)
- ASR (Automatic Speech Recognition):Whisper / wav2vec2 / SeamlessM4T
- TTS (Text-to-Speech):Bark / VITS / Suno
- Audio classification:HuBERT / AST
5.4 多模態 (Multimodal / VLM)
- VLM:LLaVA / IDEFICS / Qwen2-VL / GLM-4V
- Document AI:LayoutLMv3 / DocVQA
- Video:VideoMAE / VideoLlama / VideoMT
5.5 訓練 / Fine-tuning 工作流
flowchart LR
Data["Dataset
(HF Datasets)"]
Tok["Tokenizer
AutoTokenizer"]
Model["Base Model
AutoModelFor*"]
PEFT["PEFT
(LoRA / QLoRA)"]
Trainer["Trainer
+ TrainingArguments"]
Accel["Accelerate
(DeepSpeed/FSDP)"]
Push["Hub Push
save_pretrained + push_to_hub"]
Data --> Tok --> Model
Model -.->|"optional"| PEFT
Model --> Trainer
PEFT --> Trainer
Trainer --> Accel
Trainer --> Push
6. 資安掃描
對
src/進行靜態掃描,排除測試檔案。掃描日:2026-05-22。
6.1 危險函式呼叫
| 模式 | 結果 | 評估 |
|---|---|---|
eval( | 大量 hits,99% 為 model.eval() (PyTorch 模式切換) | 🟢 安全 — 非 builtin eval() |
exec( | 0 hits | 🟢 |
os.system | 0 hits | 🟢 |
shell=True | 0 hits in non-test code | 🟢 |
pickle.loads | 0 hits in non-test code | 🟢 |
__import__ | 1 hit (processing_utils.py:114) — 合法 dynamic module loading,受限於 allowlist | 🟢 |
subprocess.run | 主要在 models/videomt/convert_*.py (一次性轉檔工具,非 runtime path) | 🟡 — 使用者跑 conversion script 時應檢視來源 |
6.2 機密外洩
| 模式 | 結果 |
|---|---|
Hardcoded api_key / password / secret / token ≥16 char | 🟢 零命中 |
6.3 已知 CVE / 安全 issue
- 🟡 #46097(OPEN):Sharded checkpoint loader 的
weight_map(來自*.index.json)未做 path sanitisation,可能被惡意 checkpoint 利用做 path traversal。- 緩解 (mitigation):只從 trusted Hub repo / 自己訓練的權重做
from_pretrained();避免直接載入來路不明的第三方.bin/.safetensors包。 - 預計在 v5.10 修復;可關注 PR 進度。
- 緩解 (mitigation):只從 trusted Hub repo / 自己訓練的權重做
6.4 整體評估
🟡 黃燈通過 — 程式碼本身無 hardcoded secrets / 高風險 builtin 呼叫;唯一活躍 issue 為 #46097 path traversal,影響面侷限於「載入未驗證權重」場景,對只用 HF Hub 官方 / verified repo 的使用者風險低。
flowchart LR
A["Trusted Hub repo
(huggingface.co/官方/已驗證)"]
B["from_pretrained()"]
C["✅ 安全"]
D["第三方 weight 檔包 (bin/safetensors)"]
E["from_pretrained(local_path)"]
F["🟡 #46097 風險"]
A --> B --> C
D -.->|"避免"| E
E --> F
style A fill:#dfd,stroke:#0a0
style C fill:#dfd,stroke:#0a0
style D fill:#fdd,stroke:#a00
style F fill:#fdd,stroke:#a00
7. FAQ
Q1. pipeline() vs AutoModel + manual loop,怎麼選?
A. demo 用 pipeline;生產或 batched 推論用 AutoModel;要改 architecture 用具體類別。
Q2. 為什麼 model 程式碼這麼長、又複製貼上一堆?
A. 設計哲學 one model, one file — 故意不抽象,方便研究者 fork 個別模型不被牽連。
Q3. Trainer 跑得慢,怎麼加速?
A. (1) dtype=torch.bfloat16 (2) gradient_checkpointing=True (3) 配 Accelerate + DeepSpeed Zero / FSDP (4) PEFT (LoRA) 降可訓練參數量 (5) torch.compile()。
Q4. 我的 GPU 只有 8 GB,要跑 70B model 怎麼辦?
A. (1) 4-bit 量化(load_in_4bit=True via bitsandbytes)(2) Offload 部分權重到 CPU/Disk (3) 改走 vLLM / llama.cpp + GGUF。
Q5. 怎麼解決 OOM during generation?
A. 限制 max_new_tokens / 開啟 use_cache=True / attn_implementation="flash_attention_2" / 減 batch_size。
Q6. 如何安全載入第三方權重?
A. 優先用 .safetensors(不可執行任意 Python,相對 .bin pickle 安全);HF 預設會做格式偵測。詳細見 §6.3。
Q7. 想加新模型上游進 Transformers?
A. 流程:fork → 用 add-new-model-like CLI 起 scaffold → 寫 configuration_*.py + modeling_*.py + tokenization_*.py → 加 tests → 寫 docs → 開 PR;詳見 CONTRIBUTING.md。
8. 進階技巧
8.1 Flash Attention 2 / SDPA
1model = AutoModelForCausalLM.from_pretrained(
2 "Qwen/Qwen2.5-7B",
3 attn_implementation="flash_attention_2", # or "sdpa"
4 dtype=torch.bfloat16,
5 device_map="auto",
6)
8.2 Static KV Cache + torch.compile
1model.generation_config.cache_implementation = "static"
2model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
可帶來 2-4× generation latency 改善(小 batch)。
8.3 量化(4-bit, bitsandbytes)
1from transformers import BitsAndBytesConfig
2bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
3model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", quantization_config=bnb)
8.4 Continuous Batching (v5+)
新版 generation/continuous_batching/ 模組提供類 vLLM 的連續批次推論;適合自架推論服務。
8.5 Custom Generation 行為
1output = model.generate(
2 **inputs,
3 do_sample=True, top_p=0.9, temperature=0.7,
4 repetition_penalty=1.05,
5 logits_processor=[MyCustomLogitsProcessor()],
6 stopping_criteria=[StopOnTokens([50256])],
7)
9. 整合進其他工作流
flowchart TB
HF["huggingface/transformers"]
subgraph "Inference 加速"
vLLM["vLLM"]
SGLang["SGLang"]
TGI["TGI"]
LlamaCpp["llama.cpp"]
MLX["MLX (Apple Silicon)"]
end
subgraph "Training / Fine-tuning"
Accelerate["Accelerate"]
PEFT["PEFT (LoRA)"]
TRL["TRL (RLHF/DPO)"]
DeepSpeed["DeepSpeed / FSDP"]
end
subgraph "Data / Eval"
Datasets["HF Datasets"]
Evaluate["HF Evaluate"]
LMEval["lm-evaluation-harness"]
end
subgraph "Deployment"
Gradio["Gradio"]
Spaces["HF Spaces"]
ONNX["ONNX / TensorRT"]
end
HF --> vLLM
HF --> SGLang
HF --> TGI
HF --> LlamaCpp
HF --> MLX
HF --> Accelerate
HF --> PEFT
HF --> TRL
Accelerate --> DeepSpeed
Datasets --> HF
HF --> Evaluate
HF --> LMEval
HF --> Gradio
HF --> Spaces
HF --> ONNX
常見組合:
- 本地 demo:Transformers + Gradio
- 本地高效推論:Transformers → 匯出 GGUF / safetensors → llama.cpp / vLLM
- Fine-tune LLM:Transformers + PEFT (LoRA) + Datasets + Accelerate
- RLHF / DPO:Transformers + TRL + PEFT
- 量化壓縮:Transformers + bitsandbytes / AutoGPTQ / AutoAWQ
- Serving:vLLM 載入 HF checkpoint(OpenAI API 相容)
10. 重點摘要
| 維度 | 結論 |
|---|---|
| 定位 | AI 領域事實標準的 model-definition framework |
| 規模 | 160k+ stars、475+ 模型、>1M checkpoints |
| 三大入口 | pipeline() / AutoModel* / 具體類 |
| 設計哲學 | one model, one file — 反抽象、易 fork |
| 訓練 | Trainer + Accelerate (DeepSpeed/FSDP) + PEFT |
| 推論 | 內建 generation;高效部署改 vLLM / SGLang / TGI / llama.cpp |
| 安全 | 🟡 整體良好,唯 #46097 path traversal 注意第三方權重 |
| 不適用 | 自訂 nn 積木、極致生產訓練迴圈 |
11. 進一步閱讀
- 官方文件:https://huggingface.co/docs/transformers
- Model Hub:https://huggingface.co/models
- 訓練教學:https://huggingface.co/docs/transformers/training
- Pipeline tutorial:https://huggingface.co/docs/transformers/pipeline_tutorial
- Generation strategies:https://huggingface.co/docs/transformers/generation_strategies
- Accelerate:https://huggingface.co/docs/accelerate
- PEFT (LoRA):https://huggingface.co/docs/peft
- TRL (RLHF/DPO):https://huggingface.co/docs/trl
- vLLM:https://docs.vllm.ai
- Awesome Transformers 100 projects:awesome-transformers.md
- 安全議題追蹤:https://github.com/huggingface/transformers/issues/46097
Comments