⚡️ Speed up function get_optimal_tiled_canvas by 117%
#396
+18
−8
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.
📄 117% (1.17x) speedup for
get_optimal_tiled_canvasinsrc/transformers/models/got_ocr2/image_processing_got_ocr2.py⏱️ Runtime :
129 milliseconds→59.5 milliseconds(best of76runs)📝 Explanation and details
The optimization achieves a 117% speedup by fundamentally changing the algorithm in
get_all_supported_aspect_ratiosfrom a brute-force nested loop approach to a more efficient factorization-based method.Key Optimization - Algorithm Change:
Specific Changes:
width * height <= max_image_tilesfor all combinations, the optimized version iterates through each valid tile count and finds its divisor pairs using modulo operationsmax_image_tiles, this dramatically reduces the number of operationsget_optimal_tiled_canvas:twice_target_patch_areato avoid repeated multiplicationw, h = gridfor cleaner variable accessPerformance Impact:
The optimization is particularly effective for large tile ranges, as evidenced by test results showing 2356% speedup for
test_min_tiles_equals_max_tiles_largeand 125% speedup for large-scale performance tests. The factorization approach scales much better than the quadratic nested loop.Hot Path Context:
Based on
function_references,get_optimal_tiled_canvasis called fromcrop_image_to_patchesandget_number_of_image_patches- critical image processing functions that likely process multiple images in batch operations. This optimization will significantly improve throughput for OCR workloads that process many images with varying tile configurations.Test Case Benefits:
The optimization excels particularly in scenarios with large
max_image_tilesvalues (500-1000 range), showing 72-125% improvements, while maintaining correctness for all edge cases and basic functionality.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_optimal_tiled_canvas-miafdgveand push.