⚡️ Speed up function is_box_near_crop_edge by 11%
#46
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.
📄 11% (0.11x) speedup for
is_box_near_crop_edgeinultralytics/models/sam/amg.py⏱️ Runtime :
4.17 milliseconds→3.75 milliseconds(best of166runs)📝 Explanation and details
The optimization achieves an 11% speedup through several targeted improvements that reduce tensor allocations and simplify broadcasting operations:
Key Optimizations Applied:
Eliminated unnecessary tensor indexing: Replaced
crop_box_torch[None, :]andorig_box_torch[None, :]with direct broadcasting. This removes the need to create new tensors with explicitNoneindexing since PyTorch's broadcasting handles the dimension expansion automatically.Simplified tensor creation in
uncrop_boxes_xyxy: Changed from creating a nested list[[x0, y0, x0, y0]]to a flat list[x0, y0, x0, y0], eliminating one level of tensor construction overhead. Also added proper dtype matching withdtype=boxes.dtype.Replaced
torch.as_tensor()withtorch.tensor(): While functionally similar for this use case,torch.tensor()can be slightly more efficient when creating new tensors from lists.Used
torch.logical_not()instead of~operator: This provides a more explicit logical negation that can be better optimized by PyTorch's internal operations.Performance Impact:
The line profiler shows the most significant improvements in the
torch.isclose()operations (39.5% vs 38% and 15.3% vs 16.1% of total time), indicating that removing the[None, :]indexing reduces computational overhead. Theuncrop_boxes_xyxyfunction also shows improvement with the simplified offset tensor creation.Workload Implications:
Given the function reference showing
is_box_near_crop_edgeis called within a hot path in SAM's image segmentation pipeline (inside nested loops processing multiple crop regions and point batches), this 11% improvement will compound significantly. The function is used to filter out bounding boxes near crop edges, which happens for every batch of points processed across multiple image crops, making this optimization valuable for real-time segmentation workloads.Test Case Performance:
The optimization shows consistent 7-18% improvements across all test cases, with larger gains on simpler cases (empty tensors, far-from-edge boxes) and smaller but still meaningful gains on complex cases with many boxes, indicating the optimization is broadly applicable.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-is_box_near_crop_edge-mirazvrnand push.