In a Transformers pipeline() batch job, when does setting batch_size speed things up, and when does it slow them down or crash?
answer
- off unless you ask
- lists, datasets and generators only
- the longest item sets the shape
- latency and CPU say no
- measure, then push to OOM
basics
~20 sA Transformers pipeline batches only list, Dataset or generator input with batch_size above its default of 1. It helps GPU throughput on similar-length inputs; on CPU, latency-bound paths or length outliers, padding makes it slower or runs out of memory.
solid answer
~40 s`batch_size` defaults to 1, meaning no batching, and it only takes effect when the input is a list, a PyTorch `Dataset` (for example `KeyDataset` over a Datasets column) or a generator; calling the pipeline once per string in a loop never batches, and after more than ten such calls on CUDA it warns you to use a dataset. With `batch_size` above 1 the pipeline pads every item in a batch to the batch's longest sequence, so one long outlier turns a `[64, 4]` batch into `[64, 400]`, slower than no batching or a CUDA out-of-memory error. The documented rules: measure on your own data and hardware; don't batch for latency-bound serving or on CPU; on a GPU with regular lengths, raise it until you hit OOM, and handle OOM gracefully.
code
python · 15 linesfrom datasets import load_dataset
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
ds = load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised")
clf = pipeline(
"text-classification",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
device=0,
)
# Streamed and batched; truncation caps any single long review
results = []
for out in clf(KeyDataset(ds, "text"), batch_size=32, truncation=True):
results.append(out)go deeper
Recall that batch_size defaults to 1 and that batching needs a list, dataset or generator as input instead of one string per call.
Explain padding to the longest item in each batch, why an outlier slows or crashes a batch, and why chunk pipelines count forward passes rather than inputs.
Show the operating discipline: measure several sizes on real data, keep latency-bound and CPU paths unbatched, truncate long inputs, and build OOM recovery into the job.
Decide where batching belongs across a platform: offline GPU scoring tuned for throughput versus online paths tuned for latency, and whether length-grouping input is worth the pipeline complexity.
## What `batch_size` controls A Hugging Face Transformers pipeline normally processes one input at a time: pre-process, forward pass, post-process. Setting **`batch_size`**, either at construction (`pipeline(..., batch_size=16)`) or per call (`pipe(inputs, batch_size=16)`), makes it group several pre-processed inputs into one forward pass. The default is **1, which means batching is off**, because the library cannot know whether batching will help your workload. ## Which inputs can be batched Batching only happens on the pipeline's **streaming path**, which is taken when the input is: - a **list**, consumed eagerly and returning a list of results; - a PyTorch **`Dataset`**, typically `KeyDataset(dataset, "text")` from `transformers.pipelines.pt_utils`, which yields one column of a Datasets dataset and returns a lazy iterator; - a **generator**, also returning a lazy iterator, so the input is never fully materialised. A single string runs on its own whatever `batch_size` says. That exposes a common notebook-to-job mistake: a `for` loop calling `pipe(text)` once per row never batches. On a CUDA device the pipeline notices; after more than ten sequential calls it logs a warning that you seem to be using the pipeline sequentially on GPU and should use a dataset. ## Why batching can be slower: padding Tensors in one batch must share a shape. With `batch_size` above 1 the pipeline's collate function pads every item to the **longest sequence in that batch**, using the tokenizer's pad token and padding side. The documentation's example: 64 short sentences of about 4 tokens make a `[64, 4]` batch, but one 400-token sentence among them makes the whole batch `[64, 400]`, a hundred times the work, nearly all of it on padding. Throughput collapses, and at larger batch sizes the job dies with a CUDA out-of-memory error. Two related constraints: - A tokenizer with **no pad token** cannot batch: the pipeline raises a `ValueError` saying a pipeline whose tokenizer lacks a pad token cannot do batching, and suggests setting `pipe.tokenizer.pad_token_id`. Choosing a pad token is a tokenizer matter. - For tasks that pass tokenizer arguments through, such as text classification, give `truncation=True` on the call so one pathological document cannot exceed the model's maximum length. ## The documentation's rules of thumb The Transformers pipeline guide is explicit that batching can be a 10x speedup or a 5x slowdown depending on hardware, data and model: 1. **Measure** on your own load and hardware; real numbers are the only way to know. 2. **Don't batch** if you are latency-constrained, such as a live product answering one request at a time. 3. **Don't batch** on CPU. 4. **Don't batch by default** when you have no idea of the sequence lengths (natural data); measure, add it tentatively, and add OOM recovery. 5. **Do batch** on a GPU when sequence lengths are regular, and push `batch_size` up until you hit OOM; larger GPUs benefit more. 6. Once batching is on, **handle OOM errors** instead of letting one batch kill the job. | Situation | Batch? | |---|---| | Live endpoint, one request at a time | No | | CPU-only worker | No | | GPU, offline scoring, similar-length texts | Yes, tune upward | | GPU, widely varying lengths | Only after measuring, ideally grouping similar lengths | Grouping inputs of similar length before feeding them, for instance by sorting on token count, is a common way to recover the benefit on irregular data, because each batch then pads only to a nearby length. The pipeline does not do this for you. ## Chunk pipelines Some tasks make several forward passes per input. `zero-shot-classification` is a `ChunkPipeline`: one text scored against five candidate labels becomes five model inputs. For these pipelines `batch_size` counts forward passes rather than your inputs, so you can tune it independently of how many passes each input triggers. ## Measuring it properly The only trustworthy number comes from your own inputs on your own hardware. Take a fixed sample of a few thousand real records, not synthetic sentences of equal length, and run it at several batch sizes such as 1, 8, 32 and 64. Record items per second and peak GPU memory for each, and include the longest records you expect in production, because the outlier rather than the average decides whether a size is safe. A list input also holds every result in memory until the call returns, while a generator or `KeyDataset` streams results one at a time, which matters as much as batch size for a very large job. ## For the batch job Feed a `KeyDataset` or a generator, set `truncation=True`, start with a modest `batch_size` on the GPU, time a sample at several sizes, and keep the largest size that is both faster and safe for the longest inputs you expect.
- How should a batch job recover when a large batch_size hits CUDA out of memory partway through?Feed the pipeline in slices you control, catch the out-of-memory error around a slice, free cached GPU memory and re-run that slice at a smaller batch size. The pipeline does not retry for you, and the Transformers guide says to handle OOM whenever batching is on. Logging the inputs that triggered it usually reveals a length outlier worth truncating.
- What does KeyDataset add when feeding a Datasets dataset to a pipeline?`KeyDataset` wraps the dataset as a PyTorch `Dataset` that returns one column per item, such as the text field, which is an input type the pipeline streams and batches. The call then returns a lazy iterator, so results arrive as they are computed and the whole input is never materialised in memory at once.
Shipping in identical crates: every crate in a shipment must fit its largest item, so one oversized item makes the whole shipment bigger. Batching pays off when the items are of similar size.
- Setting batch_size always makes a pipeline faster.
- batch_size groups separate pipe(text) calls made in a loop.
- Batching helps on CPU as much as on a GPU.
- Each row in a batch is padded only as much as it needs.
- In zero-shot-classification, batch_size counts input texts, not forward passes.