"""MACE-small + MLP(E) -> additive delta (Hartree) on a B3LYP baseline.""" from __future__ import annotations import numpy as np import torch import torch.nn as nn from ase import Atoms from mace import data as mace_data from mace.calculators.foundations_models import mace_mp from mace.tools import torch_geometric from mace.tools.utils import AtomicNumberTable HARTREE2KCAL = 627.509474 def _build_readout_head(hidden, n_layers, device, dtype): layers = [] in_dim = 1 for _ in range(n_layers): layers.append(nn.Linear(in_dim, hidden)) layers.append(nn.SiLU()) in_dim = hidden layers.append(nn.Linear(in_dim, 1)) return nn.Sequential(*layers).to(device=device, dtype=dtype) def init_readout_last_linear_small(seq, *, weight_std=1e-6, bias=0.0): last = seq[-1] with torch.no_grad(): nn.init.normal_(last.weight, mean=0.0, std=weight_std) if last.bias is not None: nn.init.constant_(last.bias, bias) class MACEDeltaB3LYPSkala(nn.Module): def __init__( self, r_max=None, device="cuda", dtype=torch.float32, foundation="small", readout_hidden=256, readout_layers=3, last_layer_weight_std=1e-6, ): super().__init__() self.device = torch.device(device) self.dtype = dtype raw = mace_mp( model=foundation, return_raw_model=True, device=str(self.device), default_dtype="float32", ) self.mace_model = raw.float().to(device=self.device) self.readout = _build_readout_head(readout_hidden, readout_layers, self.device, dtype) init_readout_last_linear_small(self.readout, weight_std=last_layer_weight_std) zs = [int(z) for z in self.mace_model.atomic_numbers.detach().cpu().tolist()] self.z_table = AtomicNumberTable(sorted(zs)) self.r_max = float(r_max if r_max is not None else getattr(self.mace_model, "r_max", 6.0)) self.to(self.device) def forward_atomic_batch(self, batch): batch = batch.to(self.device) batch.positions = batch.positions.float() batch.node_attrs = batch.node_attrs.float() batch.shifts = batch.shifts.float() batch.cell = batch.cell.float() out = self.mace_model(batch.to_dict(), compute_force=False, training=self.training) e = out["energy"].reshape(-1, 1) return self.readout(e).reshape(-1) def _atomic_data_from_stored(mol, z_table, r_max): atoms = Atoms(symbols=mol["elements"], positions=np.asarray(mol["coords"], dtype=np.float32)) atoms.set_pbc([False, False, False]) atoms.set_cell(np.eye(3, dtype=np.float32) * 100.0) config = mace_data.config_from_atoms(atoms) return mace_data.AtomicData.from_config(config, z_table=z_table, cutoff=r_max) def forward_reaction_batch_delta_b3lyp_skala(reactions, molecules, model, r_max, device, dtype): all_mol_ids, rxn_indices, coeffs, ref_h = [], [], [], [] for ir, rxn in enumerate(reactions): ref_h.append(torch.as_tensor(rxn["energy_kcal"] / HARTREE2KCAL, dtype=dtype, device=device)) for item in rxn["mols"]: all_mol_ids.append(item["mol_id"]) rxn_indices.append(ir) coeffs.append(float(item["coeff"])) n_rxn = len(reactions) if not all_mol_ids: pred_h = torch.zeros(n_rxn, dtype=dtype, device=device) return pred_h, torch.stack(ref_h) if ref_h else torch.zeros(0, dtype=dtype, device=device) atomic_list = [_atomic_data_from_stored(molecules[mid], model.z_table, r_max) for mid in all_mol_ids] loader = torch_geometric.dataloader.DataLoader( dataset=atomic_list, batch_size=len(atomic_list), shuffle=False, drop_last=False ) batch = next(iter(loader)).to(device) batch.positions = batch.positions.to(dtype) batch.node_attrs = batch.node_attrs.to(dtype) batch.shifts = batch.shifts.to(dtype) batch.cell = batch.cell.to(dtype) delta = model.forward_atomic_batch(batch) # E_base = E_unxc + E_xc_b3lyp + d3bj - 0.2*hf_x (hf_x stored positive) const_e = torch.as_tensor( [ float(molecules[mid]["E_unxc"]) + float(molecules[mid]["E_xc_b3lyp"]) - 0.2 * float(molecules[mid]["hf_x"]) + float(molecules[mid]["d3bj_b3lyp"]) for mid in all_mol_ids ], dtype=dtype, device=device, ) e_mols = const_e + delta rxn_indices_t = torch.as_tensor(rxn_indices, dtype=torch.long, device=device) coeffs_t = torch.as_tensor(coeffs, dtype=dtype, device=device) pred_h = torch.zeros(n_rxn, dtype=dtype, device=device) pred_h.index_add_(0, rxn_indices_t, coeffs_t * e_mols) return pred_h, torch.stack(ref_h)