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

Allow ragged_batches to be configured when using Torch models with custom transforms #4512

Merged
merged 5 commits into from
Jun 27, 2024

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Jun 18, 2024

Resolves #4508

Completes #4509 as per #4509 (review).

Summary by CodeRabbit

  • New Features
    • Introduced a ragged_batches parameter to the batch inference functionality, allowing for the handling of tensors of different sizes.

Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Walkthrough

The new changes in fiftyone/utils/torch.py introduce a ragged_batches parameter that allows handling tensors of different sizes during batch inference. This modification provides flexibility for batch processing and resolves issues with custom transformation logic overriding batch inference behavior.

Changes

Files Change Summary
fiftyone/utils/torch.py Added ragged_batches parameter in predict_all function, updated PredictorConfig and TorchModel to handle it.

Possibly related issues

Poem

In dreams of tensors vast and wide,
ragged_batches now stand side by side,
With models nude yet brave and bold,
Through code, new stories will unfold.
Batch by batch, they'll swiftly glide,
Free at last, no need to hide.


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 Configration 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 and nitpick comments (7)
fiftyone/utils/torch.py (7)

Line range hint 31-34: Imports should be placed at the top of the file.

- import torch
- import torchvision
- from torchvision.transforms import functional as F
- from torch.utils.data import Dataset

Move these imports to the top of the file to adhere to PEP 8 standards for better readability and maintenance.


Line range hint 167-167: Unnecessary open mode parameters in file open operation.

- with open(req_path, "r") as f:
+ with open(req_path) as f:

The default mode for open() is 'r' (read), so specifying it is redundant.


Line range hint 283-286: Simplify conditional assignments using ternary operators.

- if isinstance(arg, torch.Tensor):
-     args = arg.unsqueeze(0)
- else:
-     args = [arg]
+ args = arg.unsqueeze(0) if isinstance(arg, torch.Tensor) else [arg]

- if isinstance(img, torch.Tensor):
-     imgs = img.unsqueeze(0)
- else:
-     imgs = [img]
+ imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img]

- if isinstance(img, torch.Tensor):
-     imgs = img.unsqueeze(0)
- else:
-     imgs = [img]
+ imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img]

- if sample is not None:
-     samples = [sample]
- else:
-     samples = None
+ samples = [sample] if sample is not None else None

These changes make the code more concise and maintainable by using Python's ternary conditional operator.

Also applies to: 666-669, 879-882, 884-887


Line range hint 892-892: Remove unnecessary inheritance from object.

- class ToPILImage(object):
+ class ToPILImage:

- class MinResize(object):
+ class MinResize:

- class MaxResize(object):
+ class MaxResize:

- class PatchSize(object):
+ class PatchSize:

- class SaveLayerTensor(object):
+ class SaveLayerTensor:

- class OutputProcessor(object):
+ class OutputProcessor:

In Python 3, all classes implicitly inherit from object, so explicitly deriving from object is redundant and not needed.

Also applies to: 904-904, 942-942, 980-980, 1006-1006, 1047-1047


Line range hint 1042-1042: Use format specifiers instead of percent format for string formatting.

- raise ValueError("No layer found with name %s" % layer_name)
+ raise ValueError(f"No layer found with name {layer_name}")

- raise ValueError("Image '%s' has no patches" % filepath)
+ raise ValueError(f"Image '{filepath}' has no patches")

- raise ValueError("Patches field '%s' has unsupported type %s" % (patches_field, label_type))
+ raise ValueError(f"Patches field '{patches_field}' has unsupported type {label_type}")

- raise ValueError("Either `image_paths` or `samples` must be provided")
+ raise ValueError("Either 'image_paths' or 'samples' must be provided")

Using f-strings provides a more readable, concise, and Pythonic way of formatting strings.

Also applies to: 1916-1916, 1939-1940, 1961-1961


Line range hint 1446-1446: Avoid using bare 'except' statements.

- except:
+ except Exception as e:

Catching Exception is generally safer than a bare except as it avoids accidentally catching system-exiting exceptions such as SystemExit and KeyboardInterrupt.


Line range hint 1689-1692: Use ternary operators for conditional assignments.

- if etau.is_str(targets):
-     targets = samples.values(targets)
- else:
-     targets = list(targets)
+ targets = samples.values(targets) if etau.is_str(targets) else list(targets)

- if str_targets:
-     targets = _to_bytes_array(targets)
- else:
-     targets = np.array(targets)
+ targets = _to_bytes_array(targets) if str_targets else np.array(targets)

Using ternary operators can simplify the code and improve readability.

Also applies to: 1695-1698

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d095b22 and fdd6117.

Files selected for processing (1)
  • fiftyone/utils/torch.py (3 hunks)
Additional context used
Ruff
fiftyone/utils/torch.py

31-31: Module level import not at top of file (E402)


32-32: Module level import not at top of file (E402)


33-33: Module level import not at top of file (E402)


34-34: Module level import not at top of file (E402)


167-167: Unnecessary open mode parameters (UP015)

Remove open mode parameters


283-286: Use ternary operator args = arg.unsqueeze(0) if isinstance(arg, torch.Tensor) else [arg] instead of if-else-block (SIM108)

Replace if-else-block with args = arg.unsqueeze(0) if isinstance(arg, torch.Tensor) else [arg]


666-669: Use ternary operator imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img] instead of if-else-block (SIM108)

Replace if-else-block with imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img]


879-882: Use ternary operator imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img] instead of if-else-block (SIM108)

Replace if-else-block with imgs = img.unsqueeze(0) if isinstance(img, torch.Tensor) else [img]


884-887: Use ternary operator samples = [sample] if sample is not None else None instead of if-else-block (SIM108)

Replace if-else-block with samples = [sample] if sample is not None else None


892-892: Class ToPILImage inherits from object (UP004)

Remove object inheritance


904-904: Class MinResize inherits from object (UP004)

Remove object inheritance


942-942: Class MaxResize inherits from object (UP004)

Remove object inheritance


980-980: Class PatchSize inherits from object (UP004)

Remove object inheritance


1006-1006: Class SaveLayerTensor inherits from object (UP004)

Remove object inheritance


1042-1042: Use format specifiers instead of percent format (UP031)

Replace with format specifiers


1047-1047: Class OutputProcessor inherits from object (UP004)

Remove object inheritance


1446-1446: Do not use bare except (E722)


1689-1692: Use ternary operator targets = samples.values(targets) if etau.is_str(targets) else list(targets) instead of if-else-block (SIM108)

Replace if-else-block with targets = samples.values(targets) if etau.is_str(targets) else list(targets)


1695-1698: Use ternary operator targets = _to_bytes_array(targets) if str_targets else np.array(targets) instead of if-else-block (SIM108)

Replace if-else-block with targets = _to_bytes_array(targets) if str_targets else np.array(targets)


1916-1916: Use format specifiers instead of percent format (UP031)

Replace with format specifiers


1939-1940: Use format specifiers instead of percent format (UP031)

Replace with format specifiers


1961-1961: Use format specifiers instead of percent format (UP031)

Replace with format specifiers

@brimoor brimoor mentioned this pull request Jun 20, 2024
7 tasks
@jacobmarks
Copy link
Contributor

Hey @dimidagd sorry for the delayed review. At CVPR, so things are pretty hectic. The implementation looks sound and doesn't break anything for me. Do you have an example transform I could use to test this out?

Copy link
Contributor

@jacobmarks jacobmarks left a comment

Choose a reason for hiding this comment

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

LGTM 👍

@brimoor brimoor merged commit 4203e7e into develop Jun 27, 2024
12 checks passed
@brimoor brimoor deleted the fix/ragged-batches branch June 27, 2024 03:54
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.

TorchImageModel Ragged batches cfg value
3 participants