Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ms/task creation performance fixes #8741

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

msarniak
Copy link

@msarniak msarniak commented Nov 26, 2024

Task creation performance on >50k frames (#8602)

Motivation and context

In our environment we are expected to create tasks with more than 50k frames for single job. I understand this is unusual. This revealed some performance issues on task creation code that may also impact, in less extent, other cases.

How has this been tested?

Tested manually in local environment. Ran unit and integration tests.
For single job task, 140k frames, creation time dropped from 37 minutes to 90 seconds (using cloud storage source without copying images locally).

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
    - [ ] I have updated the documentation accordingly
    - [ ] I have added tests to cover my changes
  • I have linked related issues (see GitHub docs)
    - [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Enhanced media reading capabilities for improved handling of image dimensions and previews.
    • Optimized file filtering and validation processes for better performance in task creation.
  • Bug Fixes

    • Strengthened error handling in validation functions to prevent incompatible configurations.
  • Documentation

    • Minor adjustments to comments for clarity in various methods.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request involve modifications across three main files: media_extractors.py, task.py, and core.py. Enhancements in media_extractors.py focus on improving the IMediaReader class and its subclasses, particularly in handling source paths and image dimensions. The task.py file sees optimizations in file filtering and validation processes, utilizing sets for efficiency. Lastly, core.py updates the get_subset method in the ImageManifestManager class to replace linear searches with dictionary lookups, enhancing performance while maintaining output consistency.

Changes

File Path Change Summary
cvat/apps/engine/media_extractors.py - Added _source_path_set in IMediaReader for efficient membership testing.
- Updated __contains__, filter, reconcile, and get_image_size methods in ImageListReader to improve handling of source paths and image dimensions.
- Modified get_preview in ZipReader for 3D previews.
cvat/apps/engine/task.py - Optimized filtering of server_files using sets.
- Enhanced _validate_job_file_mapping for better file existence checks and error handling.
- Minor adjustments to comments and logging.
utils/dataset_manifest/core.py - Improved get_subset method in ImageManifestManager by replacing linear search with dictionary-based lookup for efficiency.
- Updated method signature for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MediaReader
    participant ImageListReader
    participant ZipReader

    User->>MediaReader: Request image processing
    MediaReader->>ImageListReader: Check source paths
    ImageListReader->>ImageListReader: Use _source_path_set for membership
    ImageListReader->>MediaReader: Return processed images
    MediaReader->>ZipReader: Get image preview
    ZipReader->>ZipReader: Handle 3D previews
    ZipReader->>User: Return image preview
Loading

🐰 "In the code where paths do play,
Efficiency hops in a joyful way.
With sets and maps, we swiftly glide,
Through images and tasks, we take pride!
Let's celebrate with a happy cheer,
For every change brings us near!" 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (5)
utils/dataset_manifest/core.py (1)

647-651: Consider adding type hints and fixing indentation

While the optimization is excellent, consider these improvements:

  1. Add type hints to improve code maintainability
  2. Fix the indentation on line 650 to match the surrounding code

Here's the suggested improvement:

-    def get_subset(self, subset_names):
+    def get_subset(self, subset_names: List[str]) -> Tuple[List[int], List[Dict[str, Any]]]:
         index_list = []
         subset = []
         
         # First, create a dictionary mapping image names to their indices
         name_to_index = {name: index for index, name in enumerate(subset_names)}
         
         # Now, loop through the images and check against the dictionary
         for _, image in self:
             image_name = f"{image.full_name}"
-            if image_name in name_to_index:
+             if image_name in name_to_index:
cvat/apps/engine/media_extractors.py (3)

Line range hint 1-1: Consider adding dimension type validation

While the dimension handling is correct, it would be beneficial to add explicit validation of the dimension type to prevent potential issues with invalid values.

Add validation in the IMediaReader.__init__ method:

    def __init__(
        self,
        source_path,
        *,
        step: int = 1,
        start: int = 0,
        stop: Optional[int] = None,
        dimension: DimensionType = DimensionType.DIM_2D
    ):
+       if not isinstance(dimension, DimensionType):
+           raise ValueError(f"Invalid dimension type: {dimension}")
        self._dimension = dimension

Line range hint 1-1: Consider adding performance monitoring

To validate and track the performance improvements, consider adding performance monitoring and logging.

Add timing decorators to key methods:

import time
import logging
from functools import wraps

def log_performance(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        duration = time.time() - start_time
        logging.info(f"{func.__name__} took {duration:.2f} seconds")
        return result
    return wrapper

Apply to key methods:

+   @log_performance
    def __contains__(self, media_file):
        return media_file in self._source_path_set

Line range hint 1-1: Enhance error handling and documentation

Consider improving error handling for corrupted files and invalid formats, and add documentation for error cases.

Add comprehensive error handling:

class MediaError(Exception):
    """Base exception for media processing errors."""
    pass

class InvalidFormatError(MediaError):
    """Raised when a file format is invalid or corrupted."""
    pass

class DimensionError(MediaError):
    """Raised when dimension-related operations fail."""
    pass

Update error handling in methods:

    def get_image_size(self, i):
        if self._dimension == DimensionType.DIM_3D:
            with open(self.get_path(i), 'rb') as f:
                properties = ValidateDimension.get_pcd_properties(f)
+               if not properties:
+                   raise InvalidFormatError(f"Invalid or corrupted PCD file: {self.get_path(i)}")
                return int(properties["WIDTH"]), int(properties["HEIGHT"])
cvat/apps/engine/task.py (1)

236-240: Performance optimization: Use set for O(1) membership testing

Good optimization! Converting the filter list to a set provides O(1) lookup time while maintaining the original file order in the final result.

Consider adding a comment explaining the performance optimization:

+# Convert to set for O(1) membership testing while maintaining original order
 without_extra_dirs_set = set(without_extra_dirs)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e97ace2 and d5e2436.

📒 Files selected for processing (3)
  • cvat/apps/engine/media_extractors.py (2 hunks)
  • cvat/apps/engine/task.py (2 hunks)
  • utils/dataset_manifest/core.py (1 hunks)
🔇 Additional comments (3)
utils/dataset_manifest/core.py (1)

644-646: Great performance optimization!

Converting the list lookup to a dictionary-based approach improves the time complexity from O(n) to O(1) for each image name lookup. This is particularly beneficial when dealing with large datasets.

cvat/apps/engine/media_extractors.py (1)

206-206: Excellent performance optimization!

Using a set for membership testing improves the time complexity from O(n) to O(1), which is particularly beneficial for tasks with large numbers of frames.

Also applies to: 311-311

cvat/apps/engine/task.py (1)

712-717: Efficient validation of job file mapping

Good optimization! Using a set for membership testing improves performance while maintaining robust validation of job mapping files.

Let's verify the validation logic works as expected:

✅ Verification successful

Let me gather more information about the validation logic by checking the implementation of the file validation:


Validation logic is correctly implemented and comprehensive

The optimization and validation are well implemented with multiple layers of protection:

  • Uses O(1) set lookups for performance
  • Validates that every file in job mapping exists in server files
  • Provides clear error messages identifying missing files
  • Filters the server files to only include those specified in job mapping
  • Has comprehensive validation checks preventing incompatible parameter combinations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that job file mapping validation catches missing files

# Test: Search for ValidationError exceptions in job file mapping validation
rg -A 5 "raise ValidationError.*job.*mapping" 

Length of output: 2688


Script:

#!/bin/bash
# Search for the validation logic around the set membership check
rg -B 10 -A 10 "server_files_set = set\(data\['server_files'\]\)"

Length of output: 1546

@msarniak msarniak requested a review from nmanovic as a code owner November 26, 2024 08:48
@codecov-commenter
Copy link

codecov-commenter commented Nov 26, 2024

Codecov Report

Attention: Patch coverage is 44.44444% with 5 lines in your changes missing coverage. Please review.

Project coverage is 74.05%. Comparing base (e97ace2) to head (6d7e474).
Report is 4 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8741      +/-   ##
===========================================
+ Coverage    74.04%   74.05%   +0.01%     
===========================================
  Files          409      409              
  Lines        43786    43788       +2     
  Branches      3984     3984              
===========================================
+ Hits         32420    32427       +7     
+ Misses       11366    11361       -5     
Components Coverage Δ
cvat-ui 78.36% <ø> (+<0.01%) ⬆️
cvat-server 70.34% <44.44%> (+0.01%) ⬆️

@zhiltsov-max
Copy link
Contributor

Hi, thank you for the work done. Please consider comments below.

  1. I agree that such optimization can be useful, but I'd like add that having too many frames in a task or job is likely to result in bad performance in several other places as well, specifically in validation_layout/, data/meta/, and annotations/ endpoints of tasks and jobs. The reason is that they return non-paginated responses.
  2. If you want to put all the frames into 1 job, you can just unset or set segment_size to 0 instead of specifying all the frames in job_file_mapping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants