⚡️ Speed up method MraSparseDenseMatMul.forward by 77%
#112
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.
📄 77% (0.77x) speedup for
MraSparseDenseMatMul.forwardinsrc/transformers/models/mra/modeling_mra.py⏱️ Runtime :
99.9 microseconds→56.5 microseconds(best of12runs)📝 Explanation and details
The optimization achieves a 76% speedup by reducing redundant attribute access and improving tensor operations:
Key Optimizations:
Shape Caching: Instead of calling
.size()multiple times on tensors (which creates new tuples each time), the code caches tensor shapes once with.shapeand reuses them. This eliminates repeated method calls and tuple creation overhead.Efficient Tensor Reshaping: Replaced
.reshape()with.view()for the dense_key transformation. Since the tensor is already made contiguous later,.view()is faster as it avoids unnecessary memory allocations when possible.Streamlined Validation: Consolidated dimension checks using cached shapes (e.g.,
sq_shape[2]instead ofsparse_query.size(2)), reducing method call overhead in validation logic.Optimized Method Chaining: Combined
indices.int()and.contiguous()into a single chained operation, reducing intermediate tensor creation.Performance Impact by Test Case:
The optimizations are particularly effective for validation-heavy code paths and functions called frequently in ML pipelines, where minimizing method call overhead compounds significantly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-MraSparseDenseMatMul.forward-mhjwkggkand push.