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 FiftyOneTorchDataset #5321

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open

Add FiftyOneTorchDataset #5321

wants to merge 21 commits into from

Conversation

jacobsela
Copy link
Contributor

@jacobsela jacobsela commented Dec 27, 2024

What changes are proposed in this pull request?

  1. New class FiftyOneTorchDataset.
  2. added top-level to_torch method.
  3. some DDP utils.
  4. Recipes for use (still missing DDP example)

How is this patch tested? If it is not, please explain why.

  1. Benchmarked memory footprint
  2. Benchmarked dataset latency
  3. Validated data loaders load correct samples for each trainer
  4. Trained mint classifier w/ new class.
  5. Currently training MAGE in a DDP setup - will report results.

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

New to_torch method allows for easy transfer to a fully functional torch.utils.data.Dataset object.
Please see recipes for examples and tutorials.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other - fiftyone.utils.torch

Summary by CodeRabbit

  • New Features

    • Introduced a script for training and validating models using the MNIST dataset with PyTorch.
    • Added a new Jupyter notebook for a basic training example with the MNIST dataset.
    • Implemented a method to convert sample collections into a PyTorch-compatible format.
    • Added a new class for creating PyTorch datasets from FiftyOne datasets, enhancing integration with distributed training.
    • Introduced several utility functions and classes to optimize data handling in distributed training environments.
  • Bug Fixes

    • Improved data handling and efficiency in multi-worker environments.
  • Documentation

    • Enhanced clarity with markdown explanations in the new Jupyter notebook.

@jacobsela jacobsela added the feature Work on a feature request label Dec 27, 2024
Copy link
Contributor

coderabbitai bot commented Dec 27, 2024

Walkthrough

This pull request introduces a comprehensive set of tools and scripts for training machine learning models using the MNIST dataset with FiftyOne and PyTorch. The changes include a training script (mnist_training.py), a Jupyter notebook example (simple_training_example.ipynb), utility functions (utils.py), and enhancements to FiftyOne's core collections and torch utilities. The modifications provide a complete workflow for dataset management, model training, and evaluation, with a focus on flexibility and ease of use in machine learning experiments.

Changes

File Change Summary
docs/source/recipes/torch-dataset-examples/mnist_training.py Added main training script with functions for model training, validation, and epoch processing
docs/source/recipes/torch-dataset-examples/simple_training_example.ipynb New Jupyter notebook demonstrating MNIST dataset training with FiftyOne and PyTorch
docs/source/recipes/torch-dataset-examples/utils.py Introduced utility functions for dataset processing, data loading, and model setup
fiftyone/core/collections.py Added to_torch() method to SampleCollection for PyTorch dataset conversion
fiftyone/utils/torch.py Implemented FiftyOneTorchDataset and related serialization classes for distributed training support
docs/source/recipes/torch-dataset-examples/ddp_train.py Introduced script for training with Distributed Data Parallel (DDP) using PyTorch and FiftyOne

Possibly related PRs

Suggested reviewers

  • mwoodson1
  • jacobmarks

Poem

🐰 Behold, a dataset's dance divine,
Where MNIST digits softly align,
With PyTorch's might and FiftyOne's grace,
We train our model at lightning's pace!
A rabbit's code, both swift and bright! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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.

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 (8)
fiftyone/utils/torch.py (1)

1605-1605: Use is for None checks

This line compares to None using ==. For clarity and correctness, prefer is None.

- if self._samples == None:
+ if self._samples is None:
🧰 Tools
🪛 Ruff (0.8.2)

1605-1605: Comparison to None should be cond is None

Replace with cond is None

(E711)

docs/source/recipes/torch-dataset-examples/mnist_training.py (1)

12-39: [Function main: handle partial device availability?]

Great job customizing device usage. Consider adding a fallback for cases where "cuda:0" or the specified device is not available, e.g. defaulting to CPU.

docs/source/recipes/torch-dataset-examples/utils.py (3)

1-1: Remove unused import if truly unnecessary

It appears import fiftyone as fo is unused here. Removing it can improve clarity and avoid confusion.

- import fiftyone as fo
+ # remove if truly not needed
🧰 Tools
🪛 Ruff (0.8.2)

1-1: fiftyone imported but unused

Remove unused import: fiftyone

(F401)


131-131: Replace unnecessary ternary with direct comparison

Use a direct boolean expression to simplify logic.

- shuffle = True if split_tag == "train" else False
+ shuffle = (split_tag == "train")
🧰 Tools
🪛 Ruff (0.8.2)

131-131: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)


142-150: [setup_model: consider user flexibility]

Some users might need a different backbone or weights. Possibly add a parameter to switch from ResNet18 to other architectures?

docs/source/recipes/torch-dataset-examples/simple_training_example.ipynb (1)

68-68: Typographical correction in markdown

"traing" => "training" to maintain clarity in documentation.

- Now we will look at an actual traing script with `FiftyOneTorchDataset`
+ Now we will look at an actual training script with `FiftyOneTorchDataset`
fiftyone/core/collections.py (2)

10973-10978: Consider adding type hints for better IDE support

The method could benefit from type hints for the get_item parameter and return type to improve IDE support and code clarity.

-    def to_torch(self, get_item, **kwargs):
+    def to_torch(self, get_item: Callable[[Any], Any], **kwargs) -> "FiftyOneTorchDataset":

10973-10978: Consider adding validation for the get_item parameter

The method should validate that get_item is a callable to provide a better error message.

     def to_torch(self, get_item, **kwargs):
+        if not callable(get_item):
+            raise ValueError(
+                "The 'get_item' parameter must be a callable that accepts a sample and "
+                "returns the corresponding tensor(s)"
+            )
         from fiftyone.utils.torch import FiftyOneTorchDataset
         return FiftyOneTorchDataset(self, get_item, **kwargs)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 18dde78 and e08a447.

📒 Files selected for processing (5)
  • docs/source/recipes/torch-dataset-examples/mnist_training.py (1 hunks)
  • docs/source/recipes/torch-dataset-examples/simple_training_example.ipynb (1 hunks)
  • docs/source/recipes/torch-dataset-examples/utils.py (1 hunks)
  • fiftyone/core/collections.py (1 hunks)
  • fiftyone/utils/torch.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
docs/source/recipes/torch-dataset-examples/utils.py

1-1: fiftyone imported but unused

Remove unused import: fiftyone

(F401)


131-131: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)

fiftyone/utils/torch.py

1605-1605: Comparison to None should be cond is None

Replace with cond is None

(E711)

🔇 Additional comments (25)
fiftyone/utils/torch.py (10)

13-15: [Imports look good]

No issues found with these imports.


32-34: [Imports look good]

No issues found with these imports.


41-41: [Distributed import looks good]

No issues found with this import.


1470-1551: [Comprehensive class docstring, few content suggestions]

The docstring is highly informative. However, consider briefly specifying the expected return type in get_item (e.g., dict, tensor, or custom object) to clarify type-checking needs.


1610-1614: [Worker init logic seems correct]

The worker_init approach is aligned with best practices for DataLoader workers. Ensure thorough testing in multi-worker scenarios to confirm memory usage remains stable.


1640-1645: [Good specialized logic for cached fields]

This dictionary-based approach for returning sample data is solid for decoupling data loading from the main process. Continue ensuring the data schema remains stable across training epochs.


2220-2244: [NumpySerializedList Implementation]

Serializing data to a numpy array of bytes is a clever approach. Be aware of potential overhead for extremely large datasets.


2255-2266: [TorchSerializedList Implementation]

Converting to torch tensors is convenient for consistency with PyTorch. Looks solid.


2268-2298: [Shared memory approach]

The design for distributing serialized data across local DDP ranks is well-thought-out. Ensure proper cleanup of shared memory resources after training completes to prevent memory leaks.


2300-2351: [DDP Communication Routines]

These distributed utilities (e.g., all_gather, local_scatter) are essential for multi-rank synchronization. Make sure you test corner cases with a single rank or large multi-GPU clusters.

docs/source/recipes/torch-dataset-examples/mnist_training.py (3)

12-39: [Potential File Save Race Condition]

When saving models (torch.save(...)), measuring the overhead or ensuring concurrency safety might be needed if multiple processes attempt to save.


62-83: [Function train_epoch: structured approach looks good]

Make sure large-scale loads into batch don’t cause memory fragmentation under certain expansions of dataset size or dynamic input shapes.


86-127: [Function validation: good usage of no_grad()]

This function properly detaches computations. Just be mindful that updates to dataset._dataset.select(...) inside your loop might cause overhead if repeated too frequently on large sets.

docs/source/recipes/torch-dataset-examples/utils.py (10)

17-37: [Function get_item_quickstart: correct bounding box transformation]

Looks good. Keep in mind that large bounding box lists might impact performance if done repeatedly.


39-59: [Function get_item_cached_quickstart: consistent approach with get_item_quickstart]

The code is consistent. Validate that the fields in sample_dict exactly match your bounding box transformations to avoid index or key errors.


61-63: [Collate function: flexible approach]

Returning tuples of (image, label) as separate items is typical. If you foresee multi-output tasks or dynamic batching, consider a more advanced approach.


65-75: [Simple DataLoader creation: good reference]

This sets the stage for an easy integration with FiftyOneTorchDataset. No issues noted.


77-84: [ids_in_dataloader: demonstration function]

This demonstration function is helpful for basic usage. Keep an eye out for large memory usage if the dataset is big.


86-101: [Mapping MNIST indexes to strings: straightforward & clear]

No issues found. This is a good reference for labeling in logs.


103-107: [convert_and_normalize: future deprecation]

The warning about ToTensor() is relevant. Keep in mind that a future replacement with v2.ToImage() and v2.ToDtype(...) might be necessary.


110-118: [mnist_get_item: looks correct]

The function is straightforward. If the label format changes, ensure this integer parsing remains valid.


120-139: [create_dataloaders: flexible for train/val/test splits]

Ensure you handle the scenario when one or more splits are empty or missing tags.

🧰 Tools
🪛 Ruff (0.8.2)

131-131: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)


152-155: [setup_optim: standard setup]

This is a reasonable default. If hyperparameter tuning is frequent, consider making LR or L2 configurable at runtime.

fiftyone/core/collections.py (2)

10973-10978: LGTM: Clean implementation of the to_torch method

The implementation correctly delegates to FiftyOneTorchDataset while maintaining a clean interface. The docstring reference to the implementation class provides good discoverability.


10973-10978: Verify PyTorch dependency availability

Since this method integrates with PyTorch, we should verify that PyTorch is available when this method is called.

✅ Verification successful

PyTorch dependency is properly handled

The codebase already has proper PyTorch dependency verification through fou.ensure_torch() which is called before importing torch in the fiftyone/utils/torch.py module. This function verifies that both torch and torchvision are installed and importable. Since the to_torch() method imports from fiftyone.utils.torch, which handles the dependency check, no additional verification is needed in the method itself.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if torch is listed as a dependency
grep -r "torch" setup.py requirements*.txt

Length of output: 41


Script:

#!/bin/bash
# Search for torch-related imports and try-except blocks
rg "torch" -A 5 -B 5

Length of output: 82613


Script:

#!/bin/bash
# Search for optional dependencies setup
rg "extras_require" setup.py

Length of output: 28


Script:

#!/bin/bash
# Look for any torch-related error handling
ast-grep --pattern 'try {
  $$$
  import torch
  $$$
} catch ($$$) {
  $$$
}'

Length of output: 79


Script:

#!/bin/bash
# Look for torch import handling in the specific file
rg "torch" -B 5 -A 5 fiftyone/core/collections.py

# Look for any import error handling patterns
rg "ImportError" -B 5 -A 5 fiftyone/core/collections.py

Length of output: 3228


Script:

#!/bin/bash
# Check the torch utility module for any import error handling
rg "import.*torch" -B 5 -A 5 fiftyone/utils/torch.py

# Look for any torch-related imports in __init__.py files
rg "import.*torch" -B 5 -A 5 "**/__init__.py"

Length of output: 2442


Script:

#!/bin/bash
# Look for ensure_torch function implementation
rg "ensure_torch" -B 5 -A 5 fiftyone/utils/

# Look for any torch-related imports in utils directory
rg "import.*torch" -B 5 -A 5 fiftyone/utils/

Length of output: 15094


Script:

#!/bin/bash
# Look for ensure_torch implementation in core/utils.py
rg "def ensure_torch" -B 5 -A 10 fiftyone/core/utils.py

Length of output: 488

@jacobsela
Copy link
Contributor Author

MAGE training successful. Very coarse test, but nice to see still.
image

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 (8)
docs/source/recipes/torch-dataset-examples/ddp_train.py (5)

39-45: Confirm dataset loading approach

Each process is synchronously loading the same dataset locally, which can increase memory usage for large datasets. Confirm whether this is the intended design or if a shared or streamed approach would be more efficient.


81-81: Fix minor spelling in log message

"New best lost achieved" appears to be a typo. Change "lost" to "loss" for clarity.

- print(f"New best lost achieved : {best_loss}. Saving model...")
+ print(f"New best loss achieved : {best_loss}. Saving model...")

86-90: Remove redundant .to(DEVICES[local_rank]) call

Line 89 and 90 both move the model to the same device. You can remove one to avoid duplication.

model = utils.setup_ddp_model(
    num_classes=num_classes,
    weights_path=f"{save_dir}/epoch_{best_epoch}.pt",
).to(DEVICES[local_rank])
- model.to(DEVICES[local_rank])
ddp_model = torch.nn.parallel.DistributedDataParallel(
    model, device_ids=[DEVICES[local_rank]]
)

125-125: Correct the spelling of “cummulative_loss”

Use “cumulative_loss” for clearer communication.

- cummulative_loss = 0
+ cumulative_loss = 0

And update its usage accordingly in lines 142 and 157 as well.

Also applies to: 142-142, 157-157


143-144: Refactor nested if statements

You can combine these nested if statements for simpler logic, per the static analysis suggestion.

-if local_rank == 0:
-    if batch_num % 100 == 0:
+if local_rank == 0 and batch_num % 100 == 0:
     pbar.set_description(...)

Also applies to: 193-194

🧰 Tools
🪛 Ruff (0.8.2)

143-144: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

docs/source/recipes/torch-dataset-examples/utils.py (3)

1-1: Remove unused import [fiftyone].

The module is never referenced in the code, so you can safely delete this import line.

- import fiftyone as fo
🧰 Tools
🪛 Ruff (0.8.2)

1-1: fiftyone imported but unused

Remove unused import: fiftyone

(F401)


118-137: Function create_dataloaders: simplify conditional assignment to boolean.

Line 129 uses shuffle = True if split_tag == "train" else False. This can be simplified to:

shuffle = (split_tag == "train")
🧰 Tools
🪛 Ruff (0.8.2)

129-129: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)


164-186: Function create_dataloaders_ddp: simplify conditional assignment to boolean.

Line 175 uses shuffle = True if split_tag == "train" else False. This can be simplified to:

shuffle = (split_tag == "train")
🧰 Tools
🪛 Ruff (0.8.2)

175-175: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e08a447 and fa8db3d.

📒 Files selected for processing (2)
  • docs/source/recipes/torch-dataset-examples/ddp_train.py (1 hunks)
  • docs/source/recipes/torch-dataset-examples/utils.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
docs/source/recipes/torch-dataset-examples/ddp_train.py

143-144: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


193-194: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

docs/source/recipes/torch-dataset-examples/utils.py

1-1: fiftyone imported but unused

Remove unused import: fiftyone

(F401)


129-129: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)


175-175: Remove unnecessary True if ... else False

Remove unnecessary True if ... else False

(SIM210)

🔇 Additional comments (17)
docs/source/recipes/torch-dataset-examples/ddp_train.py (3)

14-30: Ensure environment variables are defined

The code relies on environment variables like WORLD_SIZE, LOCAL_WORLD_SIZE, and RANK. Consider adding error handling or clear messages if they are not set, to prevent runtime failures in distributed settings.


176-190: Evaluate performance impact of per-batch dataset updates

Calling dataset._dataset.select(batch["id"]).set_values(...) and samples.save() for each batch can be costly for large datasets. Consider batching result writing or deferring it until after validation to reduce overhead.
[performance]


201-207: Clarify execution instructions

The inline comment shows an example command for 6 processes (--nproc-per-node=6), but the example sets --devices 2 3 4 5 6 7, which are 6 GPUs. It would be helpful to clarify these arguments to ensure they match real-world usage scenarios (e.g., confirming GPU device IDs and process counts).

docs/source/recipes/torch-dataset-examples/utils.py (14)

2-2: Import usage .

from fiftyone.utils.torch import FiftyOneTorchDataset is used below, so this import is necessary.


4-15: Imports and augmentation pipeline .

No immediate concerns or suggestions. The augmentation pipeline is clearly defined and easy to follow.


17-37: Function get_item_quickstart .

The workflow to open the image, compute bounding boxes, and apply augmentations is clear and logical. Your handling of empty detections with a zero-tensor is appropriately done.


39-59: Function get_item_cached_quickstart .

Similar to get_item_quickstart, this approach for working with a cached sample dictionary is clear and logically consistent.


61-62: Function simple_collate_fn .

This is a valid approach that returns data in an easily unpackable tuple. No changes needed.


65-75: Function create_dataloader_simple .

DataLoader creation is straightforward, and the use of FiftyOneTorchDataset.worker_init is correctly applied. No issues found.


77-84: Function ids_in_dataloader .

Retrieving IDs from batches for verification is a helpful debugging utility. The assertion for batch size ensures the logic is working as intended.


87-101: Function mnist_index_to_label_string .

Provides a neat mapping from label indices to strings. No concerns here.


103-105: Transformation convert_and_normalize .

It neatly converts images to the proper format for PyTorch and normalizes pixel values. All good here.


108-116: Function mnist_get_item .

Processing MNIST samples into a dictionary is well-executed. The label extraction is direct and understandable.


140-148: Function setup_model .

Configuring a ResNet18 plus linear head is appropriately done. Loading weights conditionally is also clear.


150-153: Function setup_optim .

Simple, well-defined SGD optimizer creation. No issues spotted.


158-162: Function setup_ddp_model .

Applying convert_sync_batchnorm is the recommended practice for DDP. Steps are logical.


188-190: No-op main guard .

The if __name__ == "__main__": pass block can be helpful when multiprocessing in notebooks. It’s fine to keep as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Work on a feature request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant