⚡️ Speed up function compute_expand_dims_output_shape by 372%
#212
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.
📄 372% (3.72x) speedup for
compute_expand_dims_output_shapeinkeras/src/ops/operation_utils.py⏱️ Runtime :
4.48 milliseconds→947 microseconds(best of79runs)📝 Explanation and details
The key optimization is converting the
axislist to asetbefore the list comprehension that builds the new shape. This changes the axis membership test from O(n) to O(1) complexity.What changed:
axis_set = set(axis)after canonicalizing axesax in axistoax in axis_setin the list comprehensionWhy it's faster:
In the original code, for each position in
range(out_ndim), Python searches through the entireaxislist to check membership. With many axes or large output dimensions, this becomes expensive. Converting to a set provides constant-time lookups instead of linear searches.Performance impact:
The optimization shows dramatic speedups for cases with many axes:
Function usage context:
Based on the function references,
compute_expand_dims_output_shapeis called from:expand_dimsoperation (hot path for tensor operations)The optimization particularly benefits tensor operations that expand multiple dimensions simultaneously, which can occur frequently in neural network architectures that need to broadcast or reshape tensors across multiple axes.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-compute_expand_dims_output_shape-mjafsocrand push.