perf(RandCropBoxByPosNegLabeld): avoid N-fold mask allocation in randomize#8993
perf(RandCropBoxByPosNegLabeld): avoid N-fold mask allocation in randomize#8993aymuos15 wants to merge 3 commits into
Conversation
…omize Replace convert_box_to_mask + amax with direct per-box slicing into a single (1,H,W,D) union mask. This eliminates the (N_boxes,H,W,D) int16 intermediate, reducing peak memory and improving randomize() throughput by ~2-3x on typical 3D volumes. - randomize(): 2.05-2.95x speedup (3 configs, interleaved medians) - full __call__: 1.81-2.49x speedup - Numerics: bit-identical (mask, indices, centers all equal) - Peak RSS: unchanged (fg/bg index arrays dominate) Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
📝 WalkthroughWalkthrough
Estimated code review effort: 2 (Simple) | ~10 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
monai/apps/detection/transforms/dictionary.py (1)
1157-1163: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider iterable unpacking per RUF005.
Ruff flags two concatenation patterns that could use unpacking for clarity.
♻️ Optional refactor
- mask_img = np.zeros((1,) + tuple(image_size), dtype=np.int16) + mask_img = np.zeros((1, *tuple(image_size)), dtype=np.int16)- slicing = (0,) + tuple( - slice(extended_boxes_np[b, d], extended_boxes_np[b, d + spatial_dims]) for d in range(spatial_dims) - ) + slicing = (0, *tuple( + slice(extended_boxes_np[b, d], extended_boxes_np[b, d + spatial_dims]) for d in range(spatial_dims) + ))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@monai/apps/detection/transforms/dictionary.py` around lines 1157 - 1163, Update the tuple construction in the mask-building loop to use iterable unpacking instead of concatenating the leading `(0,)` tuple with the generated slice tuple, resolving the RUF005 warning while preserving the existing `mask_img` indexing behavior.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@monai/apps/detection/transforms/dictionary.py`:
- Around line 1157-1163: Update the tuple construction in the mask-building loop
to use iterable unpacking instead of concatenating the leading `(0,)` tuple with
the generated slice tuple, resolving the RUF005 warning while preserving the
existing `mask_img` indexing behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ad894203-292e-4393-874c-6c47e55e3882
📒 Files selected for processing (1)
monai/apps/detection/transforms/dictionary.py
…ransforms Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
Description
RandCropBoxByPosNegLabeld.randomizebuilds a foreground/background mask when precomputed indices are not available. The previous implementation calledconvert_box_to_maskfor each box (creating an N-channel stacked mask) then reduced withnp.amaxto a single channel, allocating an (N_boxes, H, W, D) int16 intermediate that grows linearly with the number of boxes.The fix paints directly into a single (1, H, W, D) union mask by iterating over each extended box and setting
mask[0, box_slices] = 1.Changes
monai/apps/detection/transforms/dictionary.pyRemove the now-unused import of
convert_box_to_maskfrommonai.apps.detection.transforms.box_ops.Replace the
convert_box_to_mask+np.amax(...)[0:1]block inrandomize()with direct slicing into a pre-allocated zero mask.Performance
Benchmarked old (
convert_box_to_mask+np.amax) vs new (direct slicing) implementations on synthetic 3D volumes with random boxes (spatial_size=(64,64,64),num_samples=4,pos=1,neg=1,whole_box=True).System specs
randomize()onlyFull
__call__()Types of changes
./runtests.sh -f -u --net --coverage../runtests.sh --quick --unittests --disttests.make htmlcommand in thedocs/folder.