-
Notifications
You must be signed in to change notification settings - Fork 556
Feat: Refactor dipole fitting pytorch #3281
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
4b66a9b
feat: refactor dipole fitting
anyangml f47f9ef
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 95916e9
Merge branch 'devel' into devel
anyangml 151c231
add numpy fitting refactor
anyangml 1beee90
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] fb89885
feat: add numpy dipole fitting
anyangml 70359f9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d6a0bee
Merge branch 'devel' into devel
anyangml e90e408
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 6a53772
fix: merge conflict
anyangml d4fa19a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] c8d3cc4
fix: merge conflict
anyangml 03c3aee
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 7592c75
feat: add UTs
anyangml 18b0017
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 04bce53
feat: add UTs
anyangml d223bad
chore: refactor
anyangml b733c57
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b5f2582
chore: refactor
anyangml 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,127 @@ | ||
# SPDX-License-Identifier: LGPL-3.0-or-later | ||
import logging | ||
from typing import ( | ||
List, | ||
Optional, | ||
) | ||
|
||
import torch | ||
|
||
from deepmd.pt.model.network.network import ( | ||
ResidualDeep, | ||
) | ||
from deepmd.pt.model.task.fitting import ( | ||
Fitting, | ||
GeneralFitting, | ||
) | ||
from deepmd.pt.utils import ( | ||
env, | ||
) | ||
from deepmd.pt.utils.env import ( | ||
DEFAULT_PRECISION, | ||
) | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
class DipoleFittingNet(Fitting): | ||
def __init__( | ||
self, ntypes, embedding_width, neuron, out_dim, resnet_dt=True, **kwargs | ||
): | ||
"""Construct a fitting net for dipole. | ||
class DipoleFittingNet(GeneralFitting): | ||
"""Construct a general fitting net. | ||
anyangml marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
- ntypes: Element count. | ||
- embedding_width: Embedding width per atom. | ||
- neuron: Number of neurons in each hidden layers of the fitting net. | ||
- bias_atom_e: Average enery per atom for each element. | ||
- resnet_dt: Using time-step in the ResNet construction. | ||
""" | ||
super().__init__() | ||
self.ntypes = ntypes | ||
self.embedding_width = embedding_width | ||
self.out_dim = out_dim | ||
Parameters | ||
---------- | ||
var_name : str | ||
The atomic property to fit, 'dipole'. | ||
ntypes : int | ||
Element count. | ||
dim_descrpt : int | ||
Embedding width per atom. | ||
dim_out : int | ||
The output dimension of the fitting net. | ||
dim_rot_mat : int | ||
The dimension of rotation matrix, m1. | ||
neuron : List[int] | ||
Number of neurons in each hidden layers of the fitting net. | ||
resnet_dt : bool | ||
Using time-step in the ResNet construction. | ||
numb_fparam : int | ||
Number of frame parameters. | ||
numb_aparam : int | ||
Number of atomic parameters. | ||
activation_function : str | ||
Activation function. | ||
precision : str | ||
Numerical precision. | ||
distinguish_types : bool | ||
Neighbor list that distinguish different atomic types or not. | ||
rcond : float, optional | ||
The condition number for the regression of atomic energy. | ||
seed : int, optional | ||
Random seed. | ||
""" | ||
|
||
filter_layers = [] | ||
one = ResidualDeep( | ||
0, embedding_width, neuron, 0.0, out_dim=self.out_dim, resnet_dt=resnet_dt | ||
def __init__( | ||
self, | ||
var_name: str, | ||
ntypes: int, | ||
dim_descrpt: int, | ||
dim_out: int, | ||
anyangml marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dim_rot_mat: int, | ||
anyangml marked this conversation as resolved.
Show resolved
Hide resolved
|
||
neuron: List[int] = [128, 128, 128], | ||
resnet_dt: bool = True, | ||
numb_fparam: int = 0, | ||
numb_aparam: int = 0, | ||
activation_function: str = "tanh", | ||
precision: str = DEFAULT_PRECISION, | ||
distinguish_types: bool = False, | ||
rcond: Optional[float] = None, | ||
seed: Optional[int] = None, | ||
**kwargs, | ||
anyangml marked this conversation as resolved.
Show resolved
Hide resolved
|
||
): | ||
self.dim_rot_mat = dim_rot_mat | ||
super().__init__( | ||
var_name=var_name, | ||
ntypes=ntypes, | ||
dim_descrpt=dim_descrpt, | ||
dim_out=dim_out, | ||
anyangml marked this conversation as resolved.
Show resolved
Hide resolved
|
||
neuron=neuron, | ||
resnet_dt=resnet_dt, | ||
numb_fparam=numb_fparam, | ||
numb_aparam=numb_aparam, | ||
activation_function=activation_function, | ||
precision=precision, | ||
distinguish_types=distinguish_types, | ||
rcond=rcond, | ||
seed=seed, | ||
**kwargs, | ||
) | ||
filter_layers.append(one) | ||
self.filter_layers = torch.nn.ModuleList(filter_layers) | ||
self.old_impl = False # this only supports the new implementation. | ||
Check warningCode scanning / CodeQL Overwriting attribute in super-class or sub-class
Assignment overwrites attribute old_impl, which was previously defined in superclass [GeneralFitting](1).
|
||
|
||
if "seed" in kwargs: | ||
log.info("Set seed to %d in fitting net.", kwargs["seed"]) | ||
torch.manual_seed(kwargs["seed"]) | ||
def _net_out_dim(self): | ||
"""Set the FittingNet output dim.""" | ||
return self.dim_rot_mat | ||
|
||
def forward(self, inputs, atype, atype_tebd, rot_mat): | ||
"""Based on embedding net output, alculate total energy. | ||
def serialize(self) -> dict: | ||
data = super().serialize() | ||
data["dim_rot_mat"] = self.dim_rot_mat | ||
data["old_impl"] = self.old_impl | ||
return data | ||
|
||
Args: | ||
- inputs: Descriptor. Its shape is [nframes, nloc, self.embedding_width]. | ||
- atype: Atom type. Its shape is [nframes, nloc]. | ||
- atype_tebd: Atom type embedding. Its shape is [nframes, nloc, tebd_dim] | ||
- rot_mat: GR during descriptor calculation. Its shape is [nframes * nloc, m1, 3]. | ||
|
||
Returns | ||
------- | ||
- vec_out: output vector. Its shape is [nframes, nloc, 3]. | ||
""" | ||
nframes, nloc, _ = inputs.size() | ||
if atype_tebd is not None: | ||
inputs = torch.concat([inputs, atype_tebd], dim=-1) | ||
vec_out = self.filter_layers[0](inputs) # Shape is [nframes, nloc, m1] | ||
assert list(vec_out.size()) == [nframes, nloc, self.out_dim] | ||
vec_out = vec_out.view(-1, 1, self.out_dim) | ||
vec_out = ( | ||
torch.bmm(vec_out, rot_mat).squeeze(-2).view(nframes, nloc, 3) | ||
) # Shape is [nframes, nloc, 3] | ||
return vec_out | ||
def forward( | ||
self, | ||
descriptor: torch.Tensor, | ||
atype: torch.Tensor, | ||
gr: Optional[torch.Tensor] = None, | ||
g2: Optional[torch.Tensor] = None, | ||
h2: Optional[torch.Tensor] = None, | ||
fparam: Optional[torch.Tensor] = None, | ||
aparam: Optional[torch.Tensor] = None, | ||
): | ||
nframes, nloc, _ = descriptor.shape | ||
assert gr is not None, "Must provide the rotation matrix for dipole fitting." | ||
# (nframes, nloc, m1) | ||
out = self._forward_common(descriptor, atype, gr, g2, h2, fparam, aparam)[ | ||
self.var_name | ||
] | ||
# (nframes * nloc, 1, m1) | ||
out = out.view(-1, 1, self.dim_rot_mat) | ||
# (nframes * nloc, m1, 3) | ||
gr = gr.view(nframes * nloc, -1, 3) | ||
# (nframes, nloc, 3) | ||
out = torch.bmm(out, gr).squeeze(-2).view(nframes, nloc, 3) | ||
return {self.var_name: out.to(env.GLOBAL_PT_FLOAT_PRECISION)} |
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
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.
Uh oh!
There was an error while loading. Please reload this page.