三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

Transformers:先进机器学习模型定义框架,多领域适用且降低使用成本!

Transformers:先进机器学习模型定义框架,多领域适用且降低使用成本!

支持语言与模型概述

英语 | 简体中文 | 繁體中文 | 韩语 | 西班牙语 | 日语 | 印地语 | 俄语 | 葡萄牙语 | 泰卢固语 | 法语 | 德语 | 意大利语 | 越南语 | 阿拉伯语 | 乌尔都语 | 孟加拉语 | 波斯语 | 土耳其语 | 用于推理和训练的先进预训练模型

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.5 及以上版本。可以使用 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。不过,最新版本可能不稳定。若遇到错误,随时提交问题。

git clone https://github.com/huggingface/transformers.git cd transformers # pip pip install '.[torch]' # uv uv pip install '.[torch]'

快速开始

借助 Pipeline API 立即开启 Transformers 的使用之旅。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 的输入)。

提示:只要 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 如何处理不同模态和任务。

自动语音识别
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'}]

为什么要使用 Transformers?

  • 易于使用的先进模型:在自然语言理解与生成、计算机视觉、音频、视频和多模态任务中表现卓越。降低了研究人员、工程师和开发者的入门门槛,只需学习三个类,用户面对的抽象概念较少。拥有统一的 API,可用于使用所有预训练模型。
  • 降低计算成本,减少碳足迹:共享预训练模型,无需从头开始训练,减少计算时间和生产成本。涵盖数百种模型架构,拥有超 100 万个跨所有模态的预训练检查点。
  • 为模型生命周期的每个阶段选择合适的框架:只需三行代码即可训练先进模型。可随意在 PyTorch、JAX、TF2.0 框架之间迁移单个模型,为训练、评估和生产选择合适的框架。
  • 轻松定制模型或示例以满足需求:为每个架构提供示例,以重现原作者发表的结果。尽可能一致地公开模型内部结构,模型文件可独立于库使用,便于快速实验。

何时不适合使用 Transformers?

  • 该库并非神经网络构建块的模块化工具箱。模型文件中的代码未进行额外抽象的重构,目的是让研究人员能快速对每个模型进行迭代,而无需深入研究额外的抽象层或文件。
  • 训练 API 针对 Transformers 提供的 PyTorch 模型进行了优化。对于通用机器学习循环,应使用其他库,如 Accelerate。
  • 示例脚本仅为示例,可能无法直接在特定用例中运行,需要对代码进行调整。

100 个使用 Transformers 的项目

Transformers 不仅仅是一个使用预训练模型的工具包,它还是围绕其和 Hugging Face Hub 构建的项目社区。希望 Transformers 能让开发者、研究人员、学生、教授、工程师和其他所有人都能构建他们的梦想项目。为了庆祝 Transformers 获得 10 万颗星,推出了 awesome - transformers 页面,展示了 100 个使用 Transformers 构建的出色项目。如果拥有或使用的项目认为应该列入该列表,请提交 PR 添加!

示例模型

可以在 Hub 模型页面上直接测试大多数模型。展开以下每个模态,查看适用于各种用例的示例模型。

  • 音频:使用 CLAP 进行音频分类;使用 Parakeet、Whisper、GLM - ASR 和 Moonshine - Streaming 进行自动语音识别;使用 Wav2Vec2 进行关键词检测;使用 Moshi 进行语音到语音生成;使用 MusicGen 进行文本到音频转换;使用 CSM 进行文本到语音转换。
  • 计算机视觉:使用 SAM 进行自动掩码生成;使用 DepthPro 进行深度估计;使用 DINO v2 进行图像分类;使用 SuperPoint 进行关键点检测;使用 SuperGlue 进行关键点匹配;使用 RT - DETRv2 进行目标检测;使用 VitPose 进行姿态估计;使用 OneFormer 进行通用分割;使用 VideoMAE 进行视频分类。
  • 多模态:使用 Voxtral、Audio Flamingo 进行音频或文本到文本转换;使用 LayoutLMv3 进行文档问答;使用 Qwen - VL 进行图像或文本到文本转换;使用 BLIP - 2 进行图像描述;使用 GOT - OCR2 进行基于 OCR 的文档理解;使用 TAPAS 进行表格问答;使用 Emu3 进行统一的多模态理解和生成;使用 Llava - OneVision 进行视觉到文本转换;使用 Llava 进行视觉问答;使用 Kosmos - 2 进行视觉指代表达分割。
  • 自然语言处理(NLP):使用 ModernBERT 进行掩码词填空;使用 Gemma 进行命名实体识别;使用 Mixtral 进行问答;使用 BART 进行文本摘要;使用 T5 进行翻译;使用 Llama 进行文本生成;使用 Qwen 进行文本分类。

引用

@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" }
← 返回列表