Pipeline 推理

Pipeline 是官方推荐的高层推理入口:指定任务名与模型 ID,它会组装 Preprocessor + 模型 + 后处理。适合探索 Hub 上的检查点;要抠 generate() 或训练循环,再往下层走。


常用任务

task输入典型 ungated 模型
text-classification字符串distilbert/distilbert-base-uncased-finetuned-sst-2-english
token-classification字符串(NER)dslim/bert-base-NER(使用前读模型卡)
text-generation提示词distilbert/distilgpt2Qwen/Qwen2.5-0.5B-Instruct
summarization长文本选小 T5 / DistilBART,注意许可
automatic-speech-recognition音频路径 / 数组openai/whisper-tiny
image-classification图像路径 / URLgoogle/vit-base-patch16-224
zero-shot-classification文本 + 候选标签小 MNLI 模型

完整列表见 Pipeline 文档生产环境请写死 model=,不要依赖「未指定时的默认模型」。


文本:分类

from transformers import pipeline

clf = pipeline(
    "text-classification",
    model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)
print(clf(["A thoughtful and funny script.", "Waste of time."]))

传入列表即批处理。返回每条样本的 labelscore


文本:生成

from transformers import pipeline

gen = pipeline(
    "text-generation",
    model="distilbert/distilgpt2",
    max_new_tokens=32,
    do_sample=True,
    temperature=0.8,
)
print(gen("The secret of a good tutorial is")[0]["generated_text"])

max_new_tokens 限制新生成长度,避免默认真值过短或失控续写。采样与贪婪的对比见 文本生成

中文指令可用 Qwen/Qwen2.5-0.5B-Instruct,并加上 device_map="auto"dtype="auto"。Hub 上的 DeepSeek Instruct 同样适合中文场景,先确认 ungated 再下载。


视觉:图像分类

from transformers import pipeline

vision = pipeline(
    "image-classification",
    model="google/vit-base-patch16-224",
)
# 换成本地文件或 Hub 上的示例图
print(vision("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"))

内部使用 ImageProcessor(也是 Preprocessor 的一种),把像素归一化成模型张量。


音频:Whisper-tiny

from transformers import pipeline

asr = pipeline(
    "automatic-speech-recognition",
    model="openai/whisper-tiny",
)
# asr("path/to/short.wav")

whisper-tiny 体积小、无门控,适合验证麦克风或 WAV 流程。长音频、多语言再换 whisper-small 及以上,并关注显存。


Pipeline 内部在做什么

原始输入  →  Preprocessor.encode / preprocess
          →  PreTrainedModel.forward 或 generate()
          →  后处理(id→token、softmax、时间戳)

等价于你自己写 AutoTokenizer + AutoModel*。Pipeline 省样板;自定义 padding、beam search、多轮 chat template 时,用下一章的 AutoClass 更合适。

常用参数:

参数作用
modelHub ID 或本地目录
devicecpu / cuda:0
device_map / dtype大模型分卡与精度(生成任务常用)
batch_size列表输入时的批大小
return_all_scores分类时返回全部标签分数

选型提醒

  • 只要本地闲聊:本站 Ollama 更简单。
  • 要对齐论文指标、换头、接自己的 DataLoader:留在 Transformers。
  • 张量形状与 to(device):本站 PyTorch 教程

下一步

评论