⚡️ Speed up function nms_by_containment by 741%#34
Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Open
⚡️ Speed up function nms_by_containment by 741%#34codeflash-ai[bot] wants to merge 1 commit intomainfrom
nms_by_containment by 741%#34codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **741% speedup** by eliminating expensive object allocations and algorithmic inefficiencies in two critical functions used for table structure refinement. ## Key Optimizations ### 1. **Eliminated Rect Object Overhead in `slot_into_containers`** (58.6% → 0% of total time) The original code created 3 `Rect` objects per container-package pair (240K+ allocations in large tests). The optimized version: - Pre-extracts container bboxes once: `container_bboxes = [container["bbox"] for container in container_objects]` - Computes intersections with inline arithmetic instead of `Rect.intersect()` calls - Calculates areas directly: `pkg_w * pkg_h` instead of `package_rect.get_area()` This alone eliminates the 58.6% bottleneck from the line profiler. ### 2. **Removed O(N log N) Sort Per Package** (3.5% → eliminated) The original code sorted all match scores for every package to find the best match. The optimized version: - Tracks the best container with a simple max search during iteration - No intermediate list of match dictionaries or `sort_objects_by_score()` calls - Direct comparison: `if overlap_fraction > best_score` This removes ~630 sorting operations in typical workloads. ### 3. **Set Construction Optimization in `nms_by_containment`** The original code constructed sets repeatedly in nested loops: ```python object2_packages = set(packages_by_container[object2_num]) # in outer loop object1_packages = set(packages_by_container[object1_num]) # in inner loop ``` The optimized version precomputes all sets once: ```python package_sets_by_container = [set(pkgs) for pkgs in packages_by_container] ``` This reduces ~26K set constructions to ~700 in large-scale tests (97% reduction). ### 4. **Early Exit with `break` and `continue`** - Added `break` after finding intersection in inner loop (no need to check remaining containers) - Added `continue` after marking suppression for empty packages These micro-optimizations reduce unnecessary iterations in dense scenarios. ## Performance Impact by Test Case The optimization excels in scenarios with: - **Many containers × many packages** (795% speedup in 100×100 test): Intersection calculation improvements dominate - **Dense overlapping containers** (367-706% speedup): Set precomputation and early exits shine - **One-to-one mappings at scale** (763% speedup in 200×200 test): Sorting elimination is critical Even small workloads see 60-100% speedups due to reduced object creation overhead. ## Production Context Based on `function_references`, this optimization is in the **hot path** for table structure detection: - Called by `refine_rows()` and `refine_columns()` for every table processed - Operates on detected rows/columns and tokens (typically 50-200 objects per table) - Runs on every document page with tables The 741% speedup directly translates to faster document processing pipelines, especially for documents with complex table structures or batch processing workloads where this function is called hundreds of times.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
📄 741% (7.41x) speedup for
nms_by_containmentinunstructured_inference/models/table_postprocess.py⏱️ Runtime :
232 milliseconds→27.6 milliseconds(best of51runs)📝 Explanation and details
The optimized code achieves a 741% speedup by eliminating expensive object allocations and algorithmic inefficiencies in two critical functions used for table structure refinement.
Key Optimizations
1. Eliminated Rect Object Overhead in
slot_into_containers(58.6% → 0% of total time)The original code created 3
Rectobjects per container-package pair (240K+ allocations in large tests). The optimized version:container_bboxes = [container["bbox"] for container in container_objects]Rect.intersect()callspkg_w * pkg_hinstead ofpackage_rect.get_area()This alone eliminates the 58.6% bottleneck from the line profiler.
2. Removed O(N log N) Sort Per Package (3.5% → eliminated)
The original code sorted all match scores for every package to find the best match. The optimized version:
sort_objects_by_score()callsif overlap_fraction > best_scoreThis removes ~630 sorting operations in typical workloads.
3. Set Construction Optimization in
nms_by_containmentThe original code constructed sets repeatedly in nested loops:
The optimized version precomputes all sets once:
This reduces ~26K set constructions to ~700 in large-scale tests (97% reduction).
4. Early Exit with
breakandcontinuebreakafter finding intersection in inner loop (no need to check remaining containers)continueafter marking suppression for empty packagesThese micro-optimizations reduce unnecessary iterations in dense scenarios.
Performance Impact by Test Case
The optimization excels in scenarios with:
Even small workloads see 60-100% speedups due to reduced object creation overhead.
Production Context
Based on
function_references, this optimization is in the hot path for table structure detection:refine_rows()andrefine_columns()for every table processedThe 741% speedup directly translates to faster document processing pipelines, especially for documents with complex table structures or batch processing workloads where this function is called hundreds of times.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-nms_by_containment-mkorw2k4and push.