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: make sure head can be used in DeepPot #4312

Merged
merged 6 commits into from
Nov 6, 2024

Conversation

wangzyphysics
Copy link
Contributor

@wangzyphysics wangzyphysics commented Nov 5, 2024

Following the example mentioned here , I first select a head and put it into DPCalculator but encounter the error like this:

(/public/home/mzq001/soft/deepmd-kit) [mzq001@login01 ~]$ python test.py 
To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, DP_INTRA_OP_PARALLELISM_THREADS, and DP_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
Traceback (most recent call last):
  File "/public/home/mzq001/test.py", line 4, in <module>
    dp = DPCalculator("DPA2_medium_28_10M_beta4.pt", head="H2O_H2O-PD")
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/public/home/mzq001/soft/deepmd-kit/lib/python3.11/site-packages/deepmd/calculator.py", line 92, in __init__
    self.dp = DeepPot(str(Path(model).resolve()), neighbor_list=neighbor_list)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/public/home/mzq001/soft/deepmd-kit/lib/python3.11/site-packages/deepmd/infer/deep_eval.py", line 334, in __init__
    self.deep_eval = DeepEvalBackend(
                     ^^^^^^^^^^^^^^^^
  File "/public/home/mzq001/soft/deepmd-kit/lib/python3.11/site-packages/deepmd/pt/infer/deep_eval.py", line 121, in __init__
    head is not None
AssertionError: Head must be set for multitask model! Available heads are: ['Domains_Alloy', 'Domains_Anode', 'Domains_Cluster', 'Domains_Drug', 'Domains_FerroEle', 'Domains_OC2M', 'Domains_SSE-PBE', 'Domains_SemiCond', 'H2O_H2O-PD', 'Metals_AgAu-PBE', 'Metals_AlMgCu', 'Metals_Cu', 'Metals_Sn', 'Metals_Ti', 'Metals_V', 'Metals_W', 'Others_C12H26', 'Others_HfO2', 'Domains_ANI', 'Domains_SSE-PBESol', 'Domains_Transition1x', 'H2O_H2O-DPLR', 'H2O_H2O-PBE0TS-MD', 'H2O_H2O-PBE0TS', 'H2O_H2O-SCAN0', 'Metals_AgAu-PBED3', 'Others_In2Se3', 'MP_traj_v024_alldata_mixu']
## Compute potential energy
from ase import Atoms
from deepmd.calculator import DP as DPCalculator
dp = DPCalculator("DPA2_medium_28_10M_beta4.pt", head="H2O_H2O-PD")
water = Atoms('H2O', positions=[(0.7601, 1.9270, 1), (1.9575, 1, 1), (1., 1., 1.)], cell=[100, 100, 100])
water.calc = dp
print(water.get_potential_energy())
print(water.get_forces())

## Run BFGS structure optimization
from ase.optimize import BFGS
dyn = BFGS(water)
dyn.run(fmax=1e-6)
print(water.get_positions())

The variable named head of DPCalculator is not being used in DeepPot which directly leads to this error.

Summary by CodeRabbit

  • New Features

    • Enhanced configurability of the DP class with an additional head parameter for initialization.
    • Updated default behavior in the calculate method to include stress calculations alongside energy and forces.
  • Bug Fixes

    • Clarified handling of stress property in the context of lattice relaxation, improving accuracy in calculations.

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes made in the deepmd/calculator.py file involve updates to the DP class. The constructor now accepts an additional parameter, head, which is passed to the DeepPot initialization, enhancing the configurability of the instantiation process. Additionally, the calculate method's default properties parameter has been modified from ["energy", "forces", "virial"] to ["energy", "forces", "stress"], indicating a change in the default properties computed by the method. The handling of the stress property has also been clarified in the context of lattice relaxation.

Changes

File Change Summary
deepmd/calculator.py - Updated __init__ method to include head parameter in DP class.
- Changed default properties in calculate method from ["energy", "forces", "virial"] to ["energy", "forces", "stress"].

Suggested labels

Python

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.

@github-actions github-actions bot added the Python label Nov 5, 2024
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/calculator.py (2)

90-92: LGTM! Consider documenting the supported kwargs.

The forwarding of **kwargs to DeepPot correctly enables the head parameter to be passed through. However, it would be helpful to document the supported kwargs in the class docstring, particularly mentioning the head parameter for multitask models.

Add to the class docstring:

    Parameters
    ----------
    model : Union[str, Path]
        path to the model
    label : str, optional
        calculator label, by default "DP"
    type_dict : dict[str, int], optional
        mapping of element types and their numbers, best left None and the calculator
        will infer this information from model, by default None
    neighbor_list : ase.neighborlist.NeighborList, optional
        The neighbor list object. If None, then build the native neighbor list.
+   **kwargs :
+       Additional arguments passed to DeepPot. For multitask models, 
+       the 'head' parameter must be specified.

Line range hint 102-106: Fix inconsistency in default properties parameter.

There's a discrepancy between:

  1. The docstring shows ["energy", "forces", "stress"]
  2. The actual parameter default is ["energy", "forces", "virial"]
  3. The method computes both virial and stress

This inconsistency could lead to confusion. The default properties should match the docstring and implementation.

Apply this fix:

    def calculate(
        self,
        atoms: Optional["Atoms"] = None,
-       properties: list[str] = ["energy", "forces", "virial"],
+       properties: list[str] = ["energy", "forces", "stress", "virial"],
        system_changes: list[str] = all_changes,
    ):
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (1)
  • deepmd/calculator.py (1 hunks)
🔇 Additional comments (1)
deepmd/calculator.py (1)

90-92: Verify head parameter handling in DeepPot.

Let's confirm that the head parameter is properly handled by the underlying DeepPot class.

✅ Verification successful

Based on the search results, I can now provide a final response:

The head parameter is properly supported in PyTorch backend only

The head parameter is a PyTorch-specific feature that allows selecting a specific task head in multi-task models. This is documented in multiple places:

  • It's an optional parameter in deepmd/pt/infer/deep_eval.py
  • The docstring explicitly states "(Supported backend: PyTorch) Task head to test if in multi-task mode"
  • The parameter is properly passed through the inference chain in PyTorch implementation

The kwargs forwarding in the reviewed code is correct and necessary to support this functionality in the PyTorch backend.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check DeepPot implementation for head parameter handling

# Search for head parameter usage in DeepPot class
echo "Searching for head parameter handling in DeepPot..."
ast-grep --pattern 'class DeepPot {
  $$$
  def __init__($$$) {
    $$$
    head $$$
    $$$
  }
  $$$
}'

# Search for head-related assertions or validations
echo "Searching for head-related assertions..."
rg -l "head.*must.*set" --type py

Length of output: 347


Script:

#!/bin/bash
# Let's try a different approach to find head parameter handling

# Search for DeepPot class definition and initialization
echo "Searching for DeepPot class definition..."
rg "class DeepPot" -A 20 --type py

# Search for head parameter in method signatures or docstrings
echo "Searching for head parameter mentions..."
rg "head" --type py -C 3

# Look for parameter documentation
echo "Searching in documentation..."
fd README.md --exec cat {}

Length of output: 142981


Script:

#!/bin/bash
# Let's search for head parameter handling in DeepPot class implementation
echo "Searching for DeepPot initialization and head parameter usage..."
rg -A 10 "class DeepPot" --type py

# Search for head parameter in DeepPot docstring
echo "Searching for head parameter documentation..."
rg "head.*:.*param" --type py

# Search for head parameter usage in tests
echo "Searching for head parameter usage in tests..."
rg "DeepPot.*head" --type py

Length of output: 1058


Script:

#!/bin/bash
# Let's check the inheritance chain and base class implementation
echo "Checking DeepEval base class..."
rg -A 20 "class DeepEval" --type py

# Check the actual initialization and parameter passing
echo "Checking DeepPot initialization implementation..."
rg -B 5 -A 10 "__init__.*DeepPot" --type py

# Look for head parameter usage in DeepEval
echo "Checking head parameter usage in DeepEval..."
rg "head.*=.*kwargs\.get" --type py

Length of output: 10290


Script:

#!/bin/bash
# Let's check the actual implementation of head parameter handling
echo "Checking head parameter handling in DeepEval..."
rg -B 5 -A 15 "def __init__.*DeepEval" --type py

# Check for head parameter in model initialization
echo "Checking model initialization with head parameter..."
rg -B 2 -A 5 "head.*=.*kwargs" --type py

# Check for head parameter documentation
echo "Checking head parameter documentation..."
rg -A 3 "head.*:.*Optional.*str" --type py

Length of output: 1365

Copy link

codecov bot commented Nov 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.28%. Comparing base (914b1f9) to head (4da2180).
Report is 2 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4312      +/-   ##
==========================================
- Coverage   84.42%   84.28%   -0.15%     
==========================================
  Files         570      570              
  Lines       53078    53078              
  Branches     3054     3050       -4     
==========================================
- Hits        44810    44735      -75     
- Misses       7309     7384      +75     
  Partials      959      959              

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

deepmd/calculator.py Outdated Show resolved Hide resolved
@wanghan-iapcm wanghan-iapcm requested a review from iProzd November 6, 2024 02:57
@iProzd
Copy link
Collaborator

iProzd commented Nov 6, 2024

@wangzyphysics By the way, I apologize for any inconvenience you experienced with the example. I have updated the example, and you can use an external freeze method as a temporary workaround. Thank you for identifying this issue. Regarding the interface itself, we indeed need to add this variable. Let's address and fix it within this PR.

@iProzd iProzd added this pull request to the merge queue Nov 6, 2024
Merged via the queue into deepmodeling:devel with commit 430dfa9 Nov 6, 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.

3 participants