transformers

框架

huggingface/transformers

跨模态预训练模型推理与训练框架,支持文本、视觉、音频等。

项目简介

Hugging Face Transformers 是模型定义框架,提供数千个面向文本、视觉、音频和多模态任务的预训练模型。它支持推理与训练,并兼容主流训练框架和推理引擎,集中管理模型定义以促进 AI 生态互操作。

README 预览

\n\n\n  \n    \n    \n    \n  \n  \n  \n\n\n\n    \n    \n    \n    \n    \n    \n    \n\n\n\n    \n        English |\n        简体中文 |\n        繁體中文 |\n        한국어 |\n        Español |\n        日本語 |\n        हिन्दी |\n        Русский |\n        Português |\n        తెలుగు |\n        Français |\n        Deutsch |\n        Italiano |\n        Tiếng Việt |\n        العربية |\n        اردو |\n        বাংলা |\n        فارسی |\n        Türkçe |\n    \n\n\n\n    State-of-the-art pretrained models for inference and training\n\n\n\n    \n\n\nTransformers acts as the model-definition framework for state-of-the-art machine learning with text, computer\nvision, audio, video, and multimodal models, for both inference and training.\n\nIt centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the\npivot across frameworks: if a model definition is supported, it will be compatible with the majority of training\nframeworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),\nand adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.\n\nWe pledge to help support new state-of-the-art models and democratize their usage by having their model definition be\nsimple, customizable, and efficient.\n\nThere are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.co/models) you can use.\n\nExplore the [Hub](https://huggingface.co/) today to find a model and use Transformers to help you get started right away.\n\n## Installation\n\nTransformers works with Python 3.10+, and [PyTorch](https://pytorch.org/get-started/locally/) 2.5+.\n\nCreate and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager.\n\n```py\n# venv\

常见问题 (5)

故障排除
为什么 MM Grounding DINO 和 LLMDet 在 transformers v5 中预测出错误的(过小的)边界框,以及如何修复?

transformers 5.x(5.18.0+,main 分支上仍存在)中的一个已知 bug:MMGroundingDinoForObjectDetection._tied_weights_keys 会把每个解码器层的框头(box head)和分类头(class head)都绑定到第 0 层,忽略了检查点配置中的 decoder_bbox_embed_share: false / decoder_cls_embed_share: false。因此第 1-5 层复用了第 0 层的头部,导致输出的框出错(例如 RefCOCO acc@0.5 从 7/8 跌至 0/8)。受影响的检查点包括 iSEE-Laboratory/llmdet_tiny/base/large 和 openmmlab-community/mm_grounding_dino_tiny_* 以及 mm_grounding_dino_large_all。

修复方案 1 —— 降级到 v4 的行为,即每个层保留自己的头部:
pip install "transformers==4.57.1"

修复方案 2 —— 加载模型后,从检查点恢复每个解码器层自己的头部:

from huggingface_hub import hf_hub_download
from safetensors.torch import load_file

weights = load_file(hf_hub_download(model_id, "model.safetensors"))
for i in range(1, model.config.decoder_layers):
    model.bbox_embed[i] = type(model.bbox_embed[0])(model.config.d_model, model.config.d_model, 4, 3)
    model.bbox_embed[i].load_state_dict({k.split(f"bbox_embed.{i}.")[1]: v for k, v in weights.items()
                                         if k.startswith(f"model.decoder.bbox_embed.{i}.")})
    model.class_embed[i] = type(model.class_embed[0])(model.config)
    model.class_embed[i].bias.data = weights[f"model.decoder.class_embed.{i}.bias"].clone()
model.model.decoder.bbox_embed = model.bbox_embed
model.model.decoder.class_embed = model.class_embed

你可以先用以下方式验证该 bug:在配置声明头部不共享的情况下,model.bbox_embed[1].layers[0].weight is model.bbox_embed[0].layers[0].weight 却返回 True。

来源 Issue #49529
故障排除
为什么 transformers 的视频采样在处理低 FPS 的短视频时会返回空的帧索引(read_video_pyav 中出现 IndexError)?

这是 src/transformers/video_utils.py 中 default_sample_indices_fn() 函数的一个 bug。它计算 num_frames = int(total_num_frames / video_fps * fps),对于短视频,该计算结果会被截断为 0(例如,一个 10 帧、30 FPS 的视频以 1 FPS 采样时,会得到 int(10/30*1) == 0)。下游解码器随后会崩溃:read_video_pyav() 在 indices[-1] 处失败,read_video_opencv() 在 np.stack(frames) 处失败。修复方法:将 transformers 升级到包含该补丁的版本,补丁会对结果进行钳制,使得对于任何非空视频且请求的 FPS 为正数时,至少返回一个帧索引(例如 [0])。在旧版本上的临时解决方法:请求更高的 fps,使 int(total_num_frames / video_fps * fps) >= 1;或者在 total_num_frames > 0 且 fps > 0 时,使用 num_frames = max(1, int(total_num_frames / video_fps * fps)) 对该函数进行 monkey-patch。

来源 Issue #49907
故障排除
为什么 Transformers 的 image-text-to-text pipeline 在处理批量图像时会崩溃?VLM 处理器接受哪些输入格式?

Hugging Face Transformers 中的 VLM processor 接受的输入格式并不一致,因此对某个模型有效的 pipeline 调用可能会让另一个模型崩溃。关键规则和变通方法如下:

1. **URLs**:只有 Idefics、Idefics2、Idefics3 和 Pixtral 直接接受图像 URL。对于所有其他模型(LLaVA、BLIP、PaliGemma、Qwen2-VL 等),请先下载并转换为 PIL:

from PIL import Image
import requests
image = Image.open(requests.get(url, stream=True).raw)

2. **文件路径**:没有任何 VLM processor 接受原始文件路径——务必先用 Image.open(path) 加载。

3. **每条文本对应不同数量图像的嵌套批次**(例如 images=[[img1, img2], [img3]]):只有 Qwen2-VL、Chameleon、PaliGemma、Llava-Next、LLaVA-OneVision、Mllama、InstructBLIP、Idefics2 和 Idefics3 支持这种格式。LLaVA、BLIP2、VipLlava 和 Pixtral 等模型会在 processor 层面崩溃。变通方法:改用兼容的模型(例如用 llava-hf/llava-onevision-qwen2-0.5b-ov-hf 替代 llava-hf/llava-interleave-qwen-0.5b-hf),或者将每组文本/图像分别放在单独的非批量调用中处理。

4. **Padding 的怪癖**:当 padding=True 时,Qwen2-VL 处理非嵌套的批量图像会崩溃;而 Chameleon 必须手动将 padding 设置为 True 才能正常工作。

请查阅该模型的 processor 文档,或先用单张 PIL 图像进行测试,因为 PIL 是唯一被普遍支持的格式。

来源 Issue #34545
操作指南
如何使用 SpanBERT 与 Hugging Face Transformers 进行共指消解?

SpanBERT 的预训练权重托管在 Hugging Face Hub 上,可以使用标准 BERT 架构加载:

from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("SpanBERT/spanbert-base-cased")
model = AutoModel.from_pretrained("SpanBERT/spanbert-base-cased")

SpanBERT/spanbert-large-cased 同样可用。不过,原始论文中的共指消解头(TensorFlow 1.14 的 mandarjoshi90/coref 实现)从未移植到 Transformers,因此没有内置的 SpanBERT 共指消解流水线。目前进行共指消解的替代方案:

1. 使用社区模型 biu-nlp/f-coref(fastcoref),它提供了开箱即用的共指消解流水线。
2. 使用 neuralcoref(基于 spaCy)作为替代方案。
3. 如果需要复现论文的方法,可以在加载好的 SpanBERT AutoModel 之上自行微调一个 span 分类头。

来源 Issue #6497
故障排除
为什么 Gemma4 音频模型在使用 eager attention 时会给出错误或均匀的注意力输出,以及如何修复 eager 与 sdpa 之间的不匹配问题?

根本原因:Gemma4AudioAttention 通过 masked_fill(attention_mask.logical_not(), ...) 应用注意力掩码,这假定掩码为 bool 类型。但 create_bidirectional_mask 在 eager 模式下返回的是加性浮点掩码(0.0 = 允许,finfo.min = 禁止),因此 logical_not() 会反转语义——允许的位置反而被屏蔽掉,并且在完全允许的掩码下,注意力会退化为与内容无关的近均匀平均。临时解决方法:强制使用 sdpa 注意力,它使用正确的 bool 掩码——在加载模型时传入 attn_implementation="sdpa",或调用 model.set_attn_implementation("sdpa")。永久修复(为 transformers 打补丁):在 Gemma4AudioAttention 中同时处理两种掩码约定——bool 掩码 → masked_fill(mask.logical_not(), invalid_value);浮点掩码 → 在分块 5-D 转换之后以加性方式应用,即 attn_weights = attn_weights + attention_mask。同时让 _convert_4d_mask_to_blocked_5d 感知 dtype:对于浮点掩码,使用 F.pad(..., value=torch.finfo(dtype).min) 而不是 value=False(后者会填充 0.0,在浮点约定中表示“允许”)。通过在相同随机种子下比较 eager 与 sdpa 的输出来验证修复——最大绝对差值应从约 0.12 降至约 1e-6。

来源 Issue #48818