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: breaking: backend indepdent definition for dp model #3208

Merged
merged 32 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
ba62e99
add chatgpt translated code
Jan 30, 2024
d51f044
fix bugs of nlist and add uts
Jan 31, 2024
4ed1a5e
fix wrapper class name
Jan 31, 2024
25045a1
support int types in type dict
Jan 31, 2024
1f5378b
fix descriptor interfaces (abs class should be introduced later)
Jan 31, 2024
3a029e0
add missing file
Jan 31, 2024
2e4ef50
add dp model def for atomic model
Jan 31, 2024
8c82620
refactor torch atomic model. implement serialize and deserialize. add…
Jan 31, 2024
27f14cd
dp model format for dp models.
Jan 31, 2024
fc3cc8e
dp model format for dp models. add missing files...
Jan 31, 2024
515a724
torch support for the dp model format
Jan 31, 2024
9ca6de3
add ut for the open boundary condition. fix bugs
Jan 31, 2024
7eb1637
support fparam and aparam for atomic model and model. add doc str for…
Jan 31, 2024
40042fa
clean up unused code
Jan 31, 2024
d498a23
fix bugs
Jan 31, 2024
3c84e07
add doc strings
Jan 31, 2024
0c1913b
rm unused code
Jan 31, 2024
96bbb45
fix type hint
Jan 31, 2024
c0a5a56
add format nlist to model
Feb 1, 2024
553ef53
Merge remote-tracking branch 'upstream/devel' into mdfmt-model-1
Feb 1, 2024
f54c724
add place holders to PairTab. fix test: asserting equal between floats
Feb 1, 2024
600349b
forward lower returns reduced virial
Feb 1, 2024
9dd10c9
fix ut
Feb 1, 2024
2ca139d
rm unused vars
Feb 1, 2024
927007c
do not raise, use pass
Feb 1, 2024
6f2d3ac
model_format -> dpmodel, changed module path
Feb 1, 2024
a944441
fix type of the name
Feb 1, 2024
9701ad9
rearrange the def of atomic model. provide base class for fitting. re…
Feb 1, 2024
f412bf7
add base abstract class for descriptor. also fixes get_ntype->get_ntypes
Feb 1, 2024
87fabfb
add distinguish types in base descriptor. fix docstrings
Feb 1, 2024
171e251
possible to change forward name in make base atomic model. fix debug …
Feb 2, 2024
7be7255
fix typo
Feb 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions deepmd/dpmodel/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from .common import (
DEFAULT_PRECISION,
PRECISION_DICT,
NativeOP,
)
from .model import (
DPAtomicModel,
DPModel,
)
from .output_def import (
FittingOutputDef,
ModelOutputDef,
OutputVariableDef,
fitting_check_output,
get_deriv_name,
get_reduce_name,
model_check_output,
)

__all__ = [
"DPModel",
"DPAtomicModel",
"PRECISION_DICT",
"DEFAULT_PRECISION",
"NativeOP",
"ModelOutputDef",
"FittingOutputDef",
"OutputVariableDef",
"model_check_output",
"fitting_check_output",
"get_reduce_name",
"get_deriv_name",
]
6 changes: 5 additions & 1 deletion deepmd/model_format/common.py → deepmd/dpmodel/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from abc import (
ABC,
abstractmethod,
)

import numpy as np
Expand All @@ -12,16 +13,19 @@
"half": np.float16,
"single": np.float32,
"double": np.float64,
"int32": np.int32,
"int64": np.int64,
}
DEFAULT_PRECISION = "float64"


class NativeOP(ABC):
"""The unit operation of a native model."""

@abstractmethod
def call(self, *args, **kwargs):
"""Forward pass in NumPy implementation."""
raise NotImplementedError
pass

Check warning on line 28 in deepmd/dpmodel/common.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/common.py#L28

Added line #L28 was not covered by tests

def __call__(self, *args, **kwargs):
"""Forward pass in NumPy implementation."""
Expand Down
12 changes: 12 additions & 0 deletions deepmd/dpmodel/descriptor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from .make_base_descriptor import (
make_base_descriptor,
)
from .se_e2_a import (
DescrptSeA,
)

__all__ = [
"DescrptSeA",
"make_base_descriptor",
]
8 changes: 8 additions & 0 deletions deepmd/dpmodel/descriptor/base_descriptor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
import numpy as np

from .make_base_descriptor import (
make_base_descriptor,
)

BaseDescriptor = make_base_descriptor(np.ndarray, "call")
106 changes: 106 additions & 0 deletions deepmd/dpmodel/descriptor/make_base_descriptor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from abc import (
ABC,
abstractclassmethod,
abstractmethod,
)
from typing import (
List,
Optional,
)


def make_base_descriptor(
t_tensor,
fwd_method_name: str = "forward",
):
"""Make the base class for the descriptor.

Parameters
----------
t_tensor
The type of the tensor. used in the type hint.
fwd_method_name
Name of the forward method. For dpmodels, it should be "call".
For torch models, it should be "forward".

"""

class BD(ABC):
"""Base descriptor provides the interfaces of descriptor."""

@abstractmethod
def get_rcut(self) -> float:
"""Returns the cut-off radius."""
pass

Check warning on line 35 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L35

Added line #L35 was not covered by tests

@abstractmethod
def get_sel(self) -> List[int]:
"""Returns the number of selected neighboring atoms for each type."""
pass

Check warning on line 40 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L40

Added line #L40 was not covered by tests

def get_nsel(self) -> int:
"""Returns the total number of selected neighboring atoms in the cut-off radius."""
return sum(self.get_sel())

Check warning on line 44 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L44

Added line #L44 was not covered by tests

def get_nnei(self) -> int:
"""Returns the total number of selected neighboring atoms in the cut-off radius."""
return self.get_nsel()

Check warning on line 48 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L48

Added line #L48 was not covered by tests

@abstractmethod
def get_ntypes(self) -> int:
"""Returns the number of element types."""
pass

Check warning on line 53 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L53

Added line #L53 was not covered by tests

@abstractmethod
def get_dim_out(self) -> int:
"""Returns the output descriptor dimension."""
pass

Check warning on line 58 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L58

Added line #L58 was not covered by tests

@abstractmethod
def get_dim_emb(self) -> int:
"""Returns the embedding dimension of g2."""
pass

Check warning on line 63 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L63

Added line #L63 was not covered by tests

@abstractmethod
def distinguish_types(self) -> bool:
"""Returns if the descriptor requires a neighbor list that distinguish different
atomic types or not.
"""
pass

Check warning on line 70 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L70

Added line #L70 was not covered by tests

@abstractmethod
def compute_input_stats(self, merged):
"""Update mean and stddev for descriptor elements."""
pass

Check warning on line 75 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L75

Added line #L75 was not covered by tests

@abstractmethod
def init_desc_stat(self, sumr, suma, sumn, sumr2, suma2):
"""Initialize the model bias by the statistics."""
pass

Check warning on line 80 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L80

Added line #L80 was not covered by tests

@abstractmethod
def fwd(
self,
extended_coord,
extended_atype,
nlist,
mapping: Optional[t_tensor] = None,
):
"""Calculate descriptor."""
pass

Check warning on line 91 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L91

Added line #L91 was not covered by tests

@abstractmethod
def serialize(self) -> dict:
"""Serialize the obj to dict."""
pass

Check warning on line 96 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L96

Added line #L96 was not covered by tests

@abstractclassmethod
def deserialize(cls):
"""Deserialize from a dict."""
pass

Check warning on line 101 in deepmd/dpmodel/descriptor/make_base_descriptor.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/make_base_descriptor.py#L101

Added line #L101 was not covered by tests

setattr(BD, fwd_method_name, BD.fwd)
delattr(BD, "fwd")

return BD
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,22 @@
Optional,
)

from .common import (
from deepmd.dpmodel import (
DEFAULT_PRECISION,
NativeOP,
)
from .env_mat import (
EnvMat,
)
from .network import (
from deepmd.dpmodel.utils import (
EmbeddingNet,
EnvMat,
NetworkCollection,
)

from .base_descriptor import (
BaseDescriptor,
)


class DescrptSeA(NativeOP):
class DescrptSeA(NativeOP, BaseDescriptor):
r"""DeepPot-SE constructed from all information (both angular and radial) of
atomic configurations. The embedding takes the distance between atoms as input.

Expand Down Expand Up @@ -193,9 +195,43 @@

@property
def dim_out(self):
"""Returns the output dimension of this descriptor."""
return self.get_dim_out()

def get_dim_out(self):
"""Returns the output dimension of this descriptor."""
return self.neuron[-1] * self.axis_neuron

def get_dim_emb(self):
"""Returns the embedding (g2) dimension of this descriptor."""
return self.neuron[-1]

Check warning on line 207 in deepmd/dpmodel/descriptor/se_e2_a.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/se_e2_a.py#L207

Added line #L207 was not covered by tests

def get_rcut(self):
"""Returns cutoff radius."""
return self.rcut

def get_sel(self):
"""Returns cutoff radius."""
return self.sel

def distinguish_types(self):
"""Returns if the descriptor requires a neighbor list that distinguish different
atomic types or not.
"""
return True

def get_ntypes(self) -> int:
"""Returns the number of element types."""
return self.ntypes

Check warning on line 225 in deepmd/dpmodel/descriptor/se_e2_a.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/se_e2_a.py#L225

Added line #L225 was not covered by tests

def compute_input_stats(self, merged):
"""Update mean and stddev for descriptor elements."""
raise NotImplementedError

Check warning on line 229 in deepmd/dpmodel/descriptor/se_e2_a.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/se_e2_a.py#L229

Added line #L229 was not covered by tests

def init_desc_stat(self, sumr, suma, sumn, sumr2, suma2):
"""Initialize the model bias by the statistics."""
raise NotImplementedError

Check warning on line 233 in deepmd/dpmodel/descriptor/se_e2_a.py

View check run for this annotation

Codecov / codecov/patch

deepmd/dpmodel/descriptor/se_e2_a.py#L233

Added line #L233 was not covered by tests

def cal_g(
self,
ss,
Expand All @@ -212,6 +248,7 @@
coord_ext,
atype_ext,
nlist,
mapping: Optional[np.ndarray] = None,
):
"""Compute the descriptor.

Expand All @@ -223,6 +260,8 @@
The extended aotm types. shape: nf x nall
nlist
The neighbor list. shape: nf x nloc x nnei
mapping
The index mapping from extended to lcoal region. not used by this descriptor.

Returns
-------
Expand All @@ -240,6 +279,7 @@
sw
The smooth switch function.
"""
del mapping
wanghan-iapcm marked this conversation as resolved.
Show resolved Hide resolved
# nf x nloc x nnei x 4
rr, ww = self.env_mat.call(coord_ext, atype_ext, nlist, self.davg, self.dstd)
nf, nloc, nnei, _ = rr.shape
Expand Down
12 changes: 12 additions & 0 deletions deepmd/dpmodel/fitting/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from .invar_fitting import (
InvarFitting,
)
from .make_base_fitting import (
make_base_fitting,
)

__all__ = [
"InvarFitting",
"make_base_fitting",
]
8 changes: 8 additions & 0 deletions deepmd/dpmodel/fitting/base_fitting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
import numpy as np

from .make_base_fitting import (
make_base_fitting,
)

BaseFitting = make_base_fitting(np.ndarray, fwd_method_name="call")
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,35 @@
import copy
from typing import (
Any,
Dict,
List,
Optional,
)

import numpy as np

from .common import (
from deepmd.dpmodel import (
DEFAULT_PRECISION,
NativeOP,
)
from .network import (
FittingNet,
NetworkCollection,
)
from .output_def import (
from deepmd.dpmodel.output_def import (
FittingOutputDef,
OutputVariableDef,
fitting_check_output,
)
from deepmd.dpmodel.utils import (
FittingNet,
NetworkCollection,
)

from .base_fitting import (
BaseFitting,
)


@fitting_check_output
class InvarFitting(NativeOP):
r"""Fitting the energy (or a porperty of `dim_out`) of the system. The force and the virial can also be trained.
class InvarFitting(NativeOP, BaseFitting):
r"""Fitting the energy (or a rotationally invariant porperty of `dim_out`) of the system. The force and the virial can also be trained.

Lets take the energy fitting task as an example.
The potential energy :math:`E` is a fitting network function of the descriptor :math:`\mathcal{D}`:
Expand Down Expand Up @@ -279,7 +284,7 @@ def call(
h2: Optional[np.array] = None,
fparam: Optional[np.array] = None,
aparam: Optional[np.array] = None,
):
) -> Dict[str, np.array]:
"""Calculate the fitting.

Parameters
Expand Down Expand Up @@ -320,7 +325,7 @@ def call(
"which is not consistent with {self.numb_fparam}.",
)
fparam = (fparam - self.fparam_avg) * self.fparam_inv_std
fparam = np.tile(fparam.reshape([nf, 1, -1]), [1, nloc, 1])
fparam = np.tile(fparam.reshape([nf, 1, self.numb_fparam]), [1, nloc, 1])
xx = np.concatenate(
[xx, fparam],
axis=-1,
Expand All @@ -333,6 +338,7 @@ def call(
"get an input aparam of dim {aparam.shape[-1]}, ",
"which is not consistent with {self.numb_aparam}.",
)
aparam = aparam.reshape([nf, nloc, self.numb_aparam])
aparam = (aparam - self.aparam_avg) * self.aparam_inv_std
xx = np.concatenate(
[xx, aparam],
Expand Down
Loading
Loading