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(pd): add se_atten_v2 #4558

Open
wants to merge 3 commits into
base: devel
Choose a base branch
from
Open

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Jan 17, 2025

Has been used for benchmark

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new descriptor type, DescrptSeAttenV2, with advanced embedding and attention mechanisms.
    • Enhanced support for serialization and deserialization of descriptor states.
  • Tests

    • Added comprehensive test coverage for the new descriptor implementation.
    • Expanded testing framework to support multiple backend configurations, including conditional testing for the pd backend.

Signed-off-by: Jinzhe Zeng <[email protected]>
@Copilot Copilot bot review requested due to automatic review settings January 17, 2025 09:48
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

deepmd/pd/model/descriptor/se_atten_v2.py:43

  • [nitpick] The parameter name 'sel' is ambiguous. It should be renamed to 'selection' for clarity.
sel: Union[list[int], int],

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new descriptor class DescrptSeAttenV2 in the DeepMD project. The changes involve adding the new class in se_atten_v2.py, updating the __init__.py to import and expose the class, and extending the test suite to support the new descriptor. The new descriptor includes support for attention mechanisms and improved serialization capabilities, along with enhancements to the testing framework for conditional imports and evaluation.

Changes

File Change Summary
deepmd/pd/model/descriptor/__init__.py Added import for DescrptSeAttenV2 to __all__
deepmd/pd/model/descriptor/se_atten_v2.py Added new DescrptSeAttenV2 class extending DescrptDPA1 with serialization methods
source/tests/consistent/descriptor/test_se_atten_v2.py Updated test suite with conditional imports, new evaluation method, and pd backend support

Sequence Diagram

sequenceDiagram
    participant Descriptor as DescrptSeAttenV2
    participant Serializer as Serialization Methods
    
    Descriptor->>Serializer: serialize()
    Serializer-->>Descriptor: Returns state dictionary
    
    Descriptor->>Serializer: deserialize(data)
    Serializer-->>Descriptor: Reconstructs object instance
Loading

Possibly related PRs

Suggested labels

Docs

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

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
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 UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a3242c4 and 473353e.

📒 Files selected for processing (3)
  • deepmd/pd/model/descriptor/__init__.py (2 hunks)
  • deepmd/pd/model/descriptor/se_atten_v2.py (1 hunks)
  • source/tests/consistent/descriptor/test_se_atten_v2.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
deepmd/pd/model/descriptor/se_atten_v2.py

45-45: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


56-56: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Test Python (1, 3.9)
🔇 Additional comments (5)
deepmd/pd/model/descriptor/se_atten_v2.py (1)

195-275: Implementation of serialize and deserialize methods

The serialize and deserialize methods are well-implemented, handling the conversion of the object's state to and from a dictionary correctly. This ensures that the descriptor can be saved and loaded effectively.

deepmd/pd/model/descriptor/__init__.py (2)

25-27: Correctly added import for DescrptSeAttenV2

The addition of DescrptSeAttenV2 to the imports ensures that the new descriptor is properly included in the module.


43-43: Updated __all__ to include DescrptSeAttenV2

Including DescrptSeAttenV2 in the __all__ list makes it publicly accessible when the module is imported, which is appropriate for this new descriptor.

source/tests/consistent/descriptor/test_se_atten_v2.py (2)

48-53: Conditional import for Paddle backend is appropriate

The conditional import of DescrptSeAttenV2 for the Paddle backend (pd) correctly ensures that the class is only imported when Paddle is installed.


378-387: Added eval_pd method for Paddle backend testing

The eval_pd method is correctly implemented to evaluate the descriptor using the Paddle backend, ensuring consistency in testing across different backends.

deepmd/pd/model/descriptor/se_atten_v2.py Show resolved Hide resolved
deepmd/pd/model/descriptor/se_atten_v2.py Show resolved Hide resolved
source/tests/consistent/descriptor/test_se_atten_v2.py Outdated Show resolved Hide resolved
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

♻️ Duplicate comments (1)
deepmd/pd/model/descriptor/se_atten_v2.py (1)

45-45: ⚠️ Potential issue

Fix mutable default arguments.

Using mutable default values for neuron and exclude_types parameters can lead to unexpected behavior as these defaults are shared across all instances. Use None as the default and initialize the lists in the constructor.

Apply this diff to fix both issues:

-    neuron: list = [25, 50, 100],
+    neuron: Optional[list] = None,
     # ... other parameters ...
-    exclude_types: list[tuple[int, int]] = [],
+    exclude_types: Optional[list[tuple[int, int]]] = None,

Then initialize them in the constructor:

def __init__(self, ...):
    if neuron is None:
        neuron = [25, 50, 100]
    if exclude_types is None:
        exclude_types = []
    # ... rest of the initialization

Also applies to: 56-56

🧰 Tools
🪛 Ruff (0.8.2)

45-45: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

🧹 Nitpick comments (3)
deepmd/pd/model/descriptor/se_atten_v2.py (3)

75-155: Improve docstring formatting for better readability.

The docstring has comprehensive parameter descriptions but could benefit from better formatting:

  • The math equations could use consistent formatting
  • Some parameter descriptions could be more concise

Consider reformatting math equations consistently, for example:

  • :math:r_c`` → :math:r_{\text{c}}`
  • :math:r_s`` → :math:r_{\text{s}}`

195-242: Add validation for critical fields in serialization.

While the serialization is comprehensive, consider adding validation for critical fields to ensure data integrity:

 def serialize(self) -> dict:
     obj = self.se_atten
+    # Validate critical fields
+    if obj.rcut <= 0:
+        raise ValueError("rcut must be positive")
+    if obj.rcut_smth >= obj.rcut:
+        raise ValueError("rcut_smth must be less than rcut")
+    if obj.ntypes <= 0:
+        raise ValueError("ntypes must be positive")
     data = {
         "@class": "Descriptor",
         # ... rest of the serialization

260-261: Enhance tensor conversion with error handling.

The tensor conversion function could be more robust by adding error handling and type checking:

 def t_cvt(xx):
+    if not isinstance(xx, (numpy.ndarray, list)):
+        raise TypeError(f"Expected numpy array or list, got {type(xx)}")
+    try:
         return paddle.to_tensor(xx, dtype=obj.se_atten.prec, place=env.DEVICE)
+    except Exception as e:
+        raise ValueError(f"Failed to convert tensor: {e}")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cbf7536 and 953f243.

📒 Files selected for processing (1)
  • deepmd/pd/model/descriptor/se_atten_v2.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
deepmd/pd/model/descriptor/se_atten_v2.py

45-45: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


56-56: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Analyze (python)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Build C++ (cpu, cpu)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Test C++ (true)
🔇 Additional comments (1)
deepmd/pd/model/descriptor/se_atten_v2.py (1)

1-38: LGTM! Well-organized imports and proper class registration.

The imports are logically grouped and the class is properly registered using the decorator pattern.

Copy link

codecov bot commented Jan 18, 2025

Codecov Report

Attention: Patch coverage is 97.72727% with 1 line in your changes missing coverage. Please review.

Project coverage is 84.61%. Comparing base (a3242c4) to head (953f243).

Files with missing lines Patch % Lines
deepmd/pd/model/descriptor/se_atten_v2.py 97.67% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##            devel    #4558   +/-   ##
=======================================
  Coverage   84.60%   84.61%           
=======================================
  Files         680      681    +1     
  Lines       64468    64513   +45     
  Branches     3538     3538           
=======================================
+ Hits        54546    54588   +42     
- Misses       8781     8783    +2     
- Partials     1141     1142    +1     

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

@njzjz njzjz requested a review from wanghan-iapcm January 18, 2025 10:09
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.

1 participant