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

Reduce import memory consumption #8223

Closed
wants to merge 13 commits into from

Conversation

Bobronium
Copy link
Contributor

@Bobronium Bobronium commented Jul 25, 2024

Motivation and context

memray stats for develop

Total time: 00:10:23
Peak memory usage: 4.2 GiB

memray stats for this branch

Total time: 00:05:55
Peak memory usage: 1.3 GiB

Check out flamegraphs.zip for full report.

Not yet entirely sure changes in 8965996 are sufficient. Was operating on the assumption that other importers are converting points to floats on import. Can confirm that this is the case for datumaro format.

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

    • Introduced a new LazyList class for efficient data handling and lazy evaluation of elements.
  • Improvements

    • Enhanced numerical accuracy in shape point processing by converting string attributes to float types during loading.
    • Updated the deletion process in the dataset manager for more efficient handling of annotations and data updates.
    • Modified the annotations handling function to allow for optional deep copying, improving performance flexibility.
  • Bug Fixes

    • Corrected data type handling for shape points to prevent potential type-related errors during processing.

Copy link
Contributor

coderabbitai bot commented Jul 25, 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 recent changes enhance the efficiency and clarity of the codebase by improving data handling during shape importation, optimizing deletion processes, and introducing a new LazyList class for better memory management. Key modifications include the removal of unnecessary type conversions for points, conditional handling of annotations, and improved flexibility in function parameters. Overall, these updates lead to a more robust and performant application.

Changes

Files Change Summary
cvat/apps/dataset_manager/bindings.py, cvat/apps/dataset_manager/formats/cvat.py Removed unnecessary float conversions for shape points during import; ensured proper float typing for shape coordinates to enhance accuracy.
cvat/apps/dataset_manager/task.py Modified the delete method to improve control flow with a check for deleted data and removed an initial task initialization line.
cvat/apps/engine/models.py Introduced a LazyList class for efficient string evaluation and modified database field methods to return LazyList instances.
cvat/apps/events/handlers.py Updated handle_annotations_change to include a should_deepcopy parameter for flexible annotation handling, optimizing performance.

Sequence Diagram(s)

sequenceDiagram
    participant A as User
    participant B as TaskManager
    participant C as AnnotationHandler

    A->>B: Request delete(data)
    B->>B: Check if data is empty
    B->>C: handle_annotations_change(annotations, action, should_deepcopy)
    C-->>B: Update annotations
    B-->>A: Confirm deletion
Loading

Poem

Hop and skip, the changes gleam,
In code we dance, a vibrant dream.
Shapes now float, oh what delight,
Annotations shift, all feels just right!
Lazy lists hop, memory's friend,
In this code warren, joy won't end! 🐰✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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, codebase verification and nitpick comments (1)
cvat/apps/events/handlers.py (1)

376-377: Function calls to handle_annotations_change need to be updated to match the new signature.

The following occurrences do not include the should_deepcopy argument:

  • cvat/apps/dataset_manager/task.py: handle_annotations_change(self.db_job, self.data, "create")
  • cvat/apps/dataset_manager/task.py: handle_annotations_change(self.db_job, deleted_data, "delete")
  • cvat/apps/dataset_manager/task.py: handle_annotations_change(self.db_job, self.data, "create")
  • cvat/apps/dataset_manager/task.py: handle_annotations_change(self.db_job, self.data, "update")
  • cvat/apps/dataset_manager/task.py: handle_annotations_change(self.db_job, deleted_data, "delete", should_deepcopy=False)

Please update these calls to include the should_deepcopy argument as appropriate.

Analysis chain

LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to handle_annotations_change match the new signature.


Let's correct the rg command to use the appropriate file type for Python and re-run the search to verify the function usage.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `handle_annotations_change` match the new signature.

# Test: Search for the function usage. Expect: Only occurances of the new signature.
rg --type python -A 5 $'handle_annotations_change'

Length of output: 80


Script:

#!/bin/bash
# Description: Verify all function calls to `handle_annotations_change` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type py -A 5 'handle_annotations_change'

Length of output: 3017

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 41d2f04 and c785e79.

Files selected for processing (5)
  • cvat/apps/dataset_manager/bindings.py (2 hunks)
  • cvat/apps/dataset_manager/formats/cvat.py (2 hunks)
  • cvat/apps/dataset_manager/task.py (2 hunks)
  • cvat/apps/engine/models.py (3 hunks)
  • cvat/apps/events/handlers.py (1 hunks)
Additional comments not posted (13)
cvat/apps/dataset_manager/task.py (2)

480-484: LGTM! But verify the method usage in the codebase.

The code changes are approved.

However, ensure that all method calls to delete handle the updated control flow correctly.


Line range hint 570-570:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to import_task_annotations handle the updated process correctly.

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

189-289: LGTM!

The LazyList class is well-implemented and enhances memory efficiency through lazy evaluation of elements.


Line range hint 290-316:
LGTM!

The changes in the AbstractArrayField class enhance data handling efficiency by incorporating the LazyList for lazy evaluation of elements.

cvat/apps/dataset_manager/formats/cvat.py (7)

1226-1229: Ensure consistent float conversion for box points

The conversion to float for box points is correctly implemented. This ensures numerical accuracy during calculations.


1231-1234: Ensure consistent float conversion for ellipse points

The conversion to float for ellipse points is correctly implemented. This ensures numerical accuracy during calculations.


1236-1252: Ensure consistent float conversion for cuboid points

The conversion to float for cuboid points is correctly implemented. This ensures numerical accuracy during calculations.


1285-1288: Ensure consistent float conversion for box points

The conversion to float for box points is correctly implemented. This ensures numerical accuracy during calculations.


1290-1293: Ensure consistent float conversion for ellipse points

The conversion to float for ellipse points is correctly implemented. This ensures numerical accuracy during calculations.


1295-1299: Ensure consistent float conversion for mask points

The conversion to float for mask points is correctly implemented. This ensures numerical accuracy during calculations.


1301-1317: Ensure consistent float conversion for cuboid points

The conversion to float for cuboid points is correctly implemented. This ensures numerical accuracy during calculations.

cvat/apps/dataset_manager/bindings.py (2)

Line range hint 438-438:
Verify the downstream impact of removing float conversion for track points.

The line shape['points'] = list(map(float, shape['points'])) has been removed. Ensure that downstream processes handle the points correctly without this conversion.


Line range hint 394-394:
Verify the downstream impact of removing float conversion for shape points.

The line _shape['points'] = list(map(float, _shape['points'])) has been removed. Ensure that downstream processes handle the points correctly without this conversion.

@@ -373,8 +373,8 @@ def handle_delete(scope, instance, store_in_deletion_cache=False, **kwargs):
user_email=uemail,
)

def handle_annotations_change(instance, annotations, action, **kwargs):
_annotations = deepcopy(annotations)
def handle_annotations_change(instance, annotations, action, should_deepcopy=True, **kwargs):
Copy link
Contributor

@zhiltsov-max zhiltsov-max Jul 25, 2024

Choose a reason for hiding this comment

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

I think this breaks encapsulation of the function, if a parameter with such name is required to be specified by the client code. I can see several ways to improve it:

  • rename to "annotations_mutable" or add a kw-parameter "mutable_annotations" (mutually exclusive with "annotations")
  • infer it automatically inside the function, if the operation is "delete". The problem here is this code is not responsible for this logic. The same problem is with the implemented passing of should_deepcopy=False in the delete() call - it looks like it actually must be forwarded all the way from the place the class instance is created to be fully correct.

Copy link
Member

@bsekachev bsekachev Jul 25, 2024

Choose a reason for hiding this comment

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

I think the function may be just refactored to avoid modifying its arguments (I mean even without deepcopy)

Copy link
Contributor

Choose a reason for hiding this comment

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

So now it still will be copying, but without calling deepcopy. Do we really need to send all these annotations, can it be replaced by some summary? Can we modify the recipient side to get only required fields?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So now it still will be copying, but without calling deepcopy

The main difference here is that we're only copying outer layers of the data, while nested fields remain the same objects. I'd say this has negligible impact on memory/performance, especially compared to previous implementation.

Do we really need to send all these annotations, can it be replaced by some summary? Can we modify the recipient side to get only required fields?

While I think it certainly worth a discussion, but I don't have enough context to answer these questions yet.

cvat/apps/dataset_manager/task.py Show resolved Hide resolved
cvat/apps/dataset_manager/task.py Outdated Show resolved Hide resolved
def handle_annotations_change(instance, annotations, action, **kwargs):
_annotations = deepcopy(annotations)
def handle_annotations_change(instance, annotations, action, should_deepcopy=True, **kwargs):
_annotations = deepcopy(annotations) if should_deepcopy else annotations
Copy link
Member

Choose a reason for hiding this comment

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

In my opinion we are trying to put into event too many information in this function, maybe that is worthy of discussing


return data
shapes = data.get("shates", None)
Copy link
Member

Choose a reason for hiding this comment

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

shates?

track["shapes"].append(filter_shape_data(track_shape))
tracks_by_type[track_shapes[0]["type"]].append(track)
for track in annotations.get("tracks", []):
filtered_track = filter_data(track)
Copy link
Member

Choose a reason for hiding this comment

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

Maybe it would be safer by concept to split the logic into several functions:

  • filter_track
  • filter_tag
  • filter_shape

As these 3 data structures are different by their idea.

And left one more common filter_data copying (id, attributes, frame as common properties).
But that is all about refactoring

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agreed. I've added filter_track and filter_shape, adding filter_tag didn't make sense since it would be identical to filter_data:

def filter_tag(tag):
    return filter_data(tag)

Copy link

@Bobronium
Copy link
Contributor Author

Closing in favour of 3 separate PRs:

  1. Annotations import (Optimize annotations import #8226)
  2. Array fields optimization (Lazy list for array field #8229)
  3. Logging function optimization (Remove deepcopy from handle_annotations_change #8228)

@Bobronium Bobronium closed this Jul 29, 2024
zhiltsov-max pushed a commit that referenced this pull request Jul 31, 2024
<!-- Raise an issue to propose your change
(https://github.com/cvat-ai/cvat/issues).
It helps to avoid duplication of efforts from multiple independent
contributors.
Discuss your ideas with maintainers to be sure that changes will be
approved and merged.
Read the [Contribution guide](https://docs.cvat.ai/docs/contributing/).
-->

<!-- Provide a general summary of your changes in the Title above -->

### Motivation and context
Decided to split changes in this PR:
#8223

1. Annotations import (#8226)
2. Array fields optimization (#8229)
3. Logging function optimization (this PR)

### How has this been tested?
<!-- Please describe in detail how you tested your changes.
Include details of your testing environment, and the tests you ran to
see how your change affects other areas of the code, etc. -->

### Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply.
If an item isn't applicable for some reason, then ~~explicitly
strikethrough~~ the whole
line. If you don't do that, GitHub will show incorrect progress for the
pull request.
If you're unsure about any of these, don't hesitate to ask. We're here
to help! -->
- [x] I submit my changes into the `develop` branch
- [ ] I have created a changelog fragment <!-- see top comment in
CHANGELOG.md -->
- [ ] I have updated the documentation accordingly
- [ ] I have added tests to cover my changes
- [ ] I have linked related issues (see [GitHub docs](

https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword))
- [ ] I have increased versions of npm packages if it is necessary

([cvat-canvas](https://github.com/cvat-ai/cvat/tree/develop/cvat-canvas#versioning),

[cvat-core](https://github.com/cvat-ai/cvat/tree/develop/cvat-core#versioning),

[cvat-data](https://github.com/cvat-ai/cvat/tree/develop/cvat-data#versioning)
and

[cvat-ui](https://github.com/cvat-ai/cvat/tree/develop/cvat-ui#versioning))

### License

- [x] I submit _my code changes_ under the same [MIT License](
https://github.com/cvat-ai/cvat/blob/develop/LICENSE) that covers the
project.
  Feel free to contact the maintainers if that's a concern.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved data integrity by ensuring annotations change handling occurs
every time an item is deleted.

- **New Features**
- Enhanced data filtering logic for annotations, allowing for more
efficient processing without unnecessary deep copies.
- Introduced a new function for streamlined filtering of track data,
simplifying data management.

- **Refactor**
- Consolidated data filtering into reusable functions for better
maintainability and clarity.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
zhiltsov-max pushed a commit that referenced this pull request Jul 31, 2024
<!-- Raise an issue to propose your change
(https://github.com/cvat-ai/cvat/issues).
It helps to avoid duplication of efforts from multiple independent
contributors.
Discuss your ideas with maintainers to be sure that changes will be
approved and merged.
Read the [Contribution guide](https://docs.cvat.ai/docs/contributing/).
-->

<!-- Provide a general summary of your changes in the Title above -->

### Motivation and context
Decided to split changes in this PR:
#8223
1. Annotations import (this PR)
2. Array fields optimization (#8229)
3. Logging function optimization
(#8228)

### How has this been tested?
<!-- Please describe in detail how you tested your changes.
Include details of your testing environment, and the tests you ran to
see how your change affects other areas of the code, etc. -->

### Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply.
If an item isn't applicable for some reason, then ~~explicitly
strikethrough~~ the whole
line. If you don't do that, GitHub will show incorrect progress for the
pull request.
If you're unsure about any of these, don't hesitate to ask. We're here
to help! -->
- [x] I submit my changes into the `develop` branch
- [ ] I have created a changelog fragment <!-- see top comment in
CHANGELOG.md -->
- [ ] I have updated the documentation accordingly
- [ ] I have added tests to cover my changes
- [ ] I have linked related issues (see [GitHub docs](

https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword))
- [ ] I have increased versions of npm packages if it is necessary

([cvat-canvas](https://github.com/cvat-ai/cvat/tree/develop/cvat-canvas#versioning),

[cvat-core](https://github.com/cvat-ai/cvat/tree/develop/cvat-core#versioning),

[cvat-data](https://github.com/cvat-ai/cvat/tree/develop/cvat-data#versioning)
and

[cvat-ui](https://github.com/cvat-ai/cvat/tree/develop/cvat-ui#versioning))

### License

- [x] I submit _my code changes_ under the same [MIT License](
https://github.com/cvat-ai/cvat/blob/develop/LICENSE) that covers the
project.
  Feel free to contact the maintainers if that's a concern.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Improved data type consistency for shape points during the annotation
loading process, ensuring all coordinates are treated as numeric values.
- Enhanced clarity and reliability in loading various shape types (box,
ellipse, cuboid, mask) by converting relevant attributes to floats.

- **Bug Fixes**
- Removed redundant database initialization calls during annotation
import, potentially improving the efficiency of the import process.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
zhiltsov-max pushed a commit that referenced this pull request Aug 6, 2024
<!-- Raise an issue to propose your change
(https://github.com/cvat-ai/cvat/issues).
It helps to avoid duplication of efforts from multiple independent
contributors.
Discuss your ideas with maintainers to be sure that changes will be
approved and merged.
Read the [Contribution guide](https://docs.cvat.ai/docs/contributing/).
-->

<!-- Provide a general summary of your changes in the Title above -->

### Motivation and context
Decided to split changes in this PR:
#8223

1. Annotations import (#8226)
2. Array fields optimization (this PR)
3. Logging function optimization
(#8228)

### How has this been tested?
<!-- Please describe in detail how you tested your changes.
Include details of your testing environment, and the tests you ran to
see how your change affects other areas of the code, etc. -->

### Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply.
If an item isn't applicable for some reason, then ~~explicitly
strikethrough~~ the whole
line. If you don't do that, GitHub will show incorrect progress for the
pull request.
If you're unsure about any of these, don't hesitate to ask. We're here
to help! -->
- [x] I submit my changes into the `develop` branch
- [ ] I have created a changelog fragment <!-- see top comment in
CHANGELOG.md -->
- [ ] I have updated the documentation accordingly
- [ ] I have added tests to cover my changes
- [ ] I have linked related issues (see [GitHub docs](

https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword))
- [ ] I have increased versions of npm packages if it is necessary

([cvat-canvas](https://github.com/cvat-ai/cvat/tree/develop/cvat-canvas#versioning),

[cvat-core](https://github.com/cvat-ai/cvat/tree/develop/cvat-core#versioning),

[cvat-data](https://github.com/cvat-ai/cvat/tree/develop/cvat-data#versioning)
and

[cvat-ui](https://github.com/cvat-ai/cvat/tree/develop/cvat-ui#versioning))

### License

- [x] I submit _my code changes_ under the same [MIT License](
https://github.com/cvat-ai/cvat/blob/develop/LICENSE) that covers the
project.
  Feel free to contact the maintainers if that's a concern.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Introduced the `LazyList` class for efficient, on-demand parsing of
list elements from strings.
- Added support for custom transformations through a converter function.
- Enhanced lazy evaluation with new decorators for improved performance
on list operations.
  
- **Tests**
- Implemented a comprehensive test suite for the `LazyList` class,
validating core functionalities and ensuring robustness.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@bsekachev bsekachev deleted the reduce_import_memory_consumption branch August 12, 2024 09:08
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