19 KiB
Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
English | 简体中文 | 繁體中文 | 한국어 | Español | 日本語 | हिन्दी | Русский | Português | తెలుగు | Français | Deutsch | Italiano | Tiếng Việt | العربية | اردو | বাংলা | فارسی | Türkçe |
用于推理和训练的最先进预训练模型
Transformers 是一个模型定义框架,为涉及文本、计算机视觉、音频、视频和多模态模型的最先进机器学习提供推理和训练能力。
它集中了模型定义,使整个生态系统的定义保持一致。transformers 是跨框架的枢纽:如果一个模型定义得到支持,它将兼容大多数训练框架(Axolotl、Unsloth、DeepSpeed、FSDP、PyTorch-Lightning……)、推理引擎(vLLM、SGLang、TGI……)以及利用 transformers 模型定义的周边建模库(llama.cpp、mlx……)。
我们致力于支持新的最先进模型,并通过使其模型定义简单、可定制且高效,来普及这些模型的使用。
Hugging Face Hub 上有超过 100 万个 Transformers 模型检查点 可供使用。
立即探索 Hub,找到模型并使用 Transformers 快速上手。
安装
Transformers 支持 Python 3.10+ 和 PyTorch 2.4+。
使用 venv 或 uv,(一个基于 Rust 的快速 Python 包和项目管理器)创建并激活虚拟环境。
# venv
python -m venv .my-env
source .my-env/bin/activate
# uv
uv venv .my-env
source .my-env/bin/activate
在虚拟环境中安装 Transformers。
# pip
pip install "transformers[torch]"
# uv
uv pip install "transformers[torch]"
如果你希望使用库中的最新更改或有意贡献代码,可以从源码安装 Transformers。不过,最新版本可能不稳定。如果遇到错误,欢迎提交 issue。
git clone https://github.com/huggingface/transformers.git
cd transformers
# pip
pip install '.[torch]'
# uv
uv pip install '.[torch]'
快速入门
使用 Pipeline API 快速开始使用 Transformers。Pipeline 是一个高级推理类,支持文本、音频、视觉和多模态任务。它负责预处理输入并返回相应的输出。
实例化一个 pipeline 并指定用于文本生成的模型。模型会被下载并缓存,方便你重复使用。最后,传入一些文本作为提示输入到模型中。
from transformers import pipeline
pipeline = pipeline(task="text-generation", model="Qwen/Qwen2.5-1.5B")
pipeline("the secret to baking a really good cake is ")
[{'generated_text': 'the secret to baking a really good cake is 1) to use the right ingredients and 2) to follow the recipe exactly. the recipe for the cake is as follows: 1 cup of sugar, 1 cup of flour, 1 cup of milk, 1 cup of butter, 1 cup of eggs, 1 cup of chocolate chips. if you want to make 2 cakes, how much sugar do you need? To make 2 cakes, you will need 2 cups of sugar.'}]
与模型对话的使用模式相同。唯一的区别是,你需要在你和系统之间构建一个对话历史(即输入到 Pipeline 的内容)。
Tip
只要
transformers serve正在运行.),您也可以直接从命令行与模型对话。transformers chat Qwen/Qwen2.5-0.5B-Instruct
import torch
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
pipeline = pipeline(task="text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, device_map="auto")
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
展开以下示例,了解 Pipeline 在不同模态和任务中的工作方式。
自动语音识别(Automatic speech recognition)
from transformers import pipeline
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
图像分类(Image classification)
from transformers import pipeline
pipeline = pipeline(task="image-classification", model="facebook/dinov2-small-imagenet1k-1-layer")
pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
[{'label': 'macaw', 'score': 0.997848391532898},
{'label': 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
'score': 0.0016551691805943847},
{'label': 'lorikeet', 'score': 0.00018523589824326336},
{'label': 'African grey, African gray, Psittacus erithacus',
'score': 7.85409429227002e-05},
{'label': 'quail', 'score': 5.502637941390276e-05}]
视觉问答(Visual question answering)
from transformers import pipeline
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
pipeline(
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
question="What is in the image?",
)
[{'answer': 'statue of liberty'}]
为什么我应该使用 Transformers?
-
易于使用的前沿模型:
- 在自然语言理解与生成、计算机视觉、音频、视频及多模态任务上表现出色。
- 对研究人员、工程师和开发者门槛极低。
- 用户只需学习三个类,即可掌握少量面向用户的抽象。
- 统一的 API,用于调用我们所有的预训练模型。
-
更低计算成本,更小碳足迹:
- 共享已训练好的模型,而非从零开始训练。
- 减少计算时间和生产成本。
- 涵盖数百种模型架构,跨所有模态提供超过 100 万个预训练检查点(checkpoint)。
-
为模型生命周期的每个阶段选择合适的框架:
- 仅需 3 行代码即可训练前沿模型。
- 在 PyTorch/JAX/TF2.0 框架之间随意迁移单个模型。
- 为训练、评估和生产选择最合适的框架。
-
轻松根据需求定制模型或示例:
- 我们为每种架构都提供了示例,以复现原作者发表的结果。
- 模型内部结构尽可能一致地对外暴露。
- 模型文件可独立于库使用,便于快速实验。
什么情况下我不应使用 Transformers?
- 该库并非一个由神经网络构建块组成的模块化工具箱。模型文件中的代码有意未引入额外的抽象进行重构,以便研究人员能够快速迭代每个模型,而无需深入理解额外的抽象层或文件。
- 训练 API 针对 Transformers 提供的 PyTorch 模型进行了优化。对于通用的机器学习循环,您应使用其他库,例如 Accelerate.)。
- 示例脚本)仅为示例。它们不一定能在您的特定用例中开箱即用,您需要调整代码才能使其正常工作。
100 个使用 Transformers 的项目
Transformers 不仅仅是一个使用预训练模型的工具包,更是一个围绕它和 Hugging Face Hub 构建的项目社区。我们希望 Transformers 能够赋能开发者、研究人员、学生、教授、工程师以及所有其他人,去构建他们梦想中的项目。
为了庆祝 Transformers 获得 100,000 颗星标(star),我们希望通过 awesome-transformers 页面将聚光灯投向社区,该页面列出了 100 个使用 Transformers 构建的出色项目。
如果您拥有或使用某个您认为应当列入该列表的项目,欢迎提交 PR 来添加它!
模型示例
您可以直接在大多数模型的 Hub 模型页面.)上测试它们。
展开以下各模态,查看适用于不同用例的若干模型示例。
音频(Audio)
计算机视觉(Computer vision)
多模态(Multimodal)
- 音频或文本到文本:Voxtral,)、Audio Flamingo)
- 文档问答:LayoutLMv3)
- 图像或文本到文本:Qwen-VL)
- 图像描述:BLIP-2)
- 基于 OCR 的文档理解:GOT-OCR2)
- 表格问答:TAPAS)
- 统一多模态理解与生成:Emu3)
- 视觉到文本:Llava-OneVision)
- 视觉问答:Llava)
- 视觉指代表达分割:Kosmos-2)
NLP
引用
我们有一篇关于 🤗 Transformers 库的论文 可供引用:
@inproceedings{wolf-etal-2020-transformers,
title = "Transformers: State-of-the-Art Natural Language Processing",
author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
month = oct,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2020.emnlp-demos.6/",
pages = "38--45"
}
USD 预算:$0/$3;剩余 $3。
如果你现在想继续做其他工作,可以从以下任务中选择一项:
- 📊 data-viz:使用 Vega-Altair 创建交互式图表
- 📄 PDF:从 PDF 文档中提取并保留文本格式
- 🎙️ transcription:转录音频文件(语音转文字)
- 💬 support:与文档聊天
- 🗄️ DB:与 SQL 数据库聊天
- 🦜 code:调试和开发代码
- 🤗 agent:运行你自己的自主 AI 智能体
- 🔗 workflow:创建 AI 工作流和流水线
- 🔧 function:转换和结构化数据
- 📝 data:生成合成数据和标签
- 🛠️ action:执行动作并从外部服务检索信息
- ⚡ ⚡️ Fast:使用优化的运行时在 Nvidia GPU 上执行推理
- 🛡️ Guardrails:为你的智能体添加安全护栏
- 🎯 Fine-tuning:在自有数据上微调模型
- 🚢 Inference:在生产环境中部署模型
- ✍️ Prompt Engineering:编写和测试提示词
