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

feat(pt): support loss plugin for external package #4248

Merged
merged 6 commits into from
Oct 26, 2024

Conversation

ChiahsinChu
Copy link
Contributor

@ChiahsinChu ChiahsinChu commented Oct 24, 2024

support loss plugin for external package in pt backend

Summary by CodeRabbit

  • New Features

    • Introduced a new loss class, TaskLoss, enhancing loss functionality in training.
    • Updated loss selection process to dynamically accommodate new loss types.
  • Bug Fixes

    • Improved error handling for unsupported loss types, allowing for more flexible integration.
    • Integrated plugin registry functionality into the TaskLoss class for better registration within the system.

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to the TaskLoss class in the deepmd/pt/loss/loss.py file, allowing it to inherit from a plugin registry in addition to its existing base classes. A new class method, get_loss, is added to facilitate the instantiation of TaskLoss with parameters. Additionally, the get_loss function in deepmd/pt/train/training.py is updated to support dynamic retrieval of loss classes, specifically integrating the new TaskLoss type and improving error handling.

Changes

File Path Change Summary
deepmd/pt/loss/loss.py - Updated TaskLoss class to inherit from make_plugin_registry("loss").
- Added @classmethod def get_loss(cls, loss_params: dict) -> "TaskLoss".
deepmd/pt/train/training.py - Introduced support for TaskLoss in the get_loss function, replacing NotImplementedError with dynamic handling.
- Added import statement for TaskLoss.

Possibly related PRs

  • feat(pt): support CPU parallel training with PT #4224: The changes in this PR introduce a new loss handling mechanism that includes TaskLoss, which is directly related to the modifications made in the main PR where TaskLoss is defined and its instantiation is facilitated through the new get_loss method.

Suggested reviewers

  • njzjz
  • wanghan-iapcm

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.

Copy link

codecov bot commented Oct 24, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 4 lines in your changes missing coverage. Please review.

Project coverage is 84.22%. Comparing base (a66afd3) to head (6fe31cc).
Report is 1 commits behind head on devel.

Files with missing lines Patch % Lines
deepmd/pt/loss/loss.py 66.66% 2 Missing ⚠️
deepmd/pt/train/training.py 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4248      +/-   ##
==========================================
- Coverage   84.23%   84.22%   -0.02%     
==========================================
  Files         548      548              
  Lines       51425    51431       +6     
  Branches     3051     3053       +2     
==========================================
- Hits        43317    43316       -1     
- Misses       7150     7155       +5     
- Partials      958      960       +2     

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

deepmd/pt/train/training.py Show resolved Hide resolved
@njzjz njzjz linked an issue Oct 24, 2024 that may be closed by this pull request
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 (2)
deepmd/pt/loss/loss.py (2)

45-63: LGTM: Well-structured factory method with room for enhancement

The get_loss classmethod provides a clean factory pattern for instantiating loss modules. The docstring follows NumPy style and clearly explains the default behavior.

Consider adding a note in the docstring about parameter validation:

        Parameters
        ----------
        loss_params : dict
-            The loss parameters
+            The loss parameters. Note: Parameter validation should be implemented
+            by concrete subclasses that override this method.

Line range hint 17-63: Excellent plugin architecture design

The integration of the plugin registry with TaskLoss creates a flexible extension point for custom loss implementations. This architecture:

  1. Enables external packages to register custom losses
  2. Maintains backward compatibility through the base implementation
  3. Provides a standardized way to instantiate loss modules

This is a solid foundation for the external package support objective.

Consider documenting the plugin system usage in the module docstring to help external package developers understand how to register their custom losses.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ea941ba and 6fe31cc.

📒 Files selected for processing (1)
  • deepmd/pt/loss/loss.py (2 hunks)
🔇 Additional comments (2)
deepmd/pt/loss/loss.py (2)

12-14: LGTM: Clean import addition

The import of make_plugin_registry is properly placed and follows the project's import style.


17-17: LGTM: Proper inheritance order for plugin support

The inheritance order is correct with torch.nn.Module first (for PyTorch functionality), followed by ABC (for abstract methods), and the plugin registry mixin last.

Let's verify if any external loss plugins are already registered:

✅ Verification successful

Plugin registry implementation is consistent with codebase patterns

The inheritance change is consistent with the established plugin architecture in the codebase:

  • The make_plugin_registry("loss") pattern is used consistently across multiple core components (models, descriptors, fitting, etc.)
  • The inheritance order matches other plugin-enabled classes like DescriptorBlock and Model
  • The loss plugin system is properly integrated with argument checking via loss_args_plugin in deepmd/utils/argcheck.py
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other files that might register loss plugins
rg -l "TaskLoss.register" --type py

Length of output: 35


Script:

#!/bin/bash
# Let's try a broader search to find loss plugin registrations and implementations
# First, find all Python files that might contain loss-related code
echo "=== Files containing 'loss' in their path ==="
fd "loss" -e py

echo -e "\n=== Looking for plugin registration patterns ==="
# Search for register_plugin or similar patterns
rg -i "register.*loss|loss.*register" --type py

echo -e "\n=== Looking for TaskLoss implementations ==="
# Search for classes that inherit from TaskLoss
ast-grep --pattern 'class $_ (TaskLoss)'

Length of output: 850


Script:

#!/bin/bash
# Let's check the actual implementation of loss plugins and registration mechanism
echo "=== Checking loss_args_plugin implementation ==="
rg -A 5 "loss_args_plugin\s*=\s*" --type py

echo -e "\n=== Looking for actual loss implementations ==="
# Search for any class that might be a loss implementation
ast-grep --pattern 'class $_ ($$$Loss$$$)'

echo -e "\n=== Checking make_plugin_registry usage ==="
rg "make_plugin_registry" --type py -A 2

Length of output: 5439

@wanghan-iapcm wanghan-iapcm added this pull request to the merge queue Oct 26, 2024
Merged via the queue into deepmodeling:devel with commit 659f90d Oct 26, 2024
60 checks passed
@ChiahsinChu ChiahsinChu deleted the devel-loss-plugin branch October 27, 2024 02:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature Request] Support plugin for loss (in pytorch backend)
3 participants