⚡️ Speed up function compute_pooling_output_shape by 554%
#159
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.
📄 554% (5.54x) speedup for
compute_pooling_output_shapeinkeras/src/ops/operation_utils.py⏱️ Runtime :
726 microseconds→111 microseconds(best of22runs)📝 Explanation and details
The optimized code achieves a 554% speedup by introducing a fast path for integer-only dimensions that avoids NumPy overhead entirely.
Key optimizations:
Conditional NumPy usage: Instead of always converting inputs to NumPy arrays, the code first checks if any spatial dimensions are
None. When all dimensions are known integers (the common case), it performs calculations using native Python integer arithmetic, which is much faster for small arrays.Eliminated unnecessary array conversions: The original code created
np.array(input_shape),np.array(pool_size), and performed expensive NumPy operations likenp.floor()and division even for simple cases. The optimized version uses//(integer division) and basic arithmetic when possible.Reduced memory allocations: Changed
input_shape_origin = list(input_shape)toinput_shape_origin = tuple(input_shape)to avoid an unnecessary list creation, and only creates NumPy arrays whenNonedimensions are present.Performance impact by use case:
Nonedimensions): Take the fast integer-only path, showing 4-7x speedups across test casesNonedimensions): Still use NumPy but with more efficient array creation usingdtype=np.intpandnp.floor_divideHot path significance: This function is called from pooling layers'
compute_output_shape()and ops'compute_output_spec()methods, making it critical for model compilation and shape inference. The optimization particularly benefits common CNN architectures where pooling shapes are typically known at compile time, allowing the fast integer-only path to be used consistently.The optimizations maintain identical behavior while dramatically reducing computational overhead for the most frequent use cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-compute_pooling_output_shape-mireyo77and push.