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: add DipoleModel and PolarModel #3309

Merged
merged 18 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
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
19 changes: 15 additions & 4 deletions deepmd/dpmodel/fitting/dipole_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,14 @@ class DipoleFitting(GeneralFitting):
mixed_types
If true, use a uniform fitting net for all atom types, otherwise use
different fitting nets for different atom types.
exclude_types: List[int]
exclude_types
Atomic contributions of the excluded atom types are set zero.

r_differentiable
If the variable is differentiated with respect to coordinates of atoms.
Only reduciable variable are differentiable.
c_differentiable
If the variable is differentiated with respect to the cell tensor (pbc case).
Only reduciable variable are differentiable.
"""

def __init__(
Expand All @@ -94,6 +99,8 @@ def __init__(
spin: Any = None,
mixed_types: bool = False,
exclude_types: List[int] = [],
r_differentiable: bool = True,
c_differentiable: bool = True,
old_impl=False,
):
# seed, uniform_seed are not included
Expand All @@ -109,6 +116,8 @@ def __init__(
raise NotImplementedError("atom_ener is not implemented")

self.embedding_width = embedding_width
self.r_differentiable = r_differentiable
self.c_differentiable = c_differentiable
super().__init__(
var_name=var_name,
ntypes=ntypes,
Expand Down Expand Up @@ -139,6 +148,8 @@ def serialize(self) -> dict:
data = super().serialize()
data["embedding_width"] = self.embedding_width
data["old_impl"] = self.old_impl
data["r_differentiable"] = self.r_differentiable
data["c_differentiable"] = self.c_differentiable
return data

def output_def(self):
Expand All @@ -148,8 +159,8 @@ def output_def(self):
self.var_name,
[3],
reduciable=True,
r_differentiable=True,
c_differentiable=True,
r_differentiable=self.r_differentiable,
c_differentiable=self.c_differentiable,
),
]
)
Expand Down
4 changes: 2 additions & 2 deletions deepmd/dpmodel/fitting/polarizability_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@ def output_def(self):
self.var_name,
[3, 3],
reduciable=True,
r_differentiable=True,
c_differentiable=True,
r_differentiable=False,
c_differentiable=False,
),
]
)
Expand Down
18 changes: 11 additions & 7 deletions deepmd/infer/deep_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ def eval(
**kwargs,
)
sel_natoms = self._get_sel_natoms(atom_types[0])
if sel_natoms == 0:
sel_natoms = atom_types.shape[-1] # set to natoms
if atomic:
return results[self.output_tensor_name].reshape(nframes, sel_natoms, -1)
else:
Expand Down Expand Up @@ -184,22 +186,24 @@ def eval_full(
aparam=aparam,
**kwargs,
)

sel_natoms = self._get_sel_natoms(atom_types[0])
if sel_natoms == 0:
sel_natoms = atom_types.shape[-1] # set to natoms
energy = results[f"{self.output_tensor_name}_redu"].reshape(nframes, -1)
force = results[f"{self.output_tensor_name}_derv_r"].reshape(
nframes, -1, natoms, 3
)
virial = results[f"{self.output_tensor_name}_derv_c_redu"].reshape(
nframes, -1, 9
)
atomic_energy = results[self.output_tensor_name].reshape(
nframes, sel_natoms, -1
)
atomic_virial = results[f"{self.output_tensor_name}_derv_c"].reshape(
nframes, -1, natoms, 9
)

if atomic:
atomic_energy = results[self.output_tensor_name].reshape(
nframes, sel_natoms, -1
)
atomic_virial = results[f"{self.output_tensor_name}_derv_c"].reshape(
nframes, -1, natoms, 9
)
return (
energy,
force,
Expand Down
89 changes: 89 additions & 0 deletions deepmd/pt/model/model/dipole_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Dict,
Optional,
)

import torch

from .dp_model import (
DPModel,
)


class DipoleModel(DPModel):
model_type = "dipole"

def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)

def forward(
self,
coord,
atype,
box: Optional[torch.Tensor] = None,
fparam: Optional[torch.Tensor] = None,
aparam: Optional[torch.Tensor] = None,
do_atomic_virial: bool = False,
) -> Dict[str, torch.Tensor]:
model_ret = self.forward_common(
coord,
atype,
box,
fparam=fparam,
aparam=aparam,
do_atomic_virial=do_atomic_virial,
)
if self.fitting_net is not None:
model_predict = {}
model_predict["dipole"] = model_ret["dipole"]
model_predict["global_dipole"] = model_ret["dipole_redu"]
if self.do_grad("dipole"):
model_predict["force"] = model_ret["dipole_derv_r"].squeeze(-2)
if do_atomic_virial:
model_predict["atom_virial"] = model_ret["dipole_derv_c"].squeeze(
-3
)
model_predict["virial"] = model_ret["dipole_derv_c_redu"].squeeze(-2)
else:
model_predict = model_ret
model_predict["updated_coord"] += coord
return model_predict

def forward_lower(
self,
extended_coord,
extended_atype,
nlist,
mapping: Optional[torch.Tensor] = None,
fparam: Optional[torch.Tensor] = None,
aparam: Optional[torch.Tensor] = None,
do_atomic_virial: bool = False,
):
model_ret = self.forward_common_lower(

Check warning on line 67 in deepmd/pt/model/model/dipole_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/dipole_model.py#L67

Added line #L67 was not covered by tests
extended_coord,
extended_atype,
nlist,
mapping,
fparam=fparam,
aparam=aparam,
do_atomic_virial=do_atomic_virial,
)
if self.fitting_net is not None:
model_predict = {}
model_predict["dipole"] = model_ret["dipole"]
model_predict["global_dipole"] = model_ret["dipole_redu"]
if self.do_grad("dipole"):
anyangml marked this conversation as resolved.
Show resolved Hide resolved
model_predict["force"] = model_ret["dipole_derv_r"].squeeze(-2)
if do_atomic_virial:
model_predict["atom_virial"] = model_ret["dipole_derv_c"].squeeze(

Check warning on line 83 in deepmd/pt/model/model/dipole_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/dipole_model.py#L76-L83

Added lines #L76 - L83 were not covered by tests
-3
)
model_predict["virial"] = model_ret["dipole_derv_c_redu"].squeeze(-2)

Check warning on line 86 in deepmd/pt/model/model/dipole_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/dipole_model.py#L86

Added line #L86 was not covered by tests
else:
model_predict = model_ret
return model_predict

Check warning on line 89 in deepmd/pt/model/model/dipole_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/dipole_model.py#L88-L89

Added lines #L88 - L89 were not covered by tests
75 changes: 75 additions & 0 deletions deepmd/pt/model/model/polar_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Dict,
Optional,
)

import torch

from .dp_model import (
DPModel,
)


class PolarModel(DPModel):
model_type = "polar"

def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)

def forward(
self,
coord,
atype,
box: Optional[torch.Tensor] = None,
fparam: Optional[torch.Tensor] = None,
aparam: Optional[torch.Tensor] = None,
do_atomic_virial: bool = False,
) -> Dict[str, torch.Tensor]:
model_ret = self.forward_common(
coord,
atype,
box,
fparam=fparam,
aparam=aparam,
do_atomic_virial=do_atomic_virial,
)
if self.fitting_net is not None:
model_predict = {}
model_predict["polar"] = model_ret["polar"]
model_predict["global_polar"] = model_ret["polar_redu"]
else:
model_predict = model_ret
model_predict["updated_coord"] += coord
return model_predict

def forward_lower(
self,
extended_coord,
extended_atype,
nlist,
mapping: Optional[torch.Tensor] = None,
fparam: Optional[torch.Tensor] = None,
aparam: Optional[torch.Tensor] = None,
do_atomic_virial: bool = False,
):
model_ret = self.forward_common_lower(

Check warning on line 60 in deepmd/pt/model/model/polar_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/polar_model.py#L60

Added line #L60 was not covered by tests
extended_coord,
extended_atype,
nlist,
mapping,
fparam=fparam,
aparam=aparam,
do_atomic_virial=do_atomic_virial,
)
if self.fitting_net is not None:
model_predict = {}
model_predict["polar"] = model_ret["polar"]
model_predict["global_polar"] = model_ret["polar_redu"]

Check warning on line 72 in deepmd/pt/model/model/polar_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/polar_model.py#L69-L72

Added lines #L69 - L72 were not covered by tests
else:
model_predict = model_ret
return model_predict

Check warning on line 75 in deepmd/pt/model/model/polar_model.py

View check run for this annotation

Codecov / codecov/patch

deepmd/pt/model/model/polar_model.py#L74-L75

Added lines #L74 - L75 were not covered by tests
16 changes: 14 additions & 2 deletions deepmd/pt/model/task/dipole.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ class DipoleFittingNet(GeneralFitting):
The condition number for the regression of atomic energy.
seed : int, optional
Random seed.
r_differentiable
If the variable is differentiated with respect to coordinates of atoms.
Only reduciable variable are differentiable.
c_differentiable
If the variable is differentiated with respect to the cell tensor (pbc case).
Only reduciable variable are differentiable.
"""

def __init__(
Expand All @@ -74,9 +80,13 @@ def __init__(
rcond: Optional[float] = None,
seed: Optional[int] = None,
exclude_types: List[int] = [],
r_differentiable: bool = True,
c_differentiable: bool = True,
**kwargs,
):
self.embedding_width = embedding_width
self.r_differentiable = r_differentiable
self.c_differentiable = c_differentiable
super().__init__(
var_name=var_name,
ntypes=ntypes,
Expand All @@ -103,6 +113,8 @@ def serialize(self) -> dict:
data = super().serialize()
data["embedding_width"] = self.embedding_width
data["old_impl"] = self.old_impl
data["r_differentiable"] = self.r_differentiable
data["c_differentiable"] = self.c_differentiable
return data

def output_def(self) -> FittingOutputDef:
Expand All @@ -112,8 +124,8 @@ def output_def(self) -> FittingOutputDef:
self.var_name,
[3],
reduciable=True,
r_differentiable=True,
c_differentiable=True,
r_differentiable=self.r_differentiable,
c_differentiable=self.c_differentiable,
),
]
)
Expand Down
4 changes: 2 additions & 2 deletions deepmd/pt/model/task/polarizability.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ def output_def(self) -> FittingOutputDef:
self.var_name,
[3, 3],
reduciable=True,
r_differentiable=True,
c_differentiable=True,
r_differentiable=False,
c_differentiable=False,
),
]
)
Expand Down
Loading
Loading