anonymous commited on
Commit ·
b177675
1
Parent(s): 9042866
Upload starting point for mace
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- models/mace/README.md +5 -0
- models/mace/mace/__init__.py +5 -0
- models/mace/mace/__pycache__/__init__.cpython-310.pyc +0 -0
- models/mace/mace/__pycache__/__version__.cpython-310.pyc +0 -0
- models/mace/mace/__version__.py +3 -0
- models/mace/mace/calculators/__init__.py +11 -0
- models/mace/mace/calculators/__pycache__/__init__.cpython-310.pyc +0 -0
- models/mace/mace/calculators/__pycache__/foundations_models.cpython-310.pyc +0 -0
- models/mace/mace/calculators/__pycache__/lammps_mace.cpython-310.pyc +0 -0
- models/mace/mace/calculators/__pycache__/mace.cpython-310.pyc +0 -0
- models/mace/mace/calculators/foundations_models.py +445 -0
- models/mace/mace/calculators/foundations_models/2023-12-03-mace-mp.model +3 -0
- models/mace/mace/calculators/foundations_models/ani500k_large_CC.model +3 -0
- models/mace/mace/calculators/foundations_models/mace-mpa-0-medium.model +3 -0
- models/mace/mace/calculators/foundations_models/mp_vasp_e0.json +91 -0
- models/mace/mace/calculators/lammps_mace.py +105 -0
- models/mace/mace/calculators/lammps_mliap_mace.py +228 -0
- models/mace/mace/calculators/mace.py +620 -0
- models/mace/mace/cli/__init__.py +0 -0
- models/mace/mace/cli/__pycache__/__init__.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/convert_cueq_e3nn.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/convert_e3nn_cueq.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/convert_e3nn_oeq.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/convert_oeq_e3nn.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/eval_configs.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/fine_tuning_select.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/preprocess_data.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_calc.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_eval.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_eval_copy.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_eval_foundation.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_foundation.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_inference_speed.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_jonas_calc.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/run_train.cpython-310.pyc +0 -0
- models/mace/mace/cli/__pycache__/visualise_train.cpython-310.pyc +0 -0
- models/mace/mace/cli/active_learning_md.py +193 -0
- models/mace/mace/cli/convert_cueq_e3nn.py +259 -0
- models/mace/mace/cli/convert_device.py +31 -0
- models/mace/mace/cli/convert_e3nn_cueq.py +258 -0
- models/mace/mace/cli/convert_e3nn_oeq.py +89 -0
- models/mace/mace/cli/convert_oeq_e3nn.py +78 -0
- models/mace/mace/cli/create_lammps_model.py +114 -0
- models/mace/mace/cli/eval_configs.py +337 -0
- models/mace/mace/cli/fine_tuning_select.py +529 -0
- models/mace/mace/cli/our_files/__pycache__/run_calc.cpython-310.pyc +0 -0
- models/mace/mace/cli/our_files/__pycache__/run_eval.cpython-310.pyc +0 -0
- models/mace/mace/cli/our_files/__pycache__/run_eval_foundation.cpython-310.pyc +0 -0
- models/mace/mace/cli/our_files/__pycache__/run_eval_foundation_no_finetuning.cpython-310.pyc +0 -0
- models/mace/mace/cli/our_files/run_calc.py +34 -0
models/mace/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Introduction
|
| 2 |
+
|
| 3 |
+
Running the script can be found in mace/cli/run_train
|
| 4 |
+
|
| 5 |
+
you can run it from scripts/run_mace.sh. Just speicfy pathways
|
models/mace/mace/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from .__version__ import __version__
|
| 4 |
+
|
| 5 |
+
os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
|
models/mace/mace/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (288 Bytes). View file
|
|
|
models/mace/mace/__pycache__/__version__.cpython-310.pyc
ADDED
|
Binary file (224 Bytes). View file
|
|
|
models/mace/mace/__version__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.3.15"
|
| 2 |
+
|
| 3 |
+
__all__ = ["__version__"]
|
models/mace/mace/calculators/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .foundations_models import mace_anicc, mace_mp, mace_off, mace_omol
|
| 2 |
+
from .lammps_mace import LAMMPS_MACE
|
| 3 |
+
from .mace import MACECalculator
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"MACECalculator",
|
| 7 |
+
"LAMMPS_MACE",
|
| 8 |
+
"mace_mp",
|
| 9 |
+
"mace_off",
|
| 10 |
+
"mace_anicc",
|
| 11 |
+
]
|
models/mace/mace/calculators/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (435 Bytes). View file
|
|
|
models/mace/mace/calculators/__pycache__/foundations_models.cpython-310.pyc
ADDED
|
Binary file (15.9 kB). View file
|
|
|
models/mace/mace/calculators/__pycache__/lammps_mace.cpython-310.pyc
ADDED
|
Binary file (2.33 kB). View file
|
|
|
models/mace/mace/calculators/__pycache__/mace.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
models/mace/mace/calculators/foundations_models.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import urllib.request
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, Literal, Optional, Union, overload
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from ase import units
|
| 8 |
+
from ase.calculators.mixing import SumCalculator
|
| 9 |
+
|
| 10 |
+
from mace.tools.utils import get_cache_dir
|
| 11 |
+
|
| 12 |
+
from .mace import MACECalculator
|
| 13 |
+
|
| 14 |
+
module_dir = os.path.dirname(__file__)
|
| 15 |
+
local_model_path = os.path.join(
|
| 16 |
+
module_dir, "foundations_models/mace-mpa-0-medium.model"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
mace_mp_urls = {
|
| 20 |
+
"small": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/2023-12-10-mace-128-L0_energy_epoch-249.model",
|
| 21 |
+
"medium": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/2023-12-03-mace-128-L1_epoch-199.model",
|
| 22 |
+
"large": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/MACE_MPtrj_2022.9.model",
|
| 23 |
+
"small-0b": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b/mace_agnesi_small.model",
|
| 24 |
+
"medium-0b": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b/mace_agnesi_medium.model",
|
| 25 |
+
"small-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-small-density-agnesi-stress.model",
|
| 26 |
+
"medium-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-medium-density-agnesi-stress.model",
|
| 27 |
+
"large-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-large-density-agnesi-stress.model",
|
| 28 |
+
"medium-0b3": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b3/mace-mp-0b3-medium.model",
|
| 29 |
+
"medium-mpa-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mpa_0/mace-mpa-0-medium.model",
|
| 30 |
+
"small-omat-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_omat_0/mace-omat-0-small.model",
|
| 31 |
+
"medium-omat-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_omat_0/mace-omat-0-medium.model",
|
| 32 |
+
"mace-matpes-pbe-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/MACE-matpes-pbe-omat-ft.model",
|
| 33 |
+
"mace-matpes-r2scan-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/MACE-matpes-r2scan-omat-ft.model",
|
| 34 |
+
"mh-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mh_1/mace-mh-0.model",
|
| 35 |
+
"mh-1": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mh_1/mace-mh-1.model",
|
| 36 |
+
}
|
| 37 |
+
mace_mp_names = [None] + list(mace_mp_urls.keys())
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def download_mace_mp_checkpoint(model: Optional[Union[str, Path]] = None) -> str:
|
| 41 |
+
"""
|
| 42 |
+
Downloads or locates the MACE-MP checkpoint file.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
model (str, optional): Path to the model or size specification.
|
| 46 |
+
Defaults to None which uses the medium model.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
str: Path to the downloaded (or cached, if previously loaded) checkpoint file.
|
| 50 |
+
"""
|
| 51 |
+
if model in (None, "medium-mpa-0") and os.path.isfile(local_model_path):
|
| 52 |
+
return local_model_path
|
| 53 |
+
|
| 54 |
+
checkpoint_url = (
|
| 55 |
+
mace_mp_urls.get(model, mace_mp_urls["medium-mpa-0"])
|
| 56 |
+
if model in mace_mp_names
|
| 57 |
+
else model
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
if checkpoint_url == mace_mp_urls["medium-mpa-0"]:
|
| 61 |
+
print(
|
| 62 |
+
"Using medium MPA-0 model as default MACE-MP model, to use previous (before 3.10) default model please specify 'medium' as model argument"
|
| 63 |
+
)
|
| 64 |
+
ASL_checkpoint_urls = {
|
| 65 |
+
mace_mp_urls["small-omat-0"],
|
| 66 |
+
mace_mp_urls["medium-omat-0"],
|
| 67 |
+
mace_mp_urls["mace-matpes-pbe-0"],
|
| 68 |
+
mace_mp_urls["mace-matpes-r2scan-0"],
|
| 69 |
+
}
|
| 70 |
+
if checkpoint_url in ASL_checkpoint_urls:
|
| 71 |
+
print(
|
| 72 |
+
"Using model under Academic Software License (ASL) license, see https://github.com/gabor1/ASL \n To use this model you accept the terms of the license."
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
cache_dir = get_cache_dir()
|
| 76 |
+
checkpoint_url_name = "".join(
|
| 77 |
+
c for c in os.path.basename(checkpoint_url) if c.isalnum() or c in "_"
|
| 78 |
+
)
|
| 79 |
+
cached_model_path = f"{cache_dir}/{checkpoint_url_name}"
|
| 80 |
+
|
| 81 |
+
if not os.path.isfile(cached_model_path):
|
| 82 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 83 |
+
print(f"Downloading MACE model from {checkpoint_url!r}")
|
| 84 |
+
_, http_msg = urllib.request.urlretrieve(checkpoint_url, cached_model_path)
|
| 85 |
+
if "Content-Type: text/html" in http_msg:
|
| 86 |
+
raise RuntimeError(
|
| 87 |
+
f"Model download failed, please check the URL {checkpoint_url}"
|
| 88 |
+
)
|
| 89 |
+
print(f"Cached MACE model to {cached_model_path}")
|
| 90 |
+
|
| 91 |
+
return cached_model_path
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@overload
|
| 95 |
+
def mace_mp(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ...
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@overload
|
| 99 |
+
def mace_mp(
|
| 100 |
+
*, return_raw_model: Literal[False] = False, **kwargs: Any
|
| 101 |
+
) -> MACECalculator: ...
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def mace_mp(
|
| 105 |
+
model: Optional[Union[str, Path]] = None,
|
| 106 |
+
device: str = "",
|
| 107 |
+
default_dtype: str = "float32",
|
| 108 |
+
dispersion: bool = False,
|
| 109 |
+
damping: str = "bj", # choices: ["zero", "bj", "zerom", "bjm"]
|
| 110 |
+
dispersion_xc: str = "pbe",
|
| 111 |
+
dispersion_cutoff: float = 40.0 * units.Bohr,
|
| 112 |
+
return_raw_model: bool = False,
|
| 113 |
+
**kwargs,
|
| 114 |
+
) -> Union[MACECalculator, torch.nn.Module, SumCalculator]:
|
| 115 |
+
"""
|
| 116 |
+
Constructs a MACECalculator with a pretrained model based on the Materials Project (89 elements).
|
| 117 |
+
The model is released under the MIT license. See https://github.com/ACEsuit/mace-foundations for all models.
|
| 118 |
+
Note:
|
| 119 |
+
If you are using this function, please cite the relevant paper for the Materials Project,
|
| 120 |
+
any paper associated with the MACE model, and also the following:
|
| 121 |
+
- MACE-MP by Ilyes Batatia, Philipp Benner, Yuan Chiang, Alin M. Elena,
|
| 122 |
+
Dávid P. Kovács, Janosh Riebesell, et al., 2023, arXiv:2401.00096
|
| 123 |
+
- MACE-Universal by Yuan Chiang, 2023, Hugging Face, Revision e5ebd9b,
|
| 124 |
+
DOI: 10.57967/hf/1202, URL: https://huggingface.co/cyrusyc/mace-universal
|
| 125 |
+
- Matbench Discovery by Janosh Riebesell, Rhys EA Goodall, Philipp Benner, Yuan Chiang,
|
| 126 |
+
Alpha A Lee, Anubhav Jain, Kristin A Persson, 2023, arXiv:2308.14920
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
model (str, optional): Path to the model. Defaults to None which first checks for
|
| 130 |
+
a local model and then downloads the default model from figshare. Specify "small",
|
| 131 |
+
"medium" or "large" to download a smaller or larger model from figshare.
|
| 132 |
+
device (str, optional): Device to use for the model. Defaults to "cuda" if available.
|
| 133 |
+
default_dtype (str, optional): Default dtype for the model. Defaults to "float32".
|
| 134 |
+
dispersion (bool, optional): Whether to use D3 dispersion corrections. Defaults to False.
|
| 135 |
+
damping (str): The damping function associated with the D3 correction. Defaults to "bj" for D3(BJ).
|
| 136 |
+
dispersion_xc (str, optional): Exchange-correlation functional for D3 dispersion corrections.
|
| 137 |
+
dispersion_cutoff (float, optional): Cutoff radius in Bohr for D3 dispersion corrections.
|
| 138 |
+
return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False.
|
| 139 |
+
**kwargs: Passed to MACECalculator and TorchDFTD3Calculator.
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
MACECalculator: trained on the MPtrj dataset (unless model otherwise specified).
|
| 143 |
+
"""
|
| 144 |
+
try:
|
| 145 |
+
if model in mace_mp_names or str(model).startswith("https:"):
|
| 146 |
+
model_path = download_mace_mp_checkpoint(model)
|
| 147 |
+
print(f"Using Materials Project MACE for MACECalculator with {model_path}")
|
| 148 |
+
else:
|
| 149 |
+
if not Path(model).exists():
|
| 150 |
+
raise FileNotFoundError(f"{model} not found locally")
|
| 151 |
+
model_path = model
|
| 152 |
+
except Exception as exc:
|
| 153 |
+
raise RuntimeError("Model download failed and no local model found") from exc
|
| 154 |
+
|
| 155 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 156 |
+
if default_dtype == "float64":
|
| 157 |
+
print(
|
| 158 |
+
"Using float64 for MACECalculator, which is slower but more accurate. Recommended for geometry optimization."
|
| 159 |
+
)
|
| 160 |
+
if default_dtype == "float32":
|
| 161 |
+
print(
|
| 162 |
+
"Using float32 for MACECalculator, which is faster but less accurate. Recommended for MD. Use float64 for geometry optimization."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
if return_raw_model:
|
| 166 |
+
return torch.load(model_path, map_location=device)
|
| 167 |
+
|
| 168 |
+
mace_calc = MACECalculator(
|
| 169 |
+
model_paths=model_path, device=device, default_dtype=default_dtype, **kwargs
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if not dispersion:
|
| 173 |
+
return mace_calc
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
from torch_dftd.torch_dftd3_calculator import TorchDFTD3Calculator
|
| 177 |
+
except ImportError as exc:
|
| 178 |
+
raise RuntimeError(
|
| 179 |
+
"Please install torch-dftd to use dispersion corrections (see https://github.com/pfnet-research/torch-dftd)"
|
| 180 |
+
) from exc
|
| 181 |
+
|
| 182 |
+
print("Using TorchDFTD3Calculator for D3 dispersion corrections")
|
| 183 |
+
dtype = torch.float32 if default_dtype == "float32" else torch.float64
|
| 184 |
+
d3_calc = TorchDFTD3Calculator(
|
| 185 |
+
device=device,
|
| 186 |
+
damping=damping,
|
| 187 |
+
dtype=dtype,
|
| 188 |
+
xc=dispersion_xc,
|
| 189 |
+
cutoff=dispersion_cutoff,
|
| 190 |
+
**kwargs,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
return SumCalculator([mace_calc, d3_calc])
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@overload
|
| 197 |
+
def mace_off(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ...
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@overload
|
| 201 |
+
def mace_off(
|
| 202 |
+
*, return_raw_model: Literal[False] = False, **kwargs: Any
|
| 203 |
+
) -> MACECalculator: ...
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def mace_off(
|
| 207 |
+
model: Optional[Union[str, Path]] = None,
|
| 208 |
+
device: str = "",
|
| 209 |
+
default_dtype: str = "float64",
|
| 210 |
+
return_raw_model: bool = False,
|
| 211 |
+
**kwargs,
|
| 212 |
+
) -> Union[MACECalculator, torch.nn.Module]:
|
| 213 |
+
"""
|
| 214 |
+
Constructs a MACECalculator with a pretrained model based on the MACE-OFF23 models.
|
| 215 |
+
The model is released under the ASL license.
|
| 216 |
+
Note:
|
| 217 |
+
If you are using this function, please cite the relevant paper by Kovacs et.al., arXiv:2312.15211
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
model (str, optional): Path to the model. Defaults to None which first checks for
|
| 221 |
+
a local model and then downloads the default medium model from https://github.com/ACEsuit/mace-off.
|
| 222 |
+
Specify "small", "medium" or "large" to download a smaller or larger model.
|
| 223 |
+
device (str, optional): Device to use for the model. Defaults to "cuda".
|
| 224 |
+
default_dtype (str, optional): Default dtype for the model. Defaults to "float64".
|
| 225 |
+
return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False.
|
| 226 |
+
**kwargs: Passed to MACECalculator.
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
MACECalculator: trained on the MACE-OFF23 dataset
|
| 230 |
+
"""
|
| 231 |
+
try:
|
| 232 |
+
if model in (None, "small", "medium", "large") or str(model).startswith(
|
| 233 |
+
"https:"
|
| 234 |
+
):
|
| 235 |
+
urls = dict(
|
| 236 |
+
small="https://github.com/ACEsuit/mace-off/blob/main/mace_off23/MACE-OFF23_small.model?raw=true",
|
| 237 |
+
medium="https://github.com/ACEsuit/mace-off/raw/main/mace_off23/MACE-OFF23_medium.model?raw=true",
|
| 238 |
+
large="https://github.com/ACEsuit/mace-off/blob/main/mace_off23/MACE-OFF23_large.model?raw=true",
|
| 239 |
+
)
|
| 240 |
+
checkpoint_url = (
|
| 241 |
+
urls.get(model, urls["medium"])
|
| 242 |
+
if model in (None, "small", "medium", "large")
|
| 243 |
+
else model
|
| 244 |
+
)
|
| 245 |
+
cache_dir = get_cache_dir()
|
| 246 |
+
checkpoint_url_name = os.path.basename(checkpoint_url).split("?")[0]
|
| 247 |
+
cached_model_path = f"{cache_dir}/{checkpoint_url_name}"
|
| 248 |
+
if not os.path.isfile(cached_model_path):
|
| 249 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 250 |
+
# download and save to disk
|
| 251 |
+
print(f"Downloading MACE model from {checkpoint_url!r}")
|
| 252 |
+
print(
|
| 253 |
+
"The model is distributed under the Academic Software License (ASL) license, see https://github.com/gabor1/ASL \n To use the model you accept the terms of the license."
|
| 254 |
+
)
|
| 255 |
+
print(
|
| 256 |
+
"ASL is based on the Gnu Public License, but does not permit commercial use"
|
| 257 |
+
)
|
| 258 |
+
urllib.request.urlretrieve(checkpoint_url, cached_model_path)
|
| 259 |
+
print(f"Cached MACE model to {cached_model_path}")
|
| 260 |
+
model = cached_model_path
|
| 261 |
+
msg = f"Using MACE-OFF23 MODEL for MACECalculator with {model}"
|
| 262 |
+
print(msg)
|
| 263 |
+
else:
|
| 264 |
+
if not Path(model).exists():
|
| 265 |
+
raise FileNotFoundError(f"{model} not found locally")
|
| 266 |
+
except Exception as exc:
|
| 267 |
+
raise RuntimeError("Model download failed and no local model found") from exc
|
| 268 |
+
|
| 269 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 270 |
+
|
| 271 |
+
if return_raw_model:
|
| 272 |
+
return torch.load(model, map_location=device)
|
| 273 |
+
|
| 274 |
+
if default_dtype == "float64":
|
| 275 |
+
print(
|
| 276 |
+
"Using float64 for MACECalculator, which is slower but more accurate. Recommended for geometry optimization."
|
| 277 |
+
)
|
| 278 |
+
if default_dtype == "float32":
|
| 279 |
+
print(
|
| 280 |
+
"Using float32 for MACECalculator, which is faster but less accurate. Recommended for MD. Use float64 for geometry optimization."
|
| 281 |
+
)
|
| 282 |
+
mace_calc = MACECalculator(
|
| 283 |
+
model_paths=model, device=device, default_dtype=default_dtype, **kwargs
|
| 284 |
+
)
|
| 285 |
+
return mace_calc
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@overload
|
| 289 |
+
def mace_anicc(
|
| 290 |
+
*, return_raw_model: Literal[True], **kwargs: Any
|
| 291 |
+
) -> torch.nn.Module: ...
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@overload
|
| 295 |
+
def mace_anicc(
|
| 296 |
+
*, return_raw_model: Literal[False] = False, **kwargs: Any
|
| 297 |
+
) -> MACECalculator: ...
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def mace_anicc(
|
| 301 |
+
device: str = "cuda",
|
| 302 |
+
model_path: Optional[str] = None,
|
| 303 |
+
return_raw_model: bool = False,
|
| 304 |
+
) -> Union[MACECalculator, torch.nn.Module]:
|
| 305 |
+
"""
|
| 306 |
+
Constructs a MACECalculator with a pretrained model based on the ANI (H, C, N, O).
|
| 307 |
+
The model is released under the MIT license.
|
| 308 |
+
Note:
|
| 309 |
+
If you are using this function, please cite the relevant paper associated with the MACE model, ANI dataset, and also the following:
|
| 310 |
+
- "Evaluation of the MACE Force Field Architecture by Dávid Péter Kovács, Ilyes Batatia, Eszter Sára Arany, and Gábor Csányi, The Journal of Chemical Physics, 2023, URL: https://doi.org/10.1063/5.0155322
|
| 311 |
+
"""
|
| 312 |
+
if model_path is None:
|
| 313 |
+
model_path = os.path.join(
|
| 314 |
+
module_dir, "foundations_models/ani500k_large_CC.model"
|
| 315 |
+
)
|
| 316 |
+
print(
|
| 317 |
+
"Using ANI couple cluster model for MACECalculator, see https://doi.org/10.1063/5.0155322"
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
if not os.path.exists(model_path):
|
| 321 |
+
model_dir = os.path.dirname(model_path)
|
| 322 |
+
os.makedirs(model_dir, exist_ok=True)
|
| 323 |
+
|
| 324 |
+
# Download the model
|
| 325 |
+
print(f"Model not found at {model_path}. Downloading...")
|
| 326 |
+
model_url = "https://github.com/ACEsuit/mace/raw/main/mace/calculators/foundations_models/ani500k_large_CC.model"
|
| 327 |
+
|
| 328 |
+
try:
|
| 329 |
+
|
| 330 |
+
def report_progress(block_num, block_size, total_size):
|
| 331 |
+
downloaded = block_num * block_size
|
| 332 |
+
percent = min(100, downloaded * 100 / total_size)
|
| 333 |
+
if total_size > 0:
|
| 334 |
+
print(
|
| 335 |
+
f"\rDownloading model: {percent:.1f}% ({downloaded / 1024 / 1024:.1f} MB / {total_size / 1024 / 1024:.1f} MB)",
|
| 336 |
+
end="",
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
urllib.request.urlretrieve(
|
| 340 |
+
model_url, model_path, reporthook=report_progress
|
| 341 |
+
)
|
| 342 |
+
print("\nDownload complete!")
|
| 343 |
+
|
| 344 |
+
except Exception as e:
|
| 345 |
+
raise RuntimeError(f"Failed to download model: {e}") from e
|
| 346 |
+
|
| 347 |
+
if return_raw_model:
|
| 348 |
+
return torch.load(model_path, map_location=device)
|
| 349 |
+
return MACECalculator(
|
| 350 |
+
model_paths=model_path, device=device, default_dtype="float64"
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@overload
|
| 355 |
+
def mace_omol(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ...
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@overload
|
| 359 |
+
def mace_omol(
|
| 360 |
+
*, return_raw_model: Literal[False] = False, **kwargs: Any
|
| 361 |
+
) -> MACECalculator: ...
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def mace_omol(
|
| 365 |
+
model: Optional[Union[str, Path]] = None,
|
| 366 |
+
device: str = "",
|
| 367 |
+
default_dtype: str = "float64",
|
| 368 |
+
return_raw_model: bool = False,
|
| 369 |
+
**kwargs,
|
| 370 |
+
) -> Union[MACECalculator, torch.nn.Module]:
|
| 371 |
+
"""
|
| 372 |
+
Constructs a MACECalculator with a pretrained model based on the MACE-OMOL models.
|
| 373 |
+
The model is released under the ASL license.
|
| 374 |
+
Note:
|
| 375 |
+
If you are using this function, please cite the relevant OMOL paper.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
model (str or Path, optional): Either a path to a local model file or a string specifier.
|
| 379 |
+
Use "extra_large" or None to download the default OMOL model.
|
| 380 |
+
device (str, optional): Device to use for the model. Defaults to "cuda" if available.
|
| 381 |
+
default_dtype (str, optional): Default dtype for the model. Defaults to "float64".
|
| 382 |
+
return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False.
|
| 383 |
+
**kwargs: Passed to MACECalculator.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
MACECalculator: trained on the OMOL dataset.
|
| 387 |
+
"""
|
| 388 |
+
urls = {
|
| 389 |
+
"extra_large": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_omol_0/MACE-omol-0-extra-large-1024.model"
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
try:
|
| 393 |
+
if model is None or model == "extra_large":
|
| 394 |
+
checkpoint_url = urls["extra_large"]
|
| 395 |
+
elif isinstance(model, str) and model.startswith("https:"):
|
| 396 |
+
checkpoint_url = model
|
| 397 |
+
elif isinstance(model, (str, Path)) and Path(model).exists():
|
| 398 |
+
checkpoint_url = str(model)
|
| 399 |
+
else:
|
| 400 |
+
raise ValueError(
|
| 401 |
+
f"Invalid model specification: {model}. "
|
| 402 |
+
f"Supported options: {list(urls.keys())}, a local file path, or a direct URL."
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
if checkpoint_url.startswith("http"):
|
| 406 |
+
cache_dir = get_cache_dir()
|
| 407 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 408 |
+
checkpoint_url_name = os.path.basename(checkpoint_url).split("?")[0]
|
| 409 |
+
cached_model_path = os.path.join(cache_dir, checkpoint_url_name)
|
| 410 |
+
|
| 411 |
+
if not os.path.isfile(cached_model_path):
|
| 412 |
+
print(f"Downloading MACE model from {checkpoint_url!r}")
|
| 413 |
+
print(
|
| 414 |
+
"The model is distributed under the Academic Software License (ASL), see https://github.com/gabor1/ASL\n"
|
| 415 |
+
"To use the model, you accept the terms of the license.\n"
|
| 416 |
+
"ASL is based on the GNU Public License, but does not permit commercial use."
|
| 417 |
+
)
|
| 418 |
+
urllib.request.urlretrieve(checkpoint_url, cached_model_path)
|
| 419 |
+
print(f"Cached MACE model to {cached_model_path}")
|
| 420 |
+
model = cached_model_path
|
| 421 |
+
else:
|
| 422 |
+
model = checkpoint_url
|
| 423 |
+
|
| 424 |
+
except Exception as exc:
|
| 425 |
+
raise RuntimeError("Model download failed and no local model found") from exc
|
| 426 |
+
|
| 427 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 428 |
+
|
| 429 |
+
if return_raw_model:
|
| 430 |
+
return torch.load(model, map_location=device)
|
| 431 |
+
|
| 432 |
+
if default_dtype == "float64":
|
| 433 |
+
print(
|
| 434 |
+
"Using float64 for MACECalculator, recommended for geometry optimization."
|
| 435 |
+
)
|
| 436 |
+
elif default_dtype == "float32":
|
| 437 |
+
print("Using float32 for MACECalculator, recommended for MD.")
|
| 438 |
+
|
| 439 |
+
return MACECalculator(
|
| 440 |
+
model_paths=model,
|
| 441 |
+
device=device,
|
| 442 |
+
default_dtype=default_dtype,
|
| 443 |
+
**kwargs,
|
| 444 |
+
head="omol",
|
| 445 |
+
)
|
models/mace/mace/calculators/foundations_models/2023-12-03-mace-mp.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:01bfe22100139f424713cf921144e5509cbe353d67aa9fa1be9c6e1e0ed35845
|
| 3 |
+
size 44422970
|
models/mace/mace/calculators/foundations_models/ani500k_large_CC.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ad311c590b7df90a1d4aa34d997a8c419fdb7ae777296350869614e9e07b69d
|
| 3 |
+
size 35632548
|
models/mace/mace/calculators/foundations_models/mace-mpa-0-medium.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:75428afe3a1d7d8062e19bcaabd5c433623cabf308242ec9fb493e38604fb638
|
| 3 |
+
size 79462305
|
models/mace/mace/calculators/foundations_models/mp_vasp_e0.json
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"pbe": {
|
| 3 |
+
"1": -1.11734008,
|
| 4 |
+
"2": 0.00096759,
|
| 5 |
+
"3": -0.29754725,
|
| 6 |
+
"4": -0.01781697,
|
| 7 |
+
"5": -0.26885011,
|
| 8 |
+
"6": -1.26173507,
|
| 9 |
+
"7": -3.12438806,
|
| 10 |
+
"8": -1.54838784,
|
| 11 |
+
"9": -0.51882044,
|
| 12 |
+
"10": -0.01241601,
|
| 13 |
+
"11": -0.22883163,
|
| 14 |
+
"12": -0.00951015,
|
| 15 |
+
"13": -0.21630193,
|
| 16 |
+
"14": -0.8263903,
|
| 17 |
+
"15": -1.88816619,
|
| 18 |
+
"16": -0.89160769,
|
| 19 |
+
"17": -0.25828273,
|
| 20 |
+
"18": -0.04925973,
|
| 21 |
+
"19": -0.22697913,
|
| 22 |
+
"20": -0.0927795,
|
| 23 |
+
"21": -2.11396364,
|
| 24 |
+
"22": -2.50054871,
|
| 25 |
+
"23": -3.70477179,
|
| 26 |
+
"24": -5.60261985,
|
| 27 |
+
"25": -5.32541181,
|
| 28 |
+
"26": -3.52004933,
|
| 29 |
+
"27": -1.93555024,
|
| 30 |
+
"28": -0.9351969,
|
| 31 |
+
"29": -0.60025846,
|
| 32 |
+
"30": -0.1651332,
|
| 33 |
+
"31": -0.32990651,
|
| 34 |
+
"32": -0.77971828,
|
| 35 |
+
"33": -1.68367812,
|
| 36 |
+
"34": -0.76941032,
|
| 37 |
+
"35": -0.22213843,
|
| 38 |
+
"36": -0.0335879,
|
| 39 |
+
"37": -0.1881724,
|
| 40 |
+
"38": -0.06826294,
|
| 41 |
+
"39": -2.17084228,
|
| 42 |
+
"40": -2.28579303,
|
| 43 |
+
"41": -3.13429753,
|
| 44 |
+
"42": -4.60211419,
|
| 45 |
+
"43": -3.45201492,
|
| 46 |
+
"44": -2.38073513,
|
| 47 |
+
"45": -1.46855515,
|
| 48 |
+
"46": -1.4773126,
|
| 49 |
+
"47": -0.33954585,
|
| 50 |
+
"48": -0.16843877,
|
| 51 |
+
"49": -0.35470981,
|
| 52 |
+
"50": -0.83642657,
|
| 53 |
+
"51": -1.41101987,
|
| 54 |
+
"52": -0.65740879,
|
| 55 |
+
"53": -0.18964571,
|
| 56 |
+
"54": -0.00857582,
|
| 57 |
+
"55": -0.13771876,
|
| 58 |
+
"56": -0.03457659,
|
| 59 |
+
"57": -0.45580806,
|
| 60 |
+
"58": -1.3309175,
|
| 61 |
+
"59": -0.29671824,
|
| 62 |
+
"60": -0.30391193,
|
| 63 |
+
"61": -0.30898427,
|
| 64 |
+
"62": -0.25470891,
|
| 65 |
+
"63": -8.38001538,
|
| 66 |
+
"64": -10.38896525,
|
| 67 |
+
"65": -0.3059505,
|
| 68 |
+
"66": -0.30676216,
|
| 69 |
+
"67": -0.30874667,
|
| 70 |
+
"69": -0.25190039,
|
| 71 |
+
"70": -0.06431414,
|
| 72 |
+
"71": -0.31997586,
|
| 73 |
+
"72": -3.52770927,
|
| 74 |
+
"73": -3.54492209,
|
| 75 |
+
"75": -4.70108713,
|
| 76 |
+
"76": -2.88257209,
|
| 77 |
+
"77": -1.46779304,
|
| 78 |
+
"78": -0.50269936,
|
| 79 |
+
"79": -0.28801193,
|
| 80 |
+
"80": -0.12454674,
|
| 81 |
+
"81": -0.31737194,
|
| 82 |
+
"82": -0.77644932,
|
| 83 |
+
"83": -1.32627283,
|
| 84 |
+
"89": -0.26827152,
|
| 85 |
+
"90": -0.90817426,
|
| 86 |
+
"91": -2.47653193,
|
| 87 |
+
"92": -4.90438537,
|
| 88 |
+
"93": -7.63378961,
|
| 89 |
+
"94": -10.77237713
|
| 90 |
+
}
|
| 91 |
+
}
|
models/mace/mace/calculators/lammps_mace.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from e3nn.util.jit import compile_mode
|
| 5 |
+
|
| 6 |
+
from mace.tools.scatter import scatter_sum
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@compile_mode("script")
|
| 10 |
+
class LAMMPS_MACE(torch.nn.Module):
|
| 11 |
+
def __init__(self, model, **kwargs):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.model = model
|
| 14 |
+
self.register_buffer("atomic_numbers", model.atomic_numbers)
|
| 15 |
+
self.register_buffer("r_max", model.r_max)
|
| 16 |
+
self.register_buffer("num_interactions", model.num_interactions)
|
| 17 |
+
if not hasattr(model, "heads"):
|
| 18 |
+
model.heads = [None]
|
| 19 |
+
self.register_buffer(
|
| 20 |
+
"head",
|
| 21 |
+
torch.tensor(
|
| 22 |
+
self.model.heads.index(kwargs.get("head", self.model.heads[-1])),
|
| 23 |
+
dtype=torch.long,
|
| 24 |
+
).unsqueeze(0),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
for param in self.model.parameters():
|
| 28 |
+
param.requires_grad = False
|
| 29 |
+
|
| 30 |
+
def forward(
|
| 31 |
+
self,
|
| 32 |
+
data: Dict[str, torch.Tensor],
|
| 33 |
+
local_or_ghost: torch.Tensor,
|
| 34 |
+
compute_virials: bool = False,
|
| 35 |
+
) -> Dict[str, Optional[torch.Tensor]]:
|
| 36 |
+
num_graphs = data["ptr"].numel() - 1
|
| 37 |
+
compute_displacement = False
|
| 38 |
+
if compute_virials:
|
| 39 |
+
compute_displacement = True
|
| 40 |
+
data["head"] = self.head
|
| 41 |
+
out = self.model(
|
| 42 |
+
data,
|
| 43 |
+
training=False,
|
| 44 |
+
compute_force=False,
|
| 45 |
+
compute_virials=False,
|
| 46 |
+
compute_stress=False,
|
| 47 |
+
compute_displacement=compute_displacement,
|
| 48 |
+
)
|
| 49 |
+
node_energy = out["node_energy"]
|
| 50 |
+
if node_energy is None:
|
| 51 |
+
return {
|
| 52 |
+
"total_energy_local": None,
|
| 53 |
+
"node_energy": None,
|
| 54 |
+
"forces": None,
|
| 55 |
+
"virials": None,
|
| 56 |
+
}
|
| 57 |
+
positions = data["positions"]
|
| 58 |
+
displacement = out["displacement"]
|
| 59 |
+
forces: Optional[torch.Tensor] = torch.zeros_like(positions)
|
| 60 |
+
virials: Optional[torch.Tensor] = torch.zeros_like(data["cell"])
|
| 61 |
+
# accumulate energies of local atoms
|
| 62 |
+
node_energy_local = node_energy * local_or_ghost
|
| 63 |
+
total_energy_local = scatter_sum(
|
| 64 |
+
src=node_energy_local, index=data["batch"], dim=-1, dim_size=num_graphs
|
| 65 |
+
)
|
| 66 |
+
# compute partial forces and (possibly) partial virials
|
| 67 |
+
grad_outputs: List[Optional[torch.Tensor]] = [
|
| 68 |
+
torch.ones_like(total_energy_local)
|
| 69 |
+
]
|
| 70 |
+
if compute_virials and displacement is not None:
|
| 71 |
+
forces, virials = torch.autograd.grad(
|
| 72 |
+
outputs=[total_energy_local],
|
| 73 |
+
inputs=[positions, displacement],
|
| 74 |
+
grad_outputs=grad_outputs,
|
| 75 |
+
retain_graph=False,
|
| 76 |
+
create_graph=False,
|
| 77 |
+
allow_unused=True,
|
| 78 |
+
)
|
| 79 |
+
if forces is not None:
|
| 80 |
+
forces = -1 * forces
|
| 81 |
+
else:
|
| 82 |
+
forces = torch.zeros_like(positions)
|
| 83 |
+
if virials is not None:
|
| 84 |
+
virials = -1 * virials
|
| 85 |
+
else:
|
| 86 |
+
virials = torch.zeros_like(displacement)
|
| 87 |
+
else:
|
| 88 |
+
forces = torch.autograd.grad(
|
| 89 |
+
outputs=[total_energy_local],
|
| 90 |
+
inputs=[positions],
|
| 91 |
+
grad_outputs=grad_outputs,
|
| 92 |
+
retain_graph=False,
|
| 93 |
+
create_graph=False,
|
| 94 |
+
allow_unused=True,
|
| 95 |
+
)[0]
|
| 96 |
+
if forces is not None:
|
| 97 |
+
forces = -1 * forces
|
| 98 |
+
else:
|
| 99 |
+
forces = torch.zeros_like(positions)
|
| 100 |
+
return {
|
| 101 |
+
"total_energy_local": total_energy_local,
|
| 102 |
+
"node_energy": node_energy,
|
| 103 |
+
"forces": forces,
|
| 104 |
+
"virials": virials,
|
| 105 |
+
}
|
models/mace/mace/calculators/lammps_mliap_mace.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from typing import Dict, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from ase.data import chemical_symbols
|
| 10 |
+
from e3nn.util.jit import compile_mode
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from lammps.mliap.mliap_unified_abc import MLIAPUnified
|
| 14 |
+
except ImportError:
|
| 15 |
+
|
| 16 |
+
class MLIAPUnified:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MACELammpsConfig:
|
| 22 |
+
"""Configuration settings for MACE-LAMMPS integration."""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
self.debug_time = self._get_env_bool("MACE_TIME", False)
|
| 26 |
+
self.debug_profile = self._get_env_bool("MACE_PROFILE", False)
|
| 27 |
+
self.profile_start_step = int(os.environ.get("MACE_PROFILE_START", "5"))
|
| 28 |
+
self.profile_end_step = int(os.environ.get("MACE_PROFILE_END", "10"))
|
| 29 |
+
self.allow_cpu = self._get_env_bool("MACE_ALLOW_CPU", False)
|
| 30 |
+
self.force_cpu = self._get_env_bool("MACE_FORCE_CPU", False)
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def _get_env_bool(var_name: str, default: bool) -> bool:
|
| 34 |
+
return os.environ.get(var_name, str(default)).lower() in (
|
| 35 |
+
"true",
|
| 36 |
+
"1",
|
| 37 |
+
"t",
|
| 38 |
+
"yes",
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@contextmanager
|
| 43 |
+
def timer(name: str, enabled: bool = True):
|
| 44 |
+
"""Context manager for timing code blocks."""
|
| 45 |
+
if not enabled:
|
| 46 |
+
yield
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
start = time.perf_counter()
|
| 50 |
+
try:
|
| 51 |
+
yield
|
| 52 |
+
finally:
|
| 53 |
+
elapsed = time.perf_counter() - start
|
| 54 |
+
logging.info(f"Timer - {name}: {elapsed*1000:.3f} ms")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@compile_mode("script")
|
| 58 |
+
class MACEEdgeForcesWrapper(torch.nn.Module):
|
| 59 |
+
"""Wrapper that adds per-pair force computation to a MACE model."""
|
| 60 |
+
|
| 61 |
+
def __init__(self, model: torch.nn.Module, **kwargs):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.model = model
|
| 64 |
+
self.register_buffer("atomic_numbers", model.atomic_numbers)
|
| 65 |
+
self.register_buffer("r_max", model.r_max)
|
| 66 |
+
self.register_buffer("num_interactions", model.num_interactions)
|
| 67 |
+
self.register_buffer(
|
| 68 |
+
"total_charge",
|
| 69 |
+
kwargs.get(
|
| 70 |
+
"total_charge", torch.tensor([0.0], dtype=torch.get_default_dtype())
|
| 71 |
+
),
|
| 72 |
+
)
|
| 73 |
+
self.register_buffer(
|
| 74 |
+
"total_spin",
|
| 75 |
+
kwargs.get(
|
| 76 |
+
"total_spin", torch.tensor([1.0], dtype=torch.get_default_dtype())
|
| 77 |
+
),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if not hasattr(model, "heads"):
|
| 81 |
+
model.heads = ["Default"]
|
| 82 |
+
|
| 83 |
+
head_name = kwargs.get("head", model.heads[-1])
|
| 84 |
+
head_idx = model.heads.index(head_name)
|
| 85 |
+
self.register_buffer("head", torch.tensor([head_idx], dtype=torch.long))
|
| 86 |
+
|
| 87 |
+
for p in self.model.parameters():
|
| 88 |
+
p.requires_grad = False
|
| 89 |
+
|
| 90 |
+
def forward(
|
| 91 |
+
self, data: Dict[str, torch.Tensor]
|
| 92 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 93 |
+
"""Compute energies and per-pair forces."""
|
| 94 |
+
data["head"] = self.head
|
| 95 |
+
data["total_charge"] = self.total_charge
|
| 96 |
+
data["total_spin"] = self.total_spin
|
| 97 |
+
|
| 98 |
+
out = self.model(
|
| 99 |
+
data,
|
| 100 |
+
training=False,
|
| 101 |
+
compute_force=False,
|
| 102 |
+
compute_virials=False,
|
| 103 |
+
compute_stress=False,
|
| 104 |
+
compute_displacement=False,
|
| 105 |
+
compute_edge_forces=True,
|
| 106 |
+
lammps_mliap=True,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
node_energy = out["node_energy"]
|
| 110 |
+
pair_forces = out["edge_forces"]
|
| 111 |
+
total_energy = out["energy"][0]
|
| 112 |
+
|
| 113 |
+
if pair_forces is None:
|
| 114 |
+
pair_forces = torch.zeros_like(data["vectors"])
|
| 115 |
+
|
| 116 |
+
return total_energy, node_energy, pair_forces
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class LAMMPS_MLIAP_MACE(MLIAPUnified):
|
| 120 |
+
"""MACE integration for LAMMPS using the MLIAP interface."""
|
| 121 |
+
|
| 122 |
+
def __init__(self, model, **kwargs):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.config = MACELammpsConfig()
|
| 125 |
+
self.model = MACEEdgeForcesWrapper(model, **kwargs)
|
| 126 |
+
self.element_types = [chemical_symbols[s] for s in model.atomic_numbers]
|
| 127 |
+
self.num_species = len(self.element_types)
|
| 128 |
+
self.rcutfac = 0.5 * float(model.r_max)
|
| 129 |
+
self.ndescriptors = 1
|
| 130 |
+
self.nparams = 1
|
| 131 |
+
self.dtype = model.r_max.dtype
|
| 132 |
+
self.device = "cpu"
|
| 133 |
+
self.initialized = False
|
| 134 |
+
self.step = 0
|
| 135 |
+
|
| 136 |
+
def _initialize_device(self, data):
|
| 137 |
+
using_kokkos = "kokkos" in data.__class__.__module__.lower()
|
| 138 |
+
|
| 139 |
+
if using_kokkos and not self.config.force_cpu:
|
| 140 |
+
device = torch.as_tensor(data.elems).device
|
| 141 |
+
if device.type == "cpu" and not self.config.allow_cpu:
|
| 142 |
+
raise ValueError(
|
| 143 |
+
"GPU requested but tensor is on CPU. Set MACE_ALLOW_CPU=true to allow CPU computation."
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
device = torch.device("cpu")
|
| 147 |
+
|
| 148 |
+
self.device = device
|
| 149 |
+
self.model = self.model.to(device)
|
| 150 |
+
logging.info(f"MACE model initialized on device: {device}")
|
| 151 |
+
self.initialized = True
|
| 152 |
+
|
| 153 |
+
def compute_forces(self, data):
|
| 154 |
+
natoms = data.nlocal
|
| 155 |
+
ntotal = data.ntotal
|
| 156 |
+
nghosts = ntotal - natoms
|
| 157 |
+
npairs = data.npairs
|
| 158 |
+
species = torch.as_tensor(data.elems, dtype=torch.int64)
|
| 159 |
+
|
| 160 |
+
if not self.initialized:
|
| 161 |
+
self._initialize_device(data)
|
| 162 |
+
|
| 163 |
+
self.step += 1
|
| 164 |
+
self._manage_profiling()
|
| 165 |
+
|
| 166 |
+
if natoms == 0 or npairs <= 1:
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
with timer("total_step", enabled=self.config.debug_time):
|
| 170 |
+
with timer("prepare_batch", enabled=self.config.debug_time):
|
| 171 |
+
batch = self._prepare_batch(data, natoms, nghosts, species)
|
| 172 |
+
|
| 173 |
+
with timer("model_forward", enabled=self.config.debug_time):
|
| 174 |
+
_, atom_energies, pair_forces = self.model(batch)
|
| 175 |
+
|
| 176 |
+
if self.device.type != "cpu":
|
| 177 |
+
torch.cuda.synchronize()
|
| 178 |
+
|
| 179 |
+
with timer("update_lammps", enabled=self.config.debug_time):
|
| 180 |
+
self._update_lammps_data(data, atom_energies, pair_forces, natoms)
|
| 181 |
+
|
| 182 |
+
def _prepare_batch(self, data, natoms, nghosts, species):
|
| 183 |
+
"""Prepare the input batch for the MACE model."""
|
| 184 |
+
return {
|
| 185 |
+
"vectors": torch.as_tensor(data.rij).to(self.dtype).to(self.device),
|
| 186 |
+
"node_attrs": torch.nn.functional.one_hot(
|
| 187 |
+
species.to(self.device), num_classes=self.num_species
|
| 188 |
+
).to(self.dtype),
|
| 189 |
+
"edge_index": torch.stack(
|
| 190 |
+
[
|
| 191 |
+
torch.as_tensor(data.pair_j, dtype=torch.int64).to(self.device),
|
| 192 |
+
torch.as_tensor(data.pair_i, dtype=torch.int64).to(self.device),
|
| 193 |
+
],
|
| 194 |
+
dim=0,
|
| 195 |
+
),
|
| 196 |
+
"batch": torch.zeros(natoms, dtype=torch.int64, device=self.device),
|
| 197 |
+
"lammps_class": data,
|
| 198 |
+
"natoms": (natoms, nghosts),
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
def _update_lammps_data(self, data, atom_energies, pair_forces, natoms):
|
| 202 |
+
"""Update LAMMPS data structures with computed energies and forces."""
|
| 203 |
+
if self.dtype == torch.float32:
|
| 204 |
+
pair_forces = pair_forces.double()
|
| 205 |
+
eatoms = torch.as_tensor(data.eatoms)
|
| 206 |
+
eatoms.copy_(atom_energies[:natoms])
|
| 207 |
+
data.energy = torch.sum(atom_energies[:natoms])
|
| 208 |
+
data.update_pair_forces_gpu(pair_forces)
|
| 209 |
+
|
| 210 |
+
def _manage_profiling(self):
|
| 211 |
+
if not self.config.debug_profile:
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
if self.step == self.config.profile_start_step:
|
| 215 |
+
logging.info(f"Starting CUDA profiler at step {self.step}")
|
| 216 |
+
torch.cuda.profiler.start()
|
| 217 |
+
|
| 218 |
+
if self.step == self.config.profile_end_step:
|
| 219 |
+
logging.info(f"Stopping CUDA profiler at step {self.step}")
|
| 220 |
+
torch.cuda.profiler.stop()
|
| 221 |
+
logging.info("Profiling complete. Exiting.")
|
| 222 |
+
sys.exit()
|
| 223 |
+
|
| 224 |
+
def compute_descriptors(self, data):
|
| 225 |
+
pass
|
| 226 |
+
|
| 227 |
+
def compute_gradients(self, data):
|
| 228 |
+
pass
|
models/mace/mace/calculators/mace.py
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###########################################################################################
|
| 2 |
+
# The ASE Calculator for MACE
|
| 3 |
+
# Authors: Ilyes Batatia, David Kovacs
|
| 4 |
+
# This program is distributed under the MIT License (see MIT.md)
|
| 5 |
+
###########################################################################################
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
# pylint: disable=wrong-import-position
|
| 10 |
+
import os
|
| 11 |
+
from glob import glob
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import List, Union
|
| 14 |
+
|
| 15 |
+
os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from ase.calculators.calculator import Calculator, all_changes
|
| 20 |
+
from ase.stress import full_3x3_to_voigt_6_stress
|
| 21 |
+
from e3nn import o3
|
| 22 |
+
|
| 23 |
+
from mace import data as mace_data
|
| 24 |
+
from mace.modules.utils import extract_invariant
|
| 25 |
+
from mace.tools import torch_geometric, torch_tools, utils
|
| 26 |
+
from mace.tools.compile import prepare
|
| 27 |
+
from mace.tools.scripts_utils import extract_model
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq
|
| 31 |
+
|
| 32 |
+
CUEQQ_AVAILABLE = True
|
| 33 |
+
except (ImportError, ModuleNotFoundError):
|
| 34 |
+
CUEQQ_AVAILABLE = False
|
| 35 |
+
run_e3nn_to_cueq = None
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq
|
| 39 |
+
|
| 40 |
+
OEQ_AVAILABLE = True
|
| 41 |
+
except (ImportError, ModuleNotFoundError):
|
| 42 |
+
OEQ_AVAILABLE = False
|
| 43 |
+
run_e3nn_to_oeq = None
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
import intel_extension_for_pytorch as ipex
|
| 47 |
+
|
| 48 |
+
has_ipex = True
|
| 49 |
+
except ImportError:
|
| 50 |
+
has_ipex = False
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_model_dtype(model: torch.nn.Module) -> torch.dtype:
|
| 54 |
+
"""Get the dtype of the model"""
|
| 55 |
+
mode_dtype = next(model.parameters()).dtype
|
| 56 |
+
if mode_dtype == torch.float64:
|
| 57 |
+
return "float64"
|
| 58 |
+
if mode_dtype == torch.float32:
|
| 59 |
+
return "float32"
|
| 60 |
+
raise ValueError(f"Unknown dtype {mode_dtype}")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MACECalculator(Calculator):
|
| 64 |
+
"""MACE ASE Calculator
|
| 65 |
+
args:
|
| 66 |
+
model_paths: str, path to model or models if a committee is produced
|
| 67 |
+
to make a committee use a wild card notation like mace_*.model
|
| 68 |
+
device: str, device to run on (cuda or cpu or xpu)
|
| 69 |
+
energy_units_to_eV: float, conversion factor from model energy units to eV
|
| 70 |
+
length_units_to_A: float, conversion factor from model length units to Angstroms
|
| 71 |
+
default_dtype: str, default dtype of model
|
| 72 |
+
charges_key: str, Array field of atoms object where atomic charges are stored
|
| 73 |
+
model_type: str, type of model to load
|
| 74 |
+
Options: [MACE, DipoleMACE, EnergyDipoleMACE]
|
| 75 |
+
|
| 76 |
+
Dipoles are returned in units of Debye
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
model_paths: Union[list, str, None] = None,
|
| 82 |
+
models: Union[List[torch.nn.Module], torch.nn.Module, None] = None,
|
| 83 |
+
device: str = "cpu",
|
| 84 |
+
energy_units_to_eV: float = 1.0,
|
| 85 |
+
length_units_to_A: float = 1.0,
|
| 86 |
+
default_dtype="",
|
| 87 |
+
charges_key="Qs",
|
| 88 |
+
info_keys=None,
|
| 89 |
+
arrays_keys=None,
|
| 90 |
+
model_type="MACE",
|
| 91 |
+
compile_mode=None,
|
| 92 |
+
fullgraph=True,
|
| 93 |
+
enable_cueq=False,
|
| 94 |
+
enable_oeq=False,
|
| 95 |
+
**kwargs,
|
| 96 |
+
):
|
| 97 |
+
Calculator.__init__(self, **kwargs)
|
| 98 |
+
if enable_cueq or enable_oeq:
|
| 99 |
+
assert model_type == "MACE", "CuEq only supports MACE models"
|
| 100 |
+
if compile_mode is not None:
|
| 101 |
+
logging.warning(
|
| 102 |
+
"CuEq or Oeq does not support torch.compile, setting compile_mode to None"
|
| 103 |
+
)
|
| 104 |
+
compile_mode = None
|
| 105 |
+
if enable_cueq and enable_oeq:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"CuEq and OEq cannot be used together, please choose one of them"
|
| 108 |
+
)
|
| 109 |
+
if enable_cueq and not CUEQQ_AVAILABLE:
|
| 110 |
+
raise ImportError(
|
| 111 |
+
"cuequivariance is not installed so CuEq acceleration cannot be used"
|
| 112 |
+
)
|
| 113 |
+
if enable_oeq and not OEQ_AVAILABLE:
|
| 114 |
+
raise ImportError(
|
| 115 |
+
"openequivariance is not installed so OEq acceleration cannot be used"
|
| 116 |
+
)
|
| 117 |
+
if "model_path" in kwargs:
|
| 118 |
+
deprecation_message = (
|
| 119 |
+
"'model_path' argument is deprecated, please use 'model_paths'"
|
| 120 |
+
)
|
| 121 |
+
if model_paths is None:
|
| 122 |
+
logging.warning(f"{deprecation_message} in the future.")
|
| 123 |
+
model_paths = kwargs["model_path"]
|
| 124 |
+
else:
|
| 125 |
+
raise ValueError(
|
| 126 |
+
f"both 'model_path' and 'model_paths' given, {deprecation_message} only."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if (model_paths is None) == (models is None):
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"Exactly one of 'model_paths' or 'models' must be provided"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
self.results = {}
|
| 135 |
+
if info_keys is None:
|
| 136 |
+
info_keys = {"total_spin": "spin", "total_charge": "charge"}
|
| 137 |
+
if arrays_keys is None:
|
| 138 |
+
arrays_keys = {}
|
| 139 |
+
self.info_keys = info_keys
|
| 140 |
+
self.arrays_keys = arrays_keys
|
| 141 |
+
|
| 142 |
+
self.model_type = model_type
|
| 143 |
+
self.compute_atomic_stresses = False
|
| 144 |
+
|
| 145 |
+
if model_type not in [
|
| 146 |
+
"MACE",
|
| 147 |
+
"DipoleMACE",
|
| 148 |
+
"EnergyDipoleMACE",
|
| 149 |
+
"DipolePolarizabilityMACE",
|
| 150 |
+
]:
|
| 151 |
+
raise ValueError(
|
| 152 |
+
f"Give a valid model_type: [MACE, DipoleMACE, DipolePolarizabilityMACE, EnergyDipoleMACE], {model_type} not supported"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# superclass constructor initializes self.implemented_properties to an empty list
|
| 156 |
+
if model_type in ["MACE", "EnergyDipoleMACE"]:
|
| 157 |
+
self.implemented_properties.extend(
|
| 158 |
+
[
|
| 159 |
+
"energy",
|
| 160 |
+
"energies",
|
| 161 |
+
"free_energy",
|
| 162 |
+
"node_energy",
|
| 163 |
+
"forces",
|
| 164 |
+
"stress",
|
| 165 |
+
]
|
| 166 |
+
)
|
| 167 |
+
if kwargs.get("compute_atomic_stresses", False):
|
| 168 |
+
self.implemented_properties.extend(["stresses", "virials"])
|
| 169 |
+
self.compute_atomic_stresses = True
|
| 170 |
+
if model_type in ["EnergyDipoleMACE", "DipoleMACE", "DipolePolarizabilityMACE"]:
|
| 171 |
+
self.implemented_properties.extend(["dipole"])
|
| 172 |
+
if model_type == "DipolePolarizabilityMACE":
|
| 173 |
+
self.implemented_properties.extend(
|
| 174 |
+
[
|
| 175 |
+
"charges",
|
| 176 |
+
"polarizability",
|
| 177 |
+
"polarizability_sh",
|
| 178 |
+
]
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
if model_paths is not None:
|
| 182 |
+
if isinstance(model_paths, str):
|
| 183 |
+
# Find all models that satisfy the wildcard (e.g. mace_model_*.pt)
|
| 184 |
+
model_paths_glob = glob(model_paths)
|
| 185 |
+
|
| 186 |
+
if len(model_paths_glob) == 0:
|
| 187 |
+
raise ValueError(f"Couldn't find MACE model files: {model_paths}")
|
| 188 |
+
|
| 189 |
+
model_paths = model_paths_glob
|
| 190 |
+
elif isinstance(model_paths, Path):
|
| 191 |
+
model_paths = [model_paths]
|
| 192 |
+
|
| 193 |
+
if len(model_paths) == 0:
|
| 194 |
+
raise ValueError("No mace file names supplied")
|
| 195 |
+
self.num_models = len(model_paths)
|
| 196 |
+
|
| 197 |
+
# Load models from files
|
| 198 |
+
self.models = [
|
| 199 |
+
torch.load(f=model_path, map_location=device)
|
| 200 |
+
for model_path in model_paths
|
| 201 |
+
]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
elif models is not None:
|
| 205 |
+
if not isinstance(models, list):
|
| 206 |
+
models = [models]
|
| 207 |
+
|
| 208 |
+
if len(models) == 0:
|
| 209 |
+
raise ValueError("No models supplied")
|
| 210 |
+
|
| 211 |
+
self.models = models
|
| 212 |
+
self.num_models = len(models)
|
| 213 |
+
|
| 214 |
+
if self.num_models > 1:
|
| 215 |
+
logging.info(f"Running committee mace with {self.num_models} models")
|
| 216 |
+
|
| 217 |
+
if model_type in ["MACE", "EnergyDipoleMACE"]:
|
| 218 |
+
self.implemented_properties.extend(
|
| 219 |
+
["energy_comm", "energy_var", "forces_comm", "stress_var"]
|
| 220 |
+
)
|
| 221 |
+
if model_type in [
|
| 222 |
+
"DipoleMACE",
|
| 223 |
+
"EnergyDipoleMACE",
|
| 224 |
+
"DipolePolarizabilityMACE",
|
| 225 |
+
]:
|
| 226 |
+
self.implemented_properties.extend(["dipole_var"])
|
| 227 |
+
|
| 228 |
+
if compile_mode is not None:
|
| 229 |
+
logging.info(f"Torch compile is enabled with mode: {compile_mode}")
|
| 230 |
+
self.models = [
|
| 231 |
+
torch.compile(
|
| 232 |
+
prepare(extract_model)(model=model, map_location=device),
|
| 233 |
+
mode=compile_mode,
|
| 234 |
+
fullgraph=fullgraph,
|
| 235 |
+
)
|
| 236 |
+
for model in self.models
|
| 237 |
+
]
|
| 238 |
+
self.use_compile = True
|
| 239 |
+
else:
|
| 240 |
+
self.use_compile = False
|
| 241 |
+
|
| 242 |
+
# Ensure all models are on the same device
|
| 243 |
+
for model in self.models:
|
| 244 |
+
model.to(device)
|
| 245 |
+
|
| 246 |
+
if has_ipex and device == "xpu":
|
| 247 |
+
for model in self.models:
|
| 248 |
+
model = ipex.optimize(model)
|
| 249 |
+
|
| 250 |
+
r_maxs = [model.r_max.cpu() for model in self.models]
|
| 251 |
+
r_maxs = np.array(r_maxs)
|
| 252 |
+
if not np.all(r_maxs == r_maxs[0]):
|
| 253 |
+
raise ValueError(f"committee r_max are not all the same {' '.join(r_maxs)}")
|
| 254 |
+
self.r_max = float(r_maxs[0])
|
| 255 |
+
|
| 256 |
+
self.device = torch_tools.init_device(device)
|
| 257 |
+
self.energy_units_to_eV = energy_units_to_eV
|
| 258 |
+
self.length_units_to_A = length_units_to_A
|
| 259 |
+
self.z_table = utils.AtomicNumberTable(
|
| 260 |
+
[int(z) for z in self.models[0].atomic_numbers]
|
| 261 |
+
)
|
| 262 |
+
self.charges_key = charges_key
|
| 263 |
+
|
| 264 |
+
try:
|
| 265 |
+
self.available_heads: List[str] = self.models[0].heads # type: ignore
|
| 266 |
+
except AttributeError:
|
| 267 |
+
self.available_heads = ["Default"]
|
| 268 |
+
kwarg_head = kwargs.get("head", None)
|
| 269 |
+
if kwarg_head is not None:
|
| 270 |
+
self.head = kwarg_head
|
| 271 |
+
if isinstance(self.head, str):
|
| 272 |
+
if self.head not in self.available_heads:
|
| 273 |
+
last_head = self.available_heads[-1]
|
| 274 |
+
logging.warning(
|
| 275 |
+
f"Head {self.head} not found in available heads {self.available_heads}, defaulting to the last head: {last_head}"
|
| 276 |
+
)
|
| 277 |
+
self.head = last_head
|
| 278 |
+
elif len(self.available_heads) == 1:
|
| 279 |
+
self.head = self.available_heads[0]
|
| 280 |
+
else:
|
| 281 |
+
self.head = [
|
| 282 |
+
head for head in self.available_heads if head.lower() == "default"
|
| 283 |
+
]
|
| 284 |
+
if len(self.head) == 0:
|
| 285 |
+
raise ValueError(
|
| 286 |
+
"Head keyword was not provided, and no head in the model is 'default'. "
|
| 287 |
+
"Please provide a head keyword to specify the head you want to use. "
|
| 288 |
+
f"Available heads are: {self.available_heads}"
|
| 289 |
+
)
|
| 290 |
+
self.head = self.head[0]
|
| 291 |
+
|
| 292 |
+
logging.info(f"Using head {self.head} out of {self.available_heads}")
|
| 293 |
+
|
| 294 |
+
model_dtype = get_model_dtype(self.models[0])
|
| 295 |
+
if default_dtype == "":
|
| 296 |
+
logging.warning(
|
| 297 |
+
f"No dtype selected, switching to {model_dtype} to match model dtype."
|
| 298 |
+
)
|
| 299 |
+
default_dtype = model_dtype
|
| 300 |
+
if model_dtype != default_dtype:
|
| 301 |
+
logging.warning(
|
| 302 |
+
f"Default dtype {default_dtype} does not match model dtype {model_dtype}, converting models to {default_dtype}."
|
| 303 |
+
)
|
| 304 |
+
if default_dtype == "float64":
|
| 305 |
+
self.models = [model.double() for model in self.models]
|
| 306 |
+
elif default_dtype == "float32":
|
| 307 |
+
self.models = [model.float() for model in self.models]
|
| 308 |
+
torch_tools.set_default_dtype(default_dtype)
|
| 309 |
+
if enable_cueq:
|
| 310 |
+
logging.info("Converting models to CuEq for acceleration")
|
| 311 |
+
self.models = [
|
| 312 |
+
run_e3nn_to_cueq(model, device=device).to(device)
|
| 313 |
+
for model in self.models
|
| 314 |
+
]
|
| 315 |
+
if enable_oeq:
|
| 316 |
+
logging.info("Converting models to OEq for acceleration")
|
| 317 |
+
self.models = [
|
| 318 |
+
run_e3nn_to_oeq(model, device=device).to(device)
|
| 319 |
+
for model in self.models
|
| 320 |
+
]
|
| 321 |
+
for model in self.models:
|
| 322 |
+
for param in model.parameters():
|
| 323 |
+
param.requires_grad = False
|
| 324 |
+
|
| 325 |
+
def check_state(self, atoms, tol: float = 1e-15) -> list:
|
| 326 |
+
"""
|
| 327 |
+
Check for any system changes since the last calculation.
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
atoms (ase.Atoms): The atomic structure to check.
|
| 331 |
+
tol (float): Tolerance for detecting changes.
|
| 332 |
+
|
| 333 |
+
Returns:
|
| 334 |
+
list: A list of changes detected in the system.
|
| 335 |
+
"""
|
| 336 |
+
state = super().check_state(atoms, tol=tol)
|
| 337 |
+
if (not state) and (self.atoms.info != atoms.info):
|
| 338 |
+
state.append("info")
|
| 339 |
+
return state
|
| 340 |
+
|
| 341 |
+
def _create_result_tensors(
|
| 342 |
+
self, num_models: int, num_atoms: int, batch, out: dict
|
| 343 |
+
) -> dict:
|
| 344 |
+
# unfortunately, code is expecting shape that isn't always same as underlying model
|
| 345 |
+
# output tensor shape, e.g. stress is returned as 1x3x3 and we want 3x3
|
| 346 |
+
tensor_shapes = {
|
| 347 |
+
"energy": [],
|
| 348 |
+
"node_energy": [num_atoms],
|
| 349 |
+
"forces": [num_atoms, 3],
|
| 350 |
+
"stress": [3, 3],
|
| 351 |
+
"atomic_stresses": [num_atoms, 3, 3],
|
| 352 |
+
"atomic_virials": [num_atoms, 3, 3],
|
| 353 |
+
"dipole": [3],
|
| 354 |
+
"charges": [num_atoms],
|
| 355 |
+
"polarizability": [3, 3],
|
| 356 |
+
"polarizability_sh": [6],
|
| 357 |
+
}
|
| 358 |
+
dict_of_tensors = {}
|
| 359 |
+
for key in out:
|
| 360 |
+
if key not in tensor_shapes or out.get(key) is None:
|
| 361 |
+
continue
|
| 362 |
+
shape = [num_models] + tensor_shapes[key]
|
| 363 |
+
dict_of_tensors[key] = torch.zeros(*shape, device=self.device)
|
| 364 |
+
|
| 365 |
+
node_e0 = None
|
| 366 |
+
if "node_energy" in out:
|
| 367 |
+
node_heads = batch["head"][batch["batch"]]
|
| 368 |
+
num_atoms_arange = torch.arange(batch["positions"].shape[0])
|
| 369 |
+
node_e0 = (
|
| 370 |
+
self.models[0]
|
| 371 |
+
.atomic_energies_fn(batch["node_attrs"])[num_atoms_arange, node_heads]
|
| 372 |
+
.detach()
|
| 373 |
+
.cpu()
|
| 374 |
+
.numpy()
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
return dict_of_tensors, node_e0
|
| 378 |
+
|
| 379 |
+
def _atoms_to_batch(self, atoms):
|
| 380 |
+
self.arrays_keys.update({self.charges_key: "charges"})
|
| 381 |
+
keyspec = mace_data.KeySpecification(
|
| 382 |
+
info_keys=self.info_keys, arrays_keys=self.arrays_keys
|
| 383 |
+
)
|
| 384 |
+
config = mace_data.config_from_atoms(
|
| 385 |
+
atoms, key_specification=keyspec, head_name=self.head
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
data_loader = torch_geometric.dataloader.DataLoader(
|
| 390 |
+
dataset=[
|
| 391 |
+
mace_data.AtomicData.from_config(
|
| 392 |
+
config,
|
| 393 |
+
z_table=self.z_table,
|
| 394 |
+
cutoff=self.r_max,
|
| 395 |
+
heads=self.available_heads,
|
| 396 |
+
)
|
| 397 |
+
],
|
| 398 |
+
batch_size=1,
|
| 399 |
+
shuffle=False,
|
| 400 |
+
drop_last=False,
|
| 401 |
+
)
|
| 402 |
+
batch = next(iter(data_loader)).to(self.device)
|
| 403 |
+
return batch
|
| 404 |
+
|
| 405 |
+
def _clone_batch(self, batch):
|
| 406 |
+
batch_clone = batch.clone()
|
| 407 |
+
if self.use_compile:
|
| 408 |
+
batch_clone["node_attrs"].requires_grad_(True)
|
| 409 |
+
batch_clone["positions"].requires_grad_(True)
|
| 410 |
+
return batch_clone
|
| 411 |
+
|
| 412 |
+
# pylint: disable=dangerous-default-value
|
| 413 |
+
def calculate(self, atoms=None, properties=None, system_changes=all_changes):
|
| 414 |
+
"""
|
| 415 |
+
Calculate properties.
|
| 416 |
+
:param atoms: ase.Atoms object
|
| 417 |
+
:param properties: [str], properties to be computed, used by ASE internally
|
| 418 |
+
:param system_changes: [str], system changes since last calculation, used by ASE internally
|
| 419 |
+
:return:
|
| 420 |
+
"""
|
| 421 |
+
# call to base-class to set atoms attribute
|
| 422 |
+
Calculator.calculate(self, atoms)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
batch_base = self._atoms_to_batch(atoms)
|
| 426 |
+
|
| 427 |
+
if self.model_type in ["MACE", "EnergyDipoleMACE"]:
|
| 428 |
+
compute_stress = not self.use_compile
|
| 429 |
+
else:
|
| 430 |
+
compute_stress = False
|
| 431 |
+
|
| 432 |
+
ret_tensors = None
|
| 433 |
+
node_e0 = None
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
# copy from output of model() call to ret_tensors
|
| 437 |
+
for i, model in enumerate(self.models):
|
| 438 |
+
batch = self._clone_batch(batch_base)
|
| 439 |
+
#print(type(model)) # Scale shift mace
|
| 440 |
+
out = model(
|
| 441 |
+
batch.to_dict(),
|
| 442 |
+
compute_stress=compute_stress, # Fakse
|
| 443 |
+
compute_force = True,
|
| 444 |
+
training=self.use_compile, #false
|
| 445 |
+
compute_edge_forces=self.compute_atomic_stresses, #False
|
| 446 |
+
compute_atomic_stresses=self.compute_atomic_stresses, # False
|
| 447 |
+
)
|
| 448 |
+
if i == 0:
|
| 449 |
+
ret_tensors, node_e0 = self._create_result_tensors(
|
| 450 |
+
self.num_models, len(atoms), batch, out
|
| 451 |
+
)
|
| 452 |
+
for key, val in ret_tensors.items():
|
| 453 |
+
if out.get(key) is not None:
|
| 454 |
+
val[i] = out[key].detach()
|
| 455 |
+
|
| 456 |
+
# covert from ret_tensors to calculator results dict
|
| 457 |
+
self.results = {}
|
| 458 |
+
scalar_tensors = set(["energy"])
|
| 459 |
+
results_store_ensemble = set(["energy", "forces", "stress", "dipole"])
|
| 460 |
+
for results_key, ret_key, unit_conv in [
|
| 461 |
+
("energy", "energy", self.energy_units_to_eV),
|
| 462 |
+
("node_energy", "node_energy", self.energy_units_to_eV),
|
| 463 |
+
("forces", "forces", self.energy_units_to_eV / self.length_units_to_A),
|
| 464 |
+
("stress", "stress", self.energy_units_to_eV / self.length_units_to_A**3),
|
| 465 |
+
(
|
| 466 |
+
"stresses",
|
| 467 |
+
"atomic_stresses",
|
| 468 |
+
self.energy_units_to_eV / self.length_units_to_A**3,
|
| 469 |
+
),
|
| 470 |
+
(
|
| 471 |
+
"virials",
|
| 472 |
+
"atomic_virials",
|
| 473 |
+
self.energy_units_to_eV / self.length_units_to_A**3,
|
| 474 |
+
),
|
| 475 |
+
("dipole", "dipole", 1.0),
|
| 476 |
+
("charges", "charges", 1.0),
|
| 477 |
+
("polarizability", "polarizability", 1.0),
|
| 478 |
+
("polarizability_sh", "polarizability_sh", 1.0),
|
| 479 |
+
]:
|
| 480 |
+
if ret_tensors.get(ret_key) is not None:
|
| 481 |
+
data = torch.mean(ret_tensors[ret_key], dim=0).cpu()
|
| 482 |
+
if ret_key in scalar_tensors:
|
| 483 |
+
data = data.item()
|
| 484 |
+
else:
|
| 485 |
+
data = data.numpy()
|
| 486 |
+
self.results[results_key] = data * unit_conv
|
| 487 |
+
|
| 488 |
+
if self.num_models > 1 and results_key in results_store_ensemble:
|
| 489 |
+
data = ret_tensors[results_key].cpu().numpy()
|
| 490 |
+
data *= unit_conv
|
| 491 |
+
self.results[results_key + "_comm"] = data
|
| 492 |
+
|
| 493 |
+
data = torch.var(
|
| 494 |
+
ret_tensors[results_key], dim=0, unbiased=False
|
| 495 |
+
).cpu()
|
| 496 |
+
if ret_key in scalar_tensors:
|
| 497 |
+
data = data.item()
|
| 498 |
+
else:
|
| 499 |
+
data = data.numpy()
|
| 500 |
+
data *= unit_conv
|
| 501 |
+
self.results[results_key + "_var"] = data
|
| 502 |
+
|
| 503 |
+
# special cases
|
| 504 |
+
if self.results.get("energy") is not None:
|
| 505 |
+
self.results["free_energy"] = self.results["energy"]
|
| 506 |
+
if self.results.get("node_energy") is not None:
|
| 507 |
+
self.results["energies"] = self.results["node_energy"].copy()
|
| 508 |
+
self.results["node_energy"] -= node_e0
|
| 509 |
+
if self.results.get("stress") is not None:
|
| 510 |
+
self.results["stress"] = full_3x3_to_voigt_6_stress(self.results["stress"])
|
| 511 |
+
if self.results.get("stresses") is not None:
|
| 512 |
+
self.results["stresses"] = np.asarray(
|
| 513 |
+
[
|
| 514 |
+
full_3x3_to_voigt_6_stress(stress)
|
| 515 |
+
for stress in self.results["stresses"]
|
| 516 |
+
]
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
def get_dielectric_derivatives(self, atoms=None):
|
| 520 |
+
if atoms is None and self.atoms is None:
|
| 521 |
+
raise ValueError("atoms not set")
|
| 522 |
+
if atoms is None:
|
| 523 |
+
atoms = self.atoms
|
| 524 |
+
if self.model_type not in ["DipoleMACE", "DipolePolarizabilityMACE"]:
|
| 525 |
+
raise NotImplementedError(
|
| 526 |
+
"Only implemented for DipoleMACE or DipolePolarizabilityMACE models"
|
| 527 |
+
)
|
| 528 |
+
batch = self._atoms_to_batch(atoms)
|
| 529 |
+
outputs = [
|
| 530 |
+
model(
|
| 531 |
+
self._clone_batch(batch).to_dict(),
|
| 532 |
+
compute_dielectric_derivatives=True,
|
| 533 |
+
training=self.use_compile,
|
| 534 |
+
)
|
| 535 |
+
for model in self.models
|
| 536 |
+
]
|
| 537 |
+
dipole_derivatives = [
|
| 538 |
+
output["dmu_dr"].clone().detach().cpu().numpy() for output in outputs
|
| 539 |
+
]
|
| 540 |
+
if self.models[0].use_polarizability:
|
| 541 |
+
polarizability_derivatives = [
|
| 542 |
+
output["dalpha_dr"].clone().detach().cpu().numpy() for output in outputs
|
| 543 |
+
]
|
| 544 |
+
if self.num_models == 1:
|
| 545 |
+
dipole_derivatives = dipole_derivatives[0]
|
| 546 |
+
polarizability_derivatives = polarizability_derivatives[0]
|
| 547 |
+
del outputs, batch, atoms
|
| 548 |
+
return dipole_derivatives, polarizability_derivatives
|
| 549 |
+
if self.num_models == 1:
|
| 550 |
+
return dipole_derivatives[0]
|
| 551 |
+
del outputs, batch, atoms
|
| 552 |
+
return dipole_derivatives
|
| 553 |
+
|
| 554 |
+
def get_hessian(self, atoms=None):
|
| 555 |
+
if atoms is None and self.atoms is None:
|
| 556 |
+
raise ValueError("atoms not set")
|
| 557 |
+
if atoms is None:
|
| 558 |
+
atoms = self.atoms
|
| 559 |
+
if self.model_type != "MACE":
|
| 560 |
+
raise NotImplementedError("Only implemented for MACE models")
|
| 561 |
+
batch = self._atoms_to_batch(atoms)
|
| 562 |
+
hessians = [
|
| 563 |
+
model(
|
| 564 |
+
self._clone_batch(batch).to_dict(),
|
| 565 |
+
compute_hessian=True,
|
| 566 |
+
compute_stress=False,
|
| 567 |
+
training=self.use_compile,
|
| 568 |
+
)["hessian"]
|
| 569 |
+
for model in self.models
|
| 570 |
+
]
|
| 571 |
+
hessians = [hessian.detach().cpu().numpy() for hessian in hessians]
|
| 572 |
+
if self.num_models == 1:
|
| 573 |
+
return hessians[0]
|
| 574 |
+
return hessians
|
| 575 |
+
|
| 576 |
+
def get_descriptors(self, atoms=None, invariants_only=True, num_layers=-1):
|
| 577 |
+
"""Extracts the descriptors from MACE model.
|
| 578 |
+
:param atoms: ase.Atoms object
|
| 579 |
+
:param invariants_only: bool, if True only the invariant descriptors are returned
|
| 580 |
+
:param num_layers: int, number of layers to extract descriptors from, if -1 all layers are used
|
| 581 |
+
:return: np.ndarray (num_atoms, num_interactions, invariant_features) of invariant descriptors if num_models is 1 or list[np.ndarray] otherwise
|
| 582 |
+
"""
|
| 583 |
+
if atoms is None and self.atoms is None:
|
| 584 |
+
raise ValueError("atoms not set")
|
| 585 |
+
if atoms is None:
|
| 586 |
+
atoms = self.atoms
|
| 587 |
+
if self.model_type != "MACE":
|
| 588 |
+
raise NotImplementedError("Only implemented for MACE models")
|
| 589 |
+
num_interactions = int(self.models[0].num_interactions)
|
| 590 |
+
if num_layers == -1:
|
| 591 |
+
num_layers = num_interactions
|
| 592 |
+
batch = self._atoms_to_batch(atoms)
|
| 593 |
+
descriptors = [model(batch.to_dict())["node_feats"] for model in self.models]
|
| 594 |
+
|
| 595 |
+
irreps_out = o3.Irreps(str(self.models[0].products[0].linear.irreps_out))
|
| 596 |
+
l_max = irreps_out.lmax
|
| 597 |
+
num_invariant_features = irreps_out.dim // (l_max + 1) ** 2
|
| 598 |
+
per_layer_features = [irreps_out.dim for _ in range(num_interactions)]
|
| 599 |
+
per_layer_features[-1] = (
|
| 600 |
+
num_invariant_features # Equivariant features not created for the last layer
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
if invariants_only:
|
| 604 |
+
descriptors = [
|
| 605 |
+
extract_invariant(
|
| 606 |
+
descriptor,
|
| 607 |
+
num_layers=num_layers,
|
| 608 |
+
num_features=num_invariant_features,
|
| 609 |
+
l_max=l_max,
|
| 610 |
+
)
|
| 611 |
+
for descriptor in descriptors
|
| 612 |
+
]
|
| 613 |
+
to_keep = np.sum(per_layer_features[:num_layers])
|
| 614 |
+
descriptors = [
|
| 615 |
+
descriptor[:, :to_keep].detach().cpu().numpy() for descriptor in descriptors
|
| 616 |
+
]
|
| 617 |
+
|
| 618 |
+
if self.num_models == 1:
|
| 619 |
+
return descriptors[0]
|
| 620 |
+
return descriptors
|
models/mace/mace/cli/__init__.py
ADDED
|
File without changes
|
models/mace/mace/cli/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (181 Bytes). View file
|
|
|
models/mace/mace/cli/__pycache__/convert_cueq_e3nn.cpython-310.pyc
ADDED
|
Binary file (6.79 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/convert_e3nn_cueq.cpython-310.pyc
ADDED
|
Binary file (6.97 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/convert_e3nn_oeq.cpython-310.pyc
ADDED
|
Binary file (2.03 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/convert_oeq_e3nn.cpython-310.pyc
ADDED
|
Binary file (1.88 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/eval_configs.cpython-310.pyc
ADDED
|
Binary file (7.5 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/fine_tuning_select.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/preprocess_data.cpython-310.pyc
ADDED
|
Binary file (8.12 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_calc.cpython-310.pyc
ADDED
|
Binary file (22.1 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_eval.cpython-310.pyc
ADDED
|
Binary file (9.29 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_eval_copy.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_eval_foundation.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_foundation.cpython-310.pyc
ADDED
|
Binary file (8.59 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_inference_speed.cpython-310.pyc
ADDED
|
Binary file (8.97 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/run_jonas_calc.cpython-310.pyc
ADDED
|
Binary file (825 Bytes). View file
|
|
|
models/mace/mace/cli/__pycache__/run_train.cpython-310.pyc
ADDED
|
Binary file (29.5 kB). View file
|
|
|
models/mace/mace/cli/__pycache__/visualise_train.cpython-310.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
models/mace/mace/cli/active_learning_md.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Demonstrates active learning molecular dynamics with constant temperature."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import ase.io
|
| 8 |
+
import numpy as np
|
| 9 |
+
from ase import units
|
| 10 |
+
from ase.md.langevin import Langevin
|
| 11 |
+
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
|
| 12 |
+
|
| 13 |
+
from mace.calculators.mace import MACECalculator
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def parse_args() -> argparse.Namespace:
|
| 17 |
+
parser = argparse.ArgumentParser(
|
| 18 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument("--config", help="path to XYZ configurations", required=True)
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
"--config_index", help="index of configuration", type=int, default=-1
|
| 23 |
+
)
|
| 24 |
+
parser.add_argument(
|
| 25 |
+
"--error_threshold", help="error threshold", type=float, default=0.1
|
| 26 |
+
)
|
| 27 |
+
parser.add_argument("--temperature_K", help="temperature", type=float, default=300)
|
| 28 |
+
parser.add_argument("--friction", help="friction", type=float, default=0.01)
|
| 29 |
+
parser.add_argument("--timestep", help="timestep", type=float, default=1)
|
| 30 |
+
parser.add_argument("--nsteps", help="number of steps", type=int, default=1000)
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--nprint", help="number of steps between prints", type=int, default=10
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--nsave", help="number of steps between saves", type=int, default=10
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--ncheckerror", help="number of steps between saves", type=int, default=10
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--model",
|
| 43 |
+
help="path to model. Use wildcards to add multiple models as committee eg "
|
| 44 |
+
"(`mace_*.model` to load mace_1.model, mace_2.model) ",
|
| 45 |
+
required=True,
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument("--output", help="output path", required=True)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--device",
|
| 50 |
+
help="select device",
|
| 51 |
+
type=str,
|
| 52 |
+
choices=["cpu", "cuda"],
|
| 53 |
+
default="cuda",
|
| 54 |
+
)
|
| 55 |
+
parser.add_argument(
|
| 56 |
+
"--default_dtype",
|
| 57 |
+
help="set default dtype",
|
| 58 |
+
type=str,
|
| 59 |
+
choices=["float32", "float64"],
|
| 60 |
+
default="float64",
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--compute_stress",
|
| 64 |
+
help="compute stress",
|
| 65 |
+
action="store_true",
|
| 66 |
+
default=False,
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--info_prefix",
|
| 70 |
+
help="prefix for energy, forces and stress keys",
|
| 71 |
+
type=str,
|
| 72 |
+
default="MACE_",
|
| 73 |
+
)
|
| 74 |
+
return parser.parse_args()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def printenergy(dyn, start_time=None): # store a reference to atoms in the definition.
|
| 78 |
+
"""Function to print the potential, kinetic and total energy."""
|
| 79 |
+
a = dyn.atoms
|
| 80 |
+
epot = a.get_potential_energy() / len(a)
|
| 81 |
+
ekin = a.get_kinetic_energy() / len(a)
|
| 82 |
+
if start_time is None:
|
| 83 |
+
elapsed_time = 0
|
| 84 |
+
else:
|
| 85 |
+
elapsed_time = time.time() - start_time
|
| 86 |
+
forces_var = np.var(a.calc.results["forces_comm"], axis=0)
|
| 87 |
+
print(
|
| 88 |
+
"%.1fs: Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) " # pylint: disable=C0209
|
| 89 |
+
"Etot = %.3feV t=%.1ffs Eerr = %.3feV Ferr = %.3feV/A"
|
| 90 |
+
% (
|
| 91 |
+
elapsed_time,
|
| 92 |
+
epot,
|
| 93 |
+
ekin,
|
| 94 |
+
ekin / (1.5 * units.kB),
|
| 95 |
+
epot + ekin,
|
| 96 |
+
dyn.get_time() / units.fs,
|
| 97 |
+
a.calc.results["energy_var"],
|
| 98 |
+
np.max(np.linalg.norm(forces_var, axis=1)),
|
| 99 |
+
),
|
| 100 |
+
flush=True,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def save_config(dyn, fname):
|
| 105 |
+
atomsi = dyn.atoms
|
| 106 |
+
ens = atomsi.get_potential_energy()
|
| 107 |
+
frcs = atomsi.get_forces()
|
| 108 |
+
|
| 109 |
+
atomsi.info.update(
|
| 110 |
+
{
|
| 111 |
+
"mlff_energy": ens,
|
| 112 |
+
"time": np.round(dyn.get_time() / units.fs, 5),
|
| 113 |
+
"mlff_energy_var": atomsi.calc.results["energy_var"],
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
atomsi.arrays.update(
|
| 117 |
+
{
|
| 118 |
+
"mlff_forces": frcs,
|
| 119 |
+
"mlff_forces_var": np.var(atomsi.calc.results["forces_comm"], axis=0),
|
| 120 |
+
}
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
ase.io.write(fname, atomsi, append=True)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def stop_error(dyn, threshold, reg=0.2):
|
| 127 |
+
atomsi = dyn.atoms
|
| 128 |
+
force_var = np.var(atomsi.calc.results["forces_comm"], axis=0)
|
| 129 |
+
force = atomsi.get_forces()
|
| 130 |
+
ferr = np.sqrt(np.sum(force_var, axis=1))
|
| 131 |
+
ferr_rel = ferr / (np.linalg.norm(force, axis=1) + reg)
|
| 132 |
+
|
| 133 |
+
if np.max(ferr_rel) > threshold:
|
| 134 |
+
print(
|
| 135 |
+
"Error too large {:.3}. Stopping t={:.2} fs.".format( # pylint: disable=C0209
|
| 136 |
+
np.max(ferr_rel), dyn.get_time() / units.fs
|
| 137 |
+
),
|
| 138 |
+
flush=True,
|
| 139 |
+
)
|
| 140 |
+
dyn.max_steps = 0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def main() -> None:
|
| 144 |
+
args = parse_args()
|
| 145 |
+
run(args)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def run(args: argparse.Namespace) -> None:
|
| 149 |
+
mace_fname = args.model
|
| 150 |
+
atoms_fname = args.config
|
| 151 |
+
atoms_index = args.config_index
|
| 152 |
+
|
| 153 |
+
mace_calc = MACECalculator(
|
| 154 |
+
model_paths=mace_fname,
|
| 155 |
+
device=args.device,
|
| 156 |
+
default_dtype=args.default_dtype,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
NSTEPS = args.nsteps
|
| 160 |
+
|
| 161 |
+
if os.path.exists(args.output):
|
| 162 |
+
print("Trajectory exists. Continuing from last step.")
|
| 163 |
+
atoms = ase.io.read(args.output, index=-1)
|
| 164 |
+
len_save = len(ase.io.read(args.output, ":"))
|
| 165 |
+
print("Last step: ", atoms.info["time"], "Number of configs: ", len_save)
|
| 166 |
+
NSTEPS -= len_save * args.nsave
|
| 167 |
+
else:
|
| 168 |
+
atoms = ase.io.read(atoms_fname, index=atoms_index)
|
| 169 |
+
MaxwellBoltzmannDistribution(atoms, temperature_K=args.temperature_K)
|
| 170 |
+
|
| 171 |
+
atoms.calc = mace_calc
|
| 172 |
+
|
| 173 |
+
# We want to run MD with constant energy using the Langevin algorithm
|
| 174 |
+
# with a time step of 5 fs, the temperature T and the friction
|
| 175 |
+
# coefficient to 0.02 atomic units.
|
| 176 |
+
dyn = Langevin(
|
| 177 |
+
atoms=atoms,
|
| 178 |
+
timestep=args.timestep * units.fs,
|
| 179 |
+
temperature_K=args.temperature_K,
|
| 180 |
+
friction=args.friction,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
dyn.attach(printenergy, interval=args.nsave, dyn=dyn, start_time=time.time())
|
| 184 |
+
dyn.attach(save_config, interval=args.nsave, dyn=dyn, fname=args.output)
|
| 185 |
+
dyn.attach(
|
| 186 |
+
stop_error, interval=args.ncheckerror, dyn=dyn, threshold=args.error_threshold
|
| 187 |
+
)
|
| 188 |
+
# Now run the dynamics
|
| 189 |
+
dyn.run(NSTEPS)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
main()
|
models/mace/mace/cli/convert_cueq_e3nn.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from typing import Dict, List, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from e3nn import o3
|
| 9 |
+
|
| 10 |
+
from mace.tools.cg import O3_e3nn
|
| 11 |
+
from mace.tools.cg_cueq_tools import symmetric_contraction_proj
|
| 12 |
+
from mace.tools.scripts_utils import extract_config_mace_model
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import cuequivariance as cue
|
| 16 |
+
|
| 17 |
+
CUEQQ_AVAILABLE = True
|
| 18 |
+
except (ImportError, ModuleNotFoundError):
|
| 19 |
+
CUEQQ_AVAILABLE = False
|
| 20 |
+
cue = None
|
| 21 |
+
|
| 22 |
+
SizeLike = Union[torch.Size, List[int]]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def shapes_match_up_to_unsqueeze(a: SizeLike, b: SizeLike) -> bool:
|
| 26 |
+
if isinstance(a, torch.Tensor):
|
| 27 |
+
a = a.shape
|
| 28 |
+
if isinstance(b, torch.Tensor):
|
| 29 |
+
b = b.shape
|
| 30 |
+
|
| 31 |
+
def drop(s):
|
| 32 |
+
return tuple(d for d in s if d != 1)
|
| 33 |
+
|
| 34 |
+
return drop(a) == drop(b)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def reshape_like(src: torch.Tensor, ref_shape: torch.Size) -> torch.Tensor:
|
| 38 |
+
try:
|
| 39 |
+
return src.reshape(ref_shape)
|
| 40 |
+
except RuntimeError:
|
| 41 |
+
return src.clone().reshape(ref_shape)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_kmax_pairs(
|
| 45 |
+
num_product_irreps: int, correlation: int, num_layers: int
|
| 46 |
+
) -> List[Tuple[int, int]]:
|
| 47 |
+
"""Determine kmax pairs based on num_product_irreps and correlation"""
|
| 48 |
+
if correlation == 2:
|
| 49 |
+
kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)]
|
| 50 |
+
kmax_pairs = kmax_pairs + [[num_layers - 1, 0]]
|
| 51 |
+
return kmax_pairs
|
| 52 |
+
if correlation == 3:
|
| 53 |
+
kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)]
|
| 54 |
+
kmax_pairs = kmax_pairs + [[num_layers - 1, 0]]
|
| 55 |
+
return kmax_pairs
|
| 56 |
+
raise NotImplementedError(f"Correlation {correlation} not supported")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def transfer_symmetric_contractions(
|
| 60 |
+
source_dict: Dict[str, torch.Tensor],
|
| 61 |
+
target_dict: Dict[str, torch.Tensor],
|
| 62 |
+
num_product_irreps: int,
|
| 63 |
+
products: torch.nn.Module,
|
| 64 |
+
correlation: int,
|
| 65 |
+
num_layers: int,
|
| 66 |
+
use_reduced_cg: bool,
|
| 67 |
+
):
|
| 68 |
+
"""Transfer symmetric contraction weights from CuEq to E3nn format"""
|
| 69 |
+
kmax_pairs = get_kmax_pairs(num_product_irreps, correlation, num_layers)
|
| 70 |
+
suffixes = ["_max"] + [f".{i}" for i in range(correlation - 1)]
|
| 71 |
+
for i, kmax in kmax_pairs:
|
| 72 |
+
# Get the combined weight tensor from source
|
| 73 |
+
irreps_in = o3.Irreps(
|
| 74 |
+
irrep.ir for irrep in products[i].symmetric_contractions.irreps_in
|
| 75 |
+
)
|
| 76 |
+
irreps_out = o3.Irreps(
|
| 77 |
+
irrep.ir for irrep in products[i].symmetric_contractions.irreps_out
|
| 78 |
+
)
|
| 79 |
+
wm = source_dict[f"products.{i}.symmetric_contractions.weight"]
|
| 80 |
+
if use_reduced_cg:
|
| 81 |
+
_, proj = symmetric_contraction_proj(
|
| 82 |
+
cue.Irreps(O3_e3nn, str(irreps_in)),
|
| 83 |
+
cue.Irreps(O3_e3nn, str(irreps_out)),
|
| 84 |
+
list(range(1, correlation + 1)),
|
| 85 |
+
)
|
| 86 |
+
proj = np.linalg.pinv(proj)
|
| 87 |
+
proj = torch.tensor(proj, dtype=wm.dtype, device=wm.device)
|
| 88 |
+
wm = torch.einsum("zau,ab->zbu", wm, proj)
|
| 89 |
+
# Get split sizes based on target dimensions
|
| 90 |
+
splits = []
|
| 91 |
+
for k in range(kmax + 1):
|
| 92 |
+
for suffix in suffixes:
|
| 93 |
+
key = f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix}"
|
| 94 |
+
target_shape = target_dict[key].shape
|
| 95 |
+
splits.append(target_shape[1])
|
| 96 |
+
if (
|
| 97 |
+
target_dict.get(
|
| 98 |
+
f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix.replace('.', '_')}"
|
| 99 |
+
+ "_zeroed",
|
| 100 |
+
False,
|
| 101 |
+
)
|
| 102 |
+
and not use_reduced_cg
|
| 103 |
+
):
|
| 104 |
+
splits[-1] = 0
|
| 105 |
+
|
| 106 |
+
# Split the weights using the calculated sizes
|
| 107 |
+
weights_split = torch.split(wm, splits, dim=1)
|
| 108 |
+
|
| 109 |
+
# Assign back to target dictionary
|
| 110 |
+
idx = 0
|
| 111 |
+
for k in range(kmax + 1):
|
| 112 |
+
for suffix in suffixes:
|
| 113 |
+
key = f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix}"
|
| 114 |
+
if (
|
| 115 |
+
target_dict.get(
|
| 116 |
+
f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix.replace('.', '_')}_zeroed",
|
| 117 |
+
False,
|
| 118 |
+
)
|
| 119 |
+
and not use_reduced_cg
|
| 120 |
+
):
|
| 121 |
+
continue
|
| 122 |
+
target_dict[key] = (
|
| 123 |
+
weights_split[idx] if splits[idx] > 0 else target_dict[key]
|
| 124 |
+
)
|
| 125 |
+
idx += 1
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def transfer_weights(
|
| 129 |
+
source_model: torch.nn.Module,
|
| 130 |
+
target_model: torch.nn.Module,
|
| 131 |
+
num_product_irreps: int,
|
| 132 |
+
correlation: int,
|
| 133 |
+
num_layers: int,
|
| 134 |
+
use_reduced_cg: bool,
|
| 135 |
+
):
|
| 136 |
+
"""Transfer weights from CuEq to E3nn format"""
|
| 137 |
+
# Get state dicts
|
| 138 |
+
source_dict = source_model.state_dict()
|
| 139 |
+
target_dict = target_model.state_dict()
|
| 140 |
+
|
| 141 |
+
# Transfer symmetric contractions
|
| 142 |
+
products = target_model.products
|
| 143 |
+
transfer_symmetric_contractions(
|
| 144 |
+
source_dict,
|
| 145 |
+
target_dict,
|
| 146 |
+
num_product_irreps,
|
| 147 |
+
products,
|
| 148 |
+
correlation,
|
| 149 |
+
num_layers,
|
| 150 |
+
use_reduced_cg,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Transfer remaining matching keys
|
| 154 |
+
transferred_keys = set()
|
| 155 |
+
remaining_keys = (
|
| 156 |
+
set(source_dict.keys()) & set(target_dict.keys()) - transferred_keys
|
| 157 |
+
)
|
| 158 |
+
remaining_keys = {k for k in remaining_keys if "symmetric_contraction" not in k}
|
| 159 |
+
|
| 160 |
+
if remaining_keys:
|
| 161 |
+
for key in remaining_keys:
|
| 162 |
+
src = source_dict[key]
|
| 163 |
+
tgt = target_dict[key]
|
| 164 |
+
if source_dict[key].shape == target_dict[key].shape:
|
| 165 |
+
logging.debug(f"Transferring additional key: {key}")
|
| 166 |
+
target_dict[key] = source_dict[key]
|
| 167 |
+
elif shapes_match_up_to_unsqueeze(src.shape, tgt.shape):
|
| 168 |
+
logging.debug(
|
| 169 |
+
f"Transferring key {key} after adapting shape "
|
| 170 |
+
f"{tuple(src.shape)} → {tuple(tgt.shape)}"
|
| 171 |
+
)
|
| 172 |
+
target_dict[key] = reshape_like(src, tgt.shape)
|
| 173 |
+
else:
|
| 174 |
+
logging.warning(
|
| 175 |
+
f"Shape mismatch for key {key}: "
|
| 176 |
+
f"source {source_dict[key].shape} vs target {target_dict[key].shape}"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Transfer avg_num_neighbors
|
| 180 |
+
for i in range(num_layers):
|
| 181 |
+
target_model.interactions[i].avg_num_neighbors = source_model.interactions[
|
| 182 |
+
i
|
| 183 |
+
].avg_num_neighbors
|
| 184 |
+
|
| 185 |
+
# Load state dict into target model
|
| 186 |
+
target_model.load_state_dict(target_dict)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def run(input_model, output_model="_e3nn.model", device="cpu", return_model=True):
|
| 190 |
+
|
| 191 |
+
# Load CuEq model
|
| 192 |
+
if isinstance(input_model, str):
|
| 193 |
+
source_model = torch.load(input_model, map_location=device)
|
| 194 |
+
else:
|
| 195 |
+
source_model = input_model
|
| 196 |
+
default_dtype = next(source_model.parameters()).dtype
|
| 197 |
+
torch.set_default_dtype(default_dtype)
|
| 198 |
+
# Extract configuration
|
| 199 |
+
config = extract_config_mace_model(source_model)
|
| 200 |
+
|
| 201 |
+
# Get max_L and correlation from config
|
| 202 |
+
num_product_irreps = len(config["hidden_irreps"].slices()) - 1
|
| 203 |
+
correlation = config["correlation"]
|
| 204 |
+
use_reduced_cg = config.get("use_reduced_cg", True)
|
| 205 |
+
|
| 206 |
+
# Remove CuEq config
|
| 207 |
+
config.pop("cueq_config", None)
|
| 208 |
+
|
| 209 |
+
# Create new model without CuEq config
|
| 210 |
+
logging.info("Creating new model without CuEq settings")
|
| 211 |
+
target_model = source_model.__class__(**config)
|
| 212 |
+
|
| 213 |
+
# Transfer weights with proper remapping
|
| 214 |
+
num_layers = config["num_interactions"]
|
| 215 |
+
transfer_weights(
|
| 216 |
+
source_model,
|
| 217 |
+
target_model,
|
| 218 |
+
num_product_irreps,
|
| 219 |
+
correlation,
|
| 220 |
+
num_layers,
|
| 221 |
+
use_reduced_cg,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if return_model:
|
| 225 |
+
return target_model
|
| 226 |
+
|
| 227 |
+
# Save model
|
| 228 |
+
if isinstance(input_model, str):
|
| 229 |
+
base = os.path.splitext(input_model)[0]
|
| 230 |
+
output_model = f"{base}.{output_model}"
|
| 231 |
+
logging.warning(f"Saving E3nn model to {output_model}")
|
| 232 |
+
torch.save(target_model, output_model)
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def main():
|
| 237 |
+
parser = argparse.ArgumentParser()
|
| 238 |
+
parser.add_argument("input_model", help="Path to input CuEq model")
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--output_model", help="Path to output E3nn model", default="e3nn_model.pt"
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument("--device", default="cpu", help="Device to use")
|
| 243 |
+
parser.add_argument(
|
| 244 |
+
"--return_model",
|
| 245 |
+
action="store_false",
|
| 246 |
+
help="Return model instead of saving to file",
|
| 247 |
+
)
|
| 248 |
+
args = parser.parse_args()
|
| 249 |
+
|
| 250 |
+
run(
|
| 251 |
+
input_model=args.input_model,
|
| 252 |
+
output_model=args.output_model,
|
| 253 |
+
device=args.device,
|
| 254 |
+
return_model=args.return_model,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
main()
|
models/mace/mace/cli/convert_device.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from argparse import ArgumentParser
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def main():
|
| 7 |
+
parser = ArgumentParser()
|
| 8 |
+
parser.add_argument(
|
| 9 |
+
"--target_device",
|
| 10 |
+
"-t",
|
| 11 |
+
help="device to convert to, usually 'cpu' or 'cuda'",
|
| 12 |
+
default="cpu",
|
| 13 |
+
)
|
| 14 |
+
parser.add_argument(
|
| 15 |
+
"--output_file",
|
| 16 |
+
"-o",
|
| 17 |
+
help="name for output model, defaults to model_file.target_device",
|
| 18 |
+
)
|
| 19 |
+
parser.add_argument("model_file", help="input model file path")
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
|
| 22 |
+
if args.output_file is None:
|
| 23 |
+
args.output_file = args.model_file + "." + args.target_device
|
| 24 |
+
|
| 25 |
+
model = torch.load(args.model_file, weights_only=False)
|
| 26 |
+
model.to(args.target_device)
|
| 27 |
+
torch.save(model, args.output_file)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
main()
|
models/mace/mace/cli/convert_e3nn_cueq.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 9 |
+
from mace.modules.wrapper_ops import CuEquivarianceConfig
|
| 10 |
+
from mace.tools.cg import O3_e3nn
|
| 11 |
+
from mace.tools.cg_cueq_tools import symmetric_contraction_proj
|
| 12 |
+
from mace.tools.scripts_utils import extract_config_mace_model
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import cuequivariance as cue
|
| 16 |
+
|
| 17 |
+
CUEQQ_AVAILABLE = True
|
| 18 |
+
except (ImportError, ModuleNotFoundError):
|
| 19 |
+
CUEQQ_AVAILABLE = False
|
| 20 |
+
cue = None
|
| 21 |
+
|
| 22 |
+
SizeLike = Union[torch.Size, List[int]]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def shapes_match_up_to_unsqueeze(a: SizeLike, b: SizeLike) -> bool:
|
| 26 |
+
if isinstance(a, torch.Tensor):
|
| 27 |
+
a = a.shape
|
| 28 |
+
if isinstance(b, torch.Tensor):
|
| 29 |
+
b = b.shape
|
| 30 |
+
|
| 31 |
+
def drop(s):
|
| 32 |
+
return tuple(d for d in s if d != 1)
|
| 33 |
+
|
| 34 |
+
return drop(a) == drop(b)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def reshape_like(src: torch.Tensor, ref_shape: torch.Size) -> torch.Tensor:
|
| 38 |
+
try:
|
| 39 |
+
return src.reshape(ref_shape)
|
| 40 |
+
except RuntimeError:
|
| 41 |
+
return src.clone().reshape(ref_shape)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_kmax_pairs(
|
| 45 |
+
num_product_irreps: int, correlation: int, num_layers: int
|
| 46 |
+
) -> List[Tuple[int, int]]:
|
| 47 |
+
"""Determine kmax pairs based on num_product_irreps and correlation"""
|
| 48 |
+
if correlation == 2:
|
| 49 |
+
kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)]
|
| 50 |
+
kmax_pairs = kmax_pairs + [[num_layers - 1, 0]]
|
| 51 |
+
return kmax_pairs
|
| 52 |
+
if correlation == 3:
|
| 53 |
+
kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)]
|
| 54 |
+
kmax_pairs = kmax_pairs + [[num_layers - 1, 0]]
|
| 55 |
+
return kmax_pairs
|
| 56 |
+
raise NotImplementedError(f"Correlation {correlation} not supported")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def transfer_symmetric_contractions(
|
| 60 |
+
source_dict: Dict[str, torch.Tensor],
|
| 61 |
+
target_dict: Dict[str, torch.Tensor],
|
| 62 |
+
num_product_irreps: int,
|
| 63 |
+
products: torch.nn.Module,
|
| 64 |
+
correlation: int,
|
| 65 |
+
num_layers: int,
|
| 66 |
+
use_reduced_cg: bool,
|
| 67 |
+
):
|
| 68 |
+
"""Transfer symmetric contraction weights"""
|
| 69 |
+
kmax_pairs = get_kmax_pairs(num_product_irreps, correlation, num_layers)
|
| 70 |
+
suffixes = ["_max"] + [f".{i}" for i in range(correlation - 1)]
|
| 71 |
+
for i, kmax in kmax_pairs:
|
| 72 |
+
irreps_in = o3.Irreps(
|
| 73 |
+
irrep.ir for irrep in products[i].symmetric_contractions.irreps_in
|
| 74 |
+
)
|
| 75 |
+
irreps_out = o3.Irreps(
|
| 76 |
+
irrep.ir for irrep in products[i].symmetric_contractions.irreps_out
|
| 77 |
+
)
|
| 78 |
+
if use_reduced_cg:
|
| 79 |
+
wm = torch.concatenate(
|
| 80 |
+
[
|
| 81 |
+
source_dict[
|
| 82 |
+
f"products.{i}.symmetric_contractions.contractions.{k}.weights{j}"
|
| 83 |
+
]
|
| 84 |
+
for k in range(kmax + 1)
|
| 85 |
+
for j in suffixes
|
| 86 |
+
],
|
| 87 |
+
dim=1,
|
| 88 |
+
)
|
| 89 |
+
else:
|
| 90 |
+
wm = torch.concatenate(
|
| 91 |
+
[
|
| 92 |
+
source_dict[
|
| 93 |
+
f"products.{i}.symmetric_contractions.contractions.{k}.weights{j}"
|
| 94 |
+
]
|
| 95 |
+
for k in range(kmax + 1)
|
| 96 |
+
for j in suffixes
|
| 97 |
+
if not source_dict.get(
|
| 98 |
+
f"products.{i}.symmetric_contractions.contractions.{k}.weights{j.replace('.', '_')}_zeroed",
|
| 99 |
+
False,
|
| 100 |
+
)
|
| 101 |
+
],
|
| 102 |
+
dim=1,
|
| 103 |
+
)
|
| 104 |
+
if use_reduced_cg:
|
| 105 |
+
_, proj = symmetric_contraction_proj(
|
| 106 |
+
cue.Irreps(O3_e3nn, str(irreps_in)),
|
| 107 |
+
cue.Irreps(O3_e3nn, str(irreps_out)),
|
| 108 |
+
list(range(1, correlation + 1)),
|
| 109 |
+
)
|
| 110 |
+
proj = torch.tensor(proj, dtype=wm.dtype, device=wm.device)
|
| 111 |
+
wm = torch.einsum("zau,ab->zbu", wm, proj)
|
| 112 |
+
target_dict[f"products.{i}.symmetric_contractions.weight"] = wm
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def transfer_weights(
|
| 116 |
+
source_model: torch.nn.Module,
|
| 117 |
+
target_model: torch.nn.Module,
|
| 118 |
+
num_product_irreps: int,
|
| 119 |
+
correlation: int,
|
| 120 |
+
num_layers: int,
|
| 121 |
+
use_reduced_cg: bool,
|
| 122 |
+
):
|
| 123 |
+
"""Transfer weights with proper remapping"""
|
| 124 |
+
# Get source state dict
|
| 125 |
+
source_dict = source_model.state_dict()
|
| 126 |
+
target_dict = target_model.state_dict()
|
| 127 |
+
|
| 128 |
+
products = source_model.products
|
| 129 |
+
# Transfer symmetric contractions
|
| 130 |
+
transfer_symmetric_contractions(
|
| 131 |
+
source_dict,
|
| 132 |
+
target_dict,
|
| 133 |
+
num_product_irreps,
|
| 134 |
+
products,
|
| 135 |
+
correlation,
|
| 136 |
+
num_layers,
|
| 137 |
+
use_reduced_cg,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
transferred_keys = set()
|
| 141 |
+
remaining_keys = (
|
| 142 |
+
set(source_dict.keys()) & set(target_dict.keys()) - transferred_keys
|
| 143 |
+
)
|
| 144 |
+
remaining_keys = {k for k in remaining_keys if "symmetric_contraction" not in k}
|
| 145 |
+
if remaining_keys:
|
| 146 |
+
for key in remaining_keys:
|
| 147 |
+
src = source_dict[key]
|
| 148 |
+
tgt = target_dict[key]
|
| 149 |
+
if source_dict[key].shape == target_dict[key].shape:
|
| 150 |
+
logging.debug(f"Transferring additional key: {key}")
|
| 151 |
+
target_dict[key] = source_dict[key]
|
| 152 |
+
elif shapes_match_up_to_unsqueeze(src.shape, tgt.shape):
|
| 153 |
+
logging.debug(
|
| 154 |
+
f"Transferring key {key} after adapting shape "
|
| 155 |
+
f"{tuple(src.shape)} → {tuple(tgt.shape)} -> {reshape_like(src, tgt.shape).shape}"
|
| 156 |
+
)
|
| 157 |
+
target_dict[key] = reshape_like(src, tgt.shape)
|
| 158 |
+
else:
|
| 159 |
+
logging.debug(
|
| 160 |
+
f"Shape mismatch for key {key}: "
|
| 161 |
+
f"source {source_dict[key].shape} vs target {target_dict[key].shape}"
|
| 162 |
+
)
|
| 163 |
+
# Transfer avg_num_neighbors
|
| 164 |
+
for i in range(num_layers):
|
| 165 |
+
target_model.interactions[i].avg_num_neighbors = source_model.interactions[
|
| 166 |
+
i
|
| 167 |
+
].avg_num_neighbors
|
| 168 |
+
|
| 169 |
+
# Load state dict into target model
|
| 170 |
+
target_model.load_state_dict(target_dict)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def run(
|
| 174 |
+
input_model,
|
| 175 |
+
output_model="_cueq.model",
|
| 176 |
+
device="cpu",
|
| 177 |
+
return_model=True,
|
| 178 |
+
):
|
| 179 |
+
# Setup logging
|
| 180 |
+
|
| 181 |
+
# Load original model
|
| 182 |
+
# logging.warning(f"Loading model")
|
| 183 |
+
# check if input_model is a path or a model
|
| 184 |
+
if isinstance(input_model, str):
|
| 185 |
+
source_model = torch.load(input_model, map_location=device)
|
| 186 |
+
else:
|
| 187 |
+
source_model = input_model
|
| 188 |
+
default_dtype = next(source_model.parameters()).dtype
|
| 189 |
+
torch.set_default_dtype(default_dtype)
|
| 190 |
+
# Extract configuration
|
| 191 |
+
config = extract_config_mace_model(source_model)
|
| 192 |
+
|
| 193 |
+
# Get max_L and correlation from config
|
| 194 |
+
num_product_irreps = len(config["hidden_irreps"].slices()) - 1
|
| 195 |
+
correlation = config["correlation"]
|
| 196 |
+
use_reduced_cg = config.get("use_reduced_cg", True)
|
| 197 |
+
|
| 198 |
+
# Add cuequivariance config
|
| 199 |
+
config["cueq_config"] = CuEquivarianceConfig(
|
| 200 |
+
enabled=True,
|
| 201 |
+
layout="ir_mul",
|
| 202 |
+
group="O3_e3nn",
|
| 203 |
+
optimize_all=True,
|
| 204 |
+
conv_fusion=(device == "cuda"),
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Create new model with cuequivariance config
|
| 208 |
+
logging.info("Creating new model with cuequivariance settings")
|
| 209 |
+
target_model = source_model.__class__(**config).to(device)
|
| 210 |
+
|
| 211 |
+
# Transfer weights with proper remapping
|
| 212 |
+
num_layers = config["num_interactions"]
|
| 213 |
+
transfer_weights(
|
| 214 |
+
source_model,
|
| 215 |
+
target_model,
|
| 216 |
+
num_product_irreps,
|
| 217 |
+
correlation,
|
| 218 |
+
num_layers,
|
| 219 |
+
use_reduced_cg,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
if return_model:
|
| 223 |
+
return target_model
|
| 224 |
+
|
| 225 |
+
if isinstance(input_model, str):
|
| 226 |
+
base = os.path.splitext(input_model)[0]
|
| 227 |
+
output_model = f"{base}.{output_model}"
|
| 228 |
+
logging.warning(f"Saving CuEq model to {output_model}")
|
| 229 |
+
torch.save(target_model, output_model)
|
| 230 |
+
return None
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def main():
|
| 234 |
+
parser = argparse.ArgumentParser()
|
| 235 |
+
parser.add_argument("input_model", help="Path to input MACE model")
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--output_model",
|
| 238 |
+
help="Path to output cuequivariance model",
|
| 239 |
+
default="cueq_model.pt",
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument("--device", default="cpu", help="Device to use")
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--return_model",
|
| 244 |
+
action="store_false",
|
| 245 |
+
help="Return model instead of saving to file",
|
| 246 |
+
)
|
| 247 |
+
args = parser.parse_args()
|
| 248 |
+
|
| 249 |
+
run(
|
| 250 |
+
input_model=args.input_model,
|
| 251 |
+
output_model=args.output_model,
|
| 252 |
+
device=args.device,
|
| 253 |
+
return_model=args.return_model,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
main()
|
models/mace/mace/cli/convert_e3nn_oeq.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from mace.modules.wrapper_ops import OEQConfig
|
| 8 |
+
from mace.tools.scripts_utils import extract_config_mace_model
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def run(
|
| 12 |
+
input_model,
|
| 13 |
+
output_model="_oeq.model",
|
| 14 |
+
device="cpu",
|
| 15 |
+
return_model=True,
|
| 16 |
+
):
|
| 17 |
+
# Setup logging
|
| 18 |
+
|
| 19 |
+
# Load original model
|
| 20 |
+
# logging.warning(f"Loading model")
|
| 21 |
+
# check if input_model is a path or a model
|
| 22 |
+
if isinstance(input_model, str):
|
| 23 |
+
source_model = torch.load(input_model, map_location=device)
|
| 24 |
+
else:
|
| 25 |
+
source_model = input_model
|
| 26 |
+
default_dtype = next(source_model.parameters()).dtype
|
| 27 |
+
torch.set_default_dtype(default_dtype)
|
| 28 |
+
|
| 29 |
+
config = extract_config_mace_model(source_model)
|
| 30 |
+
|
| 31 |
+
# Add OEQ config
|
| 32 |
+
config["oeq_config"] = OEQConfig(
|
| 33 |
+
enabled=False, optimize_all=True, conv_fusion="atomic"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Create new model with oeq config
|
| 37 |
+
logging.info("Creating new model with openequivariance settings")
|
| 38 |
+
target_model = source_model.__class__(**config).to(device)
|
| 39 |
+
source_dict = source_model.state_dict()
|
| 40 |
+
target_dict = target_model.state_dict()
|
| 41 |
+
|
| 42 |
+
for key in target_dict:
|
| 43 |
+
if ".conv_tp." not in key:
|
| 44 |
+
target_dict[key] = source_dict[key]
|
| 45 |
+
|
| 46 |
+
target_model.load_state_dict(target_dict)
|
| 47 |
+
|
| 48 |
+
for i in range(2):
|
| 49 |
+
target_model.interactions[i].avg_num_neighbors = source_model.interactions[
|
| 50 |
+
i
|
| 51 |
+
].avg_num_neighbors
|
| 52 |
+
|
| 53 |
+
if return_model:
|
| 54 |
+
return target_model
|
| 55 |
+
|
| 56 |
+
if isinstance(input_model, str):
|
| 57 |
+
base = os.path.splitext(input_model)[0]
|
| 58 |
+
output_model = f"{base}.{output_model}"
|
| 59 |
+
logging.warning(f"Saving OEQ model to {output_model}")
|
| 60 |
+
torch.save(target_model, output_model)
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def main():
|
| 65 |
+
parser = argparse.ArgumentParser()
|
| 66 |
+
parser.add_argument("input_model", help="Path to input MACE model")
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--output_model",
|
| 69 |
+
help="Path to output openequviariance model",
|
| 70 |
+
default="oeq_model.pt",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument("--device", default="cpu", help="Device to use")
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--return_model",
|
| 75 |
+
action="store_false",
|
| 76 |
+
help="Return model instead of saving to file",
|
| 77 |
+
)
|
| 78 |
+
args = parser.parse_args()
|
| 79 |
+
|
| 80 |
+
run(
|
| 81 |
+
input_model=args.input_model,
|
| 82 |
+
output_model=args.output_model,
|
| 83 |
+
device=args.device,
|
| 84 |
+
return_model=args.return_model,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
models/mace/mace/cli/convert_oeq_e3nn.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from mace.tools.scripts_utils import extract_config_mace_model
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def run(input_model, output_model="_e3nn.model", device="cpu", return_model=True):
|
| 11 |
+
# Load OEQ model
|
| 12 |
+
if isinstance(input_model, str):
|
| 13 |
+
source_model = torch.load(input_model, map_location=device)
|
| 14 |
+
else:
|
| 15 |
+
source_model = input_model
|
| 16 |
+
default_dtype = next(source_model.parameters()).dtype
|
| 17 |
+
torch.set_default_dtype(default_dtype)
|
| 18 |
+
# Extract configuration
|
| 19 |
+
config = extract_config_mace_model(source_model)
|
| 20 |
+
|
| 21 |
+
# Remove OEQ config
|
| 22 |
+
config.pop("oeq_config", None)
|
| 23 |
+
|
| 24 |
+
# Create new model without CuEq config
|
| 25 |
+
logging.info("Creating new model without OEQ settings")
|
| 26 |
+
target_model = source_model.__class__(**config).to(device)
|
| 27 |
+
|
| 28 |
+
source_dict = source_model.state_dict()
|
| 29 |
+
target_dict = target_model.state_dict()
|
| 30 |
+
|
| 31 |
+
for key in source_dict:
|
| 32 |
+
if ".conv_tp." not in key:
|
| 33 |
+
target_dict[key] = source_dict[key]
|
| 34 |
+
|
| 35 |
+
for i in range(2):
|
| 36 |
+
|
| 37 |
+
target_model.interactions[i].avg_num_neighbors = source_model.interactions[
|
| 38 |
+
i
|
| 39 |
+
].avg_num_neighbors
|
| 40 |
+
|
| 41 |
+
target_model.load_state_dict(target_dict)
|
| 42 |
+
|
| 43 |
+
if return_model:
|
| 44 |
+
return target_model
|
| 45 |
+
|
| 46 |
+
# Save model
|
| 47 |
+
if isinstance(input_model, str):
|
| 48 |
+
base = os.path.splitext(input_model)[0]
|
| 49 |
+
output_model = f"{base}.{output_model}"
|
| 50 |
+
logging.warning(f"Saving E3nn model to {output_model}")
|
| 51 |
+
torch.save(target_model, output_model)
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def main():
|
| 56 |
+
parser = argparse.ArgumentParser()
|
| 57 |
+
parser.add_argument("input_model", help="Path to input oeq model")
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--output_model", help="Path to output E3nn model", default="e3nn_model.pt"
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument("--device", default="cpu", help="Device to use")
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--return_model",
|
| 64 |
+
action="store_false",
|
| 65 |
+
help="Return model instead of saving to file",
|
| 66 |
+
)
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
|
| 69 |
+
run(
|
| 70 |
+
input_model=args.input_model,
|
| 71 |
+
output_model=args.output_model,
|
| 72 |
+
device=args.device,
|
| 73 |
+
return_model=args.return_model,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|
models/mace/mace/cli/create_lammps_model.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable=wrong-import-position
|
| 2 |
+
import argparse
|
| 3 |
+
import copy
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from e3nn.util import jit
|
| 10 |
+
|
| 11 |
+
from mace.calculators import LAMMPS_MACE
|
| 12 |
+
from mace.calculators.lammps_mliap_mace import LAMMPS_MLIAP_MACE
|
| 13 |
+
from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def parse_args():
|
| 17 |
+
parser = argparse.ArgumentParser(
|
| 18 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"model_path",
|
| 22 |
+
type=str,
|
| 23 |
+
help="Path to the model to be converted to LAMMPS",
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"--head",
|
| 27 |
+
type=str,
|
| 28 |
+
nargs="?",
|
| 29 |
+
help="Head of the model to be converted to LAMMPS",
|
| 30 |
+
default=None,
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"--dtype",
|
| 34 |
+
type=str,
|
| 35 |
+
nargs="?",
|
| 36 |
+
help="Data type of the model to be converted to LAMMPS",
|
| 37 |
+
default="float64",
|
| 38 |
+
)
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"--format",
|
| 41 |
+
type=str,
|
| 42 |
+
help="Old libtorch format, or new mliap format",
|
| 43 |
+
default="libtorch",
|
| 44 |
+
)
|
| 45 |
+
return parser.parse_args()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def select_head(model):
|
| 49 |
+
if hasattr(model, "heads"):
|
| 50 |
+
heads = model.heads
|
| 51 |
+
else:
|
| 52 |
+
heads = [None]
|
| 53 |
+
|
| 54 |
+
if len(heads) == 1:
|
| 55 |
+
print(f"Only one head found in the model: {heads[0]}. Skipping selection.")
|
| 56 |
+
return heads[0]
|
| 57 |
+
|
| 58 |
+
print("Available heads in the model:")
|
| 59 |
+
for i, head in enumerate(heads):
|
| 60 |
+
print(f"{i + 1}: {head}")
|
| 61 |
+
|
| 62 |
+
# Ask the user to select a head
|
| 63 |
+
selected = input(
|
| 64 |
+
f"Select a head by number (Defaulting to head: {len(heads)}, press Enter to accept): "
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if selected.isdigit() and 1 <= int(selected) <= len(heads):
|
| 68 |
+
return heads[int(selected) - 1]
|
| 69 |
+
if selected == "":
|
| 70 |
+
print("No head selected. Proceeding without specifying a head.")
|
| 71 |
+
return None
|
| 72 |
+
print(f"No valid selection made. Defaulting to the last head: {heads[-1]}")
|
| 73 |
+
return heads[-1]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
args = parse_args()
|
| 78 |
+
model_path = args.model_path # takes model name as command-line input
|
| 79 |
+
model = torch.load(
|
| 80 |
+
model_path,
|
| 81 |
+
map_location=torch.device("cuda" if torch.cuda.is_available() else "cpu"),
|
| 82 |
+
)
|
| 83 |
+
if args.dtype == "float64":
|
| 84 |
+
model = model.double().to("cpu")
|
| 85 |
+
elif args.dtype == "float32":
|
| 86 |
+
print("Converting model to float32, this may cause loss of precision.")
|
| 87 |
+
model = model.float().to("cpu")
|
| 88 |
+
|
| 89 |
+
if args.format == "mliap":
|
| 90 |
+
# Enabling cuequivariance by default. TODO: switch?
|
| 91 |
+
model = run_e3nn_to_cueq(copy.deepcopy(model))
|
| 92 |
+
model.lammps_mliap = True
|
| 93 |
+
|
| 94 |
+
if args.head is None:
|
| 95 |
+
head = select_head(model)
|
| 96 |
+
else:
|
| 97 |
+
head = args.head
|
| 98 |
+
print(
|
| 99 |
+
f"Selected head: {head} from command line in the list available heads: {model.heads}"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
lammps_class = LAMMPS_MLIAP_MACE if args.format == "mliap" else LAMMPS_MACE
|
| 103 |
+
lammps_model = (
|
| 104 |
+
lammps_class(model, head=head) if head is not None else lammps_class(model)
|
| 105 |
+
)
|
| 106 |
+
if args.format == "mliap":
|
| 107 |
+
torch.save(lammps_model, model_path + "-mliap_lammps.pt")
|
| 108 |
+
else:
|
| 109 |
+
lammps_model_compiled = jit.compile(lammps_model)
|
| 110 |
+
lammps_model_compiled.save(model_path + "-lammps.pt")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
main()
|
models/mace/mace/cli/eval_configs.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###########################################################################################
|
| 2 |
+
# Script for evaluating configurations contained in an xyz file with a trained model
|
| 3 |
+
# Authors: Ilyes Batatia, Gregor Simm
|
| 4 |
+
# This program is distributed under the MIT License (see MIT.md)
|
| 5 |
+
###########################################################################################
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
from typing import Dict
|
| 9 |
+
|
| 10 |
+
import ase.data
|
| 11 |
+
import ase.io
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from e3nn import o3
|
| 15 |
+
|
| 16 |
+
from mace import data
|
| 17 |
+
from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq
|
| 18 |
+
from mace.modules.utils import extract_invariant
|
| 19 |
+
from mace.tools import torch_geometric, torch_tools, utils
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def parse_args() -> argparse.Namespace:
|
| 23 |
+
parser = argparse.ArgumentParser(
|
| 24 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 25 |
+
)
|
| 26 |
+
parser.add_argument("--configs", help="path to XYZ configurations", required=True)
|
| 27 |
+
parser.add_argument("--model", help="path to model", required=True)
|
| 28 |
+
parser.add_argument("--output", help="output path", required=True)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--device",
|
| 31 |
+
help="select device",
|
| 32 |
+
type=str,
|
| 33 |
+
choices=["cpu", "cuda"],
|
| 34 |
+
default="cpu",
|
| 35 |
+
)
|
| 36 |
+
parser.add_argument(
|
| 37 |
+
"--enable_cueq",
|
| 38 |
+
help="enable cuequivariance acceleration",
|
| 39 |
+
action="store_true",
|
| 40 |
+
default=False,
|
| 41 |
+
)
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--default_dtype",
|
| 44 |
+
help="set default dtype",
|
| 45 |
+
type=str,
|
| 46 |
+
choices=["float32", "float64"],
|
| 47 |
+
default="float64",
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument("--batch_size", help="batch size", type=int, default=64)
|
| 50 |
+
parser.add_argument(
|
| 51 |
+
"--compute_stress",
|
| 52 |
+
help="compute stress",
|
| 53 |
+
action="store_true",
|
| 54 |
+
default=False,
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--compute_bec",
|
| 58 |
+
help="compute BEC",
|
| 59 |
+
action="store_true",
|
| 60 |
+
default=False,
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--return_contributions",
|
| 64 |
+
help="model outputs energy contributions for each body order, only supported for MACE, not ScaleShiftMACE",
|
| 65 |
+
action="store_true",
|
| 66 |
+
default=False,
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--return_descriptors",
|
| 70 |
+
help="model outputs MACE descriptors",
|
| 71 |
+
action="store_true",
|
| 72 |
+
default=False,
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--descriptor_num_layers",
|
| 76 |
+
help="number of layers to take descriptors from",
|
| 77 |
+
type=int,
|
| 78 |
+
default=-1,
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--descriptor_aggregation_method",
|
| 82 |
+
help="method for aggregating node features. None saves descriptors for each atom.",
|
| 83 |
+
choices=["mean", "per_element_mean", None],
|
| 84 |
+
default=None,
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--descriptor_invariants_only",
|
| 88 |
+
help="save invariant (l=0) descriptors only",
|
| 89 |
+
type=bool,
|
| 90 |
+
default=True,
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--return_node_energies",
|
| 94 |
+
help="model outputs MACE node energies",
|
| 95 |
+
action="store_true",
|
| 96 |
+
default=False,
|
| 97 |
+
)
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--info_prefix",
|
| 100 |
+
help="prefix for energy, forces and stress keys",
|
| 101 |
+
type=str,
|
| 102 |
+
default="MACE_",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--head",
|
| 106 |
+
help="Model head used for evaluation",
|
| 107 |
+
type=str,
|
| 108 |
+
required=False,
|
| 109 |
+
default=None,
|
| 110 |
+
)
|
| 111 |
+
return parser.parse_args()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def get_model_output(
|
| 115 |
+
model: torch.nn.Module,
|
| 116 |
+
batch: Dict[str, torch.Tensor],
|
| 117 |
+
compute_stress: bool,
|
| 118 |
+
compute_bec: bool,
|
| 119 |
+
) -> Dict[str, torch.Tensor]:
|
| 120 |
+
forward_args = {
|
| 121 |
+
"compute_stress": compute_stress,
|
| 122 |
+
}
|
| 123 |
+
if compute_bec:
|
| 124 |
+
# Only add `compute_bec` if it is requested
|
| 125 |
+
# We check if the model is MACELES at the start of the run function
|
| 126 |
+
forward_args["compute_bec"] = compute_bec
|
| 127 |
+
return model(batch, **forward_args)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main() -> None:
|
| 131 |
+
args = parse_args()
|
| 132 |
+
run(args)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def run(args: argparse.Namespace) -> None:
|
| 136 |
+
torch_tools.set_default_dtype(args.default_dtype)
|
| 137 |
+
device = torch_tools.init_device(args.device)
|
| 138 |
+
|
| 139 |
+
# Load model
|
| 140 |
+
model = torch.load(f=args.model, map_location=args.device)
|
| 141 |
+
if model.__class__.__name__ != "MACELES" and args.compute_bec:
|
| 142 |
+
raise ValueError("BEC can only be computed with MACELES model. ")
|
| 143 |
+
if args.enable_cueq:
|
| 144 |
+
print("Converting models to CuEq for acceleration")
|
| 145 |
+
model = run_e3nn_to_cueq(model, device=device)
|
| 146 |
+
#model = model.to(
|
| 147 |
+
# args.device
|
| 148 |
+
#) # shouldn't be necessary but seems to help with CUDA problems
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
for param in model.parameters():
|
| 154 |
+
param.requires_grad = False
|
| 155 |
+
|
| 156 |
+
# Load data and prepare input
|
| 157 |
+
atoms_list = ase.io.read(args.configs, index=":")
|
| 158 |
+
if args.head is not None:
|
| 159 |
+
for atoms in atoms_list:
|
| 160 |
+
atoms.info["head"] = args.head
|
| 161 |
+
configs = [data.config_from_atoms(atoms) for atoms in atoms_list]
|
| 162 |
+
|
| 163 |
+
z_table = utils.AtomicNumberTable([int(z) for z in model.atomic_numbers])
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
heads = model.heads
|
| 167 |
+
except AttributeError:
|
| 168 |
+
heads = None
|
| 169 |
+
|
| 170 |
+
data_loader = torch_geometric.dataloader.DataLoader(
|
| 171 |
+
dataset=[
|
| 172 |
+
data.AtomicData.from_config(
|
| 173 |
+
config, z_table=z_table, cutoff=float(model.r_max), heads=heads
|
| 174 |
+
)
|
| 175 |
+
for config in configs
|
| 176 |
+
],
|
| 177 |
+
batch_size=args.batch_size,
|
| 178 |
+
shuffle=False,
|
| 179 |
+
drop_last=False,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Collect data
|
| 184 |
+
energies_list = []
|
| 185 |
+
contributions_list = []
|
| 186 |
+
descriptors_list = []
|
| 187 |
+
node_energies_list = []
|
| 188 |
+
stresses_list = []
|
| 189 |
+
bec_list = []
|
| 190 |
+
qs_list = []
|
| 191 |
+
forces_collection = []
|
| 192 |
+
|
| 193 |
+
for batch in data_loader:
|
| 194 |
+
batch = batch.to(device)
|
| 195 |
+
output = get_model_output(
|
| 196 |
+
model, batch.to_dict(), args.compute_stress, args.compute_bec
|
| 197 |
+
)
|
| 198 |
+
energies_list.append(torch_tools.to_numpy(output["energy"]))
|
| 199 |
+
if args.compute_stress:
|
| 200 |
+
stresses_list.append(torch_tools.to_numpy(output["stress"]))
|
| 201 |
+
if args.compute_bec:
|
| 202 |
+
becs = np.split(
|
| 203 |
+
torch_tools.to_numpy(output["BEC"]),
|
| 204 |
+
indices_or_sections=batch.ptr[1:],
|
| 205 |
+
axis=0,
|
| 206 |
+
)
|
| 207 |
+
bec_list.append(becs[:-1]) # drop last as its empty
|
| 208 |
+
|
| 209 |
+
qs = np.split(
|
| 210 |
+
torch_tools.to_numpy(output["latent_charges"]),
|
| 211 |
+
indices_or_sections=batch.ptr[1:],
|
| 212 |
+
axis=0,
|
| 213 |
+
)
|
| 214 |
+
qs_list.append(qs[:-1]) # drop last as its empty
|
| 215 |
+
|
| 216 |
+
if args.return_contributions:
|
| 217 |
+
contributions_list.append(torch_tools.to_numpy(output["contributions"]))
|
| 218 |
+
|
| 219 |
+
if args.return_descriptors:
|
| 220 |
+
num_layers = args.descriptor_num_layers
|
| 221 |
+
if num_layers == -1:
|
| 222 |
+
num_layers = int(model.num_interactions)
|
| 223 |
+
irreps_out = o3.Irreps(str(model.products[0].linear.irreps_out))
|
| 224 |
+
l_max = irreps_out.lmax
|
| 225 |
+
num_invariant_features = irreps_out.dim // (l_max + 1) ** 2
|
| 226 |
+
per_layer_features = [
|
| 227 |
+
irreps_out.dim for _ in range(int(model.num_interactions))
|
| 228 |
+
]
|
| 229 |
+
per_layer_features[-1] = (
|
| 230 |
+
num_invariant_features # Equivariant features not created for the last layer
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
descriptors = output["node_feats"]
|
| 234 |
+
|
| 235 |
+
if args.descriptor_invariants_only:
|
| 236 |
+
descriptors = extract_invariant(
|
| 237 |
+
descriptors,
|
| 238 |
+
num_layers=num_layers,
|
| 239 |
+
num_features=num_invariant_features,
|
| 240 |
+
l_max=l_max,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
to_keep = np.sum(per_layer_features[:num_layers])
|
| 244 |
+
descriptors = descriptors[:, :to_keep].detach().cpu().numpy()
|
| 245 |
+
|
| 246 |
+
descriptors = np.split(
|
| 247 |
+
descriptors,
|
| 248 |
+
indices_or_sections=batch.ptr[1:],
|
| 249 |
+
axis=0,
|
| 250 |
+
)
|
| 251 |
+
descriptors_list.extend(descriptors[:-1]) # drop last as its empty
|
| 252 |
+
|
| 253 |
+
if args.return_node_energies:
|
| 254 |
+
node_energies_list.append(
|
| 255 |
+
np.split(
|
| 256 |
+
torch_tools.to_numpy(output["node_energy"]),
|
| 257 |
+
indices_or_sections=batch.ptr[1:],
|
| 258 |
+
axis=0,
|
| 259 |
+
)[
|
| 260 |
+
:-1
|
| 261 |
+
] # drop last as its empty
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
forces = np.split(
|
| 265 |
+
torch_tools.to_numpy(output["forces"]),
|
| 266 |
+
indices_or_sections=batch.ptr[1:],
|
| 267 |
+
axis=0,
|
| 268 |
+
)
|
| 269 |
+
forces_collection.append(forces[:-1]) # drop last as its empty
|
| 270 |
+
|
| 271 |
+
energies = np.concatenate(energies_list, axis=0)
|
| 272 |
+
forces_list = [
|
| 273 |
+
forces for forces_list in forces_collection for forces in forces_list
|
| 274 |
+
]
|
| 275 |
+
assert len(atoms_list) == len(energies) == len(forces_list)
|
| 276 |
+
if args.compute_stress:
|
| 277 |
+
stresses = np.concatenate(stresses_list, axis=0)
|
| 278 |
+
assert len(atoms_list) == stresses.shape[0]
|
| 279 |
+
|
| 280 |
+
if args.compute_bec:
|
| 281 |
+
bec_list = [becs for sublist in bec_list for becs in sublist]
|
| 282 |
+
qs_list = [qs for sublist in qs_list for qs in sublist]
|
| 283 |
+
|
| 284 |
+
if args.return_contributions:
|
| 285 |
+
contributions = np.concatenate(contributions_list, axis=0)
|
| 286 |
+
assert len(atoms_list) == contributions.shape[0]
|
| 287 |
+
|
| 288 |
+
if args.return_descriptors:
|
| 289 |
+
# no concatentation - elements of descriptors_list have non-uniform shapes
|
| 290 |
+
assert len(atoms_list) == len(descriptors_list)
|
| 291 |
+
|
| 292 |
+
if args.return_node_energies:
|
| 293 |
+
node_energies = np.concatenate(node_energies_list, axis=0)
|
| 294 |
+
assert len(atoms_list) == node_energies.shape[0]
|
| 295 |
+
|
| 296 |
+
# Store data in atoms objects
|
| 297 |
+
for i, (atoms, energy, forces) in enumerate(zip(atoms_list, energies, forces_list)):
|
| 298 |
+
atoms.calc = None # crucial
|
| 299 |
+
atoms.info[args.info_prefix + "energy"] = energy
|
| 300 |
+
atoms.arrays[args.info_prefix + "forces"] = forces
|
| 301 |
+
|
| 302 |
+
if args.compute_stress:
|
| 303 |
+
atoms.info[args.info_prefix + "stress"] = stresses[i]
|
| 304 |
+
|
| 305 |
+
if args.compute_bec:
|
| 306 |
+
atoms.arrays[args.info_prefix + "BEC"] = bec_list[i].reshape(-1, 9)
|
| 307 |
+
atoms.arrays[args.info_prefix + "latent_charges"] = qs_list[i]
|
| 308 |
+
|
| 309 |
+
if args.return_contributions:
|
| 310 |
+
atoms.info[args.info_prefix + "BO_contributions"] = contributions[i]
|
| 311 |
+
|
| 312 |
+
if args.return_descriptors:
|
| 313 |
+
descriptors = descriptors_list[i]
|
| 314 |
+
if args.descriptor_aggregation_method:
|
| 315 |
+
if args.descriptor_aggregation_method == "mean":
|
| 316 |
+
descriptors = np.mean(descriptors, axis=0)
|
| 317 |
+
elif args.descriptor_aggregation_method == "per_element_mean":
|
| 318 |
+
descriptors = {
|
| 319 |
+
element: np.mean(
|
| 320 |
+
descriptors[atoms.symbols == element], axis=0
|
| 321 |
+
).tolist()
|
| 322 |
+
for element in np.unique(atoms.symbols)
|
| 323 |
+
}
|
| 324 |
+
atoms.info[args.info_prefix + "descriptors"] = descriptors
|
| 325 |
+
else: # args.descriptor_aggregation_method is None
|
| 326 |
+
# Save descriptors for each atom (default behavior)
|
| 327 |
+
atoms.arrays[args.info_prefix + "descriptors"] = np.array(descriptors)
|
| 328 |
+
|
| 329 |
+
if args.return_node_energies:
|
| 330 |
+
atoms.arrays[args.info_prefix + "node_energies"] = node_energies[i]
|
| 331 |
+
|
| 332 |
+
# Write atoms to output path
|
| 333 |
+
ase.io.write(args.output, images=atoms_list, format="extxyz")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if __name__ == "__main__":
|
| 337 |
+
main()
|
models/mace/mace/cli/fine_tuning_select.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###########################################################################################
|
| 2 |
+
# This program is distributed under the MIT License (see MIT.md)
|
| 3 |
+
###########################################################################################
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import ast
|
| 8 |
+
import logging
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from enum import Enum
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import List, Tuple, Union
|
| 13 |
+
|
| 14 |
+
import ase.data
|
| 15 |
+
import ase.io
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from mace.calculators import MACECalculator, mace_mp
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import fpsample # type: ignore
|
| 23 |
+
except ImportError:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class FilteringType(Enum):
|
| 28 |
+
NONE = "none"
|
| 29 |
+
COMBINATIONS = "combinations"
|
| 30 |
+
EXCLUSIVE = "exclusive"
|
| 31 |
+
INCLUSIVE = "inclusive"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SubselectType(Enum):
|
| 35 |
+
FPS = "fps"
|
| 36 |
+
RANDOM = "random"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class SelectionSettings:
|
| 41 |
+
configs_pt: str
|
| 42 |
+
output: str
|
| 43 |
+
configs_ft: str | None = None
|
| 44 |
+
atomic_numbers: List[int] | None = None
|
| 45 |
+
num_samples: int | None = None
|
| 46 |
+
subselect: SubselectType = SubselectType.FPS
|
| 47 |
+
model: str = "small"
|
| 48 |
+
descriptors: str | None = None
|
| 49 |
+
device: str = "cpu"
|
| 50 |
+
default_dtype: str = "float64"
|
| 51 |
+
head_pt: str | None = None
|
| 52 |
+
head_ft: str | None = None
|
| 53 |
+
filtering_type: FilteringType = FilteringType.COMBINATIONS
|
| 54 |
+
weight_ft: float = 1.0
|
| 55 |
+
weight_pt: float = 1.0
|
| 56 |
+
allow_random_padding: bool = True
|
| 57 |
+
seed: int = 42
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def str_to_list(s: str) -> List[int]:
|
| 61 |
+
assert isinstance(s, str), "Input must be a string"
|
| 62 |
+
return ast.literal_eval(s)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def parse_args() -> argparse.Namespace:
|
| 66 |
+
parser = argparse.ArgumentParser(
|
| 67 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 68 |
+
)
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"--configs_pt",
|
| 71 |
+
help="path to XYZ configurations for the pretraining",
|
| 72 |
+
required=True,
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--configs_ft",
|
| 76 |
+
help="path or list of paths to XYZ configurations for the finetuning",
|
| 77 |
+
required=False,
|
| 78 |
+
default=None,
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--num_samples",
|
| 82 |
+
help="number of samples to select for the pretraining",
|
| 83 |
+
type=int,
|
| 84 |
+
required=False,
|
| 85 |
+
default=None,
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--subselect",
|
| 89 |
+
help="method to subselect the configurations of the pretraining set",
|
| 90 |
+
type=SubselectType,
|
| 91 |
+
choices=list(SubselectType),
|
| 92 |
+
default=SubselectType.FPS,
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--model", help="path to model", default="small", required=False
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--output", help="output path", required=True)
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--descriptors", help="path to descriptors", required=False, default=None
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--device",
|
| 103 |
+
help="select device",
|
| 104 |
+
type=str,
|
| 105 |
+
choices=["cpu", "cuda"],
|
| 106 |
+
default="cpu",
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--default_dtype",
|
| 110 |
+
help="set default dtype",
|
| 111 |
+
type=str,
|
| 112 |
+
choices=["float32", "float64"],
|
| 113 |
+
default="float64",
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--head_pt",
|
| 117 |
+
help="level of head for the pretraining set",
|
| 118 |
+
type=str,
|
| 119 |
+
default=None,
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--head_ft",
|
| 123 |
+
help="level of head for the finetuning set",
|
| 124 |
+
type=str,
|
| 125 |
+
default=None,
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--filtering_type",
|
| 129 |
+
help="filtering type",
|
| 130 |
+
type=FilteringType,
|
| 131 |
+
choices=list(FilteringType),
|
| 132 |
+
default=FilteringType.NONE,
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--weight_ft",
|
| 136 |
+
help="weight for the finetuning set",
|
| 137 |
+
type=float,
|
| 138 |
+
default=1.0,
|
| 139 |
+
)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--weight_pt",
|
| 142 |
+
help="weight for the pretraining set",
|
| 143 |
+
type=float,
|
| 144 |
+
default=1.0,
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--atomic_numbers",
|
| 148 |
+
help="list of atomic numbers to filter the configurations",
|
| 149 |
+
type=str_to_list,
|
| 150 |
+
default=None,
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--disallow_random_padding",
|
| 154 |
+
help="do not allow random padding of the configurations to match the number of samples",
|
| 155 |
+
action="store_false",
|
| 156 |
+
dest="allow_random_padding",
|
| 157 |
+
)
|
| 158 |
+
parser.add_argument("--seed", help="random seed", type=int, default=42)
|
| 159 |
+
return parser.parse_args()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def calculate_descriptors(atoms: List[ase.Atoms], calc: MACECalculator) -> None:
|
| 163 |
+
logging.info("Calculating descriptors")
|
| 164 |
+
for mol in atoms:
|
| 165 |
+
descriptors = calc.get_descriptors(mol.copy(), invariants_only=True)
|
| 166 |
+
# average descriptors over atoms for each element
|
| 167 |
+
descriptors_dict = {
|
| 168 |
+
element: np.mean(descriptors[mol.symbols == element], axis=0)
|
| 169 |
+
for element in np.unique(mol.symbols)
|
| 170 |
+
}
|
| 171 |
+
mol.info["mace_descriptors"] = descriptors_dict
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def filter_atoms(
|
| 175 |
+
atoms: ase.Atoms,
|
| 176 |
+
element_subset: List[str],
|
| 177 |
+
filtering_type: FilteringType = FilteringType.COMBINATIONS,
|
| 178 |
+
) -> bool:
|
| 179 |
+
"""
|
| 180 |
+
Filters atoms based on the provided filtering type and element subset.
|
| 181 |
+
|
| 182 |
+
Parameters:
|
| 183 |
+
atoms (ase.Atoms): The atoms object to filter.
|
| 184 |
+
element_subset (list): The list of elements to consider during filtering.
|
| 185 |
+
filtering_type (FilteringType): The type of filtering to apply.
|
| 186 |
+
Can be one of the following `FilteringType` enum members:
|
| 187 |
+
- `FilteringType.NONE`: No filtering is applied.
|
| 188 |
+
- `FilteringType.COMBINATIONS`: Return true if `atoms` is composed of combinations of elements in the subset, false otherwise. I.e. does not require all of the specified elements to be present.
|
| 189 |
+
- `FilteringType.EXCLUSIVE`: Return true if `atoms` contains *only* elements in the subset, false otherwise.
|
| 190 |
+
- `FilteringType.INCLUSIVE`: Return true if `atoms` contains all elements in the subset, false otherwise. I.e. allows additional elements.
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
bool: True if the atoms pass the filter, False otherwise.
|
| 194 |
+
"""
|
| 195 |
+
if filtering_type == FilteringType.NONE:
|
| 196 |
+
return True
|
| 197 |
+
if filtering_type == FilteringType.COMBINATIONS:
|
| 198 |
+
atom_symbols = np.unique(atoms.symbols)
|
| 199 |
+
return all(
|
| 200 |
+
x in element_subset for x in atom_symbols
|
| 201 |
+
) # atoms must *only* contain elements in the subset
|
| 202 |
+
if filtering_type == FilteringType.EXCLUSIVE:
|
| 203 |
+
atom_symbols = set(list(atoms.symbols))
|
| 204 |
+
return atom_symbols == set(element_subset)
|
| 205 |
+
if filtering_type == FilteringType.INCLUSIVE:
|
| 206 |
+
atom_symbols = np.unique(atoms.symbols)
|
| 207 |
+
return all(
|
| 208 |
+
x in atom_symbols for x in element_subset
|
| 209 |
+
) # atoms must *at least* contain elements in the subset
|
| 210 |
+
raise ValueError(
|
| 211 |
+
f"Filtering type {filtering_type} not recognised. Must be one of {list(FilteringType)}."
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class FPS:
|
| 216 |
+
def __init__(self, atoms_list: List[ase.Atoms], n_samples: int):
|
| 217 |
+
self.n_samples = n_samples
|
| 218 |
+
self.atoms_list = atoms_list
|
| 219 |
+
self.species = np.unique([x.symbol for atoms in atoms_list for x in atoms]) # type: ignore
|
| 220 |
+
self.species_dict = {x: i for i, x in enumerate(self.species)}
|
| 221 |
+
# start from a random configuration
|
| 222 |
+
self.list_index = [np.random.randint(0, len(atoms_list))]
|
| 223 |
+
self.assemble_descriptors()
|
| 224 |
+
|
| 225 |
+
def run(
|
| 226 |
+
self,
|
| 227 |
+
) -> List[int]:
|
| 228 |
+
"""
|
| 229 |
+
Run the farthest point sampling algorithm.
|
| 230 |
+
"""
|
| 231 |
+
descriptor_dataset_reshaped = (
|
| 232 |
+
self.descriptors_dataset.reshape( # pylint: disable=E1121
|
| 233 |
+
(len(self.atoms_list), -1)
|
| 234 |
+
)
|
| 235 |
+
)
|
| 236 |
+
logging.info(f"{descriptor_dataset_reshaped.shape}")
|
| 237 |
+
logging.info(f"n_samples: {self.n_samples}")
|
| 238 |
+
self.list_index = fpsample.fps_npdu_kdtree_sampling(
|
| 239 |
+
descriptor_dataset_reshaped,
|
| 240 |
+
self.n_samples,
|
| 241 |
+
)
|
| 242 |
+
return self.list_index
|
| 243 |
+
|
| 244 |
+
def assemble_descriptors(self) -> None:
|
| 245 |
+
"""
|
| 246 |
+
Assemble the descriptors for all the configurations.
|
| 247 |
+
"""
|
| 248 |
+
self.descriptors_dataset: np.ndarray = 10e10 * np.ones(
|
| 249 |
+
(
|
| 250 |
+
len(self.atoms_list),
|
| 251 |
+
len(self.species),
|
| 252 |
+
len(list(self.atoms_list[0].info["mace_descriptors"].values())[0]),
|
| 253 |
+
),
|
| 254 |
+
dtype=np.float32,
|
| 255 |
+
).astype(np.float32)
|
| 256 |
+
|
| 257 |
+
for i, atoms in enumerate(self.atoms_list):
|
| 258 |
+
descriptors = atoms.info["mace_descriptors"]
|
| 259 |
+
for z in descriptors:
|
| 260 |
+
self.descriptors_dataset[i, self.species_dict[z]] = np.array(
|
| 261 |
+
descriptors[z]
|
| 262 |
+
).astype(np.float32)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _load_calc(
|
| 266 |
+
model: str, device: str, default_dtype: str, subselect: SubselectType
|
| 267 |
+
) -> Union[MACECalculator, None]:
|
| 268 |
+
if subselect == SubselectType.RANDOM:
|
| 269 |
+
return None
|
| 270 |
+
if model in ["small", "medium", "large"]:
|
| 271 |
+
calc = mace_mp(model, device=device, default_dtype=default_dtype)
|
| 272 |
+
else:
|
| 273 |
+
calc = MACECalculator(
|
| 274 |
+
model_paths=model,
|
| 275 |
+
device=device,
|
| 276 |
+
default_dtype=default_dtype,
|
| 277 |
+
)
|
| 278 |
+
return calc
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _get_finetuning_elements(
|
| 282 |
+
atoms: List[ase.Atoms], atomic_numbers: List[int] | None
|
| 283 |
+
) -> List[str]:
|
| 284 |
+
if atoms:
|
| 285 |
+
logging.debug(
|
| 286 |
+
"Using elements from the finetuning configurations for filtering."
|
| 287 |
+
)
|
| 288 |
+
species = np.unique([x.symbol for atoms in atoms for x in atoms]).tolist() # type: ignore
|
| 289 |
+
elif atomic_numbers is not None and atomic_numbers:
|
| 290 |
+
logging.debug("Using the supplied atomic numbers for filtering.")
|
| 291 |
+
species = [ase.data.chemical_symbols[z] for z in atomic_numbers]
|
| 292 |
+
else:
|
| 293 |
+
species = []
|
| 294 |
+
return species
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _read_finetuning_configs(
|
| 298 |
+
configs_ft: Union[str, list[str], None],
|
| 299 |
+
) -> List[ase.Atoms]:
|
| 300 |
+
if isinstance(configs_ft, str):
|
| 301 |
+
path = configs_ft
|
| 302 |
+
return ase.io.read(path, index=":") # type: ignore
|
| 303 |
+
if isinstance(configs_ft, list):
|
| 304 |
+
assert all(isinstance(x, str) for x in configs_ft)
|
| 305 |
+
atoms_list_ft = []
|
| 306 |
+
for path in configs_ft:
|
| 307 |
+
atoms_list_ft += ase.io.read(path, index=":")
|
| 308 |
+
return atoms_list_ft
|
| 309 |
+
if configs_ft is None:
|
| 310 |
+
return []
|
| 311 |
+
raise ValueError(f"Invalid type for configs_ft: {type(configs_ft)}")
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _filter_pretraining_data(
|
| 315 |
+
atoms: list[ase.Atoms],
|
| 316 |
+
filtering_type: FilteringType,
|
| 317 |
+
all_species_ft: List[str],
|
| 318 |
+
) -> Tuple[List[ase.Atoms], List[ase.Atoms], list[bool]]:
|
| 319 |
+
logging.info(
|
| 320 |
+
"Filtering configurations based on the finetuning set, "
|
| 321 |
+
f"filtering type: {filtering_type}, elements: {all_species_ft}"
|
| 322 |
+
)
|
| 323 |
+
passes_filter = [filter_atoms(x, all_species_ft, filtering_type) for x in atoms]
|
| 324 |
+
assert len(passes_filter) == len(atoms), "Filtering failed"
|
| 325 |
+
filtered_atoms = [x for x, passes in zip(atoms, passes_filter) if passes]
|
| 326 |
+
remaining_atoms = [x for x, passes in zip(atoms, passes_filter) if not passes]
|
| 327 |
+
return filtered_atoms, remaining_atoms, passes_filter
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _get_random_configs(
|
| 331 |
+
num_samples: int,
|
| 332 |
+
atoms: List[ase.Atoms],
|
| 333 |
+
) -> list[ase.Atoms]:
|
| 334 |
+
if num_samples > len(atoms):
|
| 335 |
+
raise ValueError(
|
| 336 |
+
f"Requested more samples ({num_samples}) than available in the remaining set ({len(atoms)})"
|
| 337 |
+
)
|
| 338 |
+
indices = np.random.choice(list(range(len(atoms))), num_samples, replace=False)
|
| 339 |
+
return [atoms[i] for i in indices]
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _load_descriptors(
|
| 343 |
+
atoms: List[ase.Atoms],
|
| 344 |
+
passes_filter: List[bool],
|
| 345 |
+
descriptors_path: str | None,
|
| 346 |
+
calc: MACECalculator | None,
|
| 347 |
+
full_data_length: int,
|
| 348 |
+
) -> None:
|
| 349 |
+
if descriptors_path is not None:
|
| 350 |
+
logging.info(f"Loading descriptors from {descriptors_path}")
|
| 351 |
+
descriptors = np.load(descriptors_path, allow_pickle=True)
|
| 352 |
+
assert sum(passes_filter) == len(atoms)
|
| 353 |
+
if len(descriptors) != full_data_length:
|
| 354 |
+
raise ValueError(
|
| 355 |
+
f"Length of the descriptors ({len(descriptors)}) does not match the length of the data ({full_data_length})"
|
| 356 |
+
"Please provide descriptors for all configurations"
|
| 357 |
+
)
|
| 358 |
+
required_descriptors = [
|
| 359 |
+
descriptors[i] for i, passes in enumerate(passes_filter) if passes
|
| 360 |
+
]
|
| 361 |
+
for i, atoms_ in enumerate(atoms):
|
| 362 |
+
atoms_.info["mace_descriptors"] = required_descriptors[i]
|
| 363 |
+
else:
|
| 364 |
+
logging.info("Calculating descriptors")
|
| 365 |
+
if calc is None:
|
| 366 |
+
raise ValueError("MACECalculator must be provided to calculate descriptors")
|
| 367 |
+
calculate_descriptors(atoms, calc)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _maybe_save_descriptors(
|
| 371 |
+
atoms: List[ase.Atoms],
|
| 372 |
+
output_path: str,
|
| 373 |
+
) -> None:
|
| 374 |
+
"""
|
| 375 |
+
Save the descriptors if they are present in the atoms objects.
|
| 376 |
+
Also, delete the descriptors from the atoms objects.
|
| 377 |
+
"""
|
| 378 |
+
if all("mace_descriptors" in x.info for x in atoms):
|
| 379 |
+
output_path = Path(output_path)
|
| 380 |
+
descriptor_save_path = output_path.parent / (
|
| 381 |
+
output_path.stem + "_descriptors.npy"
|
| 382 |
+
)
|
| 383 |
+
logging.info(f"Saving descriptors at {descriptor_save_path}")
|
| 384 |
+
descriptors_list = [x.info["mace_descriptors"] for x in atoms]
|
| 385 |
+
np.save(descriptor_save_path, descriptors_list, allow_pickle=True)
|
| 386 |
+
for x in atoms:
|
| 387 |
+
del x.info["mace_descriptors"]
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _maybe_fps(atoms: List[ase.Atoms], num_samples: int) -> List[ase.Atoms]:
|
| 391 |
+
try:
|
| 392 |
+
fps_pt = FPS(atoms, num_samples)
|
| 393 |
+
idx_pt = fps_pt.run()
|
| 394 |
+
logging.info(f"Selected {len(idx_pt)} configurations")
|
| 395 |
+
return [atoms[i] for i in idx_pt]
|
| 396 |
+
except Exception as e: # pylint: disable=W0703
|
| 397 |
+
logging.error(f"FPS failed, selecting random configurations instead: {e}")
|
| 398 |
+
return _get_random_configs(num_samples, atoms)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def _subsample_data(
|
| 402 |
+
filtered_atoms: List[ase.Atoms],
|
| 403 |
+
remaining_atoms: List[ase.Atoms],
|
| 404 |
+
passes_filter: List[bool],
|
| 405 |
+
num_samples: int | None,
|
| 406 |
+
subselect: SubselectType,
|
| 407 |
+
descriptors_path: str | None,
|
| 408 |
+
allow_random_padding: bool,
|
| 409 |
+
calc: MACECalculator | None,
|
| 410 |
+
) -> List[ase.Atoms]:
|
| 411 |
+
if num_samples is None or num_samples == len(filtered_atoms):
|
| 412 |
+
logging.info(
|
| 413 |
+
f"No subsampling, keeping all {len(filtered_atoms)} filtered configurations"
|
| 414 |
+
)
|
| 415 |
+
return filtered_atoms
|
| 416 |
+
if num_samples > len(filtered_atoms) and allow_random_padding:
|
| 417 |
+
num_sample_randomly = num_samples - len(filtered_atoms)
|
| 418 |
+
logging.info(
|
| 419 |
+
f"Number of configurations after filtering {len(filtered_atoms)} "
|
| 420 |
+
f"is less than the number of samples {num_samples}, "
|
| 421 |
+
f"selecting {num_sample_randomly} random configurations for the rest."
|
| 422 |
+
)
|
| 423 |
+
return filtered_atoms + _get_random_configs(
|
| 424 |
+
num_sample_randomly, remaining_atoms
|
| 425 |
+
)
|
| 426 |
+
if num_samples == 0:
|
| 427 |
+
raise ValueError("Number of samples must be greater than 0")
|
| 428 |
+
if subselect == SubselectType.FPS:
|
| 429 |
+
_load_descriptors(
|
| 430 |
+
filtered_atoms,
|
| 431 |
+
passes_filter,
|
| 432 |
+
descriptors_path,
|
| 433 |
+
calc,
|
| 434 |
+
full_data_length=len(filtered_atoms) + len(remaining_atoms),
|
| 435 |
+
)
|
| 436 |
+
logging.info(
|
| 437 |
+
f"Selecting {num_samples} configurations out of {len(filtered_atoms)} using Farthest Point Sampling"
|
| 438 |
+
)
|
| 439 |
+
return _maybe_fps(filtered_atoms, num_samples)
|
| 440 |
+
if subselect == SubselectType.RANDOM:
|
| 441 |
+
logging.info(
|
| 442 |
+
f"Subselecting {num_samples} from filtered {len(filtered_atoms)} using random sampling"
|
| 443 |
+
)
|
| 444 |
+
return _get_random_configs(num_samples, filtered_atoms)
|
| 445 |
+
raise ValueError(f"Invalid subselect type: {subselect}")
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _write_metadata(
|
| 449 |
+
atoms: list[ase.Atoms], pretrained: bool, config_weight: float, head: str | None
|
| 450 |
+
) -> None:
|
| 451 |
+
for a in atoms:
|
| 452 |
+
a.info["pretrained"] = pretrained
|
| 453 |
+
a.info["config_weight"] = config_weight
|
| 454 |
+
if head is not None:
|
| 455 |
+
a.info["head"] = head
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def select_samples(
|
| 459 |
+
settings: SelectionSettings,
|
| 460 |
+
) -> None:
|
| 461 |
+
np.random.seed(settings.seed)
|
| 462 |
+
torch.manual_seed(settings.seed)
|
| 463 |
+
calc = _load_calc(
|
| 464 |
+
settings.model, settings.device, settings.default_dtype, settings.subselect
|
| 465 |
+
)
|
| 466 |
+
atoms_list_ft = _read_finetuning_configs(settings.configs_ft)
|
| 467 |
+
all_species_ft = _get_finetuning_elements(atoms_list_ft, settings.atomic_numbers)
|
| 468 |
+
|
| 469 |
+
if settings.filtering_type is not FilteringType.NONE and not all_species_ft:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
"Filtering types other than NONE require elements for filtering. They can be specified via the `--atomic_numbers` flag."
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
atoms_list_pt: list[ase.Atoms] = ase.io.read(settings.configs_pt, index=":") # type: ignore
|
| 475 |
+
filtered_pt_atoms, remaining_atoms, passes_filter = _filter_pretraining_data(
|
| 476 |
+
atoms_list_pt, settings.filtering_type, all_species_ft
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
subsampled_atoms = _subsample_data(
|
| 480 |
+
filtered_pt_atoms,
|
| 481 |
+
remaining_atoms,
|
| 482 |
+
passes_filter,
|
| 483 |
+
settings.num_samples,
|
| 484 |
+
settings.subselect,
|
| 485 |
+
settings.descriptors,
|
| 486 |
+
settings.allow_random_padding,
|
| 487 |
+
calc,
|
| 488 |
+
)
|
| 489 |
+
if ase.io.formats.filetype(settings.output, read=False) != "extxyz":
|
| 490 |
+
raise ValueError(
|
| 491 |
+
f"filename '{settings.output}' does no have "
|
| 492 |
+
"suffix compatible with extxyz format"
|
| 493 |
+
)
|
| 494 |
+
_maybe_save_descriptors(subsampled_atoms, settings.output)
|
| 495 |
+
|
| 496 |
+
_write_metadata(
|
| 497 |
+
subsampled_atoms,
|
| 498 |
+
pretrained=True,
|
| 499 |
+
config_weight=settings.weight_pt,
|
| 500 |
+
head=settings.head_pt,
|
| 501 |
+
)
|
| 502 |
+
_write_metadata(
|
| 503 |
+
atoms_list_ft,
|
| 504 |
+
pretrained=False,
|
| 505 |
+
config_weight=settings.weight_ft,
|
| 506 |
+
head=settings.head_ft,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
logging.info("Saving the selected configurations")
|
| 510 |
+
ase.io.write(settings.output, subsampled_atoms)
|
| 511 |
+
|
| 512 |
+
logging.info("Saving a combined XYZ file")
|
| 513 |
+
atoms_fps_pt_ft = subsampled_atoms + atoms_list_ft
|
| 514 |
+
|
| 515 |
+
output = Path(settings.output)
|
| 516 |
+
ase.io.write(
|
| 517 |
+
output.parent / (output.stem + "_combined" + output.suffix),
|
| 518 |
+
atoms_fps_pt_ft,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def main():
|
| 523 |
+
args = parse_args()
|
| 524 |
+
settings = SelectionSettings(**vars(args))
|
| 525 |
+
select_samples(settings)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
if __name__ == "__main__":
|
| 529 |
+
main()
|
models/mace/mace/cli/our_files/__pycache__/run_calc.cpython-310.pyc
ADDED
|
Binary file (22.1 kB). View file
|
|
|
models/mace/mace/cli/our_files/__pycache__/run_eval.cpython-310.pyc
ADDED
|
Binary file (9.43 kB). View file
|
|
|
models/mace/mace/cli/our_files/__pycache__/run_eval_foundation.cpython-310.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
models/mace/mace/cli/our_files/__pycache__/run_eval_foundation_no_finetuning.cpython-310.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
models/mace/mace/cli/our_files/run_calc.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ase.io import read, write
|
| 2 |
+
from ase.optimize import FIRE, BFGS
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from mace.calculators import MACECalculator
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
input_structure = ""
|
| 8 |
+
device = "cuda"
|
| 9 |
+
#device = "cpu"
|
| 10 |
+
|
| 11 |
+
atoms = read(input_structure)
|
| 12 |
+
|
| 13 |
+
# Attach YOUR calculator (loads model internally)
|
| 14 |
+
|
| 15 |
+
# calc = MACECalculator(
|
| 16 |
+
# model_paths='',
|
| 17 |
+
# device=device,
|
| 18 |
+
# )
|
| 19 |
+
|
| 20 |
+
#
|
| 21 |
+
print("a")
|
| 22 |
+
calc = MACECalculator(
|
| 23 |
+
model_path='',
|
| 24 |
+
device=device,
|
| 25 |
+
head='Default',
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
atoms.set_calculator(calc)
|
| 29 |
+
|
| 30 |
+
opt = BFGS(atoms, logfile="ml_relax.log", trajectory="ml_relax.traj")
|
| 31 |
+
opt.run(fmax=0.02, steps=1000)
|
| 32 |
+
|
| 33 |
+
atoms.write('POSCAR_final')
|
| 34 |
+
print("Done.")
|