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

Fix empty batch #106

Merged
merged 3 commits into from
Feb 3, 2025
Merged

Fix empty batch #106

merged 3 commits into from
Feb 3, 2025

Conversation

shaikh58
Copy link
Contributor

@shaikh58 shaikh58 commented Jan 31, 2025

  • Currently, if there is a batch with a single frame that also happens to be the last frame of a video, the imageio reader often fails at the last frame (known issue), and this leads to an empty batch which causes the Lightning training loop to fail
  • We cannot skip this batch and increment the batch id in the SleapDataset as this conflicts with the Lightning Sampler/Distributed Sampler which is required for multi-GPU training. We also don't have sampler id info in Dataset. One option is to return None which leads to an easier to read error, and the user can fix the data. There is no built-in handling in PyTorch or Lightning of empty batches/None from the data loader currently.
  • In this PR, a temporary workaround is introduced that removes the chunk from the SleapDataset state when it is initialized. This means that batch is never called, which avoids the problem altogether

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of single-frame batches in dataset processing to prevent potential loading issues.
    • Enhanced tensor dimension handling in post-processing filtering function.
  • Style

    • Improved code formatting and readability in post-processing function.
    • Added blank line for better readability in the no_batching_fn method.

…t-frame load failure causing empty batch (temp patch; needs to be integrated with sampler)
Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Walkthrough

The pull request introduces logging functionality to the BaseDataset class in the dreem/datasets/base_dataset.py file, allowing for warnings related to batch processing. It adds logic to handle cases with too few frames in a batch, logging warnings when frames are removed. Additionally, a formatting change in the dreem/inference/post_processing.py file improves the readability of the filter_max_center_dist function by adding a newline when unsqueezing a tensor with zero dimensions.

Changes

File Change Summary
dreem/datasets/base_dataset.py Introduced logging for batch processing; added logic to handle and remove single-frame batches that could cause loading issues
dreem/inference/post_processing.py Improved code formatting in filter_max_center_dist function with a newline

Poem

🐰 A Rabbit's Code Refinement Ode 🐰

Single frames, once a tricky test,
Now handled with algorithmic zest.
A newline here, a tensor there,
Cleaner code beyond compare!
Hop, hop, hooray for clean design! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 797c94c and 920b0ce.

📒 Files selected for processing (1)
  • dreem/datasets/base_dataset.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dreem/datasets/base_dataset.py
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (windows-2022, Python 3.9)
  • GitHub Check: Tests (ubuntu-22.04, Python 3.9)
  • GitHub Check: Lint

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. (Beta)
  • @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

🧹 Nitpick comments (1)
dreem/datasets/base_dataset.py (1)

117-119: Enhance warning message with more context.

The warning message could be more informative by including the frame index and video details.

-                    print(
-                        "Warning: Single frame batch; removing to avoid empty batch possibility with failed frame loading"
-                    )
+                    print(
+                        f"Warning: Removing single frame batch (frame {frame_chunk[0]}) "
+                        f"to avoid empty batch possibility with failed frame loading"
+                    )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef05900 and 797c94c.

📒 Files selected for processing (2)
  • dreem/datasets/base_dataset.py (2 hunks)
  • dreem/inference/post_processing.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (windows-2022, Python 3.9)
  • GitHub Check: Tests (ubuntu-22.04, Python 3.9)
  • GitHub Check: Lint
🔇 Additional comments (3)
dreem/datasets/base_dataset.py (2)

147-147: LGTM!

The added blank line improves code readability.


113-124: Verify data integrity after chunk removal.

While this workaround prevents empty batch issues, removing chunks could potentially impact the training process by:

  1. Reducing the total amount of training data
  2. Creating gaps in sequential frame processing
  3. Potentially affecting model performance on edge cases

Let's analyze the potential impact:

✅ Verification successful

The chunk removal implementation is safe and well-controlled

The code specifically targets edge cases where:

  • Only single-frame chunks are removed
  • Only affects frames at clip boundaries
  • Maintains dataset integrity by synchronizing frame and label removal
  • Provides warning visibility for monitoring
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze potential data loss from chunk removal
# Look for patterns that might indicate frequent chunk removals

# Search for frame processing patterns
rg -A 5 "clip_length|chunked_frame_idx" 

# Look for related test cases
fd -e py -x grep -l "test.*chunk" {}

Length of output: 40834


Script:

#!/bin/bash
# Search for test cases covering chunk removal and related error handling
ast-grep --pattern 'def test_$_($$$):
  $$$
  remove_idx $$$
  $$$'

# Look for test files containing assertions about chunk sizes
rg -B 3 -A 3 "assert.*chunk" tests/

# Check for any logging or warning messages related to chunk removal
rg -B 2 "Warning.*batch" 

Length of output: 1051

dreem/inference/post_processing.py (1)

163-164: LGTM!

The formatting change improves code readability without affecting functionality.

Copy link

codecov bot commented Jan 31, 2025

Codecov Report

Attention: Patch coverage is 90.90909% with 1 line in your changes missing coverage. Please review.

Project coverage is 73.42%. Comparing base (2af0dd5) to head (797c94c).
Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
dreem/inference/post_processing.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #106      +/-   ##
==========================================
- Coverage   73.74%   73.42%   -0.32%     
==========================================
  Files          36       36              
  Lines        2967     3165     +198     
==========================================
+ Hits         2188     2324     +136     
- Misses        779      841      +62     

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

…read in. Largest batch that can be removed must be at most 10% of clip_len). Bug fix where loop breaks when collecting ixs to remove. Remove in reverse order to prevent list idx changing
@shaikh58 shaikh58 merged commit 8d1b920 into main Feb 3, 2025
4 checks passed
@shaikh58 shaikh58 deleted the fix-empty-batch branch February 3, 2025 19:13
This was referenced Feb 4, 2025
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.

1 participant