import torch import torch.nn as nn from data import _STD_ENERGY, _STD_FORCE_SCALE from torch_scatter import scatter from tqdm import tqdm class ForceRMSELoss(nn.Module): def __init__(self): super().__init__() def forward(self, pred, target, batch): return scatter((pred - target).pow(2).sum(dim=-1), batch, reduce="mean", dim=0, dim_size=batch.max().item() + 1).sqrt().mean() def train(model, device, train_loader, optimizer, criterion_energy, criterion_force, energy_weight=1.0, force_weight=1.0, clip_gradients=False, grad_clip_norm=1.0): model.train() total_energy_loss = 0. total_force_loss = 0. progress_bar = tqdm(train_loader, desc='Training', bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') for batch in progress_bar: optimizer.zero_grad() data = batch.to(device, non_blocking=True) energies, forces, mask = model(data) energy_loss = criterion_energy(energies, data.y) force_loss = criterion_force(forces, data.y_force[mask], data.batch[mask]) loss = energy_weight * energy_loss + force_weight * force_loss total_energy_loss += energy_loss.item() total_force_loss += force_loss.item() loss.backward() if clip_gradients: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=grad_clip_norm) optimizer.step() progress_bar.set_description( f"Training - Energy Loss: {energy_loss * _STD_ENERGY:.5f}, " f"Force Loss: {force_loss * _STD_FORCE_SCALE:.5f}") average_energy_loss = total_energy_loss / len(train_loader) average_force_loss = total_force_loss / len(train_loader) return average_energy_loss, average_force_loss def evaluate(model, device, loader, criterion_energy, criterion_force): model.eval() total_energy_loss = 0. total_force_loss = 0. progress_bar = tqdm(loader, desc='Evaluating', bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') for batch in progress_bar: data = batch.to(device, non_blocking=True) energies, forces, mask = model(data) energy_loss = criterion_energy(energies, data.y) force_loss = criterion_force(forces, data.y_force[mask], data.batch[mask]) total_energy_loss += energy_loss.item() total_force_loss += force_loss.item() progress_bar.set_description( f"Evaluation - Energy Loss: {energy_loss * _STD_ENERGY:.5f}, Force Loss: {force_loss * _STD_FORCE_SCALE:.5f}") average_energy_loss = total_energy_loss / len(loader) average_force_loss = total_force_loss / len(loader) return average_energy_loss, average_force_loss