anonymous commited on
Commit
a1225ae
·
1 Parent(s): ce9b7f3

uploaded upet

Browse files
models/equiformerv2/equiformer_v2/datasets/custom_data.py CHANGED
@@ -41,7 +41,7 @@ class LargeDFTDataset(Dataset):
41
  self.normalize = normalize
42
 
43
  # dset_root = Environment.dset_path
44
- dset_root = Path("/home/x_pavme/experiments/dft-training/catalyst/tetrasphere/tetrasphere/datasets/CO2_Ti2C-MXene")
45
  # split_name = f"{partition}"
46
  # file_name = dset_root / "" / (split_name + ".npy")
47
 
 
41
  self.normalize = normalize
42
 
43
  # dset_root = Environment.dset_path
44
+ dset_root = Path("")
45
  # split_name = f"{partition}"
46
  # file_name = dset_root / "" / (split_name + ".npy")
47
 
models/upet/upet/.DS_Store ADDED
Binary file (6.15 kB). View file
 
models/upet/upet/README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Install the requirements:
2
+
3
+ ` pip install upet `
4
+
5
+ To evaluate the models, run
6
+
7
+ for UPET cons. 2.9M
8
+ ```
9
+ python eval_upet_pt.py \
10
+ --xyz ../../datasets/xyz/testdata.xyz \
11
+ --pt-path runs/seed42_upet_perstr_300ep_bs8_1e-4_lf5.pt \
12
+ --forces-key forces \
13
+ --progress
14
+ ```
15
+
16
+ for UPET non-cons. 3.0M
17
+ ```
18
+ python eval_upet_noncon_mtt.py \
19
+ --xyz ../../datasets/xyz/testdata.xyz \
20
+ --pt-path runs/seed42_upet_noncon_300ep_bs8_1e-4_lf5.pt \
21
+ --forces-key forces
22
+ ```
23
+
24
+ for PET pretrained mad-s 25.9M
25
+ ```
26
+ python eval_upet_pt.py \
27
+ --xyz ../../datasets/xyz/testdata.xyz \
28
+ --pt-path runs/seed42_pet-mad-s_perstr_100ep_bs8_1e-4_lf5.pt \
29
+ --forces-key forces \
30
+ --progress
31
+ ```
models/upet/upet/eval_upet_noncon_mtt.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Evaluate a *non-conservative* UPET metatrain-exported model.pt using `mtt eval`.
4
+
5
+ For example:
6
+
7
+ python eval_upet_noncon_mtt.py \
8
+ --xyz ../../datasets/xyz/testdata.xyz \
9
+ --pt-path runs/seed42_upet_noncon_300ep_bs8_1e-4_lf5.pt \
10
+ --forces-key forces
11
+
12
+ """
13
+
14
+ from __future__ import annotations
15
+ import argparse
16
+ import os
17
+ import subprocess
18
+ from pathlib import Path
19
+ import yaml
20
+
21
+
22
+ def run(cmd: list[str], cwd: str | None = None, env: dict | None = None) -> None:
23
+ env2 = dict(os.environ)
24
+ if env:
25
+ env2.update(env)
26
+ print("\n$ " + " ".join(cmd))
27
+ subprocess.run(cmd, cwd=cwd, env=env2, check=True)
28
+
29
+
30
+ def abs_path(p: str) -> str:
31
+ return str(Path(p).expanduser().resolve())
32
+
33
+
34
+ def write_eval_yaml(
35
+ path: Path,
36
+ *,
37
+ xyz_path: str,
38
+ length_unit: str,
39
+ energy_key: str,
40
+ energy_unit: str,
41
+ force_key: str,
42
+ force_unit: str,
43
+ ) -> None:
44
+ cfg = {
45
+ "systems": {"read_from": xyz_path, "length_unit": length_unit},
46
+ "targets": {
47
+ "energy": {"key": energy_key, "unit": energy_unit, "forces": "off"},
48
+ "non_conservative_forces": {
49
+ "key": force_key,
50
+ "quantity": "force",
51
+ "unit": force_unit,
52
+ "type": {"cartesian": {"rank": 1}},
53
+ "per_atom": True,
54
+ },
55
+ },
56
+ }
57
+ path.write_text(yaml.safe_dump(cfg, sort_keys=False))
58
+
59
+
60
+ def main():
61
+ ap = argparse.ArgumentParser(description="Evaluate non-conservative UPET/PET model.pt with mtt eval.")
62
+ ap.add_argument("--pt-path", required=True, help="Path to metatrain exported model.pt")
63
+ ap.add_argument("--xyz", required=True, help="Path to xyz/extxyz dataset with labels")
64
+
65
+ ap.add_argument("--energy-key", default="energy", help="Energy label key in xyz headers (atoms.info)")
66
+ ap.add_argument("--energy-unit", default="eV")
67
+ ap.add_argument("--forces-key", default="forces", help="Direct-force label key in xyz arrays (atoms.arrays)")
68
+ ap.add_argument("--force-unit", default="eV/angstrom", help="Force unit string for metatrain")
69
+
70
+ ap.add_argument("--length-unit", default="angstrom", choices=["angstrom", "Angstrom"])
71
+ ap.add_argument("--batch-size", type=int, default=8)
72
+ ap.add_argument("--out-xyz", default=None, help="Optional output xyz path to write predictions (mtt eval -o)")
73
+ ap.add_argument("--extensions", default=None, help="Optional extensions/ folder (mtt eval -e)")
74
+ ap.add_argument("--work-dir", default="mtt_eval_noncon", help="Directory to run in (contains eval.yaml + outputs/)")
75
+
76
+ ap.add_argument("--no-wandb", action="store_true", help="Disable wandb (sets WANDB_MODE=disabled)")
77
+ args = ap.parse_args()
78
+
79
+ work = Path(args.work_dir).expanduser().resolve()
80
+ work.mkdir(parents=True, exist_ok=True)
81
+
82
+ eval_yaml = work / "eval_noncon.yaml"
83
+ write_eval_yaml(
84
+ eval_yaml,
85
+ xyz_path=abs_path(args.xyz),
86
+ length_unit=args.length_unit,
87
+ energy_key=args.energy_key,
88
+ energy_unit=args.energy_unit,
89
+ force_key=args.forces_key,
90
+ force_unit=args.force_unit,
91
+ )
92
+
93
+ env = {}
94
+ if args.no_wandb:
95
+ env["WANDB_MODE"] = "disabled"
96
+ env["WANDB_SILENT"] = "true"
97
+
98
+ cmd = ["mtt", "eval", abs_path(args.pt_path), str(eval_yaml)]
99
+ cmd += ["-b", str(args.batch_size)]
100
+ if args.extensions:
101
+ cmd += ["-e", abs_path(args.extensions)]
102
+ if args.out_xyz:
103
+ cmd += ["-o", abs_path(args.out_xyz)]
104
+
105
+ run(cmd, cwd=str(work), env=env)
106
+ print("\nDone. metatrain wrote logs under:", str(work / "outputs"))
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()
models/upet/upet/eval_upet_pt.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ python eval_upet_pt.py \
4
+ --xyz ../../datasets/xyz/testdata.xyz \
5
+ --pt-path runs/seed42_upet_perstr_300ep_bs8_1e-4_lf5.pt \
6
+ --forces-key forces \
7
+ --progress
8
+
9
+ python eval_upet_pt.py \
10
+ --xyz ../../datasets/xyz/testdata.xyz \
11
+ --pt-path runs/seed42_pet-mad-s_perstr_100ep_bs8_1e-4_lf5.pt \
12
+ --forces-key forces \
13
+ --progress
14
+
15
+ """
16
+
17
+ from __future__ import annotations
18
+ import argparse
19
+ from pathlib import Path
20
+ import math
21
+ import numpy as np
22
+ import torch
23
+ from tqdm import tqdm
24
+ from ase.io import read
25
+ from ase.atoms import Atoms
26
+
27
+
28
+ def get_ref_energy(a: Atoms) -> float:
29
+ # Prefer calculator energy if present
30
+ if getattr(a, "calc", None) is not None:
31
+ try:
32
+ return float(a.get_potential_energy())
33
+ except Exception:
34
+ pass
35
+ # Fall back to common info keys
36
+ for k in ("energy", "energy_per_structure", "energy_total", "free_energy", "E", "Energy"):
37
+ if k in getattr(a, "info", {}):
38
+ return float(a.info[k])
39
+ raise KeyError("No reference energy found (no calculator energy and no known info key).")
40
+
41
+
42
+ def get_ref_forces(a: Atoms, forces_key: str) -> np.ndarray:
43
+ if forces_key in getattr(a, "arrays", {}):
44
+ return np.asarray(a.arrays[forces_key], dtype=float)
45
+ if "forces" in getattr(a, "arrays", {}):
46
+ return np.asarray(a.arrays["forces"], dtype=float)
47
+ # calculator fallback
48
+ if getattr(a, "calc", None) is not None:
49
+ try:
50
+ return np.asarray(a.get_forces(), dtype=float)
51
+ except Exception:
52
+ pass
53
+ raise KeyError(f"No reference forces found (arrays missing '{forces_key}'/'forces' and no calc forces).")
54
+
55
+
56
+ def compute_metrics(records):
57
+ # records: list of dict with dE (float), natoms (int), dF (np array Nx3)
58
+ total_force_components = 0.0
59
+ total_systems = 0.0
60
+ total_atoms = 0.0
61
+
62
+ sum_abs_dF = 0.0
63
+ sum_sq_dF = 0.0
64
+
65
+ sum_abs_dE = 0.0
66
+ sum_sq_dE = 0.0
67
+
68
+ sum_abs_dE_per_atom = 0.0
69
+ sum_sq_dE_per_atom = 0.0
70
+
71
+ for r in records:
72
+ n = float(r["natoms"])
73
+ total_systems += 1.0
74
+ total_atoms += n
75
+ total_force_components += 3.0 * n
76
+
77
+ dE = float(r["dE"])
78
+ abs_dE = abs(dE)
79
+ sum_abs_dE += abs_dE
80
+ sum_sq_dE += dE * dE
81
+
82
+ dE_pa = dE / n
83
+ sum_abs_dE_per_atom += abs(dE_pa)
84
+ sum_sq_dE_per_atom += dE_pa * dE_pa
85
+
86
+ dF = r["dF"].reshape(-1) # 3N
87
+ sum_abs_dF += float(np.abs(dF).sum())
88
+ sum_sq_dF += float((dF * dF).sum())
89
+
90
+ mae_F = sum_abs_dF / total_force_components if total_force_components > 0 else float("nan")
91
+ rmse_F = math.sqrt(sum_sq_dF / total_force_components) if total_force_components > 0 else float("nan")
92
+
93
+ mae_E_sys = sum_abs_dE / total_systems if total_systems > 0 else float("nan")
94
+ rmse_E_sys = math.sqrt(sum_sq_dE / total_systems) if total_systems > 0 else float("nan")
95
+
96
+ mae_E_atom_weighted = sum_abs_dE / total_atoms if total_atoms > 0 else float("nan")
97
+ rmse_E_atom_weighted = math.sqrt(sum_sq_dE / total_atoms) if total_atoms > 0 else float("nan")
98
+
99
+ # standard metric: average over systems of |dE|/N, RMSE over systems of (dE/N)
100
+ mae_E_atom_mace = sum_abs_dE_per_atom / total_systems if total_systems > 0 else float("nan")
101
+ rmse_E_atom_mace = math.sqrt(sum_sq_dE_per_atom / total_systems) if total_systems > 0 else float("nan")
102
+
103
+ return {
104
+ "MAE(F components)": mae_F,
105
+ "MAE(E per system)": mae_E_sys,
106
+ "MAE(E per atom, weighted)": mae_E_atom_weighted,
107
+ "MAE(E per atom)": mae_E_atom_mace,
108
+ "RMSE(F components)": rmse_F,
109
+ "RMSE(E per system)": rmse_E_sys,
110
+ "RMSE(E per atom, weighted)": rmse_E_atom_weighted,
111
+ "RMSE(E per atom)": rmse_E_atom_mace,
112
+ }
113
+
114
+
115
+ def main():
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--xyz", required=True, help="Path to extxyz dataset")
118
+ ap.add_argument("--pt-path", required=True, help="Path to metatrain exported model.pt")
119
+ ap.add_argument("--forces-key", default="forces_mt", help="Reference forces key in ASE arrays (default: forces_mt)")
120
+ ap.add_argument("--index", default=":", help="ASE index selector (default ':')")
121
+ ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
122
+ ap.add_argument("--batch-size", type=int, default=1, help="Kept for CLI compatibility; evaluation is per-structure.")
123
+ ap.add_argument("--progress", action="store_true", help="Show tqdm progress bar")
124
+ args = ap.parse_args()
125
+
126
+ # Import MetatomicCalculator lazily for clearer error messages
127
+ try:
128
+ from metatomic.torch.ase_calculator import MetatomicCalculator
129
+ except Exception as e:
130
+ raise SystemExit(
131
+ "Could not import MetatomicCalculator. Ensure metatomic/metatensor is installed in this env.\n"
132
+ f"Original import error: {e}"
133
+ )
134
+
135
+ calc = MetatomicCalculator(model=args.pt_path, device=args.device)
136
+
137
+ atoms_list = read(args.xyz, index=args.index)
138
+ if isinstance(atoms_list, Atoms):
139
+ atoms_list = [atoms_list]
140
+
141
+ total = len(atoms_list)
142
+ records = []
143
+
144
+ it = atoms_list
145
+ if args.progress:
146
+ it = tqdm(atoms_list, desc="Eval (UPET local .pt)", dynamic_ncols=True)
147
+
148
+ for i, atoms in enumerate(it):
149
+ nat = len(atoms)
150
+ ref_E = get_ref_energy(atoms)
151
+ ref_F = get_ref_forces(atoms, args.forces_key)
152
+
153
+ # Predict
154
+ a = atoms.copy()
155
+ a.calc = calc
156
+ pred_E = float(a.get_potential_energy())
157
+ pred_F = np.asarray(a.get_forces(), dtype=float)
158
+
159
+ if pred_F.shape != ref_F.shape:
160
+ raise ValueError(f"Force shape mismatch pred {pred_F.shape} vs ref {ref_F.shape}")
161
+
162
+ dE = pred_E - ref_E
163
+ dF = pred_F - ref_F
164
+
165
+ records.append({"dE": dE, "dF": dF, "natoms": nat})
166
+
167
+ metrics = compute_metrics(records)
168
+
169
+ print(f"Total systems in file:\t\t{total}")
170
+ print(f"Evaluated systems:\t\t{len(records)}")
171
+
172
+ for k, v in metrics.items():
173
+ print(f"{k:28s} {v:.6f}")
174
+
175
+ if __name__ == "__main__":
176
+ main()
models/upet/upet/runs/seed42_pet-mad-s_perstr_100ep_bs8_1e-4_lf5.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de68285099c86b5fb6597272fba4a51c52de7b063a62bb51d63181482f2b24c6
3
+ size 104103775
models/upet/upet/runs/seed42_upet_noncon_300ep_bs8_1e-4_lf5.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:540dd475c5af06d60ffeeed8f4283d73aa6416199995073b76e21113a1b832cd
3
+ size 12238673
models/upet/upet/runs/seed42_upet_perstr_300ep_bs8_1e-4_lf5.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1a4efeb218cc2a5627988b4d01581c260e6ff447e1ef502028eb1bc52750b9c
3
+ size 11890135