Skill Tracer
Skills › Scientific Agent Skills › transformers › pipelines.md

pipelines.md

325 lines · skills/transformers/references/pipelines.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Pipeline API Reference
2
3Targets Transformers 5.18.0. Pretrained examples below are illustrative; the local regression suite checks pipeline behavior with small random models. See [review evidence](review.md).
4

Pipeline API Reference

Targets Transformers 5.18.0. Pretrained examples below are illustrative; the local regression suite checks pipeline behavior with small random models. See review evidence.

Raw lines 1 to 4
5## Overview
6
7Pipelines provide the simplest way to use pre-trained models for inference. They abstract away tokenization, model loading, and post-processing, offering a unified interface for dozens of tasks.
8

Overview

Pipelines provide the simplest way to use pre-trained models for inference. They abstract away tokenization, model loading, and post-processing, offering a unified interface for dozens of tasks.

Raw lines 5 to 8
9## Basic Usage
11Create a pipeline by specifying a task:
13```python
14from transformers import pipeline
16# Explicit checkpoints avoid changing task defaults. Pin revision to a reviewed commit for research.
17pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
18result = pipe("This is great!")
19```
21Or specify a model:
23```python
24pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
25```

Basic Usage

Create a pipeline by specifying a task:

from transformers import pipeline

# Explicit checkpoints avoid changing task defaults. Pin revision to a reviewed commit for research.
pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
result = pipe("This is great!")

Or specify a model:

pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
Raw lines 9 to 26
27## Supported Tasks

Supported Tasks

Raw lines 27 to 28
29### Natural Language Processing
31**text-generation**: Generate text continuations
32```python
33generator = pipeline("text-generation", model="openai-community/gpt2")
34output = generator("Once upon a time", max_new_tokens=50, do_sample=True, num_return_sequences=2)
35```
37**text-classification**: Classify text into categories
38```python
39classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
40result = classifier("I love this product!") # Returns label and score
41```
43**token-classification**: Label individual tokens (NER, POS tagging)
44```python
45ner = pipeline("token-classification", model="dslim/bert-base-NER")
46entities = ner("Hugging Face is based in New York City")
47```
49**Extractive question answering:** the old `question-answering` pipeline is removed. For extractive semantics, load `AutoModelForQuestionAnswering`, tokenize question/context with `truncation="only_second"`, and decode valid context spans from start/end logits using offset and sequence-ID mappings. Long documents require overlapping windows and alignment back to the original text; independent argmax can produce an invalid span. Generative QA via a chat model does not supply equivalent calibrated answer spans.
51**fill-mask**: Predict masked tokens
52```python
53unmasker = pipeline("fill-mask", model="google-bert/bert-base-uncased")
54result = unmasker("Paris is the [MASK] of France")
55```
57**Summarization and translation:** `summarization`, `translation*`, and `text2text-generation` pipelines are removed. Existing seq2seq checkpoints still use `AutoModelForSeq2SeqLM.generate()` (see [generation](generation.md)). For instruction-based generation, use a chat checkpoint:
59```python
60summarizer = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")
61messages = [{"role": "user", "content": "Summarize this text: [replace with the source text]"}]
62summary = summarizer(messages, max_new_tokens=128, do_sample=False)
63print(summary[0]["generated_text"][-1]["content"])
64```
66**zero-shot-classification**: Classify without training data
67```python
68classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
69result = classifier(
70 "This is a course about Python programming",
71 candidate_labels=["education", "politics", "business"]
73```
75**sentiment-analysis**: Alias for text-classification focused on sentiment
76```python
77sentiment = pipeline("sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
78result = sentiment("This product exceeded my expectations!")
79```

Natural Language Processing

text-generation: Generate text continuations

generator = pipeline("text-generation", model="openai-community/gpt2")
output = generator("Once upon a time", max_new_tokens=50, do_sample=True, num_return_sequences=2)

text-classification: Classify text into categories

classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
result = classifier("I love this product!")  # Returns label and score

token-classification: Label individual tokens (NER, POS tagging)

ner = pipeline("token-classification", model="dslim/bert-base-NER")
entities = ner("Hugging Face is based in New York City")

Extractive question answering: the old question-answering pipeline is removed. For extractive semantics, load AutoModelForQuestionAnswering, tokenize question/context with truncation="only_second", and decode valid context spans from start/end logits using offset and sequence-ID mappings. Long documents require overlapping windows and alignment back to the original text; independent argmax can produce an invalid span. Generative QA via a chat model does not supply equivalent calibrated answer spans.

fill-mask: Predict masked tokens

unmasker = pipeline("fill-mask", model="google-bert/bert-base-uncased")
result = unmasker("Paris is the [MASK] of France")

Summarization and translation: summarization, translation*, and text2text-generation pipelines are removed. Existing seq2seq checkpoints still use AutoModelForSeq2SeqLM.generate() (see generation). For instruction-based generation, use a chat checkpoint:

summarizer = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")
messages = [{"role": "user", "content": "Summarize this text: [replace with the source text]"}]
summary = summarizer(messages, max_new_tokens=128, do_sample=False)
print(summary[0]["generated_text"][-1]["content"])

zero-shot-classification: Classify without training data

classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
result = classifier(
    "This is a course about Python programming",
    candidate_labels=["education", "politics", "business"]
)

sentiment-analysis: Alias for text-classification focused on sentiment

sentiment = pipeline("sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
result = sentiment("This product exceeded my expectations!")
Raw lines 29 to 80
81### Computer Vision
83**image-classification**: Classify images
84```python
85classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
86result = classifier("path/to/image.jpg")
87# Or use PIL Image or URL
88from PIL import Image
89result = classifier(Image.open("image.jpg"))
90```
92**object-detection**: Detect objects in images
93```python
94detector = pipeline("object-detection", model="facebook/detr-resnet-50")
95results = detector("image.jpg") # Returns bounding boxes and labels
96```
98**image-segmentation**: Segment images
99```python
100segmenter = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic")
101segments = segmenter("image.jpg")
102```
104**depth-estimation**: Estimate depth from images
105```python
106depth = pipeline("depth-estimation", model="Intel/dpt-large")
107result = depth("image.jpg")
108```
110For DPT, use `predicted_depth` for the raw tensor. The `depth` PIL output is a per-image min-max visualization, not metric distance; constant depth can make that normalization degenerate. Preserve preprocessing/resolution and do not infer meters without a metric-depth model/calibration.
112**zero-shot-image-classification**: Classify images without training
113```python
114classifier = pipeline("zero-shot-image-classification", model="openai/clip-vit-base-patch32")
115result = classifier("image.jpg", candidate_labels=["cat", "dog", "bird"])
116```
118CLIP scores are normalized over the supplied candidate prompts; changing that set changes scores. They are not an open-world detection probability.

Computer Vision

image-classification: Classify images

classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
result = classifier("path/to/image.jpg")
# Or use PIL Image or URL
from PIL import Image
result = classifier(Image.open("image.jpg"))

object-detection: Detect objects in images

detector = pipeline("object-detection", model="facebook/detr-resnet-50")
results = detector("image.jpg")  # Returns bounding boxes and labels

image-segmentation: Segment images

segmenter = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic")
segments = segmenter("image.jpg")

depth-estimation: Estimate depth from images

depth = pipeline("depth-estimation", model="Intel/dpt-large")
result = depth("image.jpg")

For DPT, use predicted_depth for the raw tensor. The depth PIL output is a per-image min-max visualization, not metric distance; constant depth can make that normalization degenerate. Preserve preprocessing/resolution and do not infer meters without a metric-depth model/calibration.

zero-shot-image-classification: Classify images without training

classifier = pipeline("zero-shot-image-classification", model="openai/clip-vit-base-patch32")
result = classifier("image.jpg", candidate_labels=["cat", "dog", "bird"])

CLIP scores are normalized over the supplied candidate prompts; changing that set changes scores. They are not an open-world detection probability.

Raw lines 81 to 119
120### Audio
122**automatic-speech-recognition**: Transcribe speech
123```python
124asr = pipeline("automatic-speech-recognition", model="openai/whisper-base")
125text = asr("audio.mp3")
126```
128**audio-classification**: Classify audio
129```python
130classifier = pipeline("audio-classification", model="MIT/ast-finetuned-audioset-10-10-0.4593")
131result = classifier("audio.wav", function_to_apply="sigmoid", top_k=5)
132```
134AudioSet AST predicts potentially simultaneous events: use independent sigmoid scores. The audio-classification pipeline otherwise defaults to softmax, which forces competition between labels. Match postprocessing to the checkpoint's training objective; neither score is automatically calibrated.
136**text-to-speech**: Generate speech from text (with specific models)
137```python
138tts = pipeline("text-to-speech", model="facebook/mms-tts-eng")
139audio = tts("Hello, this is a test")
140# audio["audio"] is a waveform array; audio["sampling_rate"] supplies its rate.
141```

Audio

automatic-speech-recognition: Transcribe speech

asr = pipeline("automatic-speech-recognition", model="openai/whisper-base")
text = asr("audio.mp3")

audio-classification: Classify audio

classifier = pipeline("audio-classification", model="MIT/ast-finetuned-audioset-10-10-0.4593")
result = classifier("audio.wav", function_to_apply="sigmoid", top_k=5)

AudioSet AST predicts potentially simultaneous events: use independent sigmoid scores. The audio-classification pipeline otherwise defaults to softmax, which forces competition between labels. Match postprocessing to the checkpoint's training objective; neither score is automatically calibrated.

text-to-speech: Generate speech from text (with specific models)

tts = pipeline("text-to-speech", model="facebook/mms-tts-eng")
audio = tts("Hello, this is a test")
# audio["audio"] is a waveform array; audio["sampling_rate"] supplies its rate.
Raw lines 120 to 142
143### Multimodal
145**image-text-to-text**: Generative captions or visual questions. The former `visual-question-answering` and `image-to-text` pipelines are removed. Put images inside message content; do not pass a separate images argument alongside chats.
147```python
148captioner = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Instruct")
149messages = [{"role": "user", "content": [
150 {"type": "image", "image": "image.jpg"},
151 {"type": "text", "text": "Describe this image."},
152]}]
153caption = captioner(messages, max_new_tokens=64)
154```
156**document-question-answering**: Answer questions about documents
157```python
158doc_qa = pipeline("document-question-answering", model="impira/layoutlm-document-qa")
159result = doc_qa(image="document.png", question="What is the invoice number?")
160```
162LayoutLM document QA requires OCR dependencies (`pytesseract` and a Tesseract executable) unless supplying supported precomputed word/box inputs; OCR boxes and image coordinates must agree. A local image file alone is not a preprocessed document.

Multimodal

image-text-to-text: Generative captions or visual questions. The former visual-question-answering and image-to-text pipelines are removed. Put images inside message content; do not pass a separate images argument alongside chats.

captioner = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Instruct")
messages = [{"role": "user", "content": [
    {"type": "image", "image": "image.jpg"},
    {"type": "text", "text": "Describe this image."},
]}]
caption = captioner(messages, max_new_tokens=64)

document-question-answering: Answer questions about documents

doc_qa = pipeline("document-question-answering", model="impira/layoutlm-document-qa")
result = doc_qa(image="document.png", question="What is the invoice number?")

LayoutLM document QA requires OCR dependencies (pytesseract and a Tesseract executable) unless supplying supported precomputed word/box inputs; OCR boxes and image coordinates must agree. A local image file alone is not a preprocessed document.

Raw lines 143 to 163
164## Pipeline Parameters

Pipeline Parameters

Raw lines 164 to 165
166### Common Parameters
168**model**: Model identifier or path
169```python
170pipe = pipeline("task", model="model-id")
171```
173**device**: CPU/device string, `torch.device`, or accelerator index (-1 means CPU). Never combine an explicit `device` with Accelerate `device_map` dispatch.
174```python
175pipe = pipeline("task", device=0) # Use first GPU
176```
178**device_map**: Automatic device allocation for large models
179```python
180pipe = pipeline("task", model="large-model", device_map="auto")
181```
183**dtype**: Model precision (reduces memory; `torch_dtype` is deprecated but still accepted)
184```python
185import torch
186pipe = pipeline("task", dtype=torch.float16)
187```
189**batch_size**: Process multiple inputs at once
190```python
191pipe = pipeline("task", batch_size=8)
192results = pipe(["text1", "text2", "text3"])
193```
195**Backend**: Transformers v5 pipelines use PyTorch only (TensorFlow/JAX backends were removed in v5).

Common Parameters

model: Model identifier or path

pipe = pipeline("task", model="model-id")

device: CPU/device string, torch.device, or accelerator index (-1 means CPU). Never combine an explicit device with Accelerate device_map dispatch.

pipe = pipeline("task", device=0)  # Use first GPU

device_map: Automatic device allocation for large models

pipe = pipeline("task", model="large-model", device_map="auto")

dtype: Model precision (reduces memory; torch_dtype is deprecated but still accepted)

import torch
pipe = pipeline("task", dtype=torch.float16)

batch_size: Process multiple inputs at once

pipe = pipeline("task", batch_size=8)
results = pipe(["text1", "text2", "text3"])

Backend: Transformers v5 pipelines use PyTorch only (TensorFlow/JAX backends were removed in v5).

Raw lines 166 to 196
Starts an agent dispatch :173
197## Batch Processing
199Process multiple inputs efficiently:
201```python
202classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
203texts = ["Great product!", "Terrible experience", "Just okay"]
204results = classifier(texts)
205```
207For large datasets, use generators or KeyDataset:
209```python
210from transformers.pipelines.pt_utils import KeyDataset
211import datasets
213dataset = datasets.load_dataset("dataset-name", split="test")
214pipe = pipeline("task", device=0)
216for output in pipe(KeyDataset(dataset, "text")):
217 print(output)
218```

Batch Processing

Process multiple inputs efficiently:

classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
texts = ["Great product!", "Terrible experience", "Just okay"]
results = classifier(texts)

For large datasets, use generators or KeyDataset:

from transformers.pipelines.pt_utils import KeyDataset
import datasets

dataset = datasets.load_dataset("dataset-name", split="test")
pipe = pipeline("task", device=0)

for output in pipe(KeyDataset(dataset, "text")):
    print(output)
Raw lines 197 to 219
220## Performance Optimization

Performance Optimization

Raw lines 220 to 221
222### GPU Acceleration
224Always specify device for GPU usage:
225```python
226pipe = pipeline("task", device=0)
227```

GPU Acceleration

Always specify device for GPU usage:

pipe = pipeline("task", device=0)
Raw lines 222 to 228
229### Mixed Precision
231Half precision may reduce memory and improve speed on supported hardware; measure accuracy, latency, and throughput for the actual workload:
232```python
233import torch
234pipe = pipeline("task", dtype=torch.float16, device=0)
235```

Mixed Precision

Half precision may reduce memory and improve speed on supported hardware; measure accuracy, latency, and throughput for the actual workload:

import torch
pipe = pipeline("task", dtype=torch.float16, device=0)
Raw lines 229 to 236
237### Batching Guidelines
239- **CPU**: Usually skip batching
240- **GPU with variable lengths**: May reduce efficiency
241- **GPU with similar lengths**: Significant speedup
242- **Real-time applications**: Skip batching (increases latency)
244```python
245# Good for throughput
246pipe = pipeline("task", batch_size=32, device=0)
247results = pipe(list_of_texts)
248```

Batching Guidelines

  • CPU: Usually skip batching
  • GPU with variable lengths: May reduce efficiency
  • GPU with similar lengths: Significant speedup
  • Real-time applications: Skip batching (increases latency)
# Good for throughput
pipe = pipeline("task", batch_size=32, device=0)
results = pipe(list_of_texts)
Raw lines 237 to 249
250### Streaming Output
252For text generation, stream tokens as they're generated:
254```python
255from transformers import AutoTokenizer, TextStreamer, pipeline
257tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
258streamer = TextStreamer(tokenizer)
259generator = pipeline("text-generation", model="openai-community/gpt2", streamer=streamer)
260generator("The future of AI", max_new_tokens=100)
261```

Streaming Output

For text generation, stream tokens as they're generated:

from transformers import AutoTokenizer, TextStreamer, pipeline

tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
streamer = TextStreamer(tokenizer)
generator = pipeline("text-generation", model="openai-community/gpt2", streamer=streamer)
generator("The future of AI", max_new_tokens=100)
Raw lines 250 to 262
263## Custom Pipeline Configuration
265Specify tokenizer and model separately:
267```python
268from transformers import AutoTokenizer, AutoModelForSequenceClassification
270tokenizer = AutoTokenizer.from_pretrained("model-id")
271model = AutoModelForSequenceClassification.from_pretrained("model-id")
272pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
273```
275Use custom pipeline classes:
277```python
278from transformers import TextClassificationPipeline
280class CustomPipeline(TextClassificationPipeline):
281 def postprocess(self, model_outputs, **kwargs):
282 # Custom post-processing
283 return super().postprocess(model_outputs, **kwargs)
285pipe = pipeline("text-classification", model="model-id", pipeline_class=CustomPipeline)
286```

Custom Pipeline Configuration

Specify tokenizer and model separately:

from transformers import AutoTokenizer, AutoModelForSequenceClassification

tokenizer = AutoTokenizer.from_pretrained("model-id")
model = AutoModelForSequenceClassification.from_pretrained("model-id")
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)

Use custom pipeline classes:

from transformers import TextClassificationPipeline

class CustomPipeline(TextClassificationPipeline):
    def postprocess(self, model_outputs, **kwargs):
        # Custom post-processing
        return super().postprocess(model_outputs, **kwargs)

pipe = pipeline("text-classification", model="model-id", pipeline_class=CustomPipeline)
Raw lines 263 to 287
288## Input Formats
290Pipelines accept various input types:
292**Text tasks**: Strings or lists of strings
293```python
294pipe("single text")
295pipe(["text1", "text2"])
296```
298**Image tasks**: URLs, file paths, or PIL Images. Convert NumPy arrays to a correctly scaled/color-ordered PIL image; arbitrary arrays are not universally accepted.
299```python
300pipe("https://example.com/image.jpg")
301pipe("local/path/image.png")
302from PIL import Image
303pipe(Image.open("image.jpg").convert("RGB"))
304# For a uint8 HWC RGB NumPy array:
305pipe(Image.fromarray(rgb_array))
306```
308**Audio tasks**: Encoded file paths/bytes require FFmpeg for relevant pipelines. A raw NumPy waveform must already have the expected sampling rate; use a sampling-rate dictionary where the task supports it.
309```python
310pipe("audio.mp3")
311pipe({"array": audio_array, "sampling_rate": actual_sampling_rate})
312```

Input Formats

Pipelines accept various input types:

Text tasks: Strings or lists of strings

pipe("single text")
pipe(["text1", "text2"])

Image tasks: URLs, file paths, or PIL Images. Convert NumPy arrays to a correctly scaled/color-ordered PIL image; arbitrary arrays are not universally accepted.

pipe("https://example.com/image.jpg")
pipe("local/path/image.png")
from PIL import Image
pipe(Image.open("image.jpg").convert("RGB"))
# For a uint8 HWC RGB NumPy array:
pipe(Image.fromarray(rgb_array))

Audio tasks: Encoded file paths/bytes require FFmpeg for relevant pipelines. A raw NumPy waveform must already have the expected sampling rate; use a sampling-rate dictionary where the task supports it.

pipe("audio.mp3")
pipe({"array": audio_array, "sampling_rate": actual_sampling_rate})
Raw lines 288 to 313
314## Error Handling
316For GPU memory errors, reduce the actual batch/context/token budget or recreate the same checkpoint on a supported device. Catch `torch.OutOfMemoryError` only when providing a real retry path; do not silently swap to a task default model. Re-raise unexpected exceptions. Missing files can mean a wrong revision, incomplete local snapshot, missing permissions, or an incompatible task head; inspect the underlying error.

Error Handling

For GPU memory errors, reduce the actual batch/context/token budget or recreate the same checkpoint on a supported device. Catch torch.OutOfMemoryError only when providing a real retry path; do not silently swap to a task default model. Re-raise unexpected exceptions. Missing files can mean a wrong revision, incomplete local snapshot, missing permissions, or an incompatible task head; inspect the underlying error.

Raw lines 314 to 317
318## Best Practices
3201. **Use pipelines for prototyping**: Fast iteration without boilerplate
3212. **Specify models explicitly**: Default models may change
3223. **Enable GPU when available**: Significant speedup
3234. **Use batching for throughput**: When processing many inputs
3245. **Consider memory usage**: Use float16 or smaller models for large batches
3256. **Cache models locally**: Avoid repeated downloads

Best Practices

  1. Use pipelines for prototyping: Fast iteration without boilerplate
  2. Specify models explicitly: Default models may change
  3. Enable GPU when available: Significant speedup
  4. Use batching for throughput: When processing many inputs
  5. Consider memory usage: Use float16 or smaller models for large batches
  6. Cache models locally: Avoid repeated downloads
Raw lines 318 to 325