A detector’s datasheet says 2.30 ms. The camera to box loop around it takes 12. Flip the switches and watch two thirds of the loop vanish while the network stays the same.
Learn where the rest of a vision loop goes on a Jetson: preprocessing, copies, kernel launches, sharing the GPU, the DLA, and post-processing, and how to measure each one.
Press All optimisations and watch the bars shrink. Then turn on Render load to share the GPU with a renderer, and see why the slowest frames matter more than the average. After that we build every piece from zero.
You need a rough idea of what a neural network does (numbers in, numbers out) and a little C or Python. We build the GPU, the copies and the timeline reading from zero.
Built from primary sources: the NVIDIA CUDA programming guide, the TensorRT documentation, the NVIDIA DLA blog post, the PyTorch CUDA Graphs post and the Ultralytics Jetson benchmarks. Every link is in the Field Guide.
MAKE IT FASTER
SHARE THE GPU
Only two numbers here are measured: the kernel stage, 2.62 ms (FP16) and 2.30 ms (INT8), from the Ultralytics benchmark of YOLO26n at 640 pixels on a Jetson AGX Orin 64 GB, which excludes pre and post-processing. The other stage costs, the render load and the DLA slowdown are illustrative, chosen to show a typical CPU-bound pipeline. Your own trace gives your own numbers.
Chapter 0
See why the speed on a datasheet and the speed of your robot loop are two different numbers, and learn to add up the whole stack
A team picks a small object detector for a robot. The benchmark page says 2.30 milliseconds per image on a Jetson AGX Orin. At that speed the loop should run at over 400 frames per second. The team wires the camera in and expects a fast robot.
The robot is slow. The arm reacts late and the frame rate sits near 80. Nobody changed the network. The team starts a stopwatch around the whole loop, from the camera frame to the list of boxes, and it reads about 12 ms. Where did the other 9.7 ms go?
The number comes from the Ultralytics Jetson benchmark. It lists YOLO26n, a small detector, on a Jetson AGX Orin 64 GB with a 640 pixel input. The model runs in four ways: PyTorch takes 11.58 ms, TensorRT at FP32 takes 4.18 ms, at FP16 2.62 ms, and at INT8 2.30 ms. The previous lesson covers what those precisions mean and how to prove they keep accuracy.
Read the small print under the table. It says: “Inference time does not include pre/post-processing.” The 2.30 ms covers the neural network and nothing around it. The page is honest. The trap is to forget the sentence when you plan a robot.
Think of a relay race. The network is the fastest runner, but the baton passes through six hands before the answer arrives. Each hand is a stage, and together the stages form the latency stack. Latency means the time from the moment an input exists to the moment its answer exists.
The stages run one after another, so their times add. Between them sit waits, such as a thread that stops until a copy ends.
Now try it. The hero used one example set of stage costs. Choose how much of the stack you count and see what share you report.
The bar is one frame. Bright segments are counted, faint ones are left out. Choose how far down the stack your stopwatch goes, then compare the baseline pipeline with the tuned one.
Illustrative stage costs, the same as the hero. Only the kernel stage (2.30 ms INT8) is a measured vendor figure. “Copies” counts both H2D and D2H.
With kernels only, the report says 2.30 ms, and that is 19% of the 12.0 ms loop. Switch to the tuned pipeline and the whole loop falls to 4.0 ms. The kernels did not change. Now they are more than half of the loop, because the other stages shrank around them.
Use two clocks. A CUDA event is a timestamp that the GPU records when it reaches that point in its queue. Two events around the kernels give the GPU time. A normal CPU clock around the whole loop gives the host time. The gap between them is your hidden cost.
TensorRT’s own tool, trtexec, reports the same split. It prints “GPU Compute Time” for the kernels, plus “H2D Latency” and “D2H Latency” for the copies. Its “Host Latency” is the sum of the three. The documentation says transfers are excluded by default, so the headline number leaves out the copies unless you ask for them.
On a Jetson the CPU and GPU share one pool of memory. NVIDIA’s CUDA for Tegra note says both “share SoC DRAM memory.” So H2D on Jetson is not a trip over a PCIe cable. It is still a copy, and it still costs time and memory bandwidth. Chapter 1 returns to this.
Chapter 1
Move the resize onto the GPU, then learn why one kind of memory makes a copy block the whole thread
Here is the code that most robots start with. A camera frame arrives. A few lines of Python resize it, divide by 255, reorder the axes and hand the result to the network. The lines look cheap. In the baseline of this lesson they cost 6.1 ms, more than twice the network itself.
Follow the bytes. The camera frame is an array of shape [1080, 1920, 3]: height, width, and three colour channels, one byte each. That is 1080 × 1920 × 3 = 6,220,800 bytes, about 6.2 MB.
The network wants [3, 640, 640]: channels first, a smaller picture, and each value a 32-bit float between 0 and 1. The three steps are resize (average pixels down to 640 by 640), normalise (divide by 255 so values land in 0 to 1) and layout change (move the channel axis from last to first).
The size of the result matters for the copy that follows. Resized, the picture is 640 × 640 × 3 = 1,228,800 bytes as bytes. As 32-bit floats it is four times larger: 4,915,200 bytes, about 4.9 MB. Sending floats across moves four times more data than sending bytes.
A CPU does this one pixel at a time, or a few at a time with vector instructions. A GPU has thousands of lanes. Resize and normalise are a perfect fit: every output pixel is independent. So we write them as kernels that run on the GPU. One fused kernel reads the bytes, resizes, normalises and writes the float tensor in a single pass, so the data never returns to the CPU in between. In the hero, GPU preprocessing takes this stage from 6.1 ms to 1.1 ms. Those two numbers are illustrative; yours depend on the resize method and the CPU.
To run a kernel on the frame, the frame must be in device memory. The copy that gets it there is H2D. CUDA offers cudaMemcpyAsync, a call that returns right away so the CPU can carry on while a copy engine moves the bytes. That is the promise. Whether it holds depends on the kind of host memory.
Pageable memory is ordinary memory from malloc. The operating system may move its pages around or swap them out. A copy engine reads memory by physical address, so it cannot trust a page that might move. For a pageable buffer the driver first copies the data into a hidden locked staging buffer, then starts the transfer.
NVIDIA states the consequence plainly. The CUDA programming guide says that without page-locked host buffers, cudaMemcpyAsync() still works but “it will revert to a synchronous behavior which will not overlap with other work.” The runtime’s synchronisation page agrees: transfers with pageable host memory “might be synchronous with respect to host.”
Pinned memory, also called page-locked memory, is the fix. You allocate it with cudaMallocHost (or cudaHostAlloc). The pages stay put, the copy engine reads them directly, and the call really is asynchronous. The CUDA best-practices guide adds that pinned transfers “attain the highest bandwidth between the host and the device.” It also warns not to overuse pinned memory, because locked pages are pages the operating system can no longer reuse.
c++// allocate once at start-up, never in the loop uint8_t *h_in[2]; float *d_in; cudaStream_t s; cudaMallocHost(&h_in[0], 640*640*3); // pinned: 1,228,800 bytes cudaMallocHost(&h_in[1], 640*640*3); // second buffer for double buffering cudaMalloc(&d_in, 3*640*640*sizeof(float)); cudaStreamCreate(&s); // per frame: copy bytes, then normalise on the device cudaMemcpyAsync(d_stage, h_in[f&1], 640*640*3, cudaMemcpyHostToDevice, s); normalize_hwc_to_chw<<<grid, block, 0, s>>>(d_stage, d_in); // one fused kernel enqueue_engine(ctx, d_in, d_out, s); // TensorRT, same stream
Look at the idea behind the code. Copy small bytes, not big floats, and let a kernel widen them on the device. That one choice cuts the copy to a quarter of the size.
Two numbers describe a pipeline. Latency is how long one frame takes from start to finish. Throughput is how many frames finish each second. With pageable memory each frame does three things in a row, so the period is the sum. With pinned memory and two buffers, three engines work at once on three different frames, so the period is the longest single stage.
A worked example, with illustrative copy times and the measured 2.30 ms kernel. Take H = 1.2 ms, K = 2.30 ms, D = 0.4 ms. Pageable: 1.2 + 2.30 + 0.4 = 3.9 ms per frame, or 256 frames per second. Now pin the memory and assume the copies run four times faster: H = 0.3, D = 0.1. The longest stage is K, so the period is 2.30 ms: 435 frames per second. One frame still takes 0.3 + 2.30 + 0.1 = 2.7 ms from start to end. Pinning raised throughput a lot and cut latency a little.
Overlap needs double buffering: two input buffers. While the kernels read buffer 0, the copy engine fills buffer 1. With one buffer, the next copy would overwrite data that the kernels still use.
Four lanes, four frames. Hatched yellow means the host thread is blocked. Choose the memory type, then drag the copy size and watch when frame 4 finishes.
Illustrative: kernels are the measured 2.30 ms; the copy out is one third of the copy in; pinned copies run four times faster than pageable ones (the ratio used in the hero), and both copy engines work at the same time as the GPU. Real ratios depend on the board and the buffer size.
The symptom of a hidden synchronous copy is a pipeline that never overlaps: the GPU shows gaps while the CPU thread looks busy. A profiler such as Nsight Systems (Chapter 7) shows the host thread stuck inside the copy call, and the memory row names the host memory kind. The fix is to allocate pinned buffers once at start-up and reuse them.
One Jetson detail. The CPU and GPU share DRAM there, so you may not need to copy at all. NVIDIA’s CUDA for Tegra note says that duplicate allocations and transfers “can be avoided.” It also warns that on Tegra systems without I/O coherency, repeated CPU access to pinned memory is slow, because the CPU does not cache it. So write into pinned buffers, read them once, and do not loop over them on the CPU. If the camera driver exports its buffer as a dma-buf (a Linux handle for sharing one buffer between devices, covered in the V4L2 buffer queue lesson), the best copy is the one that never happens. Check your JetPack release for the exact import call.
nsys profile --trace=cuda,nvtx twice: once with malloc buffers, once with cudaMallocHost buffers. Compare the copy rows and the time the host thread spends inside the copy call. Chapter 7 shows how to read it. For the memory and DMA side, see the lessons on ML performance and sensor and actuator integration; the virtual memory and DMA lesson of this series covers why pages must stay put.cudaMemcpyAsync from a buffer made with malloc, yet the GPU shows idle gaps and the host thread is blocked in the copy. What is the most likely cause and fix?Chapter 2
Find out why a GPU can sit idle while it has work, and how to hand it the whole plan at once
Open a profiler on a detector with small input and batch size one. The GPU lane looks like confetti: tiny kernels with empty gaps between them. The GPU is not slow. It is waiting. Something upstream feeds it one tiny job at a time, and each job arrives late.
A kernel does not start by itself. The CPU must ask. This request is a launch. The CUDA programming guide describes what happens: “the host driver performs a sequence of operations in preparation for the execution of the kernel on the GPU.” It calls this “an overhead cost which must be paid for each kernel that is issued.”
How big is the cost? Published measurements are in the microseconds. NVIDIA timed 20 short kernels on a Tesla V100 with CUDA 10.1. Each kernel ran for 2.9 µs. When the program waited after every launch, each kernel cost 9.6 µs in total. With a CUDA Graph it cost 3.4 µs. For this lesson we use 5 µs as a planning figure for one launch from a native C++ program. Python frameworks add more. Treat 5 as a starting guess and measure your own board.
Why does the gap matter? The GPU can only run what the CPU has sent. Say each kernel runs for k microseconds and each launch costs L microseconds. The CPU issues one launch every L. If k is bigger than L, launches stay ahead and the GPU never starves. If k is smaller, the GPU finishes and waits. This is the launch-bound regime: the CPU, not the GPU, sets the speed.
A worked example. Use NVIDIA’s kernel, k = 2.9 µs, and the planning launch, L = 5 µs. Busy = 2.9 / 5 = 58%. The GPU idles 42% of the time. Twenty kernels need about 20 × 5 = 100 µs to issue, although they only compute for 20 × 2.9 = 58 µs. The extra 42 µs is pure launch cost.
The top lane is the CPU issuing launches. The bottom lane is the GPU running 12 kernels. Shrink the kernel until gaps appear, then switch on the graph.
Toy model: the CPU issues launches back to back; a kernel starts when its launch is done and the GPU is free. A graph costs one launch for the whole batch, then runs nodes 1 µs apart (an illustrative figure). NVIDIA’s V100 and CUDA 10.1 measurement, 9.6 then 3.4 µs per 2.9 µs kernel, is the real data point.
A CUDA Graph is a recorded list of GPU work with its dependencies. You build it once. After that, one call replays the whole list. The guide gives three stages: definition (describe the operations and their order), instantiation (the driver “validates it, and performs much of the setup and initialization of work”) and execution (launch it “any number of times without repeating the instantiation”).
You rarely write the graph by hand. You use stream capture. The PyTorch team explains it well: CUDA work issued to a capturing stream “doesn’t actually run on the GPU. Instead, the work is recorded in a graph.” After capture, a replay “skips all layers of argument setup and kernel dispatch” and submits the work “with a single call to cudaGraphLaunch.”
c++// record once, at start-up, after warm-up cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal); preprocess_kernel<<<g, b, 0, s>>>(d_raw, d_in); ctx->enqueueV3(s); // TensorRT kernels, all in stream s cudaStreamEndCapture(s, &graph); cudaGraphInstantiate(&exec, graph, 0); // setup cost paid here, once // every frame: refill the same buffer, replay cudaMemcpyAsync(d_raw, h_pinned, bytes, cudaMemcpyHostToDevice, s); cudaGraphLaunch(exec, s); // one call, many kernels
There is a price. A replay runs “the same kernels with the same arguments,” so pointer arguments keep the same addresses. You cannot change the input shape, and you must fill the same input buffer with new data before each replay. PyTorch’s advice: use graphs when the network is “graph-safe (usually this means static shapes and static control flow)” and you suspect it is CPU-limited. A CPU-GPU synchronisation inside the captured region also breaks capture.
What do graphs buy in practice? On PyTorch’s Mask R-CNN backbone, NVIDIA measured the graphed part at 6 ms instead of 31 ms, a 5 times speedup. Because only that part was graphed, the whole model gained about 1.7 times. BERT at large scale gained 1.12 times. The gain is biggest when kernels are short and the CPU is the bottleneck. In this lesson’s hero, CUDA Graphs take launch gaps from an illustrative 1.0 ms to 0.1 ms: think of about 200 launches at 5 µs each.
TensorRT can use graphs too. The trtexec documentation lists a --noCudaGraph flag that disables capturing the inference into a CUDA Graph. Older releases used the opposite flag, so check the version you run. Fusing kernels is the other cure: fewer, larger kernels mean fewer launches. TensorRT already fuses many layers; graphs remove what is left.
The symptom: the GPU is mostly idle, yet latency is high. The measurement: in the profiler, compare each kernel’s duration with the gap before the next one. When the gaps are as large as the kernels, the loop is launch-bound. The fix: capture a graph, or fuse. Keep input shapes fixed, and keep one graph per shape if you must support several.
trtexec with and without graph capture, then look at the kernel rows in Nsight Systems. Measure the gap between kernels in microseconds.Chapter 3
See why a perception loop that is fast alone becomes jittery next to a renderer, and learn which tools help and which only look like they help
The robot has a screen. An operator watches a live 3D view of what the robot sees, and a renderer draws it on the same GPU that runs the detector. Alone, the detector finishes every frame in the same time. With the renderer on, most frames still finish on time, but some take twice as long. The average barely moves. The robot’s worst moments get much worse.
A GPU has one set of compute units. Everything that wants to run must share them. CUDA organises work into streams. A stream is an ordered queue: work in one stream runs in the order you issued it, and work in different streams may overlap or interleave. Think of a stream as a checkout lane. Several lanes can work at the same time only if there are enough cashiers.
Suppose the renderer fills a stream with three long kernels, each 2 ms. That is a queue of 6 ms. Now a camera frame arrives and the detector wants to run. The detector’s kernels sit behind the render kernels. How long does it wait? It depends on when it arrives. If it arrives just after the first render kernel started, it waits almost the whole 6 ms. If it arrives near the end, it waits almost nothing. That spread is the jitter: the frame-to-frame variation in latency.
CUDA lets you create streams with a priority (cudaStreamCreateWithPriority). The guide says: “lower numbers correspond to higher priorities.” Put perception on the high-priority stream and the GPU prefers its waiting blocks over the renderer’s.
Read the next lines slowly. The guide also says: “Stream priorities will not preempt already executing work, or guarantee any specific execution order.” And “a priority of a stream is only a hint to the runtime.” Preempt means to stop a running job to let another one in. The GPU does not do that here. A render kernel that already started must finish.
So a priority removes the queue wait but not the running wait. The perception kernel jumps ahead of the render kernels that have not started, then waits for the one that has. With 2 ms render kernels, the worst wait falls from 6 ms to 2 ms.
Worked numbers (illustrative): n = 3, r = 2 ms. Worst wait without priority: 6 ms, average 3 ms. With priority: worst 2 ms, average 1 ms. The hero uses these figures when you switch on Render load and then Stream priority. The detector’s own 2.30 ms is unchanged. What shrinks is the tail.
Drag the arrival time of your camera frame. Teal marks it. Then add priority, or move perception to the DLA, and shorten the render kernels.
Toy model: the renderer queues 3 kernels of equal length; perception needs 2.30 ms on the GPU or 3.45 ms on the DLA (a 1.5 times slowdown, illustrative); the GPU does not preempt a running kernel (as the CUDA guide states). The DLA path ignores memory contention.
The first trap is cudaDeviceSynchronize(). The guide says it “waits until all preceding commands in all streams of all host threads have completed.” One call in the renderer’s code makes its thread wait for every queue, including yours, and the reverse is also true. Use cudaStreamSynchronize or a CUDA event when you only need one stream.
The second trap is an implicit sync. Pageable copies (Chapter 1) and some allocation calls (Chapter 6) can block the calling thread without the word “synchronize” in your code. The profiler shows them as gaps.
The real fixes work together. First, give perception the higher priority. Second, ask the renderer for shorter kernels, because the longest running kernel sets your worst wait. Third, set time budgets: decide how many milliseconds of each frame each job may use. Fourth, move a job to a different engine. The next chapter does that with the DLA.
A time budget turns sharing into arithmetic. Here is an illustrative case. The display runs at 60 frames per second, so each frame lasts 1000 / 60 = 16.7 ms. Cap the renderer at 8 ms of GPU work per frame: 60 × 8 = 480 ms of every second, or 48% of the GPU. The camera runs at 30 frames per second and the tuned detector needs 4.0 ms per frame: 30 × 4.0 = 120 ms per second, or 12%. Together they use 60%, so 40% stays free. If the budgets sum to more than 100%, no priority setting can save you; something must shrink.
The symptom is jitter in the tail: a good average, a bad 99th percentile. The measurement is a timeline with both streams visible (Chapter 7). Look for a perception kernel that is ready but not running while a render kernel is. The fix is the list above, checked against the new tail.
cudaStreamCreateWithPriority. The median should barely move, and the 99th percentile should drop.Chapter 4
Learn what the other engines on a Jetson chip do, how much of the headline speed they supply, and what happens when a layer cannot run on them
Chapter 3 ended with a plan: move a job to a different engine so it stops queuing behind the renderer. A Jetson AGX Orin chip has such an engine. It is not a second GPU. It is a block of silicon built to do one family of jobs and nothing else.
A GPU is a general tool. It runs many kinds of kernels, so it carries a lot of hardware for flexibility. A fixed-function engine is the opposite: its circuits are wired for a narrow set of operations, so it does those operations with less energy. Think of a food processor next to a chef’s knife.
The DLA, the Deep Learning Accelerator, is such an engine for neural networks. NVIDIA’s blog on the Orin DLA says it “can perform compute-intensive deep learning operations like convolutions much more efficiently than a CPU.” An AGX Orin has two of them. The same post states that DLA performance per watt is on average 3 to 5 times better than the GPU’s. It also notes that running the network on the DLA keeps the GPU available for other work. That is the point for us: perception on the DLA cannot queue behind the renderer, because it is not on the same queue.
Vendors quote speed as TOPS: trillions of operations per second. The Orin post lists the peak sparse INT8 figure for each power mode. Sparse means the number assumes a network pruned into a pattern the hardware can skip. Peak means a ceiling that no real network reaches. Read the footnote on any TOPS number before you plan around it.
Look at the table the post gives, and notice how the balance flips as the power budget shrinks.
Each bar is one power mode of the AGX Orin. Solid purple is the GPU. Hatched purple is the two DLAs together. Pick a mode to read its split.
Numbers from Table 1 of NVIDIA’s “Maximizing Deep Learning Performance on NVIDIA Jetson Orin with DLA”: sparse INT8 peak, GPU plus two DLAs (MAXN 171 + 105 = 275, 50 W 109 + 92 = 200, 30 W 41 + 90 = 131, 15 W 14 + 40 = 54). The 50 W row sums to 201 because the table rounds.
At full power (MAXN) the DLAs add 105 of 275 TOPS, 38%. At 15 W they add 40 of 54, 74%. The post puts it this way: the DLAs’ peak contributes between 38% and 74% of the Orin’s total deep learning performance, depending on the power mode. On a battery-powered robot that runs in a low mode, the DLA is most of the chip.
One honest warning. The DLA can be slower than the GPU for a single frame. In this lesson’s hero, DLA offload multiplies the kernel stage by an illustrative 1.5 and removes the render wait. For a robot with a busy GPU, steady timing beats raw speed. For a robot with an idle GPU, the GPU may win. Measure both.
The DLA runs a subset of layer types. A network with one layer outside the subset cannot run entirely on the DLA. TensorRT can fall back: the unsupported layers run on the GPU and the rest on the DLA. This is useful and costly. Each time the network switches from one engine to the other, the data must change hands. That means a reformat, a sync and a handoff.
Count the switches in a small network. Twelve layers run in a row. If all twelve run on the DLA, there are zero switches. If layer 7 falls back, the sequence is DLA, GPU, DLA: two switches. If the fallback is the last layer, there is one switch. Where the fallback sits matters as much as how many layers fall back. The export, partition and fallback lesson shows how to read the partition report that lists which layer landed where.
Twelve layers run left to right. Tap a layer to make it fall back to the GPU (yellow). Count the engine switches, then try the two presets.
Illustrative: each engine switch costs 0.2 ms for the reformat, the sync and the handoff. The real cost depends on tensor sizes and your TensorRT version; read it from a profile.
The PVA, the Programmable Vision Accelerator, is a different engine: a small programmable processor for classic vision work such as filters and image pyramids, rather than neural networks. NVIDIA’s announcement of the Jetson Thor lists a third-generation PVA (PVA v3.0) among its accelerators. The same announcement does not list a DLA. Thor’s T5000 module is quoted at 128 GB of memory at 273 GB/s and 2070 TFLOPS of sparse FP4. So a design that depends on a DLA on Orin has to move to the GPU or the PVA on Thor. Check the current module datasheet before you plan, and measure; the Orin habit of “put perception on the DLA” does not carry over by default.
The symptom of a bad offload is latency that is worse than the GPU-only build. The measurement is the partition report plus a timeline showing short DLA segments separated by GPU fallbacks. The fix is to change the network so that fallback layers sit at the edge, replace unsupported layers, or give up the DLA for that model.
trtexec in two power modes and compare the median and the 99th percentile, with and without a GPU-heavy job beside them.Chapter 5
Follow the detector’s raw output to the final boxes, and see why the cleanup step can cost more than the network
The network finishes. On the GPU sits a block of numbers. Nobody can use it yet. A robot wants a short list: “a cup at this place, a hand at that place.” Turning the block into the list is post-processing. The benchmark table left it out, and so did our 2.30 ms.
Take a YOLOv8-style detector at 640 by 640 with 80 classes. It looks at the picture on three grids: 80 × 80, 40 × 40 and 20 × 20 cells, one for each of the strides 8, 16 and 32. Every cell proposes one box. That is 6,400 + 1,600 + 400 = 8,400 candidate boxes.
Each candidate carries 4 numbers for the box (centre x, centre y, width, height) and 80 class scores. The output tensor has shape [1, 84, 8400]. That is 84 × 8,400 = 705,600 floats, or 2,822,400 bytes at 4 bytes each: 2.8 MB. If you copy it all to the host, that copy is the D2H stage from Chapter 0.
Decode turns candidates into usable boxes. It takes the best class score of each candidate, drops candidates below a confidence threshold (say 0.25), and converts centre-and-size boxes to image coordinates. Decoding on the device is cheap, because every candidate is independent. And it shrinks the data: if only 300 boxes of 6 numbers each survive, the copy back is 300 × 6 × 4 = 7,200 bytes. That is 392 times smaller than the raw tensor.
One cup covers many cells. Many neighbouring cells all say “cup”, each with a slightly different box. You want one box per object. Non-maximum suppression, or NMS, is the cleanup. It needs one measure first.
IoU, intersection over union, scores how much two boxes overlap. It is the area they share divided by the area they cover together. Worked example. Box A spans x from 0 to 10 and y from 0 to 10. Box B spans x from 5 to 15, same y. They share 5 × 10 = 50. Together they cover 100 + 100 − 50 = 150. IoU = 50 / 150 = 0.33. Slide B one unit right of A, x from 1 to 11. They share 9 × 10 = 90 and cover 110 together. IoU = 0.82: almost the same box.
Count the work. In the worst case nothing gets dropped, and every box is compared with every other box. For n boxes that is n(n−1)/2 IoU computations. The cost grows with the square of the candidates that pass the confidence threshold. Double the survivors and the work quadruples.
Worked numbers, with c = 5 ns. With n = 100 survivors: 4,950 pairs, 25 µs. With n = 630: 198,135 pairs, 0.99 ms; that is the 1.0 ms NMS stage of the hero. With n = 3,000, a cluttered scene or a low threshold: 4,498,500 pairs, 22 ms. The post-processing alone is now ten times the network.
Both axes are logarithmic. Drag the number of candidates that pass the confidence threshold and compare the three ways to finish the job.
Illustrative model: CPU time is 0.02 ms plus n(n−1)/2 pairs at 5 ns each. GPU time is 0.07 ms fixed (launch, sync, small copy) plus 0.05 ns times n squared. The NMS-free time is a flat 0.02 ms for picking the top boxes. Real values depend on the code and the board.
Move it to the GPU. A GPU can compute all IoUs at once, then sweep the results in a short sequential pass. TensorRT offers NMS plugins for this; check the list for your version. The GPU version has a fixed cost (launch, sync, a small copy) and a growth rate far below the CPU’s, so it wins once n passes the crossover, about 140 candidates in the model above. Move it onto the GPU and keep it in the same stream (and in the same CUDA Graph) as the network.
Raise the threshold, cap the count. Fewer survivors means a quadratic saving. Many pipelines also keep only the top few hundred by score before NMS. Check that the cap does not drop real objects.
Remove the step. Ultralytics’ YOLO26 supports native end-to-end inference: a one-to-one head learns to output one box per object, and you switch it on with nms=False in the predict API. The docs say the default one-to-many path still uses NMS for accuracy, so check which path your deployment runs. The same docs say YOLO26 removes DFL, a loss term that made the head more complex. Where the end-to-end path is accurate enough, it is the best latency fix there is. Do not pay for a stage that the design lets you delete. Whether the 2.30 ms benchmark includes any such work is not stated, so compare whole stacks, not headline numbers.
The symptom of expensive post-processing is a CPU core at 100% in the detector loop with an idle-looking GPU, rising when the scene gets crowded. The measurement is a timer around the NMS call (or an NVTX range, Chapter 7) plotted against the candidate count. The fix is one of the three above.
Chapter 6
Remove the slow first second, the hiccup every few dozen frames and the long start-up, so that frame 5,000 behaves like frame 50
The tuned loop now takes 4.0 ms. The team deploys it. Three things go wrong. The first second after start is sluggish. Every 25th frame or so, one frame takes 6 ms longer. And after a software update, the robot needs over half a minute before it sees anything. None of these show up in an average. All of them show up in the robot.
A deterministic loop does the same work in about the same time on every frame. A control loop cares about the worst frames, not the typical one. A percentile gives the number: the 99th percentile (p99) is the time that 99 out of 100 frames beat. The max is the slowest frame of all. A safety margin has to cover the max, not the median.
Four causes explain most of the unsteadiness on an edge GPU. Each one has a symptom you can see and a fix you can apply.
Chips save power by changing their speed with the load. This is DVFS, dynamic voltage and frequency scaling. NVIDIA’s Jetson guide explains the link: clock frequency is proportional to voltage, so scaling one scales the other. When the load starts, the clocks ramp up from idle, and the first inferences run slowly.
You choose a power mode with nvpmodel -m and a mode ID. A helper script, jetson_clocks, holds the clocks high within that mode. The price is power and heat. The next lesson in this track, the edge roofline and the throttle, covers the heat side. Lock the clocks only after you have checked that the enclosure can take it.
The first call into a GPU library does hidden work: it loads code, creates contexts, picks algorithms and fills caches. That work makes frame 0 slow, and sometimes frames 1 and 2. The cure is a warm-up: run a few dummy frames before you start the clock and before the robot depends on the result. PyTorch’s own graph guidance says the same: warm up on a side stream with a few iterations before capture.
cudaMalloc asks the driver for device memory. It can take milliseconds, and it can wait for earlier GPU work to finish. Field reports describe stalls of 1 to 10 ms from allocation inside a loop; treat that range as typical and measure your own. A loop that allocates a temporary buffer each frame, or whose allocator grows during a long mission, shows a periodic spike.
The fix is to preallocate: create every buffer once at start-up, size it for the worst case, and reuse it. This is also what a CUDA Graph needs, since a graph replays with fixed addresses (Chapter 2). Static shapes and fixed buffers go together.
A TensorRT engine is the compiled network. Building one searches many kernel choices and can take tens of seconds; 30 s or more is common on edge boards, though your model decides. Loading a saved one, deserialisation, is far quicker. But the saved file is picky. The TensorRT documentation says that by default engines are compatible only with the TensorRT version that built them, and “only compatible with the type of device where they were built.” A mismatch fails to load, or you rebuild.
Options exist to relax the rule. Version-compatible builds load on later TensorRT versions, but the documentation notes they “can be slower than engines built for a specific runtime version.” The safe plan for a fleet is: build the engine per device type and TensorRT version during a setup step, save it to disk, and deserialise it at start-up before the mission begins.
Each bar is one frame of the tuned 4.0 ms loop. All three problems start switched on. Apply the fixes one at a time and watch the tall bars disappear.
Illustrative trace: a 4.0 ms loop; unlocked clocks start at twice the time and settle over 20 frames with 12% noise (2% when locked); no warm-up adds 45, 6 and 2 ms to frames 0, 1 and 2; allocation in the loop adds 6 ms every 25th frame. Engine start-up: 30 s to build, the “30 s or more” field figure, against about 1 s to load (illustrative).
A checklist for a steady loop:
Chapter 7
Learn the five rows of a GPU timeline and the shape that each of the earlier problems leaves on them
A teammate sends you a profile of the slow loop. It has two hundred rows and a thousand tiny coloured boxes. Where do you look? Every chapter so far described a problem in words. This chapter shows what each one looks like on the screen where you will really find it.
Nsight Systems is NVIDIA’s system-wide profiler. It records what the CPU threads, the CUDA calls, the GPU kernels and the memory copies were doing, and lines them all up on one time axis. A sibling tool, Nsight Compute, looks inside one kernel at a time: memory throughput, occupancy, stalls. This lesson stays with the timeline. The kernel-level view belongs to the GPU and kernels lessons of the CS336 series.
You record a run from the command line. The user guide says to pass --trace a comma-separated list with no spaces, such as --trace=cuda,nvtx:
bash# record 10 seconds of the running detector nsys profile --trace=cuda,nvtx --duration=10 -o detector ./run_detector # then open detector.nsys-rep in the Nsight Systems GUI, or print a summary: nsys stats detector.nsys-rep
NVTX is the key to a readable picture. It is the NVIDIA Tools Extension: a few calls that mark ranges and give them names. The user guide explains that the timeline then “shows when your CPU threads are executing within those regions” and projects the ranges onto the GPU timeline, so you can see which GPU work a range launched.
c++#include <nvtx3/nvToolsExt.h> nvtxRangePushA("preprocess"); preprocess(frame); nvtxRangePop(); nvtxRangePushA("infer"); enqueue_engine(s); nvtxRangePop(); nvtxRangePushA("nms"); nms_on_gpu(s); nvtxRangePop(); # Python: torch.cuda.nvtx.range_push("preprocess") ... torch.cuda.nvtx.range_pop()
Name the ranges after the stages of the stack in Chapter 0. Then the timeline answers the first question directly: how long did each stage take, in this run, on this board?
Read any timeline with the same three questions, in order.
Pick a case and read the five rows. Then switch off the NVTX ranges to see what an unlabelled profile gives you.
A drawn model, not a real capture. Durations are illustrative and follow the lesson’s tuned 4.0 ms loop with one problem added. Real Nsight Systems rows are richer, with one lane per thread and per stream.
The healthy case packs the GPU row and overlaps the copy with the kernels. The pageable case shows a long bar on the memory call and an idle GPU before the first kernel. The launch-bound case shows a dense run of short API calls and a GPU row of thin boxes with gaps that match them. The allocation case shows one long cudaMalloc bar, with the GPU idle around it. The contention case shows your kernel ready early and starting late, behind boxes that belong to someone else.
Numbers come off the timeline with simple sums. Suppose the NVTX ranges read: preprocess 6.1 ms, copy in 1.2, infer 3.3, copy out 0.4, nms 1.0. They add to 12.0 ms, the loop of Chapter 0. The infer range holds the 2.30 ms of kernels plus 1.0 ms of launch gaps. To check the busy fraction, add the kernel durations inside a stretch and divide by the length of the stretch. If kernels sum to 0.9 ms inside a 2.4 ms span, the GPU is busy 0.9 / 2.4 = 37.5% of that span. A busy fraction that low, with a dense run of launch calls above it, is the launch-bound signature.
Look for the hand-offs between rows. A launch call on the API row should be followed soon by a kernel on the GPU row. The distance between the two is the queue time. A short distance means the GPU was free. A long distance, as in the contention case, means something else held the GPU. This one habit, finding the gap between “the CPU asked” and “the GPU started”, explains more slow loops than any other.
The symptom of a profile without NVTX is a pile of unnamed kernel boxes. You can still count gaps, but you cannot say which stage owns them. The cure costs three lines per stage. Profiling also perturbs the run a little, so take your timing numbers from an unprofiled run and use the profile to explain them.
nsys profile --trace=cuda,nvtx, and read off the length of each range. Check that the total matches the loop time from your own CPU clock.Chapter 8
Keep the numbers, the checklist and the stack model as code, then take the whole stack, not one number, into your next design review
The vendor number is the kernels. The loop is the kernels plus the preprocessing, two copies, the launches, the post-processing and every wait between them. In our example that is 2.30 ms inside a 12.0 ms loop, and tuning the stages around the network gives 4.0 ms, two thirds less, with the same network. Each fix has a cause you can name and a measurement that shows it.
| Item | Value | Status and source |
|---|---|---|
| YOLO26n, AGX Orin 64 GB, 640 px | PyTorch 11.58 ms; TensorRT FP32 4.18; FP16 2.62; INT8 2.30 | Measured, excludes pre/post. Ultralytics 8.4.32 Jetson benchmark |
| Orin sparse INT8 peak, GPU + 2 DLAs | MAXN 171 + 105 = 275; 50 W 109 + 92 = 200; 30 W 41 + 90 = 131; 15 W 14 + 40 = 54 TOPS | Documented peak. NVIDIA DLA blog, Table 1 |
| DLA share and efficiency | 38% to 74% of the Orin total; performance per watt 3 to 5 times the GPU, on average | Documented. NVIDIA DLA blog |
| Launch cost, V100, CUDA 10.1 | 2.9 µs kernel: 9.6 µs with a wait after each launch, 3.8 µs overlapped, 3.4 µs in a graph | Measured by NVIDIA. CUDA Graphs blog. The 5 µs planning figure here is an estimate |
| Graph gains | Mask R-CNN backbone 31 ms to 6 ms (5 times), whole model 1.7 times; BERT 1.12 times | Measured by NVIDIA. PyTorch CUDA Graphs post |
| Pageable copy | cudaMemcpyAsync reverts to synchronous behaviour | Documented. CUDA programming guide, asynchronous execution |
| Stream priority | Lower number is higher priority; running work is not preempted; a hint only | Documented. CUDA programming guide |
cudaDeviceSynchronize | Waits for all commands in all streams of all host threads | Documented. CUDA programming guide |
| Candidates and raw output (YOLOv8-style, 640 px, 80 classes) | 8,400 = 6,400 + 1,600 + 400; tensor [1, 84, 8400] = 2.8 MB; 300 final boxes = 7,200 bytes | Arithmetic from the head layout |
| NMS comparisons | n(n−1)/2; n = 631 gives 198,765 | Arithmetic. The 5 ns per IoU is illustrative |
| Engine compatibility | By default only the same TensorRT version and device type | Documented. TensorRT engine compatibility page |
| Jetson Thor T5000 | 128 GB, 273 GB/s, 2070 TFLOPS sparse FP4, PVA v3.0; no DLA listed | Documented. NVIDIA Thor announcement |
| This lesson’s stack | 12.0 ms baseline, 4.0 ms tuned; stage costs other than kernels | Illustrative |
The whole lesson fits in a small model. It holds the stage costs, the toggles that change them and a greedy search for the knob with the largest gain. Replace the numbers with your own measurements and it becomes your planning tool.
pythonSTAGES = ["pre", "h2d", "launch", "kern", "d2h", "nms"] BASE = dict(pre=6.1, h2d=1.2, launch=1.0, kern=2.30, d2h=0.4, nms=1.0) # ms; only kern is a vendor figure KNOBS = { # each knob replaces some stage costs "gpu_preprocess": {"pre": 1.1}, "pinned_memory": {"h2d": 0.3, "d2h": 0.1}, "cuda_graph": {"launch": 0.1}, "gpu_nms": {"nms": 0.1}, } def total(on): s = dict(BASE) for k in on: s.update(KNOBS[k]) return sum(s[x] for x in STAGES) def greedy(): on = [] while len(on) < len(KNOBS): gain = {k: total(on) - total(on + [k]) for k in KNOBS if k not in on} best = max(gain, key=gain.get) on.append(best) print(f"{best:15s} saves {gain[best]:.1f} ms -> {total(on):.1f} ms") greedy() # gpu_preprocess saves 5.0 -> 7.0 ms; pinned_memory 1.2 -> 5.8; cuda_graph 0.9 -> 4.9; gpu_nms 0.9 -> 4.0
Run it and it prints four lines that end at 4.0 ms. The order is the point. The knob with the largest gain comes first, and each fix changes what the next one is worth. Measure, fix the biggest stage, measure again.
For the measuring itself, the pattern is two clocks around the same work:
c++cudaEventRecord(ev_a, s); // GPU timestamp, taken in stream order /* copy in, kernels, copy out, all enqueued on stream s */ cudaEventRecord(ev_b, s); cudaStreamSynchronize(s); // wait for this stream only float gpu_ms; cudaEventElapsedTime(&gpu_ms, ev_a, ev_b); // loop_ms = steady_clock after the NMS minus steady_clock before the resize // hidden = loop_ms - gpu_ms: the stages the vendor number leaves out
This lesson is the third in the edge track. Export, partition and fallback decides which layers land on which engine. Quantise, compile, prove parity makes the kernels small and checks accuracy. This lesson wraps the stack around them, and the edge roofline and the throttle asks how long the speed lasts in a hot enclosure.
For more depth on the pieces: the V4L2 buffer queue, where the frame begins, is in the camera lesson, and the end of the camera path is in low-latency video. The wider performance habits are in ML performance, robot real-time performance and sensor and actuator integration; the host side of real time is in real-time Linux and embedded real-time systems. Kernel-level analysis belongs to GPUs and kernels. Lessons planned for this series cover flame graphs and perf, virtual memory and DMA, and rings, queues and drops. They tell the host side of the same story.
Credit: this lesson was built from the primary documentation above. It teaches in its own words and its own models, and no course slides were used. Items marked illustrative are teaching numbers, not measurements.
Now press Present or Teach and explain, from memory, where the other two thirds of a 12 ms loop go and which measurement finds each one. Then go back to the switches at the top, turn on Render load, and explain why priority shrinks the tail but not the median.