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

Memory optimization for image chunk preparation #8581

Merged
merged 3 commits into from
Oct 23, 2024

Conversation

azhavoro
Copy link
Contributor

@azhavoro azhavoro commented Oct 22, 2024

There is no need to load all images into memory during chunk preparation

Motivation and context

How has this been tested?

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 image loading process for improved performance during task creation.
    • Introduced a new loading mechanism for images, allowing for better memory management.
  • Bug Fixes

    • Streamlined image handling logic to ensure accurate processing and loading.
  • Documentation

    • Updated method signatures to reflect changes in image loading functions for clarity.

@azhavoro azhavoro requested a review from Marishka17 as a code owner October 22, 2024 11:57
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes in this pull request primarily involve the refactoring of image loading functionalities across three files: cache.py, task.py, and utils.py. The preload_images function has been replaced with load_images, which now includes a preload parameter. This modification affects various methods, including _read_raw_images, _read_raw_frames, and _create_static_chunks, streamlining the image loading process while maintaining existing functionality. The internal logic of these methods has been updated to accommodate the new loading mechanism without altering their signatures.

Changes

File Path Change Summary
cvat/apps/engine/cache.py - Replaced preload_images with load_images in _read_raw_images, _read_raw_frames, and prepare_context_images_chunk.
- Updated checksum verification logic.
- Maintained method signatures.
cvat/apps/engine/task.py - Updated _create_static_chunks to use load_images with preload=True.
- Changed method signature from preload_images to load_images.
cvat/apps/engine/utils.py - Renamed preload_image to load_image and preload_images to load_images.
- Modified load_images to include preload parameter.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant TC as Task Creator
    participant MC as Media Cache
    participant U as Utils

    C->>TC: Request to create task
    TC->>MC: Call load_images(preload=True)
    MC->>U: Load images from paths
    U-->>MC: Return loaded images
    MC-->>TC: Provide images for task
    TC-->>C: Task created successfully
Loading

🐰 "In the cache where images lay,
Load them swiftly, come what may.
Preload or not, the choice is clear,
With each new change, we hop with cheer!
For every frame and every scene,
Our image handling's now more keen!" 🐇


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: 1

🧹 Outside diff range and nitpick comments (5)
cvat/apps/engine/utils.py (3)

366-369: LGTM! Consider improving type hints.

The renaming from preload_image to load_image is consistent with the changes in other parts of the codebase. The function's implementation remains correct and unchanged.

Consider using more specific type hints for improved clarity:

def load_image(image: tuple[str, str, str]) -> tuple[Image.Image, str, str]:

371-375: LGTM! Consider adding type hints and docstring.

The changes to the load_images function improve its flexibility and potential memory efficiency. The new preload parameter allows for both eager and lazy loading of images.

Consider the following improvements:

  1. Add type hints for better clarity:
def load_images(images: Iterable[tuple[str, str, str]], preload: bool = False) -> Union[List[tuple[Image.Image, str, str]], Iterable[tuple[Image.Image, str, str]]]:
  1. Add a docstring to explain the function's behavior and the purpose of the preload parameter:
def load_images(images: Iterable[tuple[str, str, str]], preload: bool = False) -> Union[List[tuple[Image.Image, str, str]], Iterable[tuple[Image.Image, str, str]]]:
    """
    Load images from the given iterable of image data.

    Args:
        images: An iterable of tuples containing image data (file path, format, mime type).
        preload: If True, eagerly load all images into memory. If False, return a lazy-loading iterable.

    Returns:
        If preload is True, returns a list of tuples (Image, format, mime type).
        If preload is False, returns an iterable of tuples (Image, format, mime type).
    """

These changes will improve the function's documentation and make it easier for other developers to understand and use the function correctly.


366-375: Overall assessment: Changes align with PR objectives and improve code flexibility.

The modifications to load_image and load_images functions are consistent with the PR's goal of optimizing memory usage during image chunk preparation. The new preload parameter in load_images allows for more efficient memory management when handling large datasets.

These changes appear to be correct and do not introduce any security issues. The suggestions for improved type hinting and documentation will further enhance the code quality and maintainability.

Consider reviewing the impact of these changes on the overall image loading process in the application. Ensure that other parts of the codebase that use these functions are updated accordingly, especially regarding the new lazy-loading behavior when preload=False.

cvat/apps/engine/cache.py (2)

361-361: Approve memory optimization in frame loading

The change in this line implements the same memory optimization as in the _read_raw_images method, using load_images with preload=False. This should reduce memory usage when reading frames.

For consistency, consider extracting the preload=False parameter into a constant or configuration value, as it's used in multiple places.


Line range hint 1-724: Focused optimization with potential for future improvements

The changes in this file are focused on optimizing memory usage in image and frame loading processes. This targeted approach is good for minimizing the risk of introducing bugs in unrelated functionality.

For future improvements, consider:

  1. Applying similar memory optimizations to other methods that handle large amounts of data.
  2. Reviewing the prepare_chunk and prepare_context_images_chunk methods for potential memory optimizations.
  3. Implementing a more comprehensive caching strategy that balances memory usage and performance.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 036b17a and 29151a6.

📒 Files selected for processing (3)
  • cvat/apps/engine/cache.py (3 hunks)
  • cvat/apps/engine/task.py (2 hunks)
  • cvat/apps/engine/utils.py (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
cvat/apps/engine/cache.py (2)

57-57: Update import statement to reflect new function name

The import statement has been updated to use load_images instead of preload_images. This change aligns with the refactoring of the image loading functionality.


324-331: Approve memory optimization in image loading

The changes in this segment implement the memory optimization mentioned in the PR objectives. By using load_images with preload=False, the method avoids loading all images into memory simultaneously, which should significantly reduce memory usage for large datasets.

The checksum verification logic has been updated accordingly to work with the new image loading mechanism.

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

41-41: Import load_images for optimized image loading

The addition of load_images to the imports enables efficient image loading later in the code, which is essential for memory optimization during chunk preparation.

@@ -1537,7 +1537,7 @@ def save_chunks(
MEDIA_TYPES['archive']['extractor'],
))
):
chunk_data = preload_images(chunk_data)
chunk_data = load_images(images=chunk_data, preload=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for load_images to ensure robustness

The call to load_images may raise exceptions if image loading fails due to corrupted files or I/O errors. It is recommended to add error handling to manage potential exceptions and maintain the robustness of the application.

Apply this diff to handle possible exceptions:

 def save_chunks(
     executor: concurrent.futures.ThreadPoolExecutor,
     db_segment: models.Segment,
     chunk_idx: int,
     chunk_frame_ids: Sequence[int]
 ):
     chunk_data = [media_iterator[frame_idx] for frame_idx in chunk_frame_ids]

+    try:
         if (
             db_task.dimension == models.DimensionType.DIM_2D and
             isinstance(media_extractor, (
                 MEDIA_TYPES['image']['extractor'],
                 MEDIA_TYPES['zip']['extractor'],
                 MEDIA_TYPES['pdf']['extractor'],
                 MEDIA_TYPES['archive']['extractor'],
             ))
         ):
             chunk_data = load_images(images=chunk_data, preload=True)
+    except Exception as e:
+        slogger.glob.error(f"Failed to load images for chunk {chunk_idx}: {e}")
+        raise

     # TODO: extract into a class

     fs_original = executor.submit(
         original_chunk_writer.save_as_chunk,
         images=chunk_data,
         chunk_path=db_data.get_original_segment_chunk_path(
             chunk_idx, segment_id=db_segment.id
         ),
     )

Committable suggestion was skipped due to low confidence.

@codecov-commenter
Copy link

codecov-commenter commented Oct 22, 2024

Codecov Report

Attention: Patch coverage is 62.50000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 74.28%. Comparing base (4354f72) to head (bd27b23).
Report is 5 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8581      +/-   ##
===========================================
+ Coverage    74.24%   74.28%   +0.04%     
===========================================
  Files          403      403              
  Lines        43287    43284       -3     
  Branches      3914     3914              
===========================================
+ Hits         32137    32155      +18     
+ Misses       11150    11129      -21     
Components Coverage Δ
cvat-ui 78.77% <ø> (+0.10%) ⬆️
cvat-server 70.47% <62.50%> (+<0.01%) ⬆️

cvat/apps/engine/utils.py Outdated Show resolved Hide resolved
cvat/apps/engine/cache.py Outdated Show resolved Hide resolved
@SpecLad
Copy link
Contributor

SpecLad commented Oct 22, 2024

Add a changelog entry, please.

@azhavoro azhavoro requested a review from nmanovic as a code owner October 22, 2024 14:51
Copy link

@SpecLad SpecLad merged commit c8d2b1b into develop Oct 23, 2024
34 checks passed
@SpecLad SpecLad deleted the az/optimize_chunk_preparation branch October 23, 2024 10:18
@cvat-bot cvat-bot bot mentioned this pull request Oct 24, 2024
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