Skip to content

Commit

Permalink
Fix uts; change force_real to force
Browse files Browse the repository at this point in the history
  • Loading branch information
iProzd committed Feb 26, 2024
1 parent 9bf51b4 commit 1185bc1
Show file tree
Hide file tree
Showing 12 changed files with 32 additions and 58 deletions.
23 changes: 2 additions & 21 deletions deepmd/pt/infer/deep_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,6 @@ def eval_model(
energy_out = []
atomic_energy_out = []
force_out = []
force_real_out = []
force_mag_out = []
virial_out = []
atomic_virial_out = []
Expand Down Expand Up @@ -502,8 +501,6 @@ def eval_model(
)
if "force" in batch_output:
force_out.append(batch_output["force"].detach().cpu().numpy())
if "force_real" in batch_output:
force_real_out.append(batch_output["force_real"].detach().cpu().numpy())
if "force_mag" in batch_output:
force_mag_out.append(batch_output["force_mag"].detach().cpu().numpy())
if "virial" in batch_output:
Expand All @@ -525,8 +522,6 @@ def eval_model(
atomic_energy_out.append(batch_output["atom_energy"])
if "force" in batch_output:
force_out.append(batch_output["force"])
if "force_real" in batch_output:
force_real_out.append(batch_output["force_real"])
if "force_mag" in batch_output:
force_mag_out.append(batch_output["force_mag"])
if "virial" in batch_output:
Expand All @@ -549,11 +544,6 @@ def eval_model(
force_out = (
np.concatenate(force_out) if force_out else np.zeros([nframes, natoms, 3])
)
force_real_out = (
np.concatenate(force_real_out)
if force_real_out
else np.zeros([nframes, natoms, 3])
)
force_mag_out = (
np.concatenate(force_mag_out)
if force_mag_out
Expand Down Expand Up @@ -593,13 +583,6 @@ def eval_model(
[nframes, natoms, 3], dtype=GLOBAL_PT_FLOAT_PRECISION, device=DEVICE
)
)
force_real_out = (
torch.cat(force_real_out)
if force_real_out
else torch.zeros(
[nframes, natoms, 3], dtype=GLOBAL_PT_FLOAT_PRECISION, device=DEVICE
)
)
force_mag_out = (
torch.cat(force_mag_out)
if force_mag_out
Expand Down Expand Up @@ -628,12 +611,10 @@ def eval_model(
else:
results_dict = {
"energy": energy_out,
"force": force_out,
"virial": virial_out,
}
if not getattr(model, "__USE_SPIN_INPUT__", False):
results_dict["force"] = force_out
else:
results_dict["force_real"] = force_real_out
if getattr(model, "__USE_SPIN_INPUT__", False):
results_dict["force_mag"] = force_mag_out
if atomic:
results_dict["atom_energy"] = atomic_energy_out
Expand Down
6 changes: 3 additions & 3 deletions deepmd/pt/loss/ener_spin.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ def forward(self, model_pred, label, natoms, learning_rate, mae=False):
)
more_loss["mae_e_all"] = mae_e_all.detach()

if self.has_fr and "force_real" in model_pred and "force" in label:
if self.has_fr and "force" in model_pred and "force" in label:
if not self.use_l1_all:
diff_fr = label["force"] - model_pred["force_real"]
diff_fr = label["force"] - model_pred["force"]
l2_force_real_loss = torch.mean(torch.square(diff_fr))
if not self.inference:
more_loss["l2_force_r_loss"] = l2_force_real_loss.detach()
Expand All @@ -120,7 +120,7 @@ def forward(self, model_pred, label, natoms, learning_rate, mae=False):
more_loss["mae_fr"] = mae_fr.detach()
else:
l1_force_real_loss = F.l1_loss(
label["force"], model_pred["force_real"], reduction="none"
label["force"], model_pred["force"], reduction="none"
)
more_loss["mae_fr"] = l1_force_real_loss.mean().detach()
l1_force_real_loss = l1_force_real_loss.sum(-1).mean(-1).sum()
Expand Down
10 changes: 4 additions & 6 deletions deepmd/pt/model/model/spin_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def forward(
model_predict["energy"] = model_ret["energy_redu"]
model_predict["mask_mag"] = model_ret["mask_mag"]
if self.backbone_model.do_grad_r("energy"):
model_predict["force_real"] = model_ret["energy_derv_r"].squeeze(-2)
model_predict["force"] = model_ret["energy_derv_r"].squeeze(-2)
model_predict["force_mag"] = model_ret["energy_derv_r_mag"].squeeze(-2)
if self.backbone_model.do_grad_c("energy"):
model_predict["virial"] = model_ret["energy_derv_c_redu"].squeeze(-2)
Expand All @@ -498,7 +498,7 @@ def forward(
else:
assert model_ret["dforce_real"] is not None
assert model_ret["dforce_mag"] is not None
model_predict["force_real"] = model_ret["dforce_real"]
model_predict["force"] = model_ret["dforce_real"]
model_predict["force_mag"] = model_ret["dforce_mag"]
return model_predict

Expand Down Expand Up @@ -530,9 +530,7 @@ def forward_lower(
model_predict["energy"] = model_ret["energy_redu"]
model_predict["mask_mag"] = model_ret["mask_mag"]
if self.backbone_model.do_grad_r("energy"):
model_predict["extended_force_real"] = model_ret[
"energy_derv_r"
].squeeze(-2)
model_predict["extended_force"] = model_ret["energy_derv_r"].squeeze(-2)
model_predict["extended_force_mag"] = model_ret[
"energy_derv_r_mag"
].squeeze(-2)
Expand All @@ -545,7 +543,7 @@ def forward_lower(
else:
assert model_ret["dforce_real"] is not None
assert model_ret["dforce_mag"] is not None
model_predict["extended_force_real"] = model_ret["dforce_real"]
model_predict["extended_force"] = model_ret["dforce_real"]
model_predict["extended_force_mag"] = model_ret["dforce_mag"]
else:
model_predict = model_ret
Expand Down
6 changes: 3 additions & 3 deletions deepmd/tf/descriptor/se_a.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,6 @@ class DescrptSeA(DescrptSe):
exclude_types : List[List[int]]
The excluded pairs of types which have no interaction with each other.
For example, `[[0, 1]]` means no interaction between type 0 and type 1.
env_protection: float
Protection parameter to prevent division by zero errors during environment matrix calculations.
set_davg_zero
Set the shift of embedding net input to zero.
activation_function
Expand All @@ -153,6 +151,8 @@ class DescrptSeA(DescrptSe):
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
multi_task
If the model has multi fitting nets to train.
env_protection: float
Protection parameter to prevent division by zero errors during environment matrix calculations.
References
----------
Expand All @@ -174,14 +174,14 @@ def __init__(
seed: Optional[int] = None,
type_one_side: bool = True,
exclude_types: List[List[int]] = [],
env_protection: float = 0.0, # not implement!!
set_davg_zero: bool = False,
activation_function: str = "tanh",
precision: str = "default",
uniform_seed: bool = False,
multi_task: bool = False,
spin: Optional[Spin] = None,
stripped_type_embedding: bool = False,
env_protection: float = 0.0, # not implement!!
**kwargs,
) -> None:
"""Constructor."""
Expand Down
6 changes: 3 additions & 3 deletions source/tests/pt/model/test_autodiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]

def np_infer_coord(
coord,
Expand Down Expand Up @@ -114,7 +114,7 @@ def ff_spin(_spin):
else:
# real force
fdf = -finite_difference(ff_coord, coord, delta=delta).squeeze()
rff = np_infer_coord(coord)["force_real"]
rff = np_infer_coord(coord)["force"]
np.testing.assert_almost_equal(fdf, rff, decimal=places)
# magnetic force
fdf = -finite_difference(ff_spin, spin, delta=delta).squeeze()
Expand Down Expand Up @@ -143,7 +143,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]

def np_infer(
new_cell,
Expand Down
2 changes: 1 addition & 1 deletion source/tests/pt/model/test_ener_spin_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def test_output_shape(
nframes, nloc = self.coord.shape[:2]
torch.testing.assert_close(result["energy"].shape, [nframes, 1])
torch.testing.assert_close(result["atom_energy"].shape, [nframes, nloc, 1])
torch.testing.assert_close(result["force_real"].shape, [nframes, nloc, 3])
torch.testing.assert_close(result["force"].shape, [nframes, nloc, 3])
torch.testing.assert_close(result["force_mag"].shape, [nframes, nloc, 3])
torch.testing.assert_close(result["virial"].shape, [nframes, 9])

Expand Down
8 changes: 4 additions & 4 deletions source/tests/pt/model/test_forward_lower.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]

result_forward = eval_model(
self.model,
Expand Down Expand Up @@ -105,7 +105,7 @@ def test(
torch.testing.assert_close(
result_forward_lower[key], result_forward[key], rtol=prec, atol=prec
)
elif key in ["force", "force_real", "force_mag"]:
elif key in ["force", "force_mag"]:
reduced_vv = reduce_tensor(
result_forward_lower[f"extended_{key}"], mapping, natoms
)
Expand Down Expand Up @@ -165,8 +165,8 @@ def setUp(self):

class TestEnergyModelSpinSeA(unittest.TestCase, ForwardLowerTest):
def setUp(self):
# still need to figure out why only 1e-6 rtol and atol
self.prec = 1e-6
# still need to figure out why only 1e-5 rtol and atol
self.prec = 1e-5
model_params = copy.deepcopy(model_spin)
self.type_split = False
self.test_spin = True
Expand Down
4 changes: 2 additions & 2 deletions source/tests/pt/model/test_permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]
result_0 = eval_model(
self.model,
coord.unsqueeze(0),
Expand All @@ -259,7 +259,7 @@ def test(
for key in test_keys:
if key in ["energy"]:
torch.testing.assert_close(ret0[key], ret1[key], rtol=prec, atol=prec)
elif key in ["force", "force_real", "force_mag"]:
elif key in ["force", "force_mag"]:
torch.testing.assert_close(
ret0[key][idx_perm], ret1[key], rtol=prec, atol=prec
)
Expand Down
6 changes: 3 additions & 3 deletions source/tests/pt/model/test_rot.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]
rmat = torch.tensor(special_ortho_group.rvs(3), dtype=dtype, device=env.DEVICE)

# rotate only coord and shift to the center of cell
Expand All @@ -68,7 +68,7 @@ def test(
for key in test_keys:
if key in ["energy"]:
torch.testing.assert_close(ret0[key], ret1[key], rtol=prec, atol=prec)
elif key in ["force", "force_real", "force_mag"]:
elif key in ["force", "force_mag"]:
torch.testing.assert_close(
torch.matmul(ret0[key], rmat), ret1[key], rtol=prec, atol=prec
)
Expand Down Expand Up @@ -114,7 +114,7 @@ def test(
for key in test_keys:
if key in ["energy"]:
torch.testing.assert_close(ret0[key], ret1[key], rtol=prec, atol=prec)
elif key in ["force", "force_real", "force_mag"]:
elif key in ["force", "force_mag"]:
torch.testing.assert_close(
torch.matmul(ret0[key], rmat), ret1[key], rtol=prec, atol=prec
)
Expand Down
4 changes: 2 additions & 2 deletions source/tests/pt/model/test_smooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]

result_0 = eval_model(
self.model,
Expand Down Expand Up @@ -114,7 +114,7 @@ def compare(ret0, ret1):
torch.testing.assert_close(
ret0[key], ret1[key], rtol=rprec, atol=aprec
)
elif key in ["force", "force_real", "force_mag"]:
elif key in ["force", "force_mag"]:
# plus 1. to avoid the divided-by-zero issue
torch.testing.assert_close(
1.0 + ret0[key], 1.0 + ret1[key], rtol=rprec, atol=aprec
Expand Down
4 changes: 2 additions & 2 deletions source/tests/pt/model/test_trans.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def test(
if not test_spin:
test_keys = ["energy", "force", "virial"]
else:
test_keys = ["energy", "force_real", "force_mag", "virial"]
test_keys = ["energy", "force", "force_mag", "virial"]
result_0 = eval_model(
self.model,
coord.unsqueeze(0),
Expand All @@ -65,7 +65,7 @@ def test(
ret1 = {key: result_1[key].squeeze(0) for key in test_keys}
prec = 1e-10
for key in test_keys:
if key in ["energy", "force", "force_real", "force_mag"]:
if key in ["energy", "force", "force_mag"]:
torch.testing.assert_close(ret0[key], ret1[key], rtol=prec, atol=prec)
elif key == "virial":
if not hasattr(self, "test_virial") or self.test_virial:
Expand Down
11 changes: 3 additions & 8 deletions source/tests/pt/model/test_unused_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,9 @@ def _test_unused(self, model_params):
coord = torch.matmul(coord, cell)
atype = torch.IntTensor([0, 0, 0, 1, 1]).to(env.DEVICE)
idx_perm = [1, 0, 4, 3, 2]
e0, f0, v0 = eval_model(
self.model, coord.unsqueeze(0), cell.unsqueeze(0), atype
)
ret0 = {
"energy": e0.squeeze(0),
"force": f0.squeeze(0),
"virial": v0.squeeze(0),
}
result_0 = eval_model(self.model, coord.unsqueeze(0), cell.unsqueeze(0), atype)
test_keys = ["energy", "force", "virial"]
ret0 = {key: result_0[key].squeeze(0) for key in test_keys}

# use computation graph to find all contributing tensors
def get_contributing_params(y, top_level=True):
Expand Down

0 comments on commit 1185bc1

Please sign in to comment.