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

test(pt/dp): add universal uts for all models #3873

Merged
merged 30 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c93269f
test(pt/dp): add universal uts for all models
iProzd Jun 13, 2024
108cdee
update se_r
iProzd Jun 13, 2024
5a5f9e2
fix ut
iProzd Jun 13, 2024
6f59a27
add parametrize to models
iProzd Jun 20, 2024
fbce582
Merge branch 'devel' into add_universal_ut
iProzd Jun 20, 2024
14ae51f
fix squeeze
iProzd Jun 20, 2024
b6afbb1
Update se_r.py
iProzd Jun 20, 2024
5584432
Update path.py
iProzd Jun 20, 2024
16a15c3
Update model.py
iProzd Jun 20, 2024
2542651
Update common.py
iProzd Jun 20, 2024
264718b
Update common.py
iProzd Jun 20, 2024
0098ac5
fix spin aparam
iProzd Jun 20, 2024
569d526
fix ut
iProzd Jun 21, 2024
4e71bba
split tests for descriptor and fitting
iProzd Jun 21, 2024
5e15857
Merge branch 'devel' into add_universal_ut
iProzd Jun 21, 2024
a715178
Merge branch 'devel' into add_universal_ut
iProzd Jun 24, 2024
faa62ed
Update common.py
iProzd Jun 24, 2024
50cffda
fix conversations
iProzd Jun 24, 2024
6c93a35
Merge branch 'devel' into add_universal_ut
iProzd Jun 24, 2024
e6fcb58
Update spin_model.py
iProzd Jun 24, 2024
733b9a4
fix ut
iProzd Jun 24, 2024
481d08c
fix warnings
iProzd Jun 25, 2024
151edb6
Update test_model.py
iProzd Jun 26, 2024
8495659
skip uts on cpu and gpu
iProzd Jun 26, 2024
ba63f73
fix device
iProzd Jun 26, 2024
860a01c
Update utils.py
iProzd Jun 26, 2024
0f06f17
use CUDA_VISIBLE_DEVICES
iProzd Jun 27, 2024
87187cf
Merge branch 'devel' into add_universal_ut
iProzd Jun 27, 2024
28d32ba
Merge branch 'devel' into add_universal_ut
iProzd Jun 27, 2024
3838281
Update test_cuda.yml
iProzd Jun 27, 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
13 changes: 10 additions & 3 deletions deepmd/dpmodel/atomic_model/linear_atomic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,11 @@ def forward_atomic(
]
ener_list = []
for i, model in enumerate(self.models):
mapping = self.mapping_list[i]
type_map_model = self.mapping_list[i]
ener_list.append(
model.forward_atomic(
extended_coord,
mapping[extended_atype],
type_map_model[extended_atype],
nlists_[i],
mapping,
fparam,
Expand Down Expand Up @@ -414,7 +414,12 @@ def _compute_weight(
)

numerator = np.sum(
pairwise_rr * np.exp(-pairwise_rr / self.smin_alpha), axis=-1
np.where(
nlist_larger != -1,
pairwise_rr * np.exp(-pairwise_rr / self.smin_alpha),
np.zeros_like(nlist_larger),
),
axis=-1,
) # masked nnei will be zero, no need to handle
denominator = np.sum(
np.where(
Expand All @@ -436,5 +441,7 @@ def _compute_weight(
smooth = -6 * u**5 + 15 * u**4 - 10 * u**3 + 1
coef[mid_mask] = smooth[mid_mask]
coef[right_mask] = 0
# to handle masked atoms
coef = np.where(sigma != 0, coef, np.zeros_like(coef))
self.zbl_weight = coef
return [1 - np.expand_dims(coef, -1), np.expand_dims(coef, -1)]
2 changes: 1 addition & 1 deletion deepmd/dpmodel/descriptor/se_r.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def get_dim_out(self):
return self.neuron[-1]

def get_dim_emb(self):
"""Returns the embedding (g2) dimension of this descriptor."""
"""Returns the output dimension."""
iProzd marked this conversation as resolved.
Show resolved Hide resolved
raise NotImplementedError

def get_rcut(self):
Expand Down
1 change: 1 addition & 0 deletions deepmd/dpmodel/fitting/dipole_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ def output_def(self):
reduciable=True,
r_differentiable=self.r_differentiable,
c_differentiable=self.c_differentiable,
rot_invariant=False,
),
]
)
Expand Down
1 change: 1 addition & 0 deletions deepmd/dpmodel/fitting/polarizability_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ def output_def(self):
reduciable=True,
r_differentiable=False,
c_differentiable=False,
rot_invariant=False,
iProzd marked this conversation as resolved.
Show resolved Hide resolved
),
]
)
Expand Down
4 changes: 4 additions & 0 deletions deepmd/dpmodel/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
from .dp_model import (
DPModelCommon,
)
from .ener_model import (
EnergyModel,
)
from .make_model import (
make_model,
)
Expand All @@ -23,6 +26,7 @@
)

__all__ = [
"EnergyModel",
"DPModelCommon",
"SpinModel",
"make_model",
Expand Down
15 changes: 14 additions & 1 deletion deepmd/dpmodel/output_def.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ class OutputVariableDef:
If hessian is requred
magnetic : bool
If the derivatives of variable have magnetic parts.
rot_invariant : bool
If the variable is rotationally invariant.
iProzd marked this conversation as resolved.
Show resolved Hide resolved
"""

def __init__(
Expand All @@ -199,6 +201,7 @@ def __init__(
category: int = OutputVariableCategory.OUT.value,
r_hessian: bool = False,
magnetic: bool = False,
rot_invariant: bool = True,
):
self.name = name
self.shape = list(shape)
Expand All @@ -218,6 +221,7 @@ def __init__(
self.category = category
self.r_hessian = r_hessian
self.magnetic = magnetic
self.rot_invariant = rot_invariant
if self.r_hessian:
if not self.reduciable:
raise ValueError("only reduciable variable can calculate hessian")
Expand All @@ -228,6 +232,11 @@ def __init__(
def size(self):
return self.output_size

def squeeze(self, dim):
# squeeze the shape on given dimension
if -len(self.shape) <= dim < len(self.shape) != 1 and self.shape[dim] == 1:
iProzd marked this conversation as resolved.
Show resolved Hide resolved
self.shape.pop(dim)

iProzd marked this conversation as resolved.
Show resolved Hide resolved

class FittingOutputDef:
"""Defines the shapes and other properties of the fitting network outputs.
Expand Down Expand Up @@ -306,7 +315,6 @@ def __getitem__(

def get_data(
self,
key: str,
) -> Dict[str, OutputVariableDef]:
return self.var_defs

Expand Down Expand Up @@ -417,6 +425,7 @@ def do_reduce(
c_differentiable=False,
atomic=False,
category=apply_operation(vv, OutputVariableOperation.REDU),
rot_invariant=vv.rot_invariant,
)
return def_redu

Expand Down Expand Up @@ -465,6 +474,7 @@ def do_derivative(
c_differentiable=False,
atomic=True,
category=apply_operation(vv, OutputVariableOperation.DERV_R),
rot_invariant=False,
)
if vv.magnetic:
def_derv_r[rkrm] = OutputVariableDef(
Expand All @@ -478,6 +488,7 @@ def do_derivative(
atomic=True,
category=apply_operation(vv, OutputVariableOperation.DERV_R),
magnetic=True,
rot_invariant=False,
)

if vv.c_differentiable:
Expand All @@ -490,6 +501,7 @@ def do_derivative(
c_differentiable=False,
atomic=True,
category=apply_operation(vv, OutputVariableOperation.DERV_C),
rot_invariant=False,
)
if vv.magnetic:
def_derv_r[rkcm] = OutputVariableDef(
Expand All @@ -501,5 +513,6 @@ def do_derivative(
atomic=True,
category=apply_operation(vv, OutputVariableOperation.DERV_C),
magnetic=True,
rot_invariant=False,
)
return def_derv_r, def_derv_c
4 changes: 2 additions & 2 deletions deepmd/pt/model/atomic_model/linear_atomic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,12 +224,12 @@ def forward_atomic(
ener_list = []

for i, model in enumerate(self.models):
mapping = self.mapping_list[i]
type_map_model = self.mapping_list[i]
# apply bias to each individual model
ener_list.append(
model.forward_common_atomic(
extended_coord,
mapping[extended_atype],
type_map_model[extended_atype],
nlists_[i],
mapping,
fparam,
Expand Down
3 changes: 3 additions & 0 deletions deepmd/pt/model/descriptor/se_r.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ def forward(
atype_ext: torch.Tensor,
nlist: torch.Tensor,
mapping: Optional[torch.Tensor] = None,
comm_dict: Optional[Dict[str, torch.Tensor]] = None,
):
"""Compute the descriptor.

Expand All @@ -318,6 +319,8 @@ def forward(
The neighbor list. shape: nf x nloc x nnei
mapping
The index mapping, not required by this descriptor.
comm_dict
The data needed for communication for parallel inference.

Returns
-------
Expand Down
3 changes: 3 additions & 0 deletions deepmd/pt/model/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,9 @@ def get_model(model_params):
"get_model",
"DPModelCommon",
"EnergyModel",
"DipoleModel",
"PolarModel",
"DOSModel",
"FrozenModel",
"SpinModel",
"SpinEnergyModel",
Expand Down
29 changes: 25 additions & 4 deletions deepmd/pt/model/model/dipole_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from copy import (
deepcopy,
)
from typing import (
Dict,
Optional,
Expand Down Expand Up @@ -35,6 +38,24 @@ def __init__(
DPModelCommon.__init__(self)
DPDOSModel_.__init__(self, *args, **kwargs)

def translated_output_def(self):
out_def_data = self.model_output_def().get_data()
output_def = {
"dipole": deepcopy(out_def_data["dipole"]),
"global_dipole": deepcopy(out_def_data["dipole_redu"]),
}
if self.do_grad_r("dipole"):
output_def["force"] = deepcopy(out_def_data["dipole_derv_r"])
output_def["force"].squeeze(-2)
if self.do_grad_c("dipole"):
output_def["virial"] = deepcopy(out_def_data["dipole_derv_c_redu"])
output_def["virial"].squeeze(-2)
output_def["atom_virial"] = deepcopy(out_def_data["dipole_derv_c"])
output_def["atom_virial"].squeeze(-3)
if "mask" in out_def_data:
output_def["mask"] = deepcopy(out_def_data["mask"])
return output_def
iProzd marked this conversation as resolved.
Show resolved Hide resolved

def forward(
self,
coord,
Expand Down Expand Up @@ -96,13 +117,13 @@ def forward_lower(
model_predict["dipole"] = model_ret["dipole"]
model_predict["global_dipole"] = model_ret["dipole_redu"]
if self.do_grad_r("dipole"):
model_predict["force"] = model_ret["dipole_derv_r"].squeeze(-2)
model_predict["extended_force"] = model_ret["dipole_derv_r"].squeeze(-2)
if self.do_grad_c("dipole"):
model_predict["virial"] = model_ret["dipole_derv_c_redu"].squeeze(-2)
if do_atomic_virial:
model_predict["atom_virial"] = model_ret["dipole_derv_c"].squeeze(
-3
)
model_predict["extended_virial"] = model_ret[
"dipole_derv_c"
].squeeze(-3)
else:
model_predict = model_ret
return model_predict
13 changes: 13 additions & 0 deletions deepmd/pt/model/model/dos_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from copy import (
deepcopy,
)
from typing import (
Dict,
Optional,
Expand Down Expand Up @@ -35,6 +38,16 @@ def __init__(
DPModelCommon.__init__(self)
DPDOSModel_.__init__(self, *args, **kwargs)

def translated_output_def(self):
out_def_data = self.model_output_def().get_data()
output_def = {
"atom_dos": deepcopy(out_def_data["dos"]),
"dos": deepcopy(out_def_data["dos_redu"]),
}
if "mask" in out_def_data:
output_def["mask"] = deepcopy(out_def_data["mask"])
return output_def
iProzd marked this conversation as resolved.
Show resolved Hide resolved

def forward(
self,
coord,
Expand Down
21 changes: 21 additions & 0 deletions deepmd/pt/model/model/dp_zbl_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from copy import (
deepcopy,
)
from typing import (
Dict,
List,
Expand Down Expand Up @@ -39,6 +42,24 @@ def __init__(
):
super().__init__(*args, **kwargs)

def translated_output_def(self):
out_def_data = self.model_output_def().get_data()
output_def = {
"atom_energy": deepcopy(out_def_data["energy"]),
"energy": deepcopy(out_def_data["energy_redu"]),
}
if self.do_grad_r("energy"):
output_def["force"] = deepcopy(out_def_data["energy_derv_r"])
output_def["force"].squeeze(-2)
if self.do_grad_c("energy"):
output_def["virial"] = deepcopy(out_def_data["energy_derv_c_redu"])
output_def["virial"].squeeze(-2)
output_def["atom_virial"] = deepcopy(out_def_data["energy_derv_c"])
output_def["atom_virial"].squeeze(-3)
if "mask" in out_def_data:
output_def["mask"] = deepcopy(out_def_data["mask"])
return output_def
iProzd marked this conversation as resolved.
Show resolved Hide resolved

def forward(
self,
coord,
Expand Down
21 changes: 21 additions & 0 deletions deepmd/pt/model/model/ener_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from copy import (
deepcopy,
)
from typing import (
Dict,
Optional,
Expand Down Expand Up @@ -35,6 +38,24 @@ def __init__(
DPModelCommon.__init__(self)
DPEnergyModel_.__init__(self, *args, **kwargs)

def translated_output_def(self):
out_def_data = self.model_output_def().get_data()
output_def = {
"atom_energy": deepcopy(out_def_data["energy"]),
"energy": deepcopy(out_def_data["energy_redu"]),
}
if self.do_grad_r("energy"):
output_def["force"] = deepcopy(out_def_data["energy_derv_r"])
output_def["force"].squeeze(-2)
if self.do_grad_c("energy"):
output_def["virial"] = deepcopy(out_def_data["energy_derv_c_redu"])
output_def["virial"].squeeze(-2)
output_def["atom_virial"] = deepcopy(out_def_data["energy_derv_c"])
output_def["atom_virial"].squeeze(-3)
if "mask" in out_def_data:
output_def["mask"] = deepcopy(out_def_data["mask"])
return output_def
iProzd marked this conversation as resolved.
Show resolved Hide resolved

def forward(
self,
coord,
Expand Down
13 changes: 13 additions & 0 deletions deepmd/pt/model/model/polar_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from copy import (
deepcopy,
)
from typing import (
Dict,
Optional,
Expand Down Expand Up @@ -35,6 +38,16 @@ def __init__(
DPModelCommon.__init__(self)
DPDOSModel_.__init__(self, *args, **kwargs)

def translated_output_def(self):
out_def_data = self.model_output_def().get_data()
output_def = {
"polar": deepcopy(out_def_data["polarizability"]),
"global_polar": deepcopy(out_def_data["polarizability_redu"]),
}
if "mask" in out_def_data:
output_def["mask"] = deepcopy(out_def_data["mask"])
return output_def
iProzd marked this conversation as resolved.
Show resolved Hide resolved

def forward(
self,
coord,
Expand Down
1 change: 1 addition & 0 deletions deepmd/pt/model/task/dipole.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def output_def(self) -> FittingOutputDef:
reduciable=True,
r_differentiable=self.r_differentiable,
c_differentiable=self.c_differentiable,
rot_invariant=False,
),
]
)
Expand Down
1 change: 1 addition & 0 deletions deepmd/pt/model/task/polarizability.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ def output_def(self) -> FittingOutputDef:
reduciable=True,
r_differentiable=False,
c_differentiable=False,
rot_invariant=False,
),
]
)
Expand Down
Loading
Loading