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(jax): export call_lower to SavedModel via jax2tf #4254

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

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Oct 25, 2024

Summary by CodeRabbit

  • New Features

    • Added support for TensorFlow SavedModel format in model serialization and deserialization.
    • Expanded file handling capabilities by including ".savedmodel" suffix in the backend.
  • Bug Fixes

    • Simplified handling of the sec variable for improved clarity and performance in calculations.
  • Refactor

    • Optimized internal calculations in the DescrptSeAArrayAPI class by replacing tensor contraction with broadcasting.

Signed-off-by: Jinzhe Zeng <[email protected]>
Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

📝 Walkthrough

Walkthrough

This pull request introduces modifications across three files. In deepmd/backend/jax.py, the suffixes class variable of the JAXBackend class is updated to include a new suffix ".savedmodel". In deepmd/dpmodel/descriptor/se_e2_a.py, the call method of the DescrptSeAArrayAPI class is simplified by adjusting how the sec variable is defined and optimizing the calculation of the gr_tmp variable. Lastly, in deepmd/jax/utils/serialization.py, the deserialize_to_file function is enhanced to handle TensorFlow SavedModel format, adding functionality for model serialization and deserialization.

Changes

File Path Change Summary
deepmd/backend/jax.py Updated suffixes in JAXBackend class to include ".savedmodel".
deepmd/dpmodel/descriptor/se_e2_a.py Simplified sec variable assignment in call method; optimized gr_tmp calculation using broadcasting.
deepmd/jax/utils/serialization.py Enhanced deserialize_to_file function to support .savedmodel format; no changes to serialize_from_file.

Possibly related PRs

  • feat(jax/array-api): se_e2_a #4217: The changes in the DescrptSeAArrayAPI class involve modifications to the call method, which may relate to how the backend handles different file types, including the newly added ".savedmodel" suffix in the main PR.

Suggested reviewers

  • wanghan-iapcm
  • iProzd

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

🧹 Outside diff range and nitpick comments (3)
deepmd/backend/jax.py (1)

Line range hint 27-42: Document supported formats in class docstring.

Consider enhancing the class documentation to explicitly mention the supported file formats. This would help users understand which formats they can use with the JAX backend.

 class JAXBackend(Backend):
-    """JAX backend."""
+    """JAX backend.
+    
+    Supports the following model formats:
+    - .jax: Native JAX format
+    - .savedmodel: TensorFlow SavedModel format
+    """
deepmd/jax/utils/serialization.py (2)

58-64: Clarify the usage of polymorphic_shapes in jax2tf.convert

The polymorphic_shapes parameter uses variables like nf, nloc, and nghost. If these are placeholders for dynamic dimensions, consider providing documentation or comments explaining their meanings. This will enhance code readability and maintainability for future developers.


Line range hint 88-89: Update serialize_from_file to handle .savedmodel files

Currently, serialize_from_file only supports .jax files and raises a ValueError for other formats. Since deserialize_to_file now handles .savedmodel files, consider adding support for serializing from .savedmodel files for consistency. Alternatively, update the error message to reflect the supported formats.

Example of updating the error message:

 else:
-    raise ValueError("JAX backend only supports converting .jax directory")
+    raise ValueError("JAX backend only supports converting .jax and .savedmodel formats")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 02580c2 and d46d5f0.

📒 Files selected for processing (3)
  • deepmd/backend/jax.py (1 hunks)
  • deepmd/dpmodel/descriptor/se_e2_a.py (1 hunks)
  • deepmd/jax/utils/serialization.py (1 hunks)
🔇 Additional comments (6)
deepmd/backend/jax.py (1)

41-41: Verify SavedModel serialization implementation.

The addition of ".savedmodel" suffix aligns with the PR objective. Let's verify that the serialization hooks properly support this format.

✅ Verification successful

SavedModel serialization implementation verified

The JAX backend properly implements SavedModel format support:

  1. The backend correctly registers .savedmodel suffix in JAXBackend class
  2. The serialization implementation in deepmd/jax/utils/serialization.py includes:
    • Converting JAX model to TensorFlow using jax2tf.convert
    • Saving as TensorFlow SavedModel format using tf.saved_model.save
    • Proper shape specifications for the converted model
    • Support for custom gradients
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that serialization hooks handle SavedModel format

# Test: Check if deserialize_to_file has SavedModel handling
rg -A 10 "deserialize_to_file.*savedmodel" deepmd/jax/utils/serialization.py

# Test: Check if serialize_from_file has SavedModel handling
rg -A 10 "serialize_from_file.*savedmodel" deepmd/jax/utils/serialization.py

Length of output: 157


Script:

#!/bin/bash
# Let's check for any SavedModel related code in serialization files
rg -l "SavedModel|savedmodel" --type py

# Check implementation details in serialization-related files
rg -A 10 "serialize|deserialize" --type py

# Look for any JAX to SavedModel conversion functions
ast-grep --pattern 'def $_($$) {
  $$$
  savedmodel
  $$$
}'

Length of output: 456711


Script:

#!/bin/bash
# Let's check for SavedModel related code in JAX backend
rg -A 10 "SavedModel|savedmodel" deepmd/jax/utils/serialization.py deepmd/backend/jax.py

# Check if there are any JAX to TF conversion functions
rg -A 10 "jax2tf" deepmd/jax/utils/serialization.py deepmd/backend/jax.py

# Look for any model export/save functions
rg -A 10 "save.*model|export.*model" deepmd/jax/utils/serialization.py deepmd/backend/jax.py

Length of output: 5000

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

558-558: LGTM: Simplified array assignment

The removal of unnecessary xp.asarray conversion is appropriate since self.sel_cumsum is already suitable for indexing operations.


Line range hint 580-599: Performance optimization: Replaced einsum with broadcasting

The replacement of einsum operations with equivalent sum and broadcasting operations is a good optimization. The changes maintain mathematical equivalence while potentially offering better performance on some hardware accelerators.

Original:

gr_tmp = xp.einsum("lni,lnj->lij", gg, tr)
grrg = xp.einsum("flid,fljd->flij", gr, gr1)

New:

gr_tmp = xp.sum(gg[:, :, :, None] * tr[:, :, None, :], axis=1)
grrg = xp.sum(gr[:, :, :, None, :] * gr1[:, :, None, :, :], axis=4)

Let's verify the numerical equivalence of these operations:

✅ Verification successful

Optimization change is mathematically equivalent and safe to use

The replacement of einsum with broadcasting and sum operations is mathematically sound for the following reasons:

  1. The original einsum operation xp.einsum("lni,lnj->lij", gg, tr) is equivalent to the new broadcasting operation xp.sum(gg[:, :, :, None] * tr[:, :, None, :], axis=1) as they both perform the same matrix multiplication along the specified axes.

  2. Similarly, xp.einsum("flid,fljd->flij", gr, gr1) is equivalent to xp.sum(gr[:, :, :, None, :] * gr1[:, :, None, :, :], axis=4), maintaining the same contraction pattern.

  3. The codebase shows consistent use of both einsum and broadcasting+sum patterns across different implementations (TensorFlow, PyTorch, and NumPy), indicating this is a well-understood transformation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any tests that verify the descriptor's output
rg -l "test.*descriptor.*se.*a" --type py

Length of output: 85


Script:

#!/bin/bash
# Let's examine the test file content to see if it verifies numerical equivalence
cat source/tests/tf/test_descrpt_se_a_mask.py

Length of output: 8099


Script:

#!/bin/bash
# Let's look for any other tests that might verify the descriptor output
rg -l "test.*descriptor.*se.*[aA]" --type py

# Also search for any numerical tests specifically related to einsum operations
rg "einsum|sum.*broadcast" --type py

Length of output: 3078

deepmd/jax/utils/serialization.py (3)

50-51: Verify that call_lower is a valid attribute of model

The code assigns call_lower = model.call_lower. Please ensure that all models being deserialized have the call_lower attribute. If some models might not have this attribute, consider adding a check or handling potential AttributeError exceptions to prevent runtime errors.


68-73: Ensure correct tensor shapes in tf.TensorSpec

The tf.TensorSpec definitions include dynamic dimensions (None) and a call to model.get_nnei(). Verify that model.get_nnei() returns an integer and that the tensor shapes align with the expected input dimensions. Misalignment can lead to runtime errors when the SavedModel is used.


76-79: Review the necessity of experimental_custom_gradients=True

The option experimental_custom_gradients=True is used in tf.saved_model.SaveOptions. Confirm that custom gradients are required for your use case. If not, removing this option could simplify the code and avoid potential compatibility issues with future TensorFlow versions.

deepmd/jax/utils/serialization.py Show resolved Hide resolved
Copy link

codecov bot commented Oct 25, 2024

Codecov Report

Attention: Patch coverage is 16.66667% with 10 lines in your changes missing coverage. Please review.

Project coverage is 84.21%. Comparing base (02580c2) to head (d46d5f0).

Files with missing lines Patch % Lines
deepmd/jax/utils/serialization.py 0.00% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4254      +/-   ##
==========================================
- Coverage   84.22%   84.21%   -0.01%     
==========================================
  Files         548      548              
  Lines       51426    51435       +9     
  Branches     3051     3051              
==========================================
+ Hits        43314    43317       +3     
- Misses       7151     7160       +9     
+ Partials      961      958       -3     

☔ 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