Skip to content

Add in-place inference optimization - #1089

Merged
Borda merged 7 commits into
roboflow:developfrom
pirnerjonas:codex/low-memory-inplace-inference
Jun 27, 2026
Merged

Borda merged 7 commits into
roboflow:developfrom
pirnerjonas:codex/low-memory-inplace-inference

Conversation

@pirnerjonas

@pirnerjonas pirnerjonas commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds a supported low-memory inference-only path via optimize_for_inference(..., inplace=True).

  • Keeps the default inplace=False behavior unchanged: the loaded model is deep-copied before export, so remove_optimized_model() can still return the instance to the unoptimized state.
  • Adds an explicit destructive path for memory-constrained inference: inplace=True exports and casts the loaded module itself, stores it as model.inference_model, and clears model.model after optimization succeeds.
  • Rejects inplace=True with compile=True, since tracing would create another module and undermine the low-memory path.
  • Rejects non-floating dtypes before export/casting so failed calls do not mutate or clear the base model.
  • Documents the compile=False, inplace=True usage for detection and segmentation inference.

Issue

Closes #1080

Validation

  • One-off local CPU memory check with RFDETRNano(device="cpu"), compile=False, and isolated subprocesses:
default optimize_for_inference():          base=116.2 MB, inference=116.2 MB, retained tensors=232.4 MB
optimize_for_inference(inplace=True):      base=0.0 MB,   inference=116.2 MB, retained tensors=116.2 MB
approx retained model tensor storage saved: 116.2 MB

@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82%. Comparing base (df16add) to head (a49c15e).

❌ Your project check has failed because the head coverage (82%) is below the target coverage (95%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop   #1089    +/-   ##
========================================
+ Coverage       80%     82%    +2%     
========================================
  Files          110     110            
  Lines        11879   11901    +22     
========================================
+ Hits          9468    9748   +280     
+ Misses        2411    2153   -258     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@pirnerjonas
pirnerjonas marked this pull request as ready for review June 5, 2026 12:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a supported low-memory inference-only workflow by adding an inplace option to RFDETR.optimize_for_inference(), allowing optimization to reuse the already-loaded module (instead of deep-copying it) and freeing the base model reference to reduce peak/steady-state memory.

Changes:

  • Added inplace: bool = False to optimize_for_inference() with validation (inplace=True requires compile=False) and a new internal flag _optimized_inplace.
  • Implemented the destructive in-place inference optimization path that exports/casts the loaded module and clears self.model.model on success.
  • Added tests and documentation snippets demonstrating optimize_for_inference(compile=False, inplace=True) for memory-constrained inference.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
tests/models/test_optimize_for_inference.py Adds test coverage for new inplace behavior, error cases, and state flags.
src/rfdetr/detr.py Implements inplace optimization path, new _optimized_inplace state, and updated docs/errors.
docs/learn/run/segmentation.md Documents in-place optimization for memory-constrained segmentation inference.
docs/learn/run/detection.md Documents in-place optimization for memory-constrained detection inference.

Comment thread src/rfdetr/detr.py Outdated
Comment thread src/rfdetr/detr.py
Borda and others added 2 commits June 27, 2026 09:02
- Fix flag ordering: _optimized_inplace set before model.model=None so
  exception recovery sees correct state if failure occurs between the two
- Add RuntimeError guard for second optimize_for_inference() call after
  inplace (M6) — model.model is None, create a new instance
- Add export() guard: raises RuntimeError immediately after inplace instead
  of crashing on model.model.to("cpu")
- Change remove_optimized_model() after inplace from RuntimeError to
  UserWarning + no-op (M5), preserving optimized state
- Add is_optimized_inplace property (M4)
- Improve compile=True+inplace=True error message explaining why jit.trace
  retains weight storage refs
- Update predict() resolution/batch mismatch messages to hint "create new
  instance" after inplace instead of "call remove_optimized_model()"
- Docstring: note 1.5× transient peak for dtype conversion, export()
  mutation caveat, restructure Examples to show non-inplace path first
- Docs: add dtype="float16" to inplace snippet and irreversibility note
- Tests: update remove_optimized_model inplace test to expect UserWarning,
  add float32 no-op test, second-optimize guard test, mutation-not-undone
  test, and _optimized_has_been_compiled/_optimized_batch_size assertions

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
@Borda
Borda merged commit f8c3761 into roboflow:develop Jun 27, 2026
26 of 27 checks passed
@Borda Borda added the enhancement New feature or request label Jun 27, 2026
@Borda Borda mentioned this pull request Jun 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a low-memory RF-DETR inference-only optimization path

3 participants