⚡️ Speed up method AbstractDataset._read_sample by 5%
#3
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.
📄 5% (0.05x) speedup for
AbstractDataset._read_sampleindoctr/datasets/datasets/pytorch.py⏱️ Runtime :
6.14 milliseconds→5.85 milliseconds(best of40runs)📝 Explanation and details
The optimized code achieves a 5% speedup through three key optimizations:
1. Selective deepcopy elimination in
_read_sample:The original code always performed
deepcopy(target)regardless of target type. The optimization only deepcopies whentargetis adict(which may contain mutable objects), while immutable types likestr,tuple, andnp.ndarrayare returned directly. This eliminates expensive deep copying operations for ~75% of cases, as shown by the 8-12% speedup in tuple test cases.2. Conditional RGB conversion in
read_img_as_tensor:Instead of always calling
pil_img.convert("RGB"), the code now checksif pil_img.mode != "RGB"first. For images already in RGB format (the majority case), this avoids unnecessary pixel data copying and reallocation. The line profiler shows this reduces the conversion overhead from 4.4% to 4.0% of total time.3. Optimized contiguity check in
tensor_from_numpy:Rather than always calling
.contiguous()afterpermute(), the code now checksif not img.is_contiguous()first. PyTorch'spermute()often produces contiguous tensors, so this avoids redundant memory operations when the tensor is already contiguous.Performance characteristics:
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AbstractDataset._read_sample-mg7iujvzand push.