概要

Transformer功能讲解之Pipeline

在 Hugging Face 的 Transformers 库中,pipeline是一个非常实用的高级 API,它封装了模型加载、预处理、推理和后处理的完整流程,让开发者可以用极少的代码实现各种 NLP 任务。它会自动完成以下工作:

  1. 选择预训练模型:默认情况下,会加载适合文本分类任务的预训练模型(通常是distilbert-base-uncased-finetuned-sst-2-english)
  2. 加载分词器:自动匹配模型对应的分词器,用于将文本转换为模型可理解的格式
  3. 处理输入输出:你只需要向管道输入原始文本,它就会返回分类结果(如情感分析中的 “正面” 或 “负面” 及其置信度)

技术细节

transformers.pipelines的任务列表

from tabulate import tabulate
import math, itertools

keys = list(SUPPORTED_TASKS.keys())
cols = 4
rows = math.ceil(len(keys) / cols)
table = [keys[i*cols:(i+1)*cols] for i in range(rows)]
print(tabulate(table, tablefmt="rounded_grid"))
--------------------------------------------------------------------------------------
输出结果:
╭────────────────────────────────┬────────────────────────────────┬──────────────────────┬──────────────────────────╮
│ audio-classification           │ automatic-speech-recognition   │ text-to-audio        │ feature-extraction       │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ text-classification            │ token-classification           │ question-answering   │ table-question-answering │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ visual-question-answering      │ document-question-answering    │ fill-mask            │ summarization            │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ translation                    │ text2text-generation           │ text-generation      │ zero-shot-classification │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ zero-shot-image-classification │ zero-shot-audio-classification │ image-classification │ image-feature-extraction │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ image-segmentation             │ image-to-text                  │ image-text-to-text   │ object-detection         │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ zero-shot-object-detection     │ depth-estimation               │ video-classification │ mask-generation          │
├────────────────────────────────┼────────────────────────────────┼──────────────────────┼──────────────────────────┤
│ image-to-image                 │                                │                      │                          │
╰────────────────────────────────┴────────────────────────────────┴──────────────────────┴──────────────────────────╯

Transformers库支持的任务类型可分为以下几类:

  1. 文本处理类:

    • text-classification:文本分类(如情感分析)
    • token-classification:命名实体识别
    • fill-mask:完形填空
    • summarization:文本摘要
  2. 问答类:

    • question-answering:阅读理解
    • table-question-answering:表格问答
    • document-question-answering:文档问答
  3. 生成类:

    • text-generation:文本生成
    • text2text-generation:文本到文本生成
    • translation:机器翻译
  4. 多模态类:

    • image-to-text:图像描述生成
    • text-to-image:文生图
    • image-classification:图像分类
  5. 语音类:

    • automatic-speech-recognition:语音识别
    • text-to-speech:语音合成
    • audio-classification:音频分类

pipeline 的参数

pipe = pipeline(
        task="text-classification",   # 任务名
        model="bert-base-chinese",    # 模型 repo 或路径
        tokenizer=None,               # 可单独指定 tokenizer
        device=0,                     # GPU 编号;-1 为 CPU
        framework="pt",               # "pt" 或 "tf"
        batch_size=1,                 # 推理 batch
        max_length=512,               # 传给 tokenizer 的 max_length
        truncation=True,
        top_k=1,                      # 下游后处理参数(任务相关)
        return_all_scores=False,
        use_fast=True,                # 是否用 fast tokenizer
        torch_dtype="auto",           # torch.float16 等
        model_kwargs={},              # 透传给 AutoModel.from_pretrained
        **kwargs
)

pipeline参数深入解析

它们会在内部被拆成 3 组:
加载期参数:

  • model:支持HuggingFace模型ID或本地路径
  • device:支持GPU加速(device=0表示第一块GPU)
  • framework:可选择PyTorch(“pt”)或TensorFlow(“tf”)
  • model_kwargs:可传递模型加载参数如cache_dir

预处理参数:

  • max_length:控制输入序列最大长度
  • padding:填充策略(如"max_length")
  • truncation:是否截断超长文本
  • return_tensors:返回张量格式(“pt"或"tf”)

后处理参数:

  • text-generation:
    • temperature:控制生成随机性
    • top_k:top-k采样
    • max_new_tokens:最大生成长度
  • text-classification:
    • top_k:返回前k个结果
    • function_to_apply:分数转换函数

Pipeline工作流程详解

  1. 初始化阶段:

    • 根据task参数确定任务类型
    • 加载模型配置和分词器
    • 初始化模型权重
  2. 预处理阶段:

    • 文本分词和数值化
    • 添加特殊标记(如[CLS]、[SEP])
    • 生成attention mask
    • 处理成batch形式
  3. 推理阶段:

    • 将输入张量送入模型
    • 获取模型输出logits
    • 计算attention权重(可选)
  4. 后处理阶段:

    • 应用softmax等激活函数
    • 解码输出为可读格式
    • 对结果进行排序和过滤
    • 格式化为标准输出结构

Pipeline结构示意图

pipeline(task, model, tokenizer, device, ...)
   │
   ├─1) 加载期
   │   ├─ AutoModel.from_pretrained(model, **model_kwargs)
   │   └─ AutoTokenizer.from_pretrained(tokenizer or model, use_fast=..., **tok_kwargs)
   │
   ├─2) 每次 __call__
   │   ├─ preprocess(inputs, **tok_kwargs)
   │   │   └─ tokenizer(text, max_length=..., truncation=..., padding=...)
   │   ├─ _forward(model_inputs)
   │   │   └─ model(**model_inputs)
   │   └─ postprocess(model_outputs, **task_kwargs)
   │       └─ 任务专属解码
   │
   └─3) 返回 List[Dict] / str / ...

任务(task)的默认配置格式

for k, v in SUPPORTED_TASKS['audio-classification'].items():
    print(k, v)
    
输出结果:
impl <class 'transformers.pipelines.audio_classification.AudioClassificationPipeline'>
tf ()
pt (<class 'transformers.models.auto.modeling_auto.AutoModelForAudioClassification'>,)
default {'model': {'pt': ('superb/wav2vec2-base-superb-ks', '372e048')}}
type audio
  • 键名(audio-classification):在 pipeline(“audio-classification”) 里填的那个字符串。

  • impl:implementation 的缩写,表示“具体实现类”。该调用的类是 AudioClassificationPipeline。

  • tf / pt: 该任务支持的 TensorFlow 与 PyTorch 模型基类(() 代表没有官方 TF 支持)。

  • default: 如果你什么都不指定,pipeline 会默认加载的模型/配置。
    (‘superb/wav2vec2-base-superb-ks’, ‘372e048’) 就是 repo 名 + 该 repo 里某个具体 commit 的 revision。

  • type: type 只是一个“标签”,表示任务的大类,帮助前端或 Hub 做 UI 分类。取值为:text | image | audio | video | multimodal

常见的任务(task)以及输出示例

任务名(task=) 示例输出
"sentiment-analysis" [{'label': 'POS', 'score':…}]
"text-generation" [{'generated_text': '...'}]
"question-answering" {'answer': '北京', 'score':…}
"fill-mask" [{'token_str': '学习', ...}]
"translation_en_to_zh" [{'translation_text': '...'}]
"automatic-speech-recognition" {'text': '语音转文字'}

Pipeline的创建与使用方式

from transformers import pipeline, QuestionAnsweringPipeline
# 根据任务类型直接创建Pipeline, 默认都是英文的模型
pipe = pipeline("text-classification")
print(pipe(["very good!", "vary bad!"]))

输出结果:
[{'label': 'POSITIVE', 'score': 0.9998525381088257},
 {'label': 'NEGATIVE', 'score': 0.9991207718849182}]

小结

Hugging Face Transformers 库的pipeline是连接预训练模型与实际 NLP 任务的 “桥梁”,其核心价值在于简化流程、降低门槛。通过封装模型加载、预处理、推理和后处理的全链路逻辑,开发者无需深入了解模型细节,即可用极少的代码实现文本分类、问答、生成、翻译等数十种任务。
从功能上看,pipeline的灵活性体现在:支持自定义模型与分词器、适配 PyTorch/TensorFlow 框架、支持 GPU 加速与批量处理,同时通过丰富的参数(如max_length、top_k)可精细控制任务流程。无论是快速验证想法、构建原型,还是部署生产环境,pipeline都能显著提升开发效率。
此外,其对多模态任务(如图文交互、语音处理)的支持,进一步扩展了应用场景,使其成为 NLP 及跨模态领域的实用工具。掌握pipeline的使用,能帮助开发者更高效地利用海量预训练模型,聚焦于业务逻辑而非底层实现。

Logo

一站式 AI 云服务平台

更多推荐