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(tf): fix compress suffix in DescrptDPA1Compat #4243

Merged
merged 10 commits into from
Oct 26, 2024

Conversation

iProzd
Copy link
Collaborator

@iProzd iProzd commented Oct 23, 2024

Fix #4114 .

Summary by CodeRabbit

  • New Features

    • Enhanced compression capabilities in descriptor models with new optional parameters for improved flexibility.
    • Improved serialization processes for attention layers, allowing for better handling of scaling factors and normalization.
    • Dynamic tensor name construction in utility functions to accommodate varying suffixes.
  • Bug Fixes

    • Adjusted method parameters to ensure compatibility and functionality with new suffix options.
  • Tests

    • Introduced a new test suite to validate the functionality of the TensorFlow-based descriptor model, ensuring consistent output with the updated features.

Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the DescrptSeAtten and DescrptDPA1Compat classes in deepmd/tf/descriptor/se_atten.py, including the addition of a tebd_suffix parameter to the enable_compression method. The init_variables method is updated, and a new method, update_attention_layers_serialize, is introduced. Additionally, the get_two_side_type_embedding method in deepmd/tf/utils/compress.py is updated to include a suffix parameter. A new test file is also created to validate the functionality of these changes.

Changes

File Change Summary
deepmd/tf/descriptor/se_atten.py Updated enable_compression method to include tebd_suffix. Added update_attention_layers_serialize method. Updated init_variables and serialize methods.
deepmd/tf/utils/compress.py Updated get_two_side_type_embedding method to include suffix parameter.
source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py Added new test class TestDescriptorSeA and functions build_tf_descriptor and build_eval_tf.

Assessment against linked issues

Objective Addressed Explanation
Fix enable_compression in DescrptDPA1Compat (#4114)

Possibly related PRs

  • Feat: add se_atten_v2to PyTorch and DP #3840: Changes in deepmd/tf/descriptor/se_atten.py related to serialization and handling of parameters are relevant to the introduction of the DescrptSeAttenV2 class, which also modifies serialization logic and parameters in the same file.
  • fix: correct exclude_types in descriptors #3841: The modifications in deepmd/tf/descriptor/se_atten.py regarding the exclusion mask and its application are relevant to the changes made to ensure consistency in handling exclude_types across descriptors, including those in the se_atten context.

Suggested labels

Docs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ca1319f and 4ce70f6.

📒 Files selected for processing (1)
  • source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py

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

🧹 Outside diff range and nitpick comments (5)
source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py (2)

47-59: Consider adding error handling for session operations.

While the function works correctly, it might benefit from try-catch blocks around session operations to handle potential TensorFlow runtime errors gracefully.

Example enhancement:

 def build_eval_tf(sess, obj, natoms, coords, atype, box, suffix):
     t_out, feed_dict = build_tf_descriptor(obj, natoms, coords, atype, box, suffix)
 
     t_out_indentity = [
         tf.identity(tt, name=f"o_{ii}_{suffix}") for ii, tt in enumerate(t_out)
     ]
-    run_sess(sess, tf.global_variables_initializer())
-    return run_sess(
-        sess,
-        t_out_indentity,
-        feed_dict=feed_dict,
-    )
+    try:
+        run_sess(sess, tf.global_variables_initializer())
+        return run_sess(
+            sess,
+            t_out_indentity,
+            feed_dict=feed_dict,
+        )
+    except tf.errors.OpError as e:
+        raise RuntimeError(f"Failed to evaluate descriptor: {str(e)}")

62-116: Remove or document the commented-out test case.

There's a commented-out alternative atype array that might indicate an incomplete test case:

# self.atype = np.array([0, 0, 1, 1, 1, 1], dtype=np.int32)

Either remove it or document why it's kept for future reference.

deepmd/tf/descriptor/se_atten.py (3)

2262-2262: Fix typos in the docstring.

The docstring contains typos: 'Reveive' should be 'Receive', and 'statisitcs' should be 'statistics'.


2283-2283: Correct typo in the comment.

In the comment, 'mocel' should be 'model'.


2251-2348: Add unit tests for enable_compression in DescrptDPA1Compat.

Ensure that the new enable_compression method in DescrptDPA1Compat is covered by unit tests to verify its functionality and catch potential issues.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b4701da and c8ab4f5.

📒 Files selected for processing (4)
  • deepmd/tf/descriptor/se_atten.py (1 hunks)
  • deepmd/tf/utils/compress.py (1 hunks)
  • deepmd/tf/utils/tabulate.py (1 hunks)
  • source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
deepmd/tf/utils/compress.py (1)

23-24: LGTM! The suffix parameter addition looks good.

The change maintains backward compatibility while enabling flexible tensor naming needed for compression support.

Let's verify the usage of this method with different suffixes:

✅ Verification successful

Based on the shell script results, I can now generate the final response:

The suffix parameter is correctly used and integrated across the codebase

The verification shows that:

  • In se_atten.py, the method is called with an explicit suffix parameter: get_two_side_type_embedding(self, graph, suffix=suffix)
  • In se_a.py, it's called without a suffix, utilizing the default empty string
  • The tensor naming pattern t_typeebd{suffix} is consistently used across the codebase:
    • In model.py: f"t_typeebd{suffix}:0"
    • In type_embed.py: name="t_typeebd" + suffix
    • In test files, the base name t_typeebd is used without suffix
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how the get_two_side_type_embedding method is called across the codebase
# and verify that suffix parameter is used consistently

# Search for method calls
rg -A 3 "get_two_side_type_embedding\(" 

# Search for tensor name patterns to ensure consistent suffix usage
rg "t_typeebd[^\"]*"

Length of output: 5424

source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py (3)

1-21: LGTM: Imports are well-organized and complete.

The imports are properly structured and include all necessary dependencies for the test implementation.


23-45: LGTM: Well-structured descriptor building function.

The function correctly sets up TensorFlow placeholders with appropriate types and names, and properly handles the suffix parameter.


153-154: LGTM: Standard unittest main block.

The main block is correctly implemented for running the tests.

deepmd/tf/utils/tabulate.py (1)

129-131: LGTM! Consistent tensor name resolution.

The change correctly adds the suffix to the tensor name when retrieving ntypes, maintaining consistency with how other tensors (davg, dstd) are retrieved from the graph.

deepmd/tf/descriptor/se_atten.py Outdated Show resolved Hide resolved
deepmd/tf/utils/tabulate.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

🧹 Outside diff range and nitpick comments (1)
deepmd/tf/descriptor/se_atten.py (1)

Line range hint 426-449: LGTM! Consider enhancing parameter documentation.

The addition of tebd_suffix parameter provides flexibility in scope naming for type embedding during model compression. The parameter documentation could be more specific about when to use a different suffix than the main scope suffix.

Consider updating the docstring to clarify:

@@ -2288,7 +2288 @@
        tebd_suffix : str, optional
-            The suffix of the type embedding scope, only for DescrptDPA1Compat
+            The suffix of the type embedding scope. When using DescrptDPA1Compat, 
+            this must be the same as the main suffix. For other implementations, 
+            it can be different to support separate scoping of type embeddings.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 23c7b64 and 33daa4b.

📒 Files selected for processing (1)
  • deepmd/tf/descriptor/se_atten.py (4 hunks)
🧰 Additional context used
🔇 Additional comments (2)
deepmd/tf/descriptor/se_atten.py (2)

502-504: LGTM! Consistent suffix propagation.

The tebd_suffix is correctly passed to get_two_side_type_embedding, maintaining consistency with the method signature change.


2256-2305: LGTM! Well-constrained implementation.

The override correctly enforces that tebd_suffix must match suffix in DescrptDPA1Compat, which is essential for maintaining compatibility. The parent method is called appropriately with the same suffix.

@iProzd iProzd linked an issue Oct 23, 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 (1)
deepmd/tf/descriptor/se_atten.py (1)

2257-2306: Enhance docstring to explain suffix constraint

The implementation correctly enforces that tebd_suffix must match suffix in DescrptDPA1Compat. However, the docstring could be improved to explain why this constraint exists.

Consider updating the docstring for tebd_suffix to:

-            Same as suffix.
+            The suffix of the type embedding scope. Must be the same as `suffix` in DescrptDPA1Compat
+            to maintain compatibility with the original implementation.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 33daa4b and 7491039.

📒 Files selected for processing (2)
  • deepmd/tf/descriptor/se_atten.py (5 hunks)
  • source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • source/tests/tf/test_model_compression_dpa1_compat_suffix_only.py
🧰 Additional context used
🪛 Ruff
deepmd/tf/descriptor/se_atten.py

567-567: Local variable t_ntypes is assigned to but never used

Remove assignment to unused variable t_ntypes

(F841)

🔇 Additional comments (2)
deepmd/tf/descriptor/se_atten.py (2)

Line range hint 426-449: LGTM: Well-documented parameter addition

The addition of the tebd_suffix parameter to enable_compression is well-implemented and properly documented. This change provides flexibility in specifying the suffix for type embedding scope.

Also applies to: 502-504


566-567: Verify the purpose of unused variable t_ntypes

The variable t_ntypes is assigned but never used. However, since it's in a TensorFlow graph context, it might serve a purpose in the graph structure or debugging.

Let's check if this variable is used in the graph:

🧰 Tools
🪛 Ruff

567-567: Local variable t_ntypes is assigned to but never used

Remove assignment to unused variable t_ntypes

(F841)

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 (1)
deepmd/tf/descriptor/se_atten.py (1)

567-568: Keep unused variables for documentation and debugging.

While t_ntypes and t_rcut are currently unused, they serve as important metadata about the model's configuration and may be useful for debugging. Consider adding a comment explaining their purpose or marking them with # pylint: disable=unused-variable if they are intentionally kept.

🧰 Tools
🪛 Ruff

567-567: Local variable t_ntypes is assigned to but never used

Remove assignment to unused variable t_ntypes

(F841)


568-568: Local variable t_rcut is assigned to but never used

Remove assignment to unused variable t_rcut

(F841)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7491039 and 73d816a.

📒 Files selected for processing (1)
  • deepmd/tf/descriptor/se_atten.py (5 hunks)
🧰 Additional context used
🪛 Ruff
deepmd/tf/descriptor/se_atten.py

567-567: Local variable t_ntypes is assigned to but never used

Remove assignment to unused variable t_ntypes

(F841)


568-568: Local variable t_rcut is assigned to but never used

Remove assignment to unused variable t_rcut

(F841)

🔇 Additional comments (2)
deepmd/tf/descriptor/se_atten.py (2)

Line range hint 426-504: LGTM: Proper handling of type embedding suffix in compression.

The addition of the tebd_suffix parameter and its usage in get_two_side_type_embedding correctly addresses the issue with compression suffix handling in type embeddings.


2257-2306: LGTM: Enforcing consistent suffix usage in DescrptDPA1Compat.

The implementation correctly enforces that tebd_suffix must match suffix in DescrptDPA1Compat, which is essential for maintaining consistency in the compression process.

Copy link

codecov bot commented Oct 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.28%. Comparing base (911f41b) to head (4ce70f6).
Report is 16 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4243      +/-   ##
==========================================
- Coverage   84.58%   84.28%   -0.30%     
==========================================
  Files         547      548       +1     
  Lines       51327    51434     +107     
  Branches     3047     3051       +4     
==========================================
- Hits        43413    43353      -60     
- Misses       6967     7120     +153     
- Partials      947      961      +14     

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

deepmd/tf/descriptor/se_atten.py Outdated Show resolved Hide resolved
@iProzd iProzd requested a review from njzjz October 26, 2024 07:29
@njzjz njzjz enabled auto-merge October 26, 2024 15:36
@njzjz njzjz added this pull request to the merge queue Oct 26, 2024
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Oct 26, 2024
@njzjz njzjz added this pull request to the merge queue Oct 26, 2024
Merged via the queue into deepmodeling:devel with commit 13e247e Oct 26, 2024
60 checks passed
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] fix enable_compression in TF DescrptDPA1Compat
3 participants