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

Transformers GPU Support #4987

Merged
merged 2 commits into from
Dec 18, 2024
Merged

Transformers GPU Support #4987

merged 2 commits into from
Dec 18, 2024

Conversation

danielgural
Copy link
Contributor

@danielgural danielgural commented Oct 24, 2024

What changes are proposed in this pull request?

Adding GPU support to transformers utils

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

Run this notebook tutorial with gpu https://docs.voxel51.com/integrations/huggingface.html#batch-inference

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.

(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

Summary by CodeRabbit

  • New Features

    • Improved device management for model and processor allocation, ensuring models load on the appropriate device (CUDA or CPU) seamlessly.
  • Bug Fixes

    • Streamlined logic for device assignment during model loading, enhancing consistency across different transformer classes.

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes primarily involve modifications to device allocation handling for models and processors in the fiftyone/utils/transformers.py file. The device determination logic has been simplified to utilize torch.cuda.is_available(), ensuring models and processors are assigned to "cuda" if available, or defaulting to "cpu". The _load_model methods across various transformer classes have been updated to explicitly move models to the appropriate device upon loading, enhancing consistency in device management.

Changes

File Path Change Summary
fiftyone/utils/transformers.py - Updated device allocation logic in FiftyOneTransformer, FiftyOneZeroShotTransformer, and other transformer classes to use torch.cuda.is_available().
- Modified _load_model methods to ensure models and processors are moved to the designated device upon loading.
- Adjusted _get_detector_from_processor and _get_model_for_image_text_retrieval functions for direct model loading on specified device.

Possibly related PRs

  • Enable GPU inference for transformers models #4587: The changes in this PR also focus on device management for the FiftyOneTransformer class, specifically enhancing the handling of device allocation for tensor operations, which aligns closely with the modifications made in the main PR regarding device assignment logic.

Suggested reviewers

  • jacobmarks

🐰 In the land of code, where models reside,
A hop for the device, we take in our stride.
With CUDA now checked, and tensors in place,
Our transformers are ready, they quicken their pace.
So let’s load them with care, on devices they’ll thrive,
In the world of FiftyOne, our models come alive! 🌟


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.

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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 048d041 and 3d6084f.

📒 Files selected for processing (1)
  • fiftyone/utils/transformers.py (12 hunks)
🔇 Additional comments (1)
fiftyone/utils/transformers.py (1)

Line range hint 1-1089: Implementation successfully adds GPU support.

The changes effectively implement GPU support for transformer models, aligning with the PR objectives. The implementation consistently moves models to GPU when available, which should improve inference performance as intended.

Verify GPU usage with:

✅ Verification successful

The search results confirm that CUDA support is consistently implemented across the transformers module and other related modules in the codebase. Let me verify the device handling implementation further:


GPU support implementation verified successfully

The implementation properly handles GPU support across the transformers module with:

  • Consistent device detection using torch.cuda.is_available()
  • Proper model movement to GPU using .to(device) for all model operations
  • Correct tensor operations on the target device
  • Consistent pattern of device handling across different transformer model types

The implementation follows PyTorch best practices for GPU utilization and maintains consistency with the rest of the codebase's GPU support patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if CUDA operations are properly implemented
rg "cuda" --type py

Length of output: 1885


Script:

#!/bin/bash
# Check if device property is properly used with CUDA tensors
rg "\.to\(.*device" --type py

Length of output: 1984

self.device = (
"cuda" if next(self.model.parameters()).is_cuda else "cpu"
)
self.device = "cuda" if torch.cuda.is_available() else "cpu"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor repeated device determination logic.

The device determination logic device = "cuda" if torch.cuda.is_available() else "cpu" is duplicated across multiple locations. Consider centralizing this into a utility function to improve maintainability and reduce code duplication.

Create a utility function at the module level:

def get_device():
    return "cuda" if torch.cuda.is_available() else "cpu"

Then replace all occurrences with:

self.device = get_device()
# or
device = get_device()

Also applies to: 499-499, 584-584, 696-696, 751-751, 824-824, 878-878, 932-932, 1087-1087

Comment on lines +585 to +587
model = transformers.AutoModel.from_pretrained(config.name_or_path).to(
device
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for CUDA memory allocation.

When loading models to GPU, consider adding error handling for CUDA out of memory scenarios. This is particularly important for large transformer models.

Add try-catch block around model loading:

try:
    model = transformers.AutoModel.from_pretrained(config.name_or_path).to(device)
except torch.cuda.OutOfMemoryError:
    logger.warning("CUDA out of memory. Falling back to CPU")
    device = "cpu"
    model = transformers.AutoModel.from_pretrained(config.name_or_path).to(device)

Also applies to: 698-699, 826-827, 881-882, 934-935

Comment on lines +760 to +762
return transformers.AutoProcessor.from_pretrained(name_or_path).to(
self.device
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary processor device movement.

Moving the processor to device with .to(device) is unnecessary as the processor is typically a CPU-bound operation that handles preprocessing. This could unnecessarily consume GPU memory.

Remove the device movement:

-return transformers.AutoProcessor.from_pretrained(name_or_path).to(
-    self.device
-)
+return transformers.AutoProcessor.from_pretrained(name_or_path)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return transformers.AutoProcessor.from_pretrained(name_or_path).to(
self.device
)
return transformers.AutoProcessor.from_pretrained(name_or_path)

Copy link
Contributor

@mwoodson1 mwoodson1 left a comment

Choose a reason for hiding this comment

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

lgtm!

@danielgural danielgural merged commit ff0c2e7 into develop Dec 18, 2024
13 checks passed
@danielgural danielgural deleted the zoo_gpu branch December 18, 2024 18:03
@coderabbitai coderabbitai bot mentioned this pull request Dec 27, 2024
7 tasks
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.

2 participants