⚡️ Speed up method PositionEmbeddingSine.encode_points by 30% - #96
Open
codeflash-ai[bot] wants to merge 1 commit into
Open
⚡️ Speed up method PositionEmbeddingSine.encode_points by 30%#96codeflash-ai[bot] wants to merge 1 commit into
PositionEmbeddingSine.encode_points by 30%#96codeflash-ai[bot] wants to merge 1 commit into
Conversation
The optimization achieves a **29% speedup** by replacing expensive tensor operations with more memory-efficient direct allocation and assignment patterns. **Key optimizations:** 1. **Eliminated `torch.stack().flatten()` operations**: The original code used `torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1)` which creates intermediate tensors and performs expensive reshape operations. The optimized version pre-allocates output tensors with `torch.empty()` and directly assigns values using slice operations (`px[:, 0::2] = sin_x`, `px[:, 1::2] = cos_x`). 2. **Separated sin/cos computations**: Instead of computing sin/cos within the stack operation, the optimized version computes them separately (`sin_x = pos_x[:, 0::2].sin()`), allowing for better memory locality and avoiding redundant computations. 3. **Direct memory assignment**: Using pre-allocated tensors and slice assignment is significantly faster than tensor concatenation and reshaping operations, especially for larger tensors. **Performance impact from test results:** - **Small inputs** show modest slowdowns (3-6% in basic tests) due to the overhead of separate allocations, but this is negligible in absolute terms (microseconds). - **Large-scale tests** show substantial improvements: 77% faster for 100x100 batches, 33% faster for large embedding dimensions, and 32% faster for stress tests with maximum memory usage. The optimization is particularly effective for the SAM (Segment Anything Model) use case where position embeddings are computed for large batches of image coordinates, making this a valuable improvement for computer vision workloads that process many spatial positions simultaneously.
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.
📄 30% (0.30x) speedup for
PositionEmbeddingSine.encode_pointsinultralytics/models/sam/modules/blocks.py⏱️ Runtime :
30.3 milliseconds→23.3 milliseconds(best of81runs)📝 Explanation and details
The optimization achieves a 29% speedup by replacing expensive tensor operations with more memory-efficient direct allocation and assignment patterns.
Key optimizations:
Eliminated
torch.stack().flatten()operations: The original code usedtorch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1)which creates intermediate tensors and performs expensive reshape operations. The optimized version pre-allocates output tensors withtorch.empty()and directly assigns values using slice operations (px[:, 0::2] = sin_x,px[:, 1::2] = cos_x).Separated sin/cos computations: Instead of computing sin/cos within the stack operation, the optimized version computes them separately (
sin_x = pos_x[:, 0::2].sin()), allowing for better memory locality and avoiding redundant computations.Direct memory assignment: Using pre-allocated tensors and slice assignment is significantly faster than tensor concatenation and reshaping operations, especially for larger tensors.
Performance impact from test results:
The optimization is particularly effective for the SAM (Segment Anything Model) use case where position embeddings are computed for large batches of image coordinates, making this a valuable improvement for computer vision workloads that process many spatial positions simultaneously.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-PositionEmbeddingSine.encode_points-mj9u30kzand push.