Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@gitttt-1234
Copy link
Collaborator

@gitttt-1234 gitttt-1234 commented Oct 23, 2024

Currently, the bin files generated by sleap_nn.training.generate_bin_files.py is much larger compared to the source dataset (almost 100 times bigger). Thus, to reduce the disk footprint, we convert the images to PIL before generating the .bin files and then convert it back to torch.Tensor in the Litdata.StreamingDataset classes. We also move the resizer function to get_chunks() so that the .bin files have resized image (which helps in saving up disk space).

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced dynamic image resizing capabilities across various data chunk generation functions.
    • Added a command-line argument --scale for specifying scaling factors during data processing.
  • Bug Fixes

    • Improved handling of NaN values in instance cropping calculations to enhance robustness.
    • Resolved redundancy in image normalization within the prediction pipeline.
  • Documentation

    • Updated tests to reflect changes in image transformation processes and scaling parameters.
  • Tests

    • Enhanced test coverage for model output shapes and loss values, ensuring expected functionality.

@gitttt-1234 gitttt-1234 changed the base branch from main to divya/fix-predictor October 23, 2024 00:35
@codecov
Copy link

codecov bot commented Oct 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.39%. Comparing base (f093ce2) to head (105e496).
Report is 18 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #105      +/-   ##
==========================================
+ Coverage   96.64%   97.39%   +0.74%     
==========================================
  Files          23       38      +15     
  Lines        1818     3681    +1863     
==========================================
+ Hits         1757     3585    +1828     
- Misses         61       96      +35     

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

@gitttt-1234 gitttt-1234 marked this pull request as ready for review October 23, 2024 04:38
@gitttt-1234 gitttt-1234 requested a review from talmo October 23, 2024 17:14
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes primarily enhance the image processing capabilities within the sleap_nn library. Key modifications include the introduction of a scale parameter in various data chunk functions to control image resizing, the removal of normalization steps, and the adoption of torchvision.transforms for image transformations. Additionally, updates were made to several dataset classes and their associated tests to reflect these changes. The overall aim is to streamline image handling and improve robustness in processing workflows.

Changes

File Change Summary
sleap_nn/data/get_data_chunks.py Added scale parameter to multiple functions; removed normalization; introduced apply_resizer for resizing.
sleap_nn/data/instance_cropping.py Enhanced handling of NaN values in find_instance_crop_size.
sleap_nn/data/resizing.py Changed return value of apply_sizematcher to 1.0 for type consistency; no logic changes.
sleap_nn/data/streaming_datasets.py Removed scale from constructors; added input_scale to CenteredInstanceStreamingDataset.
sleap_nn/inference/predictors.py Added max_height and max_width attributes to Predictor class; updated preprocessing logic.
sleap_nn/training/get_bin_files.py Introduced --scale argument for command-line usage to affect data chunk generation.
sleap_nn/training/model_trainer.py Updated _create_data_loaders and run_subprocess to handle scale and improved error handling.
tests/data/test_get_data_chunks.py Updated tests to apply torchvision.transforms for image shape assertions.
tests/data/test_streaming_datasets.py Added scale parameter to partial_func in dataset tests; updated constructor calls accordingly.
tests/training/test_model_trainer.py Changed checkpoint references from "best.ckpt" to "last.ckpt"; enhanced output shape and loss checks.

Possibly related PRs

Suggested reviewers

  • talmo

Poem

🐇 In fields of code, where images play,
A scale was added to brighten the day.
With transformations bright and clear,
Our data chunks now dance with cheer!
So hop along, let's resize with grace,
In the world of pixels, we find our place! 🌼


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.

@gitttt-1234 gitttt-1234 force-pushed the divya/fix-predictor branch 3 times, most recently from a269f1d to 9d87e44 Compare October 30, 2024 18:27
@gitttt-1234 gitttt-1234 changed the base branch from divya/fix-predictor to main October 30, 2024 18:58
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: 10

🧹 Outside diff range and nitpick comments (13)
tests/data/test_get_data_chunks.py (3)

Line range hint 111-112: Add tests for different scale values

While the scale parameter is set to 1.0, we should add test cases with different scale values to verify the resizing functionality works as expected.

 config.data_config.preprocessing.scale = 1.0
 config.data_config.preprocessing.is_rgb = True
+# Test with different scale values
+scales = [0.5, 2.0]
+for scale in scales:
+    config.data_config.preprocessing.scale = scale
+    samples = []
+    for idx, lf in enumerate(labels):
+        res = centered_instance_data_chunks(
+            (lf, idx),
+            data_config=config.data_config,
+            anchor_ind=0,
+            crop_size=(160, 160),
+            max_instances=2,
+            max_hw=max_hw,
+        )
+        samples.extend(res)
+    expected_size = int(226 * scale)
+    assert transform(samples[0]["instance_image"]).shape == (3, expected_size, expected_size)

Line range hint 209-260: Consider reducing test setup duplication

The transformation setup and RGB testing pattern is repeated across all test functions. Consider extracting common setup into fixtures or helper functions.

@pytest.fixture
def transform():
    return T.ToTensor()

@pytest.fixture
def rgb_config(config):
    config.data_config.preprocessing.is_rgb = True
    return config

def assert_image_shapes(sample, transform, is_rgb=False):
    channels = 3 if is_rgb else 1
    assert transform(sample["image"]).shape == (channels, 384, 384)

Line range hint 1-260: Consider enhancing test coverage for image transformations

While the changes successfully implement PIL image transformations, consider these improvements:

  1. Add property-based tests to verify transformation behavior across different image sizes and scales
  2. Add edge cases for extreme scale values
  3. Consider testing memory usage to verify the PR's objective of reducing memory footprint
sleap_nn/data/instance_cropping.py (1)

50-55: LGTM! Consider consolidating the NaN handling logic.

The NaN handling logic is robust and well-implemented. However, the code could be slightly more concise while maintaining readability.

Consider this alternative implementation that reduces repetition:

-            diff_x = np.nanmax(pts[:, 0]) - np.nanmin(pts[:, 0])
-            diff_x = 0 if np.isnan(diff_x) else diff_x
-            max_length = np.maximum(max_length, diff_x)
-            diff_y = np.nanmax(pts[:, 1]) - np.nanmin(pts[:, 1])
-            diff_y = 0 if np.isnan(diff_y) else diff_y
-            max_length = np.maximum(max_length, diff_y)
+            diffs = [np.nanmax(pts[:, i]) - np.nanmin(pts[:, i]) for i in range(2)]
+            diffs = [0 if np.isnan(d) else d for d in diffs]
+            max_length = np.maximum(max_length, max(diffs))
tests/data/test_streaming_datasets.py (1)

35-35: LGTM! Consider adding shape calculation comments.

The addition of scale parameter and testing multiple scales (0.5 and 1.0) aligns well with the PR objective. The cleanup is properly handled.

Consider adding comments explaining how the output shapes are calculated, e.g.:

# Image shape: (1, 1, 200, 200)  # Original 400x400 with scale=0.5
# Confidence maps: (1, 2, 100, 100)  # Image/2 due to output_stride=2
# PAFs: (50, 50, 2)  # Image/4 due to output_stride=4

Also applies to: 64-81

sleap_nn/data/resizing.py (4)

Line range hint 1-152: Document image format requirements and consider PIL conversion handling

Given the PR's objective to convert between Tensor and PIL formats, consider:

  1. Documenting the expected input/output image formats in function docstrings
  2. Adding PIL conversion utilities in this module since it's the central image processing location
  3. Ensuring tvf.resize behavior is consistent with both Tensor and PIL inputs

Consider adding these utility functions:

def to_pil_image(image: torch.Tensor) -> "PIL.Image":
    """Convert a torch tensor to PIL Image for storage efficiency."""
    return tvf.to_pil_image(image)

def to_tensor(image: "PIL.Image") -> torch.Tensor:
    """Convert a PIL Image back to torch tensor for processing."""
    return tvf.to_tensor(image)

Line range hint 249-286: Standardize error handling in SizeMatcher

The error handling in SizeMatcher.__iter__ uses Exception while similar checks in apply_sizematcher use ValueError. Consider standardizing to use ValueError consistently.

-                raise Exception(
+                raise ValueError(
                     f"Max height {self.max_height} should be greater than the current image height: {img_height}"
                 )
             if pad_width < 0:
-                raise Exception(
+                raise ValueError(
                     f"Max width {self.max_width} should be greater than the current image width: {img_width}"
                 )

Line range hint 31-63: Make padding more configurable

The padding functions use hardcoded parameters that could be made configurable:

  1. Padding mode is always 'constant'
  2. Padding value is always 0

Consider updating the function signature:

 def apply_pad_to_stride(
     image: torch.Tensor,
     max_stride: int,
+    pad_mode: str = "constant",
+    pad_value: float = 0.0,
 ) -> torch.Tensor:

Line range hint 89-106: Consider performance optimizations

The apply_resizer function could be optimized for batch processing:

  1. Add batch support to process multiple images at once
  2. Consider in-place operations where possible to reduce memory usage

Example batch implementation:

def apply_resizer_batch(
    images: torch.Tensor,
    instances: torch.Tensor,
    scale: float = 1.0
) -> Tuple[torch.Tensor, torch.Tensor]:
    """Batch version of apply_resizer."""
    if scale != 1.0:
        # images shape: (batch_size, channels, height, width)
        images = resize_image(images, scale)
        instances = instances * scale
    return images, instances
sleap_nn/data/get_data_chunks.py (2)

7-7: Consider cleaning up unused imports.

Since normalization steps have been removed, consider cleaning up any unused imports from the normalization module to maintain code cleanliness.

Also applies to: 17-17


74-82: Document tensor dimension requirements.

The code assumes specific tensor dimensions for the image (presence of batch dimension that gets squeezed). Consider documenting the expected input tensor format in the function's docstring to prevent potential runtime errors.

tests/training/test_model_trainer.py (2)

Line range hint 296-301: Fix inconsistent checkpoint file references

There are still references to "best.ckpt" in the test cleanup code while the loading code has been updated to use "last.ckpt". This inconsistency should be resolved to maintain test reliability.

Apply this change to all cleanup sections:

-if (Path(centroid_config.trainer_config.save_ckpt_path) / "best.ckpt").exists():
+if (Path(centroid_config.trainer_config.save_ckpt_path) / "last.ckpt").exists():
     os.remove(
         (
-            Path(centroid_config.trainer_config.save_ckpt_path) / "best.ckpt"
+            Path(centroid_config.trainer_config.save_ckpt_path) / "last.ckpt"
         ).as_posix()
     )

Also applies to: 449-454


Line range hint 1-24: Add test coverage for new image conversion features

The PR introduces Tensor-to-PIL image conversion and relocates the resizer function, but there's no test coverage for these changes. Consider adding test cases to verify:

  1. Correct conversion between Tensor and PIL formats
  2. Proper functioning of the relocated resizer

Add new test cases like:

def test_image_format_conversion():
    """Test conversion between Tensor and PIL image formats."""
    # Test tensor to PIL conversion
    tensor_image = torch.rand(1, 3, 224, 224)
    pil_image = convert_tensor_to_pil(tensor_image)
    assert isinstance(pil_image, Image.Image)
    
    # Test PIL to tensor conversion
    tensor_result = convert_pil_to_tensor(pil_image)
    assert torch.allclose(tensor_image, tensor_result)

def test_resizer_in_get_chunks():
    """Test the relocated resizer function in get_chunks."""
    # Test resizing behavior
    original_size = (224, 224)
    target_size = (112, 112)
    chunks = get_chunks(...)  # Add appropriate test data
    assert chunks[0].size == target_size
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0abb3b1 and 105e496.

📒 Files selected for processing (10)
  • sleap_nn/data/get_data_chunks.py (14 hunks)
  • sleap_nn/data/instance_cropping.py (1 hunks)
  • sleap_nn/data/resizing.py (1 hunks)
  • sleap_nn/data/streaming_datasets.py (11 hunks)
  • sleap_nn/inference/predictors.py (1 hunks)
  • sleap_nn/training/get_bin_files.py (5 hunks)
  • sleap_nn/training/model_trainer.py (3 hunks)
  • tests/data/test_get_data_chunks.py (10 hunks)
  • tests/data/test_streaming_datasets.py (8 hunks)
  • tests/training/test_model_trainer.py (4 hunks)
🔇 Additional comments (17)
sleap_nn/training/get_bin_files.py (2)

Line range hint 1-150: Verify integration with PIL conversion process.

While the scale parameter addition supports the PR's goal of reducing file sizes, we should verify the integration with the PIL conversion process mentioned in the PR objectives.

Let's check the image processing pipeline:

#!/bin/bash
# Description: Verify PIL conversion integration

# Look for PIL/image conversion logic in the codebase
echo "Searching for PIL conversion logic..."
rg -l "from PIL import|Image.fromarray|torchvision.*transforms" --type python

# Look for image processing in the data loading pipeline
echo "Searching for image processing in data pipeline..."
rg -A 10 "def (load|process|transform).*image" --type python

48-48: Verify scale parameter handling in dependent modules.

The scale parameter is being passed to various data chunk functions, but we should verify its proper handling in those modules.

Let's check the implementation of these functions:

Also applies to: 77-77, 104-104, 130-130

✅ Verification successful

Based on the search results, I can now provide a final response regarding the scale parameter handling:

Scale parameter is properly handled throughout the data processing pipeline

The scale parameter is consistently and correctly handled in all dependent modules:

  • In data chunk functions (bottomup_data_chunks, centered_instance_data_chunks, centroid_data_chunks, single_instance_data_chunks), scale is:
    • Applied to both images and instances using apply_resizer
    • Properly cascaded with eff_scale from apply_sizematcher
  • Scale transformations are properly tested in test files
  • Scale parameter flows through the inference pipeline via input_scale in predictors and model layers
  • Resizing operations maintain aspect ratios and coordinate transformations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how scale parameter is used in data chunk functions

# Look for the data chunk function implementations
echo "Searching for data chunk function implementations..."
rg -A 10 "def (bottomup|centered_instance|centroid|single_instance)_data_chunks" --type python

# Look for image scaling/resizing logic
echo "Searching for image scaling implementation..."
rg -A 5 "scale.*image|resize.*image" --type python

Length of output: 495


Script:

#!/bin/bash
# Let's try a different approach to find scale parameter usage

# Search for scale parameter in function definitions and their implementations
echo "Searching for scale parameter usage..."
rg -A 10 "def.*scale.*:|scale\s*=\s*" --type-add 'python:*.py'

# Search specifically in the data chunks related files
echo "Searching in data chunks related files..."
fd -e py chunks | xargs rg -A 10 "scale"

# Look for image processing related functions
echo "Searching for image processing..."
rg -A 10 "(process|transform).*image" --type-add 'python:*.py'

Length of output: 79132

tests/data/test_get_data_chunks.py (3)

1-2: LGTM: Import changes align with PR objectives

The addition of torchvision.transforms is appropriate for handling the new PIL image conversion workflow.


143-143: LGTM: Consistent transformation handling

The changes maintain consistency with other test functions in handling image transformations and shape assertions.

Also applies to: 171-171, 201-201


16-16: Verify the intended tensor shapes after transformation

The shape assertions have changed significantly:

  • Grayscale: (1,1,384,384)(1,384,384)
  • RGB: (1,3,384,384)(3,384,384)

These changes indicate the removal of the batch dimension. While this works for testing, we should verify if downstream components expect this tensor shape.

Also applies to: 42-42, 69-69

✅ Verification successful

Let me analyze the shape requirements more broadly to understand the tensor dimension expectations in the codebase.


Let me analyze the tensor transformations and shape expectations in the codebase to better understand if the shape changes are intentional.


Based on the codebase analysis, I can now provide a definitive response about the tensor shape changes:

Shape changes are intentional and correct

The shape changes from (1,1,384,384)(1,384,384) for grayscale and (1,3,384,384)(3,384,384) are the expected behavior of ToTensor() transform. This is because:

  1. The codebase shows consistent use of PILToTensor() followed by unsqueeze(dim=0) for image processing, indicating batch dimension is handled explicitly
  2. ToTensor() is designed to output tensors without the batch dimension, which matches the observed shape changes
  3. The removal of batch dimension is standard practice in PyTorch data transformations, as the batch dimension is typically added later by the DataLoader
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tensor shape expectations in the codebase
rg -A 2 "\.shape\s*==.*384.*384" --glob '!tests/**'

Length of output: 53


Script:

#!/bin/bash
# Search for shape-related assertions or checks in the main codebase
rg -A 2 "shape|size.*384" --glob '!tests/**'

# Search for tensor operations or model forward passes that might expect specific shapes
ast-grep --pattern 'def forward($$$) { $$$ }'

# Look for any configuration files that might specify expected dimensions
fd -e yaml -e json -e ini -e cfg -x cat {}

Length of output: 103031


Script:

#!/bin/bash
# Search for tensor shape expectations in model forward passes and data processing
rg -A 2 "ToTensor|transform.*tensor" --glob '!tests/**'

# Look for any configuration files that specify input/output tensor shapes
rg -A 2 "shape.*384|384.*shape" --glob '!tests/**'

Length of output: 1199

sleap_nn/data/instance_cropping.py (1)

50-55: Verify NaN handling with PIL image conversion.

Since this PR involves converting images to PIL format, let's verify that the NaN handling in this function remains compatible with the new image processing pipeline.

✅ Verification successful

NaN handling is properly tested and compatible with image processing pipeline

The NaN handling in the find_instance_crop_size function is verified to be working correctly:

  • The test file test_instance_cropping.py includes comprehensive tests for instance cropping functionality
  • The NaN handling code is used only for calculating bounding box dimensions and doesn't interact with PIL/image conversion
  • The image cropping is handled separately by kornia.geometry.transform.crop_and_resize after the NaN checks
  • The test test_find_instance_crop_size verifies the core functionality with real instances that could contain NaN values
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for PIL image conversion code that might interact with this function
rg -l "PIL" . | xargs rg "find_instance_crop_size"

# Search for test files that verify NaN handling
rg -l "test.*instance.*crop" . | xargs rg "nan"

Length of output: 96


Script:

#!/bin/bash
# Let's first find the function definition and its usage
ast-grep --pattern 'def find_instance_crop_size'

# Search for any PIL-related image processing in the same file
rg "PIL|Image" sleap_nn/data/instance_cropping.py

# Find tests related to instance cropping
fd "test.*instance.*crop.*\.py$"

Length of output: 174


Script:

#!/bin/bash
# Let's examine the test file to understand how NaN handling is tested
cat tests/data/test_instance_cropping.py

# Let's also look at the full implementation of instance_cropping.py
cat sleap_nn/data/instance_cropping.py

Length of output: 11743

tests/data/test_streaming_datasets.py (3)

170-170: LGTM! Changes align with PR objectives.

The implementation properly tests both scale values and includes appropriate cleanup. The output shape assertions correctly validate the scaling behavior.

Also applies to: 197-216


Line range hint 1-324: Verify test coverage of PIL conversion and resizing.

The tests provide good coverage of the new scaling functionality, but there are a few areas that could be improved:

  1. Test that the images are actually converted to PIL format and back
  2. Verify that the resizing is performed correctly with different aspect ratios
  3. Add error cases for invalid scale values

Let's check if these aspects are covered in other test files:

#!/bin/bash
# Check for PIL conversion tests
rg -l "PIL|Image\.fromarray|ToTensor" tests/
# Check for aspect ratio tests
rg -l "aspect_ratio|different.*width.*height" tests/
# Check for invalid scale tests
rg -l "invalid.*scale|negative.*scale|zero.*scale" tests/

126-126: Consider adding test case with scale=1.0 for consistency.

While the scale parameter is correctly implemented, other test functions include test cases with both scale=0.5 and scale=1.0. Consider adding a similar second test case here for consistency in test coverage.

Let's verify if other files in the test suite follow this pattern:

Also applies to: 144-144

sleap_nn/data/resizing.py (1)

152-152: LGTM: Type consistency improvement

The change from 1 to 1.0 ensures consistent float type returns for the scale ratio, matching the type returned in the resizing branch (eff_scale_ratio).

sleap_nn/data/get_data_chunks.py (2)

Line range hint 1-316: Ensure comprehensive testing of image transformations.

The changes introduce new image transformation logic across multiple functions. Consider:

  1. Adding tests for various scale factors to verify correct resizing
  2. Verifying PIL conversion maintains image quality
  3. Testing memory usage with different image sizes to confirm reduction in .bin file size
  4. Adding integration tests to verify the entire pipeline works with the new transformations
#!/bin/bash
# Check for existing image-related tests
rg -l "test.*image" tests/

161-163: Consider handling dtype conversion consistently.

The explicit conversion to float32 suggests potential dtype compatibility issues. Consider:

  1. Handling dtype conversion earlier in the pipeline
  2. Documenting the expected dtype in the function signature
  3. Adding error handling for unsupported dtypes
✅ Verification successful

Let's search with broader patterns to catch different forms of dtype conversions and documentation.


Dtype conversion is consistently handled across the codebase

The explicit conversion to float32 in get_data_chunks.py aligns with the project's established pattern. The codebase shows:

  • Consistent use of torch.float32 for image processing across multiple modules
  • Explicit dtype assertions in tests confirming float32 expectations
  • Clear documentation in docstrings specifying float32 requirements

The conversion is appropriate and follows the project's conventions. No changes needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other dtype conversions in the codebase
rg "to\(torch\.float32\)" --type py

Length of output: 122


Script:

#!/bin/bash
# Search for dtype conversions with different patterns
rg "\.to\(.*float" --type py -A 2

# Search for tensor type conversions
rg "\.type\(torch\." --type py -A 2

# Search for float dtype mentions in function signatures and docstrings
rg "dtype.*float|float.*dtype" --type py

Length of output: 15563

sleap_nn/data/streaming_datasets.py (2)

Line range hint 1-355: Verify complete implementation of PIL conversion workflow.

The changes in this file implement the PIL to Tensor conversion as intended. However, to ensure the complete workflow is functioning:

  1. Verify that images are properly converted to PIL format in generate_bin_files.py
  2. Confirm that resizing is correctly implemented in get_chunks()
  3. Ensure the conversion maintains image quality while reducing file size
#!/bin/bash
# Check for PIL usage in generate_bin_files.py
rg "PIL" --type python "generate_bin_files.py"

# Check for resize implementation in get_chunks
rg "get_chunks.*scale" --type python

8-8: Verify if resizing imports are still needed.

The apply_resizer import from sleap_nn.data.resizing appears to be unused after the changes, as the resizing functionality has been moved. Consider removing it if it's no longer needed.

Also applies to: 16-16

sleap_nn/training/model_trainer.py (1)

185-186: LGTM: Scale parameter properly integrated

The addition of the scale parameter to the subprocess call is well-implemented and aligns with the PR's objective of supporting image resizing for reduced storage requirements.

sleap_nn/inference/predictors.py (2)

Line range hint 54-55: Addition of max_height and max_width to preprocess_config

The inclusion of max_height and max_width in the preprocess_config dictionary enhances flexibility in image resizing during preprocessing. This allows for better control over the dimensions of input images, which can improve model performance and efficiency.


278-278: ⚠️ Potential issue

Potential redundant normalization of frame["image"]

The apply_normalization function is applied to frame["image"] here, but normalization may already be performed elsewhere in the preprocessing pipeline, potentially leading to redundancy.

Please run the following script to verify if apply_normalization is called on frame["image"] or ex["image"] elsewhere in the codebase:

@gitttt-1234 gitttt-1234 merged commit 176bc94 into main Oct 30, 2024
7 checks passed
@gitttt-1234 gitttt-1234 deleted the divya/fix-get-chunks branch October 30, 2024 20:11
@coderabbitai coderabbitai bot mentioned this pull request Dec 9, 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