Sub topic 9
Latency, batching, and cost
This chapter assumes you can run the retrieve-then-rerank pipeline from the earlier chapters. You should know what a bi-encoder and a cross-encoder are, and you should be comfortable with Python and sentence-transformers.
Why reranking costs more than retrieval
A bi-encoder embeds each passage once, ahead of time. At query time it embeds only the query and runs a vector search. A cross-encoder cannot do this. It must read the query and each candidate together, so every query triggers one full transformer forward pass per candidate.
The cost of reranking one query is roughly:
- candidates reranked (
k_retrieve) × cost of one forward pass. - The forward pass cost grows with the number of tokens in the pair.
Reranking 50 candidates costs about 50 model calls per query. Reranking 200 costs about four times as much. Candidate depth is the main cost lever you control.
In most systems the cross-encoder step dominates. Embedding the query and searching an index typically take milliseconds, while scoring many pairs on a CPU can take hundreds of milliseconds or more.
Batching
A GPU is efficient when it processes many inputs at once. Scoring pairs one at a time wastes that capacity. The predict method takes a batch_size argument that groups pairs into one forward pass.
import time
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=256)
query = "How do I rotate an API key?"
pairs = [(query, f"Passage number {i} about API keys and account settings.") for i in range(100)]
for batch_size in (1, 16, 64):
start = time.perf_counter()
model.predict(pairs, batch_size=batch_size)
elapsed = time.perf_counter() - start
print(f"batch_size={batch_size:>3} {elapsed * 1000:.0f} ms")Run this on your own hardware. Larger batches usually reduce total time, but the gain levels off. A very large batch can run out of memory, because memory use grows with batch size and with max_length.
Batching also pads inputs. Each batch is padded to its longest pair, so one long passage makes every shorter pair in that batch do extra work. Sorting candidates by length before batching reduces this waste. The library does this internally for predict, but you should know it happens when you compare timings.
Levers that reduce latency
| Lever | Effect | Trade-off |
|---|---|---|
| Fewer candidates | Cost falls in proportion | Lower recall if the relevant passage sat deeper in the pool |
| Smaller `max_length` | Cheaper passes, less memory | Truncation can cut off the answer |
| Smaller model (for example 6 layers instead of 12) | Faster per pair | Often lower ranking quality |
| GPU instead of CPU | Large speedup for batches | Hardware cost |
| Caching scores | Skips repeat work for repeated pairs | Only helps with repeated queries |
Change one lever at a time and measure it with the metrics from the evaluation chapter. A latency gain that drops nDCG is a quality loss, not a free win.
Measuring latency properly
Average latency hides the slow queries users notice. Record percentiles such as p50 and p95. Also run a warm-up call before timing, because the first call includes model loading and kernel setup.
import statistics
import time
def time_queries(search_fn, queries, warmup=2):
for q in queries[:warmup]:
search_fn(q)
durations = []
for q in queries:
start = time.perf_counter()
search_fn(q)
durations.append((time.perf_counter() - start) * 1000)
durations.sort()
p95_index = max(0, int(len(durations) * 0.95) - 1)
return statistics.median(durations), durations[p95_index]Estimating cost
Cost depends on how you host the model.
- Self-hosted GPU: you pay per hour whether or not requests arrive. Cost per query falls as utilization rises, so batching across concurrent requests helps.
- Self-hosted CPU: cheaper per hour, but each query takes longer, so you need more instances for the same traffic.
- Hosted reranking API: usually billed per search or per document scored, so cost scales directly with candidate depth.
A quick estimate is queries per second × candidates per query × time per pair, which gives the compute time you must provision.
Exercise
Your reranker takes 400 ms per query at 100 candidates and your latency budget is 150 ms. Name two changes you could try, and say what you would check after each.
Show answer
Reduce candidate depth (for example to 30 to 40) and reduce maxlength or switch to a smaller model. After each change, re-measure recall@k, MRR, and nDCG on your evaluation set to confirm quality did not drop too far, and re-measure p95 latency to confirm the budget is met. Moving to a GPU or increasing batchsize are also valid options.