[来源关键摘录] Transformers 官方开源仓库,提供跨模态预训练模型的统一模型定义与标准化生态接口。
[正文前段节选] Skip to content
Navigation Menu
Appearance settings
You signed in with another tab or window. Reload to refresh your session.
You signed out in another tab or window. Reload to refresh your session.
You switched accounts on another tab or window. Reload to refresh your session.
Dismiss alert
{{ message }}
Repository navigation
transformers
NotificationsYou must be signed in to change notification settings
Fork35.3k (35.3k)
Star169k (169k)You must be signed in to star a repository
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
huggingface.co/transformers
audiodeep-learningdeepseekgemmaglmhacktoberfestllmmachine-learningmodel-hubnatural-language-processingnlppretrained-modelspythonpytorchpytorch-transformersqwenspeech-recognitiontransformervlm
Apache-2.0 license
Code of conduct
Contributing
Security policy
Cite this repository
Custom properties
169.4k stars
1.3k watching
Report repository
BranchesTags
Open more actions menu
Latest commit
24,962 Commits
Folders and files
Last commit message
Last commit date
benchmark_v2
src/transformers
.git-blame-ignore-revs
.gitattributes
.python-version
CITATION.cff
CODE_OF_CONDUCT.md
CONTRIBUTING.md
MIGRATION_GUIDE_V5.md
awesome-transformers.md
doctest_list.txt
pyproject.toml
View all files
Repository files navigation
Tiếng Việt |
State-of-the-art pretrained models for inference and training
Transformers acts as the model-definition framework for state-of-the-art machine learning with text, computer
vision, audio, video, and multimodal models, for both inference and training.
It centralizes the model definition so that this definition is agreed upon across the ecosystem. transformers is the
pivot across frameworks: if a model definition is supported, it will be compatible with the majority of training
frameworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),
and adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from transformers.
We pledge to help support new state-of-the-art models and democratize their usage by having their model definition be
simple, customizable, and efficient.
There are over 1M+ Transformers model checkpoints on the Hugging Face Hub you can use.
Explore the Hub today to find a model and use Transformers to help you get started right away.
Installation
Transformers works with Python 3.11+, and PyTorch 2.6+.
Create and activate a virtual environment with venv or uv, a fast Rust-based Python package and project manager.
python -m venv .my-env
source .my-env/bin/activate
uv venv .my-env
Install Transformers in your virtual environment.
pip install "transformers[torch]"
uv pip install "transformers[torch]"
Install Transformers from source if you want the latest changes in the library or are interested in contributing. However, the latest version may not be stable. Feel free to open an issue if you encounter an error.
git clone https://github.com/huggingface/transformers.git
cd transformers
pip install '.[torch]'
uv pip install '.[torch]'
Get started with Transformers right away with the Pipeline API. The Pipeline is a high-level inference class that supports text, audio, vision, and multimodal tasks. It handles preprocessing the input and returns the appropriate output.
Instantiate a pipeline and specify model to use for text generation. The model is downloaded and cached so you can easily reuse it again. Finally, pass some text to prompt the model.
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.'}]
To chat with a model, the usage pattern is the same. The only difference is you need to construct a chat history (the input to Pipeline) between you and the system.
You can also chat with a model directly from the command line, as long as transformers serve is running.
transformers chat Qwen/Qwen2.5-0.5B-Instruct
import torch
{"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"])
Expand the examples below to see how Pipeline works for different modalities and tasks.
Automatic speech recognition
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
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
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
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'}]
Why should I use Transformers?
Easy-to-use state-of-the-art models:
High performance on natural language understanding & generation, computer vision, audio, video, and multimodal tasks.
Low barrier to entry for researchers, engineers, and developers.
Few user-facing abstractions with just three classes to learn.
A unified API for using all our pretrained models.
Lower compute costs, smaller carbon footprint:
Share trained models instead of training from scratch.
Reduce compute time and production costs.
Hundreds of model architectures with 1M+ pretrained checkpoints across all modalities.
Choose the right framework for every part of a model's lifetime:
Train state-of-the-art models in 3 lines of code.
Move a single model between PyTorch/JAX/TF2.0 frameworks at will.
Pick the right framework for training, evaluation, and production.
Easily customize a model or an example to your needs:
We provide examples for each architecture to reproduce the results published by its original authors.
Model internals are exposed as consistently as possible.
Model files can be used independently of the library for quick experiments.
When shouldn't I use Transformers?
This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files.
The training API is optimized to work with PyTorch models provided by Transformers. For generic machine learning loops, you should use another library like Accelerate.
100 projects using Transformers
[...内容已截断,完整版请查看原文或 Wayback 快照]