Sub topic 15
Dynamic batch sizes and optimization profiles
This chapter assumes you can export a PyTorch model to ONNX, create an ONNX Runtime InferenceSession, and enable the TensorRT execution provider. You should also know what an engine cache is. It covers how a dynamic batch dimension works in TensorRT, how optimization profiles define the allowed shape range, and which errors and slowdowns show up when the profile and the real traffic disagree.
Why dynamic shapes need extra care in TensorRT
When you export with dynamic_axes={"input": {0: "batch"}}, the ONNX file says the batch dimension is symbolic. ONNX Runtime's CUDA and CPU providers handle this without any extra setup. They allocate buffers for each call based on the actual input shape.
TensorRT works differently. It builds kernels ahead of time and picks them by timing candidates on the real GPU. Kernel choice depends on tensor sizes. A kernel that is fastest for batch 1 may be slow for batch 32. So TensorRT needs to know the range of shapes it should prepare for before it builds the engine.
That range is an optimization profile. A profile gives three shapes for each dynamic input:
- min: the smallest shape the engine will accept.
- opt: the shape the builder tunes for. Kernel selection and timing focus on this shape.
- max: the largest shape the engine will accept. It also sets the size of the memory the engine reserves.
At run time, any input shape between min and max is valid. Performance is best at or near opt.
Setting a profile with the TensorRT execution provider
The ONNX Runtime TensorRT provider accepts profile shapes as provider options. Each option is a string with the input name, a colon, and the dimensions joined by x. Multiple inputs are separated by commas.
import onnxruntime as ort
providers = [
(
"TensorrtExecutionProvider",
{
"trt_fp16_enable": True,
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "./trt_cache",
"trt_profile_min_shapes": "input:1x3x224x224",
"trt_profile_opt_shapes": "input:8x3x224x224",
"trt_profile_max_shapes": "input:32x3x224x224",
},
),
"CUDAExecutionProvider",
"CPUExecutionProvider",
]
sess = ort.InferenceSession("resnet50.onnx", providers=providers)
print(sess.get_providers())The three options must be set together. Their names must match the ONNX input names exactly, so input here comes from the input_names you used at export.
If you do not set the profile options, ONNX Runtime builds the engine for the first shape it sees and rebuilds when a shape falls outside the range it has seen. That can happen in the middle of serving traffic, so set the profile explicitly for any service.
What happens when a shape is outside the profile
Behavior depends on how the engine was built.
| Situation | What you see |
|---|---|
| Explicit profile, request inside min..max | Normal run, fast near opt |
| Explicit profile, request above max | Run fails with a shape or profile error |
| No explicit profile, new shape in a new range | The provider rebuilds the engine, and that call takes seconds to minutes |
| `trtexec` plan, request outside the profile | Execution context rejects the shape |
A rebuild during a request is the worst case for latency. A single call can take as long as an engine build, and every new range triggers another one. Guard against it in two ways. Put a limit on the batch size before requests reach the session, and warm the session with the min, opt, and max shapes at startup.
import numpy as np
def warm_profile(sess, name="input", sizes=(1, 8, 32)):
for n in sizes:
x = np.random.rand(n, 3, 224, 224).astype(np.float32)
sess.run(None, {name: x})
warm_profile(sess)Running all three sizes at startup forces any lazy initialization to happen before the first real request. If the engine cache is enabled, it also makes sure the cache files exist on disk.
Choosing min, opt and max
Pick the profile from your traffic, not from the largest number the GPU can hold.
- min is usually 1. A smaller min costs little, and a request of one image is common in interactive services.
- opt is the batch size you see most often under load, or the one your batcher targets. If you use a dynamic batcher with a maximum of 8, tune for 8.
- max is a hard cap from your batcher or your memory budget. Do not set it far above what you will send.
A large max has a cost. TensorRT sizes its workspace and activation memory for the max shape, so the engine reserves more GPU memory than it needs for typical requests. A wide range between min and max can also make the builder choose kernels that are a compromise, so opt-shape performance may fall slightly short of an engine built for exactly that shape.
When the traffic has two distinct modes, for example batch 1 for interactive calls and batch 32 for offline jobs, you have two options:
- Use one wide profile and accept the compromise.
- Build two engines with narrow profiles and route requests by batch size.
Measure both with the benchmarking method from the earlier chapter, with warmup and percentile latencies at each batch size. Choose the wide profile only if p95 at batch 1 and throughput at batch 32 are both acceptable.
Building the same profile with trtexec
When you build outside ONNX Runtime, the profile flags are the same idea.
trtexec --onnx=resnet50.onnx --saveEngine=resnet50.plan --fp16 \
--minShapes=input:1x3x224x224 \
--optShapes=input:8x3x224x224 \
--maxShapes=input:32x3x224x224To profile the built engine at a different batch size inside the range, load it and pass --shapes:
trtexec --loadEngine=resnet50.plan --shapes=input:16x3x224x224Compare the reported latency and throughput at 1, 8, 16 and 32. If throughput per image at 8 is much better than at 1, a batcher will pay off. If latency at 32 is far above what your service allows, lower max.
Spatial dimensions and other dynamic axes
Batch is the most common dynamic axis, but height and width can be dynamic too. Export them as dynamic axes and give each one a range in the profile.
torch.onnx.export(
model,
dummy,
"resnet50_hw.onnx",
input_names=["input"],
output_names=["logits"],
dynamic_axes={"input": {0: "batch", 2: "height", 3: "width"}},
opset_version=17,
)trtexec --onnx=resnet50_hw.onnx --saveEngine=resnet50_hw.plan --fp16 \
--minShapes=input:1x3x224x224 \
--optShapes=input:8x3x320x320 \
--maxShapes=input:32x3x640x640Each extra dynamic axis widens the space the builder must cover, which usually lowers peak speed. For classification, resize to a fixed input size in preprocessing and keep only batch dynamic. Detection models with variable input size are the usual reason to make height and width dynamic. Even then, resizing to a small set of fixed sizes and building one engine per size is often faster.
Common errors
- Input name mismatch. The profile string uses a name that does not match the ONNX input. Check with
[i.name for i in sess.get_inputs()]. - opt outside min..max. The builder rejects profiles unless min <= opt <= max for every dimension.
- Stale cache. If you change the profile but reuse an old cache directory, you may be running an engine built for the previous range. Use a separate cache path per profile, or clear the cache when you change it.
- Padding mistaken for dynamic batching. A fixed batch of 8 padded with zeros costs the same as 8 real images. A dynamic profile lets a batch of 3 run as 3.
- Benchmarking only at opt. Real traffic mixes sizes. Benchmark across the range, and report percentiles for each size.
Exercise
Your service receives mostly batches of 4, occasionally 1, and never more than 16. A teammate proposes min=1, opt=64, max=64 "to be safe". What is wrong with this profile, and what would you set instead?
Show answer
The profile tunes kernels for batch 64, which never occurs, so the common batch of 4 runs on kernels chosen for a much larger size. It also reserves workspace and activation memory for batch 64. Set min=1, opt=4, max=16. Then benchmark batch 1, 4 and 16 with warmup and report p50, p95 and p99 to confirm.
Exercise
After deploying, the first request with batch size 40 takes 90 seconds while later ones are fast, and the engine was built with a profile of min 1, opt 8, max 32. Explain the likely cause, using the options available in the TensorRT provider.
Show answer
Batch 40 is above max, so the engine cannot run it as built. If the profile was not enforced, or the session was allowed to rebuild, the provider builds a new engine for the new range during the request, which explains the 90 seconds. Fix it by capping or splitting batches at 32 before they reach the session, and by raising max only if batch 40 is a real requirement. Warm the session at startup so the rebuild never happens on a live request.