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(pt): support DeepEval.eval_descriptor #4214

Merged
merged 2 commits into from
Oct 15, 2024

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Oct 14, 2024

Fix #4112.

Summary by CodeRabbit

  • New Features

    • Introduced a method for evaluating descriptors using the deep potential model.
    • Added functionality to control descriptor evaluation during model operations.
  • Bug Fixes

    • Removed conditional skip for descriptor evaluation tests, enhancing test coverage for PyTorch models.
  • Tests

    • Added a new test class for neighbor list setups in descriptor evaluation.

@njzjz njzjz linked an issue Oct 14, 2024 that may be closed by this pull request
Signed-off-by: Jinzhe Zeng <[email protected]>
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a new method eval_descriptor in the DeepEval class for evaluating descriptors using the deep potential model. This update includes modifications to the DPAtomicModel and DPModelCommon classes to support descriptor evaluation, including new methods and attributes to manage hooks and store evaluated descriptors. Additionally, test modifications are made to allow descriptor evaluation in the TestDeepPot class and introduce a new test class for neighbor lists.

Changes

File Path Change Summary
deepmd/pt/infer/deep_eval.py Added method eval_descriptor to DeepEval class for descriptor evaluation.
deepmd/pt/model/atomic_model/dp_atomic_model.py Added attributes enable_eval_descriptor_hook, eval_descriptor_list, and methods set_eval_descriptor_hook, eval_descriptor to DPAtomicModel.
deepmd/pt/model/model/dp_model.py Added methods set_eval_descriptor_hook and eval_descriptor to DPModelCommon.
source/tests/infer/test_models.py Modified TestDeepPot to allow descriptor evaluation and added TestDeepPotNeighborList class.

Assessment against linked issues

Objective Addressed Explanation
Support eval_descriptor for PT DeepEval (#4112)

Possibly related PRs

Suggested reviewers

  • wanghan-iapcm
  • iProzd

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fabe092 and 67f104b.

📒 Files selected for processing (1)
  • deepmd/pt/infer/deep_eval.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepmd/pt/infer/deep_eval.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: 3

🧹 Outside diff range and nitpick comments (1)
deepmd/pt/infer/deep_eval.py (1)

602-647: LGTM! Consider some improvements for robustness and consistency.

The implementation of eval_descriptor looks good and correctly implements the descriptor evaluation using a hook mechanism. Here are a few suggestions to consider:

  1. Error Handling: Consider adding try-except blocks to handle potential errors gracefully, especially around lines 643-646 where the hook is set and unset.

  2. Performance Optimization: The method calls self.eval, which might perform unnecessary computations if only the descriptor is needed. If descriptor evaluation is a frequent operation, consider implementing a more optimized path.

  3. Consistency: On line 642, you're using self.dp.model["Default"] directly, while other methods in the class use self.dp.to(DEVICE). For consistency, consider using the same approach here.

Here's a potential refactor addressing these points:

def eval_descriptor(
    self,
    coords: np.ndarray,
    cells: Optional[np.ndarray],
    atom_types: np.ndarray,
    fparam: Optional[np.ndarray] = None,
    aparam: Optional[np.ndarray] = None,
    **kwargs: Any,
) -> np.ndarray:
    """Evaluate descriptors by using this DP."""
    model = self.dp.to(DEVICE).model["Default"]
    try:
        model.set_eval_descriptor_hook(True)
        self.eval(coords, cells, atom_types, fparam=fparam, aparam=aparam, **kwargs)
        descriptor = model.eval_descriptor()
    except Exception as e:
        raise RuntimeError("Error during descriptor evaluation") from e
    finally:
        model.set_eval_descriptor_hook(False)
    return to_numpy_array(descriptor)

This refactored version includes error handling, ensures consistent device placement, and maintains the hook state even if an error occurs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a1f8672 and fabe092.

📒 Files selected for processing (4)
  • deepmd/pt/infer/deep_eval.py (1 hunks)
  • deepmd/pt/model/atomic_model/dp_atomic_model.py (2 hunks)
  • deepmd/pt/model/model/dp_model.py (2 hunks)
  • source/tests/infer/test_models.py (0 hunks)
💤 Files with no reviewable changes (1)
  • source/tests/infer/test_models.py
🧰 Additional context used
🔇 Additional comments (6)
deepmd/pt/model/model/dp_model.py (4)

6-7: LGTM: torch import added correctly

The torch import is necessary for the new methods using torch functionalities and is correctly placed at the top of the file.


58-62: LGTM: set_eval_descriptor_hook method implemented correctly

The set_eval_descriptor_hook method is well-implemented:

  • Correctly uses the @torch.jit.export decorator for TorchScript compatibility.
  • Provides a clear docstring explaining its purpose.
  • Follows the single responsibility principle by delegating to self.atomic_model.

63-66: LGTM: eval_descriptor method implemented correctly

The eval_descriptor method is well-implemented:

  • Correctly uses the @torch.jit.export decorator for TorchScript compatibility.
  • Provides a clear, concise docstring.
  • Follows the single responsibility principle by delegating to self.atomic_model.
  • Specifies the return type as torch.Tensor, which is good for type hinting.

57-66: Consider adding tests for the new methods

The implementation of set_eval_descriptor_hook and eval_descriptor looks good. To ensure robustness and prevent future regressions, consider adding unit tests for these new methods if not already done.

deepmd/pt/model/atomic_model/dp_atomic_model.py (2)

65-67: Initialization of new attributes is appropriate

The new attributes enable_eval_descriptor_hook and eval_descriptor_list are properly initialized in the __init__ method. This setup allows for flexible control over descriptor evaluation during the model's forward passes.


70-74: Verify the reset behavior in set_eval_descriptor_hook

The set_eval_descriptor_hook method resets eval_descriptor_list every time it is called, regardless of whether the hook is being enabled or disabled. Is this the intended behavior? If the cache should only be cleared when enabling the hook, consider modifying the implementation to reset the list only when enable is True.

Suggested consideration:

def set_eval_descriptor_hook(self, enable: bool) -> None:
    """Set the hook for evaluating descriptor and clear the cache if enabling."""
    self.enable_eval_descriptor_hook = enable
    if enable:
        self.eval_descriptor_list = []

This ensures that the descriptor list is only cleared when the hook is enabled, preserving any cached descriptors if the hook is being disabled.

Copy link

codecov bot commented Oct 14, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.50%. Comparing base (a1f8672) to head (67f104b).
Report is 2 commits behind head on devel.

Additional details and impacted files
@@           Coverage Diff           @@
##            devel    #4214   +/-   ##
=======================================
  Coverage   83.50%   83.50%           
=======================================
  Files         541      541           
  Lines       52459    52483   +24     
  Branches     3047     3047           
=======================================
+ Hits        43804    43825   +21     
  Misses       7710     7710           
- Partials      945      948    +3     

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

@iProzd iProzd added this pull request to the merge queue Oct 15, 2024
Merged via the queue into deepmodeling:devel with commit 48f8a1e Oct 15, 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.

[Feature Request] Support eval_descriptor for PT DeepEval
3 participants