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

Fix a bug in setting up loss function for stochastic weight averaging (swa) #504

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
48 changes: 19 additions & 29 deletions mace/cli/run_train.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import json
import logging
import os
import inspect
from copy import deepcopy
from pathlib import Path
from typing import Optional
Expand Down Expand Up @@ -598,35 +599,24 @@ def run(args: argparse.Namespace) -> None:
logging.info(f"Setting start swa to {args.start_swa}")
if args.loss == "forces_only":
raise ValueError("Can not select swa with forces only loss.")
if args.loss == "virials":
loss_fn_energy = modules.WeightedEnergyForcesVirialsLoss(
energy_weight=args.swa_energy_weight,
forces_weight=args.swa_forces_weight,
virials_weight=args.swa_virials_weight,
)
elif args.loss == "stress":
loss_fn_energy = modules.WeightedEnergyForcesStressLoss(
energy_weight=args.swa_energy_weight,
forces_weight=args.swa_forces_weight,
stress_weight=args.swa_stress_weight,
)
elif args.loss == "energy_forces_dipole":
loss_fn_energy = modules.WeightedEnergyForcesDipoleLoss(
args.swa_energy_weight,
forces_weight=args.swa_forces_weight,
dipole_weight=args.swa_dipole_weight,
)
logging.info(
f"Using stochastic weight averaging (after {args.start_swa} epochs) with energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight}, dipole weight : {args.swa_dipole_weight} and learning rate : {args.swa_lr}"
)
else:
loss_fn_energy = modules.WeightedEnergyForcesLoss(
energy_weight=args.swa_energy_weight,
forces_weight=args.swa_forces_weight,
)
logging.info(
f"Using stochastic weight averaging (after {args.start_swa} epochs) with energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight} and learning rate : {args.swa_lr}"
)
# switch the weights for swa while keeping the choice of loss function unchanged
loss_class = type(loss_fn)
signature = inspect.signature(loss_class.__init__)
parameters = signature.parameters
params = {name: getattr(args, name) for name in parameters if name != 'self'}
weight_params = {
'energy_weight': 'swa_energy_weight',
'forces_weight': 'swa_forces_weight',
'virials_weight': 'swa_virials_weight',
'stress_weight': 'swa_stress_weight',
'dipole_weight': 'swa_dipole_weight',
}
for old_param, new_param in weight_params.items():
if old_param in params:
params[old_param] = getattr(args, new_param)
loss_fn_energy = loss_class(**params)
logging.info(f"Using stochastic weight averaging (after {args.start_swa} epochs) with {loss_fn_energy}")
# weights in loss function updated, creating the swa container
swa = tools.SWAContainer(
model=AveragedModel(model),
scheduler=SWALR(
Expand Down
6 changes: 3 additions & 3 deletions mace/tools/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ def valid_err_log(valid_loss, eval_metrics, logger, log_errors, epoch=None):
)
elif (
log_errors == "PerAtomRMSEstressvirials"
and eval_metrics["rmse_stress_per_atom"] is not None
and eval_metrics["rmse_stress"] is not None
):
error_e = eval_metrics["rmse_e_per_atom"] * 1e3
error_f = eval_metrics["rmse_f"] * 1e3
error_stress = eval_metrics["rmse_stress_per_atom"] * 1e3
error_stress = eval_metrics["rmse_stress"] * 1e3
logging.info(
f"Epoch {epoch}: loss={valid_loss:.4f}, RMSE_E_per_atom={error_e:.1f} meV, RMSE_F={error_f:.1f} meV / A, RMSE_stress_per_atom={error_stress:.1f} meV / A^3"
f"Epoch {epoch}: loss={valid_loss:.4f}, RMSE_E_per_atom={error_e:.1f} meV, RMSE_F={error_f:.1f} meV / A, RMSE_stress={error_stress:.1f} meV / A^3"
)
elif (
log_errors == "PerAtomRMSEstressvirials"
Expand Down