-
Notifications
You must be signed in to change notification settings - Fork 608
fix(pt): address hessian review comments #5358
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
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Safe versions of some functions that have problematic gradients. | ||
|
|
||
| Check https://jax.readthedocs.io/en/latest/faq.html#gradients-contain-nan-where-using-where | ||
| for more information. | ||
| """ | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| def safe_for_sqrt(x: torch.Tensor) -> torch.Tensor: | ||
| """Safe version of sqrt that has a gradient of 0 at x = 0.""" | ||
| mask = x > 0.0 | ||
| x_safe = torch.where(mask, x, torch.ones_like(x)) | ||
| return torch.where(mask, torch.sqrt(x_safe), torch.zeros_like(x)) | ||
|
|
||
|
|
||
| def safe_for_norm( | ||
| x: torch.Tensor, | ||
| dim: int | None = None, | ||
| keepdim: bool = False, | ||
| ord: float = 2.0, | ||
| ) -> torch.Tensor: | ||
| """Safe version of vector_norm that has a gradient of 0 at x = 0.""" | ||
| if dim is None: | ||
| mask = torch.sum(torch.square(x)) > 0 | ||
| x_safe = torch.where(mask, x, torch.ones_like(x)) | ||
| norm = torch.linalg.vector_norm(x_safe, ord=ord) | ||
| return torch.where(mask, norm, torch.zeros_like(norm)) | ||
|
|
||
| mask = torch.sum(torch.square(x), dim=(dim,), keepdim=True) > 0 | ||
| mask_out = mask if keepdim else mask.squeeze(dim) | ||
|
|
||
| x_safe = torch.where(mask, x, torch.ones_like(x)) | ||
| norm = torch.linalg.vector_norm(x_safe, ord=ord, dim=dim, keepdim=keepdim) | ||
| return torch.where(mask_out, norm, torch.zeros_like(norm)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| import copy | ||
| import unittest | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from deepmd.pt.model.model import ( | ||
| get_model, | ||
| ) | ||
| from deepmd.pt.utils import ( | ||
| env, | ||
| ) | ||
| from deepmd.pt.utils.utils import ( | ||
| to_numpy_array, | ||
| ) | ||
|
|
||
| from ...seed import ( | ||
| GLOBAL_SEED, | ||
| ) | ||
| from .test_permutation import ( | ||
| model_dpa2, | ||
| model_dpa3, | ||
| ) | ||
|
|
||
| dtype = torch.float64 | ||
|
|
||
|
|
||
| class TestDPAHessianFinite(unittest.TestCase): | ||
| def _build_inputs(self): | ||
| natoms = 5 | ||
| cell = 4.0 * torch.eye(3, dtype=dtype, device=env.DEVICE) | ||
| generator = torch.Generator(device=env.DEVICE).manual_seed(GLOBAL_SEED) | ||
| coord = 3.0 * torch.rand( | ||
| [1, natoms, 3], dtype=dtype, device=env.DEVICE, generator=generator | ||
| ) | ||
| atype = torch.tensor([[0, 0, 0, 1, 1]], dtype=torch.int64, device=env.DEVICE) | ||
| return coord.view(1, natoms * 3), atype, cell.view(1, 9) | ||
|
|
||
| def _assert_hessian_finite(self, model_params): | ||
| model = get_model(copy.deepcopy(model_params)).to(env.DEVICE) | ||
| model.enable_hessian() | ||
| model.requires_hessian("energy") | ||
| coord, atype, cell = self._build_inputs() | ||
| ret = model.forward_common(coord, atype, box=cell) | ||
| hessian = to_numpy_array(ret["energy_derv_r_derv_r"]) | ||
| self.assertTrue(np.isfinite(hessian).all()) | ||
|
|
||
| def test_dpa2_direct_dist_hessian_is_finite(self): | ||
| model_params = copy.deepcopy(model_dpa2) | ||
| model_params["descriptor"]["repformer"]["direct_dist"] = True | ||
| model_params["hessian_mode"] = True | ||
| self._assert_hessian_finite(model_params) | ||
|
|
||
| def test_dpa3_hessian_is_finite(self): | ||
| model_params = copy.deepcopy(model_dpa3) | ||
| model_params["descriptor"]["precision"] = "float64" | ||
| model_params["fitting_net"]["precision"] = "float64" | ||
| model_params["hessian_mode"] = True | ||
| self._assert_hessian_finite(model_params) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash ruff check deepmd/pt/utils/safe_gradient.py ruff format --check deepmd/pt/utils/safe_gradient.pyRepository: deepmodeling/deepmd-kit
Length of output: 578
Rename
ordargument to avoid Ruff A002 error.Line 22 shadows Python's builtin
ord, which Ruff flags as A002. This will cause CI to fail per the coding guidelines.🔧 Proposed fix
def safe_for_norm( x: torch.Tensor, dim: int | None = None, keepdim: bool = False, - ord: float = 2.0, + norm_ord: float = 2.0, ) -> torch.Tensor: @@ - norm = torch.linalg.vector_norm(x_safe, ord=ord) + norm = torch.linalg.vector_norm(x_safe, ord=norm_ord) @@ - norm = torch.linalg.vector_norm(x_safe, ord=ord, dim=dim, keepdim=keepdim) + norm = torch.linalg.vector_norm(x_safe, ord=norm_ord, dim=dim, keepdim=keepdim)🧰 Tools
🪛 Ruff (0.15.7)
[error] 22-22: Function argument
ordis shadowing a Python builtin(A002)
🤖 Prompt for AI Agents