Sub topic 1
What "fast" means: latency versus throughput
Prerequisites
This chapter assumes you can read basic Python and NumPy, and that you have trained or used an image model in PyTorch. You should know what a batch of images looks like as a tensor, for example (8, 3, 224, 224). No GPU is needed for this chapter. The later GPU chapters require an NVIDIA GPU with CUDA drivers.
Why define "fast" first
"Make inference faster" can mean two different goals. Each goal leads to different settings in ONNX Runtime and TensorRT. If you pick the wrong one, you can tune for hours and make the system worse for its real users.
This chapter defines the two measures, shows how they trade off against each other, and gives a way to choose between them. Later chapters apply that choice to exporting, running, and accelerating a vision model.
Latency
Latency is the time from when one request enters your system until its result comes back. It is measured in milliseconds per request.
Latency matters when a person or a control loop is waiting. Examples are a phone app that classifies a photo, a robot that must react to an obstacle, and a camera that triggers a reject gate on a production line.
Latency is a distribution, not a single number. Two systems can both average 20 ms, but one may take 80 ms on 1% of requests. Users notice the slow requests. For this reason, teams report percentiles. p50 is the median, p95 is the time that 95% of requests beat, and p99 is the time that 99% beat. A later chapter shows how to measure these correctly. Here, remember that a latency target should name a percentile, such as "p99 under 30 ms".
Throughput
Throughput is how much work the system finishes per unit of time. For vision models it is usually images per second.
Throughput matters when there is a large backlog and nobody waits on a single item. Examples are tagging a photo archive, processing recorded video overnight, and scoring millions of product images. In these jobs, total time and hardware cost matter more than the time of any one image.
How batching links the two
Running a GPU on one image rarely uses the whole device. Each inference call has fixed costs, such as launching kernels and moving data. Many layers also do too little work at batch size 1 to keep thousands of GPU cores busy. Putting more images in one call spreads the fixed cost across them.
The result is a trade-off. A larger batch usually raises throughput, but it also raises the latency of each call, because the call does more work. Any request that waits for a batch to fill pays an extra delay.
The script below uses a simple cost model to show this. It is an illustration with made-up numbers, not a measurement. Assume each call has 4 ms of fixed overhead and each image adds 0.5 ms.
FIXED_MS = 4.0 # per-call overhead (launch, copies, scheduling)
PER_IMAGE_MS = 0.5 # marginal cost of one more image in the batch
print(f"{'batch':>5} {'latency ms':>11} {'images/s':>9}")
for batch in [1, 2, 4, 8, 16, 32, 64]:
latency_ms = FIXED_MS + PER_IMAGE_MS * batch
throughput = batch / (latency_ms / 1000.0)
print(f"{batch:>5} {latency_ms:>11.1f} {throughput:>9.0f}")The output shows the pattern:
| Batch size | Latency per call | Throughput |
|---|---|---|
| 1 | 4.5 ms | about 222 images/s |
| 8 | 8.0 ms | 1000 images/s |
| 32 | 20.0 ms | 1600 images/s |
| 64 | 36.0 ms | about 1778 images/s |
Going from batch 1 to batch 32 multiplies throughput by about 7 but multiplies latency by about 4.4. Going from 32 to 64 almost doubles latency for an 11% gain in throughput. Throughput curves flatten as the device becomes fully used, so the last increases in batch size are costly.
The online serving case
Many real services sit between the two extremes. A web service receives independent requests from many clients and must answer each within a deadline, but it also wants good GPU use. The usual answer is dynamic batching. The server collects requests that arrive within a short window, runs them as one batch, and splits the results.
Dynamic batching adds two settings that you must choose together:
- The maximum batch size, which caps the compute time per call.
- The maximum wait time, which caps how long the first request in a batch can sit in the queue.
A request's latency in this setup is the queue wait, plus the batch compute time, plus preprocessing and postprocessing. If your deadline is 50 ms and compute for a full batch takes 20 ms, you cannot allow more than about 30 ms of waiting and other work. This is why the batch that gives the best throughput is often not allowed in a latency-bound service.
Concurrency and Little's law
A useful relationship connects the two measures. For a system in steady state, the number of requests in flight equals throughput multiplied by average latency. This is Little's law.
Suppose a service must handle 500 requests per second and each takes 40 ms on average. Then about 500 × 0.040 = 20 requests are in flight at any moment. You need enough capacity to hold that concurrency, whether through batching, several model instances, or several GPU streams.
Little's law also warns you about overload. When arrivals exceed throughput, the queue grows without bound, so latency grows too. A system can show excellent latency in a test with one client and fail in production because the real load is above its throughput limit.
Edge cases and common mistakes
- Reporting only the mean. The mean hides tail behavior. Always record p95 or p99 for latency targets.
- Measuring throughput from latency at batch 1. Dividing 1000 ms by the batch-1 latency underestimates what batching can reach. It also overestimates what you can reach under load when batches cannot fill.
- Ignoring the rest of the pipeline. Image decoding, resizing, and normalization on the CPU can dominate. A model that runs in 3 ms is not fast if preprocessing takes 15 ms. A later chapter covers preprocessing and postprocessing.
- Mixing cold and warm timings. The first calls include one-time setup such as memory allocation and, with TensorRT, possibly engine building. These calls are not representative of steady state.
- Optimizing the wrong target. Cutting latency from 12 ms to 10 ms does not help an offline job, while a larger batch might double its speed. Conversely, a larger batch can break a 30 ms deadline.
- Assuming the largest batch is best. Memory limits, flattening throughput curves, and latency budgets all cap the useful batch size.
How this shapes the rest of the tutorial
The tools in this tutorial affect the two measures in different ways. Keep this map in mind as you go through the later chapters.
| Technique | Mostly helps | Note |
|---|---|---|
| Larger batch sizes | Throughput | Raises per-call latency |
| GPU execution providers | Both | Largest gain for large models and batches |
| TensorRT engines | Both | Adds build time and shape constraints |
| FP16 and INT8 | Both | Needs an accuracy check |
| I/O binding | Latency | Removes host-device copies per call |
| Engine caching | Startup time | Does not change steady-state speed |
You will export the model with a dynamic batch dimension for exactly this reason. One file can then serve batch size 1 for latency-sensitive paths and larger batches for throughput jobs.
Exercise
A service runs a classifier with 6 ms of fixed overhead per call plus 0.4 ms per image. Requests must be answered with at most 25 ms of model time per call. What is the largest batch size that meets this limit, and what throughput does it give? Would you pick it if the p99 deadline for the whole request is 25 ms, including a 5 ms wait in the batching queue?
Show answer
Model time is 6 + 0.4 × batch. For 25 ms, batch = (25 − 6) / 0.4 = 47.5, so the largest whole batch is 47. Its latency is 6 + 18.8 = 24.8 ms, and throughput is 47 / 0.0248 ≈ 1895 images/s. If the 25 ms deadline also includes a 5 ms queue wait, model time can use only 20 ms, so batch = (20 − 6) / 0.4 = 35. That gives latency 20 ms and throughput 35 / 0.020 = 1750 images/s. In that case you would choose a maximum batch of 35 or less, because the larger batch would miss the deadline.