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(tf): support tensor fitting with hybrid descriptor #4542

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

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Jan 8, 2025

Fix #4527.

Summary by CodeRabbit

  • New Features

    • Added rotation matrix handling methods to descriptor classes.
    • Introduced validation for model initialization.
  • Bug Fixes

    • Improved error handling for fitting network configuration.
  • Tests

    • Added new test suite for dipole hybrid descriptor model validation.
  • Refactor

    • Enhanced descriptor class functionality with default rotation matrix methods.

Choose a reason for hiding this comment

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

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

Comments suppressed due to low confidence (2)

deepmd/tf/model/model.py:672

  • The error message should be more specific. Suggestion: "The descriptor's embedding width is zero, indicating it cannot provide a rotation matrix for tensorial fitting. Please check the descriptor configuration."
raise ValueError("This descriptor cannot provide a rotation matrix for a tensorial fitting.")

deepmd/tf/descriptor/descriptor.py:543

  • [nitpick] Returning a tensor with a zero dimension might lead to confusion or unexpected behavior. Consider revising the implementation to handle cases where no rotation matrix is provided more explicitly.
return tf.zeros([nframes, natoms, 0], dtype=GLOBAL_TF_FLOAT_PRECISION)
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the Descriptor and DescrptHybrid classes in the DeePMD-kit project, focusing on implementing rotation matrix handling methods. The changes include adding get_rot_mat and get_dim_rot_mat_1 methods to both classes, and introducing an input_requirement property. Additionally, a validation step is added to the StandardModel class to ensure the embedding width is non-zero. A new test file test_dipole_hybrid_descrpt.py is also created to validate the dipole model functionality with hybrid descriptors.

Changes

File Change Summary
deepmd/tf/descriptor/descriptor.py - Added get_rot_mat method returning a zero tensor
- Modified get_dim_rot_mat_1 to return 0
- Added input_requirement property
deepmd/tf/descriptor/hybrid.py - Added get_dim_rot_mat_1 method summing descriptor rotation matrix dimensions
- Added get_rot_mat method concatenating descriptor rotation matrices
deepmd/tf/model/model.py - Added validation for embedding_width in fitting network initialization
source/tests/tf/test_dipole_hybrid_descrpt.py - New test file for dipole model with hybrid descriptors

Assessment against linked issues

Objective Addressed Explanation
Fix NotImplementedError in dipole training with hybrid descriptors [#4527]
Ensure rotation matrix handling for hybrid descriptors

Possibly related PRs

Suggested labels

Docs, Examples

Suggested reviewers

  • Chengqian-Zhang

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e01a3d and 088450e.

📒 Files selected for processing (1)
  • source/tests/tf/test_dipole_hybrid_descrpt.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/tests/tf/test_dipole_hybrid_descrpt.py
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Test C++ (true)

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

🧹 Nitpick comments (6)
source/tests/tf/test_dipole_hybrid_descrpt.py (4)

23-26: Consider using type hints for global variables.

The global precision variables should have type hints for better code clarity and IDE support.

-GLOBAL_ENER_FLOAT_PRECISION = tf.float64
-GLOBAL_TF_FLOAT_PRECISION = tf.float64
-GLOBAL_NP_FLOAT_PRECISION = np.float64
+GLOBAL_ENER_FLOAT_PRECISION: tf.DType = tf.float64
+GLOBAL_TF_FLOAT_PRECISION: tf.DType = tf.float64
+GLOBAL_NP_FLOAT_PRECISION: np.dtype = np.float64

49-86: Consider extracting descriptor configuration to a separate file.

The descriptor configuration is quite large and contains repeated sections. Consider moving it to a separate JSON configuration file for better maintainability.

Also, the descriptor configuration has duplicate sections for the first two descriptors. Consider using a helper function to create these configurations:

def create_se_e2_a_config(seed: int = 1) -> dict:
    return {
        "type": "se_e2_a",
        "sel": [20, 20],
        "rcut_smth": 1.8,
        "rcut": 6.0,
        "neuron": [2, 4, 8],
        "resnet_dt": False,
        "axis_neuron": 8,
        "precision": "float64",
        "type_one_side": True,
        "seed": seed,
    }

95-95: Remove commented code.

The commented line appears to be test code. Remove it if it's not needed.

-# model._compute_dstats([test_data['coord']], [test_data['box']], [test_data['type']], [test_data['natoms_vec']], [test_data['default_mesh']])

113-114: Initialize t_fparam with None type hint.

Add type hint to t_fparam for better code clarity.

-t_fparam = None
+t_fparam: Optional[tf.Tensor] = None
deepmd/tf/descriptor/hybrid.py (1)

507-512: Add docstring parameters and return type.

The get_rot_mat method needs more detailed documentation.

 def get_rot_mat(self) -> tf.Tensor:
-    """Get rotational matrix."""
+    """Get rotational matrix by concatenating rotation matrices from all descriptors.
+
+    Returns
+    -------
+    tf.Tensor
+        The concatenated rotation matrix tensor with shape [nframes, natoms, sum(rot_mat_dim)]
+        where sum(rot_mat_dim) is the sum of rotation matrix dimensions from all descriptors
+    """
deepmd/tf/descriptor/descriptor.py (1)

108-109: Add explanation for the default return value.

Document why 0 is returned as the default value.

-        # by default, no rotation matrix
+        # Return 0 to indicate that this descriptor doesn't support rotation matrices by default.
+        # Derived classes should override this method if they support rotation matrices.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dbdb9b9 and e2e8b0a.

📒 Files selected for processing (4)
  • deepmd/tf/descriptor/descriptor.py (2 hunks)
  • deepmd/tf/descriptor/hybrid.py (1 hunks)
  • deepmd/tf/model/model.py (1 hunks)
  • source/tests/tf/test_dipole_hybrid_descrpt.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (21)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Build wheels for cp311-win_amd64
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • 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 (2, 3.12)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Analyze (python)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Build C++ (cuda120, 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: Analyze (c-cpp)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Test C++ (true)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Build C++ (cpu, cpu)
🔇 Additional comments (2)
deepmd/tf/descriptor/hybrid.py (1)

496-505: LGTM! Well-documented method.

The get_dim_rot_mat_1 method is well-documented with clear docstrings and return type hints.

deepmd/tf/model/model.py (1)

671-675: LGTM! Good validation check.

The validation ensures that tensorial fitting networks have the required rotation matrix support from their descriptors.

deepmd/tf/descriptor/descriptor.py Show resolved Hide resolved
Copy link

codecov bot commented Jan 8, 2025

Codecov Report

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

Project coverage is 84.58%. Comparing base (dbdb9b9) to head (088450e).

Files with missing lines Patch % Lines
deepmd/tf/model/model.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4542      +/-   ##
==========================================
+ Coverage   84.55%   84.58%   +0.02%     
==========================================
  Files         677      677              
  Lines       63903    63915      +12     
  Branches     3488     3487       -1     
==========================================
+ Hits        54035    54060      +25     
+ Misses       8743     8729      -14     
- Partials     1125     1126       +1     

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

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.

[BUG] Dipole training not working with any hybrid descriptor combination
1 participant