feat(cookbooks): add inference latency benchmark notebook - #1152
Merged
Merged
Conversation
- New `inference-latency-benchmark.ipynb` benchmarks FP32 / FP16+JIT / ONNX across detection (RFDETRMedium), segmentation (RFDETRSegSmall), and keypoint (RFDETRKeypointPreview); downloads COCO-128 from Universe for sample images; CUDA event timing - `cards.yaml`: add benchmark card with INFERENCE / ONNX / GPU labels - `export/_onnx/inference.py`: fix silent CPU fallback in `_create_onnx_session` — now explicitly selects CUDAExecutionProvider when available; warns when falling back to CPU - `export/main.py`: add `weights_only=False` to `torch.load()` for PyTorch ≥2.6 compatibility; relax `strict=True` → `strict=False` to match checkpoint key handling in r-flow - `detr.py`: switch `predict()` decorator to `@torch.inference_mode()`; batch GPU transfer, resize, and normalize outside per-image loop; update warning to mention `optimize_for_inference(dtype=torch.float16)` --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
`folder` is invalid for object-detection projects; switch to `coco`. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR adds a new cookbooks notebook to benchmark RF-DETR inference latency (FP32 vs FP16+JIT vs ONNX Runtime) and includes supporting runtime/export tweaks to improve inference throughput and make ONNX execution provider selection explicit.
Changes:
- Add a new cookbook notebook for GPU latency/FPS benchmarking across detection, segmentation, and keypoint models, and surface it via a new cookbooks card.
- Update ONNX Runtime session creation to prefer CUDAExecutionProvider and warn when falling back to CPU.
- Optimize
RFDETR.predict()for inference (switch totorch.inference_mode()and batch preprocessing) and adjust export CLI checkpoint loading behavior.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
src/rfdetr/export/main.py |
Adjusts checkpoint loading (torch.load) and relaxes load_state_dict strictness during export resume. |
src/rfdetr/export/_onnx/inference.py |
Explicitly selects ONNX Runtime providers (CUDA preferred) and logs providers in use. |
src/rfdetr/detr.py |
Switches predict() to inference mode and refactors preprocessing to batch operations. |
docs/cookbooks/inference-latency-benchmark.ipynb |
New benchmark notebook measuring latency/FPS across FP32, FP16+JIT, and ONNX. |
docs/cookbooks/cards.yaml |
Adds a new cookbook card linking to the benchmark notebook. |
Roboflow export is async — zip not ready on first download call. For a latency benchmark image content is irrelevant; switch to numpy random 640×640 RGB images. Removes roboflow + API-key dependency from notebook. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- Extracted ONNX export logic to `_export_onnx`. - Generalized ONNX runtime benchmarking to support multiple providers. - Replaced plain output formatting with a pandas DataFrame for cleaner summary display. - Added `pandas` as a dependency.
…sing - Add `_onnx_runtime(path, image, providers, warmup, runs)` to `export/_onnx/inference.py` — returns `(mean_ms, std_ms, provider_label)`; raises RuntimeError if requested provider fell back silently (fixes double "ONNX (CPU)" rows in benchmark output) - Extract `_preprocess_pil_to_nchw` — eliminates duplicated ImageNet normalize+NCHW block shared between `_run_inference` and `_onnx_runtime` - Extend `_create_onnx_session` with optional `providers` param; explicit list bypasses auto-selection - Cookbook: remove `_onnx_rt` wrapper; import `_onnx_runtime` directly from package; ONNX providers loop replaces two separate calls --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
CUDA RuntimeError was aborting the entire ONNX loop — CPU result survived but CUDA row was silently dropped. Now each provider has its own try/except so CPU and CUDA failures are independent and clearly labelled. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
… provider torch.cuda.is_available() can be True while onnxruntime-gpu is absent — ORT then silently uses CPU for a CUDA-requested session, producing duplicate ONNX (CPU) rows. Raise immediately on provider mismatch so the caller (cookbook torch.cuda check skips no-GPU, this raises missing-package). --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…pu on Colab Colab pre-installs onnxruntime (CPU-only); pip install onnxruntime-gpu leaves both installed and ORT picks CPU. Uninstall both first to ensure GPU build wins. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…ark starts Fail fast in section 2 if onnxruntime-gpu is absent or CPU-only build is active, with a clear fix command — avoids silent CPU fallback mid-run. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
… notebook Removed an outdated RF-DETR copyright header block from the notebook to streamline its content.
--- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…check Switch install cell to onnxruntime-cuda-12 index (PyPI default is CUDA 11.8 build which silently falls back on Colab CUDA 12.8). Remove broken session probe — _onnx_runtime already raises clearly on provider init failure. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Add explanatory paragraphs to all 8 markdown sections in inference-latency-benchmark — covering CUDA-12 index rationale, warmup/measurement runs, synthetic image equivalence, CUDA event timing accuracy, FP32/FP16+JIT/ONNX path tradeoffs, provider loop design, model family task-complexity breakdown, and how to read the FPS summary table. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Add explanatory paragraphs to all 8 markdown sections in inference-latency-benchmark — covering CUDA-12 index rationale, warmup/measurement runs, synthetic image equivalence, CUDA event timing accuracy, FP32/FP16+JIT/ONNX path tradeoffs, provider loop design, model family task-complexity breakdown, and how to read the FPS summary table. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…puts - detr.py: move per-image .to(device) inside loop and resize before torch.stack; previous batch-first approach raised RuntimeError when images had different sizes - export/main.py: add missing-key warning for strict=False load; add explanatory comment for weights_only=False matching pattern at detr.py:354 - export/_onnx/inference.py: fix _onnx_rt -> _onnx_runtime in docstring example; pass channels from ONNX metadata to _preprocess_pil_to_nchw; remove unverified CUDA sync claim from _onnx_runtime docstring; fix broken session example; add section comment marking _onnx_runtime as benchmarking-only --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Codecov Report❌ Patch coverage is ❌ Your patch check has failed because the patch coverage (16%) is below the target coverage (95%). You can increase the patch coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## develop #1152 +/- ##
=======================================
- Coverage 82% 81% -0%
=======================================
Files 110 110
Lines 11459 11488 +29
=======================================
Hits 9350 9350
- Misses 2109 2138 +29 🚀 New features to boost your workflow:
|
…no-any-return `np.ndarray.__getitem__(np.newaxis)` returns `Any` in numpy stubs; `np.expand_dims` is fully typed, resolving the `no-any-return` error at `_preprocess_pil_to_nchw` line 122. --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
inference-latency-benchmark.ipynbbenchmarks FP32 / FP16+JIT / ONNX across detection (RFDETRMedium), segmentation (RFDETRSegSmall), and keypoint (RFDETRKeypointPreview); downloads COCO-128 from Universe for sample images; CUDA event timingcards.yaml: add benchmark card with INFERENCE / ONNX / GPU labelsexport/_onnx/inference.py: fix silent CPU fallback in_create_onnx_session— now explicitly selects CUDAExecutionProvider when available; warns when falling back to CPUexport/main.py: addweights_only=Falsetotorch.load()for PyTorch ≥2.6 compatibility; relaxstrict=True→strict=Falseto match checkpoint key handling in r-flowdetr.py: switchpredict()decorator to@torch.inference_mode(); batch GPU transfer, resize, and normalize outside per-image loop; update warning to mentionoptimize_for_inference(dtype=torch.float16)Additional Context