# For two gpus run: torchrun --standalone --nproc_per_node=2 testing_equiformer.py import os import sys ROOT = os.path.dirname(os.path.abspath(__file__)) # path to experiments/ ROOT = os.path.abspath(os.path.join(ROOT, ".")) # repo root sys.path.insert(0, ROOT) # so local packages import sys.path.insert(0, os.path.join(ROOT, "equiformer_v2/ocp")) # so 'ocpmodels' resolves import argparse from datetime import datetime from types import SimpleNamespace from pathlib import Path import numpy as np import torch import torch.nn.functional as F import torch.distributed as dist from torch import nn from torch.utils.data import DataLoader, DistributedSampler from torch.nn.parallel import DistributedDataParallel as DDP from pytorch_lightning import seed_everything from tqdm.auto import tqdm from equiformer_v2.nets.equiformer_v2.equiformer_v2_oc20 import EquiformerV2_OC20 as EquiformerV2 from utils import * from model_configs import * # --------------------- DDP / torchrun compatibility ------------------- p = argparse.ArgumentParser(add_help=True) # DDP args (you already had these) p.add_argument("--local_rank", type=int, default=None) # old style p.add_argument("--local-rank", dest="local_rank_dash", type=int, default=None) # torchrun sometimes passes this # ------------------------- NEW: training/config args ------------------------- p.add_argument( "--data_path", type=str, default="YOUR PATH", help="test set root", ) p.add_argument( "--model", choices=["small", "orig"], default="orig", help="Select model config", ) p.add_argument("--seed", type=int, default = 1996, help="set the seed" ) p.add_argument("--ckpt", type=str, required=True, help="Path to checkpoint pth") args, _ = p.parse_known_args() def load_equiformer_weights(path, model): ckpt = torch.load(path, map_location="cpu") state_dict = ckpt["state_dict"] # <-- confirmed key from inspection # remove double "module.module." prefix new_state = OrderedDict() for k, v in state_dict.items(): if k.startswith("module.module."): new_state[k[len("module.module."):]] = v elif k.startswith("module."): new_state[k[len("module."):]] = v else: new_state[k] = v missing, unexpected = model.load_state_dict(new_state, strict=False) print(f"[ckpt] load strict=False | missing={len(missing)} unexpected={len(unexpected)}") if missing and len(missing) < 12: print("Missing keys:", missing) if unexpected and len(unexpected) < 12: print("Unexpected keys:", unexpected) return model #------------------------------------------------ # Check that combination of args is allowed #validate_args(args) LOCAL_RANK = ( args.local_rank if args.local_rank is not None else (args.local_rank_dash if args.local_rank_dash is not None else int(os.environ.get("LOCAL_RANK", 0))) ) WORLD_SIZE = int(os.environ.get("WORLD_SIZE", "1")) if WORLD_SIZE > 1: dist.init_process_group(backend="nccl") if torch.cuda.is_available(): torch.cuda.set_device(LOCAL_RANK) device = torch.device(f"cuda:{LOCAL_RANK}" if torch.cuda.is_available() else "cpu") is_dist = (WORLD_SIZE > 1) and dist.is_initialized() is_main = (not is_dist) or (dist.get_rank() == 0) if is_main: print("\nCONFIG:") print("-----------------------------------------------------------------------------------------------") print( f"[cfg] ckpt={args.ckpt}, model={args.model}, seed={args.seed}," ) print("-----------------------------------------------------------------------------------------------\n") print(f"[init] torch={torch.__version__} world_size={WORLD_SIZE} local_rank={LOCAL_RANK} device={device}\n") seed_everything(args.seed, workers=True) if torch.cuda.is_available(): torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # ------------------------------- Data --------------------------------- data_path = Path(args.data_path) test_dataset = DFTDatasetH5(data_path) # NOTE Sanity check for running validation #test_dataset = DFTDatasetH5(data_root, split="val") #print("TESTING ON VALIDATION") _model_map = { "small": model_config_small, "orig": model_config_orig, } model_config_to_use = _model_map[args.model] model_config_to_use = {**model_config_to_use, "avg_num_nodes": 86.7569, "avg_degree": 18.6488219106676} # Statistics based on the dataset # if args.select_test_dataset == "with_rep": # model_config_to_use = {**model_config_to_use, "avg_num_nodes": 520.46036, "avg_degree": 18.6495819106676} # elif args.select_test_dataset == "without_rep": # model_config_to_use = {**model_config_to_use, "avg_num_nodes": 86.7569, "avg_degree": 18.6488219106676} # Samplers conditional on DDP if is_dist: test_sampler = DistributedSampler(test_dataset, shuffle=True) else: test_sampler = None pin_memory = torch.cuda.is_available() test_loader = DataLoader( test_dataset, batch_size = 1, # NOTE Change to one if your GPU cannot handle sampler=test_sampler, shuffle=False, collate_fn=custom_collate_fn, num_workers=16, pin_memory=pin_memory ) if is_main: print(f"\n\nDataset size: test: {len(test_dataset)}") # ------------------------------ Model --------------------------------- model = EquiformerV2(None, None, None, **model_config_to_use).to(device) model, _, best_epoch, best_val_metric = load_checkpoint(args.ckpt, model) if is_main: print(f"Loaded model at epoch: {best_epoch} with best val metric being: {best_val_metric}") count_parameters(model) if is_dist: model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK, find_unused_parameters=False) def evaluate(model, test_loader, L1_critertion, L2_critertion): model.eval() # Global sums (MAE-style) sum_abs_dF = torch.tensor(0.0, device=device) # Σ |ΔF| over all components sum_abs_dE = torch.tensor(0.0, device=device) # Σ |ΔE| over all systems # Global sums (RMSE-style) sum_sq_dF = torch.tensor(0.0, device=device) # Σ (ΔF)^2 over all components sum_sq_dE = torch.tensor(0.0, device=device) # Σ (ΔE)^2 over all systems # NEW: per-system normalized E/atom (MACE-style) sum_abs_dE_per_atom = torch.tensor(0.0, device=device) # Σ_i |ΔE_i|/N_i sum_sq_dE_per_atom = torch.tensor(0.0, device=device) # Σ_i (ΔE_i/N_i)^2 # Denominators total_force_components = torch.tensor(0.0, device=device) # Σ (3 * natoms) total_systems = torch.tensor(0.0, device=device) # Σ n_systems total_atoms = torch.tensor(0.0, device=device) # Σ natoms (atom-weighted) with torch.no_grad(): tbar = tqdm(test_loader, disable=not is_main, dynamic_ncols=True, desc="Testing") for data in tbar: data = {k: v.to(device, non_blocking=True) for k, v in data.items()} data = SimpleNamespace(**data) # Forward pred_energy, pred_forces = model(data) # shapes pe = pred_energy.view(-1) # [n_systems] te = data.energy.view(-1) # [n_systems] # Loss sums (because reduction="sum") L1_loss_forces = L1_critertion(pred_forces, data.forces) # Σ |ΔF| over components L1_loss_energy = L1_critertion(pe, te) # Σ |ΔE| over systems L2_loss_forces = L2_critertion(pred_forces, data.forces) # Σ (ΔF)^2 over components L2_loss_energy = L2_critertion(pe, te) # Σ (ΔE)^2 over systems # Denominators natoms_per_system = data.natoms.view(-1).to(torch.float32) # [n_systems] n_systems = natoms_per_system.numel() natoms_batch = natoms_per_system.sum() total_atoms += natoms_batch total_force_components += 3.0 * natoms_batch total_systems += float(n_systems) # Accumulate global sums sum_abs_dF += L1_loss_forces sum_abs_dE += L1_loss_energy sum_sq_dF += L2_loss_forces sum_sq_dE += L2_loss_energy # NEW: MACE-style per-system E/atom dE = pe - te # [n_systems] sum_abs_dE_per_atom += (dE.abs() / natoms_per_system).sum() sum_sq_dE_per_atom += ((dE / natoms_per_system) ** 2).sum() # DDP reduction (keep exactly like before, plus the two new tensors) if is_dist: for t in [ sum_abs_dF, sum_abs_dE, sum_sq_dF, sum_sq_dE, sum_abs_dE_per_atom, sum_sq_dE_per_atom, total_force_components, total_systems, total_atoms ]: dist.all_reduce(t, op=dist.ReduceOp.SUM) # --- Final metrics --- mae_F = (sum_abs_dF / total_force_components).item() mae_E_sys = (sum_abs_dE / total_systems).item() # Existing "E per atom" in your script (atom-weighted) mae_E_atom_weighted = (sum_abs_dE / total_atoms).item() # NEW: MACE-style (average over systems of |ΔE|/N) mae_E_atom_mace = (sum_abs_dE_per_atom / total_systems).item() rmse_F = torch.sqrt(sum_sq_dF / total_force_components).item() rmse_E_sys = torch.sqrt(sum_sq_dE / total_systems).item() # Existing atom-weighted RMSE analogue rmse_E_atom_weighted = torch.sqrt(sum_sq_dE / total_atoms).item() # NEW: MACE-style per-system-per-atom RMSE rmse_E_atom_mace = torch.sqrt(sum_sq_dE_per_atom / total_systems).item() if is_main: print(f"MAE(F components): {mae_F:.6f}") print(f"MAE(E per system): {mae_E_sys:.6f}") print(f"MAE(E per atom, weighted): {mae_E_atom_weighted:.6f}") print(f"MAE(E per atom, MACE): {mae_E_atom_mace:.6f}") print(f"RMSE(F components): {rmse_F:.6f}") print(f"RMSE(E per system): {rmse_E_sys:.6f}") print(f"RMSE(E per atom, weighted): {rmse_E_atom_weighted:.6f}") print(f"RMSE(E per atom, MACE): {rmse_E_atom_mace:.6f}") return { "MAE(F components)": mae_F, "MAE(E per system)": mae_E_sys, "MAE(E per atom, weighted)": mae_E_atom_weighted, "MAE(E per atom, MACE)": mae_E_atom_mace, "RMSE(F components)": rmse_F, "RMSE(E per system)": rmse_E_sys, "RMSE(E per atom, weighted)": rmse_E_atom_weighted, "RMSE(E per atom, MACE)": rmse_E_atom_mace, } L1_critertion = nn.L1Loss(reduction="sum") L2_critertion = nn.MSELoss(reduction="sum") if __name__ == "__main__": evaluate(model, test_loader, L1_critertion, L2_critertion) # Cleanup DDP if is_dist: dist.destroy_process_group()