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

Add caching to Torch Datasets pipeline #123

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

gitttt-1234
Copy link
Contributor

@gitttt-1234 gitttt-1234 commented Dec 11, 2024

This is the second PR for #119. We implement in-memory caching by pre-loading the samples in a dictionary and applying augmentations in the __getitem__() function to ensure randomness.

Summary by CodeRabbit

  • New Features

    • Enhanced dataset classes with caching mechanisms for improved data handling.
    • Added a method to generate centered bounding boxes in the CenteredInstanceDataset class.
    • Introduced a method for cropping and resizing images in the SingleInstanceDataset class.
  • Bug Fixes

    • Refactored sample retrieval to reduce redundancy and improve efficiency.
  • Tests

    • Updated test cases to reflect changes in dataset configurations and output tensor shapes.

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes involve significant updates to the sleap_nn/data/custom_datasets.py file, focusing on enhancing dataset classes with caching mechanisms. The classes BottomUpDataset, CenteredInstanceDataset, CentroidDataset, and SingleInstanceDataset now feature a _fill_cache method for preloading samples into a cache during initialization. The __getitem__ method in these classes has been refactored to retrieve samples from the cache, improving efficiency by reducing redundant data processing. Additionally, the CenteredInstanceDataset class has a new method for generating centered bounding boxes.

Changes

File Path Change Summary
sleap_nn/data/custom_datasets.py - Added _fill_cache method in BaseDataset, BottomUpDataset, CenteredInstanceDataset, CentroidDataset, and SingleInstanceDataset classes.
- Refactored __getitem__ method in BottomUpDataset, CenteredInstanceDataset, CentroidDataset, and SingleInstanceDataset classes to utilize cached samples instead of reprocessing data.
- Added methods for generating centered bounding boxes and cropping/resizing images in CenteredInstanceDataset and SingleInstanceDataset, respectively.
tests/data/test_custom_datasets.py - Updated test cases for BottomUpDataset, CenteredInstanceDataset, CentroidDataset, and SingleInstanceDataset with new configurations and expected tensor shapes. Adjusted max_stride in tests and removed some augmentation parameters.

Poem

In the burrow, data hops,
With caching, it never stops.
Samples saved, quick as a flash,
No more waiting, just a dash!
Bunnies cheer, for speed is key,
In our datasets, we dance with glee! 🐇✨


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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: 4

🧹 Outside diff range and nitpick comments (2)
sleap_nn/data/custom_datasets.py (2)

26-26: Remove duplicate import of apply_normalization

The function apply_normalization is imported at line 26 but was already imported earlier at line 18. You can remove the duplicate import to clean up the code.

Apply this diff to remove the duplicate import:

 from sleap_nn.data.instance_cropping import make_centered_bboxes
-from sleap_nn.data.normalization import apply_normalization
 from sleap_nn.data.resizing import apply_pad_to_stride, apply_resizer

270-271: Simplify nested if statements when filtering user instances

At lines 270-271, the nested if statements can be combined into a single condition to enhance readability.

Apply this diff to simplify the condition:

-if self.data_config.user_instances_only:
-    if lf.user_instances is not None and len(lf.user_instances) > 0:
+if self.data_config.user_instances_only and lf.user_instances:
     lf.instances = lf.user_instances
🧰 Tools
🪛 Ruff (0.8.2)

270-271: Use a single if statement instead of nested if statements

(SIM102)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bc75aaf and 90cda91.

📒 Files selected for processing (1)
  • sleap_nn/data/custom_datasets.py (7 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
sleap_nn/data/custom_datasets.py

270-271: Use a single if statement instead of nested if statements

(SIM102)

sleap_nn/data/custom_datasets.py Outdated Show resolved Hide resolved
sleap_nn/data/custom_datasets.py Outdated Show resolved Hide resolved
sleap_nn/data/custom_datasets.py Outdated Show resolved Hide resolved
sleap_nn/data/custom_datasets.py Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (1)
sleap_nn/data/custom_datasets.py (1)

272-273: Simplify nested if statements into a single condition

The nested if statements at lines 272-273 can be combined into a single if statement for improved readability.

Apply this diff to combine the conditions:

-if self.data_config.user_instances_only:
-    if lf.user_instances is not None and len(lf.user_instances) > 0:
+if self.data_config.user_instances_only and lf.user_instances and len(lf.user_instances) > 0:
🧰 Tools
🪛 Ruff (0.8.2)

272-273: Use a single if statement instead of nested if statements

(SIM102)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 90cda91 and d9ce316.

📒 Files selected for processing (2)
  • sleap_nn/data/custom_datasets.py (7 hunks)
  • tests/data/test_custom_datasets.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
sleap_nn/data/custom_datasets.py

272-273: Use a single if statement instead of nested if statements

(SIM102)

🔇 Additional comments (5)
sleap_nn/data/custom_datasets.py (4)

341-342: Avoid closing videos within data loading

Closing videos at lines 341-342 inside the dataset initialization may lead to issues if the dataset accesses video frames afterward. Ensure that videos remain open for the duration of their needed use, or manage video resources appropriately.

Run the following script to check for any subsequent usage of video objects after they are closed:

#!/bin/bash
# Description: Search for usage of 'video' objects after they are closed.

# Find all instances where 'video' is used after being closed.
rg -A5 'video\.close\(\)' --no-heading --line-number | grep -A5 'video\.' 

120-122: 🛠️ Refactor suggestion

Consider refactoring caching logic to reduce duplication

The initialization of self.cache and the call to self._fill_cache() are repeated across multiple dataset classes. To improve maintainability and reduce code redundancy, consider moving the caching mechanism into the BaseDataset class or creating a shared utility method.


123-164: 🛠️ Refactor suggestion

Refactor repeated _fill_cache methods into a shared method

The _fill_cache method in BottomUpDataset is similar to those in other dataset classes. Refactoring common logic into a shared method in the BaseDataset class or a utility function can promote code reuse and simplify future maintenance.


262-264: 🛠️ Refactor suggestion

Consolidate caching logic across dataset classes

The caching logic implemented in CenteredInstanceDataset, CentroidDataset, and SingleInstanceDataset duplicates code from BottomUpDataset. Consolidating this logic can reduce redundancy and improve code maintainability.

tests/data/test_custom_datasets.py (1)

167-169: Verify expected output shapes after changing max_stride

The expected shapes of image, confidence_maps, and part_affinity_fields have been updated at lines 167-169. Confirm that these changes are correct and that the model architecture and loss functions are compatible with these new shapes.

tests/data/test_custom_datasets.py Show resolved Hide resolved
Copy link

codecov bot commented Dec 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.62%. Comparing base (f093ce2) to head (8218859).
Report is 28 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #123      +/-   ##
==========================================
+ Coverage   96.64%   97.62%   +0.98%     
==========================================
  Files          23       39      +16     
  Lines        1818     4003    +2185     
==========================================
+ Hits         1757     3908    +2151     
- Misses         61       95      +34     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@gitttt-1234 gitttt-1234 linked an issue Dec 11, 2024 that may be closed by this pull request
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: 2

🧹 Outside diff range and nitpick comments (1)
sleap_nn/data/custom_datasets.py (1)

64-111: Consider implementing cache memory management

The current caching implementation loads all samples into memory without any size limits or cleanup mechanism. For large datasets, this could lead to memory issues.

Consider implementing:

  1. A maximum cache size limit
  2. LRU (Least Recently Used) cache eviction policy
  3. Cache cleanup in the __del__ method
from functools import lru_cache
import sys

class BaseDataset(Dataset):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.cache = {}
        self.cache_size = 0
        self.max_cache_size = 1024 * 1024 * 1024  # 1GB default

    def __del__(self):
        self.cache.clear()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d9ce316 and 8218859.

📒 Files selected for processing (1)
  • sleap_nn/data/custom_datasets.py (8 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
sleap_nn/data/custom_datasets.py

272-273: Use a single if statement instead of nested if statements

(SIM102)

🔇 Additional comments (3)
sleap_nn/data/custom_datasets.py (3)

168-172: LGTM: Efficient caching implementation

The caching implementation in BottomUpDataset correctly initializes the cache and efficiently retrieves samples in getitem.


589-593: LGTM: Consistent caching implementation

The caching implementation in SingleInstanceDataset follows the established pattern and correctly handles sample retrieval.


463-514: 🛠️ Refactor suggestion

Reduce code duplication in _fill_cache methods

The _fill_cache implementation duplicates preprocessing logic from BaseDataset._fill_cache.

Consider extracting common preprocessing steps to a utility method in BaseDataset:

class BaseDataset(Dataset):
    def _preprocess_sample(self, sample):
        """Common preprocessing steps for all dataset types."""
        sample["image"] = apply_normalization(sample["image"])
        
        if self.data_config.preprocessing.is_rgb:
            sample["image"] = convert_to_rgb(sample["image"])
        else:
            sample["image"] = convert_to_grayscale(sample["image"])
            
        sample["image"], eff_scale = apply_sizematcher(
            sample["image"],
            max_height=self.max_hw[0],
            max_width=self.max_hw[1],
        )
        return sample, eff_scale

sleap_nn/data/custom_datasets.py Show resolved Hide resolved
sleap_nn/data/custom_datasets.py Show resolved Hide resolved
@gitttt-1234 gitttt-1234 requested a review from talmo December 11, 2024 20:02
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.

Vanilla PyTorch Dataset pipeline
1 participant