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

fix(jax): fix several serialization and jit issues for DPA-2 #4315

Open
wants to merge 1 commit into
base: devel
Choose a base branch
from

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Nov 5, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new methods format_nlist in DPZBLModel and EnergyModel classes for improved neighbor list formatting.
    • Added new descriptors DescrptDPA2 and DescrptSeTTebd to the public API.
  • Bug Fixes

    • Enhanced attribute handling in DPZBLModel and EnergyModel to ensure proper serialization and deserialization of atomic_model.
  • Documentation

    • Updated the public API to reflect new additions and maintain existing documentation accuracy.

- `deepmd/jax/descriptor/__init__.py` imports SeT and DPA-2 to let them found by the plugin;
- `deepmd/dpmodel/descriptor/dpa1.py` fixes the jit issue regarding to the shape generated by `jnp.prod`. The shape should be static by using `math.prod`.
- `deepmd/jax/model/ener_model.py` and `deepmd/jax/model/dp_zbl_model.py` stop the graident of coordinates when rebuilding the neighbor list. The graient of sort causes an error due to jax-ml/jax#24730.

Signed-off-by: Jinzhe Zeng <[email protected]>
@njzjz
Copy link
Member Author

njzjz commented Nov 5, 2024

The universal test may need to add JAX models and test saving to the SavedModel. (again, we cannot run TF1 and TF2 at the same session. The regular jit doesn't trigger the thrid error, only saving the model does.)

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve several modifications across multiple files, primarily focusing on the implementation of new methods and adjustments to existing methods within various classes. Key updates include the introduction of the format_nlist method in the DPZBLModel and EnergyModel classes, modifications to the cal_g and cal_g_strip methods in the DescrptDPA1 class, and enhancements to the NeighborGatedAttention class. The public interfaces remain unchanged, ensuring compatibility while improving internal logic and readability.

Changes

File Path Change Summary
deepmd/dpmodel/descriptor/dpa1.py Updated cal_g and cal_g_strip methods to use math.prod instead of xp.prod. Modified call method in DescrptBlockSeAtten to set attn_mask to False. Constructor of NeighborGatedAttention updated to include dotr and do_mask parameters.
deepmd/jax/descriptor/__init__.py Added imports for DescrptDPA2 and DescrptSeTTebd. Updated __all__ list to include these new descriptors.
deepmd/jax/model/dp_zbl_model.py Added format_nlist method to DPZBLModel. Updated __setattr__ method for atomic_model. Explicitly defined forward_common_atomic method.
deepmd/jax/model/ener_model.py Added format_nlist method to EnergyModel. Updated __setattr__ method for atomic_model. Import statements updated for jax.

Possibly related PRs

  • feat(jax/array-api): se_e2_a #4217: The changes in the DescrptSeA class and its methods are relevant as they involve modifications to the cal_g method, which is similar to the changes made in the cal_g method of the DescrptDPA1 class in the main PR.
  • feat(jax/array-api): DOS fitting #4218: The format_nlist method added to the EnergyModel class is relevant as it shares a focus on neighbor list handling, similar to the changes in the NeighborGatedAttention class in the main PR.
  • feat(jax/array-api): se_e2_r #4257: The modifications in the DescrptSeR class, particularly in the cal_g method, show a similar approach to handling array operations as seen in the changes to the cal_g method in the main PR.
  • feat(jax/array-api): DPA-2 #4294: The updates to the DescrptDPA2 class, especially regarding the call method and its handling of input arrays, align with the changes made to the DescrptDPA1 class in the main PR, focusing on array compatibility.
  • feat(jax): zbl #4301: The introduction of the DPZBLLinearEnergyAtomicModel class and its methods, particularly the forward_common_atomic method, is relevant as it enhances the atomic model framework, similar to the adjustments made in the main PR regarding the attention mechanism.

Suggested labels

Python, Docs

Suggested reviewers

  • 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
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/jax/model/ener_model.py (1)

53-66: Add documentation explaining the stop_gradient usage.

The implementation correctly prevents gradient computation during neighbor list rebuilding by using jax.lax.stop_gradient on extended_coord. This addresses the gradient sorting issue referenced in JAX issue #24730.

Consider adding a docstring explaining why stop_gradient is necessary to help future maintainers understand this critical implementation detail.

Example docstring:

def format_nlist(
    self,
    extended_coord: jnp.ndarray,
    extended_atype: jnp.ndarray,
    nlist: jnp.ndarray,
    extra_nlist_sort: bool = False,
):
    """Format neighbor list while preventing gradient computation during rebuilding.
    
    Uses stop_gradient on coordinates to prevent gradient sorting issues
    (see JAX issue #24730) during neighbor list rebuilding.
    
    Args:
        extended_coord: Extended coordinates array
        extended_atype: Extended atom types array
        nlist: Neighbor list array
        extra_nlist_sort: Optional flag for additional sorting
    """
deepmd/jax/model/dp_zbl_model.py (1)

53-66: Consider adding docstring documentation.

Adding documentation would help future maintainers understand:

  1. The purpose of stopping gradients
  2. The relationship with JAX issue #24730
  3. The impact on gradient computation

Here's a suggested docstring:

     def format_nlist(
         self,
         extended_coord: jnp.ndarray,
         extended_atype: jnp.ndarray,
         nlist: jnp.ndarray,
         extra_nlist_sort: bool = False,
     ):
+        """Format neighbor list while preventing gradient computation for coordinates.
+        
+        This prevents gradient computation during neighbor list rebuilding to avoid
+        gradient sorting issues (see JAX #24730). The gradients are stopped only for
+        the coordinate inputs used in neighbor list operations.
+        """
         return DPZBLModelDP.format_nlist(
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dabedd2 and 54dc410.

📒 Files selected for processing (4)
  • deepmd/dpmodel/descriptor/dpa1.py (3 hunks)
  • deepmd/jax/descriptor/__init__.py (2 hunks)
  • deepmd/jax/model/dp_zbl_model.py (2 hunks)
  • deepmd/jax/model/ener_model.py (2 hunks)
🔇 Additional comments (8)
deepmd/jax/descriptor/__init__.py (3)

28-28: LGTM: Updated exports list.

The __all__ list is correctly updated to include both new descriptors, making them part of the public API.

Also applies to: 30-30


20-22: LGTM: New SeT-TEBD descriptor import.

The import of DescrptSeTTebd aligns with the PR objectives to enhance the plugin system.

Let's verify the module exists:

#!/bin/bash
# Verify the se_t_tebd module exists and contains the expected class
fd "se_t_tebd.py" --type f --exec ast-grep --pattern 'class DescrptSeTTebd'

5-7: LGTM: New DPA-2 descriptor import.

The import of DescrptDPA2 aligns with the PR objectives to enhance the plugin system.

Let's verify the module exists:

✅ Verification successful

LGTM: The DPA2 descriptor import is correctly implemented.

The import of DescrptDPA2 in deepmd/jax/descriptor/__init__.py is properly implemented and matches the class definition in dpa2.py. The class is also correctly exposed in the module's __all__ list.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the DPA2 module exists and contains the expected class
fd "dpa2.py" --type f --exec ast-grep --pattern 'class DescrptDPA2'

Length of output: 75


Script:

#!/bin/bash
# Let's first check if the file exists
fd "dpa2.py" --type f

# If the file exists, let's examine its content
fd "dpa2.py" --type f --exec cat {}

Length of output: 115300


Script:

#!/bin/bash
# Let's check if the DPA2 class exists in the JAX descriptor module
rg "class DescrptDPA2" deepmd/jax/descriptor/dpa2.py

# Let's also verify the imports in the JAX descriptor module
cat deepmd/jax/descriptor/__init__.py

Length of output: 758

deepmd/jax/model/ener_model.py (1)

15-15: LGTM: Import addition is necessary.

The addition of the jax import is required for using jax.lax.stop_gradient in the new format_nlist method.

deepmd/jax/model/dp_zbl_model.py (2)

15-15: LGTM: Import addition is appropriate.

The addition of the jax import is necessary for using jax.lax.stop_gradient in the new format_nlist method.


53-66: Implementation looks correct, verify the impact.

The use of jax.lax.stop_gradient on extended_coord effectively prevents gradient computation during neighbor list rebuilding, which should resolve the gradient sorting issue (JAX #24730).

Let's verify that this is the only place where neighbor list formatting occurs in this model:

✅ Verification successful

Implementation is correct and consistent across the codebase

The verification shows that stop_gradient is consistently applied to extended_coord in both JAX model implementations (dp_zbl_model.py and ener_model.py). This is the correct approach to prevent gradient computation during neighbor list rebuilding, while the base implementations in dpmodel and pt.model handle their respective frameworks appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential neighbor list formatting operations
ast-grep --pattern 'format_nlist'

Length of output: 1089


Script:

#!/bin/bash
# Let's check the implementation of format_nlist in the parent classes
ast-grep --pattern $'class DPZBLModelDP {
  $$$
  format_nlist($$$) {
    $$$
  }
  $$$
}'

ast-grep --pattern $'class EnergyModelDP {
  $$$
  format_nlist($$$) {
    $$$
  }
  $$$
}'

Length of output: 184


Script:

#!/bin/bash
# Let's try a different approach to find the parent class implementations
rg "class (DPZBLModelDP|EnergyModelDP)" -A 10
rg "def format_nlist" -B 5 -A 10

Length of output: 4210

deepmd/dpmodel/descriptor/dpa1.py (2)

856-856: Good optimization: Using math.prod for shape calculations.

Using math.prod instead of xp.prod(xp.asarray(...)) is a better choice for shape calculations as it:

  1. Works with static shapes during JIT compilation
  2. Avoids unnecessary array conversion
  3. Is more efficient for small tuples

870-870: LGTM: Consistent use of math.prod for shape calculations.

The change is consistent with the optimization in cal_g, ensuring uniform behavior across both methods.

@njzjz njzjz changed the title fix(jax): fix several serialization and jit issues fix(jax): fix several serialization and jit issues for DPA-2 Nov 5, 2024
Copy link

codecov bot commented Nov 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.23%. Comparing base (dabedd2) to head (54dc410).

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4315      +/-   ##
==========================================
- Coverage   84.40%   84.23%   -0.18%     
==========================================
  Files         570      570              
  Lines       53071    53078       +7     
  Branches     3054     3054              
==========================================
- Hits        44794    44709      -85     
- Misses       7318     7410      +92     
  Partials      959      959              

☔ 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.

1 participant