Skip to content

refine(detection): count dense mask overlaps on bit-packed masks - #2886

Merged
Borda merged 20 commits into
roboflow:developfrom
SajjadPSavoji:fix-2845-feature-bit-packed-dense
Nov 26, 2026
Merged

Borda merged 20 commits into
roboflow:developfrom
SajjadPSavoji:fix-2845-feature-bit-packed-dense

Conversation

@SajjadPSavoji

Copy link
Copy Markdown
Contributor

Description

Dense mask IoU and NMM cast the masks to float32 copies, which is 32x the size of the bits. _group_overlapping_masks also redoes that cast on every inner iteration. Now _mask_iou_batch_split and a new _group_overlapping_packed_masks pack the masks with np.packbits, view them as uint64 and count with np.bitwise_count. Counts are exact integers and go through the same IoU/IoS division, so results are identical.

The packed path only runs on NumPy >= 2.0 with bool masks. Older NumPy and non-bool masks keep the original matmul and logical_or.reduce code. Masks over 2**24 pixels still use float64 counts. CompactMask is untouched.

Motivation and Context

Fixes #2845. The approach is from @Connoravila1.

Changes Made

  • _pack_masks, _count_pixels and _overlap_from_areas helpers in iou_and_nms.py
  • packed intersection in _mask_iou_batch_split, skipping words that are empty in either set
  • _group_overlapping_packed_masks keeps the merge candidate packed between steps
  • changelog entry

One thing I left as is: the intersection loop runs over the rows of the first set in Python and vectorizes across the second.

Apple M-series, NumPy 2.5.4, OPENBLAS_NUM_THREADS=1, develop to this change:

masks size IoU (ms) IoU peak (MiB) NMM (ms)
50 480x640 39 to 9 117 to 7 155 to 4
100 480x640 112 to 33 235 to 15 545 to 12
100 720x1280 414 to 118 703 to 44 1711 to 42

Testing

New TestBitPackedMaskOverlap in tests/detection/utils/test_iou_and_nms.py. test_mask_iou_batch_matches_fallback checks IoU and IoS against the matmul path (empty sets, all-False, all-True, pixel counts not a multiple of 8 or 64). test_mask_non_max_merge_matches_fallback checks NMM groups against the original loop. There are also tests for float masks in NMM, NMS keeps, Soft-NMS scores and exact counts above 2**24 pixels.

I ran pytest tests/detection/utils/test_iou_and_nms.py tests/detection/test_compact_mask_iou.py plus ruff check and ruff format --check on the two touched files, all clean. A 400-case fuzz against develop also gave array_equal IoU/IoS with the same dtype and identical NMM groups.

  • Added/updated tests, and the full suite passes locally
  • Updated docs (docstrings / mkdocs entry) for new or changed public API
  • Added a changelog entry in docs/changelog.md under Unreleased (skip for lint/type/format-only or pure doc changes)

Additional Notes

The IoU speedup will be smaller on many-core machines with a fast multithreaded BLAS. The memory drop and the NMM gain don't depend on BLAS.

@Borda
Borda requested a balanced review from Copilot November 5, 2026 11:29
@Borda Borda added the bug Something isn't working label Nov 5, 2026
@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95%. Comparing base (9290d6d) to head (a471de4).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2886   +/-   ##
=======================================
  Coverage       95%     95%           
=======================================
  Files           84      84           
  Lines        16343   16408   +65     
=======================================
+ Hits         15601   15669   +68     
+ Misses         742     739    -3     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

🟡 Changes recommended

The chunk planner still budgets float mask copies instead of packed buffers, causing unnecessary chunking, misleading memory warnings, and repeated packing of detections in memory-limited calls.

1 open issue
What changed in this PR

This PR optimizes Supervision’s dense boolean mask overlap calculations using bit-packed masks on NumPy ≥ 2.0, addressing #2845 without changing the public API.

Changes:

  • Adds packed intersection counting and keeps merge candidates packed during non-max merging.
  • Preserves fallback behavior for older NumPy and non-boolean masks; leaves CompactMask unchanged.
  • Adds parity and edge-case tests plus a performance changelog entry.
File Description
tests/​detection/​utils/​test_iou_and_nms.py Tests packed/fallback parity, suppression, merging, and large-mask counts.
src/​supervision/​detection/​utils/​iou_and_nms.py Implements bit-packed overlap and merge paths with shared overlap calculation.
docs/​changelog.md Documents the optimization, compatibility, and reported performance gains.

Review effort: Balanced

Borda and others added 2 commits November 5, 2026 10:52
Changes:
- Incorporate target changes to annotation, mask, dataset, geometry, and image utilities and their tests.
- Preserve the packed mask implementation and both sets of changelog entries.

Impact:
- Keep the PR compatible with the current target while retaining its dense mask optimization.

Verification:
- Focused NMS and compact mask IoU tests: 310 passed.
- Staged merge diff check passed.

Residual limits:
- Full suite has not been rerun on the merge; selected review findings remain open.

---

Co-authored-by: Codex <[email protected]>
Borda and others added 4 commits November 5, 2026 11:16
Changes:
- Budget packed mask buffers and reuse packed detections across chunks.
- Add regressions for warning floors, noncontiguous masks, and repeated packing.

Impact:
- Avoid false memory warnings and repeated detection packing in memory-limited calls.

Verification:
- Full test suite: 6503 passed, 247 skipped.
- All pre-commit hooks and diff check passed.

Residual limits:
- Peak memory and performance across representative workloads were not benchmarked.
- The original parallel handover remains incomplete; its worktrees are preserved.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Link the packed mask changelog entry to PR roboflow#2886.

Impact:
- Readers can trace the change to its pull request.

Verification:
- All pre-commit hooks and diff check passed.
- Full test suite: 6503 passed, 247 skipped.

Residual limits:
- The original parallel handover remains incomplete; its worktrees are preserved.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Retain the PR author’s packed-overlap helper and regression alongside the local chunk planner and layout-aware warning checks.
- Preserve both upstream and local mask overlap tests.

Impact:
- Integrate the current PR head without losing detection reuse or memory-limit behavior.

Verification:
- Full test suite: 6504 passed, 247 skipped.
- All pre-commit hooks and staged diff check passed.
- Independent merge challenge found no correctness defect.

Residual limits:
- Peak memory and performance across representative workloads were not benchmarked.
- The earlier parallel remediation lifecycle remains incomplete and its evidence is preserved.

---

Co-authored-by: Codex <[email protected]>
@Borda Borda added enhancement New feature or request and removed bug Something isn't working labels Nov 5, 2026
@Faris-as

Faris-as commented Nov 7, 2026

Copy link
Copy Markdown

Hi @SajjadPSavoji @SkalskiP,

Great work on this PR—leveraging np.packbits and np.bitwise_count for NumPy 2.0+ is a massive improvement for dense mask workloads.

Looking through the implementation and the chunking behavior, I noticed a few high-impact memory and vectorization optimizations that could make this even faster and cleaner:

  1. Detection word re-filtering & allocation thrashing in the chunk loop:
    In _packed_mask_iou_batch:

    used = wa.any(0) & wb.any(0)
    wa, wb = np.ascontiguousarray(wa[:, used]), np.ascontiguousarray(wb[:, used])

    When masks_true is chunked, this function runs once per chunk. Slicing and calling np.ascontiguousarray on detection_words inside each chunk iteration causes repeated memory allocations for the entire detection set. Filtering/pruning detection_words once before the chunk loop avoids this overhead.

  2. Python row loop overhead during intersection counting:

    inter = np.stack([np.bitwise_count(row & detection_words).sum(1) for row in true_words])

    Running a Python list comprehension across all rows in true_words incurs noticeable interpreter overhead when N is large. Micro-batching true_words in blocks of e.g. 16 or 32 rows and broadcasting (B, 1, K) & (1, M, K) vectorizes the bitwise popcount across both dimensions in SIMD C-speed with minimal peak memory footprint.

  3. Chunk step calculation & false memory warnings:
    Subtracting the full output_bytes (N * M * 8) directly from limit_bytes when computing step can over-constrain the chunk size down to step = 1 and trigger premature OOM warnings even when the active working buffers are well within budget.

  4. Merge conflicts:
    The branch currently has conflicts with develop.

@SajjadPSavoji, are you planning to incorporate these optimizations and rebase on develop? If you are busy or prefer, I would be happy to take over from here, resolve the conflicts, and help push this PR across the finish line!

@SajjadPSavoji

Copy link
Copy Markdown
Contributor Author

the chunk budgeting and the develop merge are already in from Borda's commits, so I'll leave it with the maintainers from here. the other two tweaks are probably better as a separate PR

@CLAassistant

CLAassistant commented Nov 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@SajjadPSavoji

Copy link
Copy Markdown
Contributor Author

@Borda @SkalskiP CLA is signed now. anything else you'd like changed on my end before this can go in?

Borda and others added 6 commits November 24, 2026 20:19
- perf(detection): keep float matmul unless packed IoU is needed
- perf(detection): reduce packed detections once per mask IoU call
- fix(detection): warn on packed buffers, not float size, for bool masks
- fix(detection): count pack and pad buffers in the memory floor
- fix(detection): validate mask ndim in packed non-max merge
- refactor(detection): share one greedy mask merging driver
- style(detection): align packed mask docstrings and constants

[resolve group] PR roboflow#2886 — items 3 2 9 10 11 12 16

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- test(detection): cover packed mask gate and mixed dtype pairs
- test(detection): test packed masks on random layouts and chunks

[resolve group] PR roboflow#2886 — items 13 14

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
[resolve group] PR roboflow#2886 — items 15

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Borda and others added 2 commits November 26, 2026 11:54
Changes:
- Merge the current develop branch and preserve packed-mask tests in the reorganized IoU test module.

Impact:
- The PR retains its packed-mask behavior alongside the current base and test organization.

Verification:
- IoU and suppression tests: 350 passed.
- Staged merge diff check passed.

Residual limits:
- Full project checks and carried-forward remediation remain pending.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Remove unused fallback branches from the private packed overlap helper and clarify its required inputs.
- Test packed overlap parity and chunk sizing for non-contiguous true masks.

Impact:
- Packed overlap retains its behavior with fewer unreachable branches and a regression check for reshape-copy budgeting.

Verification:
- Full suite: 8546 passed, 301 skipped.
- Configured Ruff, format, mypy, and scoped diff checks passed.
- Independent review found no correctness defects and its test and documentation observations were addressed.

Residual limits:
- OpenCV was unavailable locally; the suite used the NumPy fallback.

---

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Codex <[email protected]>
@Borda
Borda force-pushed the fix-2845-feature-bit-packed-dense branch from b189596 to a471de4 Compare November 26, 2026 11:22
@Borda
Borda merged commit 1ac6c82 into roboflow:develop Nov 26, 2026
38 checks passed
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.

[Feature]: Bit-packed dense mask IoU and NMM: identical results, ~20x less memory, 20-47x faster mask NMM

5 participants