Batching model inference: throughput, per-user latency, and memory
Batching can raise throughput while increasing queueing delay and memory use. Compare offline static batches with continuous batching for generation, then measure the trade-off on your model, input lengths, hardware, and latency target.
On this page
The short answer
Batching is a workload-dependent trade-off, not a guaranteed speed or latency improvement. For offline GPU work with similar input lengths, benchmark a few batch sizes. For live generation, generate_batch() returns only after every submitted request finishes; use ContinuousBatchingManager or transformers serve when requests must arrive and return independently. Cache offloading and quantization can reduce memory pressure, but speed effects depend on hardware and implementation.
Three separate measures: throughput, request latency, and memory
Throughput counts completed inputs over a workload and time interval. Request latency measures the time from submission to that request’s result. Peak memory describes device memory at the busiest point. Larger batches may improve throughput on some GPU workloads, but they can add queueing delay and consume more memory. Quantization can reduce weight memory; it does not guarantee faster inference. Decide which metric matters, then measure all three.
Practical tip
Record throughput, p95 request latency, and peak device memory separately. Start with a small batch on representative inputs, increase in controlled steps, and leave memory headroom. If a trial runs out of memory, lower the setting before continuing. For live generation, evaluate the manager or transformers serve with realistic request arrivals and response lengths.
When batching helps and when it hurts
Transformers gives rules of thumb: avoid batching when latency is the main constraint, on CPU, or when input lengths are unknown. For offline GPU workloads with regular lengths, benchmark several batch sizes and sequence limits. These are starting points, not universal rules. Padding, input variation, model, device, and software version can change the result.
Static batches for offline Pipeline work
The Pipeline API accepts batch_size. For a large dataset, KeyDataset passes one selected field at a time without first building a second list of all texts. The example classifies the IMDB test split on CUDA and yields results as it processes the dataset. Install datasets and Transformers, have a compatible GPU, and check memory before increasing the batch size.
import torch
from datasets import load_dataset
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
# Requires datasets, transformers, a CUDA-enabled PyTorch build, and a compatible GPU.
dataset = load_dataset("imdb", split="test")
classifier = pipeline(
"text-classification",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
device=0,
)
for result in classifier(
KeyDataset(dataset, "text"), batch_size=8, truncation=True
):
print(result)Continuous batching and the blocking generate_batch() call
Continuous batching changes group membership as generation progresses: finished requests leave and waiting requests can join. generate_batch() still returns group results only after all submitted requests finish. For an application that accepts requests as they arrive or streams partial output, use ContinuousBatchingManager or transformers serve. API and hardware requirements depend on the installed version. The sample uses a 4B model, bfloat16, and FlashAttention 2; it requires a compatible GPU, CUDA PyTorch, and the flash-attn package.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import ContinuousBatchingConfig, GenerationConfig
model_id = "Qwen/Qwen3-4B"
model = AutoModelForCausalLM.from_pretrained(
model_id,
attn_implementation="flash_attention_2",
device_map="auto",
dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
prompts = ["What's up?", "Name a cat breed.", "Explain model batching in one sentence."]
inputs = [tokenizer.encode(prompt) for prompt in prompts]
generation_config = GenerationConfig(
max_new_tokens=64,
eos_token_id=tokenizer.eos_token_id,
)
continuous_config = ContinuousBatchingConfig(max_batch_tokens=512)
outputs = model.generate_batch(
inputs=inputs,
generation_config=generation_config,
continuous_batching_config=continuous_config,
)
for request_id, output in outputs.items():
text = tokenizer.decode(output.generated_tokens, skip_special_tokens=True)
print(f"[{request_id}] {text}")Generation memory: cache placement and quantization
The KV cache grows with active requests and generated tokens. Transformers has options such as offloaded for dynamic caches and offloaded_static for static caches; static means fixed capacity and does not itself mean CPU offloading. Offloading can trade transfer overhead for lower GPU memory pressure. Quantization can also change memory use, but its speed effect depends on model, hardware, and backend.
Other performance tools and multi-device execution
Compilation, attention backends, and optimized kernels can change runtime and memory depending on shapes, versions, and device support. Some compilation paths have warm-up cost. Quantization is not automatically faster. Parallelism can fit model weights across devices; communication and synchronization can offset throughput or latency gains. Benchmark the combination you plan to deploy.
Uneven inputs, chunking, and recovery
ChunkPipeline handles tasks whose inputs produce multiple chunks or forward passes, but it does not make batch size independent of input shape. Long or uneven inputs can increase padding, memory, or processing time. Keep input lengths representative, set sensible limits, and recover from an out-of-memory event by reducing batch size or sequence length before retrying.
A measurement-led tuning process
Use representative short, typical, and long inputs. After warm-up, record throughput, p95 latency, and peak memory at each safe configuration. Change one setting at a time, include concurrent arrivals for serving, and leave memory headroom. Keep a configuration that meets the latency target without relying on an out-of-memory failure as the stopping point.
Things to check
- Measure throughput, p95 request latency, and peak memory as separate outcomes.
- Compare batch sizes on representative input and output lengths, including the longest expected inputs.
- Treat CPU and unknown-length guidance as a starting rule, then verify the actual workload.
- Keep memory headroom; after an out-of-memory error, reduce the batch or sequence limit before continuing.
- For generation, include KV-cache growth as output length and concurrent requests increase.
- Use generate_batch() for a finite group whose results can be collected together; use ContinuousBatchingManager or transformers serve for serving or streaming.
- Recheck warm-up, memory, and latency after changing quantization, attention backends, compilation, or parallelism.
Where this applies
Results depend on model, input and output lengths, GPU, software versions, and arrival pattern. Pipeline batching guidance is a starting point, not a performance guarantee. generate_batch() waits for all submitted requests; use ContinuousBatchingManager or transformers serve for serving and streaming. Cache options can change between Transformers releases. Parallelism can make a model fit across devices, but communication overhead means it does not guarantee lower latency or higher throughput.