Module 13 · Lesson 91 of 98

Code review and the deployment package

Review an embedded vision pipeline, justify its design choices, and package it so another developer can build, start, verify, and stop it.

  • Beginner to advanced
  • 9 min read
  • 50 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM for package review and host-side checks. A compatible NVIDIA Jetson with the project toolchain, Compute Sanitizer, and representative input is needed for target verification. DLA comparisons require a Jetson with DLA support.

Your place in the module
By the end you can 4 objectives
  • Review CUDA kernel bounds, asynchronous errors, and resource ownership.
  • Verify representative project runs with Compute Sanitizer and output comparisons.
  • Justify algorithm, precision, and inference device choices using workload evidence.
  • Package a foreground service with reproducible instructions and a tested shutdown path.
Video coming soonCode review and the deployment package
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The demo and the performance numbers
  • TensorRT runs inference on the GPU in this pipeline, after GPU preprocessing.
  • A moving object and a matching frame identifier help verify that the preview and subscriber show the same event.
  • Latency depends on the endpoints used to measure it.
01

Review correctness and resource ownership

4 min read

You have presented it. This lesson answers how to review the code for correctness and leaks and package it so someone else can run it.

A Linux service can receive SIGTERM while a capture buffer is still in use by queued GPU work. Linux delivers the signal to the process. The application's stop path must coordinate capture, workers, and GPU completion before releasing the buffer. That case gives the reviewer a concrete question to ask of each resource. Who owns it at the moment a stop request arrives? signal(7)

Start with one frame and trace it from capture to published detections. At each CUDA kernel, identify the accepted dimensions, format, pitch, and output layout. For a one-thread-per-pixel kernel, review the last block in both dimensions. A rounded-up grid can launch threads outside the logical image. Protect accesses with bounds checks, and verify that the row address uses the pitch in bytes when the image is pitched. If a kernel contains a block-wide barrier, check that the edge handling keeps the required threads participating. For a tiled filter, check how the first and last output pixels obtain their neighbors. Test an odd image size with padding, and compare the valid output pixels with a reference using the documented border rule and tolerance.

Then trace dependencies across frames. A capture slot can be returned once all consumers have finished reading it. An asynchronous launch returning to the CPU establishes submission. The event or synchronization point used by the program must establish completion before reuse. Check that the completion record belongs to the stream and frame that last used the slot. Follow the output buffer in the same way if postprocessing or publishing runs asynchronously.

Check the return values of CUDA operations such as allocation, transfer, event recording, and synchronization. Check the launch status promptly with cudaGetLastError() after each kernel launch, then check the return value at the stream or event synchronization point where the result becomes usable. Errors during execution can surface at a later runtime call. Give the log enough context to locate the fault, such as the stage, frame identifier, and operation. Make a failed frame ineligible for publication. Keep the synchronization that expresses a real dependency so routine error checking preserves the intended overlap.

Frame reviewValidateframelayoutDimensions,pitch, andformatChecklaunchstatusCheck GPUcompletionReturncaptureslotValidateframelayoutDimensions,pitch, andformatChecklaunchstatusCheck GPUcompletionReturncaptureslot
Review the frame boundary, launch check, and completion check before the capture slot is returned.

Review resource lifetimes on both normal and partial startup paths. List each acquisition and its owner, including capture descriptors and mappings, imported buffers, CUDA allocations, streams and events, and inference objects. For each failure return, follow the cleanup of everything that was acquired before it. A failure to load an engine after capture opens should still release capture resources. Release resources in dependency order after their users have finished. Preserve the original failure in the log if cleanup also fails. Repeated initialization and shutdown inside a process can expose leaks that a single startup and exit would conceal. Repeated service restarts can reveal resources that fail to reopen.

Require the project to be Compute Sanitizer clean on representative paths before handoff. Use a finite input and let the CUDA process exit through its ordinary cleanup. The following commands assume run-smoke.sh is your package's executable wrapper for a recorded fixture and ends with exec of the CUDA application. Run each command separately on the compatible NVIDIA target.

bash
compute-sanitizer --tool memcheck --leak-check full --error-exitcode 1 ./run-smoke.sh
compute-sanitizer --tool initcheck --error-exitcode 1 ./run-smoke.sh
compute-sanitizer --tool racecheck --error-exitcode 1 ./run-smoke.sh
compute-sanitizer --tool synccheck --error-exitcode 1 ./run-smoke.sh

Memcheck detects invalid device memory accesses and can report leaked CUDA allocations when the context is destroyed. Initcheck detects reads of uninitialized device global memory. Racecheck checks shared-memory hazards, and synccheck checks misuse of supported synchronization primitives. Require clean reports and successful exit for valid input. For a deliberate startup failure, check its expected application exit and diagnostic as well as any sanitizer findings. Record which paths each run exercised. Reference comparisons still establish output correctness, and lifecycle tests still cover host resources such as file descriptors and camera mappings.

02

Record the design trade-offs

3 min read

Write a short retrospective for the release. For each decision, record the chosen implementation, the alternative considered, the evidence, and the condition that would change the choice. Tie the evidence to the target configuration and the same input used for the comparison. If an alternative was only inspected for feasibility, record what you inspected. That gives the next maintainer a clear starting point for a measurement.

For algorithm choice, consider a resize and normalization stage. A fused kernel can avoid writing and rereading an intermediate image. A separate resize stage may be easier to verify and can serve another consumer that needs the resized image. Explain which outputs the pipeline actually needs, then compare the complete paths with the same interpolation, border behavior, and output layout. Count any additional buffer access, format conversion, or synchronization at the stage boundaries. Record the maintenance cost of custom code alongside the measured result.

For precision, identify where the type changes. An inference engine configured to use FP16 where supported still needs validation of complete detections. Compare against a suitable FP32 baseline using representative scenes, including examples near score thresholds. Small differences in scores can affect which detections are published. If INT8 was evaluated, record the source of its quantization scales, such as a calibration dataset or an explicitly quantized model, and evaluate the result on separate representative input. Record the acceptance criteria and the actual results together. Latency and memory measurements are useful when the resulting detections meet the project's requirements.

For DLA versus GPU, begin with the board, model, and execution configuration. On a Jetson with DLA, check whether TensorRT can place the required layers on DLA at the chosen precision and shapes. If GPU fallback is enabled, inspect where the engine actually executes. Mixed execution can add transitions or reformats and can leave GPU inference work competing with preprocessing. A DLA configuration can be worthwhile if it frees enough GPU time for the rest of the pipeline. A GPU configuration can be preferable when the model maps poorly to DLA or when GPU execution yields better end-to-end behavior. Compare frame latency, sustained throughput, and dropped frames with capture and publishing active. Document power mode and any change in output quality. If the board lacks DLA, record the hardware limit and the GPU result.

Evidence for release choicesDecisionRequiredresultPipelineevidenceAlgorithmResize andnormalizeMatchingtensor valuesTraffic andlatencyPrecisionFP16 or INT8AcceptabledetectionsQuality andresource useInference deviceDLA or GPUSupportedexecutionPlacement andframe timing
Record the output requirement and the pipeline evidence behind each release choice.
Going deeperExplore the mechanism

When asked why you chose CUDA, VPI, or OpenCV for a stage, start with that stage's input and output. For resize and normalization, a defensible CUDA choice is a fused implementation that reads the GPU-accessible capture surface and writes the inference tensor directly. Show that the exact pixel conversion, layout, and normalization match the reference, then show what intermediate storage or synchronization the implementation actually avoids.

For a standard resize or remap, VPI is a candidate when the target backend supports the operation and accepts the required format and buffer path. Include any wrapping, conversion, or synchronization the backend requires in the comparison. For overlay on frames already on the CPU, an existing OpenCV CPU routine may have a simpler data path. If the frame is already GPU-resident, OpenCV CUDA is worth considering when the deployed build includes the needed operation and its stream can be coordinated with the pipeline. Explain where each stage runs, who owns each buffer, and where execution waits. If someone proposes a different implementation, identify the specific comparison that would settle the choice.

03

Package the project for a second operator

3 min read

The README.md should let another developer start from the release revision and reach a verified result. Record the supported board, system image or JetPack release, architecture, and build and runtime dependency versions. Document how to obtain the model and test input. If the engine is generated, include the exact build command and settings used to produce it. If you ship a serialized TensorRT engine, document its tested runtime and target and the procedure to rebuild it for a different environment.

Write the build and run commands in order, with the working directory and generated artifacts identified. Include a finite smoke run with a known input. Describe what counts as success, such as matching a reference detection file within the stated tolerances and returning success after cleanup. Then describe live operation separately, including the camera mapping or selector, output location, service account, and required device access. Include an example configuration with usable defaults where possible. List required keys and explain what the program reports when a value is missing or invalid. Use a fresh checkout on the documented target to check that the commands work without files left over from development.

A service package can ship the executable, installed startup script, unit file, example configuration, and README together. Have the startup script supply the documented configuration location and replace itself with the foreground program using exec. This preserves the process identity tracked by the service manager. For example, a package can install the application as /usr/local/bin/vision-pipeline and define its --config option as shown below. These names describe files and an option supplied by the project.

bash
#!/bin/sh
exec /usr/local/bin/vision-pipeline --config /etc/vision-pipeline/config.toml

Set the unit's ExecStart= to the installed script and its User= to the documented service account. Give that account access to the required camera, accelerator, and output directory. Have the application report when its configuration, input, and inference resources are ready. In a container package, the equivalent launcher can be the entrypoint. Document the compatible host runtime and required device mappings so the operator can reproduce the target's access.

Orderly shutdownReceiveSIGTERMStop frameadmissionDrain GPUworkClosepublisherReleasecaptureresourcesExitReceiveSIGTERMStop frameadmissionDrain GPUworkClosepublisherReleasecaptureresourcesExit
Stop submissions before draining GPU work and releasing the buffers it uses.

On SIGTERM, arrange for normal application code to perform cleanup. If you handle the signal with a handler, keep it limited to an async-signal-safe notification or a flag that normal code checks. Ensure that capture and worker waits can wake or return in time to observe the request. Calling CUDA, logging through ordinary library routines, or joining threads directly from a signal handler can interrupt code that holds internal locks. signal-safety(7)

Stop admitting frames and coordinate workers so no new GPU work is submitted. Drain outstanding work before releasing its buffers. Make the output policy explicit, such as publishing completed detections and discarding queued frames that never entered inference. Flush or close the publisher according to that policy, release resources in dependency order, and exit with a status that reflects the outcome. Set the service stop timeout from observed shutdown time and the operational deadline. If work stalls beyond that deadline, the manager may forcibly terminate the process. Count that outcome as a shutdown failure when reviewing the package.

Test a normal start and stop, a stop with a frame in flight, and a failed start with invalid configuration. Inspect the actual service logs and confirm that the next start can reopen the camera and produce output. Ask the second operator to record any undocumented step and add it to the README before release. The checklist and the module recap follows by bringing this handoff evidence together with the rest of the project review.

Key takeaways

  • Launch checks and completion checks detect different CUDA failures.
  • Compute Sanitizer covers exercised CUDA paths, while output checks and lifecycle tests cover other failure modes.
  • DLA and GPU choices depend on layer support and the behavior of the complete pipeline.
  • A startup script that uses exec lets the service manager signal the application directly.
Reflect
  1. Explain to a colleague, in two sentences: review CUDA kernel bounds, asynchronous errors, and resource ownership.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close