⚡️ Speed up method DPTImageProcessor._preprocess_segmentation_map by 12%
#876
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.
📄 12% (0.12x) speedup for
DPTImageProcessor._preprocess_segmentation_mapinsrc/transformers/models/dpt/image_processing_dpt.py⏱️ Runtime :
3.09 milliseconds→2.77 milliseconds(best of19runs)📝 Explanation and details
The optimization adds a fast-path early return for NumPy arrays in the
to_numpy_arrayfunction, which is frequently called during image preprocessing in the DPT model pipeline.Key optimization:
if isinstance(img, np.ndarray) and is_valid_image(img): return imgas the first checkto_numpy()function call for arrays that are already NumPy arraysWhy this works:
In the original code, even when
imgwas already anp.ndarray, it still went through theto_numpy()function which performs type checking and potential conversions. The line profiler shows that 49 out of 55 calls toto_numpy_arraywere hitting theto_numpy(img)path, taking 791,614 nanoseconds (41.5% of total time).Performance impact:
to_numpy_arrayexecution time from 1.91ms to 1.09ms (43% faster)_preprocess_segmentation_map, the call toto_numpy_arraydrops from 2.03ms to 1.34ms (34% faster)Test case benefits:
The annotated tests show consistent improvements across all scenarios, with 60-80% speedups for basic NumPy array inputs (which are the most common case in image processing workflows). PIL image inputs see minimal impact since they still follow the original conversion path.
This optimization is particularly effective because image preprocessing often works with arrays that are already in NumPy format from previous pipeline stages, making the fast-path the common case rather than the exception.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-DPTImageProcessor._preprocess_segmentation_map-mishac5land push.