Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
0378492
Initial plan
Copilot Aug 29, 2025
04f5230
Add type hints to PyTorch backend files: inference, env_mat_stat, dat…
Copilot Aug 29, 2025
8b13778
Add type hints to neighbor_stat.py and enable ANN rule for fixed PyTo…
Copilot Aug 29, 2025
31f1a81
fix: remove ANN rule enforcement and fix remaining ruff errors
Copilot Aug 29, 2025
ecb5a04
fix: revert third-party file changes and restore ANN rules correctly
Copilot Aug 29, 2025
7266d90
fix: revert pyproject.toml and only remove ANN exclusion from deepmd/pt
Copilot Aug 29, 2025
47a3d40
Changes before error encountered
Copilot Aug 29, 2025
c9add7c
Changes before error encountered
Copilot Aug 30, 2025
0f0590d
Changes before error encountered
Copilot Aug 30, 2025
d410082
Changes before error encountered
Copilot Aug 30, 2025
f1b367c
Changes before error encountered
Copilot Aug 30, 2025
19b07d9
Changes before error encountered
Copilot Aug 30, 2025
41d70a2
fix: resolve type annotations in model files - dipole, dos, dp_zbl (2…
Copilot Aug 30, 2025
03d4902
Changes before error encountered
Copilot Aug 30, 2025
a4cfaad
Changes before error encountered
Copilot Aug 30, 2025
cf7985d
Changes before error encountered
Copilot Aug 30, 2025
aa82472
Changes before error encountered
Copilot Aug 30, 2025
25a4386
fix: resolve all remaining pre-commit errors - fix deprecated type an…
Copilot Aug 30, 2025
b2d1c86
fix: address code review feedback - remove unnecessary tuple imports …
Copilot Aug 30, 2025
e5e87bb
fix: resolve TorchScript compilation errors for PyTorch backend
Copilot Aug 30, 2025
6f1efdc
Revert "fix: resolve TorchScript compilation errors for PyTorch backend"
njzjz Aug 30, 2025
1415e50
make TorchScript happy
njzjz Aug 30, 2025
6ff6073
fix: resolve TorchScript compilation errors in deepmd.pt descriptor m…
Copilot Aug 30, 2025
8317c09
fix: resolve TorchScript compilation errors in SE-T and SE-T-TEBD des…
Copilot Aug 30, 2025
5c691a4
fix(pt): correct return type annotation in SpinModel.process_spin_inp…
Copilot Aug 30, 2025
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
26 changes: 15 additions & 11 deletions deepmd/pt/entrypoints/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Path,
)
from typing import (
Any,
Optional,
Union,
)
Expand Down Expand Up @@ -95,20 +96,23 @@


def get_trainer(
config,
init_model=None,
restart_model=None,
finetune_model=None,
force_load=False,
init_frz_model=None,
shared_links=None,
finetune_links=None,
):
config: dict[str, Any],
init_model: Optional[str] = None,
restart_model: Optional[str] = None,
finetune_model: Optional[str] = None,
force_load: bool = False,
init_frz_model: Optional[str] = None,
shared_links: Optional[dict[str, Any]] = None,
finetune_links: Optional[dict[str, Any]] = None,
) -> training.Trainer:
multi_task = "model_dict" in config.get("model", {})

def prepare_trainer_input_single(
model_params_single, data_dict_single, rank=0, seed=None
):
model_params_single: dict[str, Any],
data_dict_single: dict[str, Any],
rank: int = 0,
seed: Optional[int] = None,
) -> tuple[DpLoaderSet, Optional[DpLoaderSet], Optional[DPPath]]:
training_dataset_params = data_dict_single["training_data"]
validation_dataset_params = data_dict_single.get("validation_data", None)
validation_systems = (
Expand Down
16 changes: 9 additions & 7 deletions deepmd/pt/infer/deep_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,15 +272,15 @@ def get_ntypes_spin(self) -> int:
"""Get the number of spin atom types of this model. Only used in old implement."""
return 0

def get_has_spin(self):
def get_has_spin(self) -> bool:
"""Check if the model has spin atom types."""
return self._has_spin

def get_has_hessian(self):
def get_has_hessian(self) -> bool:
"""Check if the model has hessian."""
return self._has_hessian

def get_model_branch(self):
def get_model_branch(self) -> tuple[dict[str, str], dict[str, dict[str, Any]]]:
"""Get the model branch information."""
if "model_dict" in self.model_def_script:
model_alias_dict, model_branch_dict = get_model_dict(
Expand Down Expand Up @@ -419,7 +419,7 @@ def _eval_func(self, inner_func: Callable, numb_test: int, natoms: int) -> Calla
"""
if self.auto_batch_size is not None:

def eval_func(*args, **kwargs):
def eval_func(*args: Any, **kwargs: Any) -> Any:
return self.auto_batch_size.execute_all(
inner_func, numb_test, natoms, *args, **kwargs
)
Expand Down Expand Up @@ -453,7 +453,7 @@ def _eval_model(
fparam: Optional[np.ndarray],
aparam: Optional[np.ndarray],
request_defs: list[OutputVariableDef],
):
) -> tuple[np.ndarray, ...]:
model = self.dp.to(DEVICE)
prec = NP_PRECISION_DICT[RESERVED_PRECISION_DICT[GLOBAL_PT_FLOAT_PRECISION]]

Expand Down Expand Up @@ -531,7 +531,7 @@ def _eval_model_spin(
fparam: Optional[np.ndarray],
aparam: Optional[np.ndarray],
request_defs: list[OutputVariableDef],
):
) -> tuple[np.ndarray, ...]:
model = self.dp.to(DEVICE)

nframes = coords.shape[0]
Expand Down Expand Up @@ -608,7 +608,9 @@ def _eval_model_spin(
) # this is kinda hacky
return tuple(results)

def _get_output_shape(self, odef, nframes, natoms):
def _get_output_shape(
self, odef: OutputVariableDef, nframes: int, natoms: int
) -> list[int]:
if odef.category == OutputVariableCategory.DERV_C_REDU:
# virial
return [nframes, *odef.shape[:-1], 9]
Expand Down
8 changes: 6 additions & 2 deletions deepmd/pt/infer/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
from copy import (
deepcopy,
)
from typing import (
Optional,
Union,
)

import torch

Expand All @@ -25,8 +29,8 @@
class Tester:
def __init__(
self,
model_ckpt,
head=None,
model_ckpt: Union[str, torch.nn.Module],
head: Optional[str] = None,
) -> None:
"""Construct a DeePMD tester.

Expand Down
31 changes: 21 additions & 10 deletions deepmd/pt/loss/denoise.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Any,
)

import torch
import torch.nn.functional as F

Expand All @@ -13,15 +17,15 @@
class DenoiseLoss(TaskLoss):
def __init__(
self,
ntypes,
masked_token_loss=1.0,
masked_coord_loss=1.0,
norm_loss=0.01,
use_l1=True,
beta=1.00,
mask_loss_coord=True,
mask_loss_token=True,
**kwargs,
ntypes: int,
masked_token_loss: float = 1.0,
masked_coord_loss: float = 1.0,
norm_loss: float = 0.01,
use_l1: bool = True,
beta: float = 1.00,
mask_loss_coord: bool = True,
mask_loss_token: bool = True,
**kwargs: Any,
) -> None:
"""Construct a layer to compute loss on coord, and type reconstruction."""
super().__init__()
Expand All @@ -38,7 +42,14 @@ def __init__(
self.mask_loss_coord = mask_loss_coord
self.mask_loss_token = mask_loss_token

def forward(self, model_pred, label, natoms, learning_rate, mae=False):
def forward(
self,
model_pred: dict[str, torch.Tensor],
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: float,
mae: bool = False,
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
"""Return loss on coord and type denoise.

Returns
Expand Down
17 changes: 14 additions & 3 deletions deepmd/pt/loss/dos.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Any,
)

import torch

Expand Down Expand Up @@ -26,8 +29,8 @@ def __init__(
limit_pref_ados: float = 0.0,
start_pref_acdf: float = 0.0,
limit_pref_acdf: float = 0.0,
inference=False,
**kwargs,
inference: bool = False,
**kwargs: Any,
) -> None:
r"""Construct a loss for local and global tensors.

Expand Down Expand Up @@ -85,7 +88,15 @@ def __init__(
)
)

def forward(self, input_dict, model, label, natoms, learning_rate=0.0, mae=False):
def forward(
self,
input_dict: dict[str, torch.Tensor],
model: torch.nn.Module,
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: float = 0.0,
mae: bool = False,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, dict[str, torch.Tensor]]:
"""Return loss on local and global tensors.

Parameters
Expand Down
55 changes: 37 additions & 18 deletions deepmd/pt/loss/ener.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Any,
Optional,
)

Expand All @@ -23,7 +24,9 @@
)


def custom_huber_loss(predictions, targets, delta=1.0):
def custom_huber_loss(
predictions: torch.Tensor, targets: torch.Tensor, delta: float = 1.0
) -> torch.Tensor:
error = targets - predictions
abs_error = torch.abs(error)
quadratic_loss = 0.5 * torch.pow(error, 2)
Expand All @@ -35,13 +38,13 @@ def custom_huber_loss(predictions, targets, delta=1.0):
class EnergyStdLoss(TaskLoss):
def __init__(
self,
starter_learning_rate=1.0,
start_pref_e=0.0,
limit_pref_e=0.0,
start_pref_f=0.0,
limit_pref_f=0.0,
start_pref_v=0.0,
limit_pref_v=0.0,
starter_learning_rate: float = 1.0,
start_pref_e: float = 0.0,
limit_pref_e: float = 0.0,
start_pref_f: float = 0.0,
limit_pref_f: float = 0.0,
start_pref_v: float = 0.0,
limit_pref_v: float = 0.0,
start_pref_ae: float = 0.0,
limit_pref_ae: float = 0.0,
start_pref_pf: float = 0.0,
Expand All @@ -52,10 +55,10 @@ def __init__(
limit_pref_gf: float = 0.0,
numb_generalized_coord: int = 0,
use_l1_all: bool = False,
inference=False,
use_huber=False,
huber_delta=0.01,
**kwargs,
inference: bool = False,
use_huber: bool = False,
huber_delta: float = 0.01,
**kwargs: Any,
) -> None:
r"""Construct a layer to compute loss on energy, force and virial.

Expand Down Expand Up @@ -149,7 +152,15 @@ def __init__(
"Huber loss is not implemented for force with atom_pref, generalized force and relative force. "
)

def forward(self, input_dict, model, label, natoms, learning_rate, mae=False):
def forward(
self,
input_dict: dict[str, torch.Tensor],
model: torch.nn.Module,
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: float,
mae: bool = False,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, dict[str, torch.Tensor]]:
"""Return loss on energy and force.

Parameters
Expand Down Expand Up @@ -528,10 +539,10 @@ def deserialize(cls, data: dict) -> "TaskLoss":
class EnergyHessianStdLoss(EnergyStdLoss):
def __init__(
self,
start_pref_h=0.0,
limit_pref_h=0.0,
**kwargs,
):
start_pref_h: float = 0.0,
limit_pref_h: float = 0.0,
**kwargs: Any,
) -> None:
r"""Enable the layer to compute loss on hessian.

Parameters
Expand All @@ -549,7 +560,15 @@ def __init__(
self.start_pref_h = start_pref_h
self.limit_pref_h = limit_pref_h

def forward(self, input_dict, model, label, natoms, learning_rate, mae=False):
def forward(
self,
input_dict: dict[str, torch.Tensor],
model: torch.nn.Module,
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: float,
mae: bool = False,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, dict[str, torch.Tensor]]:
model_pred, loss, more_loss = super().forward(
input_dict, model, label, natoms, learning_rate, mae=mae
)
Expand Down
35 changes: 23 additions & 12 deletions deepmd/pt/loss/ener_spin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# SPDX-License-Identifier: LGPL-3.0-or-later
from typing import (
Any,
)

import torch
import torch.nn.functional as F
Expand All @@ -20,21 +23,21 @@
class EnergySpinLoss(TaskLoss):
def __init__(
self,
starter_learning_rate=1.0,
start_pref_e=0.0,
limit_pref_e=0.0,
start_pref_fr=0.0,
limit_pref_fr=0.0,
start_pref_fm=0.0,
limit_pref_fm=0.0,
start_pref_v=0.0,
limit_pref_v=0.0,
starter_learning_rate: float = 1.0,
start_pref_e: float = 0.0,
limit_pref_e: float = 0.0,
start_pref_fr: float = 0.0,
limit_pref_fr: float = 0.0,
start_pref_fm: float = 0.0,
limit_pref_fm: float = 0.0,
start_pref_v: float = 0.0,
limit_pref_v: float = 0.0,
start_pref_ae: float = 0.0,
limit_pref_ae: float = 0.0,
enable_atom_ener_coeff: bool = False,
use_l1_all: bool = False,
inference=False,
**kwargs,
inference: bool = False,
**kwargs: Any,
) -> None:
r"""Construct a layer to compute loss on energy, real force, magnetic force and virial.

Expand Down Expand Up @@ -93,7 +96,15 @@ def __init__(
self.use_l1_all = use_l1_all
self.inference = inference

def forward(self, input_dict, model, label, natoms, learning_rate, mae=False):
def forward(
self,
input_dict: dict[str, torch.Tensor],
model: torch.nn.Module,
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: float,
mae: bool = False,
) -> tuple[dict[str, torch.Tensor], torch.Tensor, dict[str, torch.Tensor]]:
"""Return energy loss with magnetic labels.

Parameters
Expand Down
13 changes: 11 additions & 2 deletions deepmd/pt/loss/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
abstractmethod,
)
from typing import (
Any,
NoReturn,
Union,
)

import torch
Expand All @@ -18,11 +20,18 @@


class TaskLoss(torch.nn.Module, ABC, make_plugin_registry("loss")):
def __init__(self, **kwargs) -> None:
def __init__(self, **kwargs: Any) -> None:
"""Construct loss."""
super().__init__()

def forward(self, input_dict, model, label, natoms, learning_rate) -> NoReturn:
def forward(
self,
input_dict: dict[str, torch.Tensor],
model: torch.nn.Module,
label: dict[str, torch.Tensor],
natoms: int,
learning_rate: Union[float, torch.Tensor],
) -> NoReturn:
"""Return loss ."""
raise NotImplementedError

Expand Down
Loading
Loading