Sub topic 9
Latency, batching, and cost
This chapter assumes you have read the earlier chapters on the retrieve-then-rerank pipeline and candidate depth. You should know Python, what a bi-encoder and a cross-encoder are, and how to call CrossEncoder.predict. Here you will learn where reranking time goes, how batching changes it, and how to estimate cost before you ship.
Why a reranker is the expensive stage
A bi-encoder embeds each passage once, offline. At query time it embeds only the query and runs a vector search. A cross-encoder cannot precompute anything, because its input is the query and passage together. Every query therefore triggers one full transformer forward pass per candidate.
Reranking cost per query is roughly:
- candidates reranked (
k_retrieve) multiplied by - the cost of one forward pass over
query + passagetokens.
Transformer cost grows with sequence length. For a fixed model, doubling the number of candidates roughly doubles the work, and longer passages cost more per candidate. Attention cost grows faster than linearly with length, though for short inputs the feed-forward layers dominate and growth looks close to linear.
Where the time goes in one request
A reranked search request has several parts. Only some of them are under the reranker's control.
| Stage | Typical behavior | What affects it |
|---|---|---|
| Query embedding | Fast, one short input | Model size |
| Vector or lexical search | Fast, often milliseconds | Index type, corpus size |
| Tokenization of pairs | Small but not zero | Candidate count, passage length |
| Cross-encoder forward passes | Usually the largest share | Candidates, tokens, model, hardware |
| Sorting and formatting | Negligible | Candidate count |
Because scoring dominates, nearly all tuning effort goes into three levers: fewer candidates, shorter inputs, and more efficient execution.
Batching: why it helps
Running pairs one at a time wastes the hardware. A GPU is built to do many similar operations in parallel, and a single short sequence leaves most of it idle. Batching stacks several pairs into one tensor so one forward pass scores them all.
In sentence-transformers, predict takes a batch_size argument. The earlier pipeline used batch_size=32. Batching helps in two ways:
- Higher throughput, because parallel hardware is used better.
- Less per-call overhead, such as Python dispatch and kernel launches.
Batching has limits:
- Memory. Activations scale with
batch_size × sequence_length. A batch size that works for short passages can run out of memory on 512-token passages. - Padding waste. Every sequence in a batch is padded to the longest one. One long passage in a batch of short ones makes the whole batch slower.
- Diminishing returns. Past the point where the device is saturated, a bigger batch adds no speed and raises memory use.
A common fix for padding waste is to sort candidates by length before batching, so each batch holds similar lengths. The sentence-transformers predict method does some of this for you, so check your version before adding your own sorting.
Measuring latency
Do not guess. Time the scoring step with a warm model, and separate the first call from later calls, because the first call includes one-time setup such as loading kernels.
import time
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
query = "How do I rotate an API key?"
passage = "API keys can be rotated from the Security page by creating a new key and deleting the old one. " * 5
pairs = [(query, passage)] * 100
# Warm-up call: excluded from timing.
model.predict(pairs[:8], batch_size=8)
for batch_size in (1, 8, 32, 64):
start = time.perf_counter()
model.predict(pairs, batch_size=batch_size, show_progress_bar=False)
elapsed = time.perf_counter() - start
print(f"batch_size={batch_size:>3} total={elapsed:.2f}s per_pair={elapsed / len(pairs) * 1000:.1f} ms")Run this on the hardware you will deploy on. On a CPU, the gain from larger batches is usually modest. On a GPU, it is often large until memory or compute is saturated.
For production, report percentiles, not averages. A p95 or p99 latency shows the slow requests that users actually notice, such as ones with unusually long passages.
Cost: a back-of-envelope model
Suppose you serve a given number of queries per day. Cost comes from compute time. A simple model:
- Measure the pairs per second your hardware scores at your chosen batch size and input length. Call it
T. - Reranking time per query is
k_retrieve / Tseconds. - Multiply by queries per day to get total compute-seconds.
- Divide by the device's capacity to get how many devices you need, then multiply by their price.
Worked example with made-up numbers: if one GPU scores 400 pairs per second and you rerank 50 candidates, one query takes 0.125 seconds of GPU time. One GPU handles about 8 queries per second under perfect load. At a more realistic 50 percent utilization, that is about 4 queries per second. Doubling candidates to 100 halves that to about 2.
This is why candidate depth is a cost decision as well as a quality one. The previous chapter showed how to find the depth beyond which quality stops improving. Use that depth, not a larger one.
Levers for reducing latency and cost
Listed from most to least common:
- Rerank fewer candidates. The most direct lever. Cut
k_retrieveuntil your recall and nDCG measurements start to drop, then step back up. - Truncate inputs. Lower
max_length. Halving it cuts per-pair cost, but may drop the part of the passage that answers the query. Verify with your metrics. - Use a smaller model. A 6-layer MiniLM model runs faster than a 12-layer one, usually at some quality cost. Compare on your own evaluation set.
- Use half precision on GPU. Running in float16 or bfloat16 often speeds up scoring and cuts memory. Check that ranking quality does not change on your data.
- Export to an optimized runtime. ONNX Runtime or similar tools can speed up CPU inference. Quantization (storing weights as 8-bit integers) can speed it further, again with a possible small quality loss.
- Cache results. If the same query and candidate set recur, store the scores. Cache keys must include the model name and passage text or version, or you will serve stale scores after an index update.
- Stop early. Skip reranking when the first-stage result is already confident, or when the candidate list is shorter than the final
k. Do this only if you have evidence that it does not hurt quality.
Latency budgets and trade-offs
Set a target first, for example "p95 under 300 ms for the whole search". Subtract the first-stage time and network overhead. The remainder is your reranking budget. Then pick the largest candidate depth and model that fit.
| Choice | Quality effect | Latency effect | Cost effect |
|---|---|---|---|
| More candidates | Higher recall ceiling, diminishing returns | Grows roughly linearly | Grows roughly linearly |
| Longer `max_length` | Keeps more passage text | Grows with length | Grows with length |
| Larger model | Often better ranking | Slower | Higher |
| Larger batch | None | Better throughput, possibly higher single-request latency | Lower per pair |
| Quantization | Usually small loss | Faster on CPU | Lower |
Batch size has a subtle trade-off in a live service. If you wait to collect many requests into one batch, throughput improves but each user waits longer. For interactive search, score the candidates of one query as one batch and avoid waiting for other requests unless your traffic is high enough to fill batches quickly.
Common mistakes
- Timing the first call. It includes setup and overstates latency.
- Ignoring the tail. Average latency looks fine while p99 is several times worse because of long passages.
- Setting
batch_sizetoo high. This causes out-of-memory errors on long inputs, often only in production. - Reranking too many candidates "to be safe". It raises cost with no quality gain beyond the point of diminishing returns.
- Forgetting that the cost is per query. Bi-encoder passage embeddings are paid once, while cross-encoder cost is paid on every request.
Exercise
Your service reranks 100 candidates per query. One GPU scores 500 pairs per second. You expect 10 queries per second at peak and want the GPU to stay under 70 percent utilization. How many GPUs do you need, and what is one change that would reduce this number without swapping the model?
Show answer
Each query needs 100 pairs, so 10 queries per second means 1,000 pairs per second. One GPU at 70 percent utilization provides 500 × 0.7 = 350 pairs per second. You need 1,000 / 350 ≈ 2.9, so 3 GPUs. Reducing candidates from 100 to 50 halves the load to 500 pairs per second, which needs 500 / 350 ≈ 1.4, so 2 GPUs. Shortening max_length or using half precision would also help, but check recall and nDCG first.
Exercise
A benchmark shows batchsize=64 is faster per pair than batchsize=8 on short test passages, but production crashes with out-of-memory errors. Give two likely causes and one fix.
Show answer
Production passages are probably longer than the test passages, so memory use, which scales with batchsize times sequence length, is much higher. Padding to the longest passage in each batch also inflates the tensor size. A fix is to lower batchsize, lower max_length, or sort candidates by length so batches hold similar lengths.