transformers

huggingfaceApache-2.0活跃维护 有专家点评

统一加载和运行文本、视觉、音频、多模态的预训练模型,覆盖推理与训练,省去为每个模型重写代码的麻烦。

🤗 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.

v5.22.2发布于 2026-11-06 15:43 UTC168,771star +159 / 7 天35,167fork同步于 2026-11-11 05:17 UTC

专家点评

上手难度:进阶更新于 2026-11-11

模型结构定义的公共层,训练和推理都从它取模型,但训练循环不归它管

适用场景

  • 从 Hub 拉一个没见过的架构跑推理验证:pipeline 或 AutoModel 直接加载,省掉自己对着论文抄结构;换成自己实现,光对齐权重命名就要花半天
  • 微调时只换 head 和 loss:模型结构、tokenizer、权重加载都由它处理,训练循环交给 Accelerate 或 Trainer;自己从零写会重复实现大量加载逻辑
  • 需要把同一份权重喂给 vLLM/SGLang/TGI 做在线服务:它作为权重和配置的规范来源,保证离线训练和在线推理看到的是同一个模型定义
  • 多模态或音频模型快速试水:pipeline 一行跑通,先确认模型输出形态再决定要不要接进生产

踩坑

  • 版本约束是硬门槛:README 要求 Python 3.11+ 和 PyTorch 2.6+,老环境里升级会连带影响其他依赖,装不上通常卡在这
  • 首次 pipeline 调用会联网从 Hub 下载并缓存权重,离线环境或 CI 里不预先拉取会直接失败
  • 它明确不提供通用训练循环,想直接拿它当训练框架用会撞墙,通用 ML 循环要自己接 Accelerate;issue 里反复出现 checkpoint 权重未使用之类的加载警告,换模型或换版本时容易遇到

同类对比

训练侧要完整循环用 Accelerate 或 PyTorch Lightning;推理侧追求吞吐用 vLLM/SGLang 直接加载权重,不必经过它的 pipeline

怎么上手

由 README 提炼,执行前请确认
pip install "transformers[torch]"
硬件要求按 README 说明

README 未说明具体显存要求;示例中通过 device_map="auto" 自动分配设备,并支持 dtype=torch.bfloat16。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

统一模型定义框架,让文本、视觉、音频、多模态模型在训练与推理间互通

统一加载和运行文本、视觉、音频、多模态的预训练模型,覆盖推理与训练,省去为每个模型重写代码的麻烦。

核心能力

  • 用 Pipeline 高层 API 一行完成多模态推理
  • 集中定义模型结构,兼容 vLLM、SGLang、TGI 等推理引擎
  • 同一模型可在 PyTorch、JAX、TF2.0 间迁移
  • 三行代码即可训练 SOTA 模型
  • Hub 上提供 100 万+ 预训练 checkpoint

容易踩的坑

需 Python 3.11+ 与 PyTorch 2.6+,版本不匹配会装不上;首次运行 pipeline 会从 Hugging Face Hub 下载并缓存模型,需联网;README 明确说明它不提供通用训练循环,通用 ML 循环应改用 Accelerate。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v5.22.2
  1. v5.22.2Patch release v5.22.2最新正式版2026-11-06 · 2026-11-06 15:43 UTC

    Patch release v5.22.2

    Some in between patch for security and distributed fixes. See the included commits :hugs:

    • [Distributed] Set device_id only for NCCL (#50281) by @michaelbenayoun and @3outeille
    • Harden our Jinja sandboxing (#50431) by @Rocketknight1

    Full Changelog: https://github.com/huggingface/transformers/compare/v5.22.1...v5.22.2

  2. v5.22.1Patch release v5.22.12026-10-30 · 2026-10-30 09:36 UTC
    查看更新说明

    Patch release v5.22.1

    We just had to fix the documentation!

    ** [Fix] Remove WIP doc for Ml4 (https://github.com/huggingface/transformers/pull/50124) from @remi-or

  3. v5.22.0v5.22.0: Mistral Large 4 (Le Chonk)2026-10-29 · 2026-10-29 14:15 UTC
    查看更新说明

    New Models

    Mistral Large 4 (Le Chonk)

    Mistral Large 4 is Mistral's largest and most capable model to date: a 1 trillion-parameter natively multimodal Mixture-of-Experts model with 49 billion active parameters per token (52 billion including embeddings and output layers), trained from scratch on 3,800 NVIDIA Grace Blackwell GPUs in Mistral's own datacenters in Europe.

    Mistral Large 4 unifies instruction following, reasoning, coding, and agentic workflows in a single set of weights. While a generalist model, it shows especially good performance on workloads such as cybersecurity, finance, and law, and it surpasses frontier closed models on visual grounding. It is natively fluent in 160+ languages, including every official language of the European Union.

    Key Features

    Mistral Large 4 includes the following architectural choices:

    • ~1T total / ~52B active parameters: granular Mixture-of-Experts with 128 routed experts (4 active per token) and 1 shared expert.
    • 1M context length, for long-context workloads.
    • Multimodal input: accepts text and image input, with text output. Pixtral-style vision encoder trained to handle variable image sizes and aspect ratios.
    • Instruct and Reasoning functionalities with function calls, reasoning effort configurable per request.

    Mistral Large 4 offers the following capabilities:

    • Reasoning Mode: three reasoning efforts — low, medium, high (default) — so the same model can answer a quick chat reply or work through a complex agentic run.
    • Vision: analyzes images, charts, technical drawings, and documents, with state-of-the-art visual grounding among open weights.
    • Multilingual: natively fluent in 160+ languages, including all official languages of the European Union.
    • System Prompt: strong adherence and support for system prompts.
    • Agentic: native function calling, JSON output, and strict JSON schema enforcement.
    • Cybersecurity: state of the art among open-weight models for security work, while refusing malicious requests.
    • Large Context Window: supports a 1M context window.

    The model is released under the Mistral Ecosystem Open-Weight License: a modified version of the MIT license, for both commercial and non-commercial use — operating a Model-as-a-Service business requires a separate commercial license with Mistral.

    Recommended Settings
    • Reasoning Effort:
      • 'low' / 'medium' / 'high' — default is 'high'.
      • Use reasoning_effort="high" for complex prompts and agentic usage, 'low' for fast chat replies and 'medium' for day to day usage.
    • Sampling: for all reasoning efforts, we recommend the following sampling parameters:
      • temperature=1.0
      • top_p=0.95
    • System Prompt: define a clear environment and use case, including guidance on how to effectively leverage tools in agentic systems.
    • Tools: keep the set of tools well-defined and limit their number to the minimum required for the use case.
    • Context: the checkpoint supports a 1M context window.

    Breaking changes

    • 🚨 Separate EP logic into its own file (#49679) by @3outeille

    Quantization

    FP8 quantized models can now be used for adapter training (such as LoRA with PEFT). Backward passes were added to the dense and grouped FP8 matmuls, and is_trainable is now True. Backward also dequantizes experts in chunks and skips autograd at inference, which cuts peak memory in the MoE layer backward from about 28.9 GiB to 2.8 GiB at 8k tokens. Separately, the AMD CI image now install

    • FP8 backward: chunked expert dequant, skip autograd.Function at inference (#50117) by @ArthurZucker in [#50117]
    • Train adapters on top of FP8 weights (#50031) by @qgallouede
  4. v5.21.1Patch release v5.21.12026-10-29 · 2026-10-29 08:35 UTC
    查看更新说明

    Patch release v5.21.1

    ** Fix rope_scaling setter for configs that assign it during init (#50080 )

    We broke remote code loading in vllm, this fixes it sorry everyone!

  5. v5.21Release: v5.21.02026-10-26 · 2026-10-26 18:17 UTC
    查看更新说明

    Release v5.21.0

    New Model additions

    MiniCPM-OCR

    MiniCPM-OCR is a document-understanding model from OpenBMB's MiniCPM-V family. It keeps the MiniCPM-V 4.6 architecture, which pairs a SigLIP vision encoder and a window-attention merger with a Qwen3.5 language model. It is specialized for reading text-dense images such as scanned pages, screenshots, receipts and tables.

    Links: Documentation | Paper

    • Feat test (#49920) by @guarin in #49920

    Flint

    Flint is Recursive's mixture-of-experts language model. Compared to a standard SwiGLU MoE transformer such as Qwen3-MoE, it uses hybrid attention (sliding-window attention with rotary embeddings over the current token and the previous 512 tokens in most layers, and full attention without positional encoding in the remaining layers). It also has learned attention sinks, as in GPT-OSS, with per-head RMS-normalized queries and keys. Each sparse layer routes a token to 6 of 256 experts by sigmoid score and adds an ungated shared expert, and the first two layers are dense.

    Links: Documentation

    • Add Flint model support. (#49824) by @lovishmadaan in #49824

    UltraVBert

    UltraVBert extends ModernVBert by pairing the UltraBERT text encoder with a SigLIP vision encoder for visual document understanding and retrieval. Its image processor splits each page into 512-pixel tiles plus a global view. The connector merges each 4 x 4 block of vision patches into one token, so a tile becomes 64 image tokens, and RMS-normalizes them to the scale of UltraBERT's token embeddings. The max_image_tiles setting (27 by default) caps the number of tiles per page.

    Links: Documentation

    • Add UltraVBERT (#49685) by @athrael-soju in #49685

    Gradium Phonon TTS

    Gradium Phonon TTS is Gradium's family of on-device text-to-speech models, trained with the Pocket TTS recipe. A causal transformer reads a voice prompt and the text, then emits one continuous 32-dimensional audio latent per step at 12.5 Hz through a one-step flow head, and an end-of-speech head decides when the utterance ends. The latents are decoded to 24 kHz audio by a Pocket TTS audio tokenizer. Unlike Pocket TTS, voice conditioning uses 512-dimensional latents from a separate, unreleased speaker codec, so voices come as precomputed latents and cannot be cloned from a recording.

    Links: Documentation

    • Add GradiumPhononTTS (#49791) by @eustlb in #49791

    Pocket TTS

    Pocket TTS is Kyutai's 100M-parameter text-to-speech model, built as a Continuous Audio Language Model that runs faster than real time on CPU. A causal transformer emits one continuous audio latent per frame (12.5 Hz) through a one-step flow head, and an end-of-speech head decides when to stop. A Mimi-based audio tokenizer encodes voice prompts and decodes the generated latents to 24 kHz audio. Two flow heads are released, Lagrangian self-distillation (default) and drifting, and voices can be cloned from a recording, passed as precomputed latents, or loaded from cached KV states.

    Links: Documentation | [Paper](https://huggingface.co/papers/2509.06926 (the Continuous Audio Language Models paper, arXiv 2509.06926). It is the only

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    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.

    # venv
    python -m venv .my-env
    source .my-env/bin/activate
    # uv
    uv venv .my-env
    source .my-env/bin/activate
    

    Install Transformers in your virtual environment.

    # pip
    pip install "transformers[torch]"
    
    # uv
    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
    pip install '.[torch]'
    
    # uv
    uv pip install '.[torch]'
    

    Quickstart

    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.

    [!TIP] 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
    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"])
    

    Expand the examples below to see how Pipeline works for different modalities and tasks.

    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.'}
    
    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}]
    
    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'}]
    

    Why should I use Transformers?

    1. 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.
    2. 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.
    3. 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.
    4. 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

    Transformers is more than a toolkit to use pretrained models, it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone else to build their dream projects.

    In order to celebrate Transformers 100,000 stars, we wanted to put the spotlight on the community with the awesome-transformers page which lists 100 incredible projects built with Transformers.

    If you own or use a project that you believe should be part of the list, please open a PR to add it!

    Example models

    You can test most of our models directly on their Hub model pages.

    Expand each modality below to see a few example models for various use cases.

    • Masked word completion with ModernBERT
    • Named entity recognition with Gemma
    • Question answering with Mixtral
    • Summarization with BART
    • Translation with T5
    • Text generation with Llama
    • Text classification with Qwen

    Citation

    We now have a paper you can cite for the 🤗 Transformers library:

    @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"
    }