huggingface/transformers · 上手攻略
- 仓库:huggingface/transformers
- 链接:https://github.com/huggingface/transformers
- 分类:ML 框架 · 预训练模型定义框架
- 作者:Tom
- 更新:2026-08-04
这是什么
Transformers 是 Hugging Face 维护的 Python 库,提供超过 1M 个预训练模型检查点的统一加载、微调和推理接口。它覆盖文本(NLP)、计算机视觉、音频、视频和多模态五种模态,是目前最广泛使用的开源模型定义框架。
它的核心定位不是"又一个 PyTorch 工具箱",而是模型定义层的事实标准——如果一个模型在 transformers 中有定义,它就能兼容大多数训练框架(Axolotl、Unsloth、DeepSpeed、FSDP、PyTorch-Lightning)、推理引擎(vLLM、SGLang、TGI)和跨框架工具(llama.cpp、MLX)。
官方说明:模型文件中的代码故意不做过度的抽象封装,目的是让研究者能直接看到和修改每个模型的实现细节。
解决什么问题
在 transformers 出现之前,每用一个新的预训练模型(如 BERT、GPT-2、T5)都需要:
- 手动找到原作者的代码仓库
- 搞清楚模型结构和权重格式
- 自己写推理或微调代码
transformers 通过统一的 API(AutoModel、AutoTokenizer、Pipeline)把这 1M+ 个检查点的加载标准化,同时提供预训练、微调、评估的全流程支持。你不需要关心底层是 PyTorch、JAX 还是 TensorFlow。
快速安装
依赖要求
- Python 3.10+
- PyTorch 2.5+
# 方式一:pip(推荐)
pip install "transformers[torch]"
# 方式二:uv(更快)
uv pip install "transformers[torch]"
# 方式三:从源码安装(尝鲜或贡献)
git clone https://github.com/huggingface/transformers.git
cd transformers
pip install '.[torch]'
⚠️ 注意:
[torch]标记需要 PyTorch 已安装。如果没有 GPU 或不想装 PyTorch,可只装 transformers 核心库(pip install transformers),但大多数模型无法运行。
核心用法
1. Pipeline(最简推理,3 行上手)
Pipeline 是最高层 API,一行代码完成预处理 + 推理 + 后处理:
from transformers import pipeline
# 文本生成
pipe = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
result = pipe("the secret to baking a really good cake is ")
print(result)
支持的 task 包括(部分):
| task | 说明 |
|---|---|
text-generation |
文本生成 |
automatic-speech-recognition |
语音识别 |
image-classification |
图像分类 |
visual-question-answering |
视觉问答 |
fill-mask |
掩码填充 |
summarization |
摘要 |
translation |
翻译 |
question-answering |
阅读理解 |
2. Chat 对话
import torch
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a sassy robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, any fun things to do in New York?"}
]
pipe = pipeline(
task="text-generation",
model="meta-llama/Meta-Llama-3-8B-Instruct",
dtype=torch.bfloat16,
device_map="auto"
)
response = pipe(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
3. 语音识别
from transformers import pipeline
pipe = pipeline(
task="automatic-speech-recognition",
model="openai/whisper-large-v3"
)
result = pipe("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
print(result["text"])
4. 图像分类
from transformers import pipeline
pipe = pipeline(
task="image-classification",
model="facebook/dinov2-small-imagenet1k-1-layer"
)
result = pipe("https://huggingface.co/datasets/huggingface/documentation-images/main/parrots.png")
print(result)
# [{'label': 'macaw', 'score': 0.9978}, ...]
5. 视觉问答
from transformers import pipeline
pipe = pipeline(
task="visual-question-answering",
model="Salesforce/blip-vqa-base"
)
result = pipe(
image="https://huggingface.co/datasets/huggingface/documentation-images/main/idefics-few-shot.jpg",
question="What is in the image?"
)
print(result)
6. 底层 API(AutoModel / AutoTokenizer)
当 Pipeline 不够用时,直接加载模型和分词器:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "meta-llama/Meta-Llama-3-8B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto"
)
inputs = tokenizer("The capital of France is", return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=50)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
7. 命令行聊天(无需写 Python)
# 需要 transformers serve 在运行
transformers chat Qwen/Qwen2.5-0.5B-Instruct
典型适用场景
| 场景 | 推荐 API |
|---|---|
| 快速体验某个模型 | pipeline |
| 生产级推理服务 | 底层 AutoModel + 量化 |
| 模型微调 | Trainer API + TrainingArguments |
| 多模态任务(图文问答) | pipeline 或 AutoModel |
| 跨框架模型导出 | transformers → ONNX / TFLite |
| Hub 模型搜索与对比 | Hugging Face Hub 网页 |
坑与注意
1. 模型下载与缓存
首次运行会自动下载模型到 ~/.cache/huggingface/。如果遇到网络问题:
# 使用镜像
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
# 或手动设置
from huggingface_hub import snapshot_download
snapshot_download(repo_id="meta-llama/Meta-Llama-3-8B-Instruct")
2. GPU 显存估算
| 模型规模 | 估算显存(FP16) |
|---|---|
| 7B | ~14 GB |
| 13B | ~26 GB |
| 70B | ~140 GB |
使用 device_map="auto" 可自动在多卡间分片;使用量化(GPTQ/AWQ)可大幅降低显存需求(需额外安装 transformers[torch,gptq] 等)。
3. torch_dtype=torch.bfloat16 vs torch.float16
bfloat16:动态范围与 FP32 相同,精度损失较小,适合大模型float16:精度和动态范围都降低,可能出现下溢(梯度爆炸)- 建议:Ampere 架构(RTX 30xx / A100 及以上)用
bfloat16;旧卡用float16
4. 示例脚本不等于生产代码
官方说明:仓库中的 example scripts 仅供参考,不保证在所有场景下开箱即用,需要根据实际情况调整。
5. 不是模块化工具箱
transformers 的模型文件代码有意不做过度抽象封装,目的是让研究者能直接看到和修改模型细节。如果你在寻找"模块化积木",这可能不是正确的库(应转向 peft、trl、accelerate 等上层库)。
6. pipeline 的 device 自动分配
pipeline 默认把模型放在 CPU 上,通过 device 参数手动指定:
pipe = pipeline(..., device=0) # GPU 0
pipe = pipeline(..., device="cuda:1") # GPU 1
与同类对比
| 框架 | 侧重点 | 模型数量 | 上手难度 |
|---|---|---|---|
| 🤗 Transformers | 统一模型定义 + 推理 + 微调 | 1M+ | ★★☆ |
| PyTorch (原生) | 底层框架,无模型定义 | 无 | ★★★ |
| FastAI | 图像/文本分类快速上手 | 基于 PyTorch | ★★☆ |
| DeepSpeed | 大规模分布式训练 | 无(搭配 Transformers 用) | ★★★ |
| vLLM / SGLang | 高性能推理服务 | 无(搭配 Transformers 用) | ★★☆ |
| llama.cpp | CPU 侧量化推理 | 无(支持转换后的 GGUF) | ★★☆ |
Transformers 是模型定义层的事实标准,而非训练或推理优化层。它的价值在于让你用同一套 API 访问 1M+ 模型,而不需要关心底层是哪个框架或硬件。
一句话推荐结论
Transformers 是 AI 工程师接触最多模型的基础设施库:学一次 API,就能用 1M+ 检查点,覆盖所有主流模态——无论你是快速验证想法、做微调实验,还是对接生产推理服务,它都是起点。
来源
- 仓库 README:https://github.com/huggingface/transformers
- 官方文档:https://huggingface.co/docs/transformers/index
- 模型 Hub:https://huggingface.co/models?library=transformers
- 官方论文:https://aclanthology.org/2020.emnlp-demos.6/(Wolf et al., 2020)
- 安装要求:Python 3.10+, PyTorch 2.5+(官方 README,2026-08 核实)