
Hugging Face Transformers Pipeline 推理实战指南从语音识别到多模态的零门槛用法【免费下载链接】transformers 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.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers导读本文以 Transformers 官方教程《Pipelines pour linférence》docs/source/fr/tutoriel_pipeline.md为骨架系统讲解pipeline这一高层推理接口的使用方法。无论你面对的是文本、语音、图像还是多模态任务pipeline都能自动完成模型加载 预处理 前向推理 后处理的完整链路让你在完全不了解底层模型代码的情况下直接做推理。读完本文你将掌握如何用pipeline一行代码完成 ASR 语音转写、如何切换模型与调节device/batch_size等关键参数、如何在数据集上做批量推理、如何把 pipeline 接入 Web 服务与 Gradio 演示以及如何借助accelerate运行超大模型。一、pipeline是什么任务注册表与默认模型pipeline是 Transformers 提供的统一推理入口。从源码看所有受支持的任务都被登记在SUPPORTED_TASKS注册表中见 src/transformers/pipelines/init.py每个任务都绑定了对应的 Pipeline 实现类、可用的 AutoModel 类以及默认模型。以本文主角语音识别任务为例注册表中的条目如下取自当前仓库automatic-speech-recognition: { impl: AutomaticSpeechRecognitionPipeline, pt: (AutoModelForCTC, AutoModelForTDT, AutoModelForSpeechSeq2Seq) if is_torch_available() else (), default: {model: (facebook/wav2vec2-base-960h, 22aad52)}, type: multimodal, },也就是说当你只传taskautomatic-speech-recognition而不指定模型时仓库会自动加载默认的facebook/wav2vec2-base-960h。除 ASR 外注册表还覆盖text-generation默认HuggingFaceTB/SmolLM3-3B、text-classification默认distilbert/distilbert-base-uncased-finetuned-sst-2-english、zero-shot-classification默认facebook/bart-large-mnli、image-classification默认google/vit-base-patch16-224、image-segmentation默认facebook/detr-resnet-50-panoptic、object-detection、document-question-answering默认impira/layoutlm-document-qa、text-to-audio默认suno/bark-small、video-classification、depth-estimation、mask-generation、any-to-any等 20 余类任务覆盖文本、视觉、音频与多模态全场景。pipeline工厂函数本身的签名见 src/transformers/pipelines/init.py支持task、model、config、tokenizer、feature_extractor、image_processor、processor、revision、device、device_map、dtype、model_kwargs等众多参数。一条 pipeline 由三部分组成负责预处理的 tokenizer / image_processor / feature_extractor / processor、负责预测的模型以及可选的后处理步骤。二、Pipeline 基本用法以语音识别ASR为例虽然每个任务都有专属的 pipeline 类但更简单的做法是使用通用的pipeline工厂——它会根据任务自动加载合适的默认模型和预处理类。以自动语音识别ASR即语音转文本为例from transformers import pipeline transcriber pipeline(taskautomatic-speech-recognition)创建完成后把输入此处是音频文件 URL传给 pipeline 即可transcriber(https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac) {text: I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES}如果你对默认的 Wav2Vec2 转写结果不满意可以随时换用别的 ASR 模型。例如 OpenAI 的 Whisper large-v2——它比 Wav2Vec2 晚发布两年训练数据量约为其 10 倍在多数下游基准上表现更好并且还能预测标点与大小写transcriber pipeline(modelopenai/whisper-large-v2) transcriber(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.}可以看到Whisper 的输出不仅大小写规范还带上了句号明显更贴近真实文本。这也是 pipeline 设计哲学的直接体现从一个模型切换到另一个模型是微不足道的——只需改一个模型标识符。需要说明的是从当前仓库的SUPPORTED_TASKS注册表看automatic-speech-recognition任务的默认模型是facebook/wav2vec2-base-960h见上文因此教程里先跑默认模型、再换 Whisper的对比路径完全成立也印证了model参数可以完全覆盖任务默认模型的设计。多输入批量传递如果有多条输入直接以列表形式传入即可transcriber( [ https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac, https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac, ] )Pipeline 内部会把列表输入逐条或按 batch走完预处理—推理—后处理链路输出与单条输入结构一致的结果列表。三、Pipeline 核心参数详解pipeline支持大量参数一部分是任务特定的另一部分对所有 pipeline 通用。参数可以在创建 pipeline 时设定也可以在调用时临时覆盖且调用时的参数会覆盖创建时的值并在下次调用时恢复为创建时的值transcriber pipeline(modelopenai/whisper-large-v2, my_parameter1) out transcriber(...) # 使用 my_parameter1 out transcriber(..., my_parameter2) # 临时覆盖使用 my_parameter2 out transcriber(...) # 恢复为 my_parameter1下面重点介绍 3 个关键参数。3.1 Device指定推理设备设置devicen后pipeline 会把模型自动放到指定设备上无论底层是 PyTorch 还是 TensorFlow 都适用transcriber pipeline(modelopenai/whisper-large-v2, device0)当模型太大、单张 GPU 放不下且使用 PyTorch 时可以设置device_mapauto让 Accelerate 自动决定如何切分和存放模型权重。使用device_map需要先安装 Acceleratepip install --upgrade accelerate然后transcriber pipeline(modelopenai/whisper-large-v2, device_mapauto)注意一旦传了device_mapauto就不要再同时传devicedevice参数否则可能出现预期之外的行为。从源码看src/transformers/pipelines/base.pyPipeline 在初始化时会检查模型是否已带hf_device_map即已被 Accelerate 分片加载若同时显式指定device会触发冲突检查或忽略逻辑。3.2 Batch size批大小默认情况下pipeline不会做批量推理。原因是批处理不一定更快某些场景下反而显著更慢例如单条超长音频需要分块处理时。但如果你的场景适合批处理可以这样用transcriber pipeline(modelopenai/whisper-large-v2, device0, batch_size2) audio_filenames [fhttps://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac for i in range(1, 5)] texts transcriber(audio_filenames)上面代码对 4 个音频文件以每批 2 个的方式送入模型GPU 上批处理更可能带来加速而你不需要编写任何额外的批处理逻辑。输出结果与不批处理时完全一致批处理只是帮助你提高吞吐的手段。从实现上看批处理逻辑位于 src/transformers/pipelines/base.pypipeline 内部会构造DataLoaderbatch_size即为 DataLoader 的批大小并用pad_collate_fn做动态 padding 对齐再交给PipelineIterator逐个 batch 执行前向推理。此外pipeline 还能化解批处理的另一层复杂性对某些 pipeline单个输入如一段超长音频需要被切成多个片段才能被模型处理这种分块批处理chunk batching同样由 pipeline 自动完成无需你干预。3.3 任务特定参数return_timestamps与chunk_length_s所有任务都提供各自特定的参数。以transformers.AutomaticSpeechRecognitionPipeline.__call__为例return_timestamps参数对视频字幕生成非常有用transcriber pipeline(modelopenai/whisper-large-v2, return_timestampsTrue) transcriber(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., chunks: [{timestamp: (0.0, 11.88), text: I have a dream that one day this nation will rise up and live out the true meaning of its}, {timestamp: (11.88, 12.38), text: creed.}]}可以看到模型不仅转写出了文本还给出了每一句的起止时间戳这正是视频字幕所需的。源码中对return_timestamps的取值有严格校验见 automatic_speech_recognition.pyCTC 模型只接受char或word带语言模型的 CTC 只能输出word级时间戳非 Whisper 的 seq2seq 模型暂不支持时间戳。另一个实用参数是chunk_length_s用于处理模型单次无法容纳的超长音频例如整部电影或 1 小时视频的字幕制作transcriber pipeline(modelopenai/whisper-large-v2, chunk_length_s30) transcriber(https://huggingface.co/datasets/reach-vb/random-audios/resolve/main/ted_60.wav) {text: So in college, I was a government major, ...}从源码看automatic_speech_recognition.pychunk_length_s会把音频按指定秒数切块stride_length_s默认为块长的 1/6控制相邻块之间的重叠以保证切分边界处的转写不丢失信息。若找不到真正有用的参数也可以向项目提交 feature request。四、在大数据集上运行 Pipelinepipeline 同样支持对大规模数据集做推理。官方推荐的最简单方式是使用迭代器iteratordef data(): for i in range(1000): yield fMy example {i} pipe pipeline(modelopenai-community/gpt2, device0) generated_characters 0 for out in pipe(data()): generated_characters len(out[0][generated_text])data()迭代器逐个产出样本pipeline 会自动识别输入是可迭代对象并边取数边在 GPU 上处理底层使用了 PyTorch 的DataLoader见 src/transformers/pipelines/base.py 与 src/transformers/pipelines/pt_utils.py。这样做的好处是你无需为整个数据集分配内存同时能以最快速度持续喂给 GPU。既然批处理可能提速这里也值得尝试调节batch_size参数。最常见的做法是从 Datasets 库加载数据集并用KeyDataset工具类取出关心的字段。KeyDataset的实现非常简洁见 src/transformers/pipelines/pt_utils.py它包装一个datasets.Dataset并在__getitem__中只返回指定 key 对应的值# KeyDataset 是一个工具类只输出我们关心的字段 from transformers.pipelines.pt_utils import KeyDataset from datasets import load_dataset pipe pipeline(modelhf-internal-testing/tiny-random-wav2vec2, device0) dataset load_dataset(hf-internal-testing/librispeech_asr_dummy, clean, splitvalidation[:10]) for out in pipe(KeyDataset(dataset, audio)): print(out)注意KeyDataset依赖datasets库运行上述代码前请先pip install datasets。对于需要同时取两个字段的场景如文本对分类pt_utils.py中还提供了KeyPairDataset对应src/transformers/pipelines/pt_utils.py#L313-L323。五、将 Pipeline 接入 Web 服务把 pipeline 暴露为 Web 服务是在线推理最常见的形态。由于构建推理引擎本身是一个复杂话题官方为它单独开设了专题页面详见 Pipeline 网络服务指南对应英文文档pipeline_webserver.md。简单说pipeline 的__call__接口天然适合被封装为 HTTP 端点输入 JSON 化、输出dict/列表化前后端解耦非常干净。六、视觉 Pipeline图像分类使用pipeline做视觉任务与语音任务几乎完全一样指定任务或直接指定模型然后把图像传给分类器。图像可以是URL、本地路径或 base64 编码的图像。from transformers import pipeline vision_classifier pipeline(modelgoogle/vit-base-patch16-224) preds vision_classifier( imageshttps://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg ) preds [{score: round(pred[score], 4), label: pred[label]} for pred in preds] preds [{score: 0.4335, label: lynx, catamount}, {score: 0.0348, label: cougar, puma, catamount, mountain lion, painter, panther, Felis concolor}, {score: 0.0324, label: snow leopard, ounce, Panthera uncia}, {score: 0.0239, label: Egyptian cat}, {score: 0.0229, label: tiger cat}]输出是一个按置信度排序的标签列表score已被我们手动四舍五入到 4 位小数以便展示。google/vit-base-patch16-224正是注册表中image-classification的默认模型见 src/transformers/pipelines/init.py。七、文本 Pipeline零样本分类文本任务同样只是换个模型的事。下面的例子使用facebook/bart-large-mnli——这是一个zero-shot 分类模型它允许你自由指定任意标签from transformers import pipeline # 这是一个 zero-shot-classification 模型 # 它会对待分类文本打分而标签可以由你任意指定 classifier pipeline(modelfacebook/bart-large-mnli) classifier( I have a problem with my iphone that needs to be resolved asap!!, candidate_labels[urgent, not urgent, phone, tablet, computer], ) {sequence: I have a problem with my iphone that needs to be resolved asap!!, labels: [urgent, phone, computer, not urgent, tablet], scores: [0.504, 0.479, 0.013, 0.003, 0.002]}模型把这条iPhone 需要尽快处理的文本以 0.504 的分数判为urgent紧急以 0.479 判为phone其余标签分数很低。无需微调、无需固定标签集这就是零样本分类的价值所在。facebook/bart-large-mnli也正是注册表中zero-shot-classification的默认模型。八、多模态 Pipeline视觉问答VQApipeline支持跨模态任务。例如视觉问答VQA同时接收文本问题和图像两种输入。图像可以是 URL也可以是本地路径。下面用impira/layoutlm-document-qa对一张发票图片提问from transformers import pipeline vqa pipeline(modelimpira/layoutlm-document-qa) output vqa( imagehttps://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png, questionWhat is the invoice number?, ) output[0][score] round(output[0][score], 3) output [{score: 0.425, answer: us-001, start: 16, end: 16}]模型从发票图像中直接定位并回答了发票编号是 us-001。document-question-answering同样出现在注册表中默认模型正是impira/layoutlm-document-qa见 src/transformers/pipelines/init.py。运行前提执行上述示例除 Transformers 外还需安装pytesseract文档问答依赖 OCR 提取图像文本sudo apt install -y tesseract-ocr pip install pytesseract九、在超大模型上运行 Pipeline Accelerate 与量化借助 Accelerate你可以轻松让pipeline跑在单卡装不下的大模型上。首先确保已安装pip install accelerate然后使用device_mapauto加载模型让 Accelerate 自动把权重分散到可用设备上。下面的例子使用facebook/opt-1.3b# pip install accelerate import torch from transformers import pipeline pipe pipeline(modelfacebook/opt-1.3b, dtypetorch.bfloat16, device_mapauto) output pipe(This is a cool example!, do_sampleTrue, top_p0.95)这里dtypetorch.bfloat16让模型以半精度加载以节省显存pipeline工厂函数签名中dtype参数默认为auto见 src/transformers/pipelines/init.pydo_sample与top_p则控制文本生成的采样策略。更进一步你还可以传入8-bit 量化模型。安装bitsandbytes后通过model_kwargs传入quantization_config即可# pip install accelerate bitsandbytes import torch from transformers import pipeline, BitsAndBytesConfig pipe pipeline(modelfacebook/opt-1.3b, device_mapauto, model_kwargs{quantization_config: BitsAndBytesConfig(load_in_8bitTrue)}) output pipe(This is a cool example!, do_sampleTrue, top_p0.95)model_kwargs会被原样透传给底层的模型加载函数见 src/transformers/pipelines/base.py其中会为 kwargs 打上_from_pipeline标记并合并进AutoModel.from_pretrained的调用参数。上面例子中的facebook/opt-1.3b可以替换为任意模型标识符。十、用 Gradio 一行代码搭建 Web 演示Hugging Face 支持加载 BLOOM 等超大模型而 pipeline 在 Gradio 中开箱即用——Gradio 是一个让开发者快速构建美观、易用的机器学习 Web 应用的库。先安装pip install gradio然后调用 Gradio 的Interface.from_pipeline用一行代码把图像分类 pipeline或其他任意 pipeline变成一个浏览器中可拖拽上传、即传即用的交互界面from transformers import pipeline import gradio as gr pipe pipeline(image-classification, modelgoogle/vit-base-patch16-224) gr.Interface.from_pipeline(pipe).launch()默认情况下演示运行在本地服务器上。若想分享给他人可在launch()中设置shareTrue生成一个临时公网链接若想获得永久链接则可以把它部署到 Hugging Face Spaces。结语与延伸阅读从本文可以总结出pipeline的三大价值零门槛不熟悉任何模态的底层模型代码也能直接做推理任务注册表src/transformers/pipelines/init.py自动挑选默认模型与预处理类易切换换模型只需改model标识符device、batch_size、任务特定参数在创建与调用两个层面都灵活可控可扩展既能通过迭代器/KeyDataset跑大数据集也能配合accelerate、bitsandbytes跑大模型还能一键接入 Gradio 与 Web 服务。若想继续深入可以阅读同目录下的 Quicktour 教程、任务总览以及英文版的 Pipeline 网络服务指南各任务 pipeline 类的完整参数列表则可在 src/transformers/pipelines 目录下按任务逐一查阅。【免费下载链接】transformers 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.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考