diff --git a/models/mace/README.md b/models/mace/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb20b927e1cbc808a1592519cd42238f135f118b --- /dev/null +++ b/models/mace/README.md @@ -0,0 +1,5 @@ +## Introduction + +Running the script can be found in mace/cli/run_train + +you can run it from scripts/run_mace.sh. Just speicfy pathways \ No newline at end of file diff --git a/models/mace/mace/__init__.py b/models/mace/mace/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..490c4c01eb79794be90ab73ee32623ac1ca35db2 --- /dev/null +++ b/models/mace/mace/__init__.py @@ -0,0 +1,5 @@ +import os + +from .__version__ import __version__ + +os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1" diff --git a/models/mace/mace/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10ba1f41c1d4918b2c20447f1b4df0acb8ad21d Binary files /dev/null and b/models/mace/mace/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/__pycache__/__version__.cpython-310.pyc b/models/mace/mace/__pycache__/__version__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2ef2411ba22afeee7d1f6ca3051ee8b984c1d29 Binary files /dev/null and b/models/mace/mace/__pycache__/__version__.cpython-310.pyc differ diff --git a/models/mace/mace/__version__.py b/models/mace/mace/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..76cdefb05fb0cdc28ad2937dd774c3092d89885f --- /dev/null +++ b/models/mace/mace/__version__.py @@ -0,0 +1,3 @@ +__version__ = "0.3.15" + +__all__ = ["__version__"] diff --git a/models/mace/mace/calculators/__init__.py b/models/mace/mace/calculators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d60523766efec4eef598f36baf1638b14359c54d --- /dev/null +++ b/models/mace/mace/calculators/__init__.py @@ -0,0 +1,11 @@ +from .foundations_models import mace_anicc, mace_mp, mace_off, mace_omol +from .lammps_mace import LAMMPS_MACE +from .mace import MACECalculator + +__all__ = [ + "MACECalculator", + "LAMMPS_MACE", + "mace_mp", + "mace_off", + "mace_anicc", +] diff --git a/models/mace/mace/calculators/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/calculators/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee31b3fda77c3e5918b29ae42be951d7227dc45c Binary files /dev/null and b/models/mace/mace/calculators/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/calculators/__pycache__/foundations_models.cpython-310.pyc b/models/mace/mace/calculators/__pycache__/foundations_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..777a31c32abf13f5c599b623ec55d77049782028 Binary files /dev/null and b/models/mace/mace/calculators/__pycache__/foundations_models.cpython-310.pyc differ diff --git a/models/mace/mace/calculators/__pycache__/lammps_mace.cpython-310.pyc b/models/mace/mace/calculators/__pycache__/lammps_mace.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8272405cd89b9e39fccd17500dbb778ec2e22905 Binary files /dev/null and b/models/mace/mace/calculators/__pycache__/lammps_mace.cpython-310.pyc differ diff --git a/models/mace/mace/calculators/__pycache__/mace.cpython-310.pyc b/models/mace/mace/calculators/__pycache__/mace.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c7b730953ca77f4a859298b3206d3e795d80dea Binary files /dev/null and b/models/mace/mace/calculators/__pycache__/mace.cpython-310.pyc differ diff --git a/models/mace/mace/calculators/foundations_models.py b/models/mace/mace/calculators/foundations_models.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c4c2584b07fd996af6d2f5ce4194fdde82af0f --- /dev/null +++ b/models/mace/mace/calculators/foundations_models.py @@ -0,0 +1,445 @@ +import os +import urllib.request +from pathlib import Path +from typing import Any, Literal, Optional, Union, overload + +import torch +from ase import units +from ase.calculators.mixing import SumCalculator + +from mace.tools.utils import get_cache_dir + +from .mace import MACECalculator + +module_dir = os.path.dirname(__file__) +local_model_path = os.path.join( + module_dir, "foundations_models/mace-mpa-0-medium.model" +) + +mace_mp_urls = { + "small": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/2023-12-10-mace-128-L0_energy_epoch-249.model", + "medium": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/2023-12-03-mace-128-L1_epoch-199.model", + "large": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0/MACE_MPtrj_2022.9.model", + "small-0b": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b/mace_agnesi_small.model", + "medium-0b": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b/mace_agnesi_medium.model", + "small-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-small-density-agnesi-stress.model", + "medium-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-medium-density-agnesi-stress.model", + "large-0b2": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b2/mace-large-density-agnesi-stress.model", + "medium-0b3": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mp_0b3/mace-mp-0b3-medium.model", + "medium-mpa-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_mpa_0/mace-mpa-0-medium.model", + "small-omat-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_omat_0/mace-omat-0-small.model", + "medium-omat-0": "https://github.com/ACEsuit/mace-mp/releases/download/mace_omat_0/mace-omat-0-medium.model", + "mace-matpes-pbe-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/MACE-matpes-pbe-omat-ft.model", + "mace-matpes-r2scan-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/MACE-matpes-r2scan-omat-ft.model", + "mh-0": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mh_1/mace-mh-0.model", + "mh-1": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mh_1/mace-mh-1.model", +} +mace_mp_names = [None] + list(mace_mp_urls.keys()) + + +def download_mace_mp_checkpoint(model: Optional[Union[str, Path]] = None) -> str: + """ + Downloads or locates the MACE-MP checkpoint file. + + Args: + model (str, optional): Path to the model or size specification. + Defaults to None which uses the medium model. + + Returns: + str: Path to the downloaded (or cached, if previously loaded) checkpoint file. + """ + if model in (None, "medium-mpa-0") and os.path.isfile(local_model_path): + return local_model_path + + checkpoint_url = ( + mace_mp_urls.get(model, mace_mp_urls["medium-mpa-0"]) + if model in mace_mp_names + else model + ) + + if checkpoint_url == mace_mp_urls["medium-mpa-0"]: + print( + "Using medium MPA-0 model as default MACE-MP model, to use previous (before 3.10) default model please specify 'medium' as model argument" + ) + ASL_checkpoint_urls = { + mace_mp_urls["small-omat-0"], + mace_mp_urls["medium-omat-0"], + mace_mp_urls["mace-matpes-pbe-0"], + mace_mp_urls["mace-matpes-r2scan-0"], + } + if checkpoint_url in ASL_checkpoint_urls: + print( + "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." + ) + + cache_dir = get_cache_dir() + checkpoint_url_name = "".join( + c for c in os.path.basename(checkpoint_url) if c.isalnum() or c in "_" + ) + cached_model_path = f"{cache_dir}/{checkpoint_url_name}" + + if not os.path.isfile(cached_model_path): + os.makedirs(cache_dir, exist_ok=True) + print(f"Downloading MACE model from {checkpoint_url!r}") + _, http_msg = urllib.request.urlretrieve(checkpoint_url, cached_model_path) + if "Content-Type: text/html" in http_msg: + raise RuntimeError( + f"Model download failed, please check the URL {checkpoint_url}" + ) + print(f"Cached MACE model to {cached_model_path}") + + return cached_model_path + + +@overload +def mace_mp(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ... + + +@overload +def mace_mp( + *, return_raw_model: Literal[False] = False, **kwargs: Any +) -> MACECalculator: ... + + +def mace_mp( + model: Optional[Union[str, Path]] = None, + device: str = "", + default_dtype: str = "float32", + dispersion: bool = False, + damping: str = "bj", # choices: ["zero", "bj", "zerom", "bjm"] + dispersion_xc: str = "pbe", + dispersion_cutoff: float = 40.0 * units.Bohr, + return_raw_model: bool = False, + **kwargs, +) -> Union[MACECalculator, torch.nn.Module, SumCalculator]: + """ + Constructs a MACECalculator with a pretrained model based on the Materials Project (89 elements). + The model is released under the MIT license. See https://github.com/ACEsuit/mace-foundations for all models. + Note: + If you are using this function, please cite the relevant paper for the Materials Project, + any paper associated with the MACE model, and also the following: + - MACE-MP by Ilyes Batatia, Philipp Benner, Yuan Chiang, Alin M. Elena, + Dávid P. Kovács, Janosh Riebesell, et al., 2023, arXiv:2401.00096 + - MACE-Universal by Yuan Chiang, 2023, Hugging Face, Revision e5ebd9b, + DOI: 10.57967/hf/1202, URL: https://huggingface.co/cyrusyc/mace-universal + - Matbench Discovery by Janosh Riebesell, Rhys EA Goodall, Philipp Benner, Yuan Chiang, + Alpha A Lee, Anubhav Jain, Kristin A Persson, 2023, arXiv:2308.14920 + + Args: + model (str, optional): Path to the model. Defaults to None which first checks for + a local model and then downloads the default model from figshare. Specify "small", + "medium" or "large" to download a smaller or larger model from figshare. + device (str, optional): Device to use for the model. Defaults to "cuda" if available. + default_dtype (str, optional): Default dtype for the model. Defaults to "float32". + dispersion (bool, optional): Whether to use D3 dispersion corrections. Defaults to False. + damping (str): The damping function associated with the D3 correction. Defaults to "bj" for D3(BJ). + dispersion_xc (str, optional): Exchange-correlation functional for D3 dispersion corrections. + dispersion_cutoff (float, optional): Cutoff radius in Bohr for D3 dispersion corrections. + return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False. + **kwargs: Passed to MACECalculator and TorchDFTD3Calculator. + + Returns: + MACECalculator: trained on the MPtrj dataset (unless model otherwise specified). + """ + try: + if model in mace_mp_names or str(model).startswith("https:"): + model_path = download_mace_mp_checkpoint(model) + print(f"Using Materials Project MACE for MACECalculator with {model_path}") + else: + if not Path(model).exists(): + raise FileNotFoundError(f"{model} not found locally") + model_path = model + except Exception as exc: + raise RuntimeError("Model download failed and no local model found") from exc + + device = device or ("cuda" if torch.cuda.is_available() else "cpu") + if default_dtype == "float64": + print( + "Using float64 for MACECalculator, which is slower but more accurate. Recommended for geometry optimization." + ) + if default_dtype == "float32": + print( + "Using float32 for MACECalculator, which is faster but less accurate. Recommended for MD. Use float64 for geometry optimization." + ) + + if return_raw_model: + return torch.load(model_path, map_location=device) + + mace_calc = MACECalculator( + model_paths=model_path, device=device, default_dtype=default_dtype, **kwargs + ) + + if not dispersion: + return mace_calc + + try: + from torch_dftd.torch_dftd3_calculator import TorchDFTD3Calculator + except ImportError as exc: + raise RuntimeError( + "Please install torch-dftd to use dispersion corrections (see https://github.com/pfnet-research/torch-dftd)" + ) from exc + + print("Using TorchDFTD3Calculator for D3 dispersion corrections") + dtype = torch.float32 if default_dtype == "float32" else torch.float64 + d3_calc = TorchDFTD3Calculator( + device=device, + damping=damping, + dtype=dtype, + xc=dispersion_xc, + cutoff=dispersion_cutoff, + **kwargs, + ) + + return SumCalculator([mace_calc, d3_calc]) + + +@overload +def mace_off(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ... + + +@overload +def mace_off( + *, return_raw_model: Literal[False] = False, **kwargs: Any +) -> MACECalculator: ... + + +def mace_off( + model: Optional[Union[str, Path]] = None, + device: str = "", + default_dtype: str = "float64", + return_raw_model: bool = False, + **kwargs, +) -> Union[MACECalculator, torch.nn.Module]: + """ + Constructs a MACECalculator with a pretrained model based on the MACE-OFF23 models. + The model is released under the ASL license. + Note: + If you are using this function, please cite the relevant paper by Kovacs et.al., arXiv:2312.15211 + + Args: + model (str, optional): Path to the model. Defaults to None which first checks for + a local model and then downloads the default medium model from https://github.com/ACEsuit/mace-off. + Specify "small", "medium" or "large" to download a smaller or larger model. + device (str, optional): Device to use for the model. Defaults to "cuda". + default_dtype (str, optional): Default dtype for the model. Defaults to "float64". + return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False. + **kwargs: Passed to MACECalculator. + + Returns: + MACECalculator: trained on the MACE-OFF23 dataset + """ + try: + if model in (None, "small", "medium", "large") or str(model).startswith( + "https:" + ): + urls = dict( + small="https://github.com/ACEsuit/mace-off/blob/main/mace_off23/MACE-OFF23_small.model?raw=true", + medium="https://github.com/ACEsuit/mace-off/raw/main/mace_off23/MACE-OFF23_medium.model?raw=true", + large="https://github.com/ACEsuit/mace-off/blob/main/mace_off23/MACE-OFF23_large.model?raw=true", + ) + checkpoint_url = ( + urls.get(model, urls["medium"]) + if model in (None, "small", "medium", "large") + else model + ) + cache_dir = get_cache_dir() + checkpoint_url_name = os.path.basename(checkpoint_url).split("?")[0] + cached_model_path = f"{cache_dir}/{checkpoint_url_name}" + if not os.path.isfile(cached_model_path): + os.makedirs(cache_dir, exist_ok=True) + # download and save to disk + print(f"Downloading MACE model from {checkpoint_url!r}") + print( + "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." + ) + print( + "ASL is based on the Gnu Public License, but does not permit commercial use" + ) + urllib.request.urlretrieve(checkpoint_url, cached_model_path) + print(f"Cached MACE model to {cached_model_path}") + model = cached_model_path + msg = f"Using MACE-OFF23 MODEL for MACECalculator with {model}" + print(msg) + else: + if not Path(model).exists(): + raise FileNotFoundError(f"{model} not found locally") + except Exception as exc: + raise RuntimeError("Model download failed and no local model found") from exc + + device = device or ("cuda" if torch.cuda.is_available() else "cpu") + + if return_raw_model: + return torch.load(model, map_location=device) + + if default_dtype == "float64": + print( + "Using float64 for MACECalculator, which is slower but more accurate. Recommended for geometry optimization." + ) + if default_dtype == "float32": + print( + "Using float32 for MACECalculator, which is faster but less accurate. Recommended for MD. Use float64 for geometry optimization." + ) + mace_calc = MACECalculator( + model_paths=model, device=device, default_dtype=default_dtype, **kwargs + ) + return mace_calc + + +@overload +def mace_anicc( + *, return_raw_model: Literal[True], **kwargs: Any +) -> torch.nn.Module: ... + + +@overload +def mace_anicc( + *, return_raw_model: Literal[False] = False, **kwargs: Any +) -> MACECalculator: ... + + +def mace_anicc( + device: str = "cuda", + model_path: Optional[str] = None, + return_raw_model: bool = False, +) -> Union[MACECalculator, torch.nn.Module]: + """ + Constructs a MACECalculator with a pretrained model based on the ANI (H, C, N, O). + The model is released under the MIT license. + Note: + If you are using this function, please cite the relevant paper associated with the MACE model, ANI dataset, and also the following: + - "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 + """ + if model_path is None: + model_path = os.path.join( + module_dir, "foundations_models/ani500k_large_CC.model" + ) + print( + "Using ANI couple cluster model for MACECalculator, see https://doi.org/10.1063/5.0155322" + ) + + if not os.path.exists(model_path): + model_dir = os.path.dirname(model_path) + os.makedirs(model_dir, exist_ok=True) + + # Download the model + print(f"Model not found at {model_path}. Downloading...") + model_url = "https://github.com/ACEsuit/mace/raw/main/mace/calculators/foundations_models/ani500k_large_CC.model" + + try: + + def report_progress(block_num, block_size, total_size): + downloaded = block_num * block_size + percent = min(100, downloaded * 100 / total_size) + if total_size > 0: + print( + f"\rDownloading model: {percent:.1f}% ({downloaded / 1024 / 1024:.1f} MB / {total_size / 1024 / 1024:.1f} MB)", + end="", + ) + + urllib.request.urlretrieve( + model_url, model_path, reporthook=report_progress + ) + print("\nDownload complete!") + + except Exception as e: + raise RuntimeError(f"Failed to download model: {e}") from e + + if return_raw_model: + return torch.load(model_path, map_location=device) + return MACECalculator( + model_paths=model_path, device=device, default_dtype="float64" + ) + + +@overload +def mace_omol(*, return_raw_model: Literal[True], **kwargs: Any) -> torch.nn.Module: ... + + +@overload +def mace_omol( + *, return_raw_model: Literal[False] = False, **kwargs: Any +) -> MACECalculator: ... + + +def mace_omol( + model: Optional[Union[str, Path]] = None, + device: str = "", + default_dtype: str = "float64", + return_raw_model: bool = False, + **kwargs, +) -> Union[MACECalculator, torch.nn.Module]: + """ + Constructs a MACECalculator with a pretrained model based on the MACE-OMOL models. + The model is released under the ASL license. + Note: + If you are using this function, please cite the relevant OMOL paper. + + Args: + model (str or Path, optional): Either a path to a local model file or a string specifier. + Use "extra_large" or None to download the default OMOL model. + device (str, optional): Device to use for the model. Defaults to "cuda" if available. + default_dtype (str, optional): Default dtype for the model. Defaults to "float64". + return_raw_model (bool, optional): Whether to return the raw model or an ASE calculator. Defaults to False. + **kwargs: Passed to MACECalculator. + + Returns: + MACECalculator: trained on the OMOL dataset. + """ + urls = { + "extra_large": "https://github.com/ACEsuit/mace-foundations/releases/download/mace_omol_0/MACE-omol-0-extra-large-1024.model" + } + + try: + if model is None or model == "extra_large": + checkpoint_url = urls["extra_large"] + elif isinstance(model, str) and model.startswith("https:"): + checkpoint_url = model + elif isinstance(model, (str, Path)) and Path(model).exists(): + checkpoint_url = str(model) + else: + raise ValueError( + f"Invalid model specification: {model}. " + f"Supported options: {list(urls.keys())}, a local file path, or a direct URL." + ) + + if checkpoint_url.startswith("http"): + cache_dir = get_cache_dir() + os.makedirs(cache_dir, exist_ok=True) + checkpoint_url_name = os.path.basename(checkpoint_url).split("?")[0] + cached_model_path = os.path.join(cache_dir, checkpoint_url_name) + + if not os.path.isfile(cached_model_path): + print(f"Downloading MACE model from {checkpoint_url!r}") + print( + "The model is distributed under the Academic Software License (ASL), see https://github.com/gabor1/ASL\n" + "To use the model, you accept the terms of the license.\n" + "ASL is based on the GNU Public License, but does not permit commercial use." + ) + urllib.request.urlretrieve(checkpoint_url, cached_model_path) + print(f"Cached MACE model to {cached_model_path}") + model = cached_model_path + else: + model = checkpoint_url + + except Exception as exc: + raise RuntimeError("Model download failed and no local model found") from exc + + device = device or ("cuda" if torch.cuda.is_available() else "cpu") + + if return_raw_model: + return torch.load(model, map_location=device) + + if default_dtype == "float64": + print( + "Using float64 for MACECalculator, recommended for geometry optimization." + ) + elif default_dtype == "float32": + print("Using float32 for MACECalculator, recommended for MD.") + + return MACECalculator( + model_paths=model, + device=device, + default_dtype=default_dtype, + **kwargs, + head="omol", + ) diff --git a/models/mace/mace/calculators/foundations_models/2023-12-03-mace-mp.model b/models/mace/mace/calculators/foundations_models/2023-12-03-mace-mp.model new file mode 100644 index 0000000000000000000000000000000000000000..b39e453dfebab1f344e648dfc756e1bcdd33a68f --- /dev/null +++ b/models/mace/mace/calculators/foundations_models/2023-12-03-mace-mp.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01bfe22100139f424713cf921144e5509cbe353d67aa9fa1be9c6e1e0ed35845 +size 44422970 diff --git a/models/mace/mace/calculators/foundations_models/ani500k_large_CC.model b/models/mace/mace/calculators/foundations_models/ani500k_large_CC.model new file mode 100644 index 0000000000000000000000000000000000000000..f0ecb324177e6d33145bdb76c007f796a26f0d74 --- /dev/null +++ b/models/mace/mace/calculators/foundations_models/ani500k_large_CC.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad311c590b7df90a1d4aa34d997a8c419fdb7ae777296350869614e9e07b69d +size 35632548 diff --git a/models/mace/mace/calculators/foundations_models/mace-mpa-0-medium.model b/models/mace/mace/calculators/foundations_models/mace-mpa-0-medium.model new file mode 100644 index 0000000000000000000000000000000000000000..a66dc2f233f12e53322e9cae61eb9a5070233816 --- /dev/null +++ b/models/mace/mace/calculators/foundations_models/mace-mpa-0-medium.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75428afe3a1d7d8062e19bcaabd5c433623cabf308242ec9fb493e38604fb638 +size 79462305 diff --git a/models/mace/mace/calculators/foundations_models/mp_vasp_e0.json b/models/mace/mace/calculators/foundations_models/mp_vasp_e0.json new file mode 100644 index 0000000000000000000000000000000000000000..017718799133493a6456dbed622efc4dd76b9a78 --- /dev/null +++ b/models/mace/mace/calculators/foundations_models/mp_vasp_e0.json @@ -0,0 +1,91 @@ +{ + "pbe": { + "1": -1.11734008, + "2": 0.00096759, + "3": -0.29754725, + "4": -0.01781697, + "5": -0.26885011, + "6": -1.26173507, + "7": -3.12438806, + "8": -1.54838784, + "9": -0.51882044, + "10": -0.01241601, + "11": -0.22883163, + "12": -0.00951015, + "13": -0.21630193, + "14": -0.8263903, + "15": -1.88816619, + "16": -0.89160769, + "17": -0.25828273, + "18": -0.04925973, + "19": -0.22697913, + "20": -0.0927795, + "21": -2.11396364, + "22": -2.50054871, + "23": -3.70477179, + "24": -5.60261985, + "25": -5.32541181, + "26": -3.52004933, + "27": -1.93555024, + "28": -0.9351969, + "29": -0.60025846, + "30": -0.1651332, + "31": -0.32990651, + "32": -0.77971828, + "33": -1.68367812, + "34": -0.76941032, + "35": -0.22213843, + "36": -0.0335879, + "37": -0.1881724, + "38": -0.06826294, + "39": -2.17084228, + "40": -2.28579303, + "41": -3.13429753, + "42": -4.60211419, + "43": -3.45201492, + "44": -2.38073513, + "45": -1.46855515, + "46": -1.4773126, + "47": -0.33954585, + "48": -0.16843877, + "49": -0.35470981, + "50": -0.83642657, + "51": -1.41101987, + "52": -0.65740879, + "53": -0.18964571, + "54": -0.00857582, + "55": -0.13771876, + "56": -0.03457659, + "57": -0.45580806, + "58": -1.3309175, + "59": -0.29671824, + "60": -0.30391193, + "61": -0.30898427, + "62": -0.25470891, + "63": -8.38001538, + "64": -10.38896525, + "65": -0.3059505, + "66": -0.30676216, + "67": -0.30874667, + "69": -0.25190039, + "70": -0.06431414, + "71": -0.31997586, + "72": -3.52770927, + "73": -3.54492209, + "75": -4.70108713, + "76": -2.88257209, + "77": -1.46779304, + "78": -0.50269936, + "79": -0.28801193, + "80": -0.12454674, + "81": -0.31737194, + "82": -0.77644932, + "83": -1.32627283, + "89": -0.26827152, + "90": -0.90817426, + "91": -2.47653193, + "92": -4.90438537, + "93": -7.63378961, + "94": -10.77237713 + } +} \ No newline at end of file diff --git a/models/mace/mace/calculators/lammps_mace.py b/models/mace/mace/calculators/lammps_mace.py new file mode 100644 index 0000000000000000000000000000000000000000..4211c37f6a5001d55510dbb110fa7d795ca1e57c --- /dev/null +++ b/models/mace/mace/calculators/lammps_mace.py @@ -0,0 +1,105 @@ +from typing import Dict, List, Optional + +import torch +from e3nn.util.jit import compile_mode + +from mace.tools.scatter import scatter_sum + + +@compile_mode("script") +class LAMMPS_MACE(torch.nn.Module): + def __init__(self, model, **kwargs): + super().__init__() + self.model = model + self.register_buffer("atomic_numbers", model.atomic_numbers) + self.register_buffer("r_max", model.r_max) + self.register_buffer("num_interactions", model.num_interactions) + if not hasattr(model, "heads"): + model.heads = [None] + self.register_buffer( + "head", + torch.tensor( + self.model.heads.index(kwargs.get("head", self.model.heads[-1])), + dtype=torch.long, + ).unsqueeze(0), + ) + + for param in self.model.parameters(): + param.requires_grad = False + + def forward( + self, + data: Dict[str, torch.Tensor], + local_or_ghost: torch.Tensor, + compute_virials: bool = False, + ) -> Dict[str, Optional[torch.Tensor]]: + num_graphs = data["ptr"].numel() - 1 + compute_displacement = False + if compute_virials: + compute_displacement = True + data["head"] = self.head + out = self.model( + data, + training=False, + compute_force=False, + compute_virials=False, + compute_stress=False, + compute_displacement=compute_displacement, + ) + node_energy = out["node_energy"] + if node_energy is None: + return { + "total_energy_local": None, + "node_energy": None, + "forces": None, + "virials": None, + } + positions = data["positions"] + displacement = out["displacement"] + forces: Optional[torch.Tensor] = torch.zeros_like(positions) + virials: Optional[torch.Tensor] = torch.zeros_like(data["cell"]) + # accumulate energies of local atoms + node_energy_local = node_energy * local_or_ghost + total_energy_local = scatter_sum( + src=node_energy_local, index=data["batch"], dim=-1, dim_size=num_graphs + ) + # compute partial forces and (possibly) partial virials + grad_outputs: List[Optional[torch.Tensor]] = [ + torch.ones_like(total_energy_local) + ] + if compute_virials and displacement is not None: + forces, virials = torch.autograd.grad( + outputs=[total_energy_local], + inputs=[positions, displacement], + grad_outputs=grad_outputs, + retain_graph=False, + create_graph=False, + allow_unused=True, + ) + if forces is not None: + forces = -1 * forces + else: + forces = torch.zeros_like(positions) + if virials is not None: + virials = -1 * virials + else: + virials = torch.zeros_like(displacement) + else: + forces = torch.autograd.grad( + outputs=[total_energy_local], + inputs=[positions], + grad_outputs=grad_outputs, + retain_graph=False, + create_graph=False, + allow_unused=True, + )[0] + if forces is not None: + forces = -1 * forces + else: + forces = torch.zeros_like(positions) + return { + "total_energy_local": total_energy_local, + "node_energy": node_energy, + "forces": forces, + "virials": virials, + } diff --git a/models/mace/mace/calculators/lammps_mliap_mace.py b/models/mace/mace/calculators/lammps_mliap_mace.py new file mode 100644 index 0000000000000000000000000000000000000000..9257faf5a72490b27c605fd030c04c523189bf36 --- /dev/null +++ b/models/mace/mace/calculators/lammps_mliap_mace.py @@ -0,0 +1,228 @@ +import logging +import os +import sys +import time +from contextlib import contextmanager +from typing import Dict, Tuple + +import torch +from ase.data import chemical_symbols +from e3nn.util.jit import compile_mode + +try: + from lammps.mliap.mliap_unified_abc import MLIAPUnified +except ImportError: + + class MLIAPUnified: + def __init__(self): + pass + + +class MACELammpsConfig: + """Configuration settings for MACE-LAMMPS integration.""" + + def __init__(self): + self.debug_time = self._get_env_bool("MACE_TIME", False) + self.debug_profile = self._get_env_bool("MACE_PROFILE", False) + self.profile_start_step = int(os.environ.get("MACE_PROFILE_START", "5")) + self.profile_end_step = int(os.environ.get("MACE_PROFILE_END", "10")) + self.allow_cpu = self._get_env_bool("MACE_ALLOW_CPU", False) + self.force_cpu = self._get_env_bool("MACE_FORCE_CPU", False) + + @staticmethod + def _get_env_bool(var_name: str, default: bool) -> bool: + return os.environ.get(var_name, str(default)).lower() in ( + "true", + "1", + "t", + "yes", + ) + + +@contextmanager +def timer(name: str, enabled: bool = True): + """Context manager for timing code blocks.""" + if not enabled: + yield + return + + start = time.perf_counter() + try: + yield + finally: + elapsed = time.perf_counter() - start + logging.info(f"Timer - {name}: {elapsed*1000:.3f} ms") + + +@compile_mode("script") +class MACEEdgeForcesWrapper(torch.nn.Module): + """Wrapper that adds per-pair force computation to a MACE model.""" + + def __init__(self, model: torch.nn.Module, **kwargs): + super().__init__() + self.model = model + self.register_buffer("atomic_numbers", model.atomic_numbers) + self.register_buffer("r_max", model.r_max) + self.register_buffer("num_interactions", model.num_interactions) + self.register_buffer( + "total_charge", + kwargs.get( + "total_charge", torch.tensor([0.0], dtype=torch.get_default_dtype()) + ), + ) + self.register_buffer( + "total_spin", + kwargs.get( + "total_spin", torch.tensor([1.0], dtype=torch.get_default_dtype()) + ), + ) + + if not hasattr(model, "heads"): + model.heads = ["Default"] + + head_name = kwargs.get("head", model.heads[-1]) + head_idx = model.heads.index(head_name) + self.register_buffer("head", torch.tensor([head_idx], dtype=torch.long)) + + for p in self.model.parameters(): + p.requires_grad = False + + def forward( + self, data: Dict[str, torch.Tensor] + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Compute energies and per-pair forces.""" + data["head"] = self.head + data["total_charge"] = self.total_charge + data["total_spin"] = self.total_spin + + out = self.model( + data, + training=False, + compute_force=False, + compute_virials=False, + compute_stress=False, + compute_displacement=False, + compute_edge_forces=True, + lammps_mliap=True, + ) + + node_energy = out["node_energy"] + pair_forces = out["edge_forces"] + total_energy = out["energy"][0] + + if pair_forces is None: + pair_forces = torch.zeros_like(data["vectors"]) + + return total_energy, node_energy, pair_forces + + +class LAMMPS_MLIAP_MACE(MLIAPUnified): + """MACE integration for LAMMPS using the MLIAP interface.""" + + def __init__(self, model, **kwargs): + super().__init__() + self.config = MACELammpsConfig() + self.model = MACEEdgeForcesWrapper(model, **kwargs) + self.element_types = [chemical_symbols[s] for s in model.atomic_numbers] + self.num_species = len(self.element_types) + self.rcutfac = 0.5 * float(model.r_max) + self.ndescriptors = 1 + self.nparams = 1 + self.dtype = model.r_max.dtype + self.device = "cpu" + self.initialized = False + self.step = 0 + + def _initialize_device(self, data): + using_kokkos = "kokkos" in data.__class__.__module__.lower() + + if using_kokkos and not self.config.force_cpu: + device = torch.as_tensor(data.elems).device + if device.type == "cpu" and not self.config.allow_cpu: + raise ValueError( + "GPU requested but tensor is on CPU. Set MACE_ALLOW_CPU=true to allow CPU computation." + ) + else: + device = torch.device("cpu") + + self.device = device + self.model = self.model.to(device) + logging.info(f"MACE model initialized on device: {device}") + self.initialized = True + + def compute_forces(self, data): + natoms = data.nlocal + ntotal = data.ntotal + nghosts = ntotal - natoms + npairs = data.npairs + species = torch.as_tensor(data.elems, dtype=torch.int64) + + if not self.initialized: + self._initialize_device(data) + + self.step += 1 + self._manage_profiling() + + if natoms == 0 or npairs <= 1: + return + + with timer("total_step", enabled=self.config.debug_time): + with timer("prepare_batch", enabled=self.config.debug_time): + batch = self._prepare_batch(data, natoms, nghosts, species) + + with timer("model_forward", enabled=self.config.debug_time): + _, atom_energies, pair_forces = self.model(batch) + + if self.device.type != "cpu": + torch.cuda.synchronize() + + with timer("update_lammps", enabled=self.config.debug_time): + self._update_lammps_data(data, atom_energies, pair_forces, natoms) + + def _prepare_batch(self, data, natoms, nghosts, species): + """Prepare the input batch for the MACE model.""" + return { + "vectors": torch.as_tensor(data.rij).to(self.dtype).to(self.device), + "node_attrs": torch.nn.functional.one_hot( + species.to(self.device), num_classes=self.num_species + ).to(self.dtype), + "edge_index": torch.stack( + [ + torch.as_tensor(data.pair_j, dtype=torch.int64).to(self.device), + torch.as_tensor(data.pair_i, dtype=torch.int64).to(self.device), + ], + dim=0, + ), + "batch": torch.zeros(natoms, dtype=torch.int64, device=self.device), + "lammps_class": data, + "natoms": (natoms, nghosts), + } + + def _update_lammps_data(self, data, atom_energies, pair_forces, natoms): + """Update LAMMPS data structures with computed energies and forces.""" + if self.dtype == torch.float32: + pair_forces = pair_forces.double() + eatoms = torch.as_tensor(data.eatoms) + eatoms.copy_(atom_energies[:natoms]) + data.energy = torch.sum(atom_energies[:natoms]) + data.update_pair_forces_gpu(pair_forces) + + def _manage_profiling(self): + if not self.config.debug_profile: + return + + if self.step == self.config.profile_start_step: + logging.info(f"Starting CUDA profiler at step {self.step}") + torch.cuda.profiler.start() + + if self.step == self.config.profile_end_step: + logging.info(f"Stopping CUDA profiler at step {self.step}") + torch.cuda.profiler.stop() + logging.info("Profiling complete. Exiting.") + sys.exit() + + def compute_descriptors(self, data): + pass + + def compute_gradients(self, data): + pass diff --git a/models/mace/mace/calculators/mace.py b/models/mace/mace/calculators/mace.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c05b81d1c8c91bf532ce6d45d93a41f8a0afce --- /dev/null +++ b/models/mace/mace/calculators/mace.py @@ -0,0 +1,620 @@ +########################################################################################### +# The ASE Calculator for MACE +# Authors: Ilyes Batatia, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import logging + +# pylint: disable=wrong-import-position +import os +from glob import glob +from pathlib import Path +from typing import List, Union + +os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1" + +import numpy as np +import torch +from ase.calculators.calculator import Calculator, all_changes +from ase.stress import full_3x3_to_voigt_6_stress +from e3nn import o3 + +from mace import data as mace_data +from mace.modules.utils import extract_invariant +from mace.tools import torch_geometric, torch_tools, utils +from mace.tools.compile import prepare +from mace.tools.scripts_utils import extract_model + +try: + from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq + + CUEQQ_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + CUEQQ_AVAILABLE = False + run_e3nn_to_cueq = None + +try: + from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq + + OEQ_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + OEQ_AVAILABLE = False + run_e3nn_to_oeq = None + +try: + import intel_extension_for_pytorch as ipex + + has_ipex = True +except ImportError: + has_ipex = False + + +def get_model_dtype(model: torch.nn.Module) -> torch.dtype: + """Get the dtype of the model""" + mode_dtype = next(model.parameters()).dtype + if mode_dtype == torch.float64: + return "float64" + if mode_dtype == torch.float32: + return "float32" + raise ValueError(f"Unknown dtype {mode_dtype}") + + +class MACECalculator(Calculator): + """MACE ASE Calculator + args: + model_paths: str, path to model or models if a committee is produced + to make a committee use a wild card notation like mace_*.model + device: str, device to run on (cuda or cpu or xpu) + energy_units_to_eV: float, conversion factor from model energy units to eV + length_units_to_A: float, conversion factor from model length units to Angstroms + default_dtype: str, default dtype of model + charges_key: str, Array field of atoms object where atomic charges are stored + model_type: str, type of model to load + Options: [MACE, DipoleMACE, EnergyDipoleMACE] + + Dipoles are returned in units of Debye + """ + + def __init__( + self, + model_paths: Union[list, str, None] = None, + models: Union[List[torch.nn.Module], torch.nn.Module, None] = None, + device: str = "cpu", + energy_units_to_eV: float = 1.0, + length_units_to_A: float = 1.0, + default_dtype="", + charges_key="Qs", + info_keys=None, + arrays_keys=None, + model_type="MACE", + compile_mode=None, + fullgraph=True, + enable_cueq=False, + enable_oeq=False, + **kwargs, + ): + Calculator.__init__(self, **kwargs) + if enable_cueq or enable_oeq: + assert model_type == "MACE", "CuEq only supports MACE models" + if compile_mode is not None: + logging.warning( + "CuEq or Oeq does not support torch.compile, setting compile_mode to None" + ) + compile_mode = None + if enable_cueq and enable_oeq: + raise ValueError( + "CuEq and OEq cannot be used together, please choose one of them" + ) + if enable_cueq and not CUEQQ_AVAILABLE: + raise ImportError( + "cuequivariance is not installed so CuEq acceleration cannot be used" + ) + if enable_oeq and not OEQ_AVAILABLE: + raise ImportError( + "openequivariance is not installed so OEq acceleration cannot be used" + ) + if "model_path" in kwargs: + deprecation_message = ( + "'model_path' argument is deprecated, please use 'model_paths'" + ) + if model_paths is None: + logging.warning(f"{deprecation_message} in the future.") + model_paths = kwargs["model_path"] + else: + raise ValueError( + f"both 'model_path' and 'model_paths' given, {deprecation_message} only." + ) + + if (model_paths is None) == (models is None): + raise ValueError( + "Exactly one of 'model_paths' or 'models' must be provided" + ) + + self.results = {} + if info_keys is None: + info_keys = {"total_spin": "spin", "total_charge": "charge"} + if arrays_keys is None: + arrays_keys = {} + self.info_keys = info_keys + self.arrays_keys = arrays_keys + + self.model_type = model_type + self.compute_atomic_stresses = False + + if model_type not in [ + "MACE", + "DipoleMACE", + "EnergyDipoleMACE", + "DipolePolarizabilityMACE", + ]: + raise ValueError( + f"Give a valid model_type: [MACE, DipoleMACE, DipolePolarizabilityMACE, EnergyDipoleMACE], {model_type} not supported" + ) + + # superclass constructor initializes self.implemented_properties to an empty list + if model_type in ["MACE", "EnergyDipoleMACE"]: + self.implemented_properties.extend( + [ + "energy", + "energies", + "free_energy", + "node_energy", + "forces", + "stress", + ] + ) + if kwargs.get("compute_atomic_stresses", False): + self.implemented_properties.extend(["stresses", "virials"]) + self.compute_atomic_stresses = True + if model_type in ["EnergyDipoleMACE", "DipoleMACE", "DipolePolarizabilityMACE"]: + self.implemented_properties.extend(["dipole"]) + if model_type == "DipolePolarizabilityMACE": + self.implemented_properties.extend( + [ + "charges", + "polarizability", + "polarizability_sh", + ] + ) + + if model_paths is not None: + if isinstance(model_paths, str): + # Find all models that satisfy the wildcard (e.g. mace_model_*.pt) + model_paths_glob = glob(model_paths) + + if len(model_paths_glob) == 0: + raise ValueError(f"Couldn't find MACE model files: {model_paths}") + + model_paths = model_paths_glob + elif isinstance(model_paths, Path): + model_paths = [model_paths] + + if len(model_paths) == 0: + raise ValueError("No mace file names supplied") + self.num_models = len(model_paths) + + # Load models from files + self.models = [ + torch.load(f=model_path, map_location=device) + for model_path in model_paths + ] + + + elif models is not None: + if not isinstance(models, list): + models = [models] + + if len(models) == 0: + raise ValueError("No models supplied") + + self.models = models + self.num_models = len(models) + + if self.num_models > 1: + logging.info(f"Running committee mace with {self.num_models} models") + + if model_type in ["MACE", "EnergyDipoleMACE"]: + self.implemented_properties.extend( + ["energy_comm", "energy_var", "forces_comm", "stress_var"] + ) + if model_type in [ + "DipoleMACE", + "EnergyDipoleMACE", + "DipolePolarizabilityMACE", + ]: + self.implemented_properties.extend(["dipole_var"]) + + if compile_mode is not None: + logging.info(f"Torch compile is enabled with mode: {compile_mode}") + self.models = [ + torch.compile( + prepare(extract_model)(model=model, map_location=device), + mode=compile_mode, + fullgraph=fullgraph, + ) + for model in self.models + ] + self.use_compile = True + else: + self.use_compile = False + + # Ensure all models are on the same device + for model in self.models: + model.to(device) + + if has_ipex and device == "xpu": + for model in self.models: + model = ipex.optimize(model) + + r_maxs = [model.r_max.cpu() for model in self.models] + r_maxs = np.array(r_maxs) + if not np.all(r_maxs == r_maxs[0]): + raise ValueError(f"committee r_max are not all the same {' '.join(r_maxs)}") + self.r_max = float(r_maxs[0]) + + self.device = torch_tools.init_device(device) + self.energy_units_to_eV = energy_units_to_eV + self.length_units_to_A = length_units_to_A + self.z_table = utils.AtomicNumberTable( + [int(z) for z in self.models[0].atomic_numbers] + ) + self.charges_key = charges_key + + try: + self.available_heads: List[str] = self.models[0].heads # type: ignore + except AttributeError: + self.available_heads = ["Default"] + kwarg_head = kwargs.get("head", None) + if kwarg_head is not None: + self.head = kwarg_head + if isinstance(self.head, str): + if self.head not in self.available_heads: + last_head = self.available_heads[-1] + logging.warning( + f"Head {self.head} not found in available heads {self.available_heads}, defaulting to the last head: {last_head}" + ) + self.head = last_head + elif len(self.available_heads) == 1: + self.head = self.available_heads[0] + else: + self.head = [ + head for head in self.available_heads if head.lower() == "default" + ] + if len(self.head) == 0: + raise ValueError( + "Head keyword was not provided, and no head in the model is 'default'. " + "Please provide a head keyword to specify the head you want to use. " + f"Available heads are: {self.available_heads}" + ) + self.head = self.head[0] + + logging.info(f"Using head {self.head} out of {self.available_heads}") + + model_dtype = get_model_dtype(self.models[0]) + if default_dtype == "": + logging.warning( + f"No dtype selected, switching to {model_dtype} to match model dtype." + ) + default_dtype = model_dtype + if model_dtype != default_dtype: + logging.warning( + f"Default dtype {default_dtype} does not match model dtype {model_dtype}, converting models to {default_dtype}." + ) + if default_dtype == "float64": + self.models = [model.double() for model in self.models] + elif default_dtype == "float32": + self.models = [model.float() for model in self.models] + torch_tools.set_default_dtype(default_dtype) + if enable_cueq: + logging.info("Converting models to CuEq for acceleration") + self.models = [ + run_e3nn_to_cueq(model, device=device).to(device) + for model in self.models + ] + if enable_oeq: + logging.info("Converting models to OEq for acceleration") + self.models = [ + run_e3nn_to_oeq(model, device=device).to(device) + for model in self.models + ] + for model in self.models: + for param in model.parameters(): + param.requires_grad = False + + def check_state(self, atoms, tol: float = 1e-15) -> list: + """ + Check for any system changes since the last calculation. + + Args: + atoms (ase.Atoms): The atomic structure to check. + tol (float): Tolerance for detecting changes. + + Returns: + list: A list of changes detected in the system. + """ + state = super().check_state(atoms, tol=tol) + if (not state) and (self.atoms.info != atoms.info): + state.append("info") + return state + + def _create_result_tensors( + self, num_models: int, num_atoms: int, batch, out: dict + ) -> dict: + # unfortunately, code is expecting shape that isn't always same as underlying model + # output tensor shape, e.g. stress is returned as 1x3x3 and we want 3x3 + tensor_shapes = { + "energy": [], + "node_energy": [num_atoms], + "forces": [num_atoms, 3], + "stress": [3, 3], + "atomic_stresses": [num_atoms, 3, 3], + "atomic_virials": [num_atoms, 3, 3], + "dipole": [3], + "charges": [num_atoms], + "polarizability": [3, 3], + "polarizability_sh": [6], + } + dict_of_tensors = {} + for key in out: + if key not in tensor_shapes or out.get(key) is None: + continue + shape = [num_models] + tensor_shapes[key] + dict_of_tensors[key] = torch.zeros(*shape, device=self.device) + + node_e0 = None + if "node_energy" in out: + node_heads = batch["head"][batch["batch"]] + num_atoms_arange = torch.arange(batch["positions"].shape[0]) + node_e0 = ( + self.models[0] + .atomic_energies_fn(batch["node_attrs"])[num_atoms_arange, node_heads] + .detach() + .cpu() + .numpy() + ) + + return dict_of_tensors, node_e0 + + def _atoms_to_batch(self, atoms): + self.arrays_keys.update({self.charges_key: "charges"}) + keyspec = mace_data.KeySpecification( + info_keys=self.info_keys, arrays_keys=self.arrays_keys + ) + config = mace_data.config_from_atoms( + atoms, key_specification=keyspec, head_name=self.head + ) + + + data_loader = torch_geometric.dataloader.DataLoader( + dataset=[ + mace_data.AtomicData.from_config( + config, + z_table=self.z_table, + cutoff=self.r_max, + heads=self.available_heads, + ) + ], + batch_size=1, + shuffle=False, + drop_last=False, + ) + batch = next(iter(data_loader)).to(self.device) + return batch + + def _clone_batch(self, batch): + batch_clone = batch.clone() + if self.use_compile: + batch_clone["node_attrs"].requires_grad_(True) + batch_clone["positions"].requires_grad_(True) + return batch_clone + + # pylint: disable=dangerous-default-value + def calculate(self, atoms=None, properties=None, system_changes=all_changes): + """ + Calculate properties. + :param atoms: ase.Atoms object + :param properties: [str], properties to be computed, used by ASE internally + :param system_changes: [str], system changes since last calculation, used by ASE internally + :return: + """ + # call to base-class to set atoms attribute + Calculator.calculate(self, atoms) + + + batch_base = self._atoms_to_batch(atoms) + + if self.model_type in ["MACE", "EnergyDipoleMACE"]: + compute_stress = not self.use_compile + else: + compute_stress = False + + ret_tensors = None + node_e0 = None + + + # copy from output of model() call to ret_tensors + for i, model in enumerate(self.models): + batch = self._clone_batch(batch_base) + #print(type(model)) # Scale shift mace + out = model( + batch.to_dict(), + compute_stress=compute_stress, # Fakse + compute_force = True, + training=self.use_compile, #false + compute_edge_forces=self.compute_atomic_stresses, #False + compute_atomic_stresses=self.compute_atomic_stresses, # False + ) + if i == 0: + ret_tensors, node_e0 = self._create_result_tensors( + self.num_models, len(atoms), batch, out + ) + for key, val in ret_tensors.items(): + if out.get(key) is not None: + val[i] = out[key].detach() + + # covert from ret_tensors to calculator results dict + self.results = {} + scalar_tensors = set(["energy"]) + results_store_ensemble = set(["energy", "forces", "stress", "dipole"]) + for results_key, ret_key, unit_conv in [ + ("energy", "energy", self.energy_units_to_eV), + ("node_energy", "node_energy", self.energy_units_to_eV), + ("forces", "forces", self.energy_units_to_eV / self.length_units_to_A), + ("stress", "stress", self.energy_units_to_eV / self.length_units_to_A**3), + ( + "stresses", + "atomic_stresses", + self.energy_units_to_eV / self.length_units_to_A**3, + ), + ( + "virials", + "atomic_virials", + self.energy_units_to_eV / self.length_units_to_A**3, + ), + ("dipole", "dipole", 1.0), + ("charges", "charges", 1.0), + ("polarizability", "polarizability", 1.0), + ("polarizability_sh", "polarizability_sh", 1.0), + ]: + if ret_tensors.get(ret_key) is not None: + data = torch.mean(ret_tensors[ret_key], dim=0).cpu() + if ret_key in scalar_tensors: + data = data.item() + else: + data = data.numpy() + self.results[results_key] = data * unit_conv + + if self.num_models > 1 and results_key in results_store_ensemble: + data = ret_tensors[results_key].cpu().numpy() + data *= unit_conv + self.results[results_key + "_comm"] = data + + data = torch.var( + ret_tensors[results_key], dim=0, unbiased=False + ).cpu() + if ret_key in scalar_tensors: + data = data.item() + else: + data = data.numpy() + data *= unit_conv + self.results[results_key + "_var"] = data + + # special cases + if self.results.get("energy") is not None: + self.results["free_energy"] = self.results["energy"] + if self.results.get("node_energy") is not None: + self.results["energies"] = self.results["node_energy"].copy() + self.results["node_energy"] -= node_e0 + if self.results.get("stress") is not None: + self.results["stress"] = full_3x3_to_voigt_6_stress(self.results["stress"]) + if self.results.get("stresses") is not None: + self.results["stresses"] = np.asarray( + [ + full_3x3_to_voigt_6_stress(stress) + for stress in self.results["stresses"] + ] + ) + + def get_dielectric_derivatives(self, atoms=None): + if atoms is None and self.atoms is None: + raise ValueError("atoms not set") + if atoms is None: + atoms = self.atoms + if self.model_type not in ["DipoleMACE", "DipolePolarizabilityMACE"]: + raise NotImplementedError( + "Only implemented for DipoleMACE or DipolePolarizabilityMACE models" + ) + batch = self._atoms_to_batch(atoms) + outputs = [ + model( + self._clone_batch(batch).to_dict(), + compute_dielectric_derivatives=True, + training=self.use_compile, + ) + for model in self.models + ] + dipole_derivatives = [ + output["dmu_dr"].clone().detach().cpu().numpy() for output in outputs + ] + if self.models[0].use_polarizability: + polarizability_derivatives = [ + output["dalpha_dr"].clone().detach().cpu().numpy() for output in outputs + ] + if self.num_models == 1: + dipole_derivatives = dipole_derivatives[0] + polarizability_derivatives = polarizability_derivatives[0] + del outputs, batch, atoms + return dipole_derivatives, polarizability_derivatives + if self.num_models == 1: + return dipole_derivatives[0] + del outputs, batch, atoms + return dipole_derivatives + + def get_hessian(self, atoms=None): + if atoms is None and self.atoms is None: + raise ValueError("atoms not set") + if atoms is None: + atoms = self.atoms + if self.model_type != "MACE": + raise NotImplementedError("Only implemented for MACE models") + batch = self._atoms_to_batch(atoms) + hessians = [ + model( + self._clone_batch(batch).to_dict(), + compute_hessian=True, + compute_stress=False, + training=self.use_compile, + )["hessian"] + for model in self.models + ] + hessians = [hessian.detach().cpu().numpy() for hessian in hessians] + if self.num_models == 1: + return hessians[0] + return hessians + + def get_descriptors(self, atoms=None, invariants_only=True, num_layers=-1): + """Extracts the descriptors from MACE model. + :param atoms: ase.Atoms object + :param invariants_only: bool, if True only the invariant descriptors are returned + :param num_layers: int, number of layers to extract descriptors from, if -1 all layers are used + :return: np.ndarray (num_atoms, num_interactions, invariant_features) of invariant descriptors if num_models is 1 or list[np.ndarray] otherwise + """ + if atoms is None and self.atoms is None: + raise ValueError("atoms not set") + if atoms is None: + atoms = self.atoms + if self.model_type != "MACE": + raise NotImplementedError("Only implemented for MACE models") + num_interactions = int(self.models[0].num_interactions) + if num_layers == -1: + num_layers = num_interactions + batch = self._atoms_to_batch(atoms) + descriptors = [model(batch.to_dict())["node_feats"] for model in self.models] + + irreps_out = o3.Irreps(str(self.models[0].products[0].linear.irreps_out)) + l_max = irreps_out.lmax + num_invariant_features = irreps_out.dim // (l_max + 1) ** 2 + per_layer_features = [irreps_out.dim for _ in range(num_interactions)] + per_layer_features[-1] = ( + num_invariant_features # Equivariant features not created for the last layer + ) + + if invariants_only: + descriptors = [ + extract_invariant( + descriptor, + num_layers=num_layers, + num_features=num_invariant_features, + l_max=l_max, + ) + for descriptor in descriptors + ] + to_keep = np.sum(per_layer_features[:num_layers]) + descriptors = [ + descriptor[:, :to_keep].detach().cpu().numpy() for descriptor in descriptors + ] + + if self.num_models == 1: + return descriptors[0] + return descriptors diff --git a/models/mace/mace/cli/__init__.py b/models/mace/mace/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/models/mace/mace/cli/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c152cb49bc230b11a8c70499458d229fc99228b4 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/convert_cueq_e3nn.cpython-310.pyc b/models/mace/mace/cli/__pycache__/convert_cueq_e3nn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06934187d5e1849062b89c9594e11314bca34038 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/convert_cueq_e3nn.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/convert_e3nn_cueq.cpython-310.pyc b/models/mace/mace/cli/__pycache__/convert_e3nn_cueq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af4046b29c1b4b32cc90e9a62aba06bf5527a25c Binary files /dev/null and b/models/mace/mace/cli/__pycache__/convert_e3nn_cueq.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/convert_e3nn_oeq.cpython-310.pyc b/models/mace/mace/cli/__pycache__/convert_e3nn_oeq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d971f195756f0ba8187c30b20f6ea6d2e65145e2 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/convert_e3nn_oeq.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/convert_oeq_e3nn.cpython-310.pyc b/models/mace/mace/cli/__pycache__/convert_oeq_e3nn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..454bcc622eeb0b44a3c356ad64e904700cb32be9 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/convert_oeq_e3nn.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/eval_configs.cpython-310.pyc b/models/mace/mace/cli/__pycache__/eval_configs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91cc0e876daae352c7a9402f14da0ad5a23295bc Binary files /dev/null and b/models/mace/mace/cli/__pycache__/eval_configs.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/fine_tuning_select.cpython-310.pyc b/models/mace/mace/cli/__pycache__/fine_tuning_select.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8ced232fbbf5feb635fb5da76183026a5abac1b Binary files /dev/null and b/models/mace/mace/cli/__pycache__/fine_tuning_select.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/preprocess_data.cpython-310.pyc b/models/mace/mace/cli/__pycache__/preprocess_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4426dd7ed4c3e33aaf35d45c2ddb03f862a2344d Binary files /dev/null and b/models/mace/mace/cli/__pycache__/preprocess_data.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_calc.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_calc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c299498f287c8bfbb68a270c742e4eff617824cc Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_calc.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_eval.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff4ce32302ec2a8afdcac3e7429fd861ece68f17 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_eval.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_eval_copy.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_eval_copy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85719977face324d8117a9a2fb1e38089eeb0700 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_eval_copy.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_eval_foundation.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_eval_foundation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9a7950fd7a69be5a8a099a4d3d791eef5414f40 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_eval_foundation.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_foundation.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_foundation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e84a4abc236ea21f44b88d44d3fa16ae9f2b6a2 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_foundation.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_inference_speed.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_inference_speed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd4adca5b2f8a53b5b207053921e9a65951bf008 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_inference_speed.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_jonas_calc.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_jonas_calc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b75e97637698e8058dd3c2142f957768d8a59824 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_jonas_calc.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/run_train.cpython-310.pyc b/models/mace/mace/cli/__pycache__/run_train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..916de95be7d390ba5048753fd1cc7511cc0e1296 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/run_train.cpython-310.pyc differ diff --git a/models/mace/mace/cli/__pycache__/visualise_train.cpython-310.pyc b/models/mace/mace/cli/__pycache__/visualise_train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3640405bb83a01c8c43a5d78d74a5b5af9acb332 Binary files /dev/null and b/models/mace/mace/cli/__pycache__/visualise_train.cpython-310.pyc differ diff --git a/models/mace/mace/cli/active_learning_md.py b/models/mace/mace/cli/active_learning_md.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf4f4a8817bccda23bc411dee3b9fe809681ac5 --- /dev/null +++ b/models/mace/mace/cli/active_learning_md.py @@ -0,0 +1,193 @@ +"""Demonstrates active learning molecular dynamics with constant temperature.""" + +import argparse +import os +import time + +import ase.io +import numpy as np +from ase import units +from ase.md.langevin import Langevin +from ase.md.velocitydistribution import MaxwellBoltzmannDistribution + +from mace.calculators.mace import MACECalculator + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("--config", help="path to XYZ configurations", required=True) + parser.add_argument( + "--config_index", help="index of configuration", type=int, default=-1 + ) + parser.add_argument( + "--error_threshold", help="error threshold", type=float, default=0.1 + ) + parser.add_argument("--temperature_K", help="temperature", type=float, default=300) + parser.add_argument("--friction", help="friction", type=float, default=0.01) + parser.add_argument("--timestep", help="timestep", type=float, default=1) + parser.add_argument("--nsteps", help="number of steps", type=int, default=1000) + parser.add_argument( + "--nprint", help="number of steps between prints", type=int, default=10 + ) + parser.add_argument( + "--nsave", help="number of steps between saves", type=int, default=10 + ) + parser.add_argument( + "--ncheckerror", help="number of steps between saves", type=int, default=10 + ) + + parser.add_argument( + "--model", + help="path to model. Use wildcards to add multiple models as committee eg " + "(`mace_*.model` to load mace_1.model, mace_2.model) ", + required=True, + ) + parser.add_argument("--output", help="output path", required=True) + parser.add_argument( + "--device", + help="select device", + type=str, + choices=["cpu", "cuda"], + default="cuda", + ) + parser.add_argument( + "--default_dtype", + help="set default dtype", + type=str, + choices=["float32", "float64"], + default="float64", + ) + parser.add_argument( + "--compute_stress", + help="compute stress", + action="store_true", + default=False, + ) + parser.add_argument( + "--info_prefix", + help="prefix for energy, forces and stress keys", + type=str, + default="MACE_", + ) + return parser.parse_args() + + +def printenergy(dyn, start_time=None): # store a reference to atoms in the definition. + """Function to print the potential, kinetic and total energy.""" + a = dyn.atoms + epot = a.get_potential_energy() / len(a) + ekin = a.get_kinetic_energy() / len(a) + if start_time is None: + elapsed_time = 0 + else: + elapsed_time = time.time() - start_time + forces_var = np.var(a.calc.results["forces_comm"], axis=0) + print( + "%.1fs: Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) " # pylint: disable=C0209 + "Etot = %.3feV t=%.1ffs Eerr = %.3feV Ferr = %.3feV/A" + % ( + elapsed_time, + epot, + ekin, + ekin / (1.5 * units.kB), + epot + ekin, + dyn.get_time() / units.fs, + a.calc.results["energy_var"], + np.max(np.linalg.norm(forces_var, axis=1)), + ), + flush=True, + ) + + +def save_config(dyn, fname): + atomsi = dyn.atoms + ens = atomsi.get_potential_energy() + frcs = atomsi.get_forces() + + atomsi.info.update( + { + "mlff_energy": ens, + "time": np.round(dyn.get_time() / units.fs, 5), + "mlff_energy_var": atomsi.calc.results["energy_var"], + } + ) + atomsi.arrays.update( + { + "mlff_forces": frcs, + "mlff_forces_var": np.var(atomsi.calc.results["forces_comm"], axis=0), + } + ) + + ase.io.write(fname, atomsi, append=True) + + +def stop_error(dyn, threshold, reg=0.2): + atomsi = dyn.atoms + force_var = np.var(atomsi.calc.results["forces_comm"], axis=0) + force = atomsi.get_forces() + ferr = np.sqrt(np.sum(force_var, axis=1)) + ferr_rel = ferr / (np.linalg.norm(force, axis=1) + reg) + + if np.max(ferr_rel) > threshold: + print( + "Error too large {:.3}. Stopping t={:.2} fs.".format( # pylint: disable=C0209 + np.max(ferr_rel), dyn.get_time() / units.fs + ), + flush=True, + ) + dyn.max_steps = 0 + + +def main() -> None: + args = parse_args() + run(args) + + +def run(args: argparse.Namespace) -> None: + mace_fname = args.model + atoms_fname = args.config + atoms_index = args.config_index + + mace_calc = MACECalculator( + model_paths=mace_fname, + device=args.device, + default_dtype=args.default_dtype, + ) + + NSTEPS = args.nsteps + + if os.path.exists(args.output): + print("Trajectory exists. Continuing from last step.") + atoms = ase.io.read(args.output, index=-1) + len_save = len(ase.io.read(args.output, ":")) + print("Last step: ", atoms.info["time"], "Number of configs: ", len_save) + NSTEPS -= len_save * args.nsave + else: + atoms = ase.io.read(atoms_fname, index=atoms_index) + MaxwellBoltzmannDistribution(atoms, temperature_K=args.temperature_K) + + atoms.calc = mace_calc + + # We want to run MD with constant energy using the Langevin algorithm + # with a time step of 5 fs, the temperature T and the friction + # coefficient to 0.02 atomic units. + dyn = Langevin( + atoms=atoms, + timestep=args.timestep * units.fs, + temperature_K=args.temperature_K, + friction=args.friction, + ) + + dyn.attach(printenergy, interval=args.nsave, dyn=dyn, start_time=time.time()) + dyn.attach(save_config, interval=args.nsave, dyn=dyn, fname=args.output) + dyn.attach( + stop_error, interval=args.ncheckerror, dyn=dyn, threshold=args.error_threshold + ) + # Now run the dynamics + dyn.run(NSTEPS) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/convert_cueq_e3nn.py b/models/mace/mace/cli/convert_cueq_e3nn.py new file mode 100644 index 0000000000000000000000000000000000000000..3dacb82c0182b4083c8635dc5bd0a944ac1d7ad7 --- /dev/null +++ b/models/mace/mace/cli/convert_cueq_e3nn.py @@ -0,0 +1,259 @@ +import argparse +import logging +import os +from typing import Dict, List, Tuple, Union + +import numpy as np +import torch +from e3nn import o3 + +from mace.tools.cg import O3_e3nn +from mace.tools.cg_cueq_tools import symmetric_contraction_proj +from mace.tools.scripts_utils import extract_config_mace_model + +try: + import cuequivariance as cue + + CUEQQ_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + CUEQQ_AVAILABLE = False + cue = None + +SizeLike = Union[torch.Size, List[int]] + + +def shapes_match_up_to_unsqueeze(a: SizeLike, b: SizeLike) -> bool: + if isinstance(a, torch.Tensor): + a = a.shape + if isinstance(b, torch.Tensor): + b = b.shape + + def drop(s): + return tuple(d for d in s if d != 1) + + return drop(a) == drop(b) + + +def reshape_like(src: torch.Tensor, ref_shape: torch.Size) -> torch.Tensor: + try: + return src.reshape(ref_shape) + except RuntimeError: + return src.clone().reshape(ref_shape) + + +def get_kmax_pairs( + num_product_irreps: int, correlation: int, num_layers: int +) -> List[Tuple[int, int]]: + """Determine kmax pairs based on num_product_irreps and correlation""" + if correlation == 2: + kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)] + kmax_pairs = kmax_pairs + [[num_layers - 1, 0]] + return kmax_pairs + if correlation == 3: + kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)] + kmax_pairs = kmax_pairs + [[num_layers - 1, 0]] + return kmax_pairs + raise NotImplementedError(f"Correlation {correlation} not supported") + + +def transfer_symmetric_contractions( + source_dict: Dict[str, torch.Tensor], + target_dict: Dict[str, torch.Tensor], + num_product_irreps: int, + products: torch.nn.Module, + correlation: int, + num_layers: int, + use_reduced_cg: bool, +): + """Transfer symmetric contraction weights from CuEq to E3nn format""" + kmax_pairs = get_kmax_pairs(num_product_irreps, correlation, num_layers) + suffixes = ["_max"] + [f".{i}" for i in range(correlation - 1)] + for i, kmax in kmax_pairs: + # Get the combined weight tensor from source + irreps_in = o3.Irreps( + irrep.ir for irrep in products[i].symmetric_contractions.irreps_in + ) + irreps_out = o3.Irreps( + irrep.ir for irrep in products[i].symmetric_contractions.irreps_out + ) + wm = source_dict[f"products.{i}.symmetric_contractions.weight"] + if use_reduced_cg: + _, proj = symmetric_contraction_proj( + cue.Irreps(O3_e3nn, str(irreps_in)), + cue.Irreps(O3_e3nn, str(irreps_out)), + list(range(1, correlation + 1)), + ) + proj = np.linalg.pinv(proj) + proj = torch.tensor(proj, dtype=wm.dtype, device=wm.device) + wm = torch.einsum("zau,ab->zbu", wm, proj) + # Get split sizes based on target dimensions + splits = [] + for k in range(kmax + 1): + for suffix in suffixes: + key = f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix}" + target_shape = target_dict[key].shape + splits.append(target_shape[1]) + if ( + target_dict.get( + f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix.replace('.', '_')}" + + "_zeroed", + False, + ) + and not use_reduced_cg + ): + splits[-1] = 0 + + # Split the weights using the calculated sizes + weights_split = torch.split(wm, splits, dim=1) + + # Assign back to target dictionary + idx = 0 + for k in range(kmax + 1): + for suffix in suffixes: + key = f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix}" + if ( + target_dict.get( + f"products.{i}.symmetric_contractions.contractions.{k}.weights{suffix.replace('.', '_')}_zeroed", + False, + ) + and not use_reduced_cg + ): + continue + target_dict[key] = ( + weights_split[idx] if splits[idx] > 0 else target_dict[key] + ) + idx += 1 + + +def transfer_weights( + source_model: torch.nn.Module, + target_model: torch.nn.Module, + num_product_irreps: int, + correlation: int, + num_layers: int, + use_reduced_cg: bool, +): + """Transfer weights from CuEq to E3nn format""" + # Get state dicts + source_dict = source_model.state_dict() + target_dict = target_model.state_dict() + + # Transfer symmetric contractions + products = target_model.products + transfer_symmetric_contractions( + source_dict, + target_dict, + num_product_irreps, + products, + correlation, + num_layers, + use_reduced_cg, + ) + + # Transfer remaining matching keys + transferred_keys = set() + remaining_keys = ( + set(source_dict.keys()) & set(target_dict.keys()) - transferred_keys + ) + remaining_keys = {k for k in remaining_keys if "symmetric_contraction" not in k} + + if remaining_keys: + for key in remaining_keys: + src = source_dict[key] + tgt = target_dict[key] + if source_dict[key].shape == target_dict[key].shape: + logging.debug(f"Transferring additional key: {key}") + target_dict[key] = source_dict[key] + elif shapes_match_up_to_unsqueeze(src.shape, tgt.shape): + logging.debug( + f"Transferring key {key} after adapting shape " + f"{tuple(src.shape)} → {tuple(tgt.shape)}" + ) + target_dict[key] = reshape_like(src, tgt.shape) + else: + logging.warning( + f"Shape mismatch for key {key}: " + f"source {source_dict[key].shape} vs target {target_dict[key].shape}" + ) + + # Transfer avg_num_neighbors + for i in range(num_layers): + target_model.interactions[i].avg_num_neighbors = source_model.interactions[ + i + ].avg_num_neighbors + + # Load state dict into target model + target_model.load_state_dict(target_dict) + + +def run(input_model, output_model="_e3nn.model", device="cpu", return_model=True): + + # Load CuEq model + if isinstance(input_model, str): + source_model = torch.load(input_model, map_location=device) + else: + source_model = input_model + default_dtype = next(source_model.parameters()).dtype + torch.set_default_dtype(default_dtype) + # Extract configuration + config = extract_config_mace_model(source_model) + + # Get max_L and correlation from config + num_product_irreps = len(config["hidden_irreps"].slices()) - 1 + correlation = config["correlation"] + use_reduced_cg = config.get("use_reduced_cg", True) + + # Remove CuEq config + config.pop("cueq_config", None) + + # Create new model without CuEq config + logging.info("Creating new model without CuEq settings") + target_model = source_model.__class__(**config) + + # Transfer weights with proper remapping + num_layers = config["num_interactions"] + transfer_weights( + source_model, + target_model, + num_product_irreps, + correlation, + num_layers, + use_reduced_cg, + ) + + if return_model: + return target_model + + # Save model + if isinstance(input_model, str): + base = os.path.splitext(input_model)[0] + output_model = f"{base}.{output_model}" + logging.warning(f"Saving E3nn model to {output_model}") + torch.save(target_model, output_model) + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("input_model", help="Path to input CuEq model") + parser.add_argument( + "--output_model", help="Path to output E3nn model", default="e3nn_model.pt" + ) + parser.add_argument("--device", default="cpu", help="Device to use") + parser.add_argument( + "--return_model", + action="store_false", + help="Return model instead of saving to file", + ) + args = parser.parse_args() + + run( + input_model=args.input_model, + output_model=args.output_model, + device=args.device, + return_model=args.return_model, + ) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/convert_device.py b/models/mace/mace/cli/convert_device.py new file mode 100644 index 0000000000000000000000000000000000000000..69735b7cf723f45e74b1573d7cf86cb3828dc539 --- /dev/null +++ b/models/mace/mace/cli/convert_device.py @@ -0,0 +1,31 @@ +from argparse import ArgumentParser + +import torch + + +def main(): + parser = ArgumentParser() + parser.add_argument( + "--target_device", + "-t", + help="device to convert to, usually 'cpu' or 'cuda'", + default="cpu", + ) + parser.add_argument( + "--output_file", + "-o", + help="name for output model, defaults to model_file.target_device", + ) + parser.add_argument("model_file", help="input model file path") + args = parser.parse_args() + + if args.output_file is None: + args.output_file = args.model_file + "." + args.target_device + + model = torch.load(args.model_file, weights_only=False) + model.to(args.target_device) + torch.save(model, args.output_file) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/convert_e3nn_cueq.py b/models/mace/mace/cli/convert_e3nn_cueq.py new file mode 100644 index 0000000000000000000000000000000000000000..edbbad427acc79754e65960198c47de01fef5dc4 --- /dev/null +++ b/models/mace/mace/cli/convert_e3nn_cueq.py @@ -0,0 +1,258 @@ +import argparse +import logging +import os +from typing import Dict, List, Tuple, Union + +import torch +from e3nn import o3 + +from mace.modules.wrapper_ops import CuEquivarianceConfig +from mace.tools.cg import O3_e3nn +from mace.tools.cg_cueq_tools import symmetric_contraction_proj +from mace.tools.scripts_utils import extract_config_mace_model + +try: + import cuequivariance as cue + + CUEQQ_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + CUEQQ_AVAILABLE = False + cue = None + +SizeLike = Union[torch.Size, List[int]] + + +def shapes_match_up_to_unsqueeze(a: SizeLike, b: SizeLike) -> bool: + if isinstance(a, torch.Tensor): + a = a.shape + if isinstance(b, torch.Tensor): + b = b.shape + + def drop(s): + return tuple(d for d in s if d != 1) + + return drop(a) == drop(b) + + +def reshape_like(src: torch.Tensor, ref_shape: torch.Size) -> torch.Tensor: + try: + return src.reshape(ref_shape) + except RuntimeError: + return src.clone().reshape(ref_shape) + + +def get_kmax_pairs( + num_product_irreps: int, correlation: int, num_layers: int +) -> List[Tuple[int, int]]: + """Determine kmax pairs based on num_product_irreps and correlation""" + if correlation == 2: + kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)] + kmax_pairs = kmax_pairs + [[num_layers - 1, 0]] + return kmax_pairs + if correlation == 3: + kmax_pairs = [[i, num_product_irreps] for i in range(num_layers - 1)] + kmax_pairs = kmax_pairs + [[num_layers - 1, 0]] + return kmax_pairs + raise NotImplementedError(f"Correlation {correlation} not supported") + + +def transfer_symmetric_contractions( + source_dict: Dict[str, torch.Tensor], + target_dict: Dict[str, torch.Tensor], + num_product_irreps: int, + products: torch.nn.Module, + correlation: int, + num_layers: int, + use_reduced_cg: bool, +): + """Transfer symmetric contraction weights""" + kmax_pairs = get_kmax_pairs(num_product_irreps, correlation, num_layers) + suffixes = ["_max"] + [f".{i}" for i in range(correlation - 1)] + for i, kmax in kmax_pairs: + irreps_in = o3.Irreps( + irrep.ir for irrep in products[i].symmetric_contractions.irreps_in + ) + irreps_out = o3.Irreps( + irrep.ir for irrep in products[i].symmetric_contractions.irreps_out + ) + if use_reduced_cg: + wm = torch.concatenate( + [ + source_dict[ + f"products.{i}.symmetric_contractions.contractions.{k}.weights{j}" + ] + for k in range(kmax + 1) + for j in suffixes + ], + dim=1, + ) + else: + wm = torch.concatenate( + [ + source_dict[ + f"products.{i}.symmetric_contractions.contractions.{k}.weights{j}" + ] + for k in range(kmax + 1) + for j in suffixes + if not source_dict.get( + f"products.{i}.symmetric_contractions.contractions.{k}.weights{j.replace('.', '_')}_zeroed", + False, + ) + ], + dim=1, + ) + if use_reduced_cg: + _, proj = symmetric_contraction_proj( + cue.Irreps(O3_e3nn, str(irreps_in)), + cue.Irreps(O3_e3nn, str(irreps_out)), + list(range(1, correlation + 1)), + ) + proj = torch.tensor(proj, dtype=wm.dtype, device=wm.device) + wm = torch.einsum("zau,ab->zbu", wm, proj) + target_dict[f"products.{i}.symmetric_contractions.weight"] = wm + + +def transfer_weights( + source_model: torch.nn.Module, + target_model: torch.nn.Module, + num_product_irreps: int, + correlation: int, + num_layers: int, + use_reduced_cg: bool, +): + """Transfer weights with proper remapping""" + # Get source state dict + source_dict = source_model.state_dict() + target_dict = target_model.state_dict() + + products = source_model.products + # Transfer symmetric contractions + transfer_symmetric_contractions( + source_dict, + target_dict, + num_product_irreps, + products, + correlation, + num_layers, + use_reduced_cg, + ) + + transferred_keys = set() + remaining_keys = ( + set(source_dict.keys()) & set(target_dict.keys()) - transferred_keys + ) + remaining_keys = {k for k in remaining_keys if "symmetric_contraction" not in k} + if remaining_keys: + for key in remaining_keys: + src = source_dict[key] + tgt = target_dict[key] + if source_dict[key].shape == target_dict[key].shape: + logging.debug(f"Transferring additional key: {key}") + target_dict[key] = source_dict[key] + elif shapes_match_up_to_unsqueeze(src.shape, tgt.shape): + logging.debug( + f"Transferring key {key} after adapting shape " + f"{tuple(src.shape)} → {tuple(tgt.shape)} -> {reshape_like(src, tgt.shape).shape}" + ) + target_dict[key] = reshape_like(src, tgt.shape) + else: + logging.debug( + f"Shape mismatch for key {key}: " + f"source {source_dict[key].shape} vs target {target_dict[key].shape}" + ) + # Transfer avg_num_neighbors + for i in range(num_layers): + target_model.interactions[i].avg_num_neighbors = source_model.interactions[ + i + ].avg_num_neighbors + + # Load state dict into target model + target_model.load_state_dict(target_dict) + + +def run( + input_model, + output_model="_cueq.model", + device="cpu", + return_model=True, +): + # Setup logging + + # Load original model + # logging.warning(f"Loading model") + # check if input_model is a path or a model + if isinstance(input_model, str): + source_model = torch.load(input_model, map_location=device) + else: + source_model = input_model + default_dtype = next(source_model.parameters()).dtype + torch.set_default_dtype(default_dtype) + # Extract configuration + config = extract_config_mace_model(source_model) + + # Get max_L and correlation from config + num_product_irreps = len(config["hidden_irreps"].slices()) - 1 + correlation = config["correlation"] + use_reduced_cg = config.get("use_reduced_cg", True) + + # Add cuequivariance config + config["cueq_config"] = CuEquivarianceConfig( + enabled=True, + layout="ir_mul", + group="O3_e3nn", + optimize_all=True, + conv_fusion=(device == "cuda"), + ) + + # Create new model with cuequivariance config + logging.info("Creating new model with cuequivariance settings") + target_model = source_model.__class__(**config).to(device) + + # Transfer weights with proper remapping + num_layers = config["num_interactions"] + transfer_weights( + source_model, + target_model, + num_product_irreps, + correlation, + num_layers, + use_reduced_cg, + ) + + if return_model: + return target_model + + if isinstance(input_model, str): + base = os.path.splitext(input_model)[0] + output_model = f"{base}.{output_model}" + logging.warning(f"Saving CuEq model to {output_model}") + torch.save(target_model, output_model) + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("input_model", help="Path to input MACE model") + parser.add_argument( + "--output_model", + help="Path to output cuequivariance model", + default="cueq_model.pt", + ) + parser.add_argument("--device", default="cpu", help="Device to use") + parser.add_argument( + "--return_model", + action="store_false", + help="Return model instead of saving to file", + ) + args = parser.parse_args() + + run( + input_model=args.input_model, + output_model=args.output_model, + device=args.device, + return_model=args.return_model, + ) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/convert_e3nn_oeq.py b/models/mace/mace/cli/convert_e3nn_oeq.py new file mode 100644 index 0000000000000000000000000000000000000000..61694792c038454cd1bb0b3f50ab89bb4eb297fc --- /dev/null +++ b/models/mace/mace/cli/convert_e3nn_oeq.py @@ -0,0 +1,89 @@ +import argparse +import logging +import os + +import torch + +from mace.modules.wrapper_ops import OEQConfig +from mace.tools.scripts_utils import extract_config_mace_model + + +def run( + input_model, + output_model="_oeq.model", + device="cpu", + return_model=True, +): + # Setup logging + + # Load original model + # logging.warning(f"Loading model") + # check if input_model is a path or a model + if isinstance(input_model, str): + source_model = torch.load(input_model, map_location=device) + else: + source_model = input_model + default_dtype = next(source_model.parameters()).dtype + torch.set_default_dtype(default_dtype) + + config = extract_config_mace_model(source_model) + + # Add OEQ config + config["oeq_config"] = OEQConfig( + enabled=False, optimize_all=True, conv_fusion="atomic" + ) + + # Create new model with oeq config + logging.info("Creating new model with openequivariance settings") + target_model = source_model.__class__(**config).to(device) + source_dict = source_model.state_dict() + target_dict = target_model.state_dict() + + for key in target_dict: + if ".conv_tp." not in key: + target_dict[key] = source_dict[key] + + target_model.load_state_dict(target_dict) + + for i in range(2): + target_model.interactions[i].avg_num_neighbors = source_model.interactions[ + i + ].avg_num_neighbors + + if return_model: + return target_model + + if isinstance(input_model, str): + base = os.path.splitext(input_model)[0] + output_model = f"{base}.{output_model}" + logging.warning(f"Saving OEQ model to {output_model}") + torch.save(target_model, output_model) + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("input_model", help="Path to input MACE model") + parser.add_argument( + "--output_model", + help="Path to output openequviariance model", + default="oeq_model.pt", + ) + parser.add_argument("--device", default="cpu", help="Device to use") + parser.add_argument( + "--return_model", + action="store_false", + help="Return model instead of saving to file", + ) + args = parser.parse_args() + + run( + input_model=args.input_model, + output_model=args.output_model, + device=args.device, + return_model=args.return_model, + ) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/convert_oeq_e3nn.py b/models/mace/mace/cli/convert_oeq_e3nn.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5fb48e9975e629ab184cc49aa41f624d53a845 --- /dev/null +++ b/models/mace/mace/cli/convert_oeq_e3nn.py @@ -0,0 +1,78 @@ +import argparse +import logging +import os + +import torch + +from mace.tools.scripts_utils import extract_config_mace_model + + +def run(input_model, output_model="_e3nn.model", device="cpu", return_model=True): + # Load OEQ model + if isinstance(input_model, str): + source_model = torch.load(input_model, map_location=device) + else: + source_model = input_model + default_dtype = next(source_model.parameters()).dtype + torch.set_default_dtype(default_dtype) + # Extract configuration + config = extract_config_mace_model(source_model) + + # Remove OEQ config + config.pop("oeq_config", None) + + # Create new model without CuEq config + logging.info("Creating new model without OEQ settings") + target_model = source_model.__class__(**config).to(device) + + source_dict = source_model.state_dict() + target_dict = target_model.state_dict() + + for key in source_dict: + if ".conv_tp." not in key: + target_dict[key] = source_dict[key] + + for i in range(2): + + target_model.interactions[i].avg_num_neighbors = source_model.interactions[ + i + ].avg_num_neighbors + + target_model.load_state_dict(target_dict) + + if return_model: + return target_model + + # Save model + if isinstance(input_model, str): + base = os.path.splitext(input_model)[0] + output_model = f"{base}.{output_model}" + logging.warning(f"Saving E3nn model to {output_model}") + torch.save(target_model, output_model) + return None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("input_model", help="Path to input oeq model") + parser.add_argument( + "--output_model", help="Path to output E3nn model", default="e3nn_model.pt" + ) + parser.add_argument("--device", default="cpu", help="Device to use") + parser.add_argument( + "--return_model", + action="store_false", + help="Return model instead of saving to file", + ) + args = parser.parse_args() + + run( + input_model=args.input_model, + output_model=args.output_model, + device=args.device, + return_model=args.return_model, + ) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/create_lammps_model.py b/models/mace/mace/cli/create_lammps_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7af81f25a287cc7fe20e78ecb2e81b2c75fbccba --- /dev/null +++ b/models/mace/mace/cli/create_lammps_model.py @@ -0,0 +1,114 @@ +# pylint: disable=wrong-import-position +import argparse +import copy +import os + +os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1" + +import torch +from e3nn.util import jit + +from mace.calculators import LAMMPS_MACE +from mace.calculators.lammps_mliap_mace import LAMMPS_MLIAP_MACE +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq + + +def parse_args(): + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "model_path", + type=str, + help="Path to the model to be converted to LAMMPS", + ) + parser.add_argument( + "--head", + type=str, + nargs="?", + help="Head of the model to be converted to LAMMPS", + default=None, + ) + parser.add_argument( + "--dtype", + type=str, + nargs="?", + help="Data type of the model to be converted to LAMMPS", + default="float64", + ) + parser.add_argument( + "--format", + type=str, + help="Old libtorch format, or new mliap format", + default="libtorch", + ) + return parser.parse_args() + + +def select_head(model): + if hasattr(model, "heads"): + heads = model.heads + else: + heads = [None] + + if len(heads) == 1: + print(f"Only one head found in the model: {heads[0]}. Skipping selection.") + return heads[0] + + print("Available heads in the model:") + for i, head in enumerate(heads): + print(f"{i + 1}: {head}") + + # Ask the user to select a head + selected = input( + f"Select a head by number (Defaulting to head: {len(heads)}, press Enter to accept): " + ) + + if selected.isdigit() and 1 <= int(selected) <= len(heads): + return heads[int(selected) - 1] + if selected == "": + print("No head selected. Proceeding without specifying a head.") + return None + print(f"No valid selection made. Defaulting to the last head: {heads[-1]}") + return heads[-1] + + +def main(): + args = parse_args() + model_path = args.model_path # takes model name as command-line input + model = torch.load( + model_path, + map_location=torch.device("cuda" if torch.cuda.is_available() else "cpu"), + ) + if args.dtype == "float64": + model = model.double().to("cpu") + elif args.dtype == "float32": + print("Converting model to float32, this may cause loss of precision.") + model = model.float().to("cpu") + + if args.format == "mliap": + # Enabling cuequivariance by default. TODO: switch? + model = run_e3nn_to_cueq(copy.deepcopy(model)) + model.lammps_mliap = True + + if args.head is None: + head = select_head(model) + else: + head = args.head + print( + f"Selected head: {head} from command line in the list available heads: {model.heads}" + ) + + lammps_class = LAMMPS_MLIAP_MACE if args.format == "mliap" else LAMMPS_MACE + lammps_model = ( + lammps_class(model, head=head) if head is not None else lammps_class(model) + ) + if args.format == "mliap": + torch.save(lammps_model, model_path + "-mliap_lammps.pt") + else: + lammps_model_compiled = jit.compile(lammps_model) + lammps_model_compiled.save(model_path + "-lammps.pt") + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/eval_configs.py b/models/mace/mace/cli/eval_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2acf2883f1b908bdea44af911a09182fdc4059 --- /dev/null +++ b/models/mace/mace/cli/eval_configs.py @@ -0,0 +1,337 @@ +########################################################################################### +# Script for evaluating configurations contained in an xyz file with a trained model +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import argparse +from typing import Dict + +import ase.data +import ase.io +import numpy as np +import torch +from e3nn import o3 + +from mace import data +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq +from mace.modules.utils import extract_invariant +from mace.tools import torch_geometric, torch_tools, utils + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("--configs", help="path to XYZ configurations", required=True) + parser.add_argument("--model", help="path to model", required=True) + parser.add_argument("--output", help="output path", required=True) + parser.add_argument( + "--device", + help="select device", + type=str, + choices=["cpu", "cuda"], + default="cpu", + ) + parser.add_argument( + "--enable_cueq", + help="enable cuequivariance acceleration", + action="store_true", + default=False, + ) + parser.add_argument( + "--default_dtype", + help="set default dtype", + type=str, + choices=["float32", "float64"], + default="float64", + ) + parser.add_argument("--batch_size", help="batch size", type=int, default=64) + parser.add_argument( + "--compute_stress", + help="compute stress", + action="store_true", + default=False, + ) + parser.add_argument( + "--compute_bec", + help="compute BEC", + action="store_true", + default=False, + ) + parser.add_argument( + "--return_contributions", + help="model outputs energy contributions for each body order, only supported for MACE, not ScaleShiftMACE", + action="store_true", + default=False, + ) + parser.add_argument( + "--return_descriptors", + help="model outputs MACE descriptors", + action="store_true", + default=False, + ) + parser.add_argument( + "--descriptor_num_layers", + help="number of layers to take descriptors from", + type=int, + default=-1, + ) + parser.add_argument( + "--descriptor_aggregation_method", + help="method for aggregating node features. None saves descriptors for each atom.", + choices=["mean", "per_element_mean", None], + default=None, + ) + parser.add_argument( + "--descriptor_invariants_only", + help="save invariant (l=0) descriptors only", + type=bool, + default=True, + ) + parser.add_argument( + "--return_node_energies", + help="model outputs MACE node energies", + action="store_true", + default=False, + ) + parser.add_argument( + "--info_prefix", + help="prefix for energy, forces and stress keys", + type=str, + default="MACE_", + ) + parser.add_argument( + "--head", + help="Model head used for evaluation", + type=str, + required=False, + default=None, + ) + return parser.parse_args() + + +def get_model_output( + model: torch.nn.Module, + batch: Dict[str, torch.Tensor], + compute_stress: bool, + compute_bec: bool, +) -> Dict[str, torch.Tensor]: + forward_args = { + "compute_stress": compute_stress, + } + if compute_bec: + # Only add `compute_bec` if it is requested + # We check if the model is MACELES at the start of the run function + forward_args["compute_bec"] = compute_bec + return model(batch, **forward_args) + + +def main() -> None: + args = parse_args() + run(args) + + +def run(args: argparse.Namespace) -> None: + torch_tools.set_default_dtype(args.default_dtype) + device = torch_tools.init_device(args.device) + + # Load model + model = torch.load(f=args.model, map_location=args.device) + if model.__class__.__name__ != "MACELES" and args.compute_bec: + raise ValueError("BEC can only be computed with MACELES model. ") + if args.enable_cueq: + print("Converting models to CuEq for acceleration") + model = run_e3nn_to_cueq(model, device=device) + #model = model.to( + # args.device + #) # shouldn't be necessary but seems to help with CUDA problems + + + + + for param in model.parameters(): + param.requires_grad = False + + # Load data and prepare input + atoms_list = ase.io.read(args.configs, index=":") + if args.head is not None: + for atoms in atoms_list: + atoms.info["head"] = args.head + configs = [data.config_from_atoms(atoms) for atoms in atoms_list] + + z_table = utils.AtomicNumberTable([int(z) for z in model.atomic_numbers]) + + try: + heads = model.heads + except AttributeError: + heads = None + + data_loader = torch_geometric.dataloader.DataLoader( + dataset=[ + data.AtomicData.from_config( + config, z_table=z_table, cutoff=float(model.r_max), heads=heads + ) + for config in configs + ], + batch_size=args.batch_size, + shuffle=False, + drop_last=False, + ) + + + # Collect data + energies_list = [] + contributions_list = [] + descriptors_list = [] + node_energies_list = [] + stresses_list = [] + bec_list = [] + qs_list = [] + forces_collection = [] + + for batch in data_loader: + batch = batch.to(device) + output = get_model_output( + model, batch.to_dict(), args.compute_stress, args.compute_bec + ) + energies_list.append(torch_tools.to_numpy(output["energy"])) + if args.compute_stress: + stresses_list.append(torch_tools.to_numpy(output["stress"])) + if args.compute_bec: + becs = np.split( + torch_tools.to_numpy(output["BEC"]), + indices_or_sections=batch.ptr[1:], + axis=0, + ) + bec_list.append(becs[:-1]) # drop last as its empty + + qs = np.split( + torch_tools.to_numpy(output["latent_charges"]), + indices_or_sections=batch.ptr[1:], + axis=0, + ) + qs_list.append(qs[:-1]) # drop last as its empty + + if args.return_contributions: + contributions_list.append(torch_tools.to_numpy(output["contributions"])) + + if args.return_descriptors: + num_layers = args.descriptor_num_layers + if num_layers == -1: + num_layers = int(model.num_interactions) + irreps_out = o3.Irreps(str(model.products[0].linear.irreps_out)) + l_max = irreps_out.lmax + num_invariant_features = irreps_out.dim // (l_max + 1) ** 2 + per_layer_features = [ + irreps_out.dim for _ in range(int(model.num_interactions)) + ] + per_layer_features[-1] = ( + num_invariant_features # Equivariant features not created for the last layer + ) + + descriptors = output["node_feats"] + + if args.descriptor_invariants_only: + descriptors = extract_invariant( + descriptors, + num_layers=num_layers, + num_features=num_invariant_features, + l_max=l_max, + ) + + to_keep = np.sum(per_layer_features[:num_layers]) + descriptors = descriptors[:, :to_keep].detach().cpu().numpy() + + descriptors = np.split( + descriptors, + indices_or_sections=batch.ptr[1:], + axis=0, + ) + descriptors_list.extend(descriptors[:-1]) # drop last as its empty + + if args.return_node_energies: + node_energies_list.append( + np.split( + torch_tools.to_numpy(output["node_energy"]), + indices_or_sections=batch.ptr[1:], + axis=0, + )[ + :-1 + ] # drop last as its empty + ) + + forces = np.split( + torch_tools.to_numpy(output["forces"]), + indices_or_sections=batch.ptr[1:], + axis=0, + ) + forces_collection.append(forces[:-1]) # drop last as its empty + + energies = np.concatenate(energies_list, axis=0) + forces_list = [ + forces for forces_list in forces_collection for forces in forces_list + ] + assert len(atoms_list) == len(energies) == len(forces_list) + if args.compute_stress: + stresses = np.concatenate(stresses_list, axis=0) + assert len(atoms_list) == stresses.shape[0] + + if args.compute_bec: + bec_list = [becs for sublist in bec_list for becs in sublist] + qs_list = [qs for sublist in qs_list for qs in sublist] + + if args.return_contributions: + contributions = np.concatenate(contributions_list, axis=0) + assert len(atoms_list) == contributions.shape[0] + + if args.return_descriptors: + # no concatentation - elements of descriptors_list have non-uniform shapes + assert len(atoms_list) == len(descriptors_list) + + if args.return_node_energies: + node_energies = np.concatenate(node_energies_list, axis=0) + assert len(atoms_list) == node_energies.shape[0] + + # Store data in atoms objects + for i, (atoms, energy, forces) in enumerate(zip(atoms_list, energies, forces_list)): + atoms.calc = None # crucial + atoms.info[args.info_prefix + "energy"] = energy + atoms.arrays[args.info_prefix + "forces"] = forces + + if args.compute_stress: + atoms.info[args.info_prefix + "stress"] = stresses[i] + + if args.compute_bec: + atoms.arrays[args.info_prefix + "BEC"] = bec_list[i].reshape(-1, 9) + atoms.arrays[args.info_prefix + "latent_charges"] = qs_list[i] + + if args.return_contributions: + atoms.info[args.info_prefix + "BO_contributions"] = contributions[i] + + if args.return_descriptors: + descriptors = descriptors_list[i] + if args.descriptor_aggregation_method: + if args.descriptor_aggregation_method == "mean": + descriptors = np.mean(descriptors, axis=0) + elif args.descriptor_aggregation_method == "per_element_mean": + descriptors = { + element: np.mean( + descriptors[atoms.symbols == element], axis=0 + ).tolist() + for element in np.unique(atoms.symbols) + } + atoms.info[args.info_prefix + "descriptors"] = descriptors + else: # args.descriptor_aggregation_method is None + # Save descriptors for each atom (default behavior) + atoms.arrays[args.info_prefix + "descriptors"] = np.array(descriptors) + + if args.return_node_energies: + atoms.arrays[args.info_prefix + "node_energies"] = node_energies[i] + + # Write atoms to output path + ase.io.write(args.output, images=atoms_list, format="extxyz") + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/fine_tuning_select.py b/models/mace/mace/cli/fine_tuning_select.py new file mode 100644 index 0000000000000000000000000000000000000000..60dd4b85bd8adce7093f14a79f184877f0a92d20 --- /dev/null +++ b/models/mace/mace/cli/fine_tuning_select.py @@ -0,0 +1,529 @@ +########################################################################################### +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### +from __future__ import annotations + +import argparse +import ast +import logging +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import List, Tuple, Union + +import ase.data +import ase.io +import numpy as np +import torch + +from mace.calculators import MACECalculator, mace_mp + +try: + import fpsample # type: ignore +except ImportError: + pass + + +class FilteringType(Enum): + NONE = "none" + COMBINATIONS = "combinations" + EXCLUSIVE = "exclusive" + INCLUSIVE = "inclusive" + + +class SubselectType(Enum): + FPS = "fps" + RANDOM = "random" + + +@dataclass +class SelectionSettings: + configs_pt: str + output: str + configs_ft: str | None = None + atomic_numbers: List[int] | None = None + num_samples: int | None = None + subselect: SubselectType = SubselectType.FPS + model: str = "small" + descriptors: str | None = None + device: str = "cpu" + default_dtype: str = "float64" + head_pt: str | None = None + head_ft: str | None = None + filtering_type: FilteringType = FilteringType.COMBINATIONS + weight_ft: float = 1.0 + weight_pt: float = 1.0 + allow_random_padding: bool = True + seed: int = 42 + + +def str_to_list(s: str) -> List[int]: + assert isinstance(s, str), "Input must be a string" + return ast.literal_eval(s) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--configs_pt", + help="path to XYZ configurations for the pretraining", + required=True, + ) + parser.add_argument( + "--configs_ft", + help="path or list of paths to XYZ configurations for the finetuning", + required=False, + default=None, + ) + parser.add_argument( + "--num_samples", + help="number of samples to select for the pretraining", + type=int, + required=False, + default=None, + ) + parser.add_argument( + "--subselect", + help="method to subselect the configurations of the pretraining set", + type=SubselectType, + choices=list(SubselectType), + default=SubselectType.FPS, + ) + parser.add_argument( + "--model", help="path to model", default="small", required=False + ) + parser.add_argument("--output", help="output path", required=True) + parser.add_argument( + "--descriptors", help="path to descriptors", required=False, default=None + ) + parser.add_argument( + "--device", + help="select device", + type=str, + choices=["cpu", "cuda"], + default="cpu", + ) + parser.add_argument( + "--default_dtype", + help="set default dtype", + type=str, + choices=["float32", "float64"], + default="float64", + ) + parser.add_argument( + "--head_pt", + help="level of head for the pretraining set", + type=str, + default=None, + ) + parser.add_argument( + "--head_ft", + help="level of head for the finetuning set", + type=str, + default=None, + ) + parser.add_argument( + "--filtering_type", + help="filtering type", + type=FilteringType, + choices=list(FilteringType), + default=FilteringType.NONE, + ) + parser.add_argument( + "--weight_ft", + help="weight for the finetuning set", + type=float, + default=1.0, + ) + parser.add_argument( + "--weight_pt", + help="weight for the pretraining set", + type=float, + default=1.0, + ) + parser.add_argument( + "--atomic_numbers", + help="list of atomic numbers to filter the configurations", + type=str_to_list, + default=None, + ) + parser.add_argument( + "--disallow_random_padding", + help="do not allow random padding of the configurations to match the number of samples", + action="store_false", + dest="allow_random_padding", + ) + parser.add_argument("--seed", help="random seed", type=int, default=42) + return parser.parse_args() + + +def calculate_descriptors(atoms: List[ase.Atoms], calc: MACECalculator) -> None: + logging.info("Calculating descriptors") + for mol in atoms: + descriptors = calc.get_descriptors(mol.copy(), invariants_only=True) + # average descriptors over atoms for each element + descriptors_dict = { + element: np.mean(descriptors[mol.symbols == element], axis=0) + for element in np.unique(mol.symbols) + } + mol.info["mace_descriptors"] = descriptors_dict + + +def filter_atoms( + atoms: ase.Atoms, + element_subset: List[str], + filtering_type: FilteringType = FilteringType.COMBINATIONS, +) -> bool: + """ + Filters atoms based on the provided filtering type and element subset. + + Parameters: + atoms (ase.Atoms): The atoms object to filter. + element_subset (list): The list of elements to consider during filtering. + filtering_type (FilteringType): The type of filtering to apply. + Can be one of the following `FilteringType` enum members: + - `FilteringType.NONE`: No filtering is applied. + - `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. + - `FilteringType.EXCLUSIVE`: Return true if `atoms` contains *only* elements in the subset, false otherwise. + - `FilteringType.INCLUSIVE`: Return true if `atoms` contains all elements in the subset, false otherwise. I.e. allows additional elements. + + Returns: + bool: True if the atoms pass the filter, False otherwise. + """ + if filtering_type == FilteringType.NONE: + return True + if filtering_type == FilteringType.COMBINATIONS: + atom_symbols = np.unique(atoms.symbols) + return all( + x in element_subset for x in atom_symbols + ) # atoms must *only* contain elements in the subset + if filtering_type == FilteringType.EXCLUSIVE: + atom_symbols = set(list(atoms.symbols)) + return atom_symbols == set(element_subset) + if filtering_type == FilteringType.INCLUSIVE: + atom_symbols = np.unique(atoms.symbols) + return all( + x in atom_symbols for x in element_subset + ) # atoms must *at least* contain elements in the subset + raise ValueError( + f"Filtering type {filtering_type} not recognised. Must be one of {list(FilteringType)}." + ) + + +class FPS: + def __init__(self, atoms_list: List[ase.Atoms], n_samples: int): + self.n_samples = n_samples + self.atoms_list = atoms_list + self.species = np.unique([x.symbol for atoms in atoms_list for x in atoms]) # type: ignore + self.species_dict = {x: i for i, x in enumerate(self.species)} + # start from a random configuration + self.list_index = [np.random.randint(0, len(atoms_list))] + self.assemble_descriptors() + + def run( + self, + ) -> List[int]: + """ + Run the farthest point sampling algorithm. + """ + descriptor_dataset_reshaped = ( + self.descriptors_dataset.reshape( # pylint: disable=E1121 + (len(self.atoms_list), -1) + ) + ) + logging.info(f"{descriptor_dataset_reshaped.shape}") + logging.info(f"n_samples: {self.n_samples}") + self.list_index = fpsample.fps_npdu_kdtree_sampling( + descriptor_dataset_reshaped, + self.n_samples, + ) + return self.list_index + + def assemble_descriptors(self) -> None: + """ + Assemble the descriptors for all the configurations. + """ + self.descriptors_dataset: np.ndarray = 10e10 * np.ones( + ( + len(self.atoms_list), + len(self.species), + len(list(self.atoms_list[0].info["mace_descriptors"].values())[0]), + ), + dtype=np.float32, + ).astype(np.float32) + + for i, atoms in enumerate(self.atoms_list): + descriptors = atoms.info["mace_descriptors"] + for z in descriptors: + self.descriptors_dataset[i, self.species_dict[z]] = np.array( + descriptors[z] + ).astype(np.float32) + + +def _load_calc( + model: str, device: str, default_dtype: str, subselect: SubselectType +) -> Union[MACECalculator, None]: + if subselect == SubselectType.RANDOM: + return None + if model in ["small", "medium", "large"]: + calc = mace_mp(model, device=device, default_dtype=default_dtype) + else: + calc = MACECalculator( + model_paths=model, + device=device, + default_dtype=default_dtype, + ) + return calc + + +def _get_finetuning_elements( + atoms: List[ase.Atoms], atomic_numbers: List[int] | None +) -> List[str]: + if atoms: + logging.debug( + "Using elements from the finetuning configurations for filtering." + ) + species = np.unique([x.symbol for atoms in atoms for x in atoms]).tolist() # type: ignore + elif atomic_numbers is not None and atomic_numbers: + logging.debug("Using the supplied atomic numbers for filtering.") + species = [ase.data.chemical_symbols[z] for z in atomic_numbers] + else: + species = [] + return species + + +def _read_finetuning_configs( + configs_ft: Union[str, list[str], None], +) -> List[ase.Atoms]: + if isinstance(configs_ft, str): + path = configs_ft + return ase.io.read(path, index=":") # type: ignore + if isinstance(configs_ft, list): + assert all(isinstance(x, str) for x in configs_ft) + atoms_list_ft = [] + for path in configs_ft: + atoms_list_ft += ase.io.read(path, index=":") + return atoms_list_ft + if configs_ft is None: + return [] + raise ValueError(f"Invalid type for configs_ft: {type(configs_ft)}") + + +def _filter_pretraining_data( + atoms: list[ase.Atoms], + filtering_type: FilteringType, + all_species_ft: List[str], +) -> Tuple[List[ase.Atoms], List[ase.Atoms], list[bool]]: + logging.info( + "Filtering configurations based on the finetuning set, " + f"filtering type: {filtering_type}, elements: {all_species_ft}" + ) + passes_filter = [filter_atoms(x, all_species_ft, filtering_type) for x in atoms] + assert len(passes_filter) == len(atoms), "Filtering failed" + filtered_atoms = [x for x, passes in zip(atoms, passes_filter) if passes] + remaining_atoms = [x for x, passes in zip(atoms, passes_filter) if not passes] + return filtered_atoms, remaining_atoms, passes_filter + + +def _get_random_configs( + num_samples: int, + atoms: List[ase.Atoms], +) -> list[ase.Atoms]: + if num_samples > len(atoms): + raise ValueError( + f"Requested more samples ({num_samples}) than available in the remaining set ({len(atoms)})" + ) + indices = np.random.choice(list(range(len(atoms))), num_samples, replace=False) + return [atoms[i] for i in indices] + + +def _load_descriptors( + atoms: List[ase.Atoms], + passes_filter: List[bool], + descriptors_path: str | None, + calc: MACECalculator | None, + full_data_length: int, +) -> None: + if descriptors_path is not None: + logging.info(f"Loading descriptors from {descriptors_path}") + descriptors = np.load(descriptors_path, allow_pickle=True) + assert sum(passes_filter) == len(atoms) + if len(descriptors) != full_data_length: + raise ValueError( + f"Length of the descriptors ({len(descriptors)}) does not match the length of the data ({full_data_length})" + "Please provide descriptors for all configurations" + ) + required_descriptors = [ + descriptors[i] for i, passes in enumerate(passes_filter) if passes + ] + for i, atoms_ in enumerate(atoms): + atoms_.info["mace_descriptors"] = required_descriptors[i] + else: + logging.info("Calculating descriptors") + if calc is None: + raise ValueError("MACECalculator must be provided to calculate descriptors") + calculate_descriptors(atoms, calc) + + +def _maybe_save_descriptors( + atoms: List[ase.Atoms], + output_path: str, +) -> None: + """ + Save the descriptors if they are present in the atoms objects. + Also, delete the descriptors from the atoms objects. + """ + if all("mace_descriptors" in x.info for x in atoms): + output_path = Path(output_path) + descriptor_save_path = output_path.parent / ( + output_path.stem + "_descriptors.npy" + ) + logging.info(f"Saving descriptors at {descriptor_save_path}") + descriptors_list = [x.info["mace_descriptors"] for x in atoms] + np.save(descriptor_save_path, descriptors_list, allow_pickle=True) + for x in atoms: + del x.info["mace_descriptors"] + + +def _maybe_fps(atoms: List[ase.Atoms], num_samples: int) -> List[ase.Atoms]: + try: + fps_pt = FPS(atoms, num_samples) + idx_pt = fps_pt.run() + logging.info(f"Selected {len(idx_pt)} configurations") + return [atoms[i] for i in idx_pt] + except Exception as e: # pylint: disable=W0703 + logging.error(f"FPS failed, selecting random configurations instead: {e}") + return _get_random_configs(num_samples, atoms) + + +def _subsample_data( + filtered_atoms: List[ase.Atoms], + remaining_atoms: List[ase.Atoms], + passes_filter: List[bool], + num_samples: int | None, + subselect: SubselectType, + descriptors_path: str | None, + allow_random_padding: bool, + calc: MACECalculator | None, +) -> List[ase.Atoms]: + if num_samples is None or num_samples == len(filtered_atoms): + logging.info( + f"No subsampling, keeping all {len(filtered_atoms)} filtered configurations" + ) + return filtered_atoms + if num_samples > len(filtered_atoms) and allow_random_padding: + num_sample_randomly = num_samples - len(filtered_atoms) + logging.info( + f"Number of configurations after filtering {len(filtered_atoms)} " + f"is less than the number of samples {num_samples}, " + f"selecting {num_sample_randomly} random configurations for the rest." + ) + return filtered_atoms + _get_random_configs( + num_sample_randomly, remaining_atoms + ) + if num_samples == 0: + raise ValueError("Number of samples must be greater than 0") + if subselect == SubselectType.FPS: + _load_descriptors( + filtered_atoms, + passes_filter, + descriptors_path, + calc, + full_data_length=len(filtered_atoms) + len(remaining_atoms), + ) + logging.info( + f"Selecting {num_samples} configurations out of {len(filtered_atoms)} using Farthest Point Sampling" + ) + return _maybe_fps(filtered_atoms, num_samples) + if subselect == SubselectType.RANDOM: + logging.info( + f"Subselecting {num_samples} from filtered {len(filtered_atoms)} using random sampling" + ) + return _get_random_configs(num_samples, filtered_atoms) + raise ValueError(f"Invalid subselect type: {subselect}") + + +def _write_metadata( + atoms: list[ase.Atoms], pretrained: bool, config_weight: float, head: str | None +) -> None: + for a in atoms: + a.info["pretrained"] = pretrained + a.info["config_weight"] = config_weight + if head is not None: + a.info["head"] = head + + +def select_samples( + settings: SelectionSettings, +) -> None: + np.random.seed(settings.seed) + torch.manual_seed(settings.seed) + calc = _load_calc( + settings.model, settings.device, settings.default_dtype, settings.subselect + ) + atoms_list_ft = _read_finetuning_configs(settings.configs_ft) + all_species_ft = _get_finetuning_elements(atoms_list_ft, settings.atomic_numbers) + + if settings.filtering_type is not FilteringType.NONE and not all_species_ft: + raise ValueError( + "Filtering types other than NONE require elements for filtering. They can be specified via the `--atomic_numbers` flag." + ) + + atoms_list_pt: list[ase.Atoms] = ase.io.read(settings.configs_pt, index=":") # type: ignore + filtered_pt_atoms, remaining_atoms, passes_filter = _filter_pretraining_data( + atoms_list_pt, settings.filtering_type, all_species_ft + ) + + subsampled_atoms = _subsample_data( + filtered_pt_atoms, + remaining_atoms, + passes_filter, + settings.num_samples, + settings.subselect, + settings.descriptors, + settings.allow_random_padding, + calc, + ) + if ase.io.formats.filetype(settings.output, read=False) != "extxyz": + raise ValueError( + f"filename '{settings.output}' does no have " + "suffix compatible with extxyz format" + ) + _maybe_save_descriptors(subsampled_atoms, settings.output) + + _write_metadata( + subsampled_atoms, + pretrained=True, + config_weight=settings.weight_pt, + head=settings.head_pt, + ) + _write_metadata( + atoms_list_ft, + pretrained=False, + config_weight=settings.weight_ft, + head=settings.head_ft, + ) + + logging.info("Saving the selected configurations") + ase.io.write(settings.output, subsampled_atoms) + + logging.info("Saving a combined XYZ file") + atoms_fps_pt_ft = subsampled_atoms + atoms_list_ft + + output = Path(settings.output) + ase.io.write( + output.parent / (output.stem + "_combined" + output.suffix), + atoms_fps_pt_ft, + ) + + +def main(): + args = parse_args() + settings = SelectionSettings(**vars(args)) + select_samples(settings) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/our_files/__pycache__/run_calc.cpython-310.pyc b/models/mace/mace/cli/our_files/__pycache__/run_calc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2709bb7180b28434740e774365122ed79d60b74b Binary files /dev/null and b/models/mace/mace/cli/our_files/__pycache__/run_calc.cpython-310.pyc differ diff --git a/models/mace/mace/cli/our_files/__pycache__/run_eval.cpython-310.pyc b/models/mace/mace/cli/our_files/__pycache__/run_eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0695c37a939bcebbf6e0b5b38695c2f2d4bb5ba Binary files /dev/null and b/models/mace/mace/cli/our_files/__pycache__/run_eval.cpython-310.pyc differ diff --git a/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation.cpython-310.pyc b/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a811acae3eba7a2906a91453697dfd50d11a925 Binary files /dev/null and b/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation.cpython-310.pyc differ diff --git a/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation_no_finetuning.cpython-310.pyc b/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation_no_finetuning.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e910b41c335b05bdf2c61684eb2bf9ce780e27b8 Binary files /dev/null and b/models/mace/mace/cli/our_files/__pycache__/run_eval_foundation_no_finetuning.cpython-310.pyc differ diff --git a/models/mace/mace/cli/our_files/run_calc.py b/models/mace/mace/cli/our_files/run_calc.py new file mode 100644 index 0000000000000000000000000000000000000000..e42cd5e355882261edf0919191f7ef91154d1ffe --- /dev/null +++ b/models/mace/mace/cli/our_files/run_calc.py @@ -0,0 +1,34 @@ +from ase.io import read, write +from ase.optimize import FIRE, BFGS +from pathlib import Path +from mace.calculators import MACECalculator + + +input_structure = "" +device = "cuda" +#device = "cpu" + +atoms = read(input_structure) + +# Attach YOUR calculator (loads model internally) + +# calc = MACECalculator( +# model_paths='', +# device=device, +# ) + +# +print("a") +calc = MACECalculator( + model_path='', + device=device, + head='Default', +) + +atoms.set_calculator(calc) + +opt = BFGS(atoms, logfile="ml_relax.log", trajectory="ml_relax.traj") +opt.run(fmax=0.02, steps=1000) + +atoms.write('POSCAR_final') +print("Done.") \ No newline at end of file diff --git a/models/mace/mace/cli/our_files/run_eval.py b/models/mace/mace/cli/our_files/run_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff74e76fa43fdf759b1aa00840ce4c3261cae3e --- /dev/null +++ b/models/mace/mace/cli/our_files/run_eval.py @@ -0,0 +1,410 @@ +########################################################################################### +# Training script for MACE +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import ast +import glob +import json +import logging +import os +from copy import deepcopy +from pathlib import Path +from typing import List, Optional +import torch +import torch.distributed +from tqdm import tqdm +from e3nn.util import jit +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import LBFGS +from torch.utils.data import ConcatDataset +from torch_ema import ExponentialMovingAverage + +import mace +from mace import data, tools +from mace.calculators.foundations_models import ( + mace_mp, + mace_mp_names, + mace_off, + mace_omol, +) +from mace.cli.convert_cueq_e3nn import run as run_cueq_to_e3nn +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq +from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq +from mace.cli.convert_oeq_e3nn import run as run_oeq_to_e3nn +from mace.cli.visualise_train import TrainingPlotter +from mace.data import KeySpecification, update_keyspec_from_kwargs +from mace.tools import torch_geometric +from mace.tools.distributed_tools import init_distributed +from mace.tools.model_script_utils import configure_model +from mace.tools.multihead_tools import ( + HeadConfig, + apply_pseudolabels_to_pt_head_configs, + assemble_replay_data, + dict_head_to_dataclass, + prepare_default_head, + prepare_pt_head, +) +from mace.tools.run_train_utils import ( + combine_datasets, + load_dataset_for_path, + normalize_file_paths, +) +from mace.tools.scripts_utils import ( + LRScheduler, + SubsetCollection, + check_path_ase_read, + convert_to_json_format, + dict_to_array, + extract_config_mace_model, + get_atomic_energies, + get_avg_num_neighbors, + get_config_type_weights, + get_dataset_from_xyz, + get_files_with_suffix, + get_loss_fn, + get_optimizer, + get_params_options, + get_swa, + print_git_commit, + remove_pt_head, + setup_wandb, +) +from mace.tools.tables_utils import create_error_table +from mace.tools.utils import AtomicNumberTable + + +#NOTE Calculator stuff +from pathlib import Path +import torch +from ase.io import read, write +from ase.optimize import FIRE + +from mace.calculators import MACECalculator # this exists in MACE +# If import path differs in your install, try: +# from mace.calculators.mace import MACECalculator + +import time + +def build_parser(): + parser = tools.build_default_arg_parser() + + # Your custom arguments + parser.add_argument( + "--model_paths", + type=str, + nargs="+", # one or more values + required=True, # MUST be provided + help="One or more model paths to evaluate.", + ) + + parser.add_argument( + "--out_txt", + type=str, + required=True, + help="Path to output txt file.", + ) + + parser.add_argument( + "--eval_name", + type=str, + default="multi_seed_eval", # optional → fine to keep default + help="Custom name for this evaluation run.", + ) + return parser + +#@torch.no_grad() # NOTE Becaus we need gradients for forces +def evaluate(model, loader, loss_fn, device, desc="Eval"): + model.eval() + + # MAE + sum_abs_dF = torch.tensor(0.0, device=device) # Σ |ΔF| over all components + sum_abs_dE = torch.tensor(0.0, device=device) # Σ |ΔE| over all systems + + # RMSE + sum_sq_dF = torch.tensor(0.0, device=device) # Σ (ΔF)^2 over all components + sum_sq_dE = torch.tensor(0.0, device=device) # Σ (ΔE)^2 over all systems + + # UPD: for MACE-style E/atom MAE (per-system normalized first) + sum_abs_dE_per_atom = torch.tensor(0.0, device=device) # Σ |ΔE_i|/N_i + + # UPD: for MACE-style E/atom RMSE + sum_sq_dE_per_atom = torch.tensor(0.0, device=device) + + # Total things + total_force_components = torch.tensor(0.0, device=device) # Σ (3 * natoms) + total_systems = torch.tensor(0.0, device=device) # Σ n_systems + total_atoms = torch.tensor(0.0, device=device) # Σ natoms (atom-weighted E/atom) + + for batch in tqdm(loader, desc=desc, dynamic_ncols=True): + batch = batch.to(device) + batch_dict = batch.to_dict() + + output = model( + batch_dict, + training=False, + compute_force=True, + compute_virials=False, + compute_stress=False, + ) + + + + loss_forces_L1, loss_energy_L1, loss_forces_L2, loss_energy_L2 = loss_fn(pred=output, ref=batch, do_eval=True) + + # --- infer natoms per system and number of systems --- + if hasattr(batch, "natoms") and batch.natoms is not None: + natoms_per_system = batch.natoms.view(-1).to(torch.float32) + + elif hasattr(batch, "ptr") and batch.ptr is not None: + natoms_per_system = (batch.ptr[1:] - batch.ptr[:-1]).to(torch.float32) + + else: + # Fallback: without natoms/ptr we cannot reliably infer multiple systems. + # Assume a single system in the batch. + natoms_per_system = torch.tensor( + [batch.pos.shape[0]], + device=device, + dtype=torch.float32 + ) + + + n_systems = natoms_per_system.numel() + natoms_batch = natoms_per_system.sum() + + total_atoms += natoms_batch + total_force_components += 3.0 * natoms_batch + total_systems += torch.tensor(float(n_systems), device=device) + + # accumulate sums from loss_fn + sum_abs_dF += loss_forces_L1 + sum_abs_dE += loss_energy_L1 + + sum_sq_dF += loss_forces_L2 + sum_sq_dE += loss_energy_L2 + + e_pred = output["energy"].view(-1) + e_true = batch.energy.view(-1) + dE = e_pred - e_true # [n_systems] + abs_dE = (dE).abs() # [n_systems] + + + # UPD: MACE-style per-system per-atom energy MAE + sum_abs_dE_per_atom += (abs_dE / natoms_per_system).sum() + + + # --- UPD: per-system energy-per-atom RMSE --- + dE_per_atom = dE / natoms_per_system # normalize per system + sum_sq_dE_per_atom += (dE_per_atom ** 2).sum() + + + + mae_F = (sum_abs_dF / total_force_components).item() if total_force_components.item() > 0 else float("nan") + mae_E_sys = (sum_abs_dE / total_systems).item() if total_systems.item() > 0 else float("nan") + # atom-weighted (our definition) + mae_E_atom_weighted = (sum_abs_dE / total_atoms).item() if total_atoms.item() > 0 else float("nan") + # MACE-style: average over systems of (|ΔE|/N) + mae_E_atom_mace = (sum_abs_dE_per_atom / total_systems).item() if total_systems.item() > 0 else float("nan") + + + rmse_F = torch.sqrt(sum_sq_dF / total_force_components).item() + rmse_E_sys = torch.sqrt(sum_sq_dE / total_systems).item() + # atom-weighted (our definition) + rmse_E_atom_weighted = torch.sqrt(sum_sq_dE / total_atoms).item() + # MACE-style per-system-per-atom + rmse_E_atom_mace = torch.sqrt(sum_sq_dE_per_atom / total_systems).item() + + print(f"MAE(F components): {mae_F:.6f}") + print(f"MAE(E per system): {mae_E_sys:.6f}") + print(f"MAE(E per atom, weighted): {mae_E_atom_weighted:.6f}") + print(f"MAE(E per atom, MACE): {mae_E_atom_mace:.6f}") + + print(f"RMSE(F components): {rmse_F:.6f}") + print(f"RMSE(E per system): {rmse_E_sys:.6f}") + print(f"RMSE(E per atom, weighted): {rmse_E_atom_weighted:.6f}") + print(f"RMSE(E per atom, MACE): {rmse_E_atom_mace:.6f}") + + + return { + "MAE(F components)" : mae_F, + "MAE(E per system)": mae_E_sys, + "MAE(E per atom, weighted)": mae_E_atom_weighted, + "MAE(E per atom, MACE)": mae_E_atom_mace, + + "RMSE(F components)": rmse_F, + "RMSE(E per system)": rmse_E_sys, + "RMSE(E per atom, weighted)": rmse_E_atom_weighted, + "RMSE(E per atom, MACE)": rmse_E_atom_mace + + } + # return { + # "mae_F": mae_F, + # "mae_E_sys": mae_E_sys, + # "mae_E_atom_weighted": mae_E_atom_weighted, + # "mae_E_atom_mace": mae_E_atom_mace, + # } + + +def build_valid_set_xyz(valid_xyz_path: str, model, args): + # 1) z_table must match foundation model + z_table = AtomicNumberTable([int(z) for z in model.atomic_numbers]) + heads = ["Default"] + + # 2) key spec (uses args.*_key etc.) + args.key_specification = data.KeySpecification() + data.update_keyspec_from_kwargs(args.key_specification, vars(args)) + + # 3) Build "collections" using the helper (we only need .valid) + # It expects train_path too; you can pass valid as train and use valid_fraction=1.0, + # OR pass an explicit valid_path if you have it. + collections, _ = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=[valid_xyz_path], # dummy + valid_path=[valid_xyz_path], # real valid + valid_fraction=0.0, # since valid_path is provided + config_type_weights={"Default": 1.0}, + test_path=None, + seed=args.seed, + key_specification=args.key_specification, + head_name="Default", + keep_isolated_atoms=args.keep_isolated_atoms, + prefix=args.name, + ) + + # 4) Convert configs -> AtomicData list + valid_set = [ + data.AtomicData.from_config( + config, + z_table=z_table, + cutoff=float(model.r_max), + heads=heads, + ) + for config in collections.valid + ] + return valid_set + +def count_params_millions(model, trainable_only=False): + if trainable_only: + n = sum(p.numel() for p in model.parameters() if p.requires_grad) + else: + n = sum(p.numel() for p in model.parameters()) + return n / 1e6 + + +def format_result_block(model_path: str, results: dict, seconds: float) -> str: + p = Path(model_path) + lines = [] + lines.append("=" * 100) + lines.append(f"MODEL: {p.name}") + lines.append(f"PATH: {str(p)}") + lines.append(f"TIME: {seconds:.2f} s") + for k, v in results.items(): + lines.append(f"{k:28s} {v:.8f}") + lines.append("") # blank line + return "\n".join(lines) + + +def main(): + + parser = build_parser() + args = parser.parse_args() + + + # Hard-code your loss (as you do today) + args.loss = "ours_mae" + loss_fn = get_loss_fn(args, dipole_only=False, compute_dipole=False) + + # NOTE, you forgot to change the name, but they are different seeds! not all are 42 + + model_paths = args.model_paths + + + + # Output text file (put it in work_dir if available) + out_txt = Path(args.out_txt) + out_txt.parent.mkdir(parents=True, exist_ok=True) + + # ------------------------------------------------------------------------- + # Build validation set/loader ONCE, using the first model for z_table + r_max + # (assumes comparable checkpoints; if not, rebuild per model instead) + # ------------------------------------------------------------------------- + first_model = torch.load(model_paths[0], map_location="cpu") + n_params_total = count_params_millions(first_model, trainable_only=False) + n_params_train = count_params_millions(first_model, trainable_only=True) + + print(f"Model parameters: {n_params_total:.3f} M " + f"(trainable: {n_params_train:.3f} M)") + + + + valid_set = build_valid_set_xyz(args.valid_file, first_model, args) + + + + del first_model + + valid_loader = torch_geometric.dataloader.DataLoader( + dataset=valid_set, + batch_size=args.valid_batch_size, + sampler=None, + shuffle=False, + drop_last=False, + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + + # ------------------------------------------------------------------------- + # Loop models, evaluate, and append results + # ------------------------------------------------------------------------- + with open(out_txt, "a", encoding="utf-8") as f: + f.write(f"\n\nRUN START: {time.strftime('%Y-%m-%d %H:%M:%S')}\n") + f.write(f"VALID_FILE: {args.valid_file}\n") + f.write(f"NUM_MODELS: {len(model_paths)}\n\n") + + for model_path in model_paths: + t0 = time.time() + model = torch.load(model_path, map_location="cpu") + model.to(args.device) + model.float() + + try: + results = evaluate( + model, + valid_loader, + loss_fn, + args.device, + desc=f"Eval {Path(model_path).name}", + ) + dt = time.time() - t0 + + block = format_result_block(model_path, results, dt) + print(block) + f.write(block + "\n") + f.flush() + + except Exception as e: + dt = time.time() - t0 + f.write("=" * 100 + "\n") + f.write(f"MODEL: {Path(model_path).name}\n") + f.write(f"PATH: {model_path}\n") + f.write(f"TIME: {dt:.2f} s\n") + f.write(f"ERROR: {repr(e)}\n\n") + f.flush() + + finally: + del model + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + + print(f"\nWrote results to: {out_txt}") + + + + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/models/mace/mace/cli/our_files/run_eval_foundation_no_finetuning.py b/models/mace/mace/cli/our_files/run_eval_foundation_no_finetuning.py new file mode 100644 index 0000000000000000000000000000000000000000..59fb06746fed0654aa8c73b4349e4fa65520d192 --- /dev/null +++ b/models/mace/mace/cli/our_files/run_eval_foundation_no_finetuning.py @@ -0,0 +1,469 @@ +########################################################################################### +# Training script for MACE +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import warnings +import os +warnings.filterwarnings( + "ignore", + category=FutureWarning, + message="You are using `torch.load` with `weights_only=False`" +) +os.environ["MACE_DISABLE_CUEQUIV"] = "1" + +import ast +import glob +import json +import logging +from copy import deepcopy +from pathlib import Path +from typing import List, Optional +import torch +import torch.distributed +from tqdm import tqdm +from e3nn.util import jit +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import LBFGS +from torch.utils.data import ConcatDataset +from torch_ema import ExponentialMovingAverage + +import mace +from mace import data, tools +from mace.calculators.foundations_models import ( + mace_mp, + mace_mp_names, + mace_off, + mace_omol, +) +from mace.cli.convert_cueq_e3nn import run as run_cueq_to_e3nn +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq +from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq +from mace.cli.convert_oeq_e3nn import run as run_oeq_to_e3nn +from mace.cli.visualise_train import TrainingPlotter +from mace.data import KeySpecification, update_keyspec_from_kwargs +from mace.tools import torch_geometric +from mace.tools.distributed_tools import init_distributed +from mace.tools.model_script_utils import configure_model +from mace.tools.multihead_tools import ( + HeadConfig, + apply_pseudolabels_to_pt_head_configs, + assemble_replay_data, + dict_head_to_dataclass, + prepare_default_head, + prepare_pt_head, +) +from mace.tools.run_train_utils import ( + combine_datasets, + load_dataset_for_path, + normalize_file_paths, +) +from mace.tools.scripts_utils import ( + LRScheduler, + SubsetCollection, + check_path_ase_read, + convert_to_json_format, + dict_to_array, + extract_config_mace_model, + get_atomic_energies, + get_avg_num_neighbors, + get_config_type_weights, + get_dataset_from_xyz, + get_files_with_suffix, + get_loss_fn, + get_optimizer, + get_params_options, + get_swa, + print_git_commit, + remove_pt_head, + setup_wandb, +) +from mace.tools.tables_utils import create_error_table +from mace.tools.utils import AtomicNumberTable + + +#NOTE Calculator stuff +from pathlib import Path +import torch +from ase.io import read, write +from ase.optimize import FIRE + +from mace.calculators import MACECalculator # this exists in MACE +# If import path differs in your install, try: +# from mace.calculators.mace import MACECalculator + +import time + +import ast +import torch + + + +def set_model_e0s_from_args_all_heads(model, args, *, missing: str = "keep"): + """ + Overwrite model.atomic_energies_fn.atomic_energies using args.E0s + and apply the SAME E0s to ALL heads (if multi-head). + + missing : {"keep", "zero", "error"} + - keep: keep existing values for Z not provided + - zero: set all Z to 0 first, then apply provided E0s + - error: require args.E0s to provide every Z in model.atomic_numbers + """ + import ast + import torch + + if not hasattr(model, "atomic_energies_fn"): + raise AttributeError("Model has no atomic_energies_fn; cannot set E0s.") + + if not hasattr(args, "E0s") or args.E0s is None: + raise ValueError("args.E0s is missing; provide --E0s '{...}'") + + e0s = args.E0s if isinstance(args.E0s, dict) else ast.literal_eval(args.E0s) + if not isinstance(e0s, dict): + raise TypeError(f"Expected args.E0s to parse into dict, got {type(e0s)}") + + model_zs = [int(z) for z in model.atomic_numbers] + z_to_idx = {z: i for i, z in enumerate(model_zs)} + + ae = model.atomic_energies_fn.atomic_energies # [nZ] or [n_heads, nZ] + + # Normalize to 2D [n_heads, nZ] + if ae.ndim == 1: + ae2 = ae.unsqueeze(0) + squeeze_back = True + elif ae.ndim == 2: + ae2 = ae + squeeze_back = False + else: + raise ValueError(f"Unexpected atomic_energies shape {tuple(ae.shape)}") + + # Start from existing values (keep), or zeros (zero) + new_ae2 = ae2.detach().clone() + if missing == "zero": + new_ae2.zero_() + elif missing == "keep": + pass + elif missing == "error": + pass + else: + raise ValueError("missing must be one of {'keep','zero','error'}") + + # Apply provided E0s to ALL head rows + for z, val in e0s.items(): + z = int(z) + if z not in z_to_idx: + raise KeyError(f"Atomic number Z={z} not present in model.atomic_numbers (len={len(model_zs)})") + new_ae2[:, z_to_idx[z]] = float(val) + + if missing == "error": + provided = {int(k) for k in e0s.keys()} + missing_zs = [z for z in model_zs if z not in provided] + if missing_zs: + raise ValueError( + f"args.E0s missing atomic numbers: {missing_zs[:20]}{'...' if len(missing_zs)>20 else ''}" + ) + + # Write back safely (preserve dtype/device; preserve parameter/buffer identity) + new_ae2 = new_ae2.to(dtype=ae2.dtype, device=ae2.device) + with torch.no_grad(): + if squeeze_back: + model.atomic_energies_fn.atomic_energies.copy_(new_ae2.squeeze(0)) + else: + model.atomic_energies_fn.atomic_energies.copy_(new_ae2) + + return model + + +#@torch.no_grad() # NOTE Becaus we need gradients for forces +def evaluate(model, loader, loss_fn, device, desc="Eval"): + model.eval() + + # MAE + sum_abs_dF = torch.tensor(0.0, device=device) # Σ |ΔF| over all components + sum_abs_dE = torch.tensor(0.0, device=device) # Σ |ΔE| over all systems + + # RMSE + sum_sq_dF = torch.tensor(0.0, device=device) # Σ (ΔF)^2 over all components + sum_sq_dE = torch.tensor(0.0, device=device) # Σ (ΔE)^2 over all systems + + # UPD: for MACE-style E/atom MAE (per-system normalized first) + sum_abs_dE_per_atom = torch.tensor(0.0, device=device) # Σ |ΔE_i|/N_i + + # UPD: for MACE-style E/atom RMSE + sum_sq_dE_per_atom = torch.tensor(0.0, device=device) + + # Total things + total_force_components = torch.tensor(0.0, device=device) # Σ (3 * natoms) + total_systems = torch.tensor(0.0, device=device) # Σ n_systems + total_atoms = torch.tensor(0.0, device=device) # Σ natoms (atom-weighted E/atom) + + for batch in tqdm(loader, desc=desc, dynamic_ncols=True): + batch = batch.to(device) + batch_dict = batch.to_dict() + + output = model( + batch_dict, + training=False, + compute_force=True, + compute_virials=False, + compute_stress=False, + ) + + + loss_forces_L1, loss_energy_L1, loss_forces_L2, loss_energy_L2 = loss_fn(pred=output, ref=batch, do_eval=True) + + # --- infer natoms per system and number of systems --- + if hasattr(batch, "natoms") and batch.natoms is not None: + natoms_per_system = batch.natoms.view(-1).to(torch.float32) + + elif hasattr(batch, "ptr") and batch.ptr is not None: + natoms_per_system = (batch.ptr[1:] - batch.ptr[:-1]).to(torch.float32) + + else: + # Fallback: without natoms/ptr we cannot reliably infer multiple systems. + # Assume a single system in the batch. + natoms_per_system = torch.tensor( + [batch.pos.shape[0]], + device=device, + dtype=torch.float32 + ) + + + n_systems = natoms_per_system.numel() + natoms_batch = natoms_per_system.sum() + + total_atoms += natoms_batch + total_force_components += 3.0 * natoms_batch + total_systems += torch.tensor(float(n_systems), device=device) + + # accumulate sums from loss_fn + sum_abs_dF += loss_forces_L1 + sum_abs_dE += loss_energy_L1 + + sum_sq_dF += loss_forces_L2 + sum_sq_dE += loss_energy_L2 + + e_pred = output["energy"].view(-1) + e_true = batch.energy.view(-1) + dE = e_pred - e_true # [n_systems] + abs_dE = (dE).abs() # [n_systems] + + + # UPD: MACE-style per-system per-atom energy MAE + sum_abs_dE_per_atom += (abs_dE / natoms_per_system).sum() + + + # --- UPD: per-system energy-per-atom RMSE --- + dE_per_atom = dE / natoms_per_system # normalize per system + sum_sq_dE_per_atom += (dE_per_atom ** 2).sum() + + + + mae_F = (sum_abs_dF / total_force_components).item() if total_force_components.item() > 0 else float("nan") + mae_E_sys = (sum_abs_dE / total_systems).item() if total_systems.item() > 0 else float("nan") + # atom-weighted (our definition) + mae_E_atom_weighted = (sum_abs_dE / total_atoms).item() if total_atoms.item() > 0 else float("nan") + # MACE-style: average over systems of (|ΔE|/N) + mae_E_atom_mace = (sum_abs_dE_per_atom / total_systems).item() if total_systems.item() > 0 else float("nan") + + + rmse_F = torch.sqrt(sum_sq_dF / total_force_components).item() + rmse_E_sys = torch.sqrt(sum_sq_dE / total_systems).item() + # atom-weighted (our definition) + rmse_E_atom_weighted = torch.sqrt(sum_sq_dE / total_atoms).item() + # MACE-style per-system-per-atom + rmse_E_atom_mace = torch.sqrt(sum_sq_dE_per_atom / total_systems).item() + + print(f"MAE(F components): {mae_F:.6f}") + print(f"MAE(E per system): {mae_E_sys:.6f}") + print(f"MAE(E per atom, weighted): {mae_E_atom_weighted:.6f}") + print(f"MAE(E per atom, MACE): {mae_E_atom_mace:.6f}") + + print(f"RMSE(F components): {rmse_F:.6f}") + print(f"RMSE(E per system): {rmse_E_sys:.6f}") + print(f"RMSE(E per atom, weighted): {rmse_E_atom_weighted:.6f}") + print(f"RMSE(E per atom, MACE): {rmse_E_atom_mace:.6f}") + + + return { + "MAE(F components)" : mae_F, + "MAE(E per system)": mae_E_sys, + "MAE(E per atom, weighted)": mae_E_atom_weighted, + "MAE(E per atom, MACE)": mae_E_atom_mace, + + "RMSE(F components)": rmse_F, + "RMSE(E per system)": rmse_E_sys, + "RMSE(E per atom, weighted)": rmse_E_atom_weighted, + "RMSE(E per atom, MACE)": rmse_E_atom_mace + + } + # return { + # "mae_F": mae_F, + # "mae_E_sys": mae_E_sys, + # "mae_E_atom_weighted": mae_E_atom_weighted, + # "mae_E_atom_mace": mae_E_atom_mace, + # } + + +def build_valid_set_xyz(valid_xyz_path: str, model, args, head_list, head_name: str): + z_table = AtomicNumberTable([int(z) for z in model.atomic_numbers]) + heads = head_list + + args.key_specification = data.KeySpecification() + data.update_keyspec_from_kwargs(args.key_specification, vars(args)) + + collections, _ = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=[valid_xyz_path], + valid_path=[valid_xyz_path], + valid_fraction=0.0, + config_type_weights={"Default": 1.0}, + test_path=None, + seed=args.seed, + key_specification=args.key_specification, + head_name=head_name, # <<< change here + keep_isolated_atoms=args.keep_isolated_atoms, + prefix=args.name, + ) + + valid_set = [ + data.AtomicData.from_config( + config, + z_table=z_table, + cutoff=float(model.r_max), + heads=heads, + ) + for config in collections.valid + ] + return valid_set + + +def count_params_millions(model, trainable_only=False): + if trainable_only: + n = sum(p.numel() for p in model.parameters() if p.requires_grad) + else: + n = sum(p.numel() for p in model.parameters()) + return n / 1e6 + + +def format_result_block(model_path: str, results: dict, seconds: float) -> str: + p = Path(model_path) + lines = [] + lines.append("=" * 100) + lines.append(f"MODEL: {p.name}") + lines.append(f"PATH: {str(p)}") + lines.append(f"TIME: {seconds:.2f} s") + for k, v in results.items(): + lines.append(f"{k:28s} {v:.8f}") + lines.append("") # blank line + return "\n".join(lines) + +# NOTE THIS WAS (I THINK) JUST A SCRIPT TO RUN DEFAULT FOUNDATION MODELS WITHOUT ANY FINETUNING, TO CREATE FIGURE 1 +def main(): + args = tools.build_default_arg_parser().parse_args() + + # Hard-code your loss (as you do today) + args.loss = "ours_mae" + loss_fn = get_loss_fn(args, dipole_only=False, compute_dipole=False) + + # HEADS + # mace-omat-0-medium-model: ["Default"] + # mace-mh-1.model: ['matpes_r2scan', 'mp_pbe_refit_add', 'spice_wB97M', 'oc20_usemppbe', 'omol', 'omat_pbe'] 6.4M + # mace-mh-0.model: ['rgd1_b3lyp', 'matpes_r2scan', 'mp_pbe_refit_add', 'omol', 'spice_wB97M', 'oc20_usemppbe', 'omat_pbe'] 9.1 M + # MACE-matpes-pbe-omat-ft.model: ['default'] + # 2024-01-07-mace-128-L2_epoch-199.model ["Default"] + # 2023-12-03-mace-128-L1_epoch-199.model ["Default"] 4.689 M + + + + # [foundation_checkpoints/mace-mh-1.model, foundation_checkpoints/MACE-matpes-pbe-omat-ft.model] + + model_paths = "foundation_checkpoints/MACE-matpes-pbe-omat-ft.model" + + model = torch.load(model_paths, map_location="cpu") + + n_params_total = count_params_millions(model, trainable_only=False) + n_params_train = count_params_millions(model, trainable_only=True) + + print(f"Model parameters: {n_params_total:.3f} M " + f"(trainable: {n_params_train:.3f} M)") + + + #torch.save(model, "0_8_model_inference.model") + + try: + print(model.heads) + keep_head = "omat_pbe" + model = remove_pt_head(model, keep_head) + except Exception as e: + print("Error accessing model.heads:", e) + model.heads = ["Default"] + keep_head = "Default" + + + n_params_total = count_params_millions(model, trainable_only=False) + n_params_train = count_params_millions(model, trainable_only=True) + + print(f"Model parameters: {n_params_total:.3f} M " + f"(trainable: {n_params_train:.3f} M)") + + + + + + model = set_model_e0s_from_args_all_heads(model, args, missing="keep") + + + model_config_foundation = extract_config_mace_model(model) + + + + model.to(args.device) + model.float() + + n_params_total = count_params_millions(model, trainable_only=False) + n_params_train = count_params_millions(model, trainable_only=True) + + print(f"Model parameters after removing head: {n_params_total:.3f} M " + f"(trainable: {n_params_train:.3f} M)") + + + # NOTE If you want to save a specific head later + # model_to_save = model.to("cpu").float() # ensure CPU + float32 for portability + # torch.save(model_to_save, "") + # print(f"Saved single-head model to:") + + + valid_set = build_valid_set_xyz(args.valid_file, model, args, model.heads, keep_head) + + valid_loader = torch_geometric.dataloader.DataLoader( + dataset=valid_set, + batch_size=args.valid_batch_size, + sampler=None, + shuffle=False, + drop_last=False, + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + + results = evaluate( + model, + valid_loader, + loss_fn, + args.device, + desc=f"Eval", + ) + + print(results) + + print(f'Results on Model {model_paths} for head {keep_head}') + + + + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/models/mace/mace/cli/our_files/run_inference_speed.py b/models/mace/mace/cli/our_files/run_inference_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..19b49331d9bf53f9137fb4a97d3a5dea95c54934 --- /dev/null +++ b/models/mace/mace/cli/our_files/run_inference_speed.py @@ -0,0 +1,329 @@ +########################################################################################### +# Training script for MACE +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import warnings +import os +warnings.filterwarnings( + "ignore", + category=FutureWarning, + message="You are using `torch.load` with `weights_only=False`" +) +os.environ["MACE_DISABLE_CUEQUIV"] = "1" + +import ast +import glob +import json +import logging +from copy import deepcopy +from pathlib import Path +from typing import List, Optional +import torch +import torch.distributed +from tqdm import tqdm +from e3nn.util import jit +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import LBFGS +from torch.utils.data import ConcatDataset +from torch_ema import ExponentialMovingAverage + +import mace +from mace import data, tools +from mace.calculators.foundations_models import ( + mace_mp, + mace_mp_names, + mace_off, + mace_omol, +) +from mace.cli.convert_cueq_e3nn import run as run_cueq_to_e3nn +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq +from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq +from mace.cli.convert_oeq_e3nn import run as run_oeq_to_e3nn +from mace.cli.visualise_train import TrainingPlotter +from mace.data import KeySpecification, update_keyspec_from_kwargs +from mace.tools import torch_geometric +from mace.tools.distributed_tools import init_distributed +from mace.tools.model_script_utils import configure_model +from mace.tools.multihead_tools import ( + HeadConfig, + apply_pseudolabels_to_pt_head_configs, + assemble_replay_data, + dict_head_to_dataclass, + prepare_default_head, + prepare_pt_head, +) +from mace.tools.run_train_utils import ( + combine_datasets, + load_dataset_for_path, + normalize_file_paths, +) +from mace.tools.scripts_utils import ( + LRScheduler, + SubsetCollection, + check_path_ase_read, + convert_to_json_format, + dict_to_array, + extract_config_mace_model, + get_atomic_energies, + get_avg_num_neighbors, + get_config_type_weights, + get_dataset_from_xyz, + get_files_with_suffix, + get_loss_fn, + get_optimizer, + get_params_options, + get_swa, + print_git_commit, + remove_pt_head, + setup_wandb, +) +from mace.tools.tables_utils import create_error_table +from mace.tools.utils import AtomicNumberTable + + +#NOTE Calculator stuff +from pathlib import Path +import torch +from ase.io import read, write +from ase.optimize import FIRE + +from mace.calculators import MACECalculator # this exists in MACE +# If import path differs in your install, try: +# from mace.calculators.mace import MACECalculator + +import time + +import ast +import torch + + + +def set_model_e0s_from_args_all_heads(model, args, *, missing: str = "keep"): + """ + Overwrite model.atomic_energies_fn.atomic_energies using args.E0s + and apply the SAME E0s to ALL heads (if multi-head). + + missing : {"keep", "zero", "error"} + - keep: keep existing values for Z not provided + - zero: set all Z to 0 first, then apply provided E0s + - error: require args.E0s to provide every Z in model.atomic_numbers + """ + import ast + import torch + + if not hasattr(model, "atomic_energies_fn"): + raise AttributeError("Model has no atomic_energies_fn; cannot set E0s.") + + if not hasattr(args, "E0s") or args.E0s is None: + raise ValueError("args.E0s is missing; provide --E0s '{...}'") + + e0s = args.E0s if isinstance(args.E0s, dict) else ast.literal_eval(args.E0s) + if not isinstance(e0s, dict): + raise TypeError(f"Expected args.E0s to parse into dict, got {type(e0s)}") + + model_zs = [int(z) for z in model.atomic_numbers] + z_to_idx = {z: i for i, z in enumerate(model_zs)} + + ae = model.atomic_energies_fn.atomic_energies # [nZ] or [n_heads, nZ] + + # Normalize to 2D [n_heads, nZ] + if ae.ndim == 1: + ae2 = ae.unsqueeze(0) + squeeze_back = True + elif ae.ndim == 2: + ae2 = ae + squeeze_back = False + else: + raise ValueError(f"Unexpected atomic_energies shape {tuple(ae.shape)}") + + # Start from existing values (keep), or zeros (zero) + new_ae2 = ae2.detach().clone() + if missing == "zero": + new_ae2.zero_() + elif missing == "keep": + pass + elif missing == "error": + pass + else: + raise ValueError("missing must be one of {'keep','zero','error'}") + + # Apply provided E0s to ALL head rows + for z, val in e0s.items(): + z = int(z) + if z not in z_to_idx: + raise KeyError(f"Atomic number Z={z} not present in model.atomic_numbers (len={len(model_zs)})") + new_ae2[:, z_to_idx[z]] = float(val) + + if missing == "error": + provided = {int(k) for k in e0s.keys()} + missing_zs = [z for z in model_zs if z not in provided] + if missing_zs: + raise ValueError( + f"args.E0s missing atomic numbers: {missing_zs[:20]}{'...' if len(missing_zs)>20 else ''}" + ) + + # Write back safely (preserve dtype/device; preserve parameter/buffer identity) + new_ae2 = new_ae2.to(dtype=ae2.dtype, device=ae2.device) + with torch.no_grad(): + if squeeze_back: + model.atomic_energies_fn.atomic_energies.copy_(new_ae2.squeeze(0)) + else: + model.atomic_energies_fn.atomic_energies.copy_(new_ae2) + + return model + + + +def build_valid_set_xyz(valid_xyz_path: str, model, args, head_list, head_name: str): + z_table = AtomicNumberTable([int(z) for z in model.atomic_numbers]) + heads = head_list + + args.key_specification = data.KeySpecification() + data.update_keyspec_from_kwargs(args.key_specification, vars(args)) + + collections, _ = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=[valid_xyz_path], + valid_path=[valid_xyz_path], + valid_fraction=0.0, + config_type_weights={"Default": 1.0}, + test_path=None, + seed=args.seed, + key_specification=args.key_specification, + head_name=head_name, # <<< change here + keep_isolated_atoms=args.keep_isolated_atoms, + prefix=args.name, + ) + + valid_set = [ + data.AtomicData.from_config( + config, + z_table=z_table, + cutoff=float(model.r_max), + heads=heads, + ) + for config in collections.valid + ] + return valid_set + + +def count_params_millions(model, trainable_only=False): + if trainable_only: + n = sum(p.numel() for p in model.parameters() if p.requires_grad) + else: + n = sum(p.numel() for p in model.parameters()) + return n / 1e6 + + +def format_result_block(model_path: str, results: dict, seconds: float) -> str: + p = Path(model_path) + lines = [] + lines.append("=" * 100) + lines.append(f"MODEL: {p.name}") + lines.append(f"PATH: {str(p)}") + lines.append(f"TIME: {seconds:.2f} s") + for k, v in results.items(): + lines.append(f"{k:28s} {v:.8f}") + lines.append("") # blank line + return "\n".join(lines) + + +def main(): + args = tools.build_default_arg_parser().parse_args() + + # HEADS + # mace-omat-0-medium-model: ["Default"] + # mace-mh-1.model: ['matpes_r2scan', 'mp_pbe_refit_add', 'spice_wB97M', 'oc20_usemppbe', 'omol', 'omat_pbe'] 6.4M + # mace-mh-0.model: ['rgd1_b3lyp', 'matpes_r2scan', 'mp_pbe_refit_add', 'omol', 'spice_wB97M', 'oc20_usemppbe', 'omat_pbe'] 9.1 M + # MACE-matpes-pbe-omat-ft.model: ['default'] + # 2024-01-07-mace-128-L2_epoch-199.model ["Default"] + # 2023-12-03-mace-128-L1_epoch-199.model ["Default"] 4.689 M + + + model_paths = "" + + model = torch.load(model_paths, map_location="cpu") + + try: + print(model.heads) + keep_head = "omat_pbe" + model = remove_pt_head(model, keep_head) + except Exception as e: + print("Error accessing model.heads:", e) + model.heads = ["Default"] + keep_head = "Default" + + + + n_params_total = count_params_millions(model, trainable_only=False) + n_params_train = count_params_millions(model, trainable_only=True) + + print(f"Model parameters: {n_params_total:.3f} M " + f"(trainable: {n_params_train:.3f} M)") + + + model = set_model_e0s_from_args_all_heads(model, args, missing="keep") + + + model.to(args.device) + model.float() + + + valid_set = build_valid_set_xyz(args.valid_file, model, args, model.heads, keep_head) + + valid_loader = torch_geometric.dataloader.DataLoader( + dataset=valid_set, + batch_size=args.valid_batch_size, + sampler=None, + shuffle=False, + drop_last=False, + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + + n = 1000 + + + for batch in valid_loader: + batch = batch.to(args.device) + batch_dict = batch.to_dict() + + output = model( + batch_dict, + training=False, + compute_force=True, + compute_virials=False, + compute_stress=False, + ) + + + # start timer: + start_time = time.time() + for _ in range(n): + # perform forward pass: + output = model( + batch_dict, + training=False, + compute_force=True, + compute_virials=False, + compute_stress=False, + ) + end_time = time.time() + + + print("\nTime for forward pass: {} seconds".format( (end_time - start_time) / n)) + + + + + + + + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/models/mace/mace/cli/plot_train.py b/models/mace/mace/cli/plot_train.py new file mode 100644 index 0000000000000000000000000000000000000000..238bd095f57ef7f9eaf2c046972051b82506bb60 --- /dev/null +++ b/models/mace/mace/cli/plot_train.py @@ -0,0 +1,342 @@ +import argparse +import dataclasses +import glob +import json +import os +import re +from typing import List + +import matplotlib.pyplot as plt +import pandas as pd + +plt.rcParams.update({"font.size": 8}) +plt.style.use("seaborn-v0_8-paper") + + +colors = [ + "#1f77b4", # muted blue + "#d62728", # brick red + "#ff7f0e", # safety orange + "#2ca02c", # cooked asparagus green + "#9467bd", # muted purple + "#8c564b", # chestnut brown + "#e377c2", # raspberry yogurt pink + "#7f7f7f", # middle gray + "#bcbd22", # curry yellow-green + "#17becf", # blue-teal +] + + +@dataclasses.dataclass +class RunInfo: + name: str + seed: int + + +name_re = re.compile(r"(?P.+)_run-(?P\d+)_train.txt") + + +def parse_path(path: str) -> RunInfo: + match = name_re.match(os.path.basename(path)) + if not match: + raise RuntimeError(f"Cannot parse {path}") + + return RunInfo(name=match.group("name"), seed=int(match.group("seed"))) + + +def parse_training_results(path: str) -> List[dict]: + run_info = parse_path(path) + results = [] + with open(path, mode="r", encoding="utf-8") as f: + for line in f: + d = json.loads(line) + d["name"] = run_info.name + d["seed"] = run_info.seed + results.append(d) + + return results + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Plot mace training statistics", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--path", help="Path to results file (.txt) or directory.", required=True + ) + parser.add_argument( + "--min_epoch", help="Minimum epoch.", default=0, type=int, required=False + ) + parser.add_argument( + "--start_stage_two", + "--start_swa", + help="Epoch that stage two (swa) loss began. Plots dashed line on plot to indicate. If None then assumed tag not used in training.", + default=None, + type=int, + required=False, + dest="start_swa", + ) + parser.add_argument( + "--linear", + help="Whether to plot linear instead of log scales.", + default=False, + required=False, + action="store_true", + ) + parser.add_argument( + "--error_bars", + help="Whether to plot standard deviations.", + default=False, + required=False, + action="store_true", + ) + parser.add_argument( + "--keys", + help="Comma-separated list of keys to plot.", + default="rmse_e,rmse_f", + type=str, + required=False, + ) + + parser.add_argument( + "--output_format", + help="What file type to save plot as", + default="png", + type=str, + required=False, + ) + + parser.add_argument( + "--heads", + help="Comma-separated name of the heads used for multihead training", + default=None, + type=str, + required=False, + ) + + return parser.parse_args() + + +def plot( + data: pd.DataFrame, + min_epoch: int, + output_path: str, + output_format: str, + linear: bool, + start_swa: int, + error_bars: bool, + keys: str, + heads: str, +) -> None: + """ + Plots train,validation loss and errors as a function of epoch. + min_epoch: minimum epoch to plot. + output_path: path to save the plot. + output_format: format to save the plot. + start_swa: whether to plot a dashed line to show epoch when stage two loss (swa) begins. + error_bars: whether to plot standard deviation of loss. + linear: whether to plot in linear scale or logscale (default). + keys: Values to plot. + heads: Heads used for multihead training. + """ + + labels = { + "mae_e": "MAE E [meV]", + "mae_e_per_atom": "MAE E/atom [meV]", + "rmse_e": "RMSE E [meV]", + "rmse_e_per_atom": "RMSE E/atom [meV]", + "q95_e": "Q95 E [meV]", + "mae_f": "MAE F [meV / A]", + "rel_mae_f": "Relative MAE F [meV / A]", + "rmse_f": "RMSE F [meV / A]", + "rel_rmse_f": "Relative RMSE F [meV / A]", + "q95_f": "Q95 F [meV / A]", + "mae_stress": "MAE Stress", + "rmse_stress": "RMSE Stress [meV / A^3]", + "rmse_virials_per_atom": " RMSE virials/atom [meV]", + "mae_virials": "MAE Virials [meV]", + "rmse_mu_per_atom": "RMSE MU/atom [mDebye]", + } + + data = data[data["epoch"] > min_epoch] + if heads is None: + data = ( + data.groupby(["name", "mode", "epoch"]).agg(["mean", "std"]).reset_index() + ) + + valid_data = data[data["mode"] == "eval"] + valid_data_dict = {"default": valid_data} + train_data = data[data["mode"] == "opt"] + else: + heads = heads.split(",") + # Separate eval and opt data + valid_data = ( + data[data["mode"] == "eval"] + .groupby(["name", "mode", "epoch", "head"]) + .agg(["mean", "std"]) + .reset_index() + ) + train_data = ( + data[data["mode"] == "opt"] + .groupby(["name", "mode", "epoch"]) + .agg(["mean", "std"]) + .reset_index() + ) + valid_data_dict = { + head: valid_data[valid_data["head"] == head] for head in heads + } + + for head, valid_data in valid_data_dict.items(): + fig, axes = plt.subplots( + nrows=1, ncols=2, figsize=(10, 3), constrained_layout=True + ) + + # ---- Plot loss ---- + ax = axes[0] + ax.plot( + train_data["epoch"], + train_data["loss"]["mean"], + color=colors[1], + linewidth=1, + ) + ax.set_ylabel("Training Loss", color=colors[1]) + ax.set_yscale("log") + + ax2 = ax.twinx() + ax2.plot( + valid_data["epoch"], + valid_data["loss"]["mean"], + color=colors[0], + linewidth=1, + ) + ax2.set_ylabel("Validation Loss", color=colors[0]) + + if not linear: + ax.set_yscale("log") + ax2.set_yscale("log") + + if error_bars: + ax.fill_between( + train_data["epoch"], + train_data["loss"]["mean"] - train_data["loss"]["std"], + train_data["loss"]["mean"] + train_data["loss"]["std"], + alpha=0.3, + color=colors[1], + ) + ax.fill_between( + valid_data["epoch"], + valid_data["loss"]["mean"] - valid_data["loss"]["std"], + valid_data["loss"]["mean"] + valid_data["loss"]["std"], + alpha=0.3, + color=colors[0], + ) + + if start_swa is not None: + ax.axvline( + start_swa, + color="black", + linestyle="dashed", + linewidth=1, + alpha=0.6, + label="Stage Two Starts", + ) + + ax.set_xlabel("Epoch") + ax.set_ylabel("Loss") + ax.legend(loc="upper right", fontsize=4) + ax.grid(True, linestyle="--", alpha=0.5) + + # ---- Plot selected keys ---- + ax = axes[1] + twin_axes = [] + for i, key in enumerate(keys.split(",")): + color = colors[(i + 3)] + label = labels.get(key, key) + + if i == 0: + main_ax = ax + else: + main_ax = ax.twinx() + main_ax.spines.right.set_position(("outward", 40 * (i - 1))) + twin_axes.append(main_ax) + + main_ax.plot( + valid_data["epoch"], + valid_data[key]["mean"] * 1e3, + color=color, + label=label, + linewidth=1, + ) + + if error_bars: + main_ax.fill_between( + valid_data["epoch"], + (valid_data[key]["mean"] - valid_data[key]["std"]) * 1e3, + (valid_data[key]["mean"] + valid_data[key]["std"]) * 1e3, + alpha=0.3, + color=color, + ) + + main_ax.set_ylabel(label, color=color) + main_ax.tick_params(axis="y", colors=color) + + if start_swa is not None: + ax.axvline( + start_swa, + color="black", + linestyle="dashed", + linewidth=1, + alpha=0.6, + label="Stage Two Starts", + ) + + ax.set_xlabel("Epoch") + ax.set_xlim(left=min_epoch) + ax.grid(True, linestyle="--", alpha=0.5) + + fig.savefig( + f"{output_path}_{head}.{output_format}", dpi=300, bbox_inches="tight" + ) + plt.close(fig) + + +def get_paths(path: str) -> List[str]: + if os.path.isfile(path): + return [path] + paths = glob.glob(os.path.join(path, "*_train.txt")) + + if len(paths) == 0: + raise RuntimeError(f"Cannot find results in '{path}'") + + return paths + + +def main() -> None: + args = parse_args() + run(args) + + +def run(args: argparse.Namespace) -> None: + data = pd.DataFrame( + results + for path in get_paths(args.path) + for results in parse_training_results(path) + ) + + for name, group in data.groupby("name"): + plot( + group, + min_epoch=args.min_epoch, + output_path=name, + output_format=args.output_format, + linear=args.linear, + start_swa=args.start_swa, + error_bars=args.error_bars, + keys=args.keys, + heads=args.heads, + ) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/preprocess_data.py b/models/mace/mace/cli/preprocess_data.py new file mode 100644 index 0000000000000000000000000000000000000000..84dad49447513519cebaabbe1116266339ce314e --- /dev/null +++ b/models/mace/mace/cli/preprocess_data.py @@ -0,0 +1,300 @@ +# This file loads an xyz dataset and prepares +# new hdf5 file that is ready for training with on-the-fly dataloading + +import argparse +import ast +import json +import logging +import multiprocessing as mp +import os +import random +from functools import partial +from glob import glob +from typing import List, Tuple + +import h5py +import numpy as np +import tqdm + +from mace import data, tools +from mace.data import KeySpecification, update_keyspec_from_kwargs +from mace.data.utils import save_configurations_as_HDF5 +from mace.modules import compute_statistics +from mace.tools import torch_geometric +from mace.tools.scripts_utils import get_atomic_energies, get_dataset_from_xyz +from mace.tools.utils import AtomicNumberTable + + +def compute_stats_target( + file: str, + z_table: AtomicNumberTable, + r_max: float, + atomic_energies: Tuple, + batch_size: int, +): + train_dataset = data.HDF5Dataset(file, z_table=z_table, r_max=r_max) + train_loader = torch_geometric.dataloader.DataLoader( + dataset=train_dataset, + batch_size=batch_size, + shuffle=False, + drop_last=False, + ) + + avg_num_neighbors, mean, std = compute_statistics(train_loader, atomic_energies) + output = [avg_num_neighbors, mean, std] + return output + + +def pool_compute_stats(inputs: List): + path_to_files, z_table, r_max, atomic_energies, batch_size, num_process = inputs + + with mp.Pool(processes=num_process) as pool: + re = [ + pool.apply_async( + compute_stats_target, + args=( + file, + z_table, + r_max, + atomic_energies, + batch_size, + ), + ) + for file in glob(path_to_files + "/*") + ] + + pool.close() + pool.join() + + results = [r.get() for r in tqdm.tqdm(re)] + + if not results: + raise ValueError( + "No results were computed. Check if the input files exist and are readable." + ) + + # Separate avg_num_neighbors, mean, and std + avg_num_neighbors = np.mean([r[0] for r in results]) + means = np.array([r[1] for r in results]) + stds = np.array([r[2] for r in results]) + + # Compute averages + mean = np.mean(means, axis=0).item() + std = np.mean(stds, axis=0).item() + + return avg_num_neighbors, mean, std + + +def split_array(a: np.ndarray, max_size: int): + drop_last = False + if len(a) % 2 == 1: + a = np.append(a, a[-1]) + drop_last = True + factors = get_prime_factors(len(a)) + max_factor = 1 + for i in range(1, len(factors) + 1): + for j in range(0, len(factors) - i + 1): + if np.prod(factors[j : j + i]) <= max_size: + test = np.prod(factors[j : j + i]) + max_factor = max(test, max_factor) + return np.array_split(a, max_factor), drop_last + + +def get_prime_factors(n: int): + factors = [] + for i in range(2, n + 1): + while n % i == 0: + factors.append(i) + n = n / i + return factors + + +# Define Task for Multiprocessiing +def multi_train_hdf5(process, args, split_train, drop_last): + with h5py.File(args.h5_prefix + "train/train_" + str(process) + ".h5", "w") as f: + f.attrs["drop_last"] = drop_last + save_configurations_as_HDF5(split_train[process], process, f) + + +def multi_valid_hdf5(process, args, split_valid, drop_last): + with h5py.File(args.h5_prefix + "val/val_" + str(process) + ".h5", "w") as f: + f.attrs["drop_last"] = drop_last + save_configurations_as_HDF5(split_valid[process], process, f) + + +def multi_test_hdf5(process, name, args, split_test, drop_last): + with h5py.File( + args.h5_prefix + "test/" + name + "_" + str(process) + ".h5", "w" + ) as f: + f.attrs["drop_last"] = drop_last + save_configurations_as_HDF5(split_test[process], process, f) + + +def main() -> None: + """ + This script loads an xyz dataset and prepares + new hdf5 file that is ready for training with on-the-fly dataloading + """ + args = tools.build_preprocess_arg_parser().parse_args() + run(args) + + +def run(args: argparse.Namespace): + """ + This script loads an xyz dataset and prepares + new hdf5 file that is ready for training with on-the-fly dataloading + """ + + # currently support only command line property_key syntax + args.key_specification = KeySpecification() + update_keyspec_from_kwargs(args.key_specification, vars(args)) + + # Setup + tools.set_seeds(args.seed) + random.seed(args.seed) + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)-8s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + handlers=[logging.StreamHandler()], + ) + + try: + config_type_weights = ast.literal_eval(args.config_type_weights) + assert isinstance(config_type_weights, dict) + except Exception as e: # pylint: disable=W0703 + logging.warning( + f"Config type weights not specified correctly ({e}), using Default" + ) + config_type_weights = {"Default": 1.0} + + folders = ["train", "val", "test"] + for sub_dir in folders: + if not os.path.exists(args.h5_prefix + sub_dir): + os.makedirs(args.h5_prefix + sub_dir) + + # Data preparation + collections, atomic_energies_dict = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=args.train_file, + valid_path=args.valid_file, + valid_fraction=args.valid_fraction, + config_type_weights=config_type_weights, + test_path=args.test_file, + seed=args.seed, + key_specification=args.key_specification, + head_name="", + ) + + # Atomic number table + # yapf: disable + if args.atomic_numbers is None: + z_table = tools.get_atomic_number_table_from_zs( + z + for configs in (collections.train, collections.valid) + for config in configs + for z in config.atomic_numbers + ) + else: + logging.info("Using atomic numbers from command line argument") + zs_list = ast.literal_eval(args.atomic_numbers) + assert isinstance(zs_list, list) + z_table = tools.get_atomic_number_table_from_zs(zs_list) + + logging.info("Preparing training set") + if args.shuffle: + random.shuffle(collections.train) + + # split collections.train into batches and save them to hdf5 + split_train = np.array_split(collections.train,args.num_process) + drop_last = False + if len(collections.train) % 2 == 1: + drop_last = True + + multi_train_hdf5_ = partial(multi_train_hdf5, args=args, split_train=split_train, drop_last=drop_last) + processes = [] + for i in range(args.num_process): + p = mp.Process(target=multi_train_hdf5_, args=[i]) + p.start() + processes.append(p) + + for i in processes: + i.join() + + if args.compute_statistics: + logging.info("Computing statistics") + if atomic_energies_dict is None or len(atomic_energies_dict) == 0: + atomic_energies_dict = get_atomic_energies(args.E0s, collections.train, z_table) + + # Remove atomic energies if element not in z_table + removed_atomic_energies = {} + for z in list(atomic_energies_dict): + if z not in z_table.zs: + removed_atomic_energies[z] = atomic_energies_dict.pop(z) + if len(removed_atomic_energies) > 0: + logging.warning("Atomic energies for elements not present in the atomic number table have been removed.") + logging.warning(f"Removed atomic energies (eV): {str(removed_atomic_energies)}") + logging.warning("To include these elements in the model, specify all atomic numbers explicitly using the --atomic_numbers argument.") + + atomic_energies: np.ndarray = np.array( + [atomic_energies_dict[z] for z in z_table.zs] + ) + logging.info(f"Atomic Energies: {atomic_energies.tolist()}") + _inputs = [args.h5_prefix+'train', z_table, args.r_max, atomic_energies, args.batch_size, args.num_process] + avg_num_neighbors, mean, std=pool_compute_stats(_inputs) + logging.info(f"Average number of neighbors: {avg_num_neighbors}") + logging.info(f"Mean: {mean}") + logging.info(f"Standard deviation: {std}") + + # save the statistics as a json + statistics = { + "atomic_energies": str(atomic_energies_dict), + "avg_num_neighbors": avg_num_neighbors, + "mean": mean, + "std": std, + "atomic_numbers": str([int(z) for z in z_table.zs]), + "r_max": args.r_max, + } + + with open(args.h5_prefix + "statistics.json", "w") as f: # pylint: disable=W1514 + json.dump(statistics, f) + + logging.info("Preparing validation set") + if args.shuffle: + random.shuffle(collections.valid) + split_valid = np.array_split(collections.valid, args.num_process) + drop_last = False + if len(collections.valid) % 2 == 1: + drop_last = True + + multi_valid_hdf5_ = partial(multi_valid_hdf5, args=args, split_valid=split_valid, drop_last=drop_last) + processes = [] + for i in range(args.num_process): + p = mp.Process(target=multi_valid_hdf5_, args=[i]) + p.start() + processes.append(p) + + for i in processes: + i.join() + + if args.test_file is not None: + logging.info("Preparing test sets") + for name, subset in collections.tests: + drop_last = False + if len(subset) % 2 == 1: + drop_last = True + split_test = np.array_split(subset, args.num_process) + multi_test_hdf5_ = partial(multi_test_hdf5, args=args, split_test=split_test, drop_last=drop_last) + + processes = [] + for i in range(args.num_process): + p = mp.Process(target=multi_test_hdf5_, args=[i, name]) + p.start() + processes.append(p) + + for i in processes: + i.join() + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/run_train.py b/models/mace/mace/cli/run_train.py new file mode 100644 index 0000000000000000000000000000000000000000..4dc6a3575ea3e68e3c2ad63ecad1239a5200cd25 --- /dev/null +++ b/models/mace/mace/cli/run_train.py @@ -0,0 +1,1251 @@ +########################################################################################### +# Training script for MACE +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### +import warnings +warnings.filterwarnings( + "ignore", + message=r"You are using `torch\.load` with `weights_only=False`.*", + category=FutureWarning, +) + +warnings.filterwarnings( + "ignore", + message=r".*TorchScript type system doesn't support instance-level annotations.*", + category=UserWarning, + module=r"torch\.jit\._check", +) + +import ast +import glob +import json +import logging +import os +from copy import deepcopy +from pathlib import Path +from typing import List, Optional + +import torch.distributed +from e3nn.util import jit +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.optim import LBFGS +from torch.utils.data import ConcatDataset +from torch_ema import ExponentialMovingAverage + +import mace +from mace import data, tools +from mace.calculators.foundations_models import ( + mace_mp, + mace_mp_names, + mace_off, + mace_omol, +) +from mace.cli.convert_cueq_e3nn import run as run_cueq_to_e3nn +from mace.cli.convert_e3nn_cueq import run as run_e3nn_to_cueq +from mace.cli.convert_e3nn_oeq import run as run_e3nn_to_oeq +from mace.cli.convert_oeq_e3nn import run as run_oeq_to_e3nn +from mace.cli.visualise_train import TrainingPlotter +from mace.data import KeySpecification, update_keyspec_from_kwargs +from mace.tools import torch_geometric +from mace.tools.distributed_tools import init_distributed +from mace.tools.model_script_utils import configure_model +from mace.tools.multihead_tools import ( + HeadConfig, + apply_pseudolabels_to_pt_head_configs, + assemble_replay_data, + dict_head_to_dataclass, + prepare_default_head, + prepare_pt_head, +) +from mace.tools.run_train_utils import ( + combine_datasets, + load_dataset_for_path, + normalize_file_paths, +) +from mace.tools.scripts_utils import ( + LRScheduler, + SubsetCollection, + check_path_ase_read, + convert_to_json_format, + dict_to_array, + extract_config_mace_model, + get_atomic_energies, + get_avg_num_neighbors, + get_config_type_weights, + get_dataset_from_xyz, + get_files_with_suffix, + get_loss_fn, + get_optimizer, + get_params_options, + get_swa, + print_git_commit, + remove_pt_head, + setup_wandb, +) +from mace.tools.tables_utils import create_error_table +from mace.tools.utils import AtomicNumberTable + + +import math +import torch +import torch.nn as nn + +import torch +import torch.nn as nn + +import ast +import torch +from mace.tools.utils import AtomicNumberTable + +import ast + +FULL_ZS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, + 75, 76, 77, 78, 79, 80, 81, 82, 83, 89, 90, 91, 92, 93, 94] + +def fill_E0s_with_zeros(E0s_str: str, full_zs=FULL_ZS) -> str: + """ + E0s_str: string dict, e.g. "{1: 2.46, 6: 8.02}" + returns: string dict with all full_zs keys present, missing filled with 0.0 + """ + if isinstance(E0s_str, dict): + # if you ever accidentally pass dict, still handle it + E0s = {int(k): float(v) for k, v in E0s_str.items()} + else: + E0s = ast.literal_eval(E0s_str) + if not isinstance(E0s, dict): + raise TypeError(f"E0s must parse to dict, got {type(E0s)}") + E0s = {int(k): float(v) for k, v in E0s.items()} + + filled = {int(z): float(E0s.get(int(z), 0.0)) for z in full_zs} + + # return as a string because MACE CLI expects args.E0s to be a string + return "{" + ", ".join(f"{z}: {filled[z]}" for z in full_zs) + "}" + + + + + +def diff_report(model, before_state, tol=0.0): + total = 0 + changed = 0 + worst = ("", 0.0) + for name, p in model.named_parameters(): + if not p.requires_grad: + continue + total += 1 + a = before_state[name] + b = p.detach() + d = (b - a).abs().max().item() + if d > tol: + changed += 1 + if d > worst[1]: + worst = (name, d) + print(f"Changed params: {changed}/{total} (worst: {worst[0]} maxΔ={worst[1]})") + +@torch.no_grad() +def reset_all_trainable_params_(model, seed=123, std=0.02, + reset_atomic_energies=True, + reset_scaleshift=False): + for name, p in model.named_parameters(): + if not p.requires_grad: + continue + g = torch.Generator(device=p.device).manual_seed(seed) + p.normal_(mean=0.0, std=std, generator=g) + + if reset_atomic_energies and hasattr(model, "atomic_energies_fn"): + ae = model.atomic_energies_fn + if hasattr(ae, "energies") and isinstance(ae.energies, torch.Tensor): + ae.energies.zero_() + + if reset_scaleshift and hasattr(model, "scale_shift"): + ss = model.scale_shift + if hasattr(ss, "scale"): ss.scale.fill_(1.0) + if hasattr(ss, "shift"): ss.shift.zero_() + + + +def main() -> None: + """ + This script runs the training/fine tuning for mace + """ + args = tools.build_default_arg_parser().parse_args() + run(args) + + +def run(args) -> None: + """ + This script runs the training/fine tuning for mace + """ + tag = tools.get_tag(name=args.name, seed=args.seed) + args, input_log_messages = tools.check_args(args) + + # default keyspec to update using heads dictionary + args.key_specification = KeySpecification() + update_keyspec_from_kwargs(args.key_specification, vars(args)) + + if args.device == "xpu": + try: + import intel_extension_for_pytorch as ipex + import oneccl_bindings_for_pytorch as oneccl # pylint: disable=unused-import + except ImportError as e: + raise ImportError( + "Error: Intel extension for PyTorch not found, but XPU device was specified" + ) from e + rank, local_rank, world_size = init_distributed(args) + + # Setup + tools.set_seeds(args.seed) + tools.setup_logger(level=args.log_level, tag=tag, directory=args.log_dir, rank=rank) + logging.info("===========VERIFYING SETTINGS===========") + for message, loglevel in input_log_messages: + logging.log(level=loglevel, msg=message) + + if args.distributed: + if args.device == "cuda": + torch.cuda.set_device(local_rank) + elif args.device == "xpu": + torch.xpu.set_device(local_rank) + logging.info(f"Process group initialized: {torch.distributed.is_initialized()}") + logging.info(f"Processes: {world_size}") + + try: + logging.info(f"MACE version: {mace.__version__}") + except AttributeError: + logging.info("Cannot find MACE version, please install MACE via pip") + logging.debug(f"Configuration: {args}") + + tools.set_default_dtype(args.default_dtype) + device = tools.init_device(args.device) + + + commit = print_git_commit() + model_foundation: Optional[torch.nn.Module] = None + foundation_model_avg_num_neighbors = 0 + # Filter out None from mace_mp_names to get valid model names + valid_mace_mp_models = [name for name in mace_mp_names if name is not None] + args.foundation_model_kwargs = ast.literal_eval(args.foundation_model_kwargs) + args.foundation_model_kwargs["head"] = args.foundation_head + + + if args.foundation_model is not None: + if args.foundation_model in valid_mace_mp_models: + logging.info( + f"Using foundation model mace {args.foundation_model} as initial checkpoint." + ) + calc = mace_mp( + model=args.foundation_model, + device=args.device, + default_dtype=args.default_dtype, + **args.foundation_model_kwargs, + ) + model_foundation = calc.models[0] + + elif args.foundation_model in ["small_off", "medium_off", "large_off"]: + model_type = args.foundation_model.split("_")[0] + logging.info( + f"Using foundation model mace-off-2023 {model_type} as initial checkpoint. ASL license." + ) + calc = mace_off( + model=model_type, + device=args.device, + default_dtype=args.default_dtype, + ) + model_foundation = calc.models[0] + elif args.foundation_model in ["mace_omol"]: + logging.info("Using foundation model mace-omol as initial checkpoint.") + calc = mace_omol( + device=args.device, + default_dtype=args.default_dtype, + ) + model_foundation = calc.models[0] + else: + model_foundation = torch.load( + args.foundation_model, map_location=args.device) + + logging.info( + f"Using foundation model {args.foundation_model} as initial checkpoint." + ) + args.r_max = model_foundation.r_max.item() + foundation_model_avg_num_neighbors = model_foundation.interactions[ + 0 + ].avg_num_neighbors + + if ( + args.foundation_model not in ["small", "medium", "large"] + and args.pt_train_file is None + ): + if args.multiheads_finetuning: + logging.warning( + "Using multiheads finetuning with a foundation model that is not a Materials Project model, need to provied a path to a pretraining file with --pt_train_file." + ) + args.multiheads_finetuning = False + if args.multiheads_finetuning: + assert ( + args.E0s != "average" + ), "average atomic energies cannot be used for multiheads finetuning" + # check that the foundation model has a single head, if not, use the first head + if not args.force_mh_ft_lr: + logging.info( + "Multihead finetuning mode, setting learning rate to 0.0001 and EMA to True. To use a different learning rate, set --force_mh_ft_lr=True." + ) + args.lr = 0.0001 + args.ema = True + args.ema_decay = 0.99999 + logging.info( + "Using multiheads finetuning mode, setting learning rate to 0.0001 and EMA to True" + ) + if hasattr(model_foundation, "heads"): + if len(model_foundation.heads) > 1: + logging.warning( + f"Mutlihead finetuning with models with more than one head is not supported, using the head {args.foundation_head} as foundation head." + ) + model_foundation = remove_pt_head( + model_foundation, args.foundation_head + ) + else: + args.multiheads_finetuning = False + + + + #print(model_foundation) + #print(args.foundation_head) + #print(foundation_model_avg_num_neighbors) + #print(model_foundation.r_max.item()) + + #------------------FOUNDATION MODEL LOGIC---------------------------------------- + #model = torch.load("") + #n_params = tools.count_parameters(model) + #logging.info( + #f"Total number of parameters (FOUNDATION MODEL): {n_params} ({n_params / 1_000_000:.3f}M)" + #) + #zs = [int(z) for z in model.atomic_numbers] + #z_table = AtomicNumberTable(zs) + #args.atomic_numbers = str(zs) + #args.E0s = fill_E0s_with_zeros(args.E0s) + #reset_all_trainable_params_(model, seed=123, reset_atomic_energies=True, reset_scaleshift=False) + #------------------FOUNDATION MODEL LOGIC---------------------------------------- + + + + if args.heads is not None: + args.heads = ast.literal_eval(args.heads) + for _, head_dict in args.heads.items(): + # priority is global args < head property_key values < head info_keys+arrays_keys + head_keyspec = deepcopy(args.key_specification) + update_keyspec_from_kwargs(head_keyspec, head_dict) + head_keyspec.update( + info_keys=head_dict.get("info_keys", {}), + arrays_keys=head_dict.get("arrays_keys", {}), + ) + head_dict["key_specification"] = head_keyspec + else: + args.heads = prepare_default_head(args) + if args.multiheads_finetuning: + pt_keyspec = ( + args.heads["pt_head"]["key_specification"] + if "pt_head" in args.heads + else deepcopy(args.key_specification) + ) + args.heads["pt_head"] = prepare_pt_head( + args, pt_keyspec, foundation_model_avg_num_neighbors + ) + + logging.info("===========LOADING INPUT DATA===========") + heads = list(args.heads.keys()) + logging.info(f"Using heads: {heads}") + logging.info("Using the key specifications to parse data:") + for name, head_dict in args.heads.items(): + head_keyspec = head_dict["key_specification"] + logging.info(f"{name}: {head_keyspec}") + + head_configs: List[HeadConfig] = [] + for head, head_args in args.heads.items(): + logging.info(f"============= Processing head {head} ===========") + head_config = dict_head_to_dataclass(head_args, head, args) + # don't apply user's --atomic_numbers to pt_head, that info needs to come + # from the actual pt data + if args.multiheads_finetuning and head_config.head_name == "pt_head": + head_config.atomic_numbers = None + + # Handle train_file and valid_file - normalize to lists + if hasattr(head_config, "train_file") and head_config.train_file is not None: + head_config.train_file = normalize_file_paths(head_config.train_file) + if hasattr(head_config, "valid_file") and head_config.valid_file is not None: + head_config.valid_file = normalize_file_paths(head_config.valid_file) + if hasattr(head_config, "test_file") and head_config.test_file is not None: + head_config.test_file = normalize_file_paths(head_config.test_file) + + if ( + head_config.statistics_file is not None + and head_config.head_name != "pt_head" + ): + with open(head_config.statistics_file, "r") as f: # pylint: disable=W1514 + statistics = json.load(f) + logging.info("Using statistics json file") + head_config.atomic_numbers = statistics["atomic_numbers"] + head_config.mean = statistics["mean"] + head_config.std = statistics["std"] + head_config.avg_num_neighbors = statistics["avg_num_neighbors"] + head_config.compute_avg_num_neighbors = False + if isinstance(statistics["atomic_energies"], str) and statistics[ + "atomic_energies" + ].endswith(".json"): + with open(statistics["atomic_energies"], "r", encoding="utf-8") as f: + atomic_energies = json.load(f) + head_config.E0s = atomic_energies + head_config.atomic_energies_dict = ast.literal_eval(atomic_energies) + else: + head_config.E0s = statistics["atomic_energies"] + head_config.atomic_energies_dict = ast.literal_eval( + statistics["atomic_energies"] + ) + if head_config.train_file in (["mp"], ["matpes_pbe"], ["matpes_r2scan"]): + assert ( + head_config.head_name == "pt_head" + ), "Only pt_head should use mp as train_file" + logging.info( + f"Using filtered Materials Project data for replay ({args.num_samples_pt}, {args.filter_type_pt}, {args.subselect_pt}). " + "You can also construct a different subset using `fine_tuning_select.py` script." + ) + collections = assemble_replay_data( + head_config.train_file[0], args, head_config, tag + ) + head_config.collections = collections + elif any(check_path_ase_read(f) for f in head_config.train_file): + train_files_ase_list = [ + f for f in head_config.train_file if check_path_ase_read(f) + ] + valid_files_ase_list = None + test_files_ase_list = None + if head_config.valid_file: + valid_files_ase_list = [ + f for f in head_config.valid_file if check_path_ase_read(f) + ] + if head_config.test_file: + test_files_ase_list = [ + f for f in head_config.test_file if check_path_ase_read(f) + ] + config_type_weights = get_config_type_weights( + head_config.config_type_weights + ) + collections, atomic_energies_dict = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=train_files_ase_list, + valid_path=valid_files_ase_list, + valid_fraction=head_config.valid_fraction, + config_type_weights=config_type_weights, + test_path=test_files_ase_list, + seed=args.seed, + key_specification=head_config.key_specification, + head_name=head_config.head_name, + keep_isolated_atoms=head_config.keep_isolated_atoms, + no_data_ok=( + args.pseudolabel_replay + and args.multiheads_finetuning + and head_config.head_name == "pt_head" + ), + prefix=args.name, + ) + head_config.collections = SubsetCollection( + train=collections.train, + valid=collections.valid, + tests=collections.tests, + ) + head_config.atomic_energies_dict = atomic_energies_dict + logging.info( + f"Total number of configurations: train={len(collections.train)}, valid={len(collections.valid)}, " + f"tests=[{', '.join([name + ': ' + str(len(test_configs)) for name, test_configs in collections.tests])}]," + ) + head_configs.append(head_config) + + if all( + check_path_ase_read(head_config.train_file[0]) for head_config in head_configs + ): + size_collections_train = sum( + len(head_config.collections.train) for head_config in head_configs + ) + size_collections_valid = sum( + len(head_config.collections.valid) for head_config in head_configs + ) + if size_collections_train < args.batch_size: + logging.error( + f"Batch size ({args.batch_size}) is larger than the number of training data ({size_collections_train})" + ) + if size_collections_valid < args.valid_batch_size: + logging.warning( + f"Validation batch size ({args.valid_batch_size}) is larger than the number of validation data ({size_collections_valid})" + ) + + if args.multiheads_finetuning: + logging.info( + "==================Using multiheads finetuning mode==================" + ) + args.loss = "universal" + + all_ase_readable = all( + all(check_path_ase_read(f) for f in head_config.train_file) + for head_config in head_configs + ) + head_config_pt = filter(lambda x: x.head_name == "pt_head", head_configs) + head_config_pt = next(head_config_pt, None) + assert head_config_pt is not None, "Pretraining head not found" + if all_ase_readable: + ratio_pt_ft = ( + size_collections_train - len(head_config_pt.collections.train) + ) / len(head_config_pt.collections.train) + if ratio_pt_ft < args.real_pt_data_ratio_threshold: + logging.warning( + f"Ratio of the number of configurations in the training set and the in the pt_train_file is {ratio_pt_ft}, " + f"increasing the number of configurations in the fine-tuning heads by {int(args.real_pt_data_ratio_threshold / ratio_pt_ft)}" + ) + for head_config in head_configs: + if head_config.head_name == "pt_head": + continue + head_config.collections.train += ( + head_config.collections.train + * int(args.real_pt_data_ratio_threshold / ratio_pt_ft) + ) + logging.info( + f"Total number of configurations in pretraining: train={len(head_config_pt.collections.train)}, valid={len(head_config_pt.collections.valid)}" + ) + else: + logging.debug( + "Using LMDB/HDF5 datasets for pretraining or fine-tuning - skipping ratio check" + ) + + # Atomic number table + # yapf: disable + for head_config in head_configs: + if head_config.atomic_numbers is None: + assert all(check_path_ase_read(f) for f in head_config.train_file), "Must specify atomic_numbers when using .h5 or .aselmdb train_file input" + z_table_head = tools.get_atomic_number_table_from_zs( + z + for configs in (head_config.collections.train, head_config.collections.valid) + for config in configs + for z in config.atomic_numbers + ) + head_config.atomic_numbers = z_table_head.zs + head_config.z_table = z_table_head + else: + if head_config.statistics_file is None: + logging.info("Using atomic numbers from command line argument") + else: + logging.info("Using atomic numbers from statistics file") + zs_list = ast.literal_eval(head_config.atomic_numbers) + assert isinstance(zs_list, list) + z_table_head = tools.AtomicNumberTable(zs_list) + head_config.atomic_numbers = zs_list + head_config.z_table = z_table_head + # yapf: enable + all_atomic_numbers = set() + for head_config in head_configs: + all_atomic_numbers.update(head_config.atomic_numbers) + z_table = AtomicNumberTable(sorted(list(all_atomic_numbers))) + if args.foundation_model_elements and model_foundation: + z_table = AtomicNumberTable(sorted(model_foundation.atomic_numbers.tolist())) + logging.info(f"Atomic Numbers used: {z_table.zs}") + + # Atomic energies + atomic_energies_dict = {} + for head_config in head_configs: + if head_config.atomic_energies_dict is None or len(head_config.atomic_energies_dict) == 0: + assert head_config.E0s is not None, "Atomic energies must be provided" + if all(check_path_ase_read(f) for f in head_config.train_file) and head_config.E0s.lower() != "foundation": + atomic_energies_dict[head_config.head_name] = get_atomic_energies( + head_config.E0s, head_config.collections.train, head_config.z_table + ) + elif head_config.E0s.lower() == "foundation": + assert args.foundation_model is not None + z_table_foundation = AtomicNumberTable( + [int(z) for z in model_foundation.atomic_numbers] + ) + foundation_atomic_energies = model_foundation.atomic_energies_fn.atomic_energies + if foundation_atomic_energies.ndim > 1: + foundation_atomic_energies = foundation_atomic_energies.squeeze() + if foundation_atomic_energies.ndim == 2: + foundation_atomic_energies = foundation_atomic_energies[0] + logging.info("Foundation model has multiple heads, using the first head as foundation E0s.") + atomic_energies_dict[head_config.head_name] = { + z: foundation_atomic_energies[ + z_table_foundation.z_to_index(z) + ].item() + for z in z_table.zs + } + else: + atomic_energies_dict[head_config.head_name] = get_atomic_energies(head_config.E0s, None, head_config.z_table) + else: + atomic_energies_dict[head_config.head_name] = head_config.atomic_energies_dict + + # Atomic energies for multiheads finetuning + if args.multiheads_finetuning: + assert ( + model_foundation is not None + ), "Model foundation must be provided for multiheads finetuning" + z_table_foundation = AtomicNumberTable( + [int(z) for z in model_foundation.atomic_numbers] + ) + foundation_atomic_energies = model_foundation.atomic_energies_fn.atomic_energies + if foundation_atomic_energies.ndim > 1: + foundation_atomic_energies = foundation_atomic_energies.squeeze() + if foundation_atomic_energies.ndim == 2: + foundation_atomic_energies = foundation_atomic_energies[0] + logging.info("Foundation model has multiple heads, using the first head as foundation E0s.") + atomic_energies_dict["pt_head"] = { + z: foundation_atomic_energies[ + z_table_foundation.z_to_index(z) + ].item() + for z in z_table.zs + } + heads = sorted(heads, key=lambda x: -1000 if x == "pt_head" else 0) + # Padding atomic energies if keeping all elements of the foundation model + if args.foundation_model_elements and model_foundation: + atomic_energies_dict_padded = {} + for head_name, head_energies in atomic_energies_dict.items(): + energy_head_padded = {} + for z in z_table.zs: + energy_head_padded[z] = head_energies.get(z, 0.0) + atomic_energies_dict_padded[head_name] = energy_head_padded + atomic_energies_dict = atomic_energies_dict_padded + + if args.model == "AtomicDipolesMACE": + atomic_energies = None + dipole_only = True + args.compute_dipole = True + args.compute_energy = False + args.compute_forces = False + args.compute_virials = False + args.compute_stress = False + args.compute_polarizability = False + elif args.model == "AtomicDielectricMACE": + atomic_energies = None + dipole_only = False + args.compute_dipole = True + args.compute_energy = False + args.compute_forces = False + args.compute_virials = False + args.compute_stress = False + args.compute_polarizability = True + else: + dipole_only = False + if args.model == "EnergyDipolesMACE": + args.compute_dipole = True + args.compute_energy = True + args.compute_forces = True + args.compute_virials = False + args.compute_stress = False + args.compute_polarizability = False + else: + args.compute_energy = True + args.compute_dipole = False + args.compute_polarizability = False + # atomic_energies: np.ndarray = np.array( + # [atomic_energies_dict[z] for z in z_table.zs] + # ) + atomic_energies = dict_to_array(atomic_energies_dict, heads) + for head_config in head_configs: + try: + logging.info(f"Atomic Energies used (z: eV) for head {head_config.head_name}: " + "{" + ", ".join([f"{z}: {atomic_energies_dict[head_config.head_name][z]}" for z in head_config.z_table.zs]) + "}") + except KeyError as e: + raise KeyError(f"Atomic number {e} not found in atomic_energies_dict for head {head_config.head_name}, add E0s for this atomic number") from e + + # Load datasets for each head, supporting multiple files per head + valid_sets = {head: [] for head in heads} + train_sets = {head: [] for head in heads} + + for head_config in head_configs: + train_datasets = [] + + logging.info(f"Processing datasets for head '{head_config.head_name}'") + + # Apply pseudolabels if this is the pt_head and pseudolabeling is enabled + if args.pseudolabel_replay and args.multiheads_finetuning and head_config.head_name == "pt_head": + logging.info("============= Pseudolabeling for pt_head ===========") + if apply_pseudolabels_to_pt_head_configs( + foundation_model=model_foundation, + pt_head_config=head_config, + r_max=args.r_max, + device=device, + batch_size=args.batch_size + ): + logging.info("Successfully applied pseudolabels to pt_head configurations") + else: + logging.warning("Pseudolabeling was not successful, continuing with original configurations") + + ase_files = [f for f in head_config.train_file if check_path_ase_read(f)] + non_ase_files = [f for f in head_config.train_file if not check_path_ase_read(f)] + + if ase_files: + dataset = load_dataset_for_path( + file_path=ase_files, + r_max=args.r_max, + z_table=z_table, + head_config=head_config, + heads=heads, + collection=head_config.collections.train, + ) + train_datasets.append(dataset) + logging.debug(f"Successfully loaded dataset from ASE files: {ase_files}") + + for file in non_ase_files: + dataset = load_dataset_for_path( + file_path=file, + r_max=args.r_max, + z_table=z_table, + head_config=head_config, + heads=heads, + ) + train_datasets.append(dataset) + logging.debug(f"Successfully loaded dataset from non-ASE file: {file}") + + if not train_datasets: + raise ValueError(f"No valid training datasets found for head {head_config.head_name}") + + train_sets[head_config.head_name] = combine_datasets(train_datasets, head_config.head_name) + + if head_config.valid_file: + valid_datasets = [] + + valid_ase_files = [f for f in head_config.valid_file if check_path_ase_read(f)] + valid_non_ase_files = [f for f in head_config.valid_file if not check_path_ase_read(f)] + + if valid_ase_files: + valid_dataset = load_dataset_for_path( + file_path=valid_ase_files, + r_max=args.r_max, + z_table=z_table, + head_config=head_config, + heads=heads, + collection=head_config.collections.valid, + ) + valid_datasets.append(valid_dataset) + logging.debug(f"Successfully loaded validation dataset from ASE files: {valid_ase_files}") + for valid_file in valid_non_ase_files: + valid_dataset = load_dataset_for_path( + file_path=valid_file, + r_max=args.r_max, + z_table=z_table, + head_config=head_config, + heads=heads, + ) + valid_datasets.append(valid_dataset) + logging.debug(f"Successfully loaded validation dataset from {valid_file}") + + # Combine validation datasets + if valid_datasets: + valid_sets[head_config.head_name] = combine_datasets(valid_datasets, f"{head_config.head_name}_valid") + logging.info(f"Combined validation datasets for {head_config.head_name}") + + # If no valid file is provided but collection exist, use the validation set from the collection + if head_config.valid_file is None and head_config.collections.valid: + valid_sets[head_config.head_name] = [ + data.AtomicData.from_config( + config, z_table=z_table, cutoff=args.r_max, heads=heads + ) + for config in head_config.collections.valid + ] + if not valid_sets[head_config.head_name]: + raise ValueError(f"No valid datasets found for head {head_config.head_name}, please provide a valid_file or a valid_fraction") + + # Create data loader for this head + if isinstance(train_sets[head_config.head_name], list): + dataset_size = len(train_sets[head_config.head_name]) + else: + dataset_size = len(train_sets[head_config.head_name]) + logging.info(f"Head '{head_config.head_name}' training dataset size: {dataset_size}") + + train_loader_head = torch_geometric.dataloader.DataLoader( + dataset=train_sets[head_config.head_name], + batch_size=args.batch_size, + shuffle=True, + drop_last=(not args.lbfgs), + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + head_config.train_loader = train_loader_head + + # concatenate all the trainsets + train_set = ConcatDataset([train_sets[head] for head in heads]) + train_sampler, valid_sampler = None, None + if args.distributed: + train_sampler = torch.utils.data.distributed.DistributedSampler( + train_set, + num_replicas=world_size, + rank=rank, + shuffle=True, + drop_last=(not args.lbfgs), + seed=args.seed, + ) + valid_samplers = {} + for head, valid_set in valid_sets.items(): + valid_sampler = torch.utils.data.distributed.DistributedSampler( + valid_set, + num_replicas=world_size, + rank=rank, + shuffle=True, + drop_last=True, + seed=args.seed, + ) + valid_samplers[head] = valid_sampler + + train_loader = torch_geometric.dataloader.DataLoader( + dataset=train_set, + batch_size=args.batch_size, + sampler=train_sampler, + shuffle=(train_sampler is None), + drop_last=(train_sampler is None and not args.lbfgs), + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + + valid_loaders = {heads[i]: None for i in range(len(heads))} + if not isinstance(valid_sets, dict): + valid_sets = {"Default": valid_sets} + for head, valid_set in valid_sets.items(): + valid_loaders[head] = torch_geometric.dataloader.DataLoader( + dataset=valid_set, + batch_size=args.valid_batch_size, + sampler=valid_samplers[head] if args.distributed else None, + shuffle=False, + drop_last=False, + pin_memory=args.pin_memory, + num_workers=args.num_workers, + generator=torch.Generator().manual_seed(args.seed), + ) + + loss_fn = get_loss_fn(args, dipole_only, args.compute_dipole) + args.avg_num_neighbors = get_avg_num_neighbors(head_configs, args, train_loader, device) + + atomic_numbers_list_int = [int(z) for z in ast.literal_eval(args.atomic_numbers)] + # Model + + + + # For foundation logic + if len(atomic_numbers_list_int) > 5: # NOTE atomic_numbers is a string, we fix up the code later + print("using foundation models, Model not needed") + _, output_args = configure_model(args, train_loader, atomic_energies, model_foundation, heads, z_table, head_configs) + + else: + print("Using normal model (no finetuning)") + model, output_args = configure_model(args, train_loader, atomic_energies, model_foundation, heads, z_table, head_configs) + + + + model.to(device) + model.float() + + + #print(z_table) + #print(atomic_energies) + #print(output_args) + #print(args.avg_num_neighbors) + #print(model.interactions[0].avg_num_neighbors) + + print(model) + + + # logging.debug(model_foundation) + # n_params = tools.count_parameters(model_foundation) + # logging.info( + # f"Total number of parameters(model_foundation): {n_params} ({n_params / 1_000_000:.3f}M)" + # ) + + logging.debug(model) + n_params = tools.count_parameters(model) + logging.info( + f"Total number of parameters: {n_params} ({n_params / 1_000_000:.3f}M)" + ) + + + + logging.info("===========OPTIMIZER INFORMATION===========") + logging.info(f"Using {args.optimizer.upper()} as parameter optimizer") + logging.info(f"Batch size: {args.batch_size}") + if args.ema: + logging.info(f"Using Exponential Moving Average with decay: {args.ema_decay}") + logging.info( + f"Number of gradient updates: {int(args.max_num_epochs*len(train_set)/args.batch_size)}" + ) + logging.info(f"Learning rate: {args.lr}, weight decay: {args.weight_decay}") + logging.info(f'{loss_fn} with weights (Force & Energy) {args.forces_weight} & {args.energy_weight}') + + + + # Cueq and OEQ conversion + if args.enable_cueq and args.enable_oeq: + logging.warning( + "Both CUEQ and OEQ are enabled, using CUEQ for training. " + "To use OEQ, disable CUEQ with --disable_cueq." + ) + args.enable_oeq = False + if args.enable_cueq and not args.only_cueq: + logging.info("Converting model to CUEQ for accelerated training") + assert model.__class__.__name__ in ["MACE", "ScaleShiftMACE", "MACELES"] + model = run_e3nn_to_cueq(deepcopy(model), device=device) + if args.enable_oeq: + logging.info("Converting model to OEQ for accelerated training") + assert model.__class__.__name__ in ["MACE", "ScaleShiftMACE", "MACELES"] + model = run_e3nn_to_oeq(deepcopy(model), device=device) + + # Optimizer + param_options = get_params_options(args, model) + optimizer: torch.optim.Optimizer + optimizer = get_optimizer(args, param_options) + if args.device == "xpu": + logging.info("Optimzing model and optimzier for XPU") + model, optimizer = ipex.optimize(model, optimizer=optimizer) + logger = tools.MetricsLogger( + directory=args.results_dir, tag=tag + "_train" + ) # pylint: disable=E1123 + + lr_scheduler = LRScheduler(optimizer, args) + + swa: Optional[tools.SWAContainer] = None + swas = [False] + if args.swa: + swa, swas = get_swa(args, model, optimizer, swas, dipole_only) + + checkpoint_handler = tools.CheckpointHandler( + directory=args.checkpoints_dir, + tag=tag, + keep=args.keep_checkpoints, + swa_start=args.start_swa, + ) + + start_epoch = 0 + restart_lbfgs = False + opt_start_epoch = None + if args.restart_latest: + try: + opt_start_epoch = checkpoint_handler.load_latest( + state=tools.CheckpointState(model, optimizer, lr_scheduler), + swa=True, + device=device, + ) + except Exception: # pylint: disable=W0703 + try: + opt_start_epoch = checkpoint_handler.load_latest( + state=tools.CheckpointState(model, optimizer, lr_scheduler), + swa=False, + device=device, + ) + except Exception: # pylint: disable=W0703 + restart_lbfgs = True + if opt_start_epoch is not None: + start_epoch = opt_start_epoch + + ema: Optional[ExponentialMovingAverage] = None + if args.ema: + ema = ExponentialMovingAverage(model.parameters(), decay=args.ema_decay) + else: + for group in optimizer.param_groups: + group["lr"] = args.lr + + if args.lbfgs: + logging.info("Switching optimizer to LBFGS") + optimizer = LBFGS(model.parameters(), + history_size=200, + max_iter=20, + line_search_fn="strong_wolfe") + if restart_lbfgs: + opt_start_epoch = checkpoint_handler.load_latest( + state=tools.CheckpointState(model, optimizer, lr_scheduler), + swa=False, + device=device, + ) + if opt_start_epoch is not None: + start_epoch = opt_start_epoch + + if args.wandb: + setup_wandb(args) + if args.distributed: + distributed_model = DDP(model, device_ids=[local_rank], find_unused_parameters=True,) + else: + distributed_model = None + + + train_valid_data_loader = {} + for head_config in head_configs: + data_loader_name = "train_" + head_config.head_name + train_valid_data_loader[data_loader_name] = head_config.train_loader + for head, valid_loader in valid_loaders.items(): + data_load_name = "valid_" + head + train_valid_data_loader[data_load_name] = valid_loader + + if args.plot and args.plot_frequency > 0: + try: + plotter = TrainingPlotter( + results_dir=logger.path, + heads=heads, + table_type=args.error_table, + train_valid_data=train_valid_data_loader, + test_data={}, + output_args=output_args, + device=device, + plot_frequency=args.plot_frequency, + distributed=args.distributed, + swa_start=swa.start if swa else None, + plot_interaction_e=args.plot_interaction_e + ) + except Exception as e: # pylint: disable=W0718 + logging.debug(f"Creating Plotter failed: {e}") + else: + plotter = None + + if args.dry_run: + logging.info("DRY RUN mode enabled. Stopping now.") + return + + if args.device == "xpu": + try: + model, optimizer = ipex.optimize(model, optimizer=optimizer) + except ImportError as e: + logging.error( + "Intel Extension for PyTorch not found, but XPU device was specified. " + "Please install it to use XPU device." + ) + + tools.train( + model=model, + loss_fn=loss_fn, + train_loader=train_loader, + valid_loaders=valid_loaders, + optimizer=optimizer, + lr_scheduler=lr_scheduler, + checkpoint_handler=checkpoint_handler, + eval_interval=args.eval_interval, + start_epoch=start_epoch, + max_num_epochs=args.max_num_epochs, + logger=logger, + patience=args.patience, + save_all_checkpoints=args.save_all_checkpoints, + output_args=output_args, + device=device, + swa=swa, + ema=ema, + max_grad_norm=args.clip_grad, + log_errors=args.error_table, + log_wandb=args.wandb, + distributed=args.distributed, + distributed_model=distributed_model, + plotter=plotter, + train_sampler=train_sampler, + rank=rank, + ) + + logging.info("") + logging.info("===========RESULTS===========") + + + train_valid_data_loader = {} + for head_config in head_configs: + data_loader_name = "train_" + head_config.head_name + train_valid_data_loader[data_loader_name] = head_config.train_loader + for head, valid_loader in valid_loaders.items(): + data_load_name = "valid_" + head + train_valid_data_loader[data_load_name] = valid_loader + test_sets = {} + stop_first_test = False + test_data_loader = {} + if all( + head_config.test_file == head_configs[0].test_file + for head_config in head_configs + ) and head_configs[0].test_file is not None: + stop_first_test = True + if all( + head_config.test_dir == head_configs[0].test_dir + for head_config in head_configs + ) and head_configs[0].test_dir is not None: + stop_first_test = True + for head_config in head_configs: + if all(check_path_ase_read(f) for f in head_config.train_file): + for name, subset in head_config.collections.tests: + test_sets[name] = [ + data.AtomicData.from_config( + config, z_table=z_table, cutoff=args.r_max, heads=heads + ) + for config in subset + ] + if head_config.test_dir is not None: + if not args.multi_processed_test: + test_files = get_files_with_suffix(head_config.test_dir, "_test.h5") + for test_file in test_files: + name = os.path.splitext(os.path.basename(test_file))[0] + test_sets[name] = data.HDF5Dataset( + test_file, r_max=args.r_max, z_table=z_table, heads=heads, head=head_config.head_name + ) + else: + test_folders = glob(head_config.test_dir + "/*") + for folder in test_folders: + name = os.path.splitext(os.path.basename(test_file))[0] + test_sets[name] = data.dataset_from_sharded_hdf5( + folder, r_max=args.r_max, z_table=z_table, heads=heads, head=head_config.head_name + ) + for test_name, test_set in test_sets.items(): + test_sampler = None + if args.distributed: + test_sampler = torch.utils.data.distributed.DistributedSampler( + test_set, + num_replicas=world_size, + rank=rank, + shuffle=True, + drop_last=True, + seed=args.seed, + ) + try: + drop_last = test_set.drop_last + except AttributeError as e: # pylint: disable=W0612 + drop_last = False + test_loader = torch_geometric.dataloader.DataLoader( + test_set, + batch_size=args.valid_batch_size, + shuffle=(test_sampler is None), + drop_last=drop_last, + num_workers=args.num_workers, + pin_memory=args.pin_memory, + ) + test_data_loader[test_name] = test_loader + if stop_first_test: + break + + for swa_eval in swas: + epoch = checkpoint_handler.load_latest( + state=tools.CheckpointState(model, optimizer, lr_scheduler), + swa=swa_eval, + device=device, + ) + model.to(device) + if args.distributed: + # re-enable gradients for distributed model for evaluation of stage-two model + # after param.requires_grad = False was called before evaluating stage-one model + for param in model.parameters(): + param.requires_grad = True + distributed_model = DDP(model, device_ids=[local_rank], find_unused_parameters=True) + model_to_evaluate = model if not args.distributed else distributed_model + if swa_eval: + logging.info(f"Loaded Stage two model from epoch {epoch} for evaluation") + else: + logging.info(f"Loaded Stage one model from epoch {epoch} for evaluation") + + if rank == 0: + # Save entire model + if swa_eval: + model_path = Path(args.checkpoints_dir) / (tag + "_stagetwo.model") + else: + model_path = Path(args.checkpoints_dir) / (tag + ".model") + logging.info(f"Saving model to {model_path}") + model_to_save = deepcopy(model) + if args.enable_cueq and not args.only_cueq: + logging.info("RUNING CUEQ TO E3NN") + model_to_save = run_cueq_to_e3nn(deepcopy(model), device=device) + if args.enable_oeq: + logging.info("RUNING OEQ TO E3NN") + model_to_save = run_oeq_to_e3nn(deepcopy(model), device=device) + if args.save_cpu: + model_to_save = model_to_save.to("cpu") + torch.save(model_to_save, model_path) + extra_files = { + "commit.txt": commit.encode("utf-8") if commit is not None else b"", + "config.yaml": json.dumps( + convert_to_json_format(extract_config_mace_model(model)) + ), + } + os.makedirs(args.model_dir, exist_ok=True) + if swa_eval: + torch.save( + model_to_save, Path(args.model_dir) / (args.name + "_stagetwo.model") + ) + try: + path_complied = Path(args.model_dir) / ( + args.name + "_stagetwo_compiled.model" + ) + logging.info(f"Compiling model, saving metadata {path_complied}") + model_compiled = jit.compile(deepcopy(model_to_save)) + torch.jit.save( + model_compiled, + path_complied, + _extra_files=extra_files, + ) + except Exception as e: # pylint: disable=W0718 + pass + else: + torch.save(model_to_save, Path(args.model_dir) / (args.name + ".model")) + try: + path_complied = Path(args.model_dir) / ( + args.name + "_compiled.model" + ) + logging.info(f"Compiling model, saving metadata to {path_complied}") + model_compiled = jit.compile(deepcopy(model_to_save)) + torch.jit.save( + model_compiled, + path_complied, + _extra_files=extra_files, + ) + except Exception as e: # pylint: disable=W0718 + pass + + logging.info("Computing metrics for training, validation, and test sets") + for param in model.parameters(): + param.requires_grad = False + skip_heads = args.skip_evaluate_heads.split(",") if args.skip_evaluate_heads else [] + if skip_heads: + logging.info(f"Skipping evaluation for heads: {skip_heads}") + table_train_valid = create_error_table( + table_type=args.error_table, + all_data_loaders=train_valid_data_loader, + model=model_to_evaluate, + loss_fn=loss_fn, + output_args=output_args, + log_wandb=args.wandb, + device=device, + distributed=args.distributed, + skip_heads=skip_heads, + ) + logging.info("Error-table on TRAIN and VALID:\n" + str(table_train_valid)) + + if test_data_loader: + table_test = create_error_table( + table_type=args.error_table, + all_data_loaders=test_data_loader, + model=model_to_evaluate, + loss_fn=loss_fn, + output_args=output_args, + log_wandb=args.wandb, + device=device, + distributed=args.distributed, + ) + logging.info("Error-table on TEST:\n" + str(table_test)) + if args.plot: + try: + plotter = TrainingPlotter( + results_dir=logger.path, + heads=heads, + table_type=args.error_table, + train_valid_data=train_valid_data_loader, + test_data=test_data_loader, + output_args=output_args, + device=device, + plot_frequency=args.plot_frequency, + distributed=args.distributed, + swa_start=swa.start if swa else None + ) + plotter.plot(epoch, model_to_evaluate, rank) + except Exception as e: # pylint: disable=W0718 + logging.debug(f"Plotting failed: {e}") + + if args.distributed: + torch.distributed.barrier() + + logging.info("Done") + if args.distributed: + torch.distributed.destroy_process_group() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/models/mace/mace/cli/select_head.py b/models/mace/mace/cli/select_head.py new file mode 100644 index 0000000000000000000000000000000000000000..305ab52feb3cce118b2702a95c941ea95ff457d4 --- /dev/null +++ b/models/mace/mace/cli/select_head.py @@ -0,0 +1,60 @@ +from argparse import ArgumentParser + +import torch + +from mace.tools.scripts_utils import remove_pt_head + + +def main(): + parser = ArgumentParser() + grp = parser.add_mutually_exclusive_group() + grp.add_argument( + "--head_name", + "-n", + help="name of the head to extract", + default=None, + ) + grp.add_argument( + "--list_heads", + "-l", + action="store_true", + help="list names of the heads", + ) + parser.add_argument( + "--target_device", + "-d", + help="target device, defaults to model's current device", + ) + parser.add_argument( + "--output_file", + "-o", + help="name for output model, defaults to model.head_name, followed by .target_device if specified", + ) + parser.add_argument("model_file", help="input model file path") + args = parser.parse_args() + + model = torch.load(args.model_file, map_location=args.target_device) + torch.set_default_dtype(next(model.parameters()).dtype) + + if args.list_heads: + print("Available heads:") + print("\n".join([" " + h for h in model.heads])) + else: + + if args.output_file is None: + args.output_file = ( + args.model_file + + "." + + args.head_name + + ("." + args.target_device if (args.target_device is not None) else "") + ) + + model_single = remove_pt_head(model, args.head_name) + if args.target_device is not None: + target_device = str(next(model.parameters()).device) + model_single.to(target_device) + torch.save(model_single, args.output_file) + + +if __name__ == "__main__": + main() diff --git a/models/mace/mace/cli/visualise_train.py b/models/mace/mace/cli/visualise_train.py new file mode 100644 index 0000000000000000000000000000000000000000..effbc49b3473565c2b0b687a637b44c4d433c167 --- /dev/null +++ b/models/mace/mace/cli/visualise_train.py @@ -0,0 +1,827 @@ +import json +import logging +from typing import Dict, List, Optional + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import torch +import torch.distributed +from torchmetrics import Metric + +from mace.tools.utils import filter_nonzero_weight + +plt.rcParams.update({"font.size": 8}) +mpl_logger = logging.getLogger("matplotlib") +mpl_logger.setLevel(logging.WARNING) # Only show WARNING and above + +colors = [ + "#1f77b4", # muted blue + "#d62728", # brick red + "#7f7f7f", # middle gray + "#2ca02c", # cooked asparagus green + "#ff7f0e", # safety orange + "#9467bd", # muted purple + "#8c564b", # chestnut brown + "#e377c2", # raspberry yogurt pink + "#bcbd22", # curry yellow-green + "#17becf", # blue-teal +] + +error_type = { + "TotalRMSE": ( + [("rmse_e", "RMSE E [meV]"), ("rmse_f", "RMSE F [meV / A]")], + [("energy", "Energy per atom [eV]"), ("force", "Force [eV / A]")], + ), + "PerAtomRMSE": ( + [("rmse_e_per_atom", "RMSE E/atom [meV]"), ("rmse_f", "RMSE F [meV / A]")], + [("energy", "Energy per atom [eV]"), ("force", "Force [eV / A]")], + ), + "PerAtomRMSEstressvirials": ( + [ + ("rmse_e_per_atom", "RMSE E/atom [meV]"), + ("rmse_f", "RMSE F [meV / A]"), + ("rmse_stress", "RMSE Stress [meV / A^3]"), + ], + [ + ("energy", "Energy per atom [eV]"), + ("force", "Force [eV / A]"), + ("stress", "Stress [eV / A^3]"), + ], + ), + "PerAtomMAEstressvirials": ( + [ + ("mae_e_per_atom", "MAE E/atom [meV]"), + ("mae_f", "MAE F [meV / A]"), + ("mae_stress", "MAE Stress [meV / A^3]"), + ], + [ + ("energy", "Energy per atom [eV]"), + ("force", "Force [eV / A]"), + ("stress", "Stress [eV / A^3]"), + ], + ), + "TotalMAE": ( + [("mae_e", "MAE E [meV]"), ("mae_f", "MAE F [meV / A]")], + [("energy", "Energy per atom [eV]"), ("force", "Force [eV / A]")], + ), + "PerAtomMAE": ( + [("mae_e_per_atom", "MAE E/atom [meV]"), ("mae_f", "MAE F [meV / A]")], + [("energy", "Energy per atom [eV]"), ("force", "Force [eV / A]")], + ), + "DipoleRMSE": ( + [ + ("rmse_mu_per_atom", "RMSE MU/atom [mDebye]"), + ("rel_rmse_f", "Relative MU RMSE [%]"), + ], + [("dipole", "Dipole per atom [Debye]")], + ), + "DipoleMAE": ( + [("mae_mu", "MAE MU [mDebye]"), ("rel_mae_f", "Relative MU MAE [%]")], + [("dipole", "Dipole per atom [Debye]")], + ), + "DipolePolarRMSE": ( + [ + ("rmse_mu_per_atom", "RMSE MU/atom [me AA]"), + ("rmse_alpha_per_atom", "RMSE ALPHA/atom [me AA^2/V]"), + ("rel_rmse_f", "Relative MU RMSE [%]"), + ("rmse_polarizability_per_atom", "Relative ALPHA RMSE [%]"), # check that + ], + [ + ("dipole", "Dipole per atom [me AA]]"), + ("polarizability", "Polarizability per atom [e AA^2/V]"), + ], + ), + "EnergyDipoleRMSE": ( + [ + ("rmse_e_per_atom", "RMSE E/atom [meV]"), + ("rmse_f", "RMSE F [meV / A]"), + ("rmse_mu_per_atom", "RMSE MU/atom [mDebye]"), + ], + [ + ("energy", "Energy per atom [eV]"), + ("force", "Force [eV / A]"), + ("dipole", "Dipole per atom [Debye]"), + ], + ), +} + + +class TrainingPlotter: + def __init__( + self, + results_dir: str, + heads: List[str], + table_type: str, + train_valid_data: Dict, + test_data: Dict, + output_args: str, + device: str, + plot_frequency: int, + distributed: bool = False, + swa_start: Optional[int] = None, + plot_interaction_e: bool = False, + ): + self.results_dir = results_dir + self.heads = heads + self.table_type = table_type + self.train_valid_data = train_valid_data + self.test_data = test_data + self.output_args = output_args + self.device = device + self.plot_frequency = plot_frequency + self.distributed = distributed + self.swa_start = swa_start + self.plot_interaction_e = plot_interaction_e + + def plot(self, model_epoch: str, model: torch.nn.Module, rank: int) -> None: + + # All ranks process data through model_inference + train_valid_dict = model_inference( + self.train_valid_data, + model, + self.output_args, + self.device, + self.distributed, + ) + test_dict = model_inference( + self.test_data, model, self.output_args, self.device, self.distributed + ) + + # Only rank 0 creates and saves plots + if rank != 0: + return + + data = pd.DataFrame( + results for results in parse_training_results(self.results_dir) + ) + labels, quantities = error_type[self.table_type] + + for head in self.heads: + fig = plt.figure(layout="constrained", figsize=(10, 6)) + fig.suptitle( + f"Model loaded from epoch {model_epoch} ({head} head)", fontsize=16 + ) + + subfigs = fig.subfigures(2, 1, height_ratios=[1, 1], hspace=0.05) + axsTop = subfigs[0].subplots(1, 2, sharey=False) + axsBottom = subfigs[1].subplots(1, len(quantities), sharey=False) + + plot_epoch_dependence(axsTop, data, head, model_epoch, labels) + + # Use the pre-computed results for plotting + plot_inference_from_results( + axsBottom, + train_valid_dict, + test_dict, + head, + quantities, + plot_interaction_e=self.plot_interaction_e, + ) + + if self.swa_start is not None: + # Add vertical lines to both axes + for ax in axsTop: + ax.axvline( + self.swa_start, + color="black", + linestyle="dashed", + linewidth=1, + alpha=0.6, + label="Stage Two Starts", + ) + stage = "stage_two" if self.swa_start < model_epoch else "stage_one" + else: + stage = "stage_one" + axsTop[0].legend(loc="best") + # Save the figure using the appropriate stage in the filename + filename = f"{self.results_dir[:-4]}_{head}_{stage}.png" + + fig.savefig(filename, dpi=300, bbox_inches="tight") + plt.close(fig) + + +def parse_training_results(path: str) -> List[dict]: + results = [] + with open(path, mode="r", encoding="utf-8") as f: + for line in f: + try: + d = json.loads(line.strip()) # Ensure it's valid JSON + results.append(d) + except json.JSONDecodeError: + print( + f"Skipping invalid line: {line.strip()}" + ) # Handle non-JSON lines gracefully + return results + + +def plot_epoch_dependence( + axes: np.ndarray, data: pd.DataFrame, head: str, model_epoch: str, labels: List[str] +) -> None: + + valid_data = ( + data[data["mode"] == "eval"] + .groupby(["mode", "epoch", "head"]) + .agg(["mean", "std"]) + .reset_index() + ) + valid_data = valid_data[valid_data["head"] == head] + train_data = ( + data[data["mode"] == "opt"] + .groupby(["mode", "epoch"]) + .agg(["mean", "std"]) + .reset_index() + ) + + # ---- Plot loss ---- + ax = axes[0] + ax.plot( + train_data["epoch"], train_data["loss"]["mean"], color=colors[1], linewidth=1 + ) + ax.set_ylabel("Training Loss", color=colors[1]) + ax.set_yscale("log") + + ax2 = ax.twinx() + ax2.plot( + valid_data["epoch"], valid_data["loss"]["mean"], color=colors[0], linewidth=1 + ) + ax2.set_ylabel("Validation Loss", color=colors[0]) + ax2.set_yscale("log") + + ax.axvline( + model_epoch, + color="black", + linestyle="solid", + linewidth=1, + alpha=0.8, + label="Loaded Model", + ) + ax.set_xlabel("Epoch") + ax.grid(True, linestyle="--", alpha=0.5) + + # ---- Plot selected keys ---- + ax = axes[1] + twin_axes = [] + for i, label in enumerate(labels): + color = colors[(i + 3)] + key, axis_label = label + if i == 0: + main_ax = ax + else: + main_ax = ax.twinx() + main_ax.spines.right.set_position(("outward", 60 * (i - 1))) + twin_axes.append(main_ax) + + main_ax.plot( + valid_data["epoch"], + valid_data[key]["mean"] * 1e3, + color=color, + label=label, + linewidth=1, + ) + main_ax.set_yscale("log") + main_ax.set_ylabel(axis_label, color=color) + main_ax.tick_params(axis="y", colors=color) + ax.axvline( + model_epoch, + color="black", + linestyle="solid", + linewidth=1, + alpha=0.8, + label="Loaded Model", + ) + ax.set_xlabel("Epoch") + ax.grid(True, linestyle="--", alpha=0.5) + + +# INFERENCE========= + + +def plot_inference_from_results( + axes: np.ndarray, + train_valid_dict: dict, + test_dict: dict, + head: str, + quantities: List[str], + plot_interaction_e: bool = False, +) -> None: + + for ax, quantity in zip(axes, quantities): + key, label = quantity + + # Store legend handles to avoid duplicates + legend_labels = {} + + # Plot train/valid data (each entry keeps its own name) + for name, result in train_valid_dict.items(): + if "train" in name: + fixed_color_train_valid = colors[1] + marker = "x" + else: + fixed_color_train_valid = colors[0] + marker = "+" + if head not in name: + continue + + # Initialize scatter to None + scatter = None + + if key == "energy" and "energy" in result: + e_key = "energy" if not plot_interaction_e else "interaction_energy" + scatter = ax.scatter( + result[e_key]["reference_per_atom"], + result[e_key]["predicted_per_atom"], + marker=marker, + color=fixed_color_train_valid, + label=name, + ) + + elif key == "force" and "forces" in result: + scatter = ax.scatter( + result["forces"]["reference"], + result["forces"]["predicted"], + marker=marker, + color=fixed_color_train_valid, + label=name, + ) + + elif key == "stress" and "stress" in result: + scatter = ax.scatter( + result["stress"]["reference"], + result["stress"]["predicted"], + marker=marker, + color=fixed_color_train_valid, + label=name, + ) + + elif key == "virials" and "virials" in result: + scatter = ax.scatter( + result["virials"]["reference_per_atom"], + result["virials"]["predicted_per_atom"], + marker=marker, + color=fixed_color_train_valid, + label=name, + ) + + elif key == "dipole" and "dipole" in result: + scatter = ax.scatter( + result["dipole"]["reference_per_atom"], + result["dipole"]["predicted_per_atom"], + marker=marker, + color=fixed_color_train_valid, + label=name, + ) + + # Add each train/valid dataset's name to the legend if scatter was assigned + if scatter is not None: + legend_labels[name] = scatter + + fixed_color_test = colors[2] # Color for test dataset + + # Plot test data (single legend entry) + for name, result in test_dict.items(): + # Initialize scatter to None to avoid possibly used before assignment + scatter = None + + if key == "energy" and "energy" in result: + e_key = "energy" if not plot_interaction_e else "interaction_energy" + scatter = ax.scatter( + result[e_key]["reference_per_atom"], + result[e_key]["predicted_per_atom"], + marker="o", + color=fixed_color_test, + label="Test", + ) + + elif key == "force" and "forces" in result: + scatter = ax.scatter( + result["forces"]["reference"], + result["forces"]["predicted"], + marker="o", + color=fixed_color_test, + label="Test", + ) + + elif key == "stress" and "stress" in result: + scatter = ax.scatter( + result["stress"]["reference"], + result["stress"]["predicted"], + marker="o", + color=fixed_color_test, + label="Test", + ) + + elif key == "virials" and "virials" in result: + scatter = ax.scatter( + result["virials"]["reference_per_atom"], + result["virials"]["predicted_per_atom"], + marker="o", + color=fixed_color_test, + label="Test", + ) + + elif key == "dipole" and "dipole" in result: + scatter = ax.scatter( + result["dipole"]["reference_per_atom"], + result["dipole"]["predicted_per_atom"], + marker="o", + color=fixed_color_test, + label="Test", + ) + + # Only add to legend_labels if scatter was assigned + if scatter is not None: + legend_labels["Test"] = scatter + + # Add diagonal line for guide + min_val = min(ax.get_xlim()[0], ax.get_ylim()[0]) + max_val = max(ax.get_xlim()[1], ax.get_ylim()[1]) + ax.plot( + [min_val, max_val], + [min_val, max_val], + linestyle="--", + color="black", + alpha=0.7, + ) + + # Set legend with unique entries (Test + individual train/valid names) + if legend_labels: + ax.legend( + handles=legend_labels.values(), labels=legend_labels.keys(), loc="best" + ) + if key != "energy" or not plot_interaction_e: + ax.set_xlabel(f"Reference {label}") + ax.set_ylabel(f"MACE {label}") + else: + ax.set_xlabel(f"Reference Interaction {label}") + ax.set_ylabel(f"MACE Interaction {label}") + ax.grid(True, linestyle="--", alpha=0.5) + + +def model_inference( + all_data_loaders: dict, + model: torch.nn.Module, + output_args: Dict[str, bool], + device: str, + distributed: bool = False, +): + + for param in model.parameters(): + param.requires_grad = False + + results_dict = {} + + for name in all_data_loaders: + data_loader = all_data_loaders[name] + logging.debug(f"Running inference on {name} dataset") + scatter_metric = InferenceMetric().to(device) + + for batch in data_loader: + batch = batch.to(device) + batch_dict = batch.to_dict() + output = model( + batch_dict, + training=False, + compute_force=output_args.get("forces", False), + compute_virials=output_args.get("virials", False), + compute_stress=output_args.get("stress", False), + ) + + results = scatter_metric(batch, output) + + if distributed: + torch.distributed.barrier() + + results = scatter_metric.compute() + results_dict[name] = results + scatter_metric.reset() + + del data_loader + + for param in model.parameters(): + param.requires_grad = True + + return results_dict + + +def to_numpy(tensor: torch.Tensor) -> np.ndarray: + return tensor.cpu().detach().numpy() + + +class InferenceMetric(Metric): + """Metric class for collecting reference and predicted values for scatterplot visualization.""" + + def __init__(self): + super().__init__() + # Raw values + self.add_state("ref_energies", default=[], dist_reduce_fx="cat") + self.add_state("ref_interaction_energies", default=[], dist_reduce_fx="cat") + self.add_state("pred_energies", default=[], dist_reduce_fx="cat") + self.add_state("pred_interaction_energies", default=[], dist_reduce_fx="cat") + self.add_state("ref_forces", default=[], dist_reduce_fx="cat") + self.add_state("pred_forces", default=[], dist_reduce_fx="cat") + self.add_state("ref_stress", default=[], dist_reduce_fx="cat") + self.add_state("pred_stress", default=[], dist_reduce_fx="cat") + self.add_state("ref_virials", default=[], dist_reduce_fx="cat") + self.add_state("pred_virials", default=[], dist_reduce_fx="cat") + self.add_state("ref_dipole", default=[], dist_reduce_fx="cat") + self.add_state("pred_dipole", default=[], dist_reduce_fx="cat") + + # Per-atom normalized values + self.add_state("ref_energies_per_atom", default=[], dist_reduce_fx="cat") + self.add_state( + "ref_interaction_energies_per_atom", default=[], dist_reduce_fx="cat" + ) + self.add_state("pred_energies_per_atom", default=[], dist_reduce_fx="cat") + self.add_state( + "pred_interaction_energies_per_atom", default=[], dist_reduce_fx="cat" + ) + self.add_state("ref_virials_per_atom", default=[], dist_reduce_fx="cat") + self.add_state("pred_virials_per_atom", default=[], dist_reduce_fx="cat") + self.add_state("ref_dipole_per_atom", default=[], dist_reduce_fx="cat") + self.add_state("pred_dipole_per_atom", default=[], dist_reduce_fx="cat") + + # Store atom counts for each configuration + self.add_state("atom_counts", default=[], dist_reduce_fx="cat") + + # Counters + self.add_state("n_energy", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state( + "n_interaction_energy", default=torch.tensor(0.0), dist_reduce_fx="sum" + ) + self.add_state("n_forces", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("n_stress", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("n_virials", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("n_dipole", default=torch.tensor(0.0), dist_reduce_fx="sum") + + def update(self, batch, output): # pylint: disable=arguments-differ + """Update metric states with new batch data.""" + # Calculate number of atoms per configuration + atoms_per_config = batch.ptr[1:] - batch.ptr[:-1] + self.atom_counts.append(atoms_per_config) + + # Energy + if output.get("energy") is not None and batch.energy is not None: + self.ref_energies.append(batch.energy) + self.pred_energies.append(output["energy"]) + # Per-atom normalization + self.ref_energies_per_atom.append(batch.energy / atoms_per_config) + self.pred_energies_per_atom.append(output["energy"] / atoms_per_config) + + self.n_energy += filter_nonzero_weight( + batch, + self.ref_energies, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.pred_energies, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.ref_energies_per_atom, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.pred_energies_per_atom, + batch.weight, + batch.energy_weight, + ) + + if output.get("interaction_energy") is not None and batch.energy is not None: + E0s = output["energy"].to(torch.float64) - output["interaction_energy"].to( + torch.float64 + ) + self.ref_interaction_energies.append(batch.energy - E0s) + self.pred_interaction_energies.append(output["interaction_energy"]) + # Per-atom normalization + self.ref_interaction_energies_per_atom.append( + (batch.energy - E0s) / atoms_per_config + ) + self.pred_interaction_energies_per_atom.append( + output["interaction_energy"] / atoms_per_config + ) + + self.n_interaction_energy += filter_nonzero_weight( + batch, + self.ref_interaction_energies, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.pred_interaction_energies, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.ref_interaction_energies_per_atom, + batch.weight, + batch.energy_weight, + ) + filter_nonzero_weight( + batch, + self.pred_interaction_energies_per_atom, + batch.weight, + batch.energy_weight, + ) + + # Forces + if output.get("forces") is not None and batch.forces is not None: + self.ref_forces.append(batch.forces) + self.pred_forces.append(output["forces"]) + + self.n_forces += filter_nonzero_weight( + batch, + self.ref_forces, + batch.weight, + batch.forces_weight, + spread_atoms=True, + ) + filter_nonzero_weight( + batch, + self.pred_forces, + batch.weight, + batch.forces_weight, + spread_atoms=True, + ) + + # Stress + if output.get("stress") is not None and batch.stress is not None: + self.ref_stress.append(batch.stress) + self.pred_stress.append(output["stress"]) + + self.n_stress += filter_nonzero_weight( + batch, + self.ref_stress, + batch.weight, + batch.stress_weight, + ) + filter_nonzero_weight( + batch, + self.pred_stress, + batch.weight, + batch.stress_weight, + ) + + # Virials + if output.get("virials") is not None and batch.virials is not None: + self.ref_virials.append(batch.virials) + self.pred_virials.append(output["virials"]) + # Per-atom normalization + atoms_per_config_3d = atoms_per_config.view(-1, 1, 1) + self.ref_virials_per_atom.append(batch.virials / atoms_per_config_3d) + self.pred_virials_per_atom.append(output["virials"] / atoms_per_config_3d) + + self.n_virials += filter_nonzero_weight( + batch, + self.ref_virials, + batch.weight, + batch.virials_weight, + ) + filter_nonzero_weight( + batch, + self.pred_virials, + batch.weight, + batch.virials_weight, + ) + filter_nonzero_weight( + batch, + self.ref_virials_per_atom, + batch.weight, + batch.virials_weight, + ) + filter_nonzero_weight( + batch, + self.pred_virials_per_atom, + batch.weight, + batch.virials_weight, + ) + + # Dipole + if output.get("dipole") is not None and batch.dipole is not None: + self.ref_dipole.append(batch.dipole) + self.pred_dipole.append(output["dipole"]) + atoms_per_config_3d = atoms_per_config.view(-1, 1) + self.ref_dipole_per_atom.append(batch.dipole / atoms_per_config_3d) + self.pred_dipole_per_atom.append(output["dipole"] / atoms_per_config_3d) + + self.n_dipole += filter_nonzero_weight( + batch, self.ref_dipole, batch.weight, batch.dipole_weight, "config" + ) + filter_nonzero_weight( + batch, self.pred_dipole, batch.weight, batch.dipole_weight, "config" + ) + filter_nonzero_weight( + batch, + self.ref_dipole_per_atom, + batch.weight, + batch.dipole_weight, + spread_quantity_vector=False, + ) + filter_nonzero_weight( + batch, + self.pred_dipole_per_atom, + batch.weight, + batch.dipole_weight, + spread_quantity_vector=False, + ) + + def _process_data(self, ref_list, pred_list): + # Handle different possible states of ref_list and pred_list in distributed mode + + # Check if this is a list type object + if isinstance(ref_list, (list, tuple)): + if len(ref_list) == 0: + return None, None + ref = torch.cat(ref_list).reshape(-1) + pred = torch.cat(pred_list).reshape(-1) + # Handle case where ref_list is already a tensor (happens after reset in distributed mode) + elif isinstance(ref_list, torch.Tensor): + ref = ref_list.reshape(-1) + pred = pred_list.reshape(-1) + # Handle other possible types + else: + return None, None + return to_numpy(ref), to_numpy(pred) + + def compute(self): + """Compute final results for scatterplot.""" + results = {} + + # Process energies + if self.n_energy: + ref_e, pred_e = self._process_data(self.ref_energies, self.pred_energies) + ref_e_pa, pred_e_pa = self._process_data( + self.ref_energies_per_atom, self.pred_energies_per_atom + ) + results["energy"] = { + "reference": ref_e, + "predicted": pred_e, + "reference_per_atom": ref_e_pa, + "predicted_per_atom": pred_e_pa, + } + + if self.n_interaction_energy: + ref_interaction_e, pred_interaction_e = self._process_data( + self.ref_interaction_energies, self.pred_interaction_energies + ) + ref_interaction_e_pa, pred_interaction_e_pa = self._process_data( + self.ref_interaction_energies_per_atom, + self.pred_interaction_energies_per_atom, + ) + results["interaction_energy"] = { + "reference": ref_interaction_e, + "predicted": pred_interaction_e, + "reference_per_atom": ref_interaction_e_pa, + "predicted_per_atom": pred_interaction_e_pa, + } + + # Process forces + if self.n_forces: + ref_f, pred_f = self._process_data(self.ref_forces, self.pred_forces) + results["forces"] = { + "reference": ref_f, + "predicted": pred_f, + } + + # Process stress + if self.n_stress: + ref_s, pred_s = self._process_data(self.ref_stress, self.pred_stress) + results["stress"] = { + "reference": ref_s, + "predicted": pred_s, + } + + # Process virials + if self.n_virials: + ref_v, pred_v = self._process_data(self.ref_virials, self.pred_virials) + ref_v_pa, pred_v_pa = self._process_data( + self.ref_virials_per_atom, self.pred_virials_per_atom + ) + results["virials"] = { + "reference": ref_v, + "predicted": pred_v, + "reference_per_atom": ref_v_pa, + "predicted_per_atom": pred_v_pa, + } + + # Process dipoles + if self.n_dipole: + ref_d, pred_d = self._process_data(self.ref_dipole, self.pred_dipole) + ref_d_pa, pred_d_pa = self._process_data( + self.ref_dipole_per_atom, self.pred_dipole_per_atom + ) + results["dipole"] = { + "reference": ref_d, + "predicted": pred_d, + "reference_per_atom": ref_d_pa, + "predicted_per_atom": pred_d_pa, + } + return results diff --git a/models/mace/mace/data/__init__.py b/models/mace/mace/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8629cf521b395a4cfd2899b5f89a17d45dfa2749 --- /dev/null +++ b/models/mace/mace/data/__init__.py @@ -0,0 +1,40 @@ +from .atomic_data import AtomicData +from .hdf5_dataset import HDF5Dataset, dataset_from_sharded_hdf5 +from .lmdb_dataset import LMDBDataset +from .neighborhood import get_neighborhood +from .utils import ( + Configuration, + Configurations, + KeySpecification, + compute_average_E0s, + config_from_atoms, + config_from_atoms_list, + load_from_xyz, + random_train_valid_split, + save_AtomicData_to_HDF5, + save_configurations_as_HDF5, + save_dataset_as_HDF5, + test_config_types, + update_keyspec_from_kwargs, +) + +__all__ = [ + "get_neighborhood", + "Configuration", + "Configurations", + "random_train_valid_split", + "load_from_xyz", + "test_config_types", + "config_from_atoms", + "config_from_atoms_list", + "AtomicData", + "compute_average_E0s", + "save_dataset_as_HDF5", + "HDF5Dataset", + "dataset_from_sharded_hdf5", + "save_AtomicData_to_HDF5", + "save_configurations_as_HDF5", + "KeySpecification", + "update_keyspec_from_kwargs", + "LMDBDataset", +] diff --git a/models/mace/mace/data/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53a954a8de8c7d9bbdd15bd9f0a80a4d2469cda7 Binary files /dev/null and b/models/mace/mace/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/data/__pycache__/atomic_data.cpython-310.pyc b/models/mace/mace/data/__pycache__/atomic_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce9584fe6d4da3ee6b969edde14d8935b2b4129c Binary files /dev/null and b/models/mace/mace/data/__pycache__/atomic_data.cpython-310.pyc differ diff --git a/models/mace/mace/data/__pycache__/hdf5_dataset.cpython-310.pyc b/models/mace/mace/data/__pycache__/hdf5_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d171b2fbc208f2699982f609f9e42f7418553529 Binary files /dev/null and b/models/mace/mace/data/__pycache__/hdf5_dataset.cpython-310.pyc differ diff --git a/models/mace/mace/data/__pycache__/lmdb_dataset.cpython-310.pyc b/models/mace/mace/data/__pycache__/lmdb_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..474f0477afff01669cc3138934f64fca7a355642 Binary files /dev/null and b/models/mace/mace/data/__pycache__/lmdb_dataset.cpython-310.pyc differ diff --git a/models/mace/mace/data/__pycache__/neighborhood.cpython-310.pyc b/models/mace/mace/data/__pycache__/neighborhood.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6bd4ac812bfff5e5a28377c988e9ac5b758cea4 Binary files /dev/null and b/models/mace/mace/data/__pycache__/neighborhood.cpython-310.pyc differ diff --git a/models/mace/mace/data/__pycache__/utils.cpython-310.pyc b/models/mace/mace/data/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aea38725cad33cdd0893f1c506b1a4aad5041fc Binary files /dev/null and b/models/mace/mace/data/__pycache__/utils.cpython-310.pyc differ diff --git a/models/mace/mace/data/atomic_data.py b/models/mace/mace/data/atomic_data.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd8ec0b8ad135ab4aba5cc23b9afa403b86a43f --- /dev/null +++ b/models/mace/mace/data/atomic_data.py @@ -0,0 +1,409 @@ +########################################################################################### +# Atomic Data Class for handling molecules as graphs +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from copy import deepcopy +from typing import Optional, Sequence + +import torch.utils.data + +from mace.tools import ( + AtomicNumberTable, + atomic_numbers_to_indices, + to_one_hot, + torch_geometric, + voigt_to_matrix, +) + +from .neighborhood import get_neighborhood +from .utils import Configuration + + +class AtomicData(torch_geometric.data.Data): + num_graphs: torch.Tensor + batch: torch.Tensor + edge_index: torch.Tensor + node_attrs: torch.Tensor + edge_vectors: torch.Tensor + edge_lengths: torch.Tensor + positions: torch.Tensor + shifts: torch.Tensor + unit_shifts: torch.Tensor + cell: torch.Tensor + forces: torch.Tensor + energy: torch.Tensor + stress: torch.Tensor + virials: torch.Tensor + dipole: torch.Tensor + charges: torch.Tensor + polarizability: torch.Tensor + total_charge: torch.Tensor + total_spin: torch.Tensor + weight: torch.Tensor + energy_weight: torch.Tensor + forces_weight: torch.Tensor + stress_weight: torch.Tensor + virials_weight: torch.Tensor + dipole_weight: torch.Tensor + charges_weight: torch.Tensor + polarizability_weight: torch.Tensor + + def __init__( + self, + edge_index: torch.Tensor, # [2, n_edges] + node_attrs: torch.Tensor, # [n_nodes, n_node_feats] + positions: torch.Tensor, # [n_nodes, 3] + shifts: torch.Tensor, # [n_edges, 3], + unit_shifts: torch.Tensor, # [n_edges, 3] + cell: Optional[torch.Tensor], # [3,3] + weight: Optional[torch.Tensor], # [,] + head: Optional[torch.Tensor], # [,] + energy_weight: Optional[torch.Tensor], # [,] + forces_weight: Optional[torch.Tensor], # [,] + stress_weight: Optional[torch.Tensor], # [,] + virials_weight: Optional[torch.Tensor], # [,] + dipole_weight: Optional[torch.Tensor], # [,] + charges_weight: Optional[torch.Tensor], # [,] + polarizability_weight: Optional[torch.Tensor], # [,] + forces: Optional[torch.Tensor], # [n_nodes, 3] + energy: Optional[torch.Tensor], # [, ] + stress: Optional[torch.Tensor], # [1,3,3] + virials: Optional[torch.Tensor], # [1,3,3] + dipole: Optional[torch.Tensor], # [, 3] + charges: Optional[torch.Tensor], # [n_nodes, ] + polarizability: Optional[torch.Tensor], # [1, 3, 3] + elec_temp: Optional[torch.Tensor], # [,] + total_charge: Optional[torch.Tensor] = None, # [,] + total_spin: Optional[torch.Tensor] = None, # [,] + pbc: Optional[torch.Tensor] = None, # [, 3] + **extra_data, # additional properties that aren't hard-coded and therefore not + # for correct shape, etc + ): + # Check shapes + num_nodes = node_attrs.shape[0] + + assert edge_index.shape[0] == 2 and len(edge_index.shape) == 2 + assert positions.shape == (num_nodes, 3) + assert shifts.shape[1] == 3 + assert unit_shifts.shape[1] == 3 + assert len(node_attrs.shape) == 2 + assert weight is None or len(weight.shape) == 0 + assert head is None or len(head.shape) == 0 + assert energy_weight is None or len(energy_weight.shape) == 0 + assert forces_weight is None or len(forces_weight.shape) == 0 + assert stress_weight is None or len(stress_weight.shape) == 0 + assert virials_weight is None or len(virials_weight.shape) == 0 + assert dipole_weight is None or dipole_weight.shape == (1, 3), dipole_weight + assert charges_weight is None or len(charges_weight.shape) == 0 + assert cell is None or cell.shape == (3, 3) + assert forces is None or forces.shape == (num_nodes, 3) + assert energy is None or len(energy.shape) == 0 + assert stress is None or stress.shape == (1, 3, 3) + assert virials is None or virials.shape == (1, 3, 3) + assert dipole is None or dipole.shape[-1] == 3 + assert charges is None or charges.shape == (num_nodes,) + assert elec_temp is None or len(elec_temp.shape) == 0 + assert total_charge is None or len(total_charge.shape) == 0 + assert total_spin is None or len(total_spin.shape) == 0 + assert polarizability is None or polarizability.shape == (1, 3, 3) + assert pbc is None or (pbc.shape[-1] == 3 and pbc.dtype == torch.bool) + + # Aggregate data + data = { + "num_nodes": num_nodes, + "edge_index": edge_index, + "positions": positions, + "shifts": shifts, + "unit_shifts": unit_shifts, + "cell": cell, + "node_attrs": node_attrs, + "weight": weight, + "head": head, + "energy_weight": energy_weight, + "forces_weight": forces_weight, + "stress_weight": stress_weight, + "virials_weight": virials_weight, + "dipole_weight": dipole_weight, + "charges_weight": charges_weight, + "polarizability_weight": polarizability_weight, + "forces": forces, + "energy": energy, + "stress": stress, + "virials": virials, + "dipole": dipole, + "charges": charges, + "polarizability": polarizability, + "elec_temp": elec_temp, + "total_charge": total_charge, + "total_spin": total_spin, + "pbc": pbc, + } + super().__init__(**data, **extra_data) + + @classmethod + def from_config( + cls, + config: Configuration, + z_table: AtomicNumberTable, + cutoff: float, + heads: Optional[list] = None, + **kwargs, # pylint: disable=unused-argument + ) -> "AtomicData": + if heads is None: + heads = ["Default"] + edge_index, shifts, unit_shifts, cell = get_neighborhood( + positions=config.positions, + cutoff=cutoff, + pbc=deepcopy(config.pbc), + cell=deepcopy(config.cell), + ) + indices = atomic_numbers_to_indices(config.atomic_numbers, z_table=z_table) + one_hot = to_one_hot( + torch.tensor(indices, dtype=torch.long).unsqueeze(-1), + num_classes=len(z_table), + ) + try: + head = torch.tensor(heads.index(config.head), dtype=torch.long) + except ValueError: + head = torch.tensor(len(heads) - 1, dtype=torch.long) + + cell = ( + torch.tensor(cell, dtype=torch.get_default_dtype()) + if cell is not None + else torch.tensor( + 3 * [0.0, 0.0, 0.0], dtype=torch.get_default_dtype() + ).view(3, 3) + ) + + num_atoms = len(config.atomic_numbers) + + weight = ( + torch.tensor(config.weight, dtype=torch.get_default_dtype()) + if config.weight is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + + energy_weight = ( + torch.tensor( + config.property_weights.get("energy"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("energy") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + + forces_weight = ( + torch.tensor( + config.property_weights.get("forces"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("forces") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + + stress_weight = ( + torch.tensor( + config.property_weights.get("stress"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("stress") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + + virials_weight = ( + torch.tensor( + config.property_weights.get("virials"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("virials") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + + dipole_weight = ( + torch.tensor( + config.property_weights.get("dipole"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("dipole") is not None + else torch.tensor([[1.0, 1.0, 1.0]], dtype=torch.get_default_dtype()) + ) + if len(dipole_weight.shape) == 0: + dipole_weight = dipole_weight * torch.tensor( + [[1.0, 1.0, 1.0]], dtype=torch.get_default_dtype() + ) + elif len(dipole_weight.shape) == 1: + dipole_weight = dipole_weight.unsqueeze(0) + + charges_weight = ( + torch.tensor( + config.property_weights.get("charges"), dtype=torch.get_default_dtype() + ) + if config.property_weights.get("charges") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + polarizability_weight = ( + torch.tensor( + config.property_weights.get("polarizability"), + dtype=torch.get_default_dtype(), + ) + if config.property_weights.get("polarizability") is not None + else torch.tensor( + [[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]], + dtype=torch.get_default_dtype(), + ) + ) + if len(polarizability_weight.shape) == 0: + polarizability_weight = polarizability_weight * torch.tensor( + [[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]], + dtype=torch.get_default_dtype(), + ) + elif len(polarizability_weight.shape) == 2: + polarizability_weight = polarizability_weight.unsqueeze(0) + forces = ( + torch.tensor( + config.properties.get("forces"), dtype=torch.get_default_dtype() + ) + if config.properties.get("forces") is not None + else torch.zeros(num_atoms, 3, dtype=torch.get_default_dtype()) + ) + energy = ( + torch.tensor( + config.properties.get("energy"), dtype=torch.get_default_dtype() + ) + if config.properties.get("energy") is not None + else torch.tensor(0.0, dtype=torch.get_default_dtype()) + ) + stress = ( + voigt_to_matrix( + torch.tensor( + config.properties.get("stress"), dtype=torch.get_default_dtype() + ) + ).unsqueeze(0) + if config.properties.get("stress") is not None + else torch.zeros(1, 3, 3, dtype=torch.get_default_dtype()) + ) + virials = ( + voigt_to_matrix( + torch.tensor( + config.properties.get("virials"), dtype=torch.get_default_dtype() + ) + ).unsqueeze(0) + if config.properties.get("virials") is not None + else torch.zeros(1, 3, 3, dtype=torch.get_default_dtype()) + ) + dipole = ( + torch.tensor( + config.properties.get("dipole"), dtype=torch.get_default_dtype() + ).unsqueeze(0) + if config.properties.get("dipole") is not None + else torch.zeros(1, 3, dtype=torch.get_default_dtype()) + ) + charges = ( + torch.tensor( + config.properties.get("charges"), dtype=torch.get_default_dtype() + ) + if config.properties.get("charges") is not None + else torch.zeros(num_atoms, dtype=torch.get_default_dtype()) + ) + elec_temp = ( + torch.tensor( + config.properties.get("elec_temp"), + dtype=torch.get_default_dtype(), + ) + if config.properties.get("elec_temp") is not None + else torch.tensor(0.0, dtype=torch.get_default_dtype()) + ) + + total_charge = ( + torch.tensor( + config.properties.get("total_charge"), dtype=torch.get_default_dtype() + ) + if config.properties.get("total_charge") is not None + else torch.tensor(0.0, dtype=torch.get_default_dtype()) + ) + + polarizability = ( + torch.tensor( + config.properties.get("polarizability"), dtype=torch.get_default_dtype() + ).view(1, 3, 3) + if config.properties.get("polarizability") is not None + else torch.zeros(1, 3, 3, dtype=torch.get_default_dtype()) + ) + + total_spin = ( + torch.tensor( + config.properties.get("total_spin"), dtype=torch.get_default_dtype() + ) + if config.properties.get("total_spin") is not None + else torch.tensor(1.0, dtype=torch.get_default_dtype()) + ) + if config.pbc is not None: + pbc = list(bool(pbc_) for pbc_ in config.pbc) + else: + pbc = None + pbc = ( + torch.tensor([pbc], dtype=torch.bool) + if pbc is not None + else torch.tensor([[False, False, False]], dtype=torch.bool) + ) + + cls_kwargs = dict( + edge_index=torch.tensor(edge_index, dtype=torch.long), + positions=torch.tensor(config.positions, dtype=torch.get_default_dtype()), + shifts=torch.tensor(shifts, dtype=torch.get_default_dtype()), + unit_shifts=torch.tensor(unit_shifts, dtype=torch.get_default_dtype()), + cell=cell, + node_attrs=one_hot, + weight=weight, + head=head, + energy_weight=energy_weight, + forces_weight=forces_weight, + stress_weight=stress_weight, + virials_weight=virials_weight, + dipole_weight=dipole_weight, + charges_weight=charges_weight, + polarizability_weight=polarizability_weight, + forces=forces, + energy=energy, + stress=stress, + virials=virials, + dipole=dipole, + charges=charges, + elec_temp=elec_temp, + total_charge=total_charge, + polarizability=polarizability, + total_spin=total_spin, + pbc=pbc, + ) + + # Add other properties that aren't checked. WARNING: shape dependence + # and unsqueeze(-1) call may implicitly be assuming that these are all + # per-atom, not per-config. + # + # NOTE: might be able to simpligy a lot by adding most properties this + # way, except a few that need to be special cased, e.g. are mandatory, + # really need a default value (e.g. weight), or need shape conversion + # (e.g. stress/virial). Getting the right shape might require some knowledge + # of whether the property is per-config or per-atom + for k, v in config.properties.items(): + if k not in cls_kwargs and v is not None: + if len(v.shape) == 1: + # promote to n_atoms x 1 + cls_kwargs[k] = torch.tensor( + v, dtype=torch.get_default_dtype() + ).unsqueeze(-1) + elif len(v.shape) == 2: + cls_kwargs[k] = torch.tensor(v, dtype=torch.get_default_dtype()) + + return cls(**cls_kwargs) + + +def get_data_loader( + dataset: Sequence[AtomicData], + batch_size: int, + shuffle=True, + drop_last=False, +) -> torch.utils.data.DataLoader: + return torch_geometric.dataloader.DataLoader( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last, + ) diff --git a/models/mace/mace/data/hdf5_dataset.py b/models/mace/mace/data/hdf5_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6aa7c7095b756ff0e020c0821bd6efafda9aed --- /dev/null +++ b/models/mace/mace/data/hdf5_dataset.py @@ -0,0 +1,97 @@ +from glob import glob +from typing import List + +import h5py +from torch.utils.data import ConcatDataset, Dataset + +from mace.data.atomic_data import AtomicData +from mace.data.utils import Configuration +from mace.tools.utils import AtomicNumberTable + + +class HDF5Dataset(Dataset): + def __init__( + self, file_path, r_max, z_table, atomic_dataclass=AtomicData, **kwargs + ): + super(HDF5Dataset, self).__init__() # pylint: disable=super-with-arguments + self.file_path = file_path + self._file = None + batch_key = list(self.file.keys())[0] + self.batch_size = len(self.file[batch_key].keys()) + self.length = len(self.file.keys()) * self.batch_size + self.r_max = r_max + self.z_table = z_table + self.atomic_dataclass = atomic_dataclass + try: + self.drop_last = bool(self.file.attrs["drop_last"]) + except KeyError: + self.drop_last = False + self.kwargs = kwargs + + @property + def file(self): + if self._file is None: + # If a file has not already been opened, open one here + self._file = h5py.File(self.file_path, "r") + return self._file + + def __getstate__(self): + _d = dict(self.__dict__) + + # An opened h5py.File cannot be pickled, so we must exclude it from the state + _d["_file"] = None + return _d + + def __len__(self): + return self.length + + def __getitem__(self, index): + # compute the index of the batch + batch_index = index // self.batch_size + config_index = index % self.batch_size + grp = self.file["config_batch_" + str(batch_index)] + subgrp = grp["config_" + str(config_index)] + + properties = {} + property_weights = {} + for key in subgrp["properties"]: + properties[key] = unpack_value(subgrp["properties"][key][()]) + for key in subgrp["property_weights"]: + property_weights[key] = unpack_value(subgrp["property_weights"][key][()]) + + config = Configuration( + atomic_numbers=subgrp["atomic_numbers"][()], + positions=subgrp["positions"][()], + properties=properties, + weight=unpack_value(subgrp["weight"][()]), + property_weights=property_weights, + config_type=unpack_value(subgrp["config_type"][()]), + pbc=unpack_value(subgrp["pbc"][()]), + cell=unpack_value(subgrp["cell"][()]), + ) + if config.head is None: + config.head = self.kwargs.get("head") + atomic_data = self.atomic_dataclass.from_config( + config, + z_table=self.z_table, + cutoff=self.r_max, + heads=self.kwargs.get("heads", ["Default"]), + **{k: v for k, v in self.kwargs.items() if k != "heads"}, + ) + return atomic_data + + +def dataset_from_sharded_hdf5( + files: List, z_table: AtomicNumberTable, r_max: float, **kwargs +): + files = glob(files + "/*") + datasets = [] + for file in files: + datasets.append(HDF5Dataset(file, z_table=z_table, r_max=r_max, **kwargs)) + full_dataset = ConcatDataset(datasets) + return full_dataset + + +def unpack_value(value): + value = value.decode("utf-8") if isinstance(value, bytes) else value + return None if str(value) == "None" else value diff --git a/models/mace/mace/data/lmdb_dataset.py b/models/mace/mace/data/lmdb_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ebbdaf54f3faee0fd5453cd1c509510d14c9d5 --- /dev/null +++ b/models/mace/mace/data/lmdb_dataset.py @@ -0,0 +1,69 @@ +import os + +import numpy as np +from torch.utils.data import Dataset + +from mace.data.atomic_data import AtomicData +from mace.data.utils import KeySpecification, config_from_atoms +from mace.tools.default_keys import DefaultKeys +from mace.tools.fairchem_dataset import AseDBDataset + + +class LMDBDataset(Dataset): + def __init__(self, file_path, r_max, z_table, **kwargs): + dataset_paths = file_path.split(":") # using : split multiple paths + # make sure each of the path exist + for path in dataset_paths: + assert os.path.exists(path) + config_kwargs = {} + super(LMDBDataset, self).__init__() # pylint: disable=super-with-arguments + self.AseDB = AseDBDataset(config=dict(src=dataset_paths, **config_kwargs)) + self.r_max = r_max + self.z_table = z_table + + self.kwargs = kwargs + self.transform = kwargs["transform"] if "transform" in kwargs else None + + def __len__(self): + return len(self.AseDB) + + def __getitem__(self, index): + try: + atoms = self.AseDB.get_atoms(self.AseDB.ids[index]) + except Exception as e: # pylint: disable=broad-except + print(f"Error in index {index}") + print(e) + return None + assert np.sum(atoms.get_cell() == atoms.cell) == 9 + + if hasattr(atoms, "calc") and hasattr(atoms.calc, "results"): + if "energy" in atoms.calc.results: + atoms.info[DefaultKeys.ENERGY.value] = atoms.calc.results["energy"] + if "forces" in atoms.calc.results: + atoms.arrays[DefaultKeys.FORCES.value] = atoms.calc.results["forces"] + if "stress" in atoms.calc.results: + atoms.info[DefaultKeys.STRESS.value] = atoms.calc.results["stress"] + + config = config_from_atoms( + atoms, + key_specification=KeySpecification.from_defaults(), + ) + + # Set head if not already set + if config.head == "Default": + config.head = self.kwargs.get("head", "Default") + + try: + atomic_data = AtomicData.from_config( + config, + z_table=self.z_table, + cutoff=self.r_max, + heads=self.kwargs.get("heads", ["Default"]), + ) + except Exception as e: # pylint: disable=broad-except + print(f"Error in index {index}") + print(e) + + if self.transform: + atomic_data = self.transform(atomic_data) + return atomic_data diff --git a/models/mace/mace/data/neighborhood.py b/models/mace/mace/data/neighborhood.py new file mode 100644 index 0000000000000000000000000000000000000000..03728969df6af8111b9bab8aa1602c8fa73e8082 --- /dev/null +++ b/models/mace/mace/data/neighborhood.py @@ -0,0 +1,66 @@ +from typing import Optional, Tuple + +import numpy as np +from matscipy.neighbours import neighbour_list + + +def get_neighborhood( + positions: np.ndarray, # [num_positions, 3] + cutoff: float, + pbc: Optional[Tuple[bool, bool, bool]] = None, + cell: Optional[np.ndarray] = None, # [3, 3] + true_self_interaction=False, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + if pbc is None: + pbc = (False, False, False) + + if cell is None or cell.any() == np.zeros((3, 3)).any(): + cell = np.identity(3, dtype=float) + + assert len(pbc) == 3 and all(isinstance(i, (bool, np.bool_)) for i in pbc) + assert cell.shape == (3, 3) + + pbc_x = pbc[0] + pbc_y = pbc[1] + pbc_z = pbc[2] + identity = np.identity(3, dtype=float) + max_positions = np.max(np.absolute(positions)) + 1 + # Extend cell in non-periodic directions + # For models with more than 5 layers, the multiplicative constant needs to be increased. + # temp_cell = np.copy(cell) + if not pbc_x: + cell[0, :] = max_positions * 5 * cutoff * identity[0, :] + if not pbc_y: + cell[1, :] = max_positions * 5 * cutoff * identity[1, :] + if not pbc_z: + cell[2, :] = max_positions * 5 * cutoff * identity[2, :] + + sender, receiver, unit_shifts = neighbour_list( + quantities="ijS", + pbc=pbc, + cell=cell, + positions=positions, + cutoff=cutoff, + # self_interaction=True, # we want edges from atom to itself in different periodic images + # use_scaled_positions=False, # positions are not scaled positions + ) + + if not true_self_interaction: + # Eliminate self-edges that don't cross periodic boundaries + true_self_edge = sender == receiver + true_self_edge &= np.all(unit_shifts == 0, axis=1) + keep_edge = ~true_self_edge + + # Note: after eliminating self-edges, it can be that no edges remain in this system + sender = sender[keep_edge] + receiver = receiver[keep_edge] + unit_shifts = unit_shifts[keep_edge] + + # Build output + edge_index = np.stack((sender, receiver)) # [2, n_edges] + + # From the docs: With the shift vector S, the distances D between atoms can be computed from + # D = positions[j]-positions[i]+S.dot(cell) + shifts = np.dot(unit_shifts, cell) # [n_edges, 3] + + return edge_index, shifts, unit_shifts, cell diff --git a/models/mace/mace/data/utils.py b/models/mace/mace/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..049d42cdd75457c953f8bd240befc983a6ff4cb3 --- /dev/null +++ b/models/mace/mace/data/utils.py @@ -0,0 +1,441 @@ +########################################################################################### +# Data parsing utilities +# Authors: Ilyes Batatia, Gregor Simm and David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import logging +import os +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import ase.data +import ase.io +import h5py +import numpy as np + +from mace.tools import AtomicNumberTable, DefaultKeys + +Positions = np.ndarray # [..., 3] +Cell = np.ndarray # [3,3] +Pbc = tuple # (3,) + +DEFAULT_CONFIG_TYPE = "Default" +DEFAULT_CONFIG_TYPE_WEIGHTS = {DEFAULT_CONFIG_TYPE: 1.0} + + +@dataclass +class KeySpecification: + info_keys: Dict[str, str] = field(default_factory=dict) + arrays_keys: Dict[str, str] = field(default_factory=dict) + + def update( + self, + info_keys: Optional[Dict[str, str]] = None, + arrays_keys: Optional[Dict[str, str]] = None, + ): + if info_keys is not None: + self.info_keys.update(info_keys) + if arrays_keys is not None: + self.arrays_keys.update(arrays_keys) + return self + + @classmethod + def from_defaults(cls): + instance = cls() + return update_keyspec_from_kwargs(instance, DefaultKeys.keydict()) + + +def update_keyspec_from_kwargs( + keyspec: KeySpecification, keydict: Dict[str, str] +) -> KeySpecification: + # convert command line style property_key arguments into a keyspec + infos = [ + "energy_key", + "stress_key", + "virials_key", + "dipole_key", + "head_key", + "elec_temp_key", + "total_charge_key", + "polarizability_key", + "total_spin_key", + ] + arrays = ["forces_key", "charges_key"] + info_keys = {} + arrays_keys = {} + for key in infos: + if key in keydict: + info_keys[key[:-4]] = keydict[key] + for key in arrays: + if key in keydict: + arrays_keys[key[:-4]] = keydict[key] + + # automagically add properties for embeddings + if keydict.get("embedding_specs") is not None: + for embed_name, embed_spec in keydict["embedding_specs"].items(): + key = embed_spec.get("key", embed_name) + if embed_spec["per"] == "atom": + arrays_keys[embed_name] = key + elif embed_spec["per"] == "graph": + info_keys[embed_name] = key + else: + raise ValueError( + f"Unsupported embedding_specs per {embed_spec['per']} for {embed_name}" + ) + + keyspec.update(info_keys=info_keys, arrays_keys=arrays_keys) + return keyspec + + +@dataclass +class Configuration: + atomic_numbers: np.ndarray + positions: Positions # Angstrom + properties: Dict[str, Any] + property_weights: Dict[str, float] + cell: Optional[Cell] = None + pbc: Optional[Pbc] = None + + weight: float = 1.0 # weight of config in loss + config_type: str = DEFAULT_CONFIG_TYPE # config_type of config + head: str = "Default" # head used to compute the config + + +Configurations = List[Configuration] + + +def random_train_valid_split( + items: Sequence, + valid_fraction: float, + seed: int, + work_dir: str, + prefix: Optional[str] = None, +) -> Tuple[List, List]: + assert 0.0 < valid_fraction < 1.0 + + size = len(items) + # guarantee at least one validation, mostly for tests with tiny fitting databases + assert size > 1 + train_size = min(size - int(valid_fraction * size), size - 1) + + indices = list(range(size)) + rng = np.random.default_rng(seed) + rng.shuffle(indices) + if len(indices[train_size:]) < 10: + logging.info( + f"Using random {100 * valid_fraction:.0f}% of training set for validation with following indices: {indices[train_size:]}" + ) + else: + # Save indices to file (optionally prefixed with experiment name) + filename = f"valid_indices_{seed}.txt" + if prefix is not None and len(prefix) > 0: + filename = f"{prefix}_" + filename + path = os.path.join(work_dir, filename) + with open(path, "w", encoding="utf-8") as f: + for index in indices[train_size:]: + f.write(f"{index}\n") + + logging.info( + f"Using random {100 * valid_fraction:.0f}% of training set for validation with indices saved in: {path}" + ) + + return ( + [items[i] for i in indices[:train_size]], + [items[i] for i in indices[train_size:]], + ) + + +def config_from_atoms_list( + atoms_list: List[ase.Atoms], + key_specification: KeySpecification, + config_type_weights: Optional[Dict[str, float]] = None, + head_name: str = "Default", +) -> Configurations: + """Convert list of ase.Atoms into Configurations""" + if config_type_weights is None: + config_type_weights = DEFAULT_CONFIG_TYPE_WEIGHTS + + all_configs = [] + for atoms in atoms_list: + all_configs.append( + config_from_atoms( + atoms, + key_specification=key_specification, + config_type_weights=config_type_weights, + head_name=head_name, + ) + ) + return all_configs + + +def config_from_atoms( + atoms: ase.Atoms, + key_specification: KeySpecification = KeySpecification(), + config_type_weights: Optional[Dict[str, float]] = None, + head_name: str = "Default", +) -> Configuration: + """Convert ase.Atoms to Configuration""" + if config_type_weights is None: + config_type_weights = DEFAULT_CONFIG_TYPE_WEIGHTS + + atomic_numbers = np.array( + [ase.data.atomic_numbers[symbol] for symbol in atoms.symbols] + ) + pbc = tuple(atoms.get_pbc().tolist()) + cell = np.array(atoms.get_cell()) + config_type = atoms.info.get("config_type", "Default") + weight = atoms.info.get("config_weight", 1.0) * config_type_weights.get( + config_type, 1.0 + ) + + properties = {} + property_weights = {} + for name in list(key_specification.arrays_keys) + list(key_specification.info_keys): + property_weights[name] = atoms.info.get(f"config_{name}_weight", 1.0) + + for name, atoms_key in key_specification.info_keys.items(): + properties[name] = atoms.info.get(atoms_key, None) + if not atoms_key in atoms.info: + property_weights[name] = 0.0 + + for name, atoms_key in key_specification.arrays_keys.items(): + properties[name] = atoms.arrays.get(atoms_key, None) + if not atoms_key in atoms.arrays: + property_weights[name] = 0.0 + + return Configuration( + atomic_numbers=atomic_numbers, + positions=atoms.get_positions(), + properties=properties, + weight=weight, + property_weights=property_weights, + head=head_name, + config_type=config_type, + pbc=pbc, + cell=cell, + ) + + +def test_config_types( + test_configs: Configurations, +) -> List[Tuple[str, List[Configuration]]]: + """Split test set based on config_type-s""" + test_by_ct = [] + all_cts = [] + for conf in test_configs: + if conf.head is None: + conf.head = "" + config_type_name = conf.config_type + "_" + conf.head + if config_type_name not in all_cts: + all_cts.append(config_type_name) + test_by_ct.append((config_type_name, [conf])) + else: + ind = all_cts.index(config_type_name) + test_by_ct[ind][1].append(conf) + return test_by_ct + + +def load_from_xyz( + file_path: str, + key_specification: KeySpecification, + head_name: str = "Default", + config_type_weights: Optional[Dict] = None, + extract_atomic_energies: bool = False, + keep_isolated_atoms: bool = False, + no_data_ok: bool = False, +) -> Tuple[Dict[int, float], Configurations]: + atoms_list = ase.io.read(file_path, index=":") + energy_key = key_specification.info_keys["energy"] + forces_key = key_specification.arrays_keys["forces"] + stress_key = key_specification.info_keys["stress"] + head_key = key_specification.info_keys["head"] + original_energy_key = energy_key + original_forces_key = forces_key + original_stress_key = stress_key + if energy_key == "energy": + logging.warning( + "Since ASE version 3.23.0b1, using energy_key 'energy' is no longer safe when communicating between MACE and ASE. We recommend using a different key, rewriting 'energy' to 'REF_energy'. You need to use --energy_key='REF_energy' to specify the chosen key name." + ) + key_specification.info_keys["energy"] = "REF_energy" + for atoms in atoms_list: + try: + # print("OK") + atoms.info["REF_energy"] = atoms.get_potential_energy() + # print("atoms.info['REF_energy']:", atoms.info["REF_energy"]) + except Exception as e: # pylint: disable=W0703 + logging.error(f"Failed to extract energy: {e}") + atoms.info["REF_energy"] = None + if forces_key == "forces": + logging.warning( + "Since ASE version 3.23.0b1, using forces_key 'forces' is no longer safe when communicating between MACE and ASE. We recommend using a different key, rewriting 'forces' to 'REF_forces'. You need to use --forces_key='REF_forces' to specify the chosen key name." + ) + key_specification.arrays_keys["forces"] = "REF_forces" + for atoms in atoms_list: + try: + atoms.arrays["REF_forces"] = atoms.get_forces() + except Exception as e: # pylint: disable=W0703 + logging.error(f"Failed to extract forces: {e}") + atoms.arrays["REF_forces"] = None + if stress_key == "stress": + logging.warning( + "Since ASE version 3.23.0b1, using stress_key 'stress' is no longer safe when communicating between MACE and ASE. We recommend using a different key, rewriting 'stress' to 'REF_stress'. You need to use --stress_key='REF_stress' to specify the chosen key name." + ) + key_specification.info_keys["stress"] = "REF_stress" + for atoms in atoms_list: + try: + atoms.info["REF_stress"] = atoms.get_stress() + except Exception as e: # pylint: disable=W0703 + atoms.info["REF_stress"] = None + + final_energy_key = key_specification.info_keys["energy"] + final_forces_key = key_specification.arrays_keys["forces"] + final_dipole_key = key_specification.info_keys.get("dipole", "REF_dipole") + has_energy = any(final_energy_key in atoms.info for atoms in atoms_list) + has_forces = any(final_forces_key in atoms.arrays for atoms in atoms_list) + has_dipole = any(final_dipole_key in atoms.info for atoms in atoms_list) + + if not has_energy and not has_forces and not has_dipole: + msg = f"None of '{final_energy_key}', '{final_forces_key}', and '{final_dipole_key}' found in '{file_path}'." + if no_data_ok: + logging.warning(msg + " Continuing because no_data_ok=True was passed in.") + else: + raise ValueError( + msg + + " Please change the key names in the command line arguments or ensure that the file contains the required data." + ) + if not has_energy: + logging.warning( + f"No energies found with key '{final_energy_key}' in '{file_path}'. If this is unexpected, please change the key name in the command line arguments or ensure that the file contains the required data." + ) + if not has_forces: + logging.warning( + f"No forces found with key '{final_forces_key}' in '{file_path}'. If this is unexpected, Please change the key name in the command line arguments or ensure that the file contains the required data." + ) + + if not isinstance(atoms_list, list): + atoms_list = [atoms_list] + + atomic_energies_dict = {} + if extract_atomic_energies: + atoms_without_iso_atoms = [] + + for idx, atoms in enumerate(atoms_list): + atoms.info[head_key] = head_name + isolated_atom_config = ( + len(atoms) == 1 and atoms.info.get("config_type") == "IsolatedAtom" + ) + if isolated_atom_config: + atomic_number = int(atoms.get_atomic_numbers()[0]) + if energy_key in atoms.info.keys(): + atomic_energies_dict[atomic_number] = float(atoms.info[energy_key]) + else: + logging.warning( + f"Configuration '{idx}' is marked as 'IsolatedAtom' " + "but does not contain an energy. Zero energy will be used." + ) + atomic_energies_dict[atomic_number] = 0.0 + else: + atoms_without_iso_atoms.append(atoms) + + if len(atomic_energies_dict) > 0: + logging.info("Using isolated atom energies from training file") + if not keep_isolated_atoms: + atoms_list = atoms_without_iso_atoms + + for atoms in atoms_list: + atoms.info[head_key] = head_name + + configs = config_from_atoms_list( + atoms_list, + config_type_weights=config_type_weights, + key_specification=key_specification, + head_name=head_name, + ) + key_specification.info_keys["energy"] = original_energy_key + key_specification.arrays_keys["forces"] = original_forces_key + key_specification.info_keys["stress"] = original_stress_key + return atomic_energies_dict, configs + + +def compute_average_E0s( + collections_train: Configurations, z_table: AtomicNumberTable +) -> Dict[int, float]: + """ + Function to compute the average interaction energy of each chemical element + returns dictionary of E0s + """ + len_train = len(collections_train) + len_zs = len(z_table) + A = np.zeros((len_train, len_zs)) + B = np.zeros(len_train) + for i in range(len_train): + B[i] = collections_train[i].properties["energy"] + for j, z in enumerate(z_table.zs): + A[i, j] = np.count_nonzero(collections_train[i].atomic_numbers == z) + try: + E0s = np.linalg.lstsq(A, B, rcond=None)[0] + atomic_energies_dict = {} + for i, z in enumerate(z_table.zs): + atomic_energies_dict[z] = E0s[i] + except np.linalg.LinAlgError: + logging.error( + "Failed to compute E0s using least squares regression, using the same for all atoms" + ) + atomic_energies_dict = {} + for i, z in enumerate(z_table.zs): + atomic_energies_dict[z] = 0.0 + return atomic_energies_dict + + +def save_dataset_as_HDF5(dataset: List, out_name: str) -> None: + with h5py.File(out_name, "w") as f: + for i, data in enumerate(dataset): + save_AtomicData_to_HDF5(data, i, f) + + +def save_AtomicData_to_HDF5(data, i, h5_file) -> None: + grp = h5_file.create_group(f"config_{i}") + grp["num_nodes"] = data.num_nodes + grp["edge_index"] = data.edge_index + grp["positions"] = data.positions + grp["shifts"] = data.shifts + grp["unit_shifts"] = data.unit_shifts + grp["cell"] = data.cell + grp["node_attrs"] = data.node_attrs + grp["weight"] = data.weight + grp["energy_weight"] = data.energy_weight + grp["forces_weight"] = data.forces_weight + grp["stress_weight"] = data.stress_weight + grp["virials_weight"] = data.virials_weight + grp["forces"] = data.forces + grp["energy"] = data.energy + grp["stress"] = data.stress + grp["virials"] = data.virials + grp["dipole"] = data.dipole + grp["charges"] = data.charges + grp["polarizability"] = data.polarizability + grp["head"] = data.head + + +def save_configurations_as_HDF5(configurations: Configurations, _, h5_file) -> None: + grp = h5_file.create_group("config_batch_0") + for j, config in enumerate(configurations): + subgroup_name = f"config_{j}" + subgroup = grp.create_group(subgroup_name) + subgroup["atomic_numbers"] = write_value(config.atomic_numbers) + subgroup["positions"] = write_value(config.positions) + properties_subgrp = subgroup.create_group("properties") + for key, value in config.properties.items(): + properties_subgrp[key] = write_value(value) + subgroup["cell"] = write_value(config.cell) + subgroup["pbc"] = write_value(config.pbc) + subgroup["weight"] = write_value(config.weight) + weights_subgrp = subgroup.create_group("property_weights") + for key, value in config.property_weights.items(): + weights_subgrp[key] = write_value(value) + subgroup["config_type"] = write_value(config.config_type) + + +def write_value(value): + return value if value is not None else "None" diff --git a/models/mace/mace/modules/__init__.py b/models/mace/mace/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b23524eeadb34efd358d98a30597b7ced7d7c63 --- /dev/null +++ b/models/mace/mace/modules/__init__.py @@ -0,0 +1,128 @@ +from typing import Callable, Dict, Optional, Type + +import torch + +from .blocks import ( + AtomicEnergiesBlock, + EquivariantProductBasisBlock, + InteractionBlock, + LinearDipolePolarReadoutBlock, + LinearDipoleReadoutBlock, + LinearNodeEmbeddingBlock, + LinearReadoutBlock, + NonLinearBiasReadoutBlock, + NonLinearDipolePolarReadoutBlock, + NonLinearDipoleReadoutBlock, + NonLinearReadoutBlock, + RadialEmbeddingBlock, + RealAgnosticAttResidualInteractionBlock, + RealAgnosticDensityInteractionBlock, + RealAgnosticDensityResidualInteractionBlock, + RealAgnosticInteractionBlock, + RealAgnosticResidualInteractionBlock, + RealAgnosticResidualNonLinearInteractionBlock, + ScaleShiftBlock, +) +from .loss import ( + DipolePolarLoss, + DipoleSingleLoss, + UniversalLoss, + WeightedEnergyForcesDipoleLoss, + WeightedEnergyForcesL1L2Loss, + WeightedEnergyForcesLoss, + WeightedEnergyForcesStressLoss, + WeightedEnergyForcesVirialsLoss, + WeightedForcesLoss, + WeightedHuberEnergyForcesStressLoss, + WeightedEnergyForcesMAELoss, # NOTE Added +) +from .models import ( + MACE, + AtomicDielectricMACE, + AtomicDipolesMACE, + EnergyDipolesMACE, + ScaleShiftMACE, +) +from .radial import BesselBasis, GaussianBasis, PolynomialCutoff, ZBLBasis +from .symmetric_contraction import SymmetricContraction +from .utils import ( + compute_avg_num_neighbors, + compute_dielectric_gradients, + compute_fixed_charge_dipole, + compute_fixed_charge_dipole_polar, + compute_mean_rms_energy_forces, + compute_mean_std_atomic_inter_energy, + compute_rms_dipoles, + compute_statistics, +) + +interaction_classes: Dict[str, Type[InteractionBlock]] = { + "RealAgnosticResidualInteractionBlock": RealAgnosticResidualInteractionBlock, + "RealAgnosticAttResidualInteractionBlock": RealAgnosticAttResidualInteractionBlock, + "RealAgnosticInteractionBlock": RealAgnosticInteractionBlock, + "RealAgnosticDensityInteractionBlock": RealAgnosticDensityInteractionBlock, + "RealAgnosticDensityResidualInteractionBlock": RealAgnosticDensityResidualInteractionBlock, + "RealAgnosticResidualNonLinearInteractionBlock": RealAgnosticResidualNonLinearInteractionBlock, +} + +readout_classes: Dict[str, Type[LinearReadoutBlock]] = { + "LinearReadoutBlock": LinearReadoutBlock, + "LinearDipoleReadoutBlock": LinearDipoleReadoutBlock, + "NonLinearDipoleReadoutBlock": NonLinearDipoleReadoutBlock, + "NonLinearReadoutBlock": NonLinearReadoutBlock, + "NonLinearBiasReadoutBlock": NonLinearBiasReadoutBlock, +} + +scaling_classes: Dict[str, Callable] = { + "std_scaling": compute_mean_std_atomic_inter_energy, + "rms_forces_scaling": compute_mean_rms_energy_forces, + "rms_dipoles_scaling": compute_rms_dipoles, +} + +gate_dict: Dict[str, Optional[Callable]] = { + "abs": torch.abs, + "tanh": torch.tanh, + "silu": torch.nn.functional.silu, + "None": None, +} + +__all__ = [ + "AtomicEnergiesBlock", + "RadialEmbeddingBlock", + "ZBLBasis", + "LinearNodeEmbeddingBlock", + "LinearReadoutBlock", + "EquivariantProductBasisBlock", + "ScaleShiftBlock", + "LinearDipoleReadoutBlock", + "LinearDipolePolarReadoutBlock", + "NonLinearDipoleReadoutBlock", + "NonLinearDipolePolarReadoutBlock", + "InteractionBlock", + "NonLinearReadoutBlock", + "PolynomialCutoff", + "BesselBasis", + "GaussianBasis", + "MACE", + "ScaleShiftMACE", + "AtomicDipolesMACE", + "AtomicDielectricMACE", + "EnergyDipolesMACE", + "WeightedEnergyForcesLoss", + "WeightedForcesLoss", + "WeightedEnergyForcesVirialsLoss", + "WeightedEnergyForcesStressLoss", + "DipoleSingleLoss", + "WeightedEnergyForcesDipoleLoss", + "WeightedHuberEnergyForcesStressLoss", + "UniversalLoss", + "WeightedEnergyForcesL1L2Loss", + "SymmetricContraction", + "interaction_classes", + "compute_mean_std_atomic_inter_energy", + "compute_avg_num_neighbors", + "compute_statistics", + "compute_fixed_charge_dipole", + "compute_fixed_charge_dipole_polar", + "compute_dielectric_gradients", +] diff --git a/models/mace/mace/modules/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/modules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98a7743ef8d1737235874fd0be68c97addcc5e41 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/blocks.cpython-310.pyc b/models/mace/mace/modules/__pycache__/blocks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66ab898005c4792d0f4882ab58bd4d1c27681924 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/blocks.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/embeddings.cpython-310.pyc b/models/mace/mace/modules/__pycache__/embeddings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ea40b8bb67b5cb6ea0fdf2983343d33912c4726 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/embeddings.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/irreps_tools.cpython-310.pyc b/models/mace/mace/modules/__pycache__/irreps_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de0793c19f393e6f004904b2499cda1407ae9430 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/irreps_tools.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/loss.cpython-310.pyc b/models/mace/mace/modules/__pycache__/loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dcda730e1a301f169f840b29f0f1853d2478a00 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/loss.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/models.cpython-310.pyc b/models/mace/mace/modules/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edfe35269e1cd696a8c226c9ff415068a63abf6c Binary files /dev/null and b/models/mace/mace/modules/__pycache__/models.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/radial.cpython-310.pyc b/models/mace/mace/modules/__pycache__/radial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc05fc09263e66fb79dd9e748337270311dd0c6 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/radial.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/symmetric_contraction.cpython-310.pyc b/models/mace/mace/modules/__pycache__/symmetric_contraction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10f1ee6b34e05ce0b858d272598e3600b5a64bf Binary files /dev/null and b/models/mace/mace/modules/__pycache__/symmetric_contraction.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/utils.cpython-310.pyc b/models/mace/mace/modules/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ff2fdfa520f9e8fe018f19bf3d0a1ee35ac66e7 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/utils.cpython-310.pyc differ diff --git a/models/mace/mace/modules/__pycache__/wrapper_ops.cpython-310.pyc b/models/mace/mace/modules/__pycache__/wrapper_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5860c8e7c8136172689807ecbc341de824f2436 Binary files /dev/null and b/models/mace/mace/modules/__pycache__/wrapper_ops.cpython-310.pyc differ diff --git a/models/mace/mace/modules/blocks.py b/models/mace/mace/modules/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..caa4180df4775adacc9092f75b18cce8472ddbd6 --- /dev/null +++ b/models/mace/mace/modules/blocks.py @@ -0,0 +1,1333 @@ +########################################################################################### +# Elementary Block for Building O(3) Equivariant Higher Order Message Passing Neural Network +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from abc import abstractmethod +from typing import Any, Callable, List, Optional, Tuple, Union + +import numpy as np +import torch.nn.functional +from e3nn import nn, o3 +from e3nn.util.jit import compile_mode + +from mace.modules.wrapper_ops import ( + CuEquivarianceConfig, + FullyConnectedTensorProduct, + Linear, + OEQConfig, + SymmetricContractionWrapper, + TensorProduct, + TransposeIrrepsLayoutWrapper, +) +from mace.tools.compile import simplify_if_compile +from mace.tools.scatter import scatter_sum +from mace.tools.utils import LAMMPS_MP + +from .irreps_tools import mask_head, reshape_irreps, tp_out_irreps_with_instructions +from .radial import ( + AgnesiTransform, + BesselBasis, + ChebychevBasis, + GaussianBasis, + PolynomialCutoff, + RadialMLP, + SoftTransform, +) + + +@compile_mode("script") +class LinearNodeEmbeddingBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + irreps_out: o3.Irreps, + cueq_config: Optional[CuEquivarianceConfig] = None, + ): + super().__init__() + self.linear = Linear( + irreps_in=irreps_in, irreps_out=irreps_out, cueq_config=cueq_config + ) + + def forward( + self, + node_attrs: torch.Tensor, + ) -> torch.Tensor: # [n_nodes, irreps] + return self.linear(node_attrs) + + +@compile_mode("script") +class LinearReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + irrep_out: o3.Irreps = o3.Irreps("0e"), + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.linear = Linear( + irreps_in=irreps_in, irreps_out=irrep_out, cueq_config=cueq_config + ) + + def forward( + self, + x: torch.Tensor, + heads: Optional[torch.Tensor] = None, # pylint: disable=unused-argument + ) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + return self.linear(x) # [n_nodes, 1] + + +@compile_mode("script") +class NonLinearReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + MLP_irreps: o3.Irreps, + gate: Optional[Callable], + irrep_out: o3.Irreps = o3.Irreps("0e"), + num_heads: int = 1, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.hidden_irreps = MLP_irreps + self.num_heads = num_heads + self.linear_1 = Linear( + irreps_in=irreps_in, irreps_out=self.hidden_irreps, cueq_config=cueq_config + ) + self.non_linearity = simplify_if_compile(nn.Activation)( + irreps_in=self.hidden_irreps, acts=[gate] + ) + self.linear_2 = Linear( + irreps_in=self.hidden_irreps, irreps_out=irrep_out, cueq_config=cueq_config + ) + + def forward( + self, x: torch.Tensor, heads: Optional[torch.Tensor] = None + ) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + x = self.non_linearity(self.linear_1(x)) + if hasattr(self, "num_heads"): + if self.num_heads > 1 and heads is not None: + x = mask_head(x, heads, self.num_heads) + return self.linear_2(x) # [n_nodes, len(heads)] + + +@simplify_if_compile +@compile_mode("script") +class NonLinearBiasReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + MLP_irreps: o3.Irreps, + gate: Optional[Callable], + irrep_out: o3.Irreps = o3.Irreps("0e"), + num_heads: int = 1, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.hidden_irreps = MLP_irreps + self.num_heads = num_heads + self.linear_1 = Linear( + irreps_in=irreps_in, irreps_out=self.hidden_irreps, cueq_config=cueq_config + ) + self.non_linearity = nn.Activation(irreps_in=self.hidden_irreps, acts=[gate]) + self.linear_mid = o3.Linear( + irreps_in=self.hidden_irreps, irreps_out=self.hidden_irreps, biases=True + ) + self.linear_2 = o3.Linear( + irreps_in=self.hidden_irreps, irreps_out=irrep_out, biases=True + ) + + def forward( + self, x: torch.Tensor, heads: Optional[torch.Tensor] = None + ) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + x = self.non_linearity(self.linear_1(x)) + if hasattr(self, "num_heads"): + if self.num_heads > 1 and heads is not None: + x = mask_head(x, heads, self.num_heads) + x = self.non_linearity(self.linear_mid(x)) + if hasattr(self, "num_heads"): + if self.num_heads > 1 and heads is not None: + x = mask_head(x, heads, self.num_heads) + return self.linear_2(x) # [n_nodes, len(heads)] + + +@compile_mode("script") +class LinearDipoleReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + dipole_only: bool = False, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + if dipole_only: + self.irreps_out = o3.Irreps("1x1o") + else: + self.irreps_out = o3.Irreps("1x0e + 1x1o") + self.linear = Linear( + irreps_in=irreps_in, irreps_out=self.irreps_out, cueq_config=cueq_config + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + return self.linear(x) # [n_nodes, 1] + + +@compile_mode("script") +class NonLinearDipoleReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + MLP_irreps: o3.Irreps, + gate: Callable, + dipole_only: bool = False, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.hidden_irreps = MLP_irreps + if dipole_only: + self.irreps_out = o3.Irreps("1x1o") + else: + self.irreps_out = o3.Irreps("1x0e + 1x1o") + irreps_scalars = o3.Irreps( + [(mul, ir) for mul, ir in MLP_irreps if ir.l == 0 and ir in self.irreps_out] + ) + irreps_gated = o3.Irreps( + [(mul, ir) for mul, ir in MLP_irreps if ir.l > 0 and ir in self.irreps_out] + ) + irreps_gates = o3.Irreps([mul, "0e"] for mul, _ in irreps_gated) + self.equivariant_nonlin = nn.Gate( + irreps_scalars=irreps_scalars, + act_scalars=[gate for _, ir in irreps_scalars], + irreps_gates=irreps_gates, + act_gates=[gate] * len(irreps_gates), + irreps_gated=irreps_gated, + ) + self.irreps_nonlin = self.equivariant_nonlin.irreps_in.simplify() + self.linear_1 = Linear( + irreps_in=irreps_in, irreps_out=self.irreps_nonlin, cueq_config=cueq_config + ) + self.linear_2 = Linear( + irreps_in=self.hidden_irreps, + irreps_out=self.irreps_out, + cueq_config=cueq_config, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + x = self.equivariant_nonlin(self.linear_1(x)) + return self.linear_2(x) # [n_nodes, 1] + + +@compile_mode("script") +class LinearDipolePolarReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + use_polarizability: bool = True, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + if use_polarizability: + print("You will calculate the polarizability and dipole.") + self.irreps_out = o3.Irreps("2x0e + 1x1o + 1x2e") + else: + raise ValueError( + "Invalid configuration for LinearDipolePolarReadoutBlock: " + "use_polarizability must be either True." + "If you want to calculate only the dipole, use AtomicDipolesMACE." + ) + + self.linear = Linear( + irreps_in=irreps_in, irreps_out=self.irreps_out, cueq_config=cueq_config + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + y = self.linear(x) # [n_nodes, 1] + return y # [n_nodes, 1] + + +@compile_mode("script") +class NonLinearDipolePolarReadoutBlock(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + MLP_irreps: o3.Irreps, + gate: Callable, + use_polarizability: bool = True, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.hidden_irreps = MLP_irreps + if use_polarizability: + print("You will calculate the polarizability and dipole.") + self.irreps_out = o3.Irreps("2x0e + 1x1o + 1x2e") + else: + raise ValueError( + "Invalid configuration for NonLinearDipolePolarReadoutBlock: " + "use_polarizability must be either True." + "If you want to calculate only the dipole, use AtomicDipolesMACE." + ) + irreps_scalars = o3.Irreps( + [(mul, ir) for mul, ir in MLP_irreps if ir.l == 0 and ir in self.irreps_out] + ) + irreps_gated = o3.Irreps( + [(mul, ir) for mul, ir in MLP_irreps if ir.l > 0 and ir in self.irreps_out] + ) + irreps_gates = o3.Irreps([mul, "0e"] for mul, _ in irreps_gated) + self.equivariant_nonlin = nn.Gate( + irreps_scalars=irreps_scalars, + act_scalars=[gate for _, ir in irreps_scalars], + irreps_gates=irreps_gates, + act_gates=[gate] * len(irreps_gates), + irreps_gated=irreps_gated, + ) + self.irreps_nonlin = self.equivariant_nonlin.irreps_in.simplify() + self.linear_1 = Linear( + irreps_in=irreps_in, irreps_out=self.irreps_nonlin, cueq_config=cueq_config + ) + self.linear_2 = Linear( + irreps_in=self.hidden_irreps, + irreps_out=self.irreps_out, + cueq_config=cueq_config, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ] + x = self.equivariant_nonlin(self.linear_1(x)) + return self.linear_2(x) # [n_nodes, 1] + + +@compile_mode("script") +class AtomicEnergiesBlock(torch.nn.Module): + atomic_energies: torch.Tensor + + def __init__(self, atomic_energies: Union[np.ndarray, torch.Tensor]): + super().__init__() + # assert len(atomic_energies.shape) == 1 + + self.register_buffer( + "atomic_energies", + torch.tensor(atomic_energies, dtype=torch.get_default_dtype()), + ) # [n_elements, n_heads] + + def forward( + self, x: torch.Tensor # one-hot of elements [..., n_elements] + ) -> torch.Tensor: # [..., ] + + return torch.matmul(x, torch.atleast_2d(self.atomic_energies).T) + + def __repr__(self): + formatted_energies = ", ".join( + [ + "[" + ", ".join([f"{x:.4f}" for x in group]) + "]" + for group in torch.atleast_2d(self.atomic_energies) + ] + ) + return f"{self.__class__.__name__}(energies=[{formatted_energies}])" + + +@compile_mode("script") +class RadialEmbeddingBlock(torch.nn.Module): + def __init__( + self, + r_max: float, + num_bessel: int, + num_polynomial_cutoff: int, + radial_type: str = "bessel", + distance_transform: str = "None", + apply_cutoff: bool = True, + ): + super().__init__() + if radial_type == "bessel": + self.bessel_fn = BesselBasis(r_max=r_max, num_basis=num_bessel) + elif radial_type == "gaussian": + self.bessel_fn = GaussianBasis(r_max=r_max, num_basis=num_bessel) + elif radial_type == "chebyshev": + self.bessel_fn = ChebychevBasis(r_max=r_max, num_basis=num_bessel) + if distance_transform == "Agnesi": + self.distance_transform = AgnesiTransform() + elif distance_transform == "Soft": + self.distance_transform = SoftTransform() + self.cutoff_fn = PolynomialCutoff(r_max=r_max, p=num_polynomial_cutoff) + self.out_dim = num_bessel + self.apply_cutoff = apply_cutoff + + def forward( + self, + edge_lengths: torch.Tensor, # [n_edges, 1] + node_attrs: torch.Tensor, + edge_index: torch.Tensor, + atomic_numbers: torch.Tensor, + ): + cutoff = self.cutoff_fn(edge_lengths) # [n_edges, 1] + if hasattr(self, "distance_transform"): + edge_lengths = self.distance_transform( + edge_lengths, node_attrs, edge_index, atomic_numbers + ) + radial = self.bessel_fn(edge_lengths) # [n_edges, n_basis] + if hasattr(self, "apply_cutoff"): + if not self.apply_cutoff: + return radial, cutoff + return radial * cutoff, None # [n_edges, n_basis], [n_edges, 1] + + +@compile_mode("script") +class EquivariantProductBasisBlock(torch.nn.Module): + def __init__( + self, + node_feats_irreps: o3.Irreps, + target_irreps: o3.Irreps, + correlation: int, + use_sc: bool = True, + num_elements: Optional[int] = None, + use_agnostic_product: bool = False, + use_reduced_cg: Optional[bool] = None, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, + ) -> None: + super().__init__() + + self.use_sc = use_sc + self.use_agnostic_product = use_agnostic_product + if self.use_agnostic_product: + num_elements = 1 + self.symmetric_contractions = SymmetricContractionWrapper( + irreps_in=node_feats_irreps, + irreps_out=target_irreps, + correlation=correlation, + num_elements=num_elements, + use_reduced_cg=use_reduced_cg, + cueq_config=cueq_config, + oeq_config=oeq_config, + ) + # Update linear + self.linear = Linear( + target_irreps, + target_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=cueq_config, + ) + self.cueq_config = cueq_config + + def forward( + self, + node_feats: torch.Tensor, + sc: Optional[torch.Tensor], + node_attrs: torch.Tensor, + ) -> torch.Tensor: + use_cueq = False + use_cueq_mul_ir = False + if hasattr(self, "use_agnostic_product"): + if self.use_agnostic_product: + node_attrs = torch.ones( + (node_feats.shape[0], 1), + dtype=node_feats.dtype, + device=node_feats.device, + ) + if hasattr(self, "cueq_config"): + if self.cueq_config is not None: + if self.cueq_config.enabled and ( + self.cueq_config.optimize_all or self.cueq_config.optimize_symmetric + ): + use_cueq = True + if self.cueq_config.layout_str == "mul_ir": + use_cueq_mul_ir = True + if use_cueq: + if use_cueq_mul_ir: + node_feats = torch.transpose(node_feats, 1, 2) + index_attrs = torch.nonzero(node_attrs)[:, 1].int() + node_feats = self.symmetric_contractions( + node_feats.flatten(1), + index_attrs, + ) + else: + node_feats = self.symmetric_contractions(node_feats, node_attrs) + if self.use_sc and sc is not None: + return self.linear(node_feats) + sc + return self.linear(node_feats) + + +@compile_mode("script") +class InteractionBlock(torch.nn.Module): + def __init__( + self, + node_attrs_irreps: o3.Irreps, + node_feats_irreps: o3.Irreps, + edge_attrs_irreps: o3.Irreps, + edge_feats_irreps: o3.Irreps, + target_irreps: o3.Irreps, + hidden_irreps: o3.Irreps, + avg_num_neighbors: float, + edge_irreps: Optional[o3.Irreps] = None, + radial_MLP: Optional[List[int]] = None, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, + ) -> None: + super().__init__() + self.node_attrs_irreps = node_attrs_irreps + self.node_feats_irreps = node_feats_irreps + self.edge_attrs_irreps = edge_attrs_irreps + self.edge_feats_irreps = edge_feats_irreps + self.target_irreps = target_irreps + self.hidden_irreps = hidden_irreps + self.avg_num_neighbors = avg_num_neighbors + if radial_MLP is None: + radial_MLP = [64, 64, 64] + if edge_irreps is None: + edge_irreps = self.node_feats_irreps + self.radial_MLP = radial_MLP + self.edge_irreps = edge_irreps + self.cueq_config = cueq_config + self.oeq_config = oeq_config + if self.oeq_config and self.oeq_config.conv_fusion: + self.conv_fusion = self.oeq_config.conv_fusion + if self.cueq_config and self.cueq_config.conv_fusion: + self.conv_fusion = self.cueq_config.conv_fusion + self._setup() + + @abstractmethod + def _setup(self) -> None: + raise NotImplementedError + + def handle_lammps( + self, + node_feats: torch.Tensor, + lammps_class: Optional[Any], + lammps_natoms: Tuple[int, int], + first_layer: bool, + ) -> torch.Tensor: # noqa: D401 – internal helper + if lammps_class is None or first_layer or torch.jit.is_scripting(): + return node_feats + _, n_total = lammps_natoms + pad = torch.zeros( + (n_total, node_feats.shape[1]), + dtype=node_feats.dtype, + device=node_feats.device, + ) + node_feats = torch.cat((node_feats, pad), dim=0) + node_feats = LAMMPS_MP.apply(node_feats, lammps_class) + return node_feats + + def truncate_ghosts( + self, tensor: torch.Tensor, n_real: Optional[int] = None + ) -> torch.Tensor: + """Truncate the tensor to only keep the real atoms in case of presence of ghost atoms during multi-GPU MD simulations.""" + return tensor[:n_real] if n_real is not None else tensor + + @abstractmethod + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + ) -> torch.Tensor: + raise NotImplementedError + + +nonlinearities = {1: torch.nn.functional.silu, -1: torch.tanh} + + +@compile_mode("script") +class RealAgnosticInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + if not hasattr(self, "oeq_config"): + self.oeq_config = None + + # First linear + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + oeq_config=self.oeq_config, + ) + + # Convolution weights + input_dim = self.edge_feats_irreps.num_irreps + self.conv_tp_weights = nn.FullyConnectedNet( + [input_dim] + self.radial_MLP + [self.conv_tp.weight_numel], + torch.nn.functional.silu, + ) + + # Linear + self.irreps_out = self.target_irreps + self.linear = Linear( + irreps_mid, + self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Selector TensorProduct + self.skip_tp = FullyConnectedTensorProduct( + self.irreps_out, + self.node_attrs_irreps, + self.irreps_out, + cueq_config=self.cueq_config, + ) + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + lammps_class: Optional[Any] = None, + first_layer: bool = False, + ) -> Tuple[torch.Tensor, None]: + n_real = lammps_natoms[0] if lammps_class is not None else None + node_feats = self.linear_up(node_feats) + node_feats = self.handle_lammps( + node_feats, + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + first_layer=first_layer, + ) + tp_weights = self.conv_tp_weights(edge_feats) + if cutoff is not None: + tp_weights = tp_weights * cutoff + + message = None + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats[edge_index[0]], edge_attrs, tp_weights + ) # [n_nodes, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=node_feats.shape[0] + ) + message = self.truncate_ghosts(message, n_real) + node_attrs = self.truncate_ghosts(node_attrs, n_real) + message = self.linear(message) / self.avg_num_neighbors + message = self.skip_tp(message, node_attrs) + return ( + self.reshape(message), + None, + ) # [n_nodes, channels, (lmax + 1)**2] + + +@compile_mode("script") +class RealAgnosticResidualInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + if not hasattr(self, "oeq_config"): + self.oeq_config = None + + # First linear + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + oeq_config=self.oeq_config, + ) + + # Convolution weights + input_dim = self.edge_feats_irreps.num_irreps + self.conv_tp_weights = nn.FullyConnectedNet( + [input_dim] + self.radial_MLP + [self.conv_tp.weight_numel], + torch.nn.functional.silu, # gate + ) + + # Linear + self.irreps_out = self.target_irreps + self.linear = Linear( + irreps_mid, + self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Selector TensorProduct + self.skip_tp = FullyConnectedTensorProduct( + self.node_feats_irreps, + self.node_attrs_irreps, + self.hidden_irreps, + cueq_config=self.cueq_config, + ) + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_class: Optional[Any] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + first_layer: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + n_real = lammps_natoms[0] if lammps_class is not None else None + sc = self.skip_tp(node_feats, node_attrs) + node_feats = self.linear_up(node_feats) + node_feats = self.handle_lammps( + node_feats, + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + first_layer=first_layer, + ) + tp_weights = self.conv_tp_weights(edge_feats) + if cutoff is not None: + tp_weights = tp_weights * cutoff + message = None + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats[edge_index[0]], edge_attrs, tp_weights + ) # [n_nodes, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=node_feats.shape[0] + ) + message = self.truncate_ghosts(message, n_real) + node_attrs = self.truncate_ghosts(node_attrs, n_real) + sc = self.truncate_ghosts(sc, n_real) + message = self.linear(message) / self.avg_num_neighbors + return ( + self.reshape(message), + sc, + ) # [n_nodes, channels, (lmax + 1)**2] + + +@compile_mode("script") +class RealAgnosticDensityInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + if not hasattr(self, "oeq_config"): + self.oeq_config = None + + # First linear + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + oeq_config=self.oeq_config, + ) + + # Convolution weights + input_dim = self.edge_feats_irreps.num_irreps + self.conv_tp_weights = nn.FullyConnectedNet( + [input_dim] + self.radial_MLP + [self.conv_tp.weight_numel], + torch.nn.functional.silu, + ) + + # Linear + self.irreps_out = self.target_irreps + self.linear = Linear( + irreps_mid, + self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Selector TensorProduct + self.skip_tp = FullyConnectedTensorProduct( + self.irreps_out, + self.node_attrs_irreps, + self.irreps_out, + cueq_config=self.cueq_config, + ) + + # Density normalization + self.density_fn = nn.FullyConnectedNet( + [input_dim] + + [ + 1, + ], + torch.nn.functional.silu, + ) + # Reshape + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_class: Optional[Any] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + first_layer: bool = False, + ) -> Tuple[torch.Tensor, None]: + receiver = edge_index[1] + num_nodes = node_feats.shape[0] + n_real = lammps_natoms[0] if lammps_class is not None else None + node_feats = self.linear_up(node_feats) + node_feats = self.handle_lammps( + node_feats, + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + first_layer=first_layer, + ) + tp_weights = self.conv_tp_weights(edge_feats) + edge_density = torch.tanh(self.density_fn(edge_feats) ** 2) + if cutoff is not None: + tp_weights = tp_weights * cutoff + edge_density = edge_density * cutoff + density = scatter_sum( + src=edge_density, index=receiver, dim=0, dim_size=num_nodes + ) # [n_nodes, 1] + message = None + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats[edge_index[0]], edge_attrs, tp_weights + ) # [n_nodes, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=node_feats.shape[0] + ) + + message = self.truncate_ghosts(message, n_real) + node_attrs = self.truncate_ghosts(node_attrs, n_real) + density = self.truncate_ghosts(density, n_real) + message = self.linear(message) / (density + 1) + message = self.skip_tp(message, node_attrs) + return ( + self.reshape(message), + None, + ) # [n_nodes, channels, (lmax + 1)**2] + + +@compile_mode("script") +class RealAgnosticDensityResidualInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + if not hasattr(self, "oeq_config"): + self.oeq_config = None + + # First linear + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + oeq_config=self.oeq_config, + ) + + # Convolution weights + input_dim = self.edge_feats_irreps.num_irreps + self.conv_tp_weights = nn.FullyConnectedNet( + [input_dim] + self.radial_MLP + [self.conv_tp.weight_numel], + torch.nn.functional.silu, # gate + ) + + # Linear + self.irreps_out = self.target_irreps + self.linear = Linear( + irreps_mid, + self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Selector TensorProduct + self.skip_tp = FullyConnectedTensorProduct( + self.node_feats_irreps, + self.node_attrs_irreps, + self.hidden_irreps, + cueq_config=self.cueq_config, + ) + + # Density normalization + self.density_fn = nn.FullyConnectedNet( + [input_dim] + + [ + 1, + ], + torch.nn.functional.silu, + ) + + # Reshape + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_class: Optional[Any] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + first_layer: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + receiver = edge_index[1] + num_nodes = node_feats.shape[0] + n_real = lammps_natoms[0] if lammps_class is not None else None + sc = self.skip_tp(node_feats, node_attrs) + node_feats = self.linear_up(node_feats) + node_feats = self.handle_lammps( + node_feats, + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + first_layer=first_layer, + ) + tp_weights = self.conv_tp_weights(edge_feats) + edge_density = torch.tanh(self.density_fn(edge_feats) ** 2) + if cutoff is not None: + tp_weights = tp_weights * cutoff + edge_density = edge_density * cutoff + density = scatter_sum( + src=edge_density, index=receiver, dim=0, dim_size=num_nodes + ) # [n_nodes, 1] + + message = None + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats[edge_index[0]], edge_attrs, tp_weights + ) # [n_nodes, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=node_feats.shape[0] + ) + + message = self.truncate_ghosts(message, n_real) + node_attrs = self.truncate_ghosts(node_attrs, n_real) + density = self.truncate_ghosts(density, n_real) + sc = self.truncate_ghosts(sc, n_real) + message = self.linear(message) / (density + 1) + return ( + self.reshape(message), + sc, + ) # [n_nodes, channels, (lmax + 1)**2] + + +@compile_mode("script") +class RealAgnosticAttResidualInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + if not hasattr(self, "oeq_config"): + self.oeq_config = None + + self.node_feats_down_irreps = o3.Irreps("64x0e") + # First linear + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + oeq_config=self.oeq_config, + ) + + # Convolution weights + self.linear_down = Linear( + self.node_feats_irreps, + self.node_feats_down_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + input_dim = ( + self.edge_feats_irreps.num_irreps + + 2 * self.node_feats_down_irreps.num_irreps + ) + self.conv_tp_weights = nn.FullyConnectedNet( + [input_dim] + 3 * [256] + [self.conv_tp.weight_numel], + torch.nn.functional.silu, + ) + + # Linear + self.irreps_out = self.target_irreps + self.linear = Linear( + irreps_mid, + self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + # Skip connection. + self.skip_linear = Linear( + self.node_feats_irreps, self.hidden_irreps, cueq_config=self.cueq_config + ) + + # pylint: disable=unused-argument + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_class: Optional[Any] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + first_layer: bool = False, + ) -> Tuple[torch.Tensor, None]: + sender = edge_index[0] + receiver = edge_index[1] + sc = self.skip_linear(node_feats) + node_feats_up = self.linear_up(node_feats) + node_feats_down = self.linear_down(node_feats) + augmented_edge_feats = torch.cat( + [ + edge_feats, + node_feats_down[sender], + node_feats_down[receiver], + ], + dim=-1, + ) + tp_weights = self.conv_tp_weights(augmented_edge_feats) + if cutoff is not None: + tp_weights = tp_weights * cutoff + message = None + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats_up, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats_up[edge_index[0]], edge_attrs, tp_weights + ) # [n_nodes, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=node_feats.shape[0] + ) + message = self.linear(message) / self.avg_num_neighbors + return ( + self.reshape(message), + sc, + ) # [n_nodes, channels, (lmax + 1)**2] + + +@compile_mode("script") +class RealAgnosticResidualNonLinearInteractionBlock(InteractionBlock): + def _setup(self) -> None: + if not hasattr(self, "cueq_config"): + self.cueq_config = None + # First linear + node_scalar_irreps = o3.Irreps( + [(self.node_feats_irreps.count(o3.Irrep(0, 1)), (0, 1))] + ) + self.source_embedding = Linear( + self.node_attrs_irreps, + node_scalar_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + self.target_embedding = Linear( + self.node_attrs_irreps, + node_scalar_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + self.linear_up = Linear( + self.node_feats_irreps, + self.edge_irreps, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + torch.nn.init.uniform_(self.source_embedding.weight, a=-0.001, b=0.001) + torch.nn.init.uniform_(self.target_embedding.weight, a=-0.001, b=0.001) + + # TensorProduct + irreps_mid, instructions = tp_out_irreps_with_instructions( + self.edge_irreps, + self.edge_attrs_irreps, + self.target_irreps, + ) + self.conv_tp = TensorProduct( + self.edge_irreps, + self.edge_attrs_irreps, + irreps_mid, + instructions=instructions, + shared_weights=False, + internal_weights=False, + cueq_config=self.cueq_config, + ) + + # Convolution weights + input_dim = self.edge_feats_irreps.num_irreps + self.conv_tp_weights = RadialMLP( + [input_dim + 2 * node_scalar_irreps.dim] + + self.radial_MLP + + [self.conv_tp.weight_numel] + ) + self.irreps_out = self.target_irreps + + # Selector TensorProduct + self.skip_tp = Linear( + self.node_feats_irreps, + self.hidden_irreps, + cueq_config=self.cueq_config, + ) + self.reshape = reshape_irreps(self.irreps_out, cueq_config=self.cueq_config) + + # Non-linearity + irreps_scalars = o3.Irreps( + [(mul, ir) for mul, ir in self.irreps_out if ir.l == 0] + ) + irreps_gated = o3.Irreps([(mul, ir) for mul, ir in self.irreps_out if ir.l > 0]) + irreps_gates = o3.Irreps([mul, "0e"] for mul, _ in irreps_gated) + activation_fn = torch.nn.functional.silu + act_gates_fn = torch.nn.functional.sigmoid + self.equivariant_nonlin = nn.Gate( + irreps_scalars=irreps_scalars, + act_scalars=[activation_fn for _ in irreps_scalars], + irreps_gates=irreps_gates, + act_gates=[act_gates_fn] * len(irreps_gates), + irreps_gated=irreps_gated, + ) + self.irreps_nonlin = self.equivariant_nonlin.irreps_in.simplify() + + # Linear residual + self.linear_res = Linear( + self.edge_irreps, + self.irreps_nonlin, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Linear + self.linear_1 = Linear( + irreps_mid, + self.irreps_nonlin, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + self.linear_2 = Linear( + irreps_in=self.irreps_out, + irreps_out=self.irreps_out, + internal_weights=True, + shared_weights=True, + cueq_config=self.cueq_config, + ) + + # Normalizations + self.density_fn = RadialMLP( + [input_dim + 2 * node_scalar_irreps.dim] + [64] + [1], + ) + self.alpha = torch.nn.Parameter(torch.tensor(20.0), requires_grad=True) + self.beta = torch.nn.Parameter(torch.tensor(0.0), requires_grad=True) + + self.transpose_mul_ir = TransposeIrrepsLayoutWrapper( + irreps=self.irreps_nonlin, + source="ir_mul", + target="mul_ir", + cueq_config=self.cueq_config, + ) + self.transpose_ir_mul = TransposeIrrepsLayoutWrapper( + irreps=self.irreps_out, + source="mul_ir", + target="ir_mul", + cueq_config=self.cueq_config, + ) + + def forward( + self, + node_attrs: torch.Tensor, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + edge_feats: torch.Tensor, + edge_index: torch.Tensor, + cutoff: Optional[torch.Tensor] = None, + lammps_class: Optional[Any] = None, + lammps_natoms: Tuple[int, int] = (0, 0), + first_layer: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + num_nodes = node_feats.shape[0] + n_real = lammps_natoms[0] if lammps_class is not None else None + sc = self.skip_tp(node_feats) + node_feats = self.linear_up(node_feats) + node_feats_res = self.linear_res(node_feats) + node_feats = self.handle_lammps( + node_feats, + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + first_layer=first_layer, + ) + + source_embedding = self.source_embedding(node_attrs) + target_embedding = self.target_embedding(node_attrs) + edge_feats = torch.cat( + [ + edge_feats, + source_embedding[edge_index[0]], + target_embedding[edge_index[1]], + ], + dim=-1, + ) + tp_weights = self.conv_tp_weights(edge_feats) + + edge_density = torch.tanh(self.density_fn(edge_feats) ** 2) + if cutoff is not None: + tp_weights = tp_weights * cutoff + edge_density = edge_density * cutoff + density = scatter_sum( + src=edge_density, index=edge_index[1], dim=0, dim_size=num_nodes + ) + + if hasattr(self, "conv_fusion"): + message = self.conv_tp(node_feats, edge_attrs, tp_weights, edge_index) + else: + mji = self.conv_tp( + node_feats[edge_index[0]], edge_attrs, tp_weights + ) # [n_edges, irreps] + message = scatter_sum( + src=mji, index=edge_index[1], dim=0, dim_size=num_nodes + ) # [n_nodes, irreps] + + message = self.truncate_ghosts(message, n_real) + density = self.truncate_ghosts(density, n_real) + sc = self.truncate_ghosts(sc, n_real) + node_feats_res = self.truncate_ghosts(node_feats_res, n_real) + message = self.linear_1(message) / (density * self.beta + self.alpha) + message = message + node_feats_res + if self.transpose_mul_ir is not None: + message = self.transpose_mul_ir(message) + message = self.equivariant_nonlin(message) + if self.transpose_ir_mul is not None: + message = self.transpose_ir_mul(message) + message = self.linear_2(message) + return ( + self.reshape(message), + sc, + ) + + +@compile_mode("script") +class ScaleShiftBlock(torch.nn.Module): + def __init__(self, scale: float, shift: float): + super().__init__() + self.register_buffer( + "scale", + torch.tensor(scale, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "shift", + torch.tensor(shift, dtype=torch.get_default_dtype()), + ) + + def forward(self, x: torch.Tensor, head: torch.Tensor) -> torch.Tensor: + return ( + torch.atleast_1d(self.scale)[head] * x + torch.atleast_1d(self.shift)[head] + ) + + def __repr__(self): + formatted_scale = ( + ", ".join([f"{x:.4f}" for x in self.scale]) + if self.scale.numel() > 1 + else f"{self.scale.item():.4f}" + ) + formatted_shift = ( + ", ".join([f"{x:.4f}" for x in self.shift]) + if self.shift.numel() > 1 + else f"{self.shift.item():.4f}" + ) + return f"{self.__class__.__name__}(scale={formatted_scale}, shift={formatted_shift})" diff --git a/models/mace/mace/modules/embeddings.py b/models/mace/mace/modules/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..f374a0fe8b970f48c2ea230d3162d264e622f55f --- /dev/null +++ b/models/mace/mace/modules/embeddings.py @@ -0,0 +1,69 @@ +from typing import Any, Dict, Optional + +import torch +from torch import nn + + +class GenericJointEmbedding(nn.Module): + """ + Simple concat‐fusion of any set of node‐ or graph‐level features + with a base embedding. All features are embedded (via Embedding or small MLP), + then concatenated onto `species_emb`, passed through SiLU+Linear. + """ + + def __init__( + self, + *, + base_dim: int, + embedding_specs: Optional[Dict[str, Any]], + out_dim: Optional[int] = None, + ): + super().__init__() + self.base_dim = base_dim + self.specs = dict(embedding_specs.items()) + self.out_dim = out_dim or base_dim + + # build one embedder per feature + self.embedders = nn.ModuleDict() + for name, spec in self.specs.items(): + E = spec["emb_dim"] + use_bias = spec.get("use_bias", True) + if spec["type"] == "categorical": + self.embedders[name] = nn.Embedding(spec["num_classes"], E) + elif spec["type"] == "continuous": + self.embedders[name] = nn.Sequential( + nn.Linear(spec["in_dim"], E, bias=use_bias), + nn.SiLU(), + nn.Linear(E, E, bias=use_bias), + ) + else: + raise ValueError(f"Unknown type {spec['type']} for feature {name}") + + # build the single concat→SiLU→Linear head + total_dim = sum(spec["emb_dim"] for spec in self.specs.values()) + self.project = nn.Sequential( + nn.Linear(total_dim, self.out_dim, bias=False), + nn.SiLU(), + ) + + def forward( + self, + batch: torch.Tensor, # [N_nodes,] graph indices + features: Dict[str, torch.Tensor], + ) -> torch.Tensor: + """ + features[name] is either [N_graphs, …] or [N_nodes, …] + and we upsample any per‐graph ones via feat[batch]. + Returns: [N_nodes, out_dim] + """ + embs = [] + for name, spec in self.specs.items(): + feat = features[name] + if spec["per"] == "graph": + feat = feat[batch].unsqueeze(-1) # now [N_nodes, …] + if spec["type"] == "categorical": + feat = (feat + spec.get("offset", 0)).long().squeeze(-1) # [N_nodes, 1] + emb = self.embedders[name](feat) + embs.append(emb) + x = torch.cat(embs, dim=-1) + return self.project(x) diff --git a/models/mace/mace/modules/extensions.py b/models/mace/mace/modules/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a108c18de6e72139e5aecd2ff5f9e7cf287893 --- /dev/null +++ b/models/mace/mace/modules/extensions.py @@ -0,0 +1,270 @@ +from typing import Dict, List, Optional + +import torch +from e3nn.util.jit import compile_mode + +from mace.modules.blocks import LinearReadoutBlock, NonLinearReadoutBlock +from mace.modules.models import ScaleShiftMACE +from mace.modules.utils import get_atomic_virials_stresses, get_outputs, prepare_graph +from mace.modules.wrapper_ops import CuEquivarianceConfig +from mace.tools.scatter import scatter_sum + + +def _copy_mace_readout( + mace_readout: torch.nn.Module, cueq_config: Optional[CuEquivarianceConfig] = None +) -> torch.nn.Module: + """ + Helper function to copy a MACE readout block. + """ + if isinstance(mace_readout, LinearReadoutBlock): + return LinearReadoutBlock( + irreps_in=mace_readout.linear.irreps_in, # type:ignore + irrep_out=mace_readout.linear.irreps_out, # type:ignore + cueq_config=cueq_config, + ) + if isinstance(mace_readout, NonLinearReadoutBlock): # type:ignore + return NonLinearReadoutBlock( + irreps_in=mace_readout.linear_1.irreps_in, # type:ignore + MLP_irreps=mace_readout.hidden_irreps, + gate=mace_readout.non_linearity._modules["acts"][ # pylint: disable=W0212 + 0 + ].f, + irrep_out=mace_readout.linear_2.irreps_out, # type:ignore + num_heads=mace_readout.num_heads, + cueq_config=cueq_config, + ) + raise TypeError("Unsupported readout type.") + + +def _get_readout_input_dim(block: torch.nn.Module) -> int: + if isinstance(block, LinearReadoutBlock): + return block.linear.irreps_in.dim # type:ignore + if isinstance(block, NonLinearReadoutBlock): # type:ignore + return block.linear_1.irreps_in.dim # type:ignore + raise TypeError("Unsupported readout type for input dimension retrieval.") + + +@compile_mode("script") +class MACELES(ScaleShiftMACE): + def __init__(self, les_arguments: Optional[Dict] = None, **kwargs): + super().__init__(**kwargs) + try: + from les import Les + except ImportError as exc: + raise ImportError( + "Cannot import 'les'. Please install the 'les' library from https://github.com/ChengUCB/les." + ) from exc + if les_arguments is None: + les_arguments = {"use_atomwise": False} + self.compute_bec = les_arguments.get("compute_bec", False) + self.bec_output_index = les_arguments.get("bec_output_index", None) + self.les = Les(les_arguments=les_arguments) + self.les_readouts = torch.nn.ModuleList() + self.readout_input_dims = [ + _get_readout_input_dim(readout) for readout in self.readouts # type:ignore + ] + cueq_config = kwargs.get("cueq_config", None) + for readout in self.readouts: # type:ignore + self.les_readouts.append( + _copy_mace_readout(readout, cueq_config=cueq_config) + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, + compute_force: bool = True, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_hessian: bool = False, + compute_edge_forces: bool = False, + compute_atomic_stresses: bool = False, + lammps_mliap: bool = False, + compute_bec: bool = False, + ) -> Dict[str, Optional[torch.Tensor]]: + ctx = prepare_graph( + data, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_displacement=compute_displacement, + lammps_mliap=lammps_mliap, + ) + + is_lammps = ctx.is_lammps + num_atoms_arange = ctx.num_atoms_arange + num_graphs = ctx.num_graphs + displacement = ctx.displacement + positions = ctx.positions + vectors = ctx.vectors + lengths = ctx.lengths + cell = ctx.cell + node_heads = ctx.node_heads + interaction_kwargs = ctx.interaction_kwargs + lammps_natoms = interaction_kwargs.lammps_natoms + lammps_class = interaction_kwargs.lammps_class + + # Setting LES cell input to zero when boundary conditions are not periodic + cell_les = cell.clone() + pbc_tensor = data["pbc"].to(device=data["cell"].device) + no_pbc_mask_cfg = ~pbc_tensor.any(dim=-1) + no_pbc_mask_rows = no_pbc_mask_cfg.repeat_interleave(3) + cell_les[no_pbc_mask_rows] = torch.zeros( + (no_pbc_mask_rows.sum(), 3), dtype=cell_les.dtype, device=cell_les.device + ) + + # Atomic energies + node_e0 = self.atomic_energies_fn(data["node_attrs"])[ + num_atoms_arange, node_heads + ] + e0 = scatter_sum( + src=node_e0, index=data["batch"], dim=0, dim_size=num_graphs + ).to( + vectors.dtype + ) # [n_graphs, num_heads] + + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + + if hasattr(self, "pair_repulsion"): + pair_node_energy = self.pair_repulsion_fn( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + if is_lammps: + pair_node_energy = pair_node_energy[: lammps_natoms[0]] + else: + pair_node_energy = torch.zeros_like(node_e0) + + # Embeddings of additional features + if hasattr(self, "joint_embedding"): + embedding_features: Dict[str, torch.Tensor] = {} + for name, _ in self.embedding_specs.items(): + embedding_features[name] = data[name] + node_feats += self.joint_embedding( + data["batch"], + embedding_features, + ) + if hasattr(self, "embedding_readout"): + embedding_node_energy = self.embedding_readout( + node_feats, node_heads + ).squeeze(-1) + embedding_energy = scatter_sum( + src=embedding_node_energy, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) + e0 += embedding_energy + + # Interactions + node_es_list = [pair_node_energy] + node_feats_list: List[torch.Tensor] = [] + node_qs_list: List[torch.Tensor] = [] + + for i, (interaction, product) in enumerate( + zip(self.interactions, self.products) + ): + node_attrs_slice = data["node_attrs"] + if is_lammps and i > 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats, sc = interaction( + node_attrs=node_attrs_slice, + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + first_layer=(i == 0), + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + ) + if is_lammps and i == 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats = product( + node_feats=node_feats, sc=sc, node_attrs=node_attrs_slice + ) + node_feats_list.append(node_feats) + + for i, (readout, les_readout) in enumerate( + zip(self.readouts, self.les_readouts) + ): + feat_idx = -1 if len(self.readouts) == 1 else i + node_es = readout(node_feats_list[feat_idx], node_heads)[ + num_atoms_arange, node_heads + ] + node_qs = les_readout(node_feats_list[feat_idx], node_heads)[ + num_atoms_arange, node_heads + ] # type:ignore + node_qs_list.append(node_qs) + node_es_list.append(node_es) + + node_feats_out = torch.cat(node_feats_list, dim=-1) + node_inter_es = torch.sum(torch.stack(node_es_list, dim=0), dim=0) + node_inter_es = self.scale_shift(node_inter_es, node_heads) + inter_e = scatter_sum(node_inter_es, data["batch"], dim=-1, dim_size=num_graphs) + + total_energy = e0 + inter_e + node_energy = node_e0.clone().double() + node_inter_es.clone().double() + + les_q = torch.sum(torch.stack(node_qs_list, dim=1), dim=1) + les_result = self.les( + latent_charges=les_q, + positions=positions, + cell=cell_les.view(-1, 3, 3), + batch=data["batch"], + compute_energy=True, + compute_bec=(compute_bec or self.compute_bec), + bec_output_index=self.bec_output_index, + ) + les_energy_opt = les_result["E_lr"] + if les_energy_opt is None: + les_energy = torch.zeros_like(total_energy) + else: + les_energy = les_energy_opt + total_energy += les_energy + + forces, virials, stress, hessian, edge_forces = get_outputs( + energy=inter_e + les_energy, + positions=positions, + displacement=displacement, + vectors=vectors, + cell=cell, + training=training, + compute_force=compute_force, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_hessian=compute_hessian, + compute_edge_forces=compute_edge_forces, + ) + + atomic_virials: Optional[torch.Tensor] = None + atomic_stresses: Optional[torch.Tensor] = None + if compute_atomic_stresses and edge_forces is not None: + atomic_virials, atomic_stresses = get_atomic_virials_stresses( + edge_forces=edge_forces, + edge_index=data["edge_index"], + vectors=vectors, + num_atoms=positions.shape[0], + batch=data["batch"], + cell=cell, + ) + return { + "energy": total_energy, + "node_energy": node_energy, + "forces": forces, + "edge_forces": edge_forces, + "virials": virials, + "stress": stress, + "atomic_virials": atomic_virials, + "atomic_stresses": atomic_stresses, + "displacement": displacement, + "hessian": hessian, + "node_feats": node_feats_out, + "les_energy": les_energy, + "latent_charges": les_q, + "BEC": les_result["BEC"], + } diff --git a/models/mace/mace/modules/irreps_tools.py b/models/mace/mace/modules/irreps_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..6677b1bef2be949300a26e5e852ef80fac8c0724 --- /dev/null +++ b/models/mace/mace/modules/irreps_tools.py @@ -0,0 +1,116 @@ +########################################################################################### +# Elementary tools for handling irreducible representations +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from typing import List, Optional, Tuple + +import torch +from e3nn import o3 +from e3nn.util.jit import compile_mode + +from mace.modules.wrapper_ops import CuEquivarianceConfig + + +# Based on mir-group/nequip +def tp_out_irreps_with_instructions( + irreps1: o3.Irreps, irreps2: o3.Irreps, target_irreps: o3.Irreps +) -> Tuple[o3.Irreps, List]: + trainable = True + + # Collect possible irreps and their instructions + irreps_out_list: List[Tuple[int, o3.Irreps]] = [] + instructions = [] + for i, (mul, ir_in) in enumerate(irreps1): + for j, (_, ir_edge) in enumerate(irreps2): + for ir_out in ir_in * ir_edge: # | l1 - l2 | <= l <= l1 + l2 + if ir_out in target_irreps: + k = len(irreps_out_list) # instruction index + irreps_out_list.append((mul, ir_out)) + instructions.append((i, j, k, "uvu", trainable)) + + # We sort the output irreps of the tensor product so that we can simplify them + # when they are provided to the second o3.Linear + irreps_out = o3.Irreps(irreps_out_list) + irreps_out, permut, _ = irreps_out.sort() + + # Permute the output indexes of the instructions to match the sorted irreps: + instructions = [ + (i_in1, i_in2, permut[i_out], mode, train) + for i_in1, i_in2, i_out, mode, train in instructions + ] + + instructions = sorted(instructions, key=lambda x: x[2]) + + return irreps_out, instructions + + +def linear_out_irreps(irreps: o3.Irreps, target_irreps: o3.Irreps) -> o3.Irreps: + # Assuming simplified irreps + irreps_mid = [] + for _, ir_in in irreps: + found = False + + for mul, ir_out in target_irreps: + if ir_in == ir_out: + irreps_mid.append((mul, ir_out)) + found = True + break + + if not found: + raise RuntimeError(f"{ir_in} not in {target_irreps}") + + return o3.Irreps(irreps_mid) + + +@compile_mode("script") +class reshape_irreps(torch.nn.Module): + def __init__( + self, irreps: o3.Irreps, cueq_config: Optional[CuEquivarianceConfig] = None + ) -> None: + super().__init__() + self.irreps = o3.Irreps(irreps) + self.cueq_config = cueq_config + self.dims = [] + self.muls = [] + for mul, ir in self.irreps: + d = ir.dim + self.dims.append(d) + self.muls.append(mul) + + def forward(self, tensor: torch.Tensor) -> torch.Tensor: + ix = 0 + out = [] + batch, _ = tensor.shape + for mul, d in zip(self.muls, self.dims): + field = tensor[:, ix : ix + mul * d] # [batch, sample, mul * repr] + ix += mul * d + if hasattr(self, "cueq_config"): + if self.cueq_config is not None: + if self.cueq_config.layout_str == "mul_ir": + field = field.reshape(batch, mul, d) + else: + field = field.reshape(batch, d, mul) + else: + field = field.reshape(batch, mul, d) + else: + field = field.reshape(batch, mul, d) + out.append(field) + + if hasattr(self, "cueq_config"): + if self.cueq_config is not None: # pylint: disable=no-else-return + if self.cueq_config.layout_str == "mul_ir": + return torch.cat(out, dim=-1) + return torch.cat(out, dim=-2) + else: + return torch.cat(out, dim=-1) + return torch.cat(out, dim=-1) + + +def mask_head(x: torch.Tensor, head: torch.Tensor, num_heads: int) -> torch.Tensor: + mask = torch.zeros(x.shape[0], x.shape[1] // num_heads, num_heads, device=x.device) + idx = torch.arange(mask.shape[0], device=x.device) + mask[idx, :, head] = 1 + mask = mask.permute(0, 2, 1).reshape(x.shape) + return x * mask diff --git a/models/mace/mace/modules/loss.py b/models/mace/mace/modules/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2b12bda8cf87dfe070301f0a5892c99884d1c161 --- /dev/null +++ b/models/mace/mace/modules/loss.py @@ -0,0 +1,688 @@ +########################################################################################### +# Implementation of different loss functions +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from typing import Optional + +import torch +import torch.distributed as dist + +from mace.tools import TensorDict +from mace.tools.torch_geometric import Batch + + +from torch import nn +from mace.tools.torch_geometric import Batch +from mace.tools import TensorDict + + + +# ------------------------------------------------------------------------------ +# Helper function for loss reduction that handles DDP correction +# ------------------------------------------------------------------------------ +def is_ddp_enabled(): + return dist.is_initialized() and dist.get_world_size() > 1 + + +def reduce_loss(raw_loss: torch.Tensor, ddp: Optional[bool] = None) -> torch.Tensor: + """ + Reduces an element-wise loss tensor. + + If ddp is True and distributed is initialized, the function computes: + + loss = (local_sum * world_size) / global_num_elements + + Otherwise, it returns the regular mean. + """ + ddp = is_ddp_enabled() if ddp is None else ddp + if ddp and dist.is_initialized(): + world_size = dist.get_world_size() + n_local = raw_loss.numel() + loss_sum = raw_loss.sum() + total_samples = torch.tensor( + n_local, device=raw_loss.device, dtype=raw_loss.dtype + ) + dist.all_reduce(total_samples, op=dist.ReduceOp.SUM) + return loss_sum * world_size / total_samples + return raw_loss.mean() + + +# ------------------------------------------------------------------------------ +# Energy Loss Functions +# ------------------------------------------------------------------------------ + + +def mean_squared_error_energy( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + raw_loss = torch.square(ref["energy"] - pred["energy"]) + return reduce_loss(raw_loss, ddp) + + +def weighted_mean_squared_error_energy( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + # Calculate per-graph number of atoms. + num_atoms = ref.ptr[1:] - ref.ptr[:-1] # shape: [n_graphs] + raw_loss = ( + ref.weight + * ref.energy_weight + * torch.square((ref["energy"] - pred["energy"]) / num_atoms) + ) + return reduce_loss(raw_loss, ddp) + + +def weighted_mean_absolute_error_energy( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + num_atoms = ref.ptr[1:] - ref.ptr[:-1] + raw_loss = ( + ref.weight + * ref.energy_weight + * torch.abs((ref["energy"] - pred["energy"]) / num_atoms) + ) + return reduce_loss(raw_loss, ddp) + + +# ------------------------------------------------------------------------------ +# Stress and Virials Loss Functions +# ------------------------------------------------------------------------------ + + +def weighted_mean_squared_stress( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + configs_weight = ref.weight.view(-1, 1, 1) + configs_stress_weight = ref.stress_weight.view(-1, 1, 1) + raw_loss = ( + configs_weight + * configs_stress_weight + * torch.square(ref["stress"] - pred["stress"]) + ) + return reduce_loss(raw_loss, ddp) + + +def weighted_mean_squared_virials( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + configs_weight = ref.weight.view(-1, 1, 1) + configs_virials_weight = ref.virials_weight.view(-1, 1, 1) + num_atoms = (ref.ptr[1:] - ref.ptr[:-1]).view(-1, 1, 1) + raw_loss = ( + configs_weight + * configs_virials_weight + * torch.square((ref["virials"] - pred["virials"]) / num_atoms) + ) + return reduce_loss(raw_loss, ddp) + + +# ------------------------------------------------------------------------------ +# Forces Loss Functions +# ------------------------------------------------------------------------------ + + +def mean_squared_error_forces( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + # Repeat per-graph weights to per-atom level. + configs_weight = torch.repeat_interleave( + ref.weight, ref.ptr[1:] - ref.ptr[:-1] + ).unsqueeze(-1) + configs_forces_weight = torch.repeat_interleave( + ref.forces_weight, ref.ptr[1:] - ref.ptr[:-1] + ).unsqueeze(-1) + raw_loss = ( + configs_weight + * configs_forces_weight + * torch.square(ref["forces"] - pred["forces"]) + ) + return reduce_loss(raw_loss, ddp) + + +def mean_normed_error_forces( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + raw_loss = torch.linalg.vector_norm(ref["forces"] - pred["forces"], ord=2, dim=-1) + return reduce_loss(raw_loss, ddp) + + +# ------------------------------------------------------------------------------ +# Dipole Loss Function +# ------------------------------------------------------------------------------ + + +def weighted_mean_squared_error_dipole( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + num_atoms = (ref.ptr[1:] - ref.ptr[:-1]).unsqueeze(-1) + raw_loss = torch.square((ref["dipole"] - pred["dipole"]) / num_atoms) + return reduce_loss(raw_loss, ddp) + + +# ------------------------------------------------------------------------------ +# Polarizability Loss Function +# ------------------------------------------------------------------------------ + + +def weighted_mean_squared_error_polarizability( + ref: Batch, + pred: TensorDict, + ddp: Optional[ + bool + ] = None, # ,mean: Optional[torch.Tensor] = None , std: Optional[torch.Tensor] = None +) -> torch.Tensor: + # polarizability: [n_graphs, ] + # ref_polar = ref["polarizability"].view(-1, 3, 3) * std.view(1, 3, 3) + mean.view(1, 3, 3) if mean is not None and std is not None else ref["polarizability"] + num_atoms = (ref.ptr[1:] - ref.ptr[:-1]).view(-1, 1, 1) # [n_graphs,1] + raw_loss = torch.square( + (ref["polarizability"].view(-1, 3, 3) - pred["polarizability"]) / num_atoms + ) + return reduce_loss(raw_loss, ddp) + + +# ------------------------------------------------------------------------------ +# Conditional Losses for Forces +# ------------------------------------------------------------------------------ + + +def conditional_mse_forces( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + configs_weight = torch.repeat_interleave( + ref.weight, ref.ptr[1:] - ref.ptr[:-1] + ).unsqueeze(-1) + configs_forces_weight = torch.repeat_interleave( + ref.forces_weight, ref.ptr[1:] - ref.ptr[:-1] + ).unsqueeze(-1) + # Define multiplication factors for different regimes. + factors = torch.tensor( + [1.0, 0.7, 0.4, 0.1], device=ref["forces"].device, dtype=ref["forces"].dtype + ) + err = ref["forces"] - pred["forces"] + se = torch.zeros_like(err) + norm_forces = torch.norm(ref["forces"], dim=-1) + c1 = norm_forces < 100 + c2 = (norm_forces >= 100) & (norm_forces < 200) + c3 = (norm_forces >= 200) & (norm_forces < 300) + se[c1] = torch.square(err[c1]) * factors[0] + se[c2] = torch.square(err[c2]) * factors[1] + se[c3] = torch.square(err[c3]) * factors[2] + se[~(c1 | c2 | c3)] = torch.square(err[~(c1 | c2 | c3)]) * factors[3] + raw_loss = configs_weight * configs_forces_weight * se + return reduce_loss(raw_loss, ddp) + + +def conditional_huber_forces( + ref_forces: torch.Tensor, + pred_forces: torch.Tensor, + huber_delta: float, + ddp: Optional[bool] = None, +) -> torch.Tensor: + factors = huber_delta * torch.tensor( + [1.0, 0.7, 0.4, 0.1], device=ref_forces.device, dtype=ref_forces.dtype + ) + norm_forces = torch.norm(ref_forces, dim=-1) + c1 = norm_forces < 100 + c2 = (norm_forces >= 100) & (norm_forces < 200) + c3 = (norm_forces >= 200) & (norm_forces < 300) + c4 = ~(c1 | c2 | c3) + se = torch.zeros_like(pred_forces) + se[c1] = torch.nn.functional.huber_loss( + ref_forces[c1], pred_forces[c1], reduction="none", delta=factors[0] + ) + se[c2] = torch.nn.functional.huber_loss( + ref_forces[c2], pred_forces[c2], reduction="none", delta=factors[1] + ) + se[c3] = torch.nn.functional.huber_loss( + ref_forces[c3], pred_forces[c3], reduction="none", delta=factors[2] + ) + se[c4] = torch.nn.functional.huber_loss( + ref_forces[c4], pred_forces[c4], reduction="none", delta=factors[3] + ) + return reduce_loss(se, ddp) + + +# ------------------------------------------------------------------------------ +# Loss Modules Combining Multiple Quantities +# ------------------------------------------------------------------------------ + + +class WeightedEnergyForcesLoss(torch.nn.Module): + def __init__(self, energy_weight=1.0, forces_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_energy = weighted_mean_squared_error_energy(ref, pred, ddp) + loss_forces = mean_squared_error_forces(ref, pred, ddp) + return self.energy_weight * loss_energy + self.forces_weight * loss_forces + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f})" + ) + + +class WeightedForcesLoss(torch.nn.Module): + def __init__(self, forces_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_forces = mean_squared_error_forces(ref, pred, ddp) + return self.forces_weight * loss_forces + + def __repr__(self): + return f"{self.__class__.__name__}(forces_weight={self.forces_weight:.3f})" + + +class WeightedEnergyForcesStressLoss(torch.nn.Module): + def __init__(self, energy_weight=1.0, forces_weight=1.0, stress_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "stress_weight", + torch.tensor(stress_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_energy = weighted_mean_squared_error_energy(ref, pred, ddp) + loss_forces = mean_squared_error_forces(ref, pred, ddp) + loss_stress = weighted_mean_squared_stress(ref, pred, ddp) + return ( + self.energy_weight * loss_energy + + self.forces_weight * loss_forces + + self.stress_weight * loss_stress + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f}, stress_weight={self.stress_weight:.3f})" + ) + + +class WeightedHuberEnergyForcesStressLoss(torch.nn.Module): + def __init__( + self, energy_weight=1.0, forces_weight=1.0, stress_weight=1.0, huber_delta=0.01 + ) -> None: + super().__init__() + # We store the huber_delta rather than a loss with fixed reduction. + self.huber_delta = huber_delta + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "stress_weight", + torch.tensor(stress_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + num_atoms = ref.ptr[1:] - ref.ptr[:-1] + if ddp: + loss_energy = torch.nn.functional.huber_loss( + ref["energy"] / num_atoms, + pred["energy"] / num_atoms, + reduction="none", + delta=self.huber_delta, + ) + loss_energy = reduce_loss(loss_energy, ddp) + loss_forces = torch.nn.functional.huber_loss( + ref["forces"], pred["forces"], reduction="none", delta=self.huber_delta + ) + loss_forces = reduce_loss(loss_forces, ddp) + loss_stress = torch.nn.functional.huber_loss( + ref["stress"], pred["stress"], reduction="none", delta=self.huber_delta + ) + loss_stress = reduce_loss(loss_stress, ddp) + else: + loss_energy = torch.nn.functional.huber_loss( + ref["energy"] / num_atoms, + pred["energy"] / num_atoms, + reduction="mean", + delta=self.huber_delta, + ) + loss_forces = torch.nn.functional.huber_loss( + ref["forces"], pred["forces"], reduction="mean", delta=self.huber_delta + ) + loss_stress = torch.nn.functional.huber_loss( + ref["stress"], pred["stress"], reduction="mean", delta=self.huber_delta + ) + return ( + self.energy_weight * loss_energy + + self.forces_weight * loss_forces + + self.stress_weight * loss_stress + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f}, stress_weight={self.stress_weight:.3f})" + ) + + +class UniversalLoss(torch.nn.Module): + def __init__( + self, energy_weight=1.0, forces_weight=1.0, stress_weight=1.0, huber_delta=0.01 + ) -> None: + super().__init__() + self.huber_delta = huber_delta + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "stress_weight", + torch.tensor(stress_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + num_atoms = ref.ptr[1:] - ref.ptr[:-1] + configs_stress_weight = ref.stress_weight.view(-1, 1, 1) + configs_energy_weight = ref.energy_weight + configs_forces_weight = torch.repeat_interleave( + ref.forces_weight, ref.ptr[1:] - ref.ptr[:-1] + ).unsqueeze(-1) + if ddp: + loss_energy = torch.nn.functional.huber_loss( + configs_energy_weight * ref["energy"] / num_atoms, + configs_energy_weight * pred["energy"] / num_atoms, + reduction="none", + delta=self.huber_delta, + ) + loss_energy = reduce_loss(loss_energy, ddp) + loss_forces = conditional_huber_forces( + configs_forces_weight * ref["forces"], + configs_forces_weight * pred["forces"], + huber_delta=self.huber_delta, + ddp=ddp, + ) + loss_stress = torch.nn.functional.huber_loss( + configs_stress_weight * ref["stress"], + configs_stress_weight * pred["stress"], + reduction="none", + delta=self.huber_delta, + ) + loss_stress = reduce_loss(loss_stress, ddp) + else: + loss_energy = torch.nn.functional.huber_loss( + configs_energy_weight * ref["energy"] / num_atoms, + configs_energy_weight * pred["energy"] / num_atoms, + reduction="mean", + delta=self.huber_delta, + ) + loss_forces = conditional_huber_forces( + configs_forces_weight * ref["forces"], + configs_forces_weight * pred["forces"], + huber_delta=self.huber_delta, + ddp=ddp, + ) + loss_stress = torch.nn.functional.huber_loss( + configs_stress_weight * ref["stress"], + configs_stress_weight * pred["stress"], + reduction="mean", + delta=self.huber_delta, + ) + return ( + self.energy_weight * loss_energy + + self.forces_weight * loss_forces + + self.stress_weight * loss_stress + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f}, stress_weight={self.stress_weight:.3f})" + ) + + +class WeightedEnergyForcesVirialsLoss(torch.nn.Module): + def __init__( + self, energy_weight=1.0, forces_weight=1.0, virials_weight=1.0 + ) -> None: + super().__init__() + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "virials_weight", + torch.tensor(virials_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_energy = weighted_mean_squared_error_energy(ref, pred, ddp) + loss_forces = mean_squared_error_forces(ref, pred, ddp) + loss_virials = weighted_mean_squared_virials(ref, pred, ddp) + return ( + self.energy_weight * loss_energy + + self.forces_weight * loss_forces + + self.virials_weight * loss_virials + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f}, virials_weight={self.virials_weight:.3f})" + ) + + +class DipoleSingleLoss(torch.nn.Module): + def __init__(self, dipole_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "dipole_weight", + torch.tensor(dipole_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss = ( + weighted_mean_squared_error_dipole(ref, pred, ddp) * 100.0 + ) # scale adjustment + return self.dipole_weight * loss + + def __repr__(self): + return f"{self.__class__.__name__}(dipole_weight={self.dipole_weight:.3f})" + + +class DipolePolarLoss(torch.nn.Module): + def __init__( + self, dipole_weight=1.0, polarizability_weight=1.0 + ) -> ( + None + ): # dipole_mean=None,dipole_std=None,polarizability_mean=None,polarizability_std=None + super().__init__() + self.register_buffer( + "dipole_weight", + torch.tensor(dipole_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "polarizability_weight", + torch.tensor(polarizability_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_dipole = weighted_mean_squared_error_dipole( + ref, pred, ddp + ) # ,self.dipole_mean,self.dipole_std) #* 100.0 # scale adjustment + + loss_polarizability = weighted_mean_squared_error_polarizability( + ref, pred, ddp + ) # ,self.polarizability_mean,self.polarizability_std) #* 100.0 # scale adjustment + return ( + self.dipole_weight * loss_dipole + + self.polarizability_weight * loss_polarizability + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(" + f"dipole_weight={self.dipole_weight:.3f}, polarizability_weight={self.polarizability_weight:.3f})" + ) + + +class WeightedEnergyForcesDipoleLoss(torch.nn.Module): + def __init__(self, energy_weight=1.0, forces_weight=1.0, dipole_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "dipole_weight", + torch.tensor(dipole_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_energy = weighted_mean_squared_error_energy(ref, pred, ddp) + loss_forces = mean_squared_error_forces(ref, pred, ddp) + loss_dipole = weighted_mean_squared_error_dipole(ref, pred, ddp) * 100.0 + return ( + self.energy_weight * loss_energy + + self.forces_weight * loss_forces + + self.dipole_weight * loss_dipole + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f}, dipole_weight={self.dipole_weight:.3f})" + ) + + +class WeightedEnergyForcesL1L2Loss(torch.nn.Module): + def __init__(self, energy_weight=1.0, forces_weight=1.0) -> None: + super().__init__() + self.register_buffer( + "energy_weight", + torch.tensor(energy_weight, dtype=torch.get_default_dtype()), + ) + self.register_buffer( + "forces_weight", + torch.tensor(forces_weight, dtype=torch.get_default_dtype()), + ) + + def forward( + self, ref: Batch, pred: TensorDict, ddp: Optional[bool] = None + ) -> torch.Tensor: + loss_energy = weighted_mean_absolute_error_energy(ref, pred, ddp) + loss_forces = mean_normed_error_forces(ref, pred, ddp) + return self.energy_weight * loss_energy + self.forces_weight * loss_forces + + def __repr__(self): + return ( + f"{self.__class__.__name__}(energy_weight={self.energy_weight:.3f}, " + f"forces_weight={self.forces_weight:.3f})" + ) + + +def weighted_mean_absolute_error_forces( + ref: Batch, pred: TensorDict, ddp: Optional[bool] = None +) -> torch.Tensor: + # Repeat per-graph weights to per-atom level. + num_atoms_per_graph = ref.ptr[1:] - ref.ptr[:-1] # [n_graphs] + configs_weight = torch.repeat_interleave(ref.weight, num_atoms_per_graph).unsqueeze(-1) + configs_forces_weight = torch.repeat_interleave(ref.forces_weight, num_atoms_per_graph).unsqueeze(-1) + + raw_loss = configs_weight * configs_forces_weight * torch.abs(ref["forces"] - pred["forces"]) + return reduce_loss(raw_loss, ddp) + + + + +class WeightedEnergyForcesMAELoss(nn.Module): + """ + loss = forces_weight * MAE(forces) + + (energy_weight / total_atoms_in_batch) * MAE(energy) + + Forces MAE: mean over all components [n_atoms, 3] + Energy MAE: mean over graphs [n_graphs] + """ + + def __init__(self, energy_weight: float = 1.0, forces_weight: float = 1.0): + super().__init__() + self.l1 = nn.L1Loss(reduction="mean") + self.l1_eval = nn.L1Loss(reduction="sum") + self.l2_eval = nn.MSELoss(reduction="sum") + self.energy_weight = energy_weight + self.forces_weight = forces_weight + + + def forward(self, ref: Batch, pred: TensorDict, do_eval=False) -> torch.Tensor: + loss_forces = self.l1(pred["forces"], ref["forces"]) + loss_energy = self.l1(pred["energy"], ref["energy"]) + + + # ptr: graph boundaries in the PyG Batch (provided by the dataloader collate) + num_atoms_per_graph = ref.ptr[1:] - ref.ptr[:-1] + total_atoms = num_atoms_per_graph.sum().to(loss_energy.dtype) + + + if do_eval: + loss_forces_l1 = self.l1_eval(pred["forces"], ref["forces"]) + loss_energy_l1 = self.l1_eval(pred["energy"], ref["energy"]) + + loss_forces_l2 = self.l2_eval(pred["forces"], ref["forces"]) + loss_energy_l2 = self.l2_eval(pred["energy"], ref["energy"]) + + + return loss_forces_l1, loss_energy_l1, loss_forces_l2, loss_energy_l2 + + return self.forces_weight * loss_forces + (self.energy_weight / total_atoms) * loss_energy + + diff --git a/models/mace/mace/modules/models.py b/models/mace/mace/modules/models.py new file mode 100644 index 0000000000000000000000000000000000000000..e31d202a77270fbde1243fef452eaa57605cc8ce --- /dev/null +++ b/models/mace/mace/modules/models.py @@ -0,0 +1,1438 @@ +########################################################################################### +# Implementation of MACE models and other models based E(3)-Equivariant MPNNs +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from typing import Any, Callable, Dict, List, Optional, Type, Union + +import numpy as np +import torch +from e3nn import o3 +from e3nn.util.jit import compile_mode + +from mace.modules.embeddings import GenericJointEmbedding +from mace.modules.radial import ZBLBasis +from mace.tools.scatter import scatter_mean, scatter_sum +from mace.tools.torch_tools import get_change_of_basis, spherical_to_cartesian + +from .blocks import ( + AtomicEnergiesBlock, + EquivariantProductBasisBlock, + InteractionBlock, + LinearDipolePolarReadoutBlock, + LinearDipoleReadoutBlock, + LinearNodeEmbeddingBlock, + LinearReadoutBlock, + NonLinearDipolePolarReadoutBlock, + NonLinearDipoleReadoutBlock, + NonLinearReadoutBlock, + RadialEmbeddingBlock, + ScaleShiftBlock, +) +from .utils import ( + compute_dielectric_gradients, + compute_fixed_charge_dipole, + compute_fixed_charge_dipole_polar, + get_atomic_virials_stresses, + get_edge_vectors_and_lengths, + get_outputs, + get_symmetric_displacement, + prepare_graph, +) + + +@compile_mode("script") +class MACE(torch.nn.Module): + def __init__( + self, + r_max: float, + num_bessel: int, + num_polynomial_cutoff: int, + max_ell: int, + interaction_cls: Type[InteractionBlock], + interaction_cls_first: Type[InteractionBlock], + num_interactions: int, + num_elements: int, + hidden_irreps: o3.Irreps, + MLP_irreps: o3.Irreps, + atomic_energies: np.ndarray, + avg_num_neighbors: float, + atomic_numbers: List[int], + correlation: Union[int, List[int]], + gate: Optional[Callable], + pair_repulsion: bool = False, + apply_cutoff: bool = True, + use_reduced_cg: bool = True, + use_so3: bool = False, + use_agnostic_product: bool = False, + use_last_readout_only: bool = False, + use_embedding_readout: bool = False, + distance_transform: str = "None", + edge_irreps: Optional[o3.Irreps] = None, + use_edge_irreps_first: bool = False, + radial_MLP: Optional[List[int]] = None, + radial_type: Optional[str] = "bessel", + heads: Optional[List[str]] = None, + cueq_config: Optional[Dict[str, Any]] = None, + embedding_specs: Optional[Dict[str, Any]] = None, + oeq_config: Optional[Dict[str, Any]] = None, + lammps_mliap: Optional[bool] = False, + readout_cls: Optional[Type[NonLinearReadoutBlock]] = NonLinearReadoutBlock, + ): + super().__init__() + self.register_buffer( + "atomic_numbers", torch.tensor(atomic_numbers, dtype=torch.int64) + ) + self.register_buffer( + "r_max", torch.tensor(r_max, dtype=torch.get_default_dtype()) + ) + self.register_buffer( + "num_interactions", torch.tensor(num_interactions, dtype=torch.int64) + ) + if heads is None: + heads = ["Default"] + self.heads = heads + if isinstance(correlation, int): + correlation = [correlation] * num_interactions + self.lammps_mliap = lammps_mliap + self.apply_cutoff = apply_cutoff + self.edge_irreps = edge_irreps + self.use_reduced_cg = use_reduced_cg + self.use_agnostic_product = use_agnostic_product + self.use_so3 = use_so3 + self.use_last_readout_only = use_last_readout_only + self.use_edge_irreps_first = use_edge_irreps_first + + # Embedding + node_attr_irreps = o3.Irreps([(num_elements, (0, 1))]) + node_feats_irreps = o3.Irreps([(hidden_irreps.count(o3.Irrep(0, 1)), (0, 1))]) + self.node_embedding = LinearNodeEmbeddingBlock( + irreps_in=node_attr_irreps, + irreps_out=node_feats_irreps, + cueq_config=cueq_config, + ) + embedding_size = node_feats_irreps.count(o3.Irrep(0, 1)) + if embedding_specs is not None: + self.embedding_specs = embedding_specs + self.joint_embedding = GenericJointEmbedding( + base_dim=embedding_size, + embedding_specs=embedding_specs, + out_dim=embedding_size, + ) + if use_embedding_readout: + self.embedding_readout = LinearReadoutBlock( + node_feats_irreps, + o3.Irreps(f"{len(heads)}x0e"), + cueq_config, + oeq_config, + ) + + self.radial_embedding = RadialEmbeddingBlock( + r_max=r_max, + num_bessel=num_bessel, + num_polynomial_cutoff=num_polynomial_cutoff, + radial_type=radial_type, + distance_transform=distance_transform, + apply_cutoff=apply_cutoff, + ) + edge_feats_irreps = o3.Irreps(f"{self.radial_embedding.out_dim}x0e") + if pair_repulsion: + self.pair_repulsion_fn = ZBLBasis(p=num_polynomial_cutoff) + self.pair_repulsion = True + + if not use_so3: + sh_irreps = o3.Irreps.spherical_harmonics(max_ell) + else: + sh_irreps = o3.Irreps.spherical_harmonics(max_ell, p=1) + num_features = hidden_irreps.count(o3.Irrep(0, 1)) + + # interaction_irreps = (sh_irreps * num_features).sort()[0].simplify() + def generate_irreps(l): + str_irrep = "+".join([f"1x{i}e+1x{i}o" for i in range(l + 1)]) + return o3.Irreps(str_irrep) + + sh_irreps_inter = sh_irreps + if hidden_irreps.count(o3.Irrep(0, -1)) > 0: + sh_irreps_inter = generate_irreps(max_ell) + interaction_irreps = (sh_irreps_inter * num_features).sort()[0].simplify() + interaction_irreps_first = (sh_irreps * num_features).sort()[0].simplify() + + self.spherical_harmonics = o3.SphericalHarmonics( + sh_irreps, normalize=True, normalization="component" + ) + if radial_MLP is None: + radial_MLP = [64, 64, 64] + # Interactions and readout + self.atomic_energies_fn = AtomicEnergiesBlock(atomic_energies) + if num_interactions == 1: + hidden_irreps_out = str(hidden_irreps[0]) + else: + hidden_irreps_out = hidden_irreps + edge_irreps_first = None + if use_edge_irreps_first and edge_irreps is not None: + edge_irreps_first = o3.Irreps(f"{edge_irreps.count(o3.Irrep(0, 1))}x0e") + inter = interaction_cls_first( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=node_feats_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps_first, + hidden_irreps=hidden_irreps_out, + edge_irreps=edge_irreps_first, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + cueq_config=cueq_config, + oeq_config=oeq_config, + ) + self.interactions = torch.nn.ModuleList([inter]) + + # Use the appropriate self connection at the first layer for proper E0 + use_sc_first = False + if "Residual" in str(interaction_cls_first): + use_sc_first = True + + node_feats_irreps_out = inter.target_irreps + prod = EquivariantProductBasisBlock( + node_feats_irreps=node_feats_irreps_out, + target_irreps=hidden_irreps_out, + correlation=correlation[0], + num_elements=num_elements, + use_sc=use_sc_first, + cueq_config=cueq_config, + oeq_config=oeq_config, + use_reduced_cg=use_reduced_cg, + use_agnostic_product=use_agnostic_product, + ) + self.products = torch.nn.ModuleList([prod]) + + self.readouts = torch.nn.ModuleList() + if not use_last_readout_only: + self.readouts.append( + LinearReadoutBlock( + hidden_irreps_out, + o3.Irreps(f"{len(heads)}x0e"), + cueq_config, + oeq_config, + ) + ) + + for i in range(num_interactions - 1): + if i == num_interactions - 2: + hidden_irreps_out = str( + hidden_irreps[0] + ) # Select only scalars for last layer + else: + hidden_irreps_out = hidden_irreps + inter = interaction_cls( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=hidden_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps_out, + avg_num_neighbors=avg_num_neighbors, + edge_irreps=edge_irreps, + radial_MLP=radial_MLP, + cueq_config=cueq_config, + oeq_config=oeq_config, + ) + self.interactions.append(inter) + prod = EquivariantProductBasisBlock( + node_feats_irreps=interaction_irreps, + target_irreps=hidden_irreps_out, + correlation=correlation[i + 1], + num_elements=num_elements, + use_sc=True, + cueq_config=cueq_config, + oeq_config=oeq_config, + use_reduced_cg=use_reduced_cg, + use_agnostic_product=use_agnostic_product, + ) + self.products.append(prod) + if i == num_interactions - 2: + self.readouts.append( + readout_cls( + hidden_irreps_out, + (len(heads) * MLP_irreps).simplify(), + gate, + o3.Irreps(f"{len(heads)}x0e"), + len(heads), + cueq_config, + oeq_config, + ) + ) + elif not use_last_readout_only: + self.readouts.append( + LinearReadoutBlock( + hidden_irreps, + o3.Irreps(f"{len(heads)}x0e"), + cueq_config, + oeq_config, + ) + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, + compute_force: bool = True, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_hessian: bool = False, + compute_edge_forces: bool = False, + compute_atomic_stresses: bool = False, + lammps_mliap: bool = False, + ) -> Dict[str, Optional[torch.Tensor]]: + # Setup + ctx = prepare_graph( + data, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_displacement=compute_displacement, + lammps_mliap=lammps_mliap, + ) + is_lammps = ctx.is_lammps + num_atoms_arange = ctx.num_atoms_arange.to(torch.int64) + num_graphs = ctx.num_graphs + displacement = ctx.displacement + positions = ctx.positions + vectors = ctx.vectors + lengths = ctx.lengths + cell = ctx.cell + node_heads = ctx.node_heads.to(torch.int64) + interaction_kwargs = ctx.interaction_kwargs + lammps_natoms = interaction_kwargs.lammps_natoms + lammps_class = interaction_kwargs.lammps_class + + + + + # Atomic energies + node_e0 = self.atomic_energies_fn(data["node_attrs"])[ + num_atoms_arange, node_heads + ] + e0 = scatter_sum( + src=node_e0, index=data["batch"], dim=0, dim_size=num_graphs + ).to( + vectors.dtype + ) # [n_graphs, n_heads] + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + if hasattr(self, "pair_repulsion"): + pair_node_energy = self.pair_repulsion_fn( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + if is_lammps: + pair_node_energy = pair_node_energy[: lammps_natoms[0]] + pair_energy = scatter_sum( + src=pair_node_energy, index=data["batch"], dim=-1, dim_size=num_graphs + ) # [n_graphs,] + else: + pair_node_energy = torch.zeros_like(node_e0) + pair_energy = torch.zeros_like(e0) + + if hasattr(self, "joint_embedding"): + embedding_features: Dict[str, torch.Tensor] = {} + for name, _ in self.embedding_specs.items(): + embedding_features[name] = data[name] + node_feats += self.joint_embedding( + data["batch"], + embedding_features, + ) + if hasattr(self, "embedding_readout"): + embedding_node_energy = self.embedding_readout( + node_feats, node_heads + ).squeeze(-1) + embedding_energy = scatter_sum( + src=embedding_node_energy, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) + e0 += embedding_energy + + # Interactions + energies = [e0, pair_energy] + node_energies_list = [node_e0, pair_node_energy] + node_feats_concat: List[torch.Tensor] = [] + + for i, (interaction, product) in enumerate( + zip(self.interactions, self.products) + ): + node_attrs_slice = data["node_attrs"] + if is_lammps and i > 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats, sc = interaction( + node_attrs=node_attrs_slice, + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + first_layer=(i == 0), + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + ) + if is_lammps and i == 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats = product( + node_feats=node_feats, sc=sc, node_attrs=node_attrs_slice + ) + node_feats_concat.append(node_feats) + + for i, readout in enumerate(self.readouts): + feat_idx = -1 if len(self.readouts) == 1 else i + node_es = readout(node_feats_concat[feat_idx], node_heads)[ + num_atoms_arange, node_heads + ] + energy = scatter_sum(node_es, data["batch"], dim=0, dim_size=num_graphs) + energies.append(energy) + node_energies_list.append(node_es) + + contributions = torch.stack(energies, dim=-1) + total_energy = torch.sum(contributions, dim=-1) + node_energy = torch.sum(torch.stack(node_energies_list, dim=-1), dim=-1) + node_feats_out = torch.cat(node_feats_concat, dim=-1) + + forces, virials, stress, hessian, edge_forces = get_outputs( + energy=total_energy, + positions=positions, + displacement=displacement, + vectors=vectors, + cell=cell, + training=training, + compute_force=compute_force, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_hessian=compute_hessian, + compute_edge_forces=compute_edge_forces, + ) + + atomic_virials: Optional[torch.Tensor] = None + atomic_stresses: Optional[torch.Tensor] = None + if compute_atomic_stresses and edge_forces is not None: + atomic_virials, atomic_stresses = get_atomic_virials_stresses( + edge_forces=edge_forces, + edge_index=data["edge_index"], + vectors=vectors, + num_atoms=positions.shape[0], + batch=data["batch"], + cell=cell, + ) + return { + "energy": total_energy, + "node_energy": node_energy, + "contributions": contributions, + "forces": forces, + "edge_forces": edge_forces, + "virials": virials, + "stress": stress, + "atomic_virials": atomic_virials, + "atomic_stresses": atomic_stresses, + "displacement": displacement, + "hessian": hessian, + "node_feats": node_feats_out, + } + + +@compile_mode("script") +class ScaleShiftMACE(MACE): + def __init__( + self, + atomic_inter_scale: float, + atomic_inter_shift: float, + **kwargs, + ): + super().__init__(**kwargs) + self.scale_shift = ScaleShiftBlock( + scale=atomic_inter_scale, shift=atomic_inter_shift + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, + compute_force: bool = True, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_hessian: bool = False, + compute_edge_forces: bool = False, + compute_atomic_stresses: bool = False, + lammps_mliap: bool = False, + ) -> Dict[str, Optional[torch.Tensor]]: + + + + + # Setup + ctx = prepare_graph( + data, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_displacement=compute_displacement, + lammps_mliap=lammps_mliap, + ) + + is_lammps = ctx.is_lammps + num_atoms_arange = ctx.num_atoms_arange.to(torch.int64) + num_graphs = ctx.num_graphs + displacement = ctx.displacement + positions = ctx.positions + vectors = ctx.vectors + lengths = ctx.lengths + cell = ctx.cell + node_heads = ctx.node_heads.to(torch.int64) + interaction_kwargs = ctx.interaction_kwargs + lammps_natoms = interaction_kwargs.lammps_natoms + lammps_class = interaction_kwargs.lammps_class + + + # Atomic energies + node_e0 = self.atomic_energies_fn(data["node_attrs"])[ + num_atoms_arange, node_heads + ] + e0 = scatter_sum( + src=node_e0, index=data["batch"], dim=0, dim_size=num_graphs + ).to( + vectors.dtype + ) # [n_graphs, num_heads] + + + + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + + if hasattr(self, "pair_repulsion"): + pair_node_energy = self.pair_repulsion_fn( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + if is_lammps: + pair_node_energy = pair_node_energy[: lammps_natoms[0]] + else: + pair_node_energy = torch.zeros_like(node_e0) + + # Embeddings of additional features + if hasattr(self, "joint_embedding"): + embedding_features: Dict[str, torch.Tensor] = {} + for name, _ in self.embedding_specs.items(): + embedding_features[name] = data[name] + node_feats += self.joint_embedding( + data["batch"], + embedding_features, + ) + if hasattr(self, "embedding_readout"): + embedding_node_energy = torch.atleast_1d( + self.embedding_readout(node_feats, node_heads)[ + num_atoms_arange, node_heads + ].squeeze(-1) + ) + embedding_energy = scatter_sum( + src=embedding_node_energy, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) + e0 += embedding_energy + + # Interactions + node_es_list = [pair_node_energy] + node_feats_list: List[torch.Tensor] = [] + + for i, (interaction, product) in enumerate( + zip(self.interactions, self.products) + ): + node_attrs_slice = data["node_attrs"] + if is_lammps and i > 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats, sc = interaction( + node_attrs=node_attrs_slice, + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + first_layer=(i == 0), + lammps_class=lammps_class, + lammps_natoms=lammps_natoms, + ) + if is_lammps and i == 0: + node_attrs_slice = node_attrs_slice[: lammps_natoms[0]] + node_feats = product( + node_feats=node_feats, sc=sc, node_attrs=node_attrs_slice + ) + node_feats_list.append(node_feats) + + for i, readout in enumerate(self.readouts): + feat_idx = -1 if len(self.readouts) == 1 else i + node_es_list.append( + readout(node_feats_list[feat_idx], node_heads)[ + num_atoms_arange, node_heads + ] + ) + + node_feats_out = torch.cat(node_feats_list, dim=-1) + node_inter_es = torch.sum(torch.stack(node_es_list, dim=0), dim=0) + node_inter_es = self.scale_shift(node_inter_es, node_heads) + inter_e = scatter_sum(node_inter_es, data["batch"], dim=-1, dim_size=num_graphs) + + + total_energy = e0 + inter_e + node_energy = node_e0.clone().double() + node_inter_es.clone().double() + + forces, virials, stress, hessian, edge_forces = get_outputs( + energy=inter_e, + positions=positions, + displacement=displacement, + vectors=vectors, + cell=cell, + training=training, + compute_force=compute_force, + compute_virials=compute_virials, + compute_stress=compute_stress, + compute_hessian=compute_hessian, + compute_edge_forces=compute_edge_forces or compute_atomic_stresses, + ) + + atomic_virials: Optional[torch.Tensor] = None + atomic_stresses: Optional[torch.Tensor] = None + if compute_atomic_stresses and edge_forces is not None: + atomic_virials, atomic_stresses = get_atomic_virials_stresses( + edge_forces=edge_forces, + edge_index=data["edge_index"], + vectors=vectors, + num_atoms=positions.shape[0], + batch=data["batch"], + cell=cell, + ) + return { + "energy": total_energy, + "node_energy": node_energy, + "interaction_energy": inter_e, + "forces": forces, + "edge_forces": edge_forces, + "virials": virials, + "stress": stress, + "atomic_virials": atomic_virials, + "atomic_stresses": atomic_stresses, + "hessian": hessian, + "displacement": displacement, + "node_feats": node_feats_out, + } + + +@compile_mode("script") +class AtomicDipolesMACE(torch.nn.Module): + def __init__( + self, + r_max: float, + num_bessel: int, + num_polynomial_cutoff: int, + max_ell: int, + interaction_cls: Type[InteractionBlock], + interaction_cls_first: Type[InteractionBlock], + num_interactions: int, + num_elements: int, + hidden_irreps: o3.Irreps, + MLP_irreps: o3.Irreps, + avg_num_neighbors: float, + atomic_numbers: List[int], + correlation: int, + gate: Optional[Callable], + atomic_energies: Optional[ + None + ], # Just here to make it compatible with energy models, MUST be None + apply_cutoff: bool = True, # pylint: disable=unused-argument + use_reduced_cg: bool = True, # pylint: disable=unused-argument + use_so3: bool = False, # pylint: disable=unused-argument + distance_transform: str = "None", # pylint: disable=unused-argument + radial_type: Optional[str] = "bessel", + radial_MLP: Optional[List[int]] = None, + cueq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + oeq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + edge_irreps: Optional[o3.Irreps] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.register_buffer( + "atomic_numbers", torch.tensor(atomic_numbers, dtype=torch.int64) + ) + self.register_buffer("r_max", torch.tensor(r_max, dtype=torch.float64)) + self.register_buffer( + "num_interactions", torch.tensor(num_interactions, dtype=torch.int64) + ) + assert atomic_energies is None + + # Embedding + node_attr_irreps = o3.Irreps([(num_elements, (0, 1))]) + node_feats_irreps = o3.Irreps([(hidden_irreps.count(o3.Irrep(0, 1)), (0, 1))]) + self.node_embedding = LinearNodeEmbeddingBlock( + irreps_in=node_attr_irreps, irreps_out=node_feats_irreps + ) + self.radial_embedding = RadialEmbeddingBlock( + r_max=r_max, + num_bessel=num_bessel, + num_polynomial_cutoff=num_polynomial_cutoff, + radial_type=radial_type, + ) + edge_feats_irreps = o3.Irreps(f"{self.radial_embedding.out_dim}x0e") + + sh_irreps = o3.Irreps.spherical_harmonics(max_ell) + num_features = hidden_irreps.count(o3.Irrep(0, 1)) + interaction_irreps = (sh_irreps * num_features).sort()[0].simplify() + self.spherical_harmonics = o3.SphericalHarmonics( + sh_irreps, normalize=True, normalization="component" + ) + if radial_MLP is None: + radial_MLP = [64, 64, 64] + + # Interactions and readouts + inter = interaction_cls_first( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=node_feats_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions = torch.nn.ModuleList([inter]) + + # Use the appropriate self connection at the first layer + use_sc_first = False + if "Residual" in str(interaction_cls_first): + use_sc_first = True + + node_feats_irreps_out = inter.target_irreps + prod = EquivariantProductBasisBlock( + node_feats_irreps=node_feats_irreps_out, + target_irreps=hidden_irreps, + correlation=correlation, + num_elements=num_elements, + use_sc=use_sc_first, + ) + self.products = torch.nn.ModuleList([prod]) + + self.readouts = torch.nn.ModuleList() + self.readouts.append(LinearDipoleReadoutBlock(hidden_irreps, dipole_only=True)) + + for i in range(num_interactions - 1): + if i == num_interactions - 2: + assert ( + len(hidden_irreps) > 1 + ), "To predict dipoles use at least l=1 hidden_irreps" + hidden_irreps_out = str( + hidden_irreps[1] + ) # Select only l=1 vectors for last layer + else: + hidden_irreps_out = hidden_irreps + inter = interaction_cls( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=hidden_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps_out, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions.append(inter) + prod = EquivariantProductBasisBlock( + node_feats_irreps=interaction_irreps, + target_irreps=hidden_irreps_out, + correlation=correlation, + num_elements=num_elements, + use_sc=True, + ) + self.products.append(prod) + if i == num_interactions - 2: + self.readouts.append( + NonLinearDipoleReadoutBlock( + hidden_irreps_out, MLP_irreps, gate, dipole_only=True + ) + ) + else: + self.readouts.append( + LinearDipoleReadoutBlock(hidden_irreps, dipole_only=True) + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, # pylint: disable=W0613 + compute_force: bool = False, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_edge_forces: bool = False, # pylint: disable=W0613 + compute_atomic_stresses: bool = False, # pylint: disable=W0613 + ) -> Dict[str, Optional[torch.Tensor]]: + assert compute_force is False + assert compute_virials is False + assert compute_stress is False + assert compute_displacement is False + # Setup + data["node_attrs"].requires_grad_(True) + data["positions"].requires_grad_(True) + num_graphs = data["ptr"].numel() - 1 + + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + vectors, lengths = get_edge_vectors_and_lengths( + positions=data["positions"], + edge_index=data["edge_index"], + shifts=data["shifts"], + ) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + + # Interactions + dipoles = [] + for interaction, product, readout in zip( + self.interactions, self.products, self.readouts + ): + node_feats, sc = interaction( + node_attrs=data["node_attrs"], + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + ) + node_feats = product( + node_feats=node_feats, + sc=sc, + node_attrs=data["node_attrs"], + ) + node_dipoles = readout(node_feats).squeeze(-1) # [n_nodes,3] + dipoles.append(node_dipoles) + + # Compute the dipoles + contributions_dipoles = torch.stack( + dipoles, dim=-1 + ) # [n_nodes,3,n_contributions] + atomic_dipoles = torch.sum(contributions_dipoles, dim=-1) # [n_nodes,3] + total_dipole = scatter_sum( + src=atomic_dipoles, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) # [n_graphs,3] + baseline = compute_fixed_charge_dipole( + charges=data["charges"], + positions=data["positions"], + batch=data["batch"], + num_graphs=num_graphs, + ) # [n_graphs,3] + total_dipole = total_dipole + baseline + + output = { + "dipole": total_dipole, + "atomic_dipoles": atomic_dipoles, + } + return output + + +@compile_mode("script") +class AtomicDielectricMACE(torch.nn.Module): + def __init__( + self, + r_max: float, + num_bessel: int, + num_polynomial_cutoff: int, + max_ell: int, + interaction_cls: Type[InteractionBlock], + interaction_cls_first: Type[InteractionBlock], + num_interactions: int, + num_elements: int, + hidden_irreps: o3.Irreps, + MLP_irreps: o3.Irreps, + avg_num_neighbors: float, + atomic_numbers: List[int], + correlation: int, + gate: Optional[Callable], + atomic_energies: Optional[ + None + ], # Just here to make it compatible with energy models, MUST be None + apply_cutoff: bool = True, # pylint: disable=unused-argument + use_reduced_cg: bool = True, # pylint: disable=unused-argument + use_so3: bool = False, # pylint: disable=unused-argument + distance_transform: str = "None", # pylint: disable=unused-argument + radial_type: Optional[str] = "bessel", + radial_MLP: Optional[List[int]] = None, + cueq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + oeq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + edge_irreps: Optional[o3.Irreps] = None, # pylint: disable=unused-argument + dipole_only: Optional[bool] = True, # pylint: disable=unused-argument + use_polarizability: Optional[bool] = True, # pylint: disable=unused-argument + means_stds: Optional[Dict[str, torch.Tensor]] = None, # pylint: disable=W0613 + ): + super().__init__() + self.register_buffer( + "atomic_numbers", torch.tensor(atomic_numbers, dtype=torch.int64) + ) + self.register_buffer("r_max", torch.tensor(r_max, dtype=torch.float64)) + self.register_buffer( + "num_interactions", torch.tensor(num_interactions, dtype=torch.int64) + ) + + # Predefine buffers to be TorchScript-safe + self.register_buffer("dipole_mean", torch.zeros(3)) + self.register_buffer("dipole_std", torch.ones(3)) + self.register_buffer( + "polarizability_mean", torch.zeros(3, 3) + ) # 3x3 matrix flattened + self.use_polarizability = use_polarizability + self.register_buffer("polarizability_std", torch.ones(3, 3)) + self.register_buffer("change_of_basis", get_change_of_basis()) + # self.register_buffer("mean_polarizability_sh", torch.zeros(6)) + # self.register_buffer("std_polarizability_sh", torch.ones(6)) + if means_stds is not None: + if "dipole_mean" in means_stds: + self.dipole_mean.data.copy_(means_stds["dipole_mean"]) + if "dipole_std" in means_stds: + self.dipole_std.data.copy_(means_stds["dipole_std"]) + if "polarizability_mean" in means_stds: + self.polarizability_mean.data.copy_(means_stds["polarizability_mean"]) + if "polarizability_std" in means_stds: + self.polarizability_std.data.copy_(means_stds["polarizability_std"]) + # if "mean_polarizability_sh" in means_stds: + # self.mean_polarizability_sh.data.copy_(means_stds["mean_polarizability_sh"]) + # if "std_polarizability_sh" in means_stds: + # self.std_polarizability_sh.data.copy_(means_stds["std_polarizability_sh"])''' + assert atomic_energies is None + # self.use_polarizability = use_polarizability + # self.use_dipole = use_dipole + + # Embedding + node_attr_irreps = o3.Irreps([(num_elements, (0, 1))]) + node_feats_irreps = o3.Irreps([(hidden_irreps.count(o3.Irrep(0, 1)), (0, 1))]) + self.node_embedding = LinearNodeEmbeddingBlock( + irreps_in=node_attr_irreps, irreps_out=node_feats_irreps + ) + self.radial_embedding = RadialEmbeddingBlock( + r_max=r_max, + num_bessel=num_bessel, + num_polynomial_cutoff=num_polynomial_cutoff, + radial_type=radial_type, + ) + edge_feats_irreps = o3.Irreps(f"{self.radial_embedding.out_dim}x0e") + + sh_irreps = o3.Irreps.spherical_harmonics(max_ell) + num_features = hidden_irreps.count(o3.Irrep(0, 1)) + interaction_irreps = (sh_irreps * num_features).sort()[0].simplify() + self.spherical_harmonics = o3.SphericalHarmonics( + sh_irreps, normalize=True, normalization="component" + ) + if radial_MLP is None: + radial_MLP = [64, 64, 64] + + # Interactions and readouts + inter = interaction_cls_first( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=node_feats_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions = torch.nn.ModuleList([inter]) + + # Use the appropriate self connection at the first layer + use_sc_first = False + if "Residual" in str(interaction_cls_first): + use_sc_first = True + + node_feats_irreps_out = inter.target_irreps + prod = EquivariantProductBasisBlock( + node_feats_irreps=node_feats_irreps_out, + target_irreps=hidden_irreps, + correlation=correlation, + num_elements=num_elements, + use_sc=use_sc_first, + ) + self.products = torch.nn.ModuleList([prod]) + + self.readouts = torch.nn.ModuleList() + self.readouts.append( + LinearDipolePolarReadoutBlock(hidden_irreps, use_polarizability=True) + ) + + for i in range(num_interactions - 1): + if i == num_interactions - 2: + # does it always do polar and dipole together? + assert ( + len(hidden_irreps) > 1 + ), "To predict dipoles use at least l=1 hidden_irreps" + # hidden_irreps_out = str( + # hidden_irreps[1] + # ) # Select only l=1 vectors for last layer + hidden_irreps_out = ( + hidden_irreps # this is different in the AtomicDipoleMACE + ) + else: + hidden_irreps_out = hidden_irreps + inter = interaction_cls( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=hidden_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps_out, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions.append(inter) + prod = EquivariantProductBasisBlock( + node_feats_irreps=interaction_irreps, + target_irreps=hidden_irreps_out, + correlation=correlation, + num_elements=num_elements, + use_sc=True, + ) + self.products.append(prod) + if i == num_interactions - 2: + self.readouts.append( + NonLinearDipolePolarReadoutBlock( + hidden_irreps_out, + MLP_irreps, + gate, + use_polarizability=True, + ) + ) + # print("Nonlinear irrpes: ", hidden_irreps_out, MLP_irreps) + # exit() + else: + self.readouts.append( + LinearDipolePolarReadoutBlock( + hidden_irreps, + # use_charge=True, + use_polarizability=True, + ) + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, # pylint: disable=W0613 + compute_force: bool = False, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_dielectric_derivatives: bool = False, # no training on derivatives + compute_edge_forces: bool = False, # pylint: disable=W0613 + compute_atomic_stresses: bool = False, # pylint: disable=W0613 + ) -> Dict[str, Optional[torch.Tensor]]: + assert compute_force is False + assert compute_virials is False + assert compute_stress is False + assert compute_displacement is False + # Setup + data["node_attrs"].requires_grad_(True) + data["positions"].requires_grad_(True) + num_graphs = data["ptr"].numel() - 1 + num_atoms = data["ptr"][1:] - data["ptr"][:-1] + + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + vectors, lengths = get_edge_vectors_and_lengths( + positions=data["positions"], + edge_index=data["edge_index"], + shifts=data["shifts"], + ) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + + # Interactions + charges = [] + dipoles = [] + polarizabilities = [] + for interaction, product, readout in zip( + self.interactions, self.products, self.readouts + ): + node_feats, sc = interaction( + node_attrs=data["node_attrs"], + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + ) + + node_feats = product( + node_feats=node_feats, + sc=sc, + node_attrs=data["node_attrs"], + ) + + node_out = readout(node_feats).squeeze(-1) # [n_nodes,3] + charges.append(node_out[:, 0]) + + if self.use_polarizability: + node_dipoles = node_out[:, 2:5] + node_polarizability = torch.cat( + (node_out[:, 1].unsqueeze(-1), node_out[:, 5:]), dim=-1 + ) + polarizabilities.append(node_polarizability) + dipoles.append(node_dipoles) + else: + node_dipoles = node_out[:, 1:4] + dipoles.append(node_dipoles) + # raise ValueError( + # "Polarizability is not used in this model, but it is required for the AtomicDielectricMACE." + # ) + contributions_dipoles = torch.stack( + dipoles, dim=-1 + ) # [n_nodes,3,n_contributions] + atomic_dipoles = torch.sum(contributions_dipoles, dim=-1) # [n_nodes,3] + atomic_charges = torch.stack(charges, dim=-1).sum(-1) # [n_nodes,] + # The idea is to normalize the charges so that they sum to the net charge in the system before predicting the dipole. + total_charge_excess = scatter_mean( + src=atomic_charges, index=data["batch"], dim_size=num_graphs + ) - (data["total_charge"] / num_atoms) + atomic_charges = atomic_charges - total_charge_excess[data["batch"]] + total_dipole = scatter_sum( + src=atomic_dipoles, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) # [n_graphs,3] + baseline = compute_fixed_charge_dipole_polar( + charges=atomic_charges, # or data["charges"], ????? + positions=data["positions"], + batch=data["batch"], + num_graphs=num_graphs, + ) # [n_graphs,3] + total_dipole = total_dipole + baseline + + if self.use_polarizability: + # Compute the polarizabilities + contributions_polarizabilities = torch.stack( + polarizabilities, dim=-1 + ) # [n_nodes,6,n_contributions] + atomic_polarizabilities = torch.sum( + contributions_polarizabilities, dim=-1 + ) # [n_nodes,6] + total_polarizability_spherical = scatter_sum( + src=atomic_polarizabilities, + index=data["batch"], + dim=0, + dim_size=num_graphs, + ) # [n_graphs,6] + total_polarizability = spherical_to_cartesian( + total_polarizability_spherical, self.change_of_basis + ) + + if compute_dielectric_derivatives: + dmu_dr = compute_dielectric_gradients( + dielectric=total_dipole, + positions=data["positions"], + ) + dalpha_dr = compute_dielectric_gradients( + dielectric=total_polarizability.flatten(-2), + positions=data["positions"], + ) + else: + dmu_dr = None + dalpha_dr = None + else: + if compute_dielectric_derivatives: + dmu_dr = compute_dielectric_gradients( + dielectric=total_dipole, + positions=data["positions"], + ) + else: + dmu_dr = None + total_polarizability = None + total_polarizability_spherical = None + dalpha_dr = None + + output = { + "charges": atomic_charges, + "dipole": total_dipole, + "atomic_dipoles": atomic_dipoles, + "polarizability": total_polarizability, + "polarizability_sh": total_polarizability_spherical, + "dmu_dr": dmu_dr, + "dalpha_dr": dalpha_dr, + } + return output + + +@compile_mode("script") +class EnergyDipolesMACE(torch.nn.Module): + def __init__( + self, + r_max: float, + num_bessel: int, + num_polynomial_cutoff: int, + max_ell: int, + interaction_cls: Type[InteractionBlock], + interaction_cls_first: Type[InteractionBlock], + num_interactions: int, + num_elements: int, + hidden_irreps: o3.Irreps, + MLP_irreps: o3.Irreps, + avg_num_neighbors: float, + atomic_numbers: List[int], + correlation: int, + gate: Optional[Callable], + atomic_energies: Optional[np.ndarray], + apply_cutoff: bool = True, # pylint: disable=unused-argument + use_reduced_cg: bool = True, # pylint: disable=unused-argument + use_so3: bool = False, # pylint: disable=unused-argument + distance_transform: str = "None", # pylint: disable=unused-argument + radial_MLP: Optional[List[int]] = None, + cueq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + oeq_config: Optional[Dict[str, Any]] = None, # pylint: disable=unused-argument + edge_irreps: Optional[o3.Irreps] = None, # pylint: disable=unused-argument + ): + super().__init__() + self.register_buffer( + "atomic_numbers", torch.tensor(atomic_numbers, dtype=torch.int64) + ) + self.register_buffer("r_max", torch.tensor(r_max, dtype=torch.float64)) + self.register_buffer( + "num_interactions", torch.tensor(num_interactions, dtype=torch.int64) + ) + # Embedding + node_attr_irreps = o3.Irreps([(num_elements, (0, 1))]) + node_feats_irreps = o3.Irreps([(hidden_irreps.count(o3.Irrep(0, 1)), (0, 1))]) + self.node_embedding = LinearNodeEmbeddingBlock( + irreps_in=node_attr_irreps, irreps_out=node_feats_irreps + ) + self.radial_embedding = RadialEmbeddingBlock( + r_max=r_max, + num_bessel=num_bessel, + num_polynomial_cutoff=num_polynomial_cutoff, + ) + edge_feats_irreps = o3.Irreps(f"{self.radial_embedding.out_dim}x0e") + + sh_irreps = o3.Irreps.spherical_harmonics(max_ell) + num_features = hidden_irreps.count(o3.Irrep(0, 1)) + interaction_irreps = (sh_irreps * num_features).sort()[0].simplify() + self.spherical_harmonics = o3.SphericalHarmonics( + sh_irreps, normalize=True, normalization="component" + ) + if radial_MLP is None: + radial_MLP = [64, 64, 64] + # Interactions and readouts + self.atomic_energies_fn = AtomicEnergiesBlock(atomic_energies) + + inter = interaction_cls_first( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=node_feats_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions = torch.nn.ModuleList([inter]) + + # Use the appropriate self connection at the first layer + use_sc_first = False + if "Residual" in str(interaction_cls_first): + use_sc_first = True + + node_feats_irreps_out = inter.target_irreps + prod = EquivariantProductBasisBlock( + node_feats_irreps=node_feats_irreps_out, + target_irreps=hidden_irreps, + correlation=correlation, + num_elements=num_elements, + use_sc=use_sc_first, + ) + self.products = torch.nn.ModuleList([prod]) + + self.readouts = torch.nn.ModuleList() + self.readouts.append(LinearDipoleReadoutBlock(hidden_irreps, dipole_only=False)) + + for i in range(num_interactions - 1): + if i == num_interactions - 2: + assert ( + len(hidden_irreps) > 1 + ), "To predict dipoles use at least l=1 hidden_irreps" + hidden_irreps_out = str( + hidden_irreps[:2] + ) # Select scalars and l=1 vectors for last layer + else: + hidden_irreps_out = hidden_irreps + inter = interaction_cls( + node_attrs_irreps=node_attr_irreps, + node_feats_irreps=hidden_irreps, + edge_attrs_irreps=sh_irreps, + edge_feats_irreps=edge_feats_irreps, + target_irreps=interaction_irreps, + hidden_irreps=hidden_irreps_out, + avg_num_neighbors=avg_num_neighbors, + radial_MLP=radial_MLP, + ) + self.interactions.append(inter) + prod = EquivariantProductBasisBlock( + node_feats_irreps=interaction_irreps, + target_irreps=hidden_irreps_out, + correlation=correlation, + num_elements=num_elements, + use_sc=True, + ) + self.products.append(prod) + if i == num_interactions - 2: + self.readouts.append( + NonLinearDipoleReadoutBlock( + hidden_irreps_out, MLP_irreps, gate, dipole_only=False + ) + ) + else: + self.readouts.append( + LinearDipoleReadoutBlock(hidden_irreps, dipole_only=False) + ) + + def forward( + self, + data: Dict[str, torch.Tensor], + training: bool = False, + compute_force: bool = True, + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + compute_edge_forces: bool = False, # pylint: disable=W0613 + compute_atomic_stresses: bool = False, # pylint: disable=W0613 + ) -> Dict[str, Optional[torch.Tensor]]: + # Setup + data["node_attrs"].requires_grad_(True) + data["positions"].requires_grad_(True) + num_graphs = data["ptr"].numel() - 1 + num_atoms_arange = torch.arange(data["positions"].shape[0]) + displacement = torch.zeros( + (num_graphs, 3, 3), + dtype=data["positions"].dtype, + device=data["positions"].device, + ) + if compute_virials or compute_stress or compute_displacement: + ( + data["positions"], + data["shifts"], + displacement, + ) = get_symmetric_displacement( + positions=data["positions"], + unit_shifts=data["unit_shifts"], + cell=data["cell"], + edge_index=data["edge_index"], + num_graphs=num_graphs, + batch=data["batch"], + ) + + # Atomic energies + node_e0 = self.atomic_energies_fn(data["node_attrs"])[ + num_atoms_arange, data["head"][data["batch"]] + ] + e0 = scatter_sum( + src=node_e0, index=data["batch"], dim=-1, dim_size=num_graphs + ) # [n_graphs,] + + # Embeddings + node_feats = self.node_embedding(data["node_attrs"]) + vectors, lengths = get_edge_vectors_and_lengths( + positions=data["positions"], + edge_index=data["edge_index"], + shifts=data["shifts"], + ) + edge_attrs = self.spherical_harmonics(vectors) + edge_feats, cutoff = self.radial_embedding( + lengths, data["node_attrs"], data["edge_index"], self.atomic_numbers + ) + + # Interactions + energies = [e0] + node_energies_list = [node_e0] + dipoles = [] + for interaction, product, readout in zip( + self.interactions, self.products, self.readouts + ): + node_feats, sc = interaction( + node_attrs=data["node_attrs"], + node_feats=node_feats, + edge_attrs=edge_attrs, + edge_feats=edge_feats, + edge_index=data["edge_index"], + cutoff=cutoff, + ) + node_feats = product( + node_feats=node_feats, + sc=sc, + node_attrs=data["node_attrs"], + ) + node_out = readout(node_feats).squeeze(-1) # [n_nodes, ] + # node_energies = readout(node_feats).squeeze(-1) # [n_nodes, ] + node_energies = node_out[:, 0] + energy = scatter_sum( + src=node_energies, index=data["batch"], dim=-1, dim_size=num_graphs + ) # [n_graphs,] + energies.append(energy) + node_dipoles = node_out[:, 1:] + dipoles.append(node_dipoles) + + # Compute the energies and dipoles + contributions = torch.stack(energies, dim=-1) + total_energy = torch.sum(contributions, dim=-1) # [n_graphs, ] + node_energy_contributions = torch.stack(node_energies_list, dim=-1) + node_energy = torch.sum(node_energy_contributions, dim=-1) # [n_nodes, ] + contributions_dipoles = torch.stack( + dipoles, dim=-1 + ) # [n_nodes,3,n_contributions] + atomic_dipoles = torch.sum(contributions_dipoles, dim=-1) # [n_nodes,3] + total_dipole = scatter_sum( + src=atomic_dipoles, + index=data["batch"].unsqueeze(-1), + dim=0, + dim_size=num_graphs, + ) # [n_graphs,3] + baseline = compute_fixed_charge_dipole( + charges=data["charges"], + positions=data["positions"], + batch=data["batch"], + num_graphs=num_graphs, + ) # [n_graphs,3] + total_dipole = total_dipole + baseline + + forces, virials, stress, _, _ = get_outputs( + energy=total_energy, + positions=data["positions"], + displacement=displacement, + cell=data["cell"], + training=training, + compute_force=compute_force, + compute_virials=compute_virials, + compute_stress=compute_stress, + ) + + output = { + "energy": total_energy, + "node_energy": node_energy, + "contributions": contributions, + "forces": forces, + "virials": virials, + "stress": stress, + "displacement": displacement, + "dipole": total_dipole, + "atomic_dipoles": atomic_dipoles, + } + return output diff --git a/models/mace/mace/modules/radial.py b/models/mace/mace/modules/radial.py new file mode 100644 index 0000000000000000000000000000000000000000..5e19204bd8a1b4e7621b9411e608049512b468a9 --- /dev/null +++ b/models/mace/mace/modules/radial.py @@ -0,0 +1,384 @@ +########################################################################################### +# Radial basis and cutoff +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import logging + +import ase +import numpy as np +import torch +from e3nn.util.jit import compile_mode + +from mace.tools.scatter import scatter_sum + + +@compile_mode("script") +class BesselBasis(torch.nn.Module): + """ + Equation (7) + """ + + def __init__(self, r_max: float, num_basis=8, trainable=False): + super().__init__() + + bessel_weights = ( + np.pi + / r_max + * torch.linspace( + start=1.0, + end=num_basis, + steps=num_basis, + dtype=torch.get_default_dtype(), + ) + ) + if trainable: + self.bessel_weights = torch.nn.Parameter(bessel_weights) + else: + self.register_buffer("bessel_weights", bessel_weights) + + self.register_buffer( + "r_max", torch.tensor(r_max, dtype=torch.get_default_dtype()) + ) + self.register_buffer( + "prefactor", + torch.tensor(np.sqrt(2.0 / r_max), dtype=torch.get_default_dtype()), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [..., 1] + numerator = torch.sin(self.bessel_weights * x) # [..., num_basis] + return self.prefactor * (numerator / x) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(r_max={self.r_max}, num_basis={len(self.bessel_weights)}, " + f"trainable={self.bessel_weights.requires_grad})" + ) + + +@compile_mode("script") +class ChebychevBasis(torch.nn.Module): + """ + Equation (7) + """ + + def __init__(self, r_max: float, num_basis=8): + super().__init__() + self.register_buffer( + "n", + torch.arange(1, num_basis + 1, dtype=torch.get_default_dtype()).unsqueeze( + 0 + ), + ) + self.num_basis = num_basis + self.r_max = r_max + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [..., 1] + x = x.repeat(1, self.num_basis) + n = self.n.repeat(len(x), 1) + return torch.special.chebyshev_polynomial_t(x, n) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(r_max={self.r_max}, num_basis={self.num_basis}," + ) + + +@compile_mode("script") +class GaussianBasis(torch.nn.Module): + """ + Gaussian basis functions + """ + + def __init__(self, r_max: float, num_basis=128, trainable=False): + super().__init__() + gaussian_weights = torch.linspace( + start=0.0, end=r_max, steps=num_basis, dtype=torch.get_default_dtype() + ) + if trainable: + self.gaussian_weights = torch.nn.Parameter( + gaussian_weights, requires_grad=True + ) + else: + self.register_buffer("gaussian_weights", gaussian_weights) + self.coeff = -0.5 / (r_max / (num_basis - 1)) ** 2 + + def forward(self, x: torch.Tensor) -> torch.Tensor: # [..., 1] + x = x - self.gaussian_weights + return torch.exp(self.coeff * torch.pow(x, 2)) + + +@compile_mode("script") +class PolynomialCutoff(torch.nn.Module): + """Polynomial cutoff function that goes from 1 to 0 as x goes from 0 to r_max. + Equation (8) -- TODO: from where? + """ + + p: torch.Tensor + r_max: torch.Tensor + + def __init__(self, r_max: float, p=6): + super().__init__() + self.register_buffer("p", torch.tensor(p, dtype=torch.int)) + self.register_buffer( + "r_max", torch.tensor(r_max, dtype=torch.get_default_dtype()) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.calculate_envelope(x, self.r_max, self.p.to(torch.int)) + + @staticmethod + def calculate_envelope( + x: torch.Tensor, r_max: torch.Tensor, p: torch.Tensor + ) -> torch.Tensor: + r_over_r_max = x / r_max + envelope = ( + 1.0 + - ((p + 1.0) * (p + 2.0) / 2.0) * torch.pow(r_over_r_max, p) + + p * (p + 2.0) * torch.pow(r_over_r_max, p + 1) + - (p * (p + 1.0) / 2) * torch.pow(r_over_r_max, p + 2) + ) + return envelope * (x < r_max) + + def __repr__(self): + return f"{self.__class__.__name__}(p={self.p}, r_max={self.r_max})" + + +@compile_mode("script") +class ZBLBasis(torch.nn.Module): + """Implementation of the Ziegler-Biersack-Littmark (ZBL) potential + with a polynomial cutoff envelope. + """ + + p: torch.Tensor + + def __init__(self, p=6, trainable=False, **kwargs): + super().__init__() + if "r_max" in kwargs: + logging.warning( + "r_max is deprecated. r_max is determined from the covalent radii." + ) + + # Pre-calculate the p coefficients for the ZBL potential + self.register_buffer( + "c", + torch.tensor( + [0.1818, 0.5099, 0.2802, 0.02817], dtype=torch.get_default_dtype() + ), + ) + self.register_buffer("p", torch.tensor(p, dtype=torch.int)) + self.register_buffer( + "covalent_radii", + torch.tensor( + ase.data.covalent_radii, + dtype=torch.get_default_dtype(), + ), + ) + if trainable: + self.a_exp = torch.nn.Parameter(torch.tensor(0.300, requires_grad=True)) + self.a_prefactor = torch.nn.Parameter( + torch.tensor(0.4543, requires_grad=True) + ) + else: + self.register_buffer("a_exp", torch.tensor(0.300)) + self.register_buffer("a_prefactor", torch.tensor(0.4543)) + + def forward( + self, + x: torch.Tensor, + node_attrs: torch.Tensor, + edge_index: torch.Tensor, + atomic_numbers: torch.Tensor, + ) -> torch.Tensor: + sender = edge_index[0] + receiver = edge_index[1] + node_atomic_numbers = atomic_numbers[torch.argmax(node_attrs, dim=1)].unsqueeze( + -1 + ) + Z_u = node_atomic_numbers[sender].to(torch.int64) + Z_v = node_atomic_numbers[receiver].to(torch.int64) + a = ( + self.a_prefactor + * 0.529 + / (torch.pow(Z_u, self.a_exp) + torch.pow(Z_v, self.a_exp)) + ) + r_over_a = x / a + phi = ( + self.c[0] * torch.exp(-3.2 * r_over_a) + + self.c[1] * torch.exp(-0.9423 * r_over_a) + + self.c[2] * torch.exp(-0.4028 * r_over_a) + + self.c[3] * torch.exp(-0.2016 * r_over_a) + ) + v_edges = (14.3996 * Z_u * Z_v) / x * phi + r_max = self.covalent_radii[Z_u] + self.covalent_radii[Z_v] + envelope = PolynomialCutoff.calculate_envelope(x, r_max, self.p) + v_edges = 0.5 * v_edges * envelope + V_ZBL = scatter_sum(v_edges, receiver, dim=0, dim_size=node_attrs.size(0)) + return V_ZBL.squeeze(-1) + + def __repr__(self): + return f"{self.__class__.__name__}(c={self.c})" + + +@compile_mode("script") +class AgnesiTransform(torch.nn.Module): + """Agnesi transform - see section on Radial transformations in + ACEpotentials.jl, JCP 2023 (https://doi.org/10.1063/5.0158783). + """ + + def __init__( + self, + q: float = 0.9183, + p: float = 4.5791, + a: float = 1.0805, + trainable=False, + ): + super().__init__() + self.register_buffer("q", torch.tensor(q, dtype=torch.get_default_dtype())) + self.register_buffer("p", torch.tensor(p, dtype=torch.get_default_dtype())) + self.register_buffer("a", torch.tensor(a, dtype=torch.get_default_dtype())) + self.register_buffer( + "covalent_radii", + torch.tensor( + ase.data.covalent_radii, + dtype=torch.get_default_dtype(), + ), + ) + if trainable: + self.a = torch.nn.Parameter(torch.tensor(1.0805, requires_grad=True)) + self.q = torch.nn.Parameter(torch.tensor(0.9183, requires_grad=True)) + self.p = torch.nn.Parameter(torch.tensor(4.5791, requires_grad=True)) + + def forward( + self, + x: torch.Tensor, + node_attrs: torch.Tensor, + edge_index: torch.Tensor, + atomic_numbers: torch.Tensor, + ) -> torch.Tensor: + sender = edge_index[0] + receiver = edge_index[1] + node_atomic_numbers = atomic_numbers[torch.argmax(node_attrs, dim=1)].unsqueeze( + -1 + ) + Z_u = node_atomic_numbers[sender].to(torch.int64) + Z_v = node_atomic_numbers[receiver].to(torch.int64) + r_0: torch.Tensor = 0.5 * (self.covalent_radii[Z_u] + self.covalent_radii[Z_v]) + r_over_r_0 = x / r_0 + return ( + 1 + + ( + self.a + * torch.pow(r_over_r_0, self.q) + / (1 + torch.pow(r_over_r_0, self.q - self.p)) + ) + ).reciprocal_() + + def __repr__(self): + return ( + f"{self.__class__.__name__}(a={self.a:.4f}, q={self.q:.4f}, p={self.p:.4f})" + ) + + +@compile_mode("script") +class SoftTransform(torch.nn.Module): + """ + Tanh-based smooth transformation: + T(x) = p1 + (x - p1)*0.5*[1 + tanh(alpha*(x - m))], + which smoothly transitions from ~p1 for x << p1 to ~x for x >> r0. + """ + + def __init__(self, alpha: float = 4.0, trainable=False): + """ + Args: + p1 (float): Lower "clamp" point. + alpha (float): Steepness; if None, defaults to ~6/(r0-p1). + trainable (bool): Whether to make parameters trainable. + """ + super().__init__() + # Initialize parameters + self.register_buffer( + "alpha", torch.tensor(alpha, dtype=torch.get_default_dtype()) + ) + if trainable: + self.alpha = torch.nn.Parameter(self.alpha.clone()) + self.register_buffer( + "covalent_radii", + torch.tensor( + ase.data.covalent_radii, + dtype=torch.get_default_dtype(), + ), + ) + + def compute_r_0( + self, + node_attrs: torch.Tensor, + edge_index: torch.Tensor, + atomic_numbers: torch.Tensor, + ) -> torch.Tensor: + """ + Compute r_0 based on atomic information. + + Args: + node_attrs (torch.Tensor): Node attributes (one-hot encoding of atomic numbers). + edge_index (torch.Tensor): Edge index indicating connections. + atomic_numbers (torch.Tensor): Atomic numbers. + + Returns: + torch.Tensor: r_0 values for each edge. + """ + sender = edge_index[0] + receiver = edge_index[1] + node_atomic_numbers = atomic_numbers[torch.argmax(node_attrs, dim=1)].unsqueeze( + -1 + ) + Z_u = node_atomic_numbers[sender].to(torch.int64) + Z_v = node_atomic_numbers[receiver].to(torch.int64) + r_0: torch.Tensor = self.covalent_radii[Z_u] + self.covalent_radii[Z_v] + return r_0 + + def forward( + self, + x: torch.Tensor, + node_attrs: torch.Tensor, + edge_index: torch.Tensor, + atomic_numbers: torch.Tensor, + ) -> torch.Tensor: + + r_0 = self.compute_r_0(node_attrs, edge_index, atomic_numbers) + p_0 = (3 / 4) * r_0 + p_1 = (4 / 3) * r_0 + m = 0.5 * (p_0 + p_1) + alpha = self.alpha / (p_1 - p_0) + s_x = 0.5 * (1.0 + torch.tanh(alpha * (x - m))) + return p_0 + (x - p_0) * s_x + + def __repr__(self): + return f"{self.__class__.__name__}(alpha={self.alpha.item():.4f})" + + +class RadialMLP(torch.nn.Module): + """ + Construct a radial MLP (Linear → LayerNorm → SiLU) stack + given a list of channel sizes, following ESEN / FairChem. + """ + + def __init__(self, channels_list) -> None: + super().__init__() + + modules = [] + in_channels = channels_list[0] + + for idx, out_channels in enumerate(channels_list[1:], start=1): + modules.append(torch.nn.Linear(in_channels, out_channels, bias=True)) + in_channels = out_channels + if idx < len(channels_list) - 1: + modules.append(torch.nn.LayerNorm(out_channels)) + modules.append(torch.nn.SiLU()) + + self.net = torch.nn.Sequential(*modules) + self.hs = channels_list + + def forward(self, inputs: torch.Tensor) -> torch.Tensor: + return self.net(inputs) diff --git a/models/mace/mace/modules/symmetric_contraction.py b/models/mace/mace/modules/symmetric_contraction.py new file mode 100644 index 0000000000000000000000000000000000000000..ee25a18d78c6f3a1e5236c962c940a556394648e --- /dev/null +++ b/models/mace/mace/modules/symmetric_contraction.py @@ -0,0 +1,273 @@ +########################################################################################### +# Implementation of the symmetric contraction algorithm presented in the MACE paper +# (Batatia et al, MACE: Higher Order Equivariant Message Passing Neural Networks for Fast and Accurate Force Fields , Eq.10 and 11) +# Authors: Ilyes Batatia +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +from typing import Dict, Optional, Union + +import opt_einsum_fx +import torch +import torch.fx +from e3nn import o3 +from e3nn.util.codegen import CodeGenMixin +from e3nn.util.jit import compile_mode + +from mace.tools.cg import U_matrix_real +from mace.tools.compile import simplify_if_compile + +BATCH_EXAMPLE = 10 +ALPHABET = ["w", "x", "v", "n", "z", "r", "t", "y", "u", "o", "p", "s"] + + +@simplify_if_compile +@compile_mode("script") +class SymmetricContraction(CodeGenMixin, torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + irreps_out: o3.Irreps, + correlation: Union[int, Dict[str, int]], + irrep_normalization: str = "component", + path_normalization: str = "element", + use_reduced_cg: bool = False, + internal_weights: Optional[bool] = None, + shared_weights: Optional[bool] = None, + num_elements: Optional[int] = None, + ) -> None: + super().__init__() + + if irrep_normalization is None: + irrep_normalization = "component" + + if path_normalization is None: + path_normalization = "element" + + assert irrep_normalization in ["component", "norm", "none"] + assert path_normalization in ["element", "path", "none"] + + self.irreps_in = o3.Irreps(irreps_in) + self.irreps_out = o3.Irreps(irreps_out) + + del irreps_in, irreps_out + + if not isinstance(correlation, tuple): + corr = correlation + correlation = {} + for irrep_out in self.irreps_out: + correlation[irrep_out] = corr + + assert shared_weights or not internal_weights + + if internal_weights is None: + internal_weights = True + + self.internal_weights = internal_weights + self.shared_weights = shared_weights + + del internal_weights, shared_weights + + self.contractions = torch.nn.ModuleList() + for irrep_out in self.irreps_out: + self.contractions.append( + Contraction( + irreps_in=self.irreps_in, + irrep_out=o3.Irreps(str(irrep_out.ir)), + correlation=correlation[irrep_out], + internal_weights=self.internal_weights, + num_elements=num_elements, + weights=self.shared_weights, + use_reduced_cg=use_reduced_cg, + ) + ) + + def forward(self, x: torch.Tensor, y: torch.Tensor): + outs = [contraction(x, y) for contraction in self.contractions] + return torch.cat(outs, dim=-1) + + +@compile_mode("script") +class Contraction(torch.nn.Module): + def __init__( + self, + irreps_in: o3.Irreps, + irrep_out: o3.Irreps, + correlation: int, + internal_weights: bool = True, + use_reduced_cg: bool = False, + num_elements: Optional[int] = None, + weights: Optional[torch.Tensor] = None, + ) -> None: + super().__init__() + + self.num_features = irreps_in.count((0, 1)) + self.coupling_irreps = o3.Irreps([irrep.ir for irrep in irreps_in]) + self.correlation = correlation + dtype = torch.get_default_dtype() + + path_weight = [] + for nu in range(1, correlation + 1): + U_matrix = U_matrix_real( + irreps_in=self.coupling_irreps, + irreps_out=irrep_out, + correlation=nu, + use_cueq_cg=use_reduced_cg, + dtype=dtype, + )[-1] + path_weight.append(not torch.equal(U_matrix, torch.zeros_like(U_matrix))) + self.register_buffer(f"U_matrix_{nu}", U_matrix) + + # Tensor contraction equations + self.contractions_weighting = torch.nn.ModuleList() + self.contractions_features = torch.nn.ModuleList() + + # Create weight for product basis + self.weights = torch.nn.ParameterList([]) + + for i in range(correlation, 0, -1): + # Shapes definying + num_params = self.U_tensors(i).size()[-1] + num_equivariance = 2 * irrep_out.lmax + 1 + num_ell = self.U_tensors(i).size()[-2] + + if i == correlation: + parse_subscript_main = ( + [ALPHABET[j] for j in range(i + min(irrep_out.lmax, 1) - 1)] + + ["ik,ekc,bci,be -> bc"] + + [ALPHABET[j] for j in range(i + min(irrep_out.lmax, 1) - 1)] + ) + graph_module_main = torch.fx.symbolic_trace( + lambda x, y, w, z: torch.einsum( + "".join(parse_subscript_main), x, y, w, z + ) + ) + + # Optimizing the contractions + self.graph_opt_main = opt_einsum_fx.optimize_einsums_full( + model=graph_module_main, + example_inputs=( + torch.randn( + [num_equivariance] + [num_ell] * i + [num_params] + ).squeeze(0), + torch.randn((num_elements, num_params, self.num_features)), + torch.randn((BATCH_EXAMPLE, self.num_features, num_ell)), + torch.randn((BATCH_EXAMPLE, num_elements)), + ), + ) + # Parameters for the product basis + w = torch.nn.Parameter( + torch.randn((num_elements, num_params, self.num_features)) + / num_params + ) + self.weights_max = w + else: + # Generate optimized contractions equations + parse_subscript_weighting = ( + [ALPHABET[j] for j in range(i + min(irrep_out.lmax, 1))] + + ["k,ekc,be->bc"] + + [ALPHABET[j] for j in range(i + min(irrep_out.lmax, 1))] + ) + parse_subscript_features = ( + ["bc"] + + [ALPHABET[j] for j in range(i - 1 + min(irrep_out.lmax, 1))] + + ["i,bci->bc"] + + [ALPHABET[j] for j in range(i - 1 + min(irrep_out.lmax, 1))] + ) + + # Symbolic tracing of contractions + graph_module_weighting = torch.fx.symbolic_trace( + lambda x, y, z: torch.einsum( + "".join(parse_subscript_weighting), x, y, z + ) + ) + graph_module_features = torch.fx.symbolic_trace( + lambda x, y: torch.einsum("".join(parse_subscript_features), x, y) + ) + + # Optimizing the contractions + graph_opt_weighting = opt_einsum_fx.optimize_einsums_full( + model=graph_module_weighting, + example_inputs=( + torch.randn( + [num_equivariance] + [num_ell] * i + [num_params] + ).squeeze(0), + torch.randn((num_elements, num_params, self.num_features)), + torch.randn((BATCH_EXAMPLE, num_elements)), + ), + ) + graph_opt_features = opt_einsum_fx.optimize_einsums_full( + model=graph_module_features, + example_inputs=( + torch.randn( + [BATCH_EXAMPLE, self.num_features, num_equivariance] + + [num_ell] * i + ).squeeze(2), + torch.randn((BATCH_EXAMPLE, self.num_features, num_ell)), + ), + ) + self.contractions_weighting.append(graph_opt_weighting) + self.contractions_features.append(graph_opt_features) + # Parameters for the product basis + w = torch.nn.Parameter( + torch.randn((num_elements, num_params, self.num_features)) + / num_params + ) + self.weights.append(w) + + for idx, keep in enumerate(path_weight): + zero_flag = not keep + if idx < correlation - 1: + if zero_flag: + self.weights[idx] = EmptyParam(self.weights[idx]) + self.register_buffer( + f"weights_{idx}_zeroed", + torch.tensor(zero_flag, dtype=torch.bool), + ) + else: + if zero_flag: + self.weights_max = EmptyParam(self.weights_max) + self.register_buffer( + "weights_max_zeroed", + torch.tensor(zero_flag, dtype=torch.bool), + ) + + if not internal_weights: + self.weights = weights[:-1] + self.weights_max = weights[-1] + + def forward(self, x: torch.Tensor, y: torch.Tensor): + + out = self.graph_opt_main( + self.U_tensors(self.correlation), + self.weights_max, + x, + y, + ) + for i, (weight, contract_weights, contract_features) in enumerate( + zip(self.weights, self.contractions_weighting, self.contractions_features) + ): + c_tensor = contract_weights( + self.U_tensors(self.correlation - i - 1), + weight, + y, + ) + c_tensor = c_tensor + out + out = contract_features(c_tensor, x) + + return out.view(out.shape[0], -1) + + def U_tensors(self, nu: int): + return dict(self.named_buffers())[f"U_matrix_{nu}"] + + +class EmptyParam(torch.nn.Parameter): + def __new__(cls, data): # pylint: disable=signature-differs + zero = torch.zeros_like(data) + return super().__new__(cls, zero, requires_grad=False) + + def requires_grad_( + self, mode: bool = True + ): # pylint: disable=arguments-differ, arguments-renamed + del mode + return self diff --git a/models/mace/mace/modules/utils.py b/models/mace/mace/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a74fd4789d3b0bba4052a35edfdbb7e69ddca8 --- /dev/null +++ b/models/mace/mace/modules/utils.py @@ -0,0 +1,641 @@ +########################################################################################### +# Utilities +# Authors: Ilyes Batatia, Gregor Simm and David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import logging +from typing import Dict, List, NamedTuple, Optional, Tuple + +import numpy as np +import torch +import torch.utils.data +from scipy.constants import c, e + +from mace.tools import to_numpy +from mace.tools.scatter import scatter_mean, scatter_std, scatter_sum +from mace.tools.torch_geometric.batch import Batch + +from .blocks import AtomicEnergiesBlock + + +def compute_forces( + energy: torch.Tensor, positions: torch.Tensor, training: bool = True +) -> torch.Tensor: + grad_outputs: List[Optional[torch.Tensor]] = [torch.ones_like(energy)] + gradient = torch.autograd.grad( + outputs=[energy], # [n_graphs, ] + inputs=[positions], # [n_nodes, 3] + grad_outputs=grad_outputs, + retain_graph=training, # Make sure the graph is not destroyed during training + create_graph=training, # Create graph for second derivative + allow_unused=True, # For complete dissociation turn to true + )[ + 0 + ] # [n_nodes, 3] + if gradient is None: + return torch.zeros_like(positions) + return -1 * gradient + + +def compute_forces_virials( + energy: torch.Tensor, + positions: torch.Tensor, + displacement: torch.Tensor, + cell: torch.Tensor, + training: bool = True, + compute_stress: bool = False, +) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: + grad_outputs: List[Optional[torch.Tensor]] = [torch.ones_like(energy)] + forces, virials = torch.autograd.grad( + outputs=[energy], # [n_graphs, ] + inputs=[positions, displacement], # [n_nodes, 3] + grad_outputs=grad_outputs, + retain_graph=training, # Make sure the graph is not destroyed during training + create_graph=training, # Create graph for second derivative + allow_unused=True, + ) + stress = torch.zeros_like(displacement) + if compute_stress and virials is not None: + cell = cell.view(-1, 3, 3) + volume = torch.linalg.det(cell).abs().unsqueeze(-1) + stress = virials / volume.view(-1, 1, 1) + stress = torch.where(torch.abs(stress) < 1e10, stress, torch.zeros_like(stress)) + if forces is None: + forces = torch.zeros_like(positions) + if virials is None: + virials = torch.zeros((1, 3, 3)) + + return -1 * forces, -1 * virials, stress + + +def get_symmetric_displacement( + positions: torch.Tensor, + unit_shifts: torch.Tensor, + cell: Optional[torch.Tensor], + edge_index: torch.Tensor, + num_graphs: int, + batch: torch.Tensor, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if cell is None: + cell = torch.zeros( + num_graphs * 3, + 3, + dtype=positions.dtype, + device=positions.device, + ) + sender = edge_index[0] + displacement = torch.zeros( + (num_graphs, 3, 3), + dtype=positions.dtype, + device=positions.device, + ) + displacement.requires_grad_(True) + symmetric_displacement = 0.5 * ( + displacement + displacement.transpose(-1, -2) + ) # From https://github.com/mir-group/nequip + positions = positions + torch.einsum( + "be,bec->bc", positions, symmetric_displacement[batch] + ) + cell = cell.view(-1, 3, 3) + cell = cell + torch.matmul(cell, symmetric_displacement) + shifts = torch.einsum( + "be,bec->bc", + unit_shifts, + cell[batch[sender]], + ) + return positions, shifts, displacement + + +@torch.jit.unused +def compute_hessians_vmap( + forces: torch.Tensor, + positions: torch.Tensor, +) -> torch.Tensor: + forces_flatten = forces.view(-1) + num_elements = forces_flatten.shape[0] + + def get_vjp(v): + return torch.autograd.grad( + -1 * forces_flatten, + positions, + v, + retain_graph=True, + create_graph=False, + allow_unused=False, + ) + + I_N = torch.eye(num_elements).to(forces.device) + try: + chunk_size = 1 if num_elements < 64 else 16 + gradient = torch.vmap(get_vjp, in_dims=0, out_dims=0, chunk_size=chunk_size)( + I_N + )[0] + except RuntimeError: + gradient = compute_hessians_loop(forces, positions) + if gradient is None: + return torch.zeros((positions.shape[0], forces.shape[0], 3, 3)) + return gradient + + +@torch.jit.unused +def compute_hessians_loop( + forces: torch.Tensor, + positions: torch.Tensor, +) -> torch.Tensor: + hessian = [] + for grad_elem in forces.view(-1): + hess_row = torch.autograd.grad( + outputs=[-1 * grad_elem], + inputs=[positions], + grad_outputs=torch.ones_like(grad_elem), + retain_graph=True, + create_graph=False, + allow_unused=False, + )[0] + hess_row = hess_row.detach() # this makes it very slow? but needs less memory + if hess_row is None: + hessian.append(torch.zeros_like(positions)) + else: + hessian.append(hess_row) + hessian = torch.stack(hessian) + return hessian + + +def get_outputs( + energy: torch.Tensor, + positions: torch.Tensor, + cell: torch.Tensor, + displacement: Optional[torch.Tensor], + vectors: Optional[torch.Tensor] = None, + training: bool = False, + compute_force: bool = True, + compute_virials: bool = True, + compute_stress: bool = True, + compute_hessian: bool = False, + compute_edge_forces: bool = False, +) -> Tuple[ + Optional[torch.Tensor], + Optional[torch.Tensor], + Optional[torch.Tensor], + Optional[torch.Tensor], + Optional[torch.Tensor], +]: + if (compute_virials or compute_stress) and displacement is not None: + forces, virials, stress = compute_forces_virials( + energy=energy, + positions=positions, + displacement=displacement, + cell=cell, + compute_stress=compute_stress, + training=(training or compute_hessian or compute_edge_forces), + ) + elif compute_force: + forces, virials, stress = ( + compute_forces( + energy=energy, + positions=positions, + training=(training or compute_hessian or compute_edge_forces), + ), + None, + None, + ) + else: + forces, virials, stress = (None, None, None) + if compute_hessian: + assert forces is not None, "Forces must be computed to get the hessian" + hessian = compute_hessians_vmap(forces, positions) + else: + hessian = None + if compute_edge_forces and vectors is not None: + edge_forces = compute_forces( + energy=energy, + positions=vectors, + training=(training or compute_hessian), + ) + if edge_forces is not None: + edge_forces = -1 * edge_forces # Match LAMMPS sign convention + else: + edge_forces = None + return forces, virials, stress, hessian, edge_forces + + +def get_atomic_virials_stresses( + edge_forces: torch.Tensor, # [n_edges, 3] + edge_index: torch.Tensor, # [2, n_edges] + vectors: torch.Tensor, # [n_edges, 3] + num_atoms: int, + batch: torch.Tensor, + cell: torch.Tensor, # [n_graphs, 3, 3] +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """ + Compute atomic virials and optionally atomic stresses from edge forces and vectors. + From pobo95 PR #528. + Returns: + Tuple of: + - Atomic virials [num_atoms, 3, 3] + - Atomic stresses [num_atoms, 3, 3] (None if not computed) + """ + edge_virial = torch.einsum("zi,zj->zij", edge_forces, vectors) + atom_virial_sender = scatter_sum( + src=edge_virial, index=edge_index[0], dim=0, dim_size=num_atoms + ) + atom_virial_receiver = scatter_sum( + src=edge_virial, index=edge_index[1], dim=0, dim_size=num_atoms + ) + atom_virial = (atom_virial_sender + atom_virial_receiver) / 2 + atom_virial = (atom_virial + atom_virial.transpose(-1, -2)) / 2 + atom_stress = None + cell = cell.view(-1, 3, 3) + volume = torch.linalg.det(cell).abs().unsqueeze(-1) + atom_volume = volume[batch].view(-1, 1, 1) + atom_stress = atom_virial / atom_volume + atom_stress = torch.where( + torch.abs(atom_stress) < 1e10, atom_stress, torch.zeros_like(atom_stress) + ) + return -1 * atom_virial, atom_stress + + +def get_edge_vectors_and_lengths( + positions: torch.Tensor, # [n_nodes, 3] + edge_index: torch.Tensor, # [2, n_edges] + shifts: torch.Tensor, # [n_edges, 3] + normalize: bool = False, + eps: float = 1e-9, +) -> Tuple[torch.Tensor, torch.Tensor]: + sender = edge_index[0] + receiver = edge_index[1] + vectors = positions[receiver] - positions[sender] + shifts # [n_edges, 3] + lengths = torch.linalg.norm(vectors, dim=-1, keepdim=True) # [n_edges, 1] + if normalize: + vectors_normed = vectors / (lengths + eps) + return vectors_normed, lengths + + return vectors, lengths + + +def _check_non_zero(std): + if np.any(std == 0): + logging.warning( + "Standard deviation of the scaling is zero, Changing to no scaling" + ) + std[std == 0] = 1 + return std + + +def extract_invariant(x: torch.Tensor, num_layers: int, num_features: int, l_max: int): + out = [] + out.append(x[:, :num_features]) + for i in range(1, num_layers): + out.append( + x[ + :, + i + * (l_max + 1) ** 2 + * num_features : (i * (l_max + 1) ** 2 + 1) + * num_features, + ] + ) + return torch.cat(out, dim=-1) + + +def compute_mean_std_atomic_inter_energy( + data_loader: torch.utils.data.DataLoader, + atomic_energies: np.ndarray, +) -> Tuple[float, float]: + atomic_energies_fn = AtomicEnergiesBlock(atomic_energies=atomic_energies) + + avg_atom_inter_es_list = [] + head_list = [] + + for batch in data_loader: + node_e0 = atomic_energies_fn(batch.node_attrs) + graph_e0s = scatter_sum( + src=node_e0, index=batch.batch, dim=0, dim_size=batch.num_graphs + )[torch.arange(batch.num_graphs), batch.head] + graph_sizes = batch.ptr[1:] - batch.ptr[:-1] + avg_atom_inter_es_list.append( + (batch.energy - graph_e0s) / graph_sizes + ) # {[n_graphs], } + head_list.append(batch.head) + + avg_atom_inter_es = torch.cat(avg_atom_inter_es_list) # [total_n_graphs] + head = torch.cat(head_list, dim=0) # [total_n_graphs] + # mean = to_numpy(torch.mean(avg_atom_inter_es)).item() + # std = to_numpy(torch.std(avg_atom_inter_es)).item() + mean = to_numpy(scatter_mean(src=avg_atom_inter_es, index=head, dim=0).squeeze(-1)) + std = to_numpy(scatter_std(src=avg_atom_inter_es, index=head, dim=0).squeeze(-1)) + std = _check_non_zero(std) + + return mean, std + + +def _compute_mean_std_atomic_inter_energy( + batch: Batch, + atomic_energies_fn: AtomicEnergiesBlock, +) -> Tuple[torch.Tensor, torch.Tensor]: + head = batch.head + node_e0 = atomic_energies_fn(batch.node_attrs) + graph_e0s = scatter_sum( + src=node_e0, index=batch.batch, dim=0, dim_size=batch.num_graphs + )[torch.arange(batch.num_graphs), head] + graph_sizes = batch.ptr[1:] - batch.ptr[:-1] + atom_energies = (batch.energy - graph_e0s) / graph_sizes + return atom_energies + + +def compute_mean_rms_energy_forces( + data_loader: torch.utils.data.DataLoader, + atomic_energies: np.ndarray, +) -> Tuple[float, float]: + atomic_energies_fn = AtomicEnergiesBlock(atomic_energies=atomic_energies) + + atom_energy_list = [] + forces_list = [] + head_list = [] + head_batch = [] + + for batch in data_loader: + head = batch.head + node_e0 = atomic_energies_fn(batch.node_attrs) + graph_e0s = scatter_sum( + src=node_e0, index=batch.batch, dim=0, dim_size=batch.num_graphs + )[torch.arange(batch.num_graphs), head] + graph_sizes = batch.ptr[1:] - batch.ptr[:-1] + atom_energy_list.append( + (batch.energy - graph_e0s) / graph_sizes + ) # {[n_graphs], } + forces_list.append(batch.forces) # {[n_graphs*n_atoms,3], } + head_list.append(head) + head_batch.append(head[batch.batch]) + + atom_energies = torch.cat(atom_energy_list, dim=0) # [total_n_graphs] + forces = torch.cat(forces_list, dim=0) # {[total_n_graphs*n_atoms,3], } + head = torch.cat(head_list, dim=0) # [total_n_graphs] + head_batch = torch.cat(head_batch, dim=0) # [total_n_graphs] + + # mean = to_numpy(torch.mean(atom_energies)).item() + # rms = to_numpy(torch.sqrt(torch.mean(torch.square(forces)))).item() + mean = to_numpy(scatter_mean(src=atom_energies, index=head, dim=0).squeeze(-1)) + rms = to_numpy( + torch.sqrt( + scatter_mean(src=torch.square(forces), index=head_batch, dim=0).mean(-1) + ) + ) + rms = _check_non_zero(rms) + + return mean, rms + + +def _compute_mean_rms_energy_forces( + batch: Batch, + atomic_energies_fn: AtomicEnergiesBlock, +) -> Tuple[torch.Tensor, torch.Tensor]: + head = batch.head + node_e0 = atomic_energies_fn(batch.node_attrs) + graph_e0s = scatter_sum( + src=node_e0, index=batch.batch, dim=0, dim_size=batch.num_graphs + )[torch.arange(batch.num_graphs), head] + graph_sizes = batch.ptr[1:] - batch.ptr[:-1] + atom_energies = (batch.energy - graph_e0s) / graph_sizes # {[n_graphs], } + forces = batch.forces # {[n_graphs*n_atoms,3], } + + return atom_energies, forces + + +def compute_avg_num_neighbors(data_loader: torch.utils.data.DataLoader) -> float: + num_neighbors = [] + for batch in data_loader: + _, receivers = batch.edge_index + _, counts = torch.unique(receivers, return_counts=True) + num_neighbors.append(counts) + + avg_num_neighbors = torch.mean( + torch.cat(num_neighbors, dim=0).type(torch.get_default_dtype()) + ) + return to_numpy(avg_num_neighbors).item() + + +def compute_statistics( + data_loader: torch.utils.data.DataLoader, + atomic_energies: np.ndarray, +) -> Tuple[float, float, float, float]: + atomic_energies_fn = AtomicEnergiesBlock(atomic_energies=atomic_energies) + + atom_energy_list = [] + forces_list = [] + num_neighbors = [] + head_list = [] + head_batch = [] + + for batch in data_loader: + head = batch.head + node_e0 = atomic_energies_fn(batch.node_attrs) + graph_e0s = scatter_sum( + src=node_e0, index=batch.batch, dim=0, dim_size=batch.num_graphs + )[torch.arange(batch.num_graphs), head] + graph_sizes = batch.ptr[1:] - batch.ptr[:-1] + atom_energy_list.append( + (batch.energy - graph_e0s) / graph_sizes + ) # {[n_graphs], } + forces_list.append(batch.forces) # {[n_graphs*n_atoms,3], } + head_list.append(head) # {[n_graphs], } + head_batch.append(head[batch.batch]) + _, receivers = batch.edge_index + _, counts = torch.unique(receivers, return_counts=True) + num_neighbors.append(counts) + + atom_energies = torch.cat(atom_energy_list, dim=0) # [total_n_graphs] + forces = torch.cat(forces_list, dim=0) # {[total_n_graphs*n_atoms,3], } + head = torch.cat(head_list, dim=0) # [total_n_graphs] + head_batch = torch.cat(head_batch, dim=0) # [total_n_graphs] + + # mean = to_numpy(torch.mean(atom_energies)).item() + mean = to_numpy(scatter_mean(src=atom_energies, index=head, dim=0).squeeze(-1)) + rms = to_numpy( + torch.sqrt( + scatter_mean(src=torch.square(forces), index=head_batch, dim=0).mean(-1) + ) + ) + + avg_num_neighbors = torch.mean( + torch.cat(num_neighbors, dim=0).type(torch.get_default_dtype()) + ) + + return to_numpy(avg_num_neighbors).item(), mean, rms + + +def compute_rms_dipoles( + data_loader: torch.utils.data.DataLoader, +) -> Tuple[float, float]: + dipoles_list = [] + for batch in data_loader: + dipoles_list.append(batch.dipole) # {[n_graphs,3], } + + dipoles = torch.cat(dipoles_list, dim=0) # {[total_n_graphs,3], } + rms = to_numpy(torch.sqrt(torch.mean(torch.square(dipoles)))).item() + rms = _check_non_zero(rms) + return rms + + +def compute_fixed_charge_dipole( + charges: torch.Tensor, + positions: torch.Tensor, + batch: torch.Tensor, + num_graphs: int, +) -> torch.Tensor: + mu = positions * charges.unsqueeze(-1) / (1e-11 / c / e) # [N_atoms,3] + return scatter_sum( + src=mu, index=batch.unsqueeze(-1), dim=0, dim_size=num_graphs + ) # [N_graphs,3] + + +def compute_fixed_charge_dipole_polar( + charges: torch.Tensor, + positions: torch.Tensor, + batch: torch.Tensor, + num_graphs: int, +) -> torch.Tensor: + mu = positions * charges.unsqueeze( + -1 + ) # / (1e-11 / c / e) # [N_atoms,3] = 0.20819... + return scatter_sum(src=mu, index=batch.unsqueeze(-1), dim=0, dim_size=num_graphs) + + +@torch.jit.ignore +def compute_dielectric_gradients( + dielectric: torch.Tensor, + positions: torch.Tensor, +) -> Tuple[torch.tensor, torch.tensor]: + dielectric_flatten = dielectric.view(-1) + + def get_vjp(v): + return torch.autograd.grad( + dielectric_flatten, + positions, + v, + retain_graph=True, + create_graph=True, + allow_unused=False, + ) + + try: + I_N = torch.eye(dielectric.shape[-1]).to(dielectric.device) + gradient = torch.vmap(get_vjp, in_dims=0, out_dims=0)(I_N)[0] + except RuntimeError: + gradient = compute_dielectric_gradients_loop(dielectric, positions).detach() + if gradient is None: + return torch.zeros((positions.shape[0], dielectric.shape[-1], 3)) + return gradient + + +def compute_dielectric_gradients_loop( + dielectric: torch.Tensor, + positions: torch.Tensor, +) -> torch.Tensor: + gradients = [] + for i in range(dielectric.shape[-1]): + grad_elem = dielectric[:, i] + hess_row = torch.autograd.grad( + grad_elem, + positions, + retain_graph=True, + create_graph=True, + allow_unused=False, + )[0] + gradients.append(hess_row) + gradients = torch.stack(gradients) + return gradients + + +class InteractionKwargs(NamedTuple): + lammps_class: Optional[torch.Tensor] + lammps_natoms: Tuple[int, int] = (0, 0) + + +class GraphContext(NamedTuple): + is_lammps: bool + num_graphs: int + num_atoms_arange: torch.Tensor + displacement: Optional[torch.Tensor] + positions: torch.Tensor + vectors: torch.Tensor + lengths: torch.Tensor + cell: torch.Tensor + node_heads: torch.Tensor + interaction_kwargs: InteractionKwargs + + +def prepare_graph( + data: Dict[str, torch.Tensor], + compute_virials: bool = False, + compute_stress: bool = False, + compute_displacement: bool = False, + lammps_mliap: bool = False, +) -> GraphContext: + if torch.jit.is_scripting(): + lammps_mliap = False + + node_heads = ( + data["head"][data["batch"]] + if "head" in data + else torch.zeros_like(data["batch"]) + ) + + if lammps_mliap: + n_real, n_total = data["natoms"][0], data["natoms"][1] + num_graphs = 2 + num_atoms_arange = torch.arange(n_real, device=data["node_attrs"].device) + displacement = None + positions = torch.zeros( + (int(n_real), 3), + dtype=data["vectors"].dtype, + device=data["vectors"].device, + ) + cell = torch.zeros( + (num_graphs, 3, 3), + dtype=data["vectors"].dtype, + device=data["vectors"].device, + ) + vectors = data["vectors"].requires_grad_(True) + lengths = torch.linalg.vector_norm(vectors, dim=1, keepdim=True) + ikw = InteractionKwargs(data["lammps_class"], (n_real, n_total)) + else: + if not torch.compiler.is_compiling(): + data["positions"].requires_grad_(True) + positions = data["positions"] + cell = data["cell"] + num_atoms_arange = torch.arange(positions.shape[0], device=positions.device) + num_graphs = int(data["ptr"].numel() - 1) + displacement = torch.zeros( + (num_graphs, 3, 3), dtype=positions.dtype, device=positions.device + ) + if compute_virials or compute_stress or compute_displacement: + p, s, displacement = get_symmetric_displacement( + positions=positions, + unit_shifts=data["unit_shifts"], + cell=cell, + edge_index=data["edge_index"], + num_graphs=num_graphs, + batch=data["batch"], + ) + data["positions"], data["shifts"] = p, s + vectors, lengths = get_edge_vectors_and_lengths( + positions=data["positions"], + edge_index=data["edge_index"], + shifts=data["shifts"], + ) + ikw = InteractionKwargs(None, (0, 0)) + + return GraphContext( + is_lammps=lammps_mliap, + num_graphs=num_graphs, + num_atoms_arange=num_atoms_arange, + displacement=displacement, + positions=positions, + vectors=vectors, + lengths=lengths, + cell=cell, + node_heads=node_heads, + interaction_kwargs=ikw, + ) diff --git a/models/mace/mace/modules/wrapper_ops.py b/models/mace/mace/modules/wrapper_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..db23a09c47fb9f6325ae3c91e6b21a48ced93da2 --- /dev/null +++ b/models/mace/mace/modules/wrapper_ops.py @@ -0,0 +1,330 @@ +""" +Wrapper class for o3.Linear that optionally uses cuet.Linear +""" + +import dataclasses +import types +from typing import List, Optional + +import torch +from e3nn import o3 + +from mace.modules.symmetric_contraction import SymmetricContraction +from mace.tools.cg import O3_e3nn +from mace.tools.scatter import scatter_sum + +try: + import cuequivariance as cue + import cuequivariance_torch as cuet + + CUET_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + CUET_AVAILABLE = False + +try: + import openequivariance as oeq + + OEQ_AVAILABLE = True +except ImportError: + OEQ_AVAILABLE = False + + +@dataclasses.dataclass +class CuEquivarianceConfig: + """Configuration for cuequivariance acceleration""" + + enabled: bool = False + layout: str = "mul_ir" # One of: mul_ir, ir_mul + layout_str: str = "mul_ir" + group: str = "O3" + optimize_all: bool = False # Set to True to enable all optimizations + optimize_linear: bool = False + optimize_channelwise: bool = False + optimize_symmetric: bool = False + optimize_fctp: bool = False + conv_fusion: bool = False # Set to True to enable conv fusion + + def __post_init__(self): + if self.enabled and CUET_AVAILABLE: + self.layout_str = self.layout + self.layout = getattr(cue, self.layout) + self.group = ( + O3_e3nn if self.group == "O3_e3nn" else getattr(cue, self.group) + ) + if not CUET_AVAILABLE: + self.enabled = False + + +@dataclasses.dataclass +class OEQConfig: + """Configuration for cuequivariance acceleration""" + + enabled: bool = False + optimize_all: bool = False + optimize_channelwise: bool = False + conv_fusion: Optional[str] = "atomic" + + def __post_init__(self): + if not OEQ_AVAILABLE: + self.enabled = False + + +class Linear: + """Returns either a cuet.Linear or o3.Linear based on config""" + + def __new__( + cls, + irreps_in: o3.Irreps, + irreps_out: o3.Irreps, + shared_weights: bool = True, + internal_weights: bool = True, + cueq_config: Optional[CuEquivarianceConfig] = None, + ): + if ( + CUET_AVAILABLE + and cueq_config is not None + and cueq_config.enabled + and (cueq_config.optimize_all or cueq_config.optimize_linear) + ): + return cuet.Linear( + cue.Irreps(cueq_config.group, irreps_in), + cue.Irreps(cueq_config.group, irreps_out), + layout=cueq_config.layout, + shared_weights=shared_weights, + method="naive", + ) + + return o3.Linear( + irreps_in, + irreps_out, + shared_weights=shared_weights, + internal_weights=internal_weights, + ) + + +def with_scatter_sum(conv_tp: torch.nn.Module) -> torch.nn.Module: + conv_tp.original_forward = conv_tp.forward + + def forward( + self, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + tp_weights: torch.Tensor, + edge_index: torch.Tensor, + ) -> torch.Tensor: + sender = edge_index[0] + receiver = edge_index[1] + num_nodes = node_feats.shape[0] + + mji = self.original_forward(node_feats[sender], edge_attrs, tp_weights) + message = scatter_sum(src=mji, index=receiver, dim=0, dim_size=num_nodes) + return message + + conv_tp.forward = types.MethodType(forward, conv_tp) + return conv_tp + + +def with_cueq_conv_fusion(conv_tp: torch.nn.Module) -> torch.nn.Module: + """Wraps a cuet.ConvTensorProduct to use conv fusion""" + conv_tp.original_forward = conv_tp.forward + num_segment = conv_tp.m.buffer_num_segments[0] + num_operands = conv_tp.m.operand_extent + conv_tp.weight_numel = num_segment * num_operands + + def forward( + self, + node_feats: torch.Tensor, + edge_attrs: torch.Tensor, + tp_weights: torch.Tensor, + edge_index: torch.Tensor, + ) -> torch.Tensor: + sender = edge_index[0] + receiver = edge_index[1] + return self.original_forward( + [tp_weights, node_feats, edge_attrs], + {1: sender}, + {0: node_feats}, + {0: receiver}, + )[0] + + conv_tp.forward = types.MethodType(forward, conv_tp) + return conv_tp + + +class TensorProduct: + """Wrapper around o3.TensorProduct/cuet.ChannelwiseTensorProduct/oeq.TensorProduct followed by a scatter sum""" + + def __new__( + cls, + irreps_in1: o3.Irreps, + irreps_in2: o3.Irreps, + irreps_out: o3.Irreps, + instructions: Optional[List] = None, + shared_weights: bool = False, + internal_weights: bool = False, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, + ): + if ( + CUET_AVAILABLE + and cueq_config is not None + and cueq_config.enabled + and (cueq_config.optimize_all or cueq_config.optimize_channelwise) + ): + if cueq_config.conv_fusion: + return with_cueq_conv_fusion( + cuet.SegmentedPolynomial( + cue.descriptors.channelwise_tensor_product( + cue.Irreps(cueq_config.group, irreps_in1), + cue.Irreps(cueq_config.group, irreps_in2), + cue.Irreps(cueq_config.group, irreps_out), + ) + .flatten_coefficient_modes() + .squeeze_modes() + .polynomial, + math_dtype=torch.get_default_dtype(), + method="uniform_1d", + ) + ) + return cuet.ChannelWiseTensorProduct( + cue.Irreps(cueq_config.group, irreps_in1), + cue.Irreps(cueq_config.group, irreps_in2), + cue.Irreps(cueq_config.group, irreps_out), + layout=cueq_config.layout, + shared_weights=shared_weights, + internal_weights=internal_weights, + dtype=torch.get_default_dtype(), + math_dtype=torch.get_default_dtype(), + ) + if ( + OEQ_AVAILABLE + and oeq_config is not None + and oeq_config.enabled + and (oeq_config.optimize_all or oeq_config.optimize_channelwise) + ): + dtype = oeq.torch_to_oeq_dtype(torch.get_default_dtype()) + tpp = oeq.TPProblem( + irreps_in1, + irreps_in2, + irreps_out, + instructions, + shared_weights=shared_weights, + internal_weights=internal_weights, + irrep_dtype=dtype, + weight_dtype=dtype, + ) + + if oeq_config.conv_fusion is None: + return oeq.TensorProduct(tpp) + if oeq_config.conv_fusion == "atomic": + return oeq.TensorProductConv(tpp, deterministic=False) + + raise ValueError(f"Unknown conv_fusion option: {oeq_config.conv_fusion}") + + return o3.TensorProduct( + irreps_in1, + irreps_in2, + irreps_out, + instructions=instructions, + shared_weights=shared_weights, + internal_weights=internal_weights, + ) + + +class FullyConnectedTensorProduct: + """Wrapper around o3.FullyConnectedTensorProduct/cuet.FullyConnectedTensorProduct""" + + def __new__( + cls, + irreps_in1: o3.Irreps, + irreps_in2: o3.Irreps, + irreps_out: o3.Irreps, + shared_weights: bool = True, + internal_weights: bool = True, + cueq_config: Optional[CuEquivarianceConfig] = None, + ): + if ( + CUET_AVAILABLE + and cueq_config is not None + and cueq_config.enabled + and (cueq_config.optimize_all or cueq_config.optimize_fctp) + ): + return cuet.FullyConnectedTensorProduct( + cue.Irreps(cueq_config.group, irreps_in1), + cue.Irreps(cueq_config.group, irreps_in2), + cue.Irreps(cueq_config.group, irreps_out), + layout=cueq_config.layout, + shared_weights=shared_weights, + internal_weights=internal_weights, + method="naive", + ) + + return o3.FullyConnectedTensorProduct( + irreps_in1, + irreps_in2, + irreps_out, + shared_weights=shared_weights, + internal_weights=internal_weights, + ) + + +class SymmetricContractionWrapper: + """Wrapper around SymmetricContraction/cuet.SymmetricContraction""" + + def __new__( + cls, + irreps_in: o3.Irreps, + irreps_out: o3.Irreps, + correlation: int, + num_elements: Optional[int] = None, + cueq_config: Optional[CuEquivarianceConfig] = None, + oeq_config: Optional[OEQConfig] = None, # pylint: disable=unused-argument + use_reduced_cg: bool = True, + ): + use_reduced_cg = use_reduced_cg and CUET_AVAILABLE + if ( + CUET_AVAILABLE + and cueq_config is not None + and cueq_config.enabled + and (cueq_config.optimize_all or cueq_config.optimize_symmetric) + ): + return cuet.SymmetricContraction( + cue.Irreps(cueq_config.group, irreps_in), + cue.Irreps(cueq_config.group, irreps_out), + layout_in=cue.ir_mul, + layout_out=cueq_config.layout, + contraction_degree=correlation, + num_elements=num_elements, + original_mace=(not use_reduced_cg), + dtype=torch.get_default_dtype(), + math_dtype=torch.get_default_dtype(), + ) + + return SymmetricContraction( + irreps_in=irreps_in, + irreps_out=irreps_out, + correlation=correlation, + num_elements=num_elements, + use_reduced_cg=use_reduced_cg, + ) + + +class TransposeIrrepsLayoutWrapper: + """Wrapper around cuet.TransposeIrrepsLayout""" + + def __new__( + cls, + irreps: o3.Irreps, + source: str, + target: str, + cueq_config: Optional[CuEquivarianceConfig] = None, + ): + if CUET_AVAILABLE and cueq_config is not None and cueq_config.enabled: + return cuet.TransposeIrrepsLayout( + cue.Irreps(cueq_config.group, irreps), + source=getattr(cue, source), + target=getattr(cue, target), + use_fallback=True, + ) + + return None diff --git a/models/mace/mace/py.typed b/models/mace/mace/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/models/mace/mace/py.typed @@ -0,0 +1 @@ + diff --git a/models/mace/mace/tools/__init__.py b/models/mace/mace/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa6b0765befce9fab668c2483f7db946a2bfa9d --- /dev/null +++ b/models/mace/mace/tools/__init__.py @@ -0,0 +1,73 @@ +from .arg_parser import build_default_arg_parser, build_preprocess_arg_parser +from .arg_parser_tools import check_args +from .cg import U_matrix_real +from .checkpoint import CheckpointHandler, CheckpointIO, CheckpointState +from .default_keys import DefaultKeys +from .finetuning_utils import load_foundations, load_foundations_elements +from .torch_tools import ( + TensorDict, + cartesian_to_spherical, + count_parameters, + init_device, + init_wandb, + set_default_dtype, + set_seeds, + spherical_to_cartesian, + to_numpy, + to_one_hot, + voigt_to_matrix, +) +from .train import SWAContainer, evaluate, train +from .utils import ( + AtomicNumberTable, + MetricsLogger, + atomic_numbers_to_indices, + compute_c, + compute_mae, + compute_q95, + compute_rel_mae, + compute_rel_rmse, + compute_rmse, + get_atomic_number_table_from_zs, + get_tag, + setup_logger, +) + +__all__ = [ + "TensorDict", + "AtomicNumberTable", + "atomic_numbers_to_indices", + "to_numpy", + "to_one_hot", + "build_default_arg_parser", + "check_args", + "DefaultKeys", + "set_seeds", + "init_device", + "setup_logger", + "get_tag", + "count_parameters", + "MetricsLogger", + "get_atomic_number_table_from_zs", + "train", + "evaluate", + "SWAContainer", + "CheckpointHandler", + "CheckpointIO", + "CheckpointState", + "set_default_dtype", + "compute_mae", + "compute_rel_mae", + "compute_rmse", + "compute_rel_rmse", + "compute_q95", + "compute_c", + "U_matrix_real", + "spherical_to_cartesian", + "cartesian_to_spherical", + "voigt_to_matrix", + "init_wandb", + "load_foundations", + "load_foundations_elements", + "build_preprocess_arg_parser", +] diff --git a/models/mace/mace/tools/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1b25ffc757687b7db77d9e4a5e3833f92ff7fec Binary files /dev/null and b/models/mace/mace/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/arg_parser.cpython-310.pyc b/models/mace/mace/tools/__pycache__/arg_parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f401d77d4fd8eda62472e6c37d9f5fc287192ab Binary files /dev/null and b/models/mace/mace/tools/__pycache__/arg_parser.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/arg_parser_tools.cpython-310.pyc b/models/mace/mace/tools/__pycache__/arg_parser_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29e8d8fec8c5ad9d5d845c236abff7741173d4eb Binary files /dev/null and b/models/mace/mace/tools/__pycache__/arg_parser_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/cg.cpython-310.pyc b/models/mace/mace/tools/__pycache__/cg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adbb5706e9d4494d6845317c9a1168b24f1ded0f Binary files /dev/null and b/models/mace/mace/tools/__pycache__/cg.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/cg_cueq_tools.cpython-310.pyc b/models/mace/mace/tools/__pycache__/cg_cueq_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c8b60ccb15c67801e10823ac5efdd16a9c910ff Binary files /dev/null and b/models/mace/mace/tools/__pycache__/cg_cueq_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/checkpoint.cpython-310.pyc b/models/mace/mace/tools/__pycache__/checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd5f8e3677388c74c98f5a3711ae3f2137ba45cf Binary files /dev/null and b/models/mace/mace/tools/__pycache__/checkpoint.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/compile.cpython-310.pyc b/models/mace/mace/tools/__pycache__/compile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85312136f3a1ddbb928887c68252673c509ad7ba Binary files /dev/null and b/models/mace/mace/tools/__pycache__/compile.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/default_keys.cpython-310.pyc b/models/mace/mace/tools/__pycache__/default_keys.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be3d69f17d4e38c5ebcbef39b23dd90f1d795c35 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/default_keys.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/distributed_tools.cpython-310.pyc b/models/mace/mace/tools/__pycache__/distributed_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5277f1bfc1d47d1742d389bc858687ae9a604f05 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/distributed_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/finetuning_utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/finetuning_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e87c043b2893665478c50f7f3831eb32fd50ce Binary files /dev/null and b/models/mace/mace/tools/__pycache__/finetuning_utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/model_script_utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/model_script_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22d28a3a87b784c91322e87ae725a0690fb73bfd Binary files /dev/null and b/models/mace/mace/tools/__pycache__/model_script_utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/multihead_tools.cpython-310.pyc b/models/mace/mace/tools/__pycache__/multihead_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ef9d6ee9679fa9d6958c102bafd7ee935b6dcf3 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/multihead_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/run_train_utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/run_train_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f6602a25ec8d9e64d53db82d5d664849ac4d092 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/run_train_utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/scatter.cpython-310.pyc b/models/mace/mace/tools/__pycache__/scatter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2e7e6ee666c9bff93658493362f8aeb55bd09d0 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/scatter.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/scripts_utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/scripts_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6bc012181ac116bf3dbd993708dfe33b1f7b8f Binary files /dev/null and b/models/mace/mace/tools/__pycache__/scripts_utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/slurm_distributed.cpython-310.pyc b/models/mace/mace/tools/__pycache__/slurm_distributed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9700d7462ccbab56c64b5ebcec0dadda3ccd463 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/slurm_distributed.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/tables_utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/tables_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9eed0838a2662603c82a071c3ebc7e5b3c7a245 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/tables_utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/torch_tools.cpython-310.pyc b/models/mace/mace/tools/__pycache__/torch_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c47c23e6ff90c139f5270faf51399931e5a63baa Binary files /dev/null and b/models/mace/mace/tools/__pycache__/torch_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/train.cpython-310.pyc b/models/mace/mace/tools/__pycache__/train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1c7d5eb1d1f23aad20eb2b9fb1b62ec2701ab46 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/train.cpython-310.pyc differ diff --git a/models/mace/mace/tools/__pycache__/utils.cpython-310.pyc b/models/mace/mace/tools/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7945a28ce5ef3246debb8ed2192e562e10754181 Binary files /dev/null and b/models/mace/mace/tools/__pycache__/utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/arg_parser.py b/models/mace/mace/tools/arg_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..6b181aa9e570d2547087bdacde674873d39167b8 --- /dev/null +++ b/models/mace/mace/tools/arg_parser.py @@ -0,0 +1,1173 @@ +########################################################################################### +# Parsing functionalities +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import argparse +import os +from typing import Dict, Optional + +from .default_keys import DefaultKeys + + +# NOTE This is this the arg parser used for running train +def build_default_arg_parser() -> argparse.ArgumentParser: + try: + import configargparse + + parser = configargparse.ArgumentParser( + config_file_parser_class=configargparse.YAMLConfigFileParser, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add( + "--config", + type=str, + is_config_file=True, + help="config file to aggregate options", + ) + except ImportError: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + # Name and seed + parser.add_argument("--name", help="experiment name", required=True) + parser.add_argument("--seed", help="random seed", type=int, default=123) + + # Directories + parser.add_argument( + "--work_dir", + help="set directory for all files and folders", + type=str, + default=".", + ) + parser.add_argument( + "--log_dir", help="directory for log files", type=str, default=None + ) + parser.add_argument( + "--model_dir", help="directory for final model", type=str, default=None + ) + parser.add_argument( + "--checkpoints_dir", + help="directory for checkpoint files", + type=str, + default=None, + ) + parser.add_argument( + "--results_dir", help="directory for results", type=str, default=None + ) + parser.add_argument( + "--downloads_dir", help="directory for downloads", type=str, default=None + ) + + # Device and logging + parser.add_argument( + "--device", + help="select device", + type=str, + choices=["cpu", "cuda", "mps", "xpu"], + default="cpu", + ) + parser.add_argument( + "--default_dtype", + help="set default dtype", + type=str, + choices=["float32", "float64"], + default="float64", + ) + parser.add_argument( + "--distributed", + help="train in multi-GPU data parallel mode", + action="store_true", + default=False, + ) + parser.add_argument( + "--launcher", + default="torchrun", + choices=["slurm", "torchrun", "mpi", "none"], + help="How the job was launched", + ) + parser.add_argument("--log_level", help="log level", type=str, default="INFO") + + parser.add_argument( + "--plot", + help="Plot results of training", + type=str2bool, + default=True, + ) + + parser.add_argument( + "--plot_frequency", + help="Set plotting frequency: '0' for only at the end or an integer N to plot every N epochs.", + type=int, + default="0", + ) + + parser.add_argument( + "--plot_interaction_e", + help="Whether to plot energy without E0s", + type=str2bool, + default=False, + ) + + parser.add_argument( + "--error_table", + help="Type of error table produced at the end of the training", + type=str, + choices=[ + "PerAtomRMSE", + "TotalRMSE", + "PerAtomRMSEstressvirials", + "PerAtomMAEstressvirials", + "PerAtomMAE", + "TotalMAE", + "DipoleRMSE", + "DipoleMAE", + "DipolePolarRMSE", + "EnergyDipoleRMSE", + ], + default="PerAtomRMSE", + ) + + # Model + parser.add_argument( + "--model", + help="model type", + default="MACE", + choices=[ + "BOTNet", + "MACE", + "ScaleShiftMACE", + "MACELES", + "ScaleShiftBOTNet", + "AtomicDipolesMACE", + "AtomicDielectricMACE", + "EnergyDipolesMACE", + ], + ) + parser.add_argument( + "--r_max", help="distance cutoff (in Ang)", type=float, default=5.0 + ) + parser.add_argument( + "--radial_type", + help="type of radial basis functions", + type=str, + default="bessel", + choices=["bessel", "gaussian", "chebyshev"], + ) + parser.add_argument( + "--num_radial_basis", + help="number of radial basis functions", + type=int, + default=8, + ) + parser.add_argument( + "--num_cutoff_basis", + help="number of basis functions for smooth cutoff", + type=int, + default=5, + ) + parser.add_argument( + "--pair_repulsion", + help="use pair repulsion term with ZBL potential", + action="store_true", + default=False, + ) + parser.add_argument( + "--distance_transform", + help="use distance transform for radial basis functions", + default="None", + choices=["None", "Agnesi", "Soft"], + ) + parser.add_argument( + "--apply_cutoff", + help="apply cutoff to the radial basis functions before MLP", + type=str2bool, + default=True, + ) + parser.add_argument( + "--use_last_readout_only", + help="use only the last readout for the final output", + type=str2bool, + default=False, + ) + parser.add_argument( + "--use_embedding_readout", + help="use embedding readout for the final output", + type=str2bool, + default=False, + ) + parser.add_argument( + "--interaction", + help="name of interaction block", + type=str, + default="RealAgnosticResidualInteractionBlock", + choices=[ + "RealAgnosticResidualInteractionBlock", + "RealAgnosticAttResidualInteractionBlock", + "RealAgnosticInteractionBlock", + "RealAgnosticDensityInteractionBlock", + "RealAgnosticDensityResidualInteractionBlock", + "RealAgnosticResidualNonLinearInteractionBlock", + ], + ) + parser.add_argument( + "--interaction_first", + help="name of interaction block", + type=str, + default="RealAgnosticResidualInteractionBlock", + choices=[ + "RealAgnosticResidualInteractionBlock", + "RealAgnosticInteractionBlock", + "RealAgnosticDensityInteractionBlock", + "RealAgnosticDensityResidualInteractionBlock", + "RealAgnosticResidualNonLinearInteractionBlock", + ], + ) + parser.add_argument( + "--max_ell", help=r"highest \ell of spherical harmonics", type=int, default=3 + ) + parser.add_argument( + "--correlation", help="correlation order at each layer", type=int, default=3 + ) + parser.add_argument( + "--use_reduced_cg", + help="use reduced generalized Clebsch-Gordan coefficients", + type=str2bool, + default=False, + ) + parser.add_argument( + "--use_so3", + help="use SO(3) irreps instead of O(3) irreps", + type=str2bool, + default=False, + ) + parser.add_argument( + "--use_agnostic_product", + help="use element agnostic product", + type=str2bool, + default=False, + ) + parser.add_argument( + "--num_interactions", help="number of interactions", type=int, default=2 + ) + parser.add_argument( + "--MLP_irreps", + help="hidden irreps of the MLP in last readout", + type=str, + default="16x0e", + ) + parser.add_argument( + "--radial_MLP", + help="width of the radial MLP", + type=str, + default="[64, 64, 64]", + ) + parser.add_argument( + "--hidden_irreps", + help="irreps for hidden node states", + type=str, + default=None, + ) + parser.add_argument( + "--edge_irreps", + help="irreps for edge states", + type=str, + default=None, + ) + # add option to specify irreps by channel number and max L + parser.add_argument( + "--num_channels", + help="number of embedding channels", + type=int, + default=None, + ) + parser.add_argument( + "--max_L", + help="max L equivariance of the message", + type=int, + default=None, + ) + parser.add_argument( + "--gate", + help="non linearity for last readout", + type=str, + default="silu", + choices=["silu", "tanh", "abs", "None"], + ) + parser.add_argument( + "--scaling", + help="type of scaling to the output", + type=str, + default="rms_forces_scaling", + choices=["std_scaling", "rms_forces_scaling", "no_scaling"], + ) + parser.add_argument( + "--avg_num_neighbors", + help="normalization factor for the message", + type=float, + default=1, + ) + parser.add_argument( + "--compute_avg_num_neighbors", + help="normalization factor for the message", + type=str2bool, + default=True, + ) + parser.add_argument( + "--compute_stress", + help="Select True to compute stress", + type=str2bool, + default=False, + ) + parser.add_argument( + "--compute_forces", + help="Select True to compute forces", + type=str2bool, + default=True, + ) + parser.add_argument( + "--compute_polarizability", + help="Select True to compute polarizability", + type=str2bool, + default=False, + ) + parser.add_argument( + "--compute_atomic_dipole", + help="Select True to compute dipoles", + type=str2bool, + default=False, + ) + + # Dataset + parser.add_argument( + "--train_file", + help="Training set file, format is .xyz or .h5", + type=str, + required=False, + ) + parser.add_argument( + "--valid_file", + help="Validation set .xyz or .h5 file", + default=None, + type=str, + required=False, + ) + parser.add_argument( + "--valid_fraction", + help="Fraction of training set used for validation", + type=float, + default=0.1, + required=False, + ) + parser.add_argument( + "--test_file", + help="Test set .xyz pt .h5 file", + type=str, + ) + parser.add_argument( + "--test_dir", + help="Path to directory with test files named as test_*.h5", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--multi_processed_test", + help="Boolean value for whether the test data was multiprocessed", + type=str2bool, + default=False, + required=False, + ) + parser.add_argument( + "--num_workers", + help="Number of workers for data loading", + type=int, + default=0, + ) + parser.add_argument( + "--pin_memory", + help="Pin memory for data loading", + default=True, + type=str2bool, + ) + parser.add_argument( + "--atomic_numbers", + help="List of atomic numbers", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--mean", + help="Mean energy per atom of training set", + type=float, + default=None, + required=False, + ) + parser.add_argument( + "--std", + help="Standard deviation of force components in the training set", + type=float, + default=None, + required=False, + ) + parser.add_argument( + "--statistics_file", + help="json file containing statistics of training set", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--les_arguments", + help="Path to the LES arguments file", + type=read_yaml, + default=None, + required=False, + ) + parser.add_argument( + "--E0s", + help="Dictionary of isolated atom energies", + type=str, + default=None, + required=False, + ) + + # Fine-tuning + parser.add_argument( + "--pseudolabel_replay", + help="Use pseudolabels from foundation model for replay data in multihead finetuning", + type=str2bool, + default=False, + ) + parser.add_argument( + "--foundation_filter_elements", + help="Filter element during fine-tuning", + type=str2bool, + default=True, + required=False, + ) + parser.add_argument( + "--heads", + help="Dict of heads: containing individual files and E0s", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--multiheads_finetuning", + help="Boolean value for whether the model is multiheaded", + type=str2bool, + default=True, + ) + parser.add_argument( + "--foundation_head", + help="Name of the head to use for fine-tuning", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--weight_pt_head", + help="Weight of the pretrained head in the loss function", + type=float, + default=1.0, + ) + parser.add_argument( + "--real_pt_data_ratio_threshold", + help="threshold of real data to replay data below which real data (sum over all real heads) is duplicated", + type=float, + default=0.1, + ) + parser.add_argument( + "--num_samples_pt", + help="Number of samples in the pretrained head", + type=int, + default=10000, + ) + parser.add_argument( + "--force_mh_ft_lr", + help="Force the multiheaded fine-tuning to use arg_parser lr", + type=str2bool, + default=False, + ) + parser.add_argument( + "--subselect_pt", + help="Method to subselect the configurations of the pretraining set", + choices=["fps", "random"], + default="random", + ) + parser.add_argument( + "--filter_type_pt", + help="Filtering method for collecting the pretraining set", + choices=["none", "combinations", "inclusive", "exclusive"], + default="none", + ) + parser.add_argument( + "--disallow_random_padding_pt", + help="do not allow random padding of the configurations to match the number of samples", + action="store_false", + dest="allow_random_padding_pt", + ) + parser.add_argument( + "--pt_train_file", + help="Training set file for the pretrained head", + type=str, + default=None, + ) + parser.add_argument( + "--pt_valid_file", + help="Validation set file for the pretrained head", + type=str, + default=None, + ) + parser.add_argument( + "--foundation_model_elements", + help="Keep all elements of the foundation model during fine-tuning", + type=str2bool, + default=False, + ) + parser.add_argument( + "--keep_isolated_atoms", + help="Keep isolated atoms in the dataset, useful for transfer learning", + type=str2bool, + default=False, + ) + + # Keys + parser.add_argument( + "--energy_key", + help="Key of reference energies in training xyz", + type=str, + default=DefaultKeys.ENERGY.value, + ) + parser.add_argument( + "--forces_key", + help="Key of reference forces in training xyz", + type=str, + default=DefaultKeys.FORCES.value, + ) + parser.add_argument( + "--virials_key", + help="Key of reference virials in training xyz", + type=str, + default=DefaultKeys.VIRIALS.value, + ) + parser.add_argument( + "--stress_key", + help="Key of reference stress in training xyz", + type=str, + default=DefaultKeys.STRESS.value, + ) + parser.add_argument( + "--dipole_key", + help="Key of reference dipoles in training xyz", + type=str, + default=DefaultKeys.DIPOLE.value, + ) + parser.add_argument( + "--polarizability_key", + help="Key of polarizability in training xyz", + type=str, + default=DefaultKeys.POLARIZABILITY.value, + ) + parser.add_argument( + "--head_key", + help="Key of head in training xyz", + type=str, + default=DefaultKeys.HEAD.value, + ) + parser.add_argument( + "--charges_key", + help="Key of atomic charges in training xyz", + type=str, + default=DefaultKeys.CHARGES.value, + ) + parser.add_argument( + "--elec_temp_key", + help="Key of electronic temperature in training xyz", + type=str, + default=DefaultKeys.ELEC_TEMP.value, + ) + parser.add_argument( + "--total_spin_key", + help="Key of total spin in training xyz", + type=str, + default=DefaultKeys.TOTAL_SPIN.value, + ) + parser.add_argument( + "--total_charge_key", + help="Key of total charge in training xyz", + type=str, + default=DefaultKeys.TOTAL_CHARGE.value, + ) + parser.add_argument( + "--embedding_specs", + help=( + "Dict of feature‐spec dictionaries. " + "embedding_specs:\n" + " total_spin:\n" + " type: categorical\n" + " per: graph\n" + " num_classes: 101\n" + " emb_dim: 64\n" + " total_charge:\n" + " type: categorical\n" + " per: graph\n" + " num_classes: 201\n" + " emb_dim: 64\n" + " temperature:\n" + " type: continuous\n" + " per: graph\n" + " in_dim: 1\n" + " emb_dim: 32\n" + ), + default=None, + ) + parser.add_argument( + "--skip_evaluate_heads", + help="Comma-separated list of heads to skip during final evaluation", + type=str, + default="pt_head", + ) + + # Loss and optimization + parser.add_argument( + "--loss", + help="type of loss", + default="weighted", + choices=[ + "ef", + "weighted", + "forces_only", + "virials", + "stress", + "dipole", + "dipole_polar", + "huber", + "universal", + "energy_forces_dipole", + "l1l2energyforces", + "ours_mae", + ], + ) + parser.add_argument( + "--forces_weight", help="weight of forces loss", type=float, default=100.0 + ) + parser.add_argument( + "--swa_forces_weight", + "--stage_two_forces_weight", + help="weight of forces loss after starting Stage Two (previously called swa)", + type=float, + default=100.0, + dest="swa_forces_weight", + ) + parser.add_argument( + "--energy_weight", help="weight of energy loss", type=float, default=1.0 + ) + parser.add_argument( + "--swa_energy_weight", + "--stage_two_energy_weight", + help="weight of energy loss after starting Stage Two (previously called swa)", + type=float, + default=1000.0, + dest="swa_energy_weight", + ) + parser.add_argument( + "--virials_weight", help="weight of virials loss", type=float, default=1.0 + ) + parser.add_argument( + "--swa_virials_weight", + "--stage_two_virials_weight", + help="weight of virials loss after starting Stage Two (previously called swa)", + type=float, + default=10.0, + dest="swa_virials_weight", + ) + parser.add_argument( + "--stress_weight", help="weight of stress loss", type=float, default=1.0 + ) + parser.add_argument( + "--swa_stress_weight", + "--stage_two_stress_weight", + help="weight of stress loss after starting Stage Two (previously called swa)", + type=float, + default=10.0, + dest="swa_stress_weight", + ) + parser.add_argument( + "--dipole_weight", help="weight of dipoles loss", type=float, default=1.0 + ) + parser.add_argument( + "--swa_dipole_weight", + "--stage_two_dipole_weight", + help="weight of dipoles after starting Stage Two (previously called swa)", + type=float, + default=1.0, + dest="swa_dipole_weight", + ) + parser.add_argument( + "--swa_polarizability_weight", + "--stage_two_polarizability_weight", + help="weight of polarizability after starting Stage Two (previously called swa)", + type=float, + default=1.0, + dest="swa_polarizability_weight", + ) + parser.add_argument( + "--polarizability_weight", + help="weight of polarizability loss", + type=float, + default=1.0, + ) + parser.add_argument( + "--config_type_weights", + help="String of dictionary containing the weights for each config type", + type=str, + default='{"Default":1.0}', + ) + parser.add_argument( + "--huber_delta", + help="delta parameter for huber loss", + type=float, + default=0.01, + ) + parser.add_argument( + "--optimizer", + help="Optimizer for parameter optimization", + type=str, + default="adam", + choices=["adam", "adamw", "schedulefree"], + ) + parser.add_argument( + "--beta", + help="Beta parameter for the optimizer", + type=float, + default=0.9, + ) + parser.add_argument("--batch_size", help="batch size", type=int, default=10) + parser.add_argument( + "--valid_batch_size", help="Validation batch size", type=int, default=10 + ) + parser.add_argument( + "--lr", help="Learning rate of optimizer", type=float, default=0.01 + ) + parser.add_argument( + "--swa_lr", + "--stage_two_lr", + help="Learning rate of optimizer in Stage Two (previously called swa)", + type=float, + default=1e-3, + dest="swa_lr", + ) + parser.add_argument( + "--weight_decay", help="weight decay (L2 penalty)", type=float, default=5e-7 + ) + parser.add_argument( + "--amsgrad", + help="use amsgrad variant of optimizer", + action="store_true", + default=True, + ) + parser.add_argument( + "--scheduler", help="Type of scheduler", type=str, default="ReduceLROnPlateau" + ) + parser.add_argument( + "--lr_factor", help="Learning rate factor", type=float, default=0.8 + ) + parser.add_argument( + "--scheduler_patience", help="Learning rate factor", type=int, default=50 + ) + parser.add_argument( + "--lr_scheduler_gamma", + help="Gamma of learning rate scheduler", + type=float, + default=0.9993, + ) + parser.add_argument( + "--swa", + "--stage_two", + help="use Stage Two loss weight, which decreases the learning rate and increases the energy weight at the end of the training to help converge them", + action="store_true", + default=False, + dest="swa", + ) + parser.add_argument( + "--start_swa", + "--start_stage_two", + help="Number of epochs before changing to Stage Two loss weights", + type=int, + default=None, + dest="start_swa", + ) + parser.add_argument( + "--lbfgs", + help="Switch to L-BFGS optimizer", + action="store_true", + default=False, + ) + parser.add_argument( + "--ema", + help="use Exponential Moving Average", + action="store_true", + default=False, + ) + parser.add_argument( + "--ema_decay", + help="Exponential Moving Average decay", + type=float, + default=0.99, + ) + parser.add_argument( + "--max_num_epochs", help="Maximum number of epochs", type=int, default=2048 + ) + parser.add_argument( + "--patience", + help="Maximum number of consecutive epochs of increasing loss", + type=int, + default=2048, + ) + parser.add_argument( + "--foundation_model", + help="Path to the foundation model for transfer learning", + type=str, + default=None, + ) + parser.add_argument( + "--foundation_model_kwargs", + help="Additional kwargs for the foundation model for transfer learning", + type=str, + default="{}", + ) + parser.add_argument( + "--foundation_model_readout", + help="Use readout of foundation model for transfer learning", + action="store_false", + default=True, + ) + parser.add_argument( + "--eval_interval", help="evaluate model every epochs", type=int, default=1 + ) + parser.add_argument( + "--keep_checkpoints", + help="keep all checkpoints", + action="store_true", + default=False, + ) + parser.add_argument( + "--save_all_checkpoints", + help="save all checkpoints", + action="store_true", + default=False, + ) + parser.add_argument( + "--restart_latest", + help="restart optimizer from latest checkpoint", + action="store_true", + default=False, + ) + parser.add_argument( + "--save_cpu", + help="Save a model to be loaded on cpu", + action="store_true", + default=False, + ) + parser.add_argument( + "--clip_grad", + help="Gradient Clipping Value", + type=check_float_or_none, + default=10.0, + ) + parser.add_argument( + "--dry_run", + help="Run all steps upto training to test settings.", + action="store_true", + default=False, + ) + # option for cuequivariance acceleration + parser.add_argument( + "--enable_cueq", + help="Enable cuequivariance acceleration", + type=str2bool, + default=False, + ) + parser.add_argument( + "--only_cueq", + help="Only use cuequivariance acceleration", + type=str2bool, + default=False, + ) + # option for openequivariance acceleration + parser.add_argument( + "--enable_oeq", + help="Enable openequivariance acceleration", + type=str2bool, + default=False, + ) + # options for using Weights and Biases for experiment tracking + # to install see https://wandb.ai + parser.add_argument( + "--wandb", + help="Use Weights and Biases for experiment tracking", + action="store_true", + default=False, + ) + parser.add_argument( + "--wandb_dir", + help="An absolute path to a directory where Weights and Biases metadata will be stored", + type=str, + default=None, + ) + parser.add_argument( + "--wandb_project", + help="Weights and Biases project name", + type=str, + default="", + ) + parser.add_argument( + "--wandb_entity", + help="Weights and Biases entity name", + type=str, + default="", + ) + parser.add_argument( + "--wandb_name", + help="Weights and Biases experiment name", + type=str, + default="", + ) + parser.add_argument( + "--wandb_log_hypers", + help="The hyperparameters to log in Weights and Biases", + nargs="+", + default=[ + "num_channels", + "max_L", + "correlation", + "lr", + "swa_lr", + "weight_decay", + "batch_size", + "max_num_epochs", + "start_swa", + "energy_weight", + "forces_weight", + ], + ) + return parser + + +def build_preprocess_arg_parser() -> argparse.ArgumentParser: + try: + import configargparse + + parser = configargparse.ArgumentParser( + config_file_parser_class=configargparse.YAMLConfigFileParser, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add( + "--config", + type=str, + is_config_file=True, + help="config file to aggregate options", + ) + except ImportError: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--train_file", + help="Training set h5 file", + type=str, + default=None, + required=True, + ) + parser.add_argument( + "--valid_file", + help="Training set xyz file", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--num_process", + help="The user defined number of processes to use, as well as the number of files created.", + type=int, + default=int(os.cpu_count() / 4), + ) + parser.add_argument( + "--valid_fraction", + help="Fraction of training set used for validation", + type=float, + default=0.1, + required=False, + ) + parser.add_argument( + "--test_file", + help="Test set xyz file", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--work_dir", + help="set directory for all files and folders", + type=str, + default=".", + ) + parser.add_argument( + "--h5_prefix", + help="Prefix for h5 files when saving", + type=str, + default="", + ) + parser.add_argument( + "--r_max", help="distance cutoff (in Ang)", type=float, default=5.0 + ) + parser.add_argument( + "--config_type_weights", + help="String of dictionary containing the weights for each config type", + type=str, + default='{"Default":1.0}', + ) + parser.add_argument( + "--energy_key", + help="Key of reference energies in training xyz", + type=str, + default=DefaultKeys.ENERGY.value, + ) + parser.add_argument( + "--forces_key", + help="Key of reference forces in training xyz", + type=str, + default=DefaultKeys.FORCES.value, + ) + parser.add_argument( + "--virials_key", + help="Key of reference virials in training xyz", + type=str, + default=DefaultKeys.VIRIALS.value, + ) + parser.add_argument( + "--stress_key", + help="Key of reference stress in training xyz", + type=str, + default=DefaultKeys.STRESS.value, + ) + parser.add_argument( + "--dipole_key", + help="Key of reference dipoles in training xyz", + type=str, + default=DefaultKeys.DIPOLE.value, + ) + parser.add_argument( + "--polarizability_key", + help="Key of polarizability in training xyz", + type=str, + default=DefaultKeys.POLARIZABILITY.value, + ) + parser.add_argument( + "--charges_key", + help="Key of atomic charges in training xyz", + type=str, + default=DefaultKeys.CHARGES.value, + ) + parser.add_argument( + "--atomic_numbers", + help="List of atomic numbers", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--compute_statistics", + help="Compute statistics for the dataset", + action="store_true", + default=False, + ) + parser.add_argument( + "--batch_size", + help="batch size to compute average number of neighbours", + type=int, + default=16, + ) + + parser.add_argument( + "--scaling", + help="type of scaling to the output", + type=str, + default="rms_forces_scaling", + choices=["std_scaling", "rms_forces_scaling", "no_scaling"], + ) + parser.add_argument( + "--E0s", + help="Dictionary of isolated atom energies", + type=str, + default=None, + required=False, + ) + parser.add_argument( + "--shuffle", + help="Shuffle the training dataset", + type=str2bool, + default=True, + ) + parser.add_argument( + "--seed", + help="Random seed for splitting training and validation sets", + type=int, + default=123, + ) + parser.add_argument( + "--head_key", + help="Key of head in training xyz", + type=str, + default=DefaultKeys.HEAD.value, + ) + parser.add_argument( + "--heads", + help="Dict of heads: containing individual files and E0s", + type=str, + default=None, + required=False, + ) + return parser + + +def check_float_or_none(value: str) -> Optional[float]: + try: + return float(value) + except ValueError: + if value != "None": + raise argparse.ArgumentTypeError( + f"{value} is an invalid value (float or None)" + ) from None + return None + + +def str2bool(value): + if isinstance(value, bool): + return value + if value.lower() in ("yes", "true", "t", "y", "1"): + return True + if value.lower() in ("no", "false", "f", "n", "0"): + return False + raise argparse.ArgumentTypeError("Boolean value expected.") + + +def read_yaml(value: str) -> Dict: + from pathlib import Path + + import yaml + + if not Path(value).is_file(): + raise argparse.ArgumentTypeError(f"File {value} does not exist.") + with open(value, "r", encoding="utf-8") as file: + try: + return yaml.safe_load(file) + except yaml.YAMLError as exc: + raise argparse.ArgumentTypeError( + f"Error parsing YAML file {value}: {exc}" + ) from exc diff --git a/models/mace/mace/tools/arg_parser_tools.py b/models/mace/mace/tools/arg_parser_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d48b4fd1123ed89b4306d6fccdf2a63ba19edc --- /dev/null +++ b/models/mace/mace/tools/arg_parser_tools.py @@ -0,0 +1,126 @@ +import ast +import logging +import os + +from e3nn import o3 + + +def check_args(args): + """ + Check input arguments, update them if necessary for valid and consistent inputs, and return a tuple containing + the (potentially) modified args and a list of log messages. + """ + log_messages = [] + + # Directories + # Use work_dir for all other directories as well, unless they were specified by the user + if args.log_dir is None: + args.log_dir = os.path.join(args.work_dir, "logs") + if args.model_dir is None: + args.model_dir = args.work_dir + if args.checkpoints_dir is None: + args.checkpoints_dir = os.path.join(args.work_dir, "checkpoints") + if args.results_dir is None: + args.results_dir = os.path.join(args.work_dir, "results") + if args.downloads_dir is None: + args.downloads_dir = os.path.join(args.work_dir, "downloads") + + # Model + # Check if hidden_irreps, num_channels and max_L are consistent + if args.hidden_irreps is None and args.num_channels is None and args.max_L is None: + args.hidden_irreps, args.num_channels, args.max_L = "128x0e + 128x1o", 128, 1 + elif ( + args.hidden_irreps is not None + and args.num_channels is not None + and args.max_L is not None + ): + args.hidden_irreps = o3.Irreps( + (args.num_channels * o3.Irreps.spherical_harmonics(args.max_L)) + .sort() + .irreps.simplify() + ) + log_messages.append( + ( + "All of hidden_irreps, num_channels and max_L are specified", + logging.WARNING, + ) + ) + log_messages.append( + ( + f"Using num_channels and max_L to create hidden_irreps: {args.hidden_irreps}.", + logging.WARNING, + ) + ) + assert ( + len({irrep.mul for irrep in o3.Irreps(args.hidden_irreps)}) == 1 + ), "All channels must have the same dimension, use the num_channels and max_L keywords to specify the number of channels and the maximum L" + elif args.num_channels is not None and args.max_L is not None: + assert args.num_channels > 0, "num_channels must be positive integer" + assert args.max_L >= 0, "max_L must be non-negative integer" + args.hidden_irreps = o3.Irreps( + (args.num_channels * o3.Irreps.spherical_harmonics(args.max_L)) + .sort() + .irreps.simplify() + ) + assert ( + len({irrep.mul for irrep in o3.Irreps(args.hidden_irreps)}) == 1 + ), "All channels must have the same dimension, use the num_channels and max_L keywords to specify the number of channels and the maximum L" + elif args.hidden_irreps is not None: + assert ( + len({irrep.mul for irrep in o3.Irreps(args.hidden_irreps)}) == 1 + ), "All channels must have the same dimension, use the num_channels and max_L keywords to specify the number of channels and the maximum L" + + args.num_channels = list( + {irrep.mul for irrep in o3.Irreps(args.hidden_irreps)} + )[0] + args.max_L = o3.Irreps(args.hidden_irreps).lmax + elif args.max_L is not None and args.num_channels is None: + assert args.max_L >= 0, "max_L must be non-negative integer" + args.num_channels = 128 + args.hidden_irreps = o3.Irreps( + (args.num_channels * o3.Irreps.spherical_harmonics(args.max_L)) + .sort() + .irreps.simplify() + ) + elif args.max_L is None and args.num_channels is not None: + assert args.num_channels > 0, "num_channels must be positive integer" + args.max_L = 1 + args.hidden_irreps = o3.Irreps( + (args.num_channels * o3.Irreps.spherical_harmonics(args.max_L)) + .sort() + .irreps.simplify() + ) + + # Loss and optimization + # Check Stage Two loss start + if args.start_swa is not None: + args.swa = True + log_messages.append( + ( + "Stage Two is activated as start_stage_two was defined", + logging.INFO, + ) + ) + + if args.swa: + if args.start_swa is None: + args.start_swa = max(1, args.max_num_epochs // 4 * 3) + if args.start_swa > args.max_num_epochs: + log_messages.append( + ( + f"start_stage_two must be less than max_num_epochs, got {args.start_swa} > {args.max_num_epochs}", + logging.WARNING, + ) + ) + log_messages.append( + ( + "Stage Two will not start, as start_stage_two > max_num_epochs", + logging.WARNING, + ) + ) + args.swa = False + + if args.embedding_specs: + args.embedding_specs = ast.literal_eval(args.embedding_specs) + + return args, log_messages diff --git a/models/mace/mace/tools/cg.py b/models/mace/mace/tools/cg.py new file mode 100644 index 0000000000000000000000000000000000000000..29cf05ee90a6508196807bac889fd5ccf7b0cf5f --- /dev/null +++ b/models/mace/mace/tools/cg.py @@ -0,0 +1,278 @@ +########################################################################################### +# Higher Order Real Clebsch Gordan (based on e3nn by Mario Geiger) +# Authors: Ilyes Batatia +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import collections +import itertools +import os +from typing import Iterator, List, Union + +import numpy as np +import torch +from e3nn import o3 + +try: + import cuequivariance as cue + + CUET_AVAILABLE = True +except ImportError: + CUET_AVAILABLE = False + +USE_CUEQ_CG = os.environ.get("MACE_USE_CUEQ_CG", "0").lower() in ( + "1", + "true", + "yes", + "y", +) + +_TP = collections.namedtuple("_TP", "op, args") +_INPUT = collections.namedtuple("_INPUT", "tensor, start, stop") + + +def _wigner_nj( + irrepss: List[o3.Irreps], + normalization: str = "component", + filter_ir_mid=None, + dtype=None, +): + irrepss = [o3.Irreps(irreps) for irreps in irrepss] + if filter_ir_mid is not None: + filter_ir_mid = [o3.Irrep(ir) for ir in filter_ir_mid] + + if len(irrepss) == 1: + (irreps,) = irrepss + ret = [] + e = torch.eye(irreps.dim, dtype=dtype) + i = 0 + for mul, ir in irreps: + for _ in range(mul): + sl = slice(i, i + ir.dim) + ret += [(ir, _INPUT(0, sl.start, sl.stop), e[sl])] + i += ir.dim + return ret + + *irrepss_left, irreps_right = irrepss + ret = [] + for ir_left, path_left, C_left in _wigner_nj( + irrepss_left, + normalization=normalization, + filter_ir_mid=filter_ir_mid, + dtype=dtype, + ): + i = 0 + for mul, ir in irreps_right: + for ir_out in ir_left * ir: + if filter_ir_mid is not None and ir_out not in filter_ir_mid: + continue + + C = o3.wigner_3j(ir_out.l, ir_left.l, ir.l, dtype=dtype) + if normalization == "component": + C *= ir_out.dim**0.5 + if normalization == "norm": + C *= ir_left.dim**0.5 * ir.dim**0.5 + + C = torch.einsum("jk,ijl->ikl", C_left.flatten(1), C) + C = C.reshape( + ir_out.dim, *(irreps.dim for irreps in irrepss_left), ir.dim + ) + for u in range(mul): + E = torch.zeros( + ir_out.dim, + *(irreps.dim for irreps in irrepss_left), + irreps_right.dim, + dtype=dtype, + ) + sl = slice(i + u * ir.dim, i + (u + 1) * ir.dim) + E[..., sl] = C + ret += [ + ( + ir_out, + _TP( + op=(ir_left, ir, ir_out), + args=( + path_left, + _INPUT(len(irrepss_left), sl.start, sl.stop), + ), + ), + E, + ) + ] + i += mul * ir.dim + return sorted(ret, key=lambda x: x[0]) + + +def U_matrix_real( + irreps_in: Union[str, o3.Irreps], + irreps_out: Union[str, o3.Irreps], + correlation: int, + normalization: str = "component", + filter_ir_mid=None, + dtype=None, + use_cueq_cg=True, + use_nonsymmetric_product=False, +): + irreps_out = o3.Irreps(irreps_out) + irrepss = [o3.Irreps(irreps_in)] * correlation + + if use_cueq_cg is None: + use_cueq_cg = USE_CUEQ_CG + if correlation == 4 and not use_cueq_cg: + filter_ir_mid = [(i, 1 if i % 2 == 0 else -1) for i in range(12)] + if use_cueq_cg and CUET_AVAILABLE: + return compute_U_cueq( # pylint: disable=possibly-used-before-assignment + irreps_in, irreps_out=irreps_out, correlation=correlation, dtype=dtype + ) + + try: + wigners = _wigner_nj(irrepss, normalization, filter_ir_mid, dtype) + except NotImplementedError as e: + if CUET_AVAILABLE: + return compute_U_cueq( # pylint: disable=possibly-used-before-assignment + irreps_in, + irreps_out=irreps_out, + correlation=correlation, + use_nonsymmetric_product=use_nonsymmetric_product, + dtype=dtype, + ) + raise NotImplementedError( + "The requested Clebsch-Gordan coefficients are not implemented, please install cuequivariance; pip install cuequivariance" + ) from e + + current_ir = wigners[0][0] + out = [] + stack = torch.tensor([]) + + for ir, _, base_o3 in wigners: + if ir in irreps_out and ir == current_ir: + stack = torch.cat((stack, base_o3.squeeze().unsqueeze(-1)), dim=-1) + last_ir = current_ir + elif ir in irreps_out and ir != current_ir: + if len(stack) != 0: + out += [last_ir, stack] + stack = base_o3.squeeze().unsqueeze(-1) + current_ir, last_ir = ir, ir + else: + current_ir = ir + try: + out += [last_ir, stack] + except: # pylint: disable=bare-except + first_dim = irreps_out.dim + if first_dim != 1: + size = [first_dim] + [o3.Irreps(irreps_in).dim] * correlation + [1] + else: + size = [o3.Irreps(irreps_in).dim] * correlation + [1] + out = [str(irreps_out)[:-2], torch.zeros(size, dtype=dtype)] + return out + + +if CUET_AVAILABLE: + + def compute_U_cueq( + irreps_in, irreps_out, correlation=2, use_nonsymmetric_product=False, dtype=None + ): + if dtype is None: + dtype = torch.get_default_dtype() + U = [] + irreps_in = cue.Irreps(O3_e3nn, str(irreps_in)) + irreps_out = cue.Irreps(O3_e3nn, str(irreps_out)) + for _, ir in irreps_out: + try: + U_matrix_full_symm = cue.reduced_symmetric_tensor_product_basis( + irreps_in, + correlation, + keep_ir=ir, + layout=cue.ir_mul, + ) + U_matrix_full_symm = U_matrix_full_symm.array + if use_nonsymmetric_product: + try: + U_matrix_full_antisymmetric = ( + cue.reduced_antisymmetric_tensor_product_basis( + irreps_in, + correlation, + keep_ir=ir, + layout=cue.ir_mul, + ).array + ) + U_matrix_full = torch.cat( + (U_matrix_full_symm, U_matrix_full_antisymmetric), dim=-1 + ) + except ValueError: + continue + else: + U_matrix_full = U_matrix_full_symm + + except ValueError: + if ir.dim == 1: + out_shape = (*([irreps_in.dim] * correlation), 1) + else: + out_shape = (ir.dim, *([irreps_in.dim] * correlation), 1) + return [ + torch.zeros( + out_shape, + dtype=torch.get_default_dtype(), + ) + ] + if U_matrix_full.shape[-1] == 0: + if ir.dim == 1: + out_shape = (*([irreps_in.dim] * correlation), 1) + else: + out_shape = (ir.dim, *([irreps_in.dim] * correlation), 1) + return [ + torch.zeros( + out_shape, + dtype=torch.get_default_dtype(), + ) + ] + ir_str = str(ir) + U.append(ir_str) + U_matrix_full = torch.tensor( + U_matrix_full.reshape(*([irreps_in.dim] * correlation), ir.dim, -1), + dtype=dtype, + ) + U_matrix_full = torch.moveaxis(U_matrix_full, -2, 0) + if ir.dim == 1: + U_matrix_full = U_matrix_full[0] + U.append(U_matrix_full) + return U + + class O3_e3nn(cue.O3): + def __mul__( # pylint: disable=no-self-argument + rep1: "O3_e3nn", rep2: "O3_e3nn" + ) -> Iterator["O3_e3nn"]: + return [O3_e3nn(l=ir.l, p=ir.p) for ir in cue.O3.__mul__(rep1, rep2)] + + @classmethod + def clebsch_gordan( + cls, rep1: "O3_e3nn", rep2: "O3_e3nn", rep3: "O3_e3nn" + ) -> np.ndarray: + rep1, rep2, rep3 = cls._from(rep1), cls._from(rep2), cls._from(rep3) + + if rep1.p * rep2.p == rep3.p: + return o3.wigner_3j(rep1.l, rep2.l, rep3.l).numpy()[None] * np.sqrt( + rep3.dim + ) + return np.zeros((0, rep1.dim, rep2.dim, rep3.dim)) + + def __lt__( # pylint: disable=no-self-argument + rep1: "O3_e3nn", rep2: "O3_e3nn" + ) -> bool: + rep2 = rep1._from(rep2) + return (rep1.l, rep1.p) < (rep2.l, rep2.p) + + @classmethod + def iterator(cls) -> Iterator["O3_e3nn"]: + for l in itertools.count(0): + yield O3_e3nn(l=l, p=1 * (-1) ** l) + yield O3_e3nn(l=l, p=-1 * (-1) ** l) + +else: + + class O3_e3nn: + pass + + print( + "cuequivariance or cuequivariance_torch is not available. Cuequivariance acceleration will be disabled." + ) diff --git a/models/mace/mace/tools/cg_cueq_tools.py b/models/mace/mace/tools/cg_cueq_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..9362b2a4557da1045a5c9079f6d0ac8fcda02cc7 --- /dev/null +++ b/models/mace/mace/tools/cg_cueq_tools.py @@ -0,0 +1,192 @@ +# This coded was modified from the cuequivariance library: https://github.com/NVIDIA/cuEquivariance/blob/main/cuequivariance/cuequivariance/group_theory/experimental/mace/symmetric_contractions.py +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from typing import Optional + +import numpy as np +from e3nn import o3 + +from mace.tools.cg import U_matrix_real + +try: + import cuequivariance as cue + from cuequivariance.etc.linalg import round_to_sqrt_rational, triu_array + + CUEQQ_AVAILABLE = True +except (ImportError, ModuleNotFoundError): + CUEQQ_AVAILABLE = False + + class DummyCueq: + class EquivariantPolynomial: + pass + + class Irreps: + pass + + cue = DummyCueq() + round_to_sqrt_rational = None + triu_array = None + + +def symmetric_contraction_proj( + irreps_in: cue.Irreps, irreps_out: cue.Irreps, degrees: tuple[int, ...] +) -> tuple[cue.EquivariantPolynomial, np.ndarray]: + r""" + subscripts: ``weights[u],input[u],output[u]`` + + Example: + + .. code-block:: python + + e, p = symmetric_contraction( + 4 * cue.Irreps("SO3", "0+1+2"), 4 * cue.Irreps("SO3", "0+1"), [1, 2, 3] + ) + assert p.shape == (62, 18) + + mul = e.inputs[1].irreps.muls[0] + w = jax.random.normal(jax.random.key(0), (p.shape[0], mul)) + w = jnp.einsum("au,ab->bu", w, p).flatten() + + x = cuex.randn(jax.random.key(1), e.inputs[1]) + y = cuex.equivariant_polynomial(e, [w, x]) + """ + return symmetric_contraction_cached(irreps_in, irreps_out, tuple(degrees)) + + +def symmetric_contraction_cached( + irreps_in: cue.Irreps, irreps_out: cue.Irreps, degrees: tuple[int, ...] +) -> tuple[cue.EquivariantPolynomial, np.ndarray]: + assert min(degrees) > 0 + + # poly1 replicates the behavior of the original MACE implementation + poly1 = cue.EquivariantPolynomial.stack( + [ + cue.EquivariantPolynomial.stack( + [ + _symmetric_contraction(irreps_in, irreps_out[i : i + 1], deg) + for deg in reversed(degrees) + ], + [True, False, False], + ) + for i in range(len(irreps_out)) + ], + [True, False, True], + ) + + poly2 = cue.descriptors.symmetric_contraction(irreps_in, irreps_out, degrees) + a1, a2 = [ + np.concatenate( + [ + _flatten( + _stp_to_matrix(d.symmetrize_operands(range(1, d.num_operands - 1))), + 1, + None, + ) + for _, d in pol.polynomial.operations + ], + axis=1, + ) + for pol in [poly1, poly2] + ] + + # This nonzeros selection is just for lightening the inversion + nonzeros = np.nonzero(np.any(a1 != 0, axis=0) | np.any(a2 != 0, axis=0))[0] + a1, a2 = a1[:, nonzeros], a2[:, nonzeros] + projection_1_2 = a1 @ np.linalg.pinv(a2) + # projection = np.linalg.lstsq(a2.T, a1.T, rcond=None)[0].T + projection_1_2 = round_to_sqrt_rational(projection_1_2) + np.testing.assert_allclose(a1, projection_1_2 @ a2, atol=1e-7) + return poly2, projection_1_2 + + +def _flatten( + x: np.ndarray, axis_start: Optional[int] = None, axis_end: Optional[int] = None +) -> np.ndarray: + x = np.asarray(x) + if axis_start is None: + axis_start = 0 + if axis_end is None: + axis_end = x.ndim + assert 0 <= axis_start <= axis_end <= x.ndim + return x.reshape( + x.shape[:axis_start] + + (np.prod(x.shape[axis_start:axis_end]),) + + x.shape[axis_end:] + ) + + +def _stp_to_matrix( + d: cue.SegmentedTensorProduct, +) -> np.ndarray: + m = np.zeros([ope.num_segments for ope in d.operands]) + for path in d.paths: + m[path.indices] = path.coefficients + return m + + +# This function is an adaptation of https://github.com/ACEsuit/mace/blob/bd412319b11c5f56c37cec6c4cfae74b2a49ff43/mace/modules/symmetric_contraction.py +def _symmetric_contraction( + irreps_in: cue.Irreps, irreps_out: cue.Irreps, degree: int +) -> cue.EquivariantPolynomial: + mul = irreps_in.muls[0] + assert all(mul == m for m in irreps_in.muls) + assert all(mul == m for m in irreps_out.muls) + irreps_in = irreps_in.set_mul(1) + irreps_out = irreps_out.set_mul(1) + + input_operands = range(1, degree + 1) + output_operand = degree + 1 + + abc = "abcdefgh"[:degree] + d = cue.SegmentedTensorProduct.from_subscripts( + f"u_{'_'.join(f'{a}' for a in abc)}_i+{abc}ui" + ) + + for i in input_operands: + d.add_segment(i, (irreps_in.dim,)) + irreps_out_e3nn = o3.Irreps(str(irreps_out)) + irreps_in_e3nn = o3.Irreps(str(irreps_in)) + for _, ir in irreps_out: + u = U_matrix_real(irreps_in_e3nn, irreps_out_e3nn, degree)[-1] + if str(ir) == "0e" or str(ir) == "0o": + u = u.unsqueeze(0) + u = np.asarray(u) + u = np.moveaxis(u, 0, -1) + # u is shape (irreps_in.dim, ..., irreps_in.dim, u, ir_out.dim) + + if u.shape[-2] == 0: + d.add_segment(output_operand, {"i": ir.dim}) + else: + u = triu_array(u, degree) + d.add_path(None, *(0,) * degree, None, c=u) + + d = d.flatten_coefficient_modes() + d = d.append_modes_to_all_operands("u", {"u": mul}) + + assert d.num_operands >= 3 + [w, x], y = d.operands[:2], d.operands[-1] + + return cue.EquivariantPolynomial( + [ + cue.IrrepsAndLayout(irreps_in.new_scalars(w.size), cue.ir_mul), + cue.IrrepsAndLayout(mul * irreps_in, cue.ir_mul), + ], + [cue.IrrepsAndLayout(mul * irreps_out, cue.ir_mul)], + cue.SegmentedPolynomial( + [w, x], [y], [(cue.Operation([0] + [1] * degree + [2]), d)] + ), + ) diff --git a/models/mace/mace/tools/checkpoint.py b/models/mace/mace/tools/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..81161cccda0245b8fb75291f38ebb8742fd29a4b --- /dev/null +++ b/models/mace/mace/tools/checkpoint.py @@ -0,0 +1,227 @@ +########################################################################################### +# Checkpointing +# Authors: Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import dataclasses +import logging +import os +import re +from typing import Dict, List, Optional, Tuple + +import torch + +from .torch_tools import TensorDict + +Checkpoint = Dict[str, TensorDict] + + +@dataclasses.dataclass +class CheckpointState: + model: torch.nn.Module + optimizer: torch.optim.Optimizer + lr_scheduler: torch.optim.lr_scheduler.ExponentialLR + + +class CheckpointBuilder: + @staticmethod + def create_checkpoint(state: CheckpointState) -> Checkpoint: + return { + "model": state.model.state_dict(), + "optimizer": state.optimizer.state_dict(), + "lr_scheduler": state.lr_scheduler.state_dict(), + } + + @staticmethod + def load_checkpoint( + state: CheckpointState, checkpoint: Checkpoint, strict: bool + ) -> None: + state.model.load_state_dict(checkpoint["model"], strict=strict) # type: ignore + state.optimizer.load_state_dict(checkpoint["optimizer"]) + state.lr_scheduler.load_state_dict(checkpoint["lr_scheduler"]) + + +@dataclasses.dataclass +class CheckpointPathInfo: + path: str + tag: str + epochs: int + swa: bool + + +class CheckpointIO: + def __init__( + self, directory: str, tag: str, keep: bool = False, swa_start: int = None + ) -> None: + self.directory = directory + self.tag = tag + self.keep = keep + self.old_path: Optional[str] = None + self.swa_start = swa_start + + self._epochs_string = "_epoch-" + self._filename_extension = "pt" + + def _get_checkpoint_filename(self, epochs: int, swa_start=None) -> str: + if swa_start is not None and epochs >= swa_start: + return ( + self.tag + + self._epochs_string + + str(epochs) + + "_swa" + + "." + + self._filename_extension + ) + return ( + self.tag + + self._epochs_string + + str(epochs) + + "." + + self._filename_extension + ) + + def _list_file_paths(self) -> List[str]: + if not os.path.isdir(self.directory): + return [] + all_paths = [ + os.path.join(self.directory, f) for f in os.listdir(self.directory) + ] + return [path for path in all_paths if os.path.isfile(path)] + + def _parse_checkpoint_path(self, path: str) -> Optional[CheckpointPathInfo]: + filename = os.path.basename(path) + regex = re.compile( + rf"^(?P.+){self._epochs_string}(?P\d+)\.{self._filename_extension}$" + ) + regex2 = re.compile( + rf"^(?P.+){self._epochs_string}(?P\d+)_swa\.{self._filename_extension}$" + ) + match = regex.match(filename) + match2 = regex2.match(filename) + swa = False + if not match: + if not match2: + return None + match = match2 + swa = True + + return CheckpointPathInfo( + path=path, + tag=match.group("tag"), + epochs=int(match.group("epochs")), + swa=swa, + ) + + def _get_latest_checkpoint_path(self, swa) -> Optional[str]: + all_file_paths = self._list_file_paths() + checkpoint_info_list = [ + self._parse_checkpoint_path(path) for path in all_file_paths + ] + selected_checkpoint_info_list = [ + info for info in checkpoint_info_list if info and info.tag == self.tag + ] + + if len(selected_checkpoint_info_list) == 0: + logging.warning( + f"Cannot find checkpoint with tag '{self.tag}' in '{self.directory}'" + ) + return None + + selected_checkpoint_info_list_swa = [] + selected_checkpoint_info_list_no_swa = [] + + for ckp in selected_checkpoint_info_list: + if ckp.swa: + selected_checkpoint_info_list_swa.append(ckp) + else: + selected_checkpoint_info_list_no_swa.append(ckp) + if swa: + try: + latest_checkpoint_info = max( + selected_checkpoint_info_list_swa, key=lambda info: info.epochs + ) + except ValueError: + logging.warning( + "No SWA checkpoint found, while SWA is enabled. Compare the swa_start parameter and the latest checkpoint." + ) + else: + latest_checkpoint_info = max( + selected_checkpoint_info_list_no_swa, key=lambda info: info.epochs + ) + return latest_checkpoint_info.path + + def save( + self, checkpoint: Checkpoint, epochs: int, keep_last: bool = False + ) -> None: + if not self.keep and self.old_path and not keep_last: + logging.debug(f"Deleting old checkpoint file: {self.old_path}") + os.remove(self.old_path) + + filename = self._get_checkpoint_filename(epochs, self.swa_start) + path = os.path.join(self.directory, filename) + logging.debug(f"Saving checkpoint: {path}") + os.makedirs(self.directory, exist_ok=True) + torch.save(obj=checkpoint, f=path) + self.old_path = path + + def load_latest( + self, swa: Optional[bool] = False, device: Optional[torch.device] = None + ) -> Optional[Tuple[Checkpoint, int]]: + path = self._get_latest_checkpoint_path(swa=swa) + if path is None: + return None + + return self.load(path, device=device) + + def load( + self, path: str, device: Optional[torch.device] = None + ) -> Tuple[Checkpoint, int]: + checkpoint_info = self._parse_checkpoint_path(path) + + if checkpoint_info is None: + raise RuntimeError(f"Cannot find path '{path}'") + + logging.info(f"Loading checkpoint: {checkpoint_info.path}") + return ( + torch.load(f=checkpoint_info.path, map_location=device), + checkpoint_info.epochs, + ) + + +class CheckpointHandler: + def __init__(self, *args, **kwargs) -> None: + self.io = CheckpointIO(*args, **kwargs) + self.builder = CheckpointBuilder() + + def save( + self, state: CheckpointState, epochs: int, keep_last: bool = False + ) -> None: + checkpoint = self.builder.create_checkpoint(state) + self.io.save(checkpoint, epochs, keep_last) + + def load_latest( + self, + state: CheckpointState, + swa: Optional[bool] = False, + device: Optional[torch.device] = None, + strict=False, + ) -> Optional[int]: + result = self.io.load_latest(swa=swa, device=device) + if result is None: + return None + + checkpoint, epochs = result + self.builder.load_checkpoint(state=state, checkpoint=checkpoint, strict=strict) + return epochs + + def load( + self, + state: CheckpointState, + path: str, + strict=False, + device: Optional[torch.device] = None, + ) -> int: + checkpoint, epochs = self.io.load(path, device=device) + self.builder.load_checkpoint(state=state, checkpoint=checkpoint, strict=strict) + return epochs diff --git a/models/mace/mace/tools/compile.py b/models/mace/mace/tools/compile.py new file mode 100644 index 0000000000000000000000000000000000000000..03282067380d9de08a0af41a66edd38f4ddc973c --- /dev/null +++ b/models/mace/mace/tools/compile.py @@ -0,0 +1,95 @@ +from contextlib import contextmanager +from functools import wraps +from typing import Callable, Tuple + +try: + import torch._dynamo as dynamo +except ImportError: + dynamo = None +from e3nn import get_optimization_defaults, set_optimization_defaults +from torch import autograd, nn +from torch.fx import symbolic_trace + +ModuleFactory = Callable[..., nn.Module] +TypeTuple = Tuple[type, ...] + + +@contextmanager +def disable_e3nn_codegen(): + """Context manager that disables the legacy PyTorch code generation used in e3nn.""" + init_val = get_optimization_defaults()["jit_script_fx"] + set_optimization_defaults(jit_script_fx=False) + yield + set_optimization_defaults(jit_script_fx=init_val) + + +def prepare(func: ModuleFactory, allow_autograd: bool = True) -> ModuleFactory: + """Function transform that prepares a MACE module for torch.compile + + Args: + func (ModuleFactory): A function that creates an nn.Module + allow_autograd (bool, optional): Force inductor compiler to inline call to + `torch.autograd.grad`. Defaults to True. + + Returns: + ModuleFactory: Decorated function that creates a torch.compile compatible module + """ + if allow_autograd: + dynamo.allow_in_graph(autograd.grad) + else: + dynamo.disallow_in_graph(autograd.grad) + + @wraps(func) + def wrapper(*args, **kwargs): + with disable_e3nn_codegen(): + model = func(*args, **kwargs) + + model = simplify(model) + return model + + return wrapper + + +_SIMPLIFY_REGISTRY = set() + + +def simplify_if_compile(module: nn.Module) -> nn.Module: + """Decorator to register a module for symbolic simplification + + The decorated module will be simplifed using `torch.fx.symbolic_trace`. + This constrains the module to not have any dynamic control flow, see: + + https://pytorch.org/docs/stable/fx.html#limitations-of-symbolic-tracing + + Args: + module (nn.Module): the module to register + + Returns: + nn.Module: registered module + """ + _SIMPLIFY_REGISTRY.add(module) + return module + + +def simplify(module: nn.Module) -> nn.Module: + """Recursively searches for registered modules to simplify with + `torch.fx.symbolic_trace` to support compiling with the PyTorch Dynamo compiler. + + Modules are registered with the `simplify_if_compile` decorator and + + Args: + module (nn.Module): the module to simplify + + Returns: + nn.Module: the simplified module + """ + simplify_types = tuple(_SIMPLIFY_REGISTRY) + + for name, child in module.named_children(): + if isinstance(child, simplify_types): + traced = symbolic_trace(child) + setattr(module, name, traced) + else: + simplify(child) + + return module diff --git a/models/mace/mace/tools/default_keys.py b/models/mace/mace/tools/default_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..a8280cf53d27d30072e66e6175eec165109d019e --- /dev/null +++ b/models/mace/mace/tools/default_keys.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from enum import Enum + + +class DefaultKeys(Enum): + ENERGY = "REF_energy" + FORCES = "REF_forces" + STRESS = "REF_stress" + VIRIALS = "REF_virials" + DIPOLE = "dipole" + POLARIZABILITY = "polarizability" + HEAD = "head" + CHARGES = "REF_charges" + TOTAL_CHARGE = "total_charge" + TOTAL_SPIN = "total_spin" + ELEC_TEMP = "elec_temp" + + @staticmethod + def keydict() -> dict[str, str]: + key_dict = {} + for member in DefaultKeys: + key_name = f"{member.name.lower()}_key" + key_dict[key_name] = member.value + return key_dict diff --git a/models/mace/mace/tools/distributed_tools.py b/models/mace/mace/tools/distributed_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..5afde9a72425e1391efd1b22f079e7d28994ae54 --- /dev/null +++ b/models/mace/mace/tools/distributed_tools.py @@ -0,0 +1,60 @@ +import os + +import torch + + +def init_distributed(args): + """ + Returns (rank, local_rank, world_size) and initialises the process-group. + Works for: slurm | torchrun | mpi | none + """ + if not args.distributed: + return 0, 0, 1 # single-GPU / debug run + + # ------------------------------------------------------------------ slurm + if args.launcher == "slurm": + from mace.tools.slurm_distributed import DistributedEnvironment + + env = DistributedEnvironment() + rank, local_rank, world_size = env.rank, env.local_rank, env.world_size + + # ---------------------------------------------------------------- torchrun + elif args.launcher == "torchrun": + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + + + # -------------------------------------------------------------------- mpi + elif args.launcher == "mpi": + # OpenMPI & Intel-MPI export these: + rank = int(os.environ["OMPI_COMM_WORLD_RANK"]) + world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"]) + + # local-rank isn’t standardised; compute it from local node-size + local_size = int(os.environ.get("OMPI_COMM_WORLD_LOCAL_SIZE", 1)) + local_rank = rank % local_size + + # tell PyTorch where the rendez-vous server is + os.environ.setdefault("MASTER_ADDR", os.environ["MASTER_ADDR"]) + os.environ.setdefault("MASTER_PORT", os.environ.get("MASTER_PORT", "33333")) + # torchrun style vars so later code keeps working + os.environ["RANK"] = str(rank) + os.environ["WORLD_SIZE"] = str(world_size) + os.environ["LOCAL_RANK"] = str(local_rank) + + else: # "none" + return 0, 0, 1 + + if not torch.distributed.is_initialized(): + if args.device == "cuda": + torch.distributed.init_process_group( + backend="nccl", + init_method="env://", + ) + elif args.device == "xpu": + torch.distributed.init_process_group( + backend="ccl", + init_method="env://", + ) + return rank, local_rank, world_size diff --git a/models/mace/mace/tools/fairchem_dataset/__init__.py b/models/mace/mace/tools/fairchem_dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5163777df311ba3342680b1f8eec7004b7cb6110 --- /dev/null +++ b/models/mace/mace/tools/fairchem_dataset/__init__.py @@ -0,0 +1,3 @@ +from .lmdb_dataset_tools import AseDBDataset + +__all__ = ["AseDBDataset"] diff --git a/models/mace/mace/tools/fairchem_dataset/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/tools/fairchem_dataset/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db9029da623caec6a772094540fecaa21ec76d03 Binary files /dev/null and b/models/mace/mace/tools/fairchem_dataset/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/tools/fairchem_dataset/__pycache__/lmdb_dataset_tools.cpython-310.pyc b/models/mace/mace/tools/fairchem_dataset/__pycache__/lmdb_dataset_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29158e0410ce45cec370150fe16d20c6f8155b09 Binary files /dev/null and b/models/mace/mace/tools/fairchem_dataset/__pycache__/lmdb_dataset_tools.cpython-310.pyc differ diff --git a/models/mace/mace/tools/fairchem_dataset/fairchem_readme.md b/models/mace/mace/tools/fairchem_dataset/fairchem_readme.md new file mode 100644 index 0000000000000000000000000000000000000000..252c5e78266e509b79fdef08cd65b8ff39b32262 --- /dev/null +++ b/models/mace/mace/tools/fairchem_dataset/fairchem_readme.md @@ -0,0 +1,17 @@ +# AseDBDataset Library + +This library provides a standalone implementation of the AseDBDataset class extracted from the FairChem codebase. The AseDBDataset allows you to connect to ASE databases with various backends including JSON, SQLite, and LMDB. + +## License Information + +The code in this repository contains components from multiple sources with different licenses: + +1. **Main Code (AseDBDataset, AseAtomsDataset, BaseDataset, etc.)**: + - Original Source: Meta's FairChem codebase + - License: MIT License + - Copyright: Meta, Inc. and its affiliates + +2. **LMDBDatabase Component**: + - Original Source: Modified from ASE database JSON backend + - License: LGPL 2.1 + - The ASE notice for the LGPL 2.1 license is available at: https://gitlab.com/ase/ase/-/blob/master/LICENSE diff --git a/models/mace/mace/tools/fairchem_dataset/lmdb_dataset_tools.py b/models/mace/mace/tools/fairchem_dataset/lmdb_dataset_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..15694063ceff7c9634055794afd883e23c85e33f --- /dev/null +++ b/models/mace/mace/tools/fairchem_dataset/lmdb_dataset_tools.py @@ -0,0 +1,1033 @@ +""" +This module contains the AseDBDataset class and its dependencies. +It is extracted from the fairchem codebase and adapted to remove dependencies on fairchem. + +Original code copyright: +Copyright (c) Meta, Inc. and its affiliates. + +This source code is licensed under the MIT license found in the +LICENSE file in the root directory of this source tree. +""" + +from __future__ import annotations + +import bisect +import logging +import numbers +import os +import zlib +from abc import ABC, abstractmethod + +try: + from functools import cache, cached_property +except ImportError: + from functools import cached_property, lru_cache + + cache = lru_cache(maxsize=None) +from glob import glob +from pathlib import Path +from typing import Any, Callable, TypeVar + +import ase +import ase.db.core +import ase.db.row +import ase.io +import lmdb +import numpy as np +import orjson +import torch + +# Type variable for generic dataset return type +T_co = TypeVar("T_co", covariant=True) + + +def _decode_ndarrays(obj): + """Recursively turn {"__ndarray__": [...] } blobs back into NumPy arrays.""" + if isinstance(obj, dict): + if "__ndarray__" in obj: + shape, dtype, flat = obj["__ndarray__"] + return np.asarray(flat, dtype=dtype).reshape(shape) + # recurse into dict values + return {k: _decode_ndarrays(v) for k, v in obj.items()} + if isinstance(obj, list): + return [_decode_ndarrays(v) for v in obj] + if isinstance(obj, tuple): + return tuple(_decode_ndarrays(v) for v in obj) + return obj # everything else is left untouched + + +def rename_data_object_keys(data_object, key_mapping: dict[str, str | list[str]]): + """Rename data object keys + + Args: + data_object: data object + key_mapping: dictionary specifying keys to rename and new names {prev_key: new_key} + + new_key can be a list of new keys, for example, + prev_key: energy + new_key: [common_energy, oc20_energy] + + This is currently required when we use a single target/label for multiple tasks + """ + for _property in key_mapping: + # catch for test data not containing labels + if _property in data_object: + list_of_new_keys = key_mapping[_property] + if isinstance(list_of_new_keys, str): + list_of_new_keys = [list_of_new_keys] + for new_property in list_of_new_keys: + if new_property == _property: + continue + assert new_property not in data_object + data_object[new_property] = data_object[_property] + if _property not in list_of_new_keys: + del data_object[_property] + return data_object + + +def apply_one_tags( + atoms: ase.Atoms, skip_if_nonzero: bool = True, skip_always: bool = False +): + """ + This function will apply tags of 1 to an ASE atoms object. + It is used as an atoms_transform in the datasets contained in this file. + + Certain models will treat atoms differently depending on their tags. + For example, GemNet-OC by default will only compute triplet and quadruplet interactions + for atoms with non-zero tags. This model throws an error if there are no tagged atoms. + For this reason, the default behavior is to tag atoms in structures with no tags. + + args: + skip_if_nonzero (bool): If at least one atom has a nonzero tag, do not tag any atoms + + skip_always (bool): Do not apply any tags. This arg exists so that this function can be disabled + without needing to pass a callable (which is currently difficult to do with main.py) + """ + if skip_always: + return atoms + + if np.all(atoms.get_tags() == 0) or not skip_if_nonzero: + atoms.set_tags(np.ones(len(atoms))) + + return atoms + + +class UnsupportedDatasetError(ValueError): + pass + + +class BaseDataset(ABC): + """Base Dataset class for all ASE datasets.""" + + def __init__(self, config: dict): + """Initialize + + Args: + config (dict): dataset configuration + """ + self.config = config + self.paths = [] + + if "src" in self.config: + if isinstance(config["src"], str): + self.paths = [Path(self.config["src"])] + else: + self.paths = tuple(Path(path) for path in sorted(config["src"])) + + self.lin_ref = None + if self.config.get("lin_ref", False): + lin_ref = torch.tensor( + np.load(self.config["lin_ref"], allow_pickle=True)["coeff"] + ) + self.lin_ref = torch.nn.Parameter(lin_ref, requires_grad=False) + + def __len__(self) -> int: + return self.num_samples + + def metadata_hasattr(self, attr) -> bool: + return attr in self._metadata + + @cached_property + def indices(self): + return np.arange(self.num_samples, dtype=int) + + @cached_property + def _metadata(self) -> dict[str, np.ndarray]: + # logic to read metadata file here + metadata_npzs = [] + if self.config.get("metadata_path", None) is not None: + metadata_npzs.append( + np.load(self.config["metadata_path"], allow_pickle=True) + ) + + else: + for path in self.paths: + if path.is_file(): + metadata_file = path.parent / "metadata.npz" + else: + metadata_file = path / "metadata.npz" + if metadata_file.is_file(): + metadata_npzs.append(np.load(metadata_file, allow_pickle=True)) + + if len(metadata_npzs) == 0: + logging.warning( + f"Could not find dataset metadata.npz files in '{self.paths}'" + ) + return {} + + metadata = { + field: np.concatenate([metadata[field] for metadata in metadata_npzs]) + for field in metadata_npzs[0] + } + + assert np.issubdtype( + metadata["natoms"].dtype, np.integer + ), f"Metadata natoms must be an integer type! not {metadata['natoms'].dtype}" + assert metadata["natoms"].shape[0] == len( + self + ), "Loaded metadata and dataset size mismatch." + + return metadata + + def get_metadata(self, attr, idx): + if attr in self._metadata: + metadata_attr = self._metadata[attr] + if isinstance(idx, list): + return [metadata_attr[_idx] for _idx in idx] + return metadata_attr[idx] + return None + + +class Subset(BaseDataset): + """A subset that also takes metadata if given.""" + + def __init__( + self, + dataset: BaseDataset, + indices: list[int], + metadata: dict[str, np.ndarray], + ) -> None: + super().__init__(dataset.config) + self.dataset = dataset + self.metadata = metadata + self.indices = indices + self.num_samples = len(indices) + self.config = dataset.config + + @cached_property + def _metadata(self) -> dict[str, np.ndarray]: + return self.dataset._metadata # pylint: disable=protected-access + + def get_metadata(self, attr, idx): + if isinstance(idx, list): + return self.dataset.get_metadata(attr, [[self.indices[i] for i in idx]]) + return self.dataset.get_metadata(attr, self.indices[idx]) + + +class LMDBDatabase(ase.db.core.Database): + """ + This module is modified from the ASE db json backend + and is thus licensed under the corresponding LGPL2.1 license. + + The ASE notice for the LGPL2.1 license is available here: + https://gitlab.com/ase/ase/-/blob/master/LICENSE + """ + + def __init__( # pylint: disable=keyword-arg-before-vararg + self, + filename: str | Path | None = None, + create_indices: bool = True, + use_lock_file: bool = False, + serial: bool = False, + readonly: bool = False, # Moved after *args to make it keyword-only + *args, + **kwargs, + ) -> None: + """ + For the most part, this is identical to the standard ase db initiation + arguments, except that we add a readonly flag. + """ + super().__init__( + Path(filename), + create_indices, + use_lock_file, + serial, + *args, + **kwargs, + ) + + # Add a readonly mode for when we're only training + # to make sure there's no parallel locks + self.readonly = readonly + + if self.readonly: + # Open a new env + self.env = lmdb.open( + str(self.filename), + subdir=False, + meminit=False, + map_async=True, + readonly=True, + lock=False, + ) + + # Open a transaction and keep it open for fast read/writes! + self.txn = self.env.begin(write=False) + + else: + # Open a new env with write access + self.env = lmdb.open( + str(self.filename), + map_size=1099511627776 * 2, + subdir=False, + meminit=False, + map_async=True, + ) + + self.txn = self.env.begin(write=True) + + # Load all ids based on keys in the DB. + self.ids = [] + self.deleted_ids = [] + self._load_ids() + + def __enter__(self) -> "LMDBDatabase": + return self + + def __exit__(self, exc_type, exc_value, tb) -> None: + self.close() + + def close(self) -> None: + # Close the lmdb environment and transaction + self.txn.commit() + self.env.close() + + def _write( + self, + atoms: ase.Atoms | ase.db.row.AtomsRow, + key_value_pairs: dict, + data: dict | None, + id: int | None = None, # pylint: disable=redefined-builtin + ) -> None: + + # 1) dump the entire atoms.info dict into key_value_pairs + key_value_pairs = dict(key_value_pairs or {}, **atoms.info) + scalar_types = (numbers.Real, str, bool, np.bool_) + key_value_pairs = { + k: v + for k, v in (key_value_pairs or {}).items() + if isinstance(v, scalar_types) + } + + if data is None: + data = {} + for k, v in atoms.info.items(): + if isinstance(v, scalar_types): + key_value_pairs[k] = v + else: + # If the value is not serializable, we store it in data + data.setdefault("__info__", {})[k] = v + arrays_to_dump = {} + for name, arr in atoms.arrays.items(): + if name not in ( + "numbers", + "positions", + "tags", + "momenta", + "masses", + "charges", + "magmoms", + "velocities", + ): + arrays_to_dump[name] = arr + if arrays_to_dump: + data.setdefault("__arrays__", {}).update(arrays_to_dump) + + # 3) also save all extra calculator results (if any) + if hasattr(atoms, "calc") and getattr(atoms.calc, "results", None): + for k, v in atoms.calc.results.items(): + if k in ("energy", "forces", "stress", "free_energy"): + continue # ASE already stores these + data.setdefault(k, v) + # Call parent method with the original parameter name + super()._write(atoms, key_value_pairs, data) + + mtime = ase.db.core.now() + + if isinstance(atoms, ase.db.row.AtomsRow): + row = atoms + else: + row = ase.db.row.AtomsRow(atoms) + row.ctime = mtime + row.user = os.getenv("USER") + + dct = {} + for key in row.__dict__: + # Use getattr to avoid accessing protected member directly + if key[0] == "_" or key == "id" or key in getattr(row, "_keys", []): + continue + dct[key] = row[key] + + dct["mtime"] = mtime + + if key_value_pairs: + dct["key_value_pairs"] = key_value_pairs + + if data: + dct["data"] = data + + constraints = row.get("constraints") + if constraints: + dct["constraints"] = [constraint.todict() for constraint in constraints] + + # json doesn't like Cell objects, so make it an array + dct["cell"] = np.asarray(dct["cell"]) + + if id is None: + id = self._nextid + nextid = id + 1 + else: + data = self.txn.get(f"{id}".encode("ascii")) + assert data is not None + + # Add the new entry + self.txn.put( + f"{id}".encode("ascii"), + zlib.compress(orjson.dumps(dct, option=orjson.OPT_SERIALIZE_NUMPY)), + ) + # only append if idx is not in ids + if id not in self.ids: + self.ids.append(id) + self.txn.put( + "nextid".encode("ascii"), + zlib.compress(orjson.dumps(nextid, option=orjson.OPT_SERIALIZE_NUMPY)), + ) + # check if id is in removed ids and remove accordingly + if id in self.deleted_ids: + self.deleted_ids.remove(id) + self._write_deleted_ids() + + return id + + def _update( + self, + idx: int, + key_value_pairs: dict | None = None, + data: dict | None = None, + ): + # hack this to play nicely with ASE code + row = self._get_row(idx, include_data=True) + if data is not None or key_value_pairs is not None: + self._write( + atoms=row, key_value_pairs=key_value_pairs, data=data, id=idx + ) # Fixed E1123 by using id=idx + + def _write_deleted_ids(self): + self.txn.put( + "deleted_ids".encode("ascii"), + zlib.compress( + orjson.dumps(self.deleted_ids, option=orjson.OPT_SERIALIZE_NUMPY) + ), + ) + + def delete(self, ids: list[int]) -> None: + for idx in ids: + self.txn.delete(f"{idx}".encode("ascii")) + self.ids.remove(idx) + + self.deleted_ids += ids + self._write_deleted_ids() + + def _get_row(self, idx: int, include_data: bool = True): + if idx is None: + assert len(self.ids) == 1 + idx = self.ids[0] + data = self.txn.get(f"{idx}".encode("ascii")) + + if data is not None: + dct = orjson.loads(zlib.decompress(data)) + else: + raise KeyError(f"Id {idx} missing from the database!") + + if not include_data: + dct.pop("data", None) + + dct["id"] = idx + return ase.db.row.AtomsRow(dct) + + def _get_row_by_index(self, index: int, include_data: bool = True): + """Auxiliary function to get the ith entry, rather than a specific id""" + data = self.txn.get(f"{self.ids[index]}".encode("ascii")) + + if data is not None: + dct = orjson.loads(zlib.decompress(data)) + else: + raise KeyError(f"Id {id} missing from the database!") + + if not include_data: + dct.pop("data", None) + + dct["id"] = id + return ase.db.row.AtomsRow(dct) + + def _select( + self, + keys, + cmps: list[tuple[str, str, str]], + explain: bool = False, + _verbosity: int = 0, # Unused parameter marked with underscore + limit: int | None = None, + offset: int = 0, + sort: str | None = None, + include_data: bool = True, + _columns: str = "all", # Unused parameter marked with underscore + ): + if explain: + yield {"explain": (0, 0, 0, "scan table")} + return + + if sort is not None: + if sort[0] == "-": + reverse = True + sort = sort[1:] + else: + reverse = False + + rows = [] + missing = [] + for row in self._select(keys, cmps): + key = row.get(sort) + if key is None: + missing.append((0, row)) + else: + rows.append((key, row)) + + rows.sort(reverse=reverse, key=lambda x: x[0]) + rows += missing + + if limit: + rows = rows[offset : offset + limit] + for _, row in rows: + yield row + return + + if not limit: + limit = -offset - 1 + + cmps = [(key, ase.db.core.ops[op], val) for key, op, val in cmps] + n = 0 + for idx in self.ids: + if n - offset == limit: + return + row = self._get_row(idx, include_data=include_data) + + for key in keys: + if key not in row: + break + else: + for key, op, val in cmps: + if isinstance(key, int): + value = np.equal(row.numbers, key).sum() + else: + value = row.get(key) + if key == "pbc": + assert op in [ase.db.core.ops["="], ase.db.core.ops["!="]] + value = "".join("FT"[x] for x in value) + if value is None or not op(value, val): + break + else: + if n >= offset: + yield row + n += 1 + + @property + def metadata(self): + """Override abstract metadata method from Database class.""" + return self.db_metadata + + @property + def db_metadata(self): + """Load the metadata from the DB if present""" + if self._metadata is None: + metadata = self.txn.get("metadata".encode("ascii")) + if metadata is None: + self._metadata = {} + else: + self._metadata = orjson.loads(zlib.decompress(metadata)) + + return self._metadata.copy() + + @db_metadata.setter + def db_metadata(self, dct): + self._metadata = dct + + # Put the updated metadata dictionary + self.txn.put( + "metadata".encode("ascii"), + zlib.compress(orjson.dumps(dct, option=orjson.OPT_SERIALIZE_NUMPY)), + ) + + @property + def _nextid(self): + """Get the id of the next row to be written""" + # Get the nextid + nextid_data = self.txn.get("nextid".encode("ascii")) + if nextid_data: + return orjson.loads(zlib.decompress(nextid_data)) + return 1 # Removed unnecessary else (R1705) + + def count(self, selection=None, **kwargs) -> int: + """Count rows. + + See the select() method for the selection syntax. Use db.count() or + len(db) to count all rows. + """ + if selection is not None: + n = 0 + for _row in self.select(selection, **kwargs): + n += 1 + return n + return len(self.ids) + + def _load_ids(self) -> None: + """Load ids from the DB + + Since ASE db ids are mostly 1-N integers, but can be missing entries + if ids have been deleted. To save space and operating under the assumption + that there will probably not be many deletions in most OCP datasets, + we just store the deleted ids. + """ + # Load the deleted ids + deleted_ids_data = self.txn.get("deleted_ids".encode("ascii")) + if deleted_ids_data is not None: + self.deleted_ids = orjson.loads(zlib.decompress(deleted_ids_data)) + + # Reconstruct the full id list + self.ids = [i for i in range(1, self._nextid) if i not in set(self.deleted_ids)] + + +# Placeholder for AtomsToGraphs class +# This is a minimal implementation without the full functionality +class AtomsToGraphs: + """Enhanced AtomsToGraphs implementation with proper property handling.""" + + def __init__( + self, + r_edges=False, + r_pbc=True, + r_energy=False, + r_forces=False, + r_stress=False, + r_data_keys=None, + **kwargs, + ): + self.r_edges = r_edges + self.r_pbc = r_pbc + self.r_energy = r_energy + self.r_forces = r_forces + self.r_stress = r_stress + self.r_data_keys = r_data_keys or {} + self.kwargs = kwargs + + def convert(self, atoms, sid=None): + """ + Convert ASE atoms to graph data format with proper property handling. + """ + from mace.tools.torch_geometric.data import Data + + # Create a minimal data object with required properties + data = Data() + + # Set positions + data.pos = torch.tensor(atoms.get_positions(), dtype=torch.float) + + # Set atomic numbers + data.atomic_numbers = torch.tensor(atoms.get_atomic_numbers(), dtype=torch.long) + + # Set cell if available + if atoms.cell is not None: + data.cell = torch.tensor(atoms.get_cell(), dtype=torch.float) + + # Set PBC if requested + if self.r_pbc: + data.pbc = torch.tensor(atoms.get_pbc(), dtype=torch.bool) + + # Set energy if requested + if self.r_energy: + energy = self._get_property(atoms, "energy") + if energy is not None: + data.energy = torch.tensor(energy, dtype=torch.float) + + # Set forces if requested + if self.r_forces: + forces = self._get_property(atoms, "forces") + if forces is not None: + data.forces = torch.tensor(forces, dtype=torch.float) + + # Set stress if requested + if self.r_stress: + stress = self._get_property(atoms, "stress") + if stress is not None: + data.stress = torch.tensor(stress, dtype=torch.float) + + # Set sid if provided + if sid is not None: + data.sid = sid + + return data + + def _get_property(self, atoms, prop_name): + """Get property from atoms, checking custom names first then standard methods.""" + # Check if we have a custom name for this property + custom_name = self.r_data_keys.get(prop_name) + + # Try custom name in info dict + if custom_name and custom_name in atoms.info: + return atoms.info[custom_name] + + # Try custom name in arrays dict + if custom_name and custom_name in atoms.arrays: + return atoms.arrays[custom_name] + + # Try standard name in info dict + if prop_name in atoms.info: + return atoms.info[prop_name] + + # Try standard name in arrays dict + if prop_name in atoms.arrays: + return atoms.arrays[prop_name] + + # Try standard ASE methods + method_map = { + "energy": "get_potential_energy", + "forces": "get_forces", + "stress": "get_stress", + } + + if prop_name in method_map and hasattr(atoms, method_map[prop_name]): + try: + method = getattr(atoms, method_map[prop_name]) + return method() + except ( + AttributeError, + RuntimeError, + ) as exc: # Fixed W0718 by specifying exceptions + logging.debug(f"Error getting property {prop_name}: {exc}") + # Removed unnecessary pass (W0107) + + return None + + +# Placeholder for DataTransforms class +class DataTransforms: + """Minimal implementation of DataTransforms to satisfy dependencies.""" + + def __init__(self, transforms_config=None): + self.transforms_config = transforms_config or {} + + def __call__(self, data): + """Apply transforms to data""" + # No transforms applied in this minimal implementation + return data + + +class AseAtomsDataset(BaseDataset, ABC): + """ + This is an abstract Dataset that includes helpful utilities for turning + ASE atoms objects into OCP-usable data objects. This should not be instantiated directly + as get_atoms_object and load_dataset_get_ids are not implemented in this base class. + + Derived classes must add at least two things: + self.get_atoms_object(id): a function that takes an identifier and returns a corresponding atoms object + + self.load_dataset_get_ids(config: dict): This function is responsible for any initialization/loads + of the dataset and importantly must return a list of all possible identifiers that can be passed into + self.get_atoms_object(id) + + Identifiers need not be any particular type. + """ + + def __init__( + self, + config: dict, + atoms_transform: Callable[[ase.Atoms, Any], ase.Atoms] = apply_one_tags, + ) -> None: + super().__init__(config) + + a2g_args = config.get("a2g_args", {}) or {} + + # set default to False if not set by user, assuming otf_graph will be used + if "r_edges" not in a2g_args: + a2g_args["r_edges"] = False + + # Make sure we always include PBC info in the resulting atoms objects + a2g_args["r_pbc"] = True + self.a2g = AtomsToGraphs(**a2g_args) + + self.key_mapping = self.config.get("key_mapping", None) + self.transforms = DataTransforms(self.config.get("transforms", {})) + + self.atoms_transform = atoms_transform + + if self.config.get("keep_in_memory", False): + self.__getitem__ = cache(self.__getitem__) + + self.ids = self._load_dataset_get_ids(config) + self.num_samples = len(self.ids) + + if len(self.ids) == 0: + raise ValueError( + rf"No valid ase data found! \n" + f"Double check that the src path and/or glob search pattern gives ASE compatible data: {config['src']}" + ) + + def __getitem__(self, idx): # pylint: disable=method-hidden + # Handle slicing + if isinstance(idx, slice): + return [self[i] for i in range(*idx.indices(len(self)))] + + # Get atoms object via derived class method + atoms = self.get_atoms(self.ids[idx]) + + # Transform atoms object + if self.atoms_transform is not None: + atoms = self.atoms_transform( + atoms, **self.config.get("atoms_transform_args", {}) + ) + + sid = atoms.info.get("sid", self.ids[idx]) + fid = atoms.info.get("fid", torch.tensor([0])) + + # Convert to data object + data_object = self.a2g.convert(atoms, sid) + data_object.fid = fid + data_object.natoms = len(atoms) + + # apply linear reference + if self.a2g.r_energy is True and self.lin_ref is not None: + data_object.energy -= sum(self.lin_ref[data_object.atomic_numbers.long()]) + + # Transform data object + data_object = self.transforms(data_object) + + if self.key_mapping is not None: + data_object = rename_data_object_keys(data_object, self.key_mapping) + + if self.config.get("include_relaxed_energy", False): + data_object.energy_relaxed = self.get_relaxed_energy(self.ids[idx]) + + return data_object + + @abstractmethod + def get_atoms(self, idx: str | int) -> ase.Atoms: + # This function should return an ASE atoms object. + raise NotImplementedError( + "Returns an ASE atoms object. Derived classes should implement this function." + ) + + @abstractmethod + def _load_dataset_get_ids(self, config): + # This function should return a list of ids that can be used to index into the database + raise NotImplementedError( + "Every ASE dataset needs to declare a function to load the dataset and return a list of ids." + ) + + def get_relaxed_energy(self, identifier): + raise NotImplementedError( + "Reading relaxed energy from trajectory or file is not implemented with this dataset. " + "If relaxed energies are saved with the atoms info dictionary, they can be used by passing the keys in " + "the r_data_keys argument under a2g_args." + ) + + def get_metadata(self, attr, idx): + # try the parent method + metadata = super().get_metadata(attr, idx) + if metadata is not None: + return metadata + # try to resolve it here + if attr != "natoms": + return None + if isinstance(idx, (list, np.ndarray)): + return np.array([self.get_metadata(attr, i) for i in idx]) + return len(self.get_atoms(idx)) + + +class AseDBDataset(AseAtomsDataset): + """ + This Dataset connects to an ASE Database, allowing the storage of atoms objects + with a variety of backends including JSON, SQLite, and database server options. + """ + + def _load_dataset_get_ids(self, config: dict) -> list[int]: + if isinstance(config["src"], list): + filepaths = [] + for path in sorted(config["src"]): + if os.path.isdir(path): + filepaths.extend(sorted(glob(f"{path}/*"))) + elif os.path.isfile(path): + filepaths.append(path) + else: + raise RuntimeError(f"Error reading dataset in {path}!") + elif os.path.isfile(config["src"]): + filepaths = [config["src"]] + elif os.path.isdir(config["src"]): + filepaths = sorted(glob(f'{config["src"]}/*')) + else: + filepaths = sorted(glob(config["src"])) + + self.dbs = [] + + for path in filepaths: + try: + self.dbs.append(self.connect_db(path, config.get("connect_args", {}))) + except ValueError: + logging.debug( + f"Tried to connect to {path} but it's not an ASE database!" + ) + + self.select_args = config.get("select_args", {}) + if self.select_args is None: + self.select_args = {} + + # Get all unique IDs from the databases + self.db_ids = [] + for db in self.dbs: + if hasattr(db, "ids") and self.select_args == {}: + self.db_ids.append(db.ids) + else: + # this is the slow alternative + self.db_ids.append([row.id for row in db.select(**self.select_args)]) + + idlens = [len(ids) for ids in self.db_ids] + self._idlen_cumulative = np.cumsum(idlens).tolist() + + return list(range(sum(idlens))) + + def get_atoms(self, idx: int) -> ase.Atoms: + """ + Return an `ase.Atoms` object for the dataset entry `idx`, decoding any + JSON‐encoded ndarrays encountered anywhere in the row. + """ + # ------------------------------------------------------------------ # + # 1. Locate the correct database and row # + # ------------------------------------------------------------------ # + db_idx = bisect.bisect(self._idlen_cumulative, idx) + local_idx = idx - self._idlen_cumulative[db_idx - 1] if db_idx else idx + row = self.get_row_from_db(db_idx, local_idx) + + # ------------------------------------------------------------------ # + # 2. Fast path if ASE can already parse the row natively # + # ------------------------------------------------------------------ # + if not (isinstance(row.numbers, dict) and "__ndarray__" in row.numbers): + atoms = row.toatoms() + else: + # -------------------------------------------------------------- # + # 3. Decode *everything* that might hide __ndarray__ blobs # + # -------------------------------------------------------------- # + atom_numbers = _decode_ndarrays(row.numbers) + positions = _decode_ndarrays(row.positions) + cell = _decode_ndarrays(getattr(row, "cell", None)) + pbc = _decode_ndarrays(getattr(row, "pbc", None)) + + atoms = ase.Atoms( + numbers=atom_numbers, + positions=positions, + cell=cell if cell is not None else None, + pbc=pbc if pbc is not None else None, + ) + + # ------------------------------------------------------------------ # + # 4. Row-level dictionaries (data / key_value_pairs) – deep decode # + # ------------------------------------------------------------------ # + data_dict = _decode_ndarrays(row.data) if isinstance(row.data, dict) else {} + kvp_dict = ( + _decode_ndarrays(row.key_value_pairs) + if getattr(row, "key_value_pairs", None) + else {} + ) + + atoms.info.update(data_dict) + atoms.info.update(kvp_dict) + + # ------------------------------------------------------------------ # + # 5. Energy, forces, stress → atoms.calc (decode if needed) # + # ------------------------------------------------------------------ # + calc_kwargs = {} + for prop in ("energy", "forces", "stress", "free_energy"): + val = getattr(row, prop, None) + if val is not None: + calc_kwargs[prop] = _decode_ndarrays(val) + atoms.info[prop] = calc_kwargs[prop] + + if calc_kwargs: + from ase.calculators.singlepoint import SinglePointCalculator + + atoms.calc = SinglePointCalculator(atoms, **calc_kwargs) + + # ------------------------------------------------------------------ # + # 6. Extra arrays & info stored under __arrays__ / __info__ # + # ------------------------------------------------------------------ # + extra_arrays = data_dict.pop("__arrays__", {}) + for name, arr in extra_arrays.items(): + atoms.new_array(name, np.asarray(arr)) # already decoded above + + extra_info = data_dict.pop("__info__", {}) + atoms.info.update(extra_info) + + # ------------------------------------------------------------------ # + # 7. Respect any user-defined r_data_keys renamings # + # ------------------------------------------------------------------ # + a2g_args = self.config.get("a2g_args", {}) or {} + r_data_keys = a2g_args.get("r_data_keys", {}) + for custom, standard in r_data_keys.items(): + if standard in atoms.info: + atoms.info[custom] = atoms.info[standard] + elif standard in atoms.arrays: + atoms.arrays[custom] = atoms.arrays[standard] + + return atoms + + def get_row_from_db(self, db_idx, el_idx): + """Get a row from the database at the given indices.""" + db = self.dbs[db_idx] + row_id = self.db_ids[db_idx][el_idx] + if isinstance(db, LMDBDatabase): + return db._get_row(row_id) # pylint: disable=protected-access + return db.get(row_id) + + @staticmethod + def connect_db( + address: str | Path, connect_args: dict | None = None + ) -> ase.db.core.Database: + if connect_args is None: + connect_args = {} + db_type = connect_args.get("type", "extract_from_name") + if db_type in ("lmdb", "aselmdb") or ( + db_type == "extract_from_name" + and str(address).rsplit(".", maxsplit=1)[-1] in ("lmdb", "aselmdb") + ): + return LMDBDatabase(address, readonly=True, **connect_args) + + return ase.db.connect(address, **connect_args) + + def __del__(self): + for db in self.dbs: + if hasattr(db, "close"): + db.close() + + def sample_property_metadata( + self, + ) -> dict: # Removed unused argument num_samples (W0613) + """ + Sample property metadata from the database. + + This method was previously using the copy module which is now removed. + """ + logging.warning( + "You specified a folder of ASE dbs, so it's impossible to know which metadata to use. Using the first!" + ) + if self.dbs[0].metadata == {}: + return {} + + # Fixed unnecessary comprehension (R1721) + return dict(self.dbs[0].metadata.items()) diff --git a/models/mace/mace/tools/finetuning_utils.py b/models/mace/mace/tools/finetuning_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3e81492bd43ac0f0ed8a311fecaea4a7836ea108 --- /dev/null +++ b/models/mace/mace/tools/finetuning_utils.py @@ -0,0 +1,310 @@ +import torch + +from mace.tools.utils import AtomicNumberTable + + +def load_foundations_elements( + model: torch.nn.Module, + model_foundations: torch.nn.Module, + table: AtomicNumberTable, + load_readout=False, + use_shift=True, + use_scale=True, + max_L=2, +): + """ + Load the foundations of a model into a model for fine-tuning. + """ + assert model_foundations.r_max == model.r_max + z_table = AtomicNumberTable([int(z) for z in model_foundations.atomic_numbers]) + model_heads = model.heads + new_z_table = table + num_species_foundations = len(z_table.zs) + num_channels_foundation = ( + model_foundations.node_embedding.linear.weight.shape[0] + // num_species_foundations + ) + indices_weights = [z_table.z_to_index(z) for z in new_z_table.zs] + num_radial = model.radial_embedding.out_dim + num_species = len(indices_weights) + max_ell = model.spherical_harmonics._lmax # pylint: disable=protected-access + model.node_embedding.linear.weight = torch.nn.Parameter( + model_foundations.node_embedding.linear.weight.view( + num_species_foundations, -1 + )[indices_weights, :] + .flatten() + .clone() + / (num_species_foundations / num_species) ** 0.5 + ) + if hasattr(model, "joint_embedding"): + for (_, param_1), (_, param_2) in zip( + model.joint_embedding.named_parameters(), + model_foundations.joint_embedding.named_parameters(), + ): + param_1.data.copy_(param_2.data) + if hasattr(model, "embedding_readout"): + for (_, param_1), (_, param_2) in zip( + model.embedding_readout.named_parameters(), + model_foundations.embedding_readout.named_parameters(), + ): + param_1.data.copy_( + param_2.data.reshape(-1, 1) + .repeat(1, len(model_heads)) + .flatten() + .clone() + ) + if model.radial_embedding.bessel_fn.__class__.__name__ == "BesselBasis": + model.radial_embedding.bessel_fn.bessel_weights = torch.nn.Parameter( + model_foundations.radial_embedding.bessel_fn.bessel_weights.clone() + ) + for i in range(int(model.num_interactions)): + model.interactions[i].linear_up.weight = torch.nn.Parameter( + model_foundations.interactions[i].linear_up.weight.clone() + ) + model.interactions[i].avg_num_neighbors = model_foundations.interactions[ + i + ].avg_num_neighbors + + for (_, param_1), (_, param_2) in zip( + model.interactions[i].conv_tp_weights.named_parameters(), + model_foundations.interactions[i].conv_tp_weights.named_parameters(), + ): + if param_1.shape == param_2.shape: + param_1.data.copy_(param_2.data) + else: + param_1.data.copy_(param_2.data[: (num_radial + 2 * num_species), ...]) + if hasattr(model.interactions[i], "linear"): + model.interactions[i].linear.weight = torch.nn.Parameter( + model_foundations.interactions[i].linear.weight.clone() + ) + if hasattr(model.interactions[i], "linear_1"): + model.interactions[i].linear_1.weight = torch.nn.Parameter( + model_foundations.interactions[i].linear_1.weight.clone() + ) + if hasattr(model.interactions[i], "linear_2"): + model.interactions[i].linear_2.weight = torch.nn.Parameter( + model_foundations.interactions[i].linear_2.weight.clone() + ) + if hasattr(model.interactions[i], "linear_res"): + model.interactions[i].linear_res.weight = torch.nn.Parameter( + model_foundations.interactions[i].linear_res.weight.clone() + ) + if hasattr(model.interactions[i], "source_embedding"): + model.interactions[i].source_embedding.weight = torch.nn.Parameter( + model_foundations.interactions[i] + .source_embedding.weight.view(num_species_foundations, -1)[ + indices_weights, : + ] + .flatten() + .clone() + / (num_species_foundations / num_species) ** 0.5 + ) + if hasattr(model.interactions[i], "target_embedding"): + model.interactions[i].target_embedding.weight = torch.nn.Parameter( + model_foundations.interactions[i] + .target_embedding.weight.view(num_species_foundations, -1)[ + indices_weights, : + ] + .flatten() + .clone() + / (num_species_foundations / num_species) ** 0.5 + ) + if hasattr(model.interactions[i], "alpha"): + model.interactions[i].alpha = torch.nn.Parameter( + model_foundations.interactions[i].alpha.clone() + ) + if hasattr(model.interactions[i], "beta"): + model.interactions[i].beta = torch.nn.Parameter( + model_foundations.interactions[i].beta.clone() + ) + if model.interactions[i].__class__.__name__ in [ + "RealAgnosticResidualInteractionBlock", + "RealAgnosticDensityResidualInteractionBlock", + ]: + model.interactions[i].skip_tp.weight = torch.nn.Parameter( + model_foundations.interactions[i] + .skip_tp.weight.reshape( + num_channels_foundation, + num_species_foundations, + num_channels_foundation, + )[:, indices_weights, :] + .flatten() + .clone() + / (num_species_foundations / num_species) ** 0.5 + ) + elif model.interactions[i].__class__.__name__ in [ + "RealAgnosticResidualNonLinearInteractionBlock", + ]: + model.interactions[i].skip_tp.weight = torch.nn.Parameter( + model_foundations.interactions[i].skip_tp.weight + ) + else: + model.interactions[i].skip_tp.weight = torch.nn.Parameter( + model_foundations.interactions[i] + .skip_tp.weight.reshape( + num_channels_foundation, + (max_ell + 1), + num_species_foundations, + num_channels_foundation, + )[:, :, indices_weights, :] + .flatten() + .clone() + / (num_species_foundations / num_species) ** 0.5 + ) + if hasattr(model.interactions[i], "density_fn"): + for (_, param_1), (_, param_2) in zip( + model.interactions[i].density_fn.named_parameters(), + model_foundations.interactions[i].density_fn.named_parameters(), + ): + param_1.data.copy_(param_2.data) + + # Transferring products + for i, product in enumerate(model.products): + indices_weights_prod = indices_weights + if hasattr(product, "use_agnostic_product"): + if product.use_agnostic_product: + indices_weights_prod = [0] + max_range = max_L + 1 if i < len(model.products) - 1 else 1 + for j in range(max_range): # Assuming 3 contractions in symmetric_contractions + product.symmetric_contractions.contractions[j].weights_max = ( + torch.nn.Parameter( + model_foundations.products[i] + .symmetric_contractions.contractions[j] + .weights_max[indices_weights_prod, :, :] + .clone() + ) + ) + + target_weights = product.symmetric_contractions.contractions[j].weights + source_weights = ( + model_foundations.products[i] + .symmetric_contractions.contractions[j] + .weights + ) + for k, _ in enumerate(target_weights): + target_weights[k] = torch.nn.Parameter( + source_weights[k][indices_weights_prod, :, :].clone() + ) + product.linear.weight = torch.nn.Parameter( + model_foundations.products[i].linear.weight.clone() + ) + + if load_readout: + # Transferring readouts + for i, readout in enumerate(model.readouts): + if readout.__class__.__name__ == "LinearReadoutBlock": + model_readouts_zero_linear_weight = readout.linear.weight.clone() + model_readouts_zero_linear_weight = ( + model_foundations.readouts[i] + .linear.weight.view(num_channels_foundation, -1) + .repeat(1, len(model_heads)) + .flatten() + .clone() + ) + readout.linear.weight = torch.nn.Parameter( + model_readouts_zero_linear_weight + ) + if readout.__class__.__name__ in [ + "NonLinearBiasReadoutBlock", + "NonLinearReadoutBlock", + ]: + assert hasattr(readout, "linear_1") or hasattr( + readout, "linear_mid" + ), "Readout block must have linear_1 or linear_mid" + # Determine shapes once to avoid uninitialized use + if hasattr(readout, "linear_1"): + shape_input_1 = ( + model_foundations.readouts[i] + .linear_1.__dict__["irreps_out"] + .num_irreps + ) + shape_output_1 = readout.linear_1.__dict__["irreps_out"].num_irreps + else: + raise ValueError("Readout block must have linear_1") + if hasattr(readout, "linear_1"): + model_readouts_one_linear_1_weight = readout.linear_1.weight.clone() + model_readouts_one_linear_1_weight = ( + model_foundations.readouts[i] + .linear_1.weight.view(num_channels_foundation, -1) + .repeat(1, len(model_heads)) + .flatten() + .clone() + ) + readout.linear_1.weight = torch.nn.Parameter( + model_readouts_one_linear_1_weight + ) + if readout.linear_1.bias is not None: + model_readouts_one_linear_1_bias = readout.linear_1.bias.clone() + model_readouts_one_linear_1_bias = ( + model_foundations.readouts[i] + .linear_1.bias.view(-1) + .repeat(len(model_heads)) + .clone() + ) + readout.linear_1.bias = torch.nn.Parameter( + model_readouts_one_linear_1_bias + ) + if hasattr(readout, "linear_mid"): + readout.linear_mid.weight = torch.nn.Parameter( + model_foundations.readouts[i] + .linear_mid.weight.view( + shape_input_1, + shape_input_1, + ) + .repeat(len(model_heads), len(model_heads)) + .flatten() + .clone() + / ((shape_input_1) / (shape_output_1)) ** 0.5 + ) + # if it has biases transfer them too + if readout.linear_mid.bias is not None: + readout.linear_mid.bias = torch.nn.Parameter( + model_foundations.readouts[i] + .linear_mid.bias.repeat(len(model_heads)) + .clone() + ) + if hasattr(readout, "linear_2"): + model_readouts_one_linear_2_weight = readout.linear_2.weight.clone() + model_readouts_one_linear_2_weight = model_foundations.readouts[ + i + ].linear_2.weight.view(shape_input_1, -1).repeat( + len(model_heads), len(model_heads) + ).flatten().clone() / ( + ((shape_input_1) / (shape_output_1)) ** 0.5 + ) + readout.linear_2.weight = torch.nn.Parameter( + model_readouts_one_linear_2_weight + ) + if readout.linear_2.bias is not None: + model_readouts_one_linear_2_bias = readout.linear_2.bias.clone() + model_readouts_one_linear_2_bias = ( + model_foundations.readouts[i] + .linear_2.bias.view(-1) + .repeat(len(model_heads)) + .flatten() + .clone() + ) + readout.linear_2.bias = torch.nn.Parameter( + model_readouts_one_linear_2_bias + ) + if model_foundations.scale_shift is not None: + if use_scale: + model.scale_shift.scale = model_foundations.scale_shift.scale.repeat( + len(model_heads) + ).clone() + if use_shift: + model.scale_shift.shift = model_foundations.scale_shift.shift.repeat( + len(model_heads) + ).clone() + return model + + +def load_foundations( + model, + model_foundations, +): + for name, param in model_foundations.named_parameters(): + if name in model.state_dict().keys(): + if "readouts" not in name: + model.state_dict()[name].copy_(param) + return model diff --git a/models/mace/mace/tools/model_script_utils.py b/models/mace/mace/tools/model_script_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2152135acc5a7fd21dc0b7bb55881d55db827c1e --- /dev/null +++ b/models/mace/mace/tools/model_script_utils.py @@ -0,0 +1,368 @@ +import ast +import logging + +import numpy as np +from e3nn import o3 + +from mace import modules +from mace.modules.wrapper_ops import CuEquivarianceConfig +from mace.tools.finetuning_utils import load_foundations_elements +from mace.tools.scripts_utils import extract_config_mace_model +from mace.tools.utils import AtomicNumberTable + + +def configure_model( + args, + train_loader, + atomic_energies, + model_foundation=None, + heads=None, + z_table=None, + head_configs=None, # NOTE This contains a lot of things +): + + + # Selecting outputs + compute_virials = args.loss == "virials" + compute_stress = args.loss in ("stress", "huber", "universal") + + if compute_virials: + args.compute_virials = True + args.error_table = "PerAtomRMSEstressvirials" + elif compute_stress: + args.compute_stress = True + args.error_table = "PerAtomRMSEstressvirials" + + output_args = { + "energy": args.compute_energy, + "forces": args.compute_forces, + "virials": compute_virials, + "stress": compute_stress, + "dipoles": args.compute_dipole, + "polarizabilities": args.compute_polarizability, + } + logging.info( + f"During training the following quantities will be reported: {', '.join([f'{report}' for report, value in output_args.items() if value])}" + ) + logging.info("===========MODEL DETAILS===========") + + if args.scaling == "no_scaling": + args.std = 1.0 + if head_configs is not None: + for head_config in head_configs: + head_config.std = 1.0 + logging.info("No scaling selected") + + + if ( + head_configs is not None + and args.std is not None + and not isinstance(args.std, list) + ): + atomic_inter_scale = [] + for head_config in head_configs: + if hasattr(head_config, "std") and head_config.std is not None: + atomic_inter_scale.append(head_config.std) + elif args.std is not None: + atomic_inter_scale.append( + args.std if isinstance(args.std, float) else 1.0 + ) + args.std = atomic_inter_scale + + elif (args.mean is None or args.std is None) and ( + args.model not in ("AtomicDipolesMACE", "AtomicDielectricMACE") + ): + args.mean, args.std = modules.scaling_classes[args.scaling]( + train_loader, atomic_energies + ) + if args.embedding_specs is not None: + logging.info("Using embedding specifications from command line arguments") + logging.info(f"Embedding specifications: {args.embedding_specs}") + + + # Build model + if model_foundation is not None and args.model in [ + "MACE", + "ScaleShiftMACE", + "MACELES", + ]: + logging.info("Loading FOUNDATION model") + model_config_foundation = extract_config_mace_model(model_foundation) + model_config_foundation["atomic_energies"] = atomic_energies + + if args.foundation_model_elements: + foundation_z_table = AtomicNumberTable( + [int(z) for z in model_foundation.atomic_numbers] + ) + model_config_foundation["atomic_numbers"] = foundation_z_table.zs + model_config_foundation["num_elements"] = len(foundation_z_table) + z_table = foundation_z_table + logging.info( + f"Using all elements from foundation model: {foundation_z_table.zs}" + ) + else: + model_config_foundation["atomic_numbers"] = z_table.zs + model_config_foundation["num_elements"] = len(z_table) + logging.info(f"Using filtered elements: {z_table.zs}") + + args.max_L = model_config_foundation["hidden_irreps"].lmax + + if ( + args.model == "ScaleShiftMACE" + or model_foundation.__class__.__name__ == "ScaleShiftMACE" + ): + model_config_foundation["atomic_inter_shift"] = ( + _determine_atomic_inter_shift(args.mean, heads) + ) + else: + model_config_foundation["atomic_inter_shift"] = [0.0] * len(heads) + model_config_foundation["atomic_inter_scale"] = [1.0] * len(heads) + args.avg_num_neighbors = model_config_foundation["avg_num_neighbors"] + args.model = ( + "FoundationMACELES" if args.model == "MACELES" else "FoundationMACE" + ) + model_config_foundation["heads"] = heads + model_config = model_config_foundation + + logging.info("Model configuration extracted from foundation model") + logging.info(f"Using {args.loss} loss function for fine-tuning") + logging.info( + f"Message passing with hidden irreps {model_config_foundation['hidden_irreps']})" + ) + logging.info( + f"{model_config_foundation['num_interactions']} layers, each with correlation order: {model_config_foundation['correlation']} (body order: {model_config_foundation['correlation']+1}) and spherical harmonics up to: l={model_config_foundation['max_ell']}" + ) + logging.info( + f"Radial cutoff: {model_config_foundation['r_max']} A (total receptive field for each atom: {model_config_foundation['r_max'] * model_config_foundation['num_interactions']} A)" + ) + logging.info( + f"Distance transform for radial basis functions: {model_config_foundation['distance_transform']}" + ) + else: + logging.info("Building model") + logging.info( + f"Message passing with {args.num_channels} channels and max_L={args.max_L} ({args.hidden_irreps})" + ) + logging.info( + f"{args.num_interactions} layers, each with correlation order: {args.correlation} (body order: {args.correlation+1}) and spherical harmonics up to: l={args.max_ell}" + ) + logging.info( + f"{args.num_radial_basis} radial and {args.num_cutoff_basis} basis functions" + ) + logging.info( + f"Radial cutoff: {args.r_max} A (total receptive field for each atom: {args.r_max * args.num_interactions} A)" + ) + logging.info( + f"Distance transform for radial basis functions: {args.distance_transform}" + ) + + assert ( + len({irrep.mul for irrep in o3.Irreps(args.hidden_irreps)}) == 1 + ), "All channels must have the same dimension, use the num_channels and max_L keywords to specify the number of channels and the maximum L" + + logging.info(f"Hidden irreps: {args.hidden_irreps}") + + cueq_config = None + if args.only_cueq: + logging.info("Using only the backend of the model") + cueq_config = CuEquivarianceConfig( + enabled=True, + layout="ir_mul", + group="O3_e3nn", + optimize_all=True, + conv_fusion=(args.device == "cuda"), + ) + + + + + + model_config = dict( + r_max=args.r_max, + num_bessel=args.num_radial_basis, + num_polynomial_cutoff=args.num_cutoff_basis, + max_ell=args.max_ell, + interaction_cls=modules.interaction_classes[args.interaction], + num_interactions=args.num_interactions, + num_elements=len(z_table), + hidden_irreps=o3.Irreps(args.hidden_irreps), + edge_irreps=o3.Irreps(args.edge_irreps) if args.edge_irreps else None, + atomic_energies=atomic_energies, + apply_cutoff=args.apply_cutoff, + avg_num_neighbors=args.avg_num_neighbors, + atomic_numbers=z_table.zs, + use_reduced_cg=args.use_reduced_cg, + use_so3=args.use_so3, + cueq_config=cueq_config, + ) + + + + model_config_foundation = None + + model = _build_model(args, model_config, model_config_foundation, heads) + + if model_foundation is not None: + model = load_foundations_elements( + model, + model_foundation, + z_table, + load_readout=args.foundation_filter_elements, + max_L=args.max_L, + ) + + + return model, output_args + + +def _determine_atomic_inter_shift(mean, heads): + if isinstance(mean, np.ndarray): + if mean.size == 1: + return mean.item() + if mean.size == len(heads): + return mean.tolist() + logging.info("Mean not in correct format, using default value of 0.0") + return [0.0] * len(heads) + if isinstance(mean, list) and len(mean) == len(heads): + return mean + if isinstance(mean, float): + return [mean] * len(heads) + logging.info("Mean not in correct format, using default value of 0.0") + return [0.0] * len(heads) + + +def _build_model( + args, model_config, model_config_foundation, heads +): # pylint: disable=too-many-return-statements + if args.model == "MACE": + if args.interaction_first not in [ + "RealAgnosticInteractionBlock", + "RealAgnosticDensityInteractionBlock", + ]: + args.interaction_first = "RealAgnosticInteractionBlock" + return modules.ScaleShiftMACE( + **model_config, + pair_repulsion=args.pair_repulsion, + distance_transform=args.distance_transform, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[args.interaction_first], + MLP_irreps=o3.Irreps(args.MLP_irreps), + atomic_inter_scale=args.std, + atomic_inter_shift=[0.0] * len(heads), + radial_MLP=ast.literal_eval(args.radial_MLP), + radial_type=args.radial_type, + heads=heads, + embedding_specs=args.embedding_specs, + use_embedding_readout=args.use_embedding_readout, + use_last_readout_only=args.use_last_readout_only, + use_agnostic_product=args.use_agnostic_product, + ) + if args.model == "ScaleShiftMACE": + return modules.ScaleShiftMACE( + **model_config, + pair_repulsion=args.pair_repulsion, + distance_transform=args.distance_transform, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[args.interaction_first], + MLP_irreps=o3.Irreps(args.MLP_irreps), + atomic_inter_scale=args.std, + atomic_inter_shift=args.mean, + radial_MLP=ast.literal_eval(args.radial_MLP), + radial_type=args.radial_type, + heads=heads, + embedding_specs=args.embedding_specs, + use_embedding_readout=args.use_embedding_readout, + use_last_readout_only=args.use_last_readout_only, + use_agnostic_product=args.use_agnostic_product, + ) + if args.model == "FoundationMACE": + return modules.ScaleShiftMACE(**model_config_foundation) + if args.model == "FoundationMACELES": + from mace.modules.extensions import MACELES + + return MACELES( + les_arguments=args.les_arguments, + **model_config_foundation, + ) + if args.model == "ScaleShiftBOTNet": + # say it is deprecated + raise RuntimeError("ScaleShiftBOTNet is deprecated, use MACE instead") + if args.model == "BOTNet": + raise RuntimeError("BOTNet is deprecated, use MACE instead") + if args.model == "AtomicDipolesMACE": + assert args.loss == "dipole", "Use dipole loss with AtomicDipolesMACE model" + assert ( + args.error_table == "DipoleRMSE" + ), "Use error_table DipoleRMSE with AtomicDipolesMACE model" + return modules.AtomicDipolesMACE( + **model_config, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[ + "RealAgnosticInteractionBlock" + ], + MLP_irreps=o3.Irreps(args.MLP_irreps), + ) + + if args.model == "AtomicDielectricMACE": + args.error_table = "DipolePolarRMSE" + # std_df = modules.scaling_classes["rms_dipoles_scaling"](train_loader) + assert ( + args.loss == "dipole_polar" + ), "Use dipole_polar loss with AtomicDielectricMACE model" + assert args.error_table in ( + "DipoleRMSE", + "DipolePolarRMSE", + ), "Use error_table DipoleRMSE with AtomicDielectricMACE model" + return modules.AtomicDielectricMACE( + **model_config, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[ + "RealAgnosticInteractionBlock" + ], + MLP_irreps=o3.Irreps(args.MLP_irreps), + use_polarizability=True, + ) + + if args.model == "EnergyDipolesMACE": + assert ( + args.loss == "energy_forces_dipole" + ), "Use energy_forces_dipole loss with EnergyDipolesMACE model" + assert ( + args.error_table == "EnergyDipoleRMSE" + ), "Use error_table EnergyDipoleRMSE with AtomicDipolesMACE model" + return modules.EnergyDipolesMACE( + **model_config, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[ + "RealAgnosticInteractionBlock" + ], + MLP_irreps=o3.Irreps(args.MLP_irreps), + ) + if args.model == "MACELES": + from mace.modules.extensions import MACELES + + return MACELES( + les_arguments=args.les_arguments, + **model_config, + pair_repulsion=args.pair_repulsion, + distance_transform=args.distance_transform, + correlation=args.correlation, + gate=modules.gate_dict[args.gate], + interaction_cls_first=modules.interaction_classes[args.interaction_first], + MLP_irreps=o3.Irreps(args.MLP_irreps), + atomic_inter_scale=args.std, + atomic_inter_shift=[0.0] * len(heads), + radial_MLP=ast.literal_eval(args.radial_MLP), + radial_type=args.radial_type, + heads=heads, + embedding_specs=args.embedding_specs, + use_embedding_readout=args.use_embedding_readout, + use_last_readout_only=args.use_last_readout_only, + use_agnostic_product=args.use_agnostic_product, + ) + raise RuntimeError(f"Unknown model: '{args.model}'") diff --git a/models/mace/mace/tools/multihead_tools.py b/models/mace/mace/tools/multihead_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..a435819744a62816414bd98df18d5c3f24602674 --- /dev/null +++ b/models/mace/mace/tools/multihead_tools.py @@ -0,0 +1,429 @@ +import argparse +import ast +import dataclasses +import logging +import os +import urllib.request +from copy import deepcopy +from typing import Any, Dict, List, Optional, Union + +import torch + +from mace.cli.fine_tuning_select import ( + FilteringType, + SelectionSettings, + SubselectType, + select_samples, +) +from mace.data import AtomicData, KeySpecification +from mace.data.utils import Configuration +from mace.tools import torch_geometric +from mace.tools.scripts_utils import SubsetCollection, get_dataset_from_xyz +from mace.tools.utils import AtomicNumberTable, get_cache_dir + + +@dataclasses.dataclass +class HeadConfig: + head_name: str + key_specification: KeySpecification + train_file: Optional[Union[str, List[str]]] = None + valid_file: Optional[Union[str, List[str]]] = None + test_file: Optional[str] = None + test_dir: Optional[str] = None + E0s: Optional[Any] = None + statistics_file: Optional[str] = None + valid_fraction: Optional[float] = None + config_type_weights: Optional[Dict[str, float]] = None + keep_isolated_atoms: Optional[bool] = None + atomic_numbers: Optional[Union[List[int], List[str]]] = None + mean: Optional[float] = None + std: Optional[float] = None + avg_num_neighbors: Optional[float] = None + compute_avg_num_neighbors: Optional[bool] = None + collections: Optional[SubsetCollection] = None + train_loader: Optional[torch.utils.data.DataLoader] = None + z_table: Optional[Any] = None + atomic_energies_dict: Optional[Dict[str, float]] = None + + +def dict_head_to_dataclass( + head: Dict[str, Any], head_name: str, args: argparse.Namespace +) -> HeadConfig: + """Convert head dictionary to HeadConfig dataclass.""" + # parser+head args that have no defaults but are required + if (args.train_file is None) and (head.get("train_file", None) is None): + raise ValueError( + "train file is not set in the head config yaml or via command line args" + ) + + return HeadConfig( + head_name=head_name, + train_file=head.get("train_file", args.train_file), + valid_file=head.get("valid_file", args.valid_file), + test_file=head.get("test_file", None), + test_dir=head.get("test_dir", None), + E0s=head.get("E0s", args.E0s), + statistics_file=head.get("statistics_file", args.statistics_file), + valid_fraction=head.get("valid_fraction", args.valid_fraction), + config_type_weights=head.get("config_type_weights", args.config_type_weights), + compute_avg_num_neighbors=head.get( + "compute_avg_num_neighbors", args.compute_avg_num_neighbors + ), + atomic_numbers=head.get("atomic_numbers", args.atomic_numbers), + mean=head.get("mean", args.mean), + std=head.get("std", args.std), + avg_num_neighbors=head.get("avg_num_neighbors", args.avg_num_neighbors), + key_specification=head["key_specification"], + keep_isolated_atoms=head.get("keep_isolated_atoms", args.keep_isolated_atoms), + ) + + +def prepare_default_head(args: argparse.Namespace) -> Dict[str, Any]: + """Prepare a default head from args.""" + return { + "Default": { + "train_file": args.train_file, + "valid_file": args.valid_file, + "test_file": args.test_file, + "test_dir": args.test_dir, + "E0s": args.E0s, + "statistics_file": args.statistics_file, + "key_specification": args.key_specification, + "valid_fraction": args.valid_fraction, + "config_type_weights": args.config_type_weights, + "keep_isolated_atoms": args.keep_isolated_atoms, + } + } + + +def prepare_pt_head( + args: argparse.Namespace, + pt_keyspec: KeySpecification, + foundation_model_num_neighbours: float, +) -> Dict[str, Any]: + """Prepare a pretraining head from args.""" + if ( + args.foundation_model in ["small", "medium", "large"] + or args.pt_train_file == "mp" + ): + logging.info( + "Using foundation model for multiheads finetuning with Materials Project data" + ) + pt_keyspec.update( + info_keys={"energy": "energy", "stress": "stress"}, + arrays_keys={"forces": "forces"}, + ) + pt_head = { + "train_file": "mp", + "E0s": "foundation", + "statistics_file": None, + "key_specification": pt_keyspec, + "avg_num_neighbors": foundation_model_num_neighbours, + "compute_avg_num_neighbors": False, + } + else: + pt_head = { + "train_file": args.pt_train_file, + "valid_file": args.pt_valid_file, + "E0s": "foundation", + "statistics_file": args.statistics_file, + "valid_fraction": args.valid_fraction, + "key_specification": pt_keyspec, + "avg_num_neighbors": foundation_model_num_neighbours, + "keep_isolated_atoms": args.keep_isolated_atoms, + "compute_avg_num_neighbors": False, + } + + return pt_head + + +def assemble_replay_data( + name: str, + args: argparse.Namespace, + head_config_pt: HeadConfig, + tag: str, +) -> SubsetCollection: + """Assemble data for replay fine-tuning.""" + try: + if name == "mp": + checkpoint_url = "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mp_0b/mp_traj_combined.xyz" + elif name == "matpes_pbe": + checkpoint_url = "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/matpes-pbe-replay-data.xyz" + elif name == "matpes_r2scan": + checkpoint_url = "https://github.com/ACEsuit/mace-foundations/releases/download/mace_matpes_0/matpes-r2scan-replay-data.extxyz" + else: + raise ValueError(f"Unknown replay dataset name {name}") + + cache_dir = get_cache_dir() + checkpoint_url_name = "".join( + c for c in os.path.basename(checkpoint_url) if c.isalnum() or c in "_" + ) + cached_dataset_path = f"{cache_dir}/{checkpoint_url_name}" + if not os.path.isfile(cached_dataset_path): + os.makedirs(cache_dir, exist_ok=True) + # download and save to disk + logging.info("Downloading MP structures for finetuning") + _, http_msg = urllib.request.urlretrieve( + checkpoint_url, cached_dataset_path + ) + if "Content-Type: text/html" in http_msg: + raise RuntimeError( + f"Dataset download failed, please check the URL {checkpoint_url}" + ) + logging.info(f"Materials Project dataset to {cached_dataset_path}") + output = f"mp_finetuning-{tag}.xyz" + atomic_numbers = ( + ast.literal_eval(args.atomic_numbers) + if args.atomic_numbers is not None + else None + ) + settings = SelectionSettings( + configs_pt=cached_dataset_path, + output=f"mp_finetuning-{tag}.xyz", + atomic_numbers=atomic_numbers, + num_samples=args.num_samples_pt, + seed=args.seed, + head_pt="pbe_mp", + weight_pt=args.weight_pt_head, + filtering_type=FilteringType(args.filter_type_pt), + subselect=SubselectType(args.subselect_pt), + default_dtype=args.default_dtype, + allow_random_padding=args.allow_random_padding_pt, + ) + select_samples(settings) + head_config_pt.train_file = [output] + collections_mp, _ = get_dataset_from_xyz( + work_dir=args.work_dir, + train_path=output, + valid_path=None, + valid_fraction=args.valid_fraction, + config_type_weights=None, + test_path=None, + seed=args.seed, + key_specification=head_config_pt.key_specification, + head_name="pt_head", + keep_isolated_atoms=args.keep_isolated_atoms, + no_data_ok=( + args.pseudolabel_replay + and args.multiheads_finetuning + and head_config_pt.head_name == "pt_head" + ), + prefix=args.name, + ) + return collections_mp + except Exception as exc: + raise RuntimeError( + "Foundation model replay data or descriptors cached data not found and download failed" + ) from exc + + +def generate_pseudolabels_for_configs( + model: torch.nn.Module, + configs: List[Configuration], + z_table: AtomicNumberTable, + r_max: float, + device: torch.device, + batch_size: int, +) -> List[Configuration]: + """ + Generate pseudolabels for a list of Configuration objects. + + Args: + model: The foundation model + configs: List of Configuration objects + z_table: Atomic number table + r_max: Cutoff radius + device: Device to run model on + batch_size: Batch size for inference + + Returns: + List of Configuration objects with updated properties + """ + + model.eval() + updated_configs = [] + + # Disable gradient tracking for model parameters + original_requires_grad = {} + for param in model.parameters(): + original_requires_grad[param] = param.requires_grad + param.requires_grad = False + + # Process configs in batches + for i in range(0, len(configs), batch_size): + batch_configs = configs[i : i + batch_size] + + try: + # Create temporary AtomicData objects for this batch + batch_data = [ + AtomicData.from_config(config, z_table=z_table, cutoff=r_max) + for config in batch_configs + ] + + # Create a batch for model inference + batch = torch_geometric.Batch.from_data_list(batch_data).to(device) + batch_dict = batch.to_dict() + + # Run model inference with computation of all properties + out = model( + batch_dict, + training=False, + compute_force=True, + compute_virials=True, + compute_stress=True, + ) + + # Process each configuration in the batch + for j, config in enumerate(batch_configs): + # Create a deepcopy to avoid modifying the original + config_copy = deepcopy(config) + + # Ensure properties dict exists + if not hasattr(config_copy, "properties"): + config_copy.properties = {} + + # Update config properties with pseudolabels + if "energy" in out and out["energy"] is not None: + config_copy.properties["energy"] = ( + out["energy"][j].detach().cpu().item() + ) + if "forces" in out and out["forces"] is not None: + # Forces are per atom + node_start = batch.ptr[j].item() + node_end = batch.ptr[j + 1].item() + + config_copy.properties["forces"] = ( + out["forces"][node_start:node_end].detach().cpu().numpy() + ) + if "stress" in out and out["stress"] is not None: + config_copy.properties["stress"] = ( + out["stress"][j].detach().cpu().numpy() + ) + if "virials" in out and out["virials"] is not None: + config_copy.properties["virials"] = ( + out["virials"][j].detach().cpu().numpy() + ) + if "dipole" in out and out["dipole"] is not None: + config_copy.properties["dipole"] = ( + out["dipole"][j].detach().cpu().numpy() + ) + if "charges" in out and out["charges"] is not None: + # Charges are per atom + node_start = batch.ptr[j].item() + node_end = batch.ptr[j + 1].item() + + config_copy.properties["charges"] = ( + out["charges"][node_start:node_end].detach().cpu().numpy() + ) + + updated_configs.append(config_copy) + + except Exception as e: # pylint: disable=broad-except + logging.error( + f"Error generating pseudolabels for batch {i//batch_size + 1}: {str(e)}" + ) + # On error, return the original configs for this batch + updated_configs.extend([deepcopy(config) for config in batch_configs]) + + # Restore original requires_grad settings + for param, requires_grad in original_requires_grad.items(): + param.requires_grad = requires_grad + + logging.info(f"Generated pseudolabels for {len(updated_configs)} configurations") + return updated_configs + + +def apply_pseudolabels_to_pt_head_configs( + foundation_model: torch.nn.Module, + pt_head_config: HeadConfig, + r_max: float, + device: torch.device, + batch_size: int, +) -> bool: + """ + Apply pseudolabels to pt_head configurations using the foundation model. + + Args: + foundation_model: The pre-loaded foundation model + pt_head_config: The HeadConfig object for pt_head + r_max: Cutoff radius + device: Device to run model on + batch_size: Batch size for inference + + Returns: + bool: True if pseudolabeling was successful, False otherwise + """ + + try: + logging.info( + "Applying pseudolabels to pt_head configurations using foundation model" + ) + + foundation_model.to(device) + + # Use foundation model's z_table if available + if hasattr(foundation_model, "atomic_numbers"): + z_table = AtomicNumberTable( + sorted(foundation_model.atomic_numbers.tolist()) + ) + logging.info( + f"Using foundation model's atomic numbers for pseudolabeling: {z_table.zs}" + ) + elif hasattr(pt_head_config, "z_table") and pt_head_config.z_table is not None: + z_table = pt_head_config.z_table + logging.info(f"Using pt_head's z_table for pseudolabeling: {z_table.zs}") + else: + logging.warning("No atomic number table available for pseudolabeling") + return False + + # Process training configurations + if ( + hasattr(pt_head_config.collections, "train") + and pt_head_config.collections.train + ): + logging.info( + f"Generating pseudolabels for {len(pt_head_config.collections.train)} pt_head training configurations" + ) + updated_train_configs = generate_pseudolabels_for_configs( + model=foundation_model, + configs=pt_head_config.collections.train, + z_table=z_table, + r_max=r_max, + device=device, + batch_size=batch_size, + ) + + # Replace the original configurations with updated ones + pt_head_config.collections.train = updated_train_configs + logging.info( + f"Successfully applied pseudolabels to {len(updated_train_configs)} training configurations" + ) + + # Process validation configurations if they exist + if ( + hasattr(pt_head_config.collections, "valid") + and pt_head_config.collections.valid + ): + logging.info( + f"Generating pseudolabels for {len(pt_head_config.collections.valid)} pt_head validation configurations" + ) + updated_valid_configs = generate_pseudolabels_for_configs( + model=foundation_model, + configs=pt_head_config.collections.valid, + z_table=z_table, + r_max=r_max, + device=device, + batch_size=batch_size, + ) + + # Replace the original configurations with updated ones + pt_head_config.collections.valid = updated_valid_configs + logging.info( + f"Successfully applied pseudolabels to {len(updated_valid_configs)} validation configurations" + ) + + return True + + except Exception as e: # pylint: disable=broad-except + logging.error(f"Error applying pseudolabels: {str(e)}") + return False diff --git a/models/mace/mace/tools/run_train_utils.py b/models/mace/mace/tools/run_train_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce37e0edc345f7367eac550af822e6ee03c7e9f4 --- /dev/null +++ b/models/mace/mace/tools/run_train_utils.py @@ -0,0 +1,217 @@ +import logging +import os +from pathlib import Path +from typing import Any, List, Optional, Union + +import torch +from torch.utils.data import ConcatDataset + +from mace import data +from mace.tools.scripts_utils import check_path_ase_read +from mace.tools.torch_geometric.dataset import Dataset +from mace.tools.utils import AtomicNumberTable + + +def normalize_file_paths(file_paths: Union[str, List[str]]) -> List[str]: + """ + Normalize file paths to a list format. + + Args: + file_paths: Either a string or a list of strings representing file paths + + Returns: + A list of file paths + """ + if isinstance(file_paths, str): + return [file_paths] + if isinstance(file_paths, list): + return file_paths + raise ValueError(f"Unexpected file paths format: {type(file_paths)}") + + +def load_dataset_for_path( + file_path: Union[str, Path, List[str]], + r_max: float, + z_table: AtomicNumberTable, + heads: List[str], + head_config: Any, + collection: Optional[Any] = None, +) -> Union[Dataset, List]: + """ + Load a dataset from a file path based on its format. + + Args: + file_path: Path to the dataset file + r_max: Cutoff radius + z_table: Atomic number table + heads: List of head names + head_name: Current head name + **kwargs: Additional arguments + + Returns: + Loaded dataset + """ + if isinstance(file_path, list): + if len(file_path) == 1: + file_path = file_path[0] + if isinstance(file_path, list): + is_ase_readable = all(check_path_ase_read(p) for p in file_path) + if not is_ase_readable: + raise ValueError( + "Not all paths in the list are ASE readable, not supported" + ) + if isinstance(file_path, str): + is_ase_readable = check_path_ase_read(file_path) + + if is_ase_readable: + assert ( + collection is not None + ), "Collection must be provided for ASE readable files" + return [ + data.AtomicData.from_config( + config, z_table=z_table, cutoff=r_max, heads=heads + ) + for config in collection + ] + + filepath = Path(file_path) + if filepath.is_dir(): + + if filepath.name.endswith("_lmdb") or any( + f.endswith(".lmdb") or f.endswith(".aselmdb") for f in os.listdir(filepath) + ): + logging.info(f"Loading LMDB dataset from {file_path}") + return data.LMDBDataset( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + + h5_files = list(filepath.glob("*.h5")) + list(filepath.glob("*.hdf5")) + if h5_files: + logging.info(f"Loading HDF5 dataset from directory {file_path}") + try: + return data.dataset_from_sharded_hdf5( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + except Exception as e: + logging.error(f"Error loading sharded HDF5 dataset: {e}") + raise + + if "lmdb" in str(filepath).lower() or "aselmdb" in str(filepath).lower(): + logging.info(f"Loading LMDB dataset based on path name: {file_path}") + return data.LMDBDataset( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + + logging.info(f"Attempting to load directory as HDF5 dataset: {file_path}") + try: + return data.dataset_from_sharded_hdf5( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + except Exception as e: + logging.error(f"Error loading as sharded HDF5: {e}") + raise + + suffix = filepath.suffix.lower() + if suffix in (".h5", ".hdf5"): + logging.info(f"Loading single HDF5 file: {file_path}") + return data.HDF5Dataset( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + + if suffix in (".lmdb", ".aselmdb", ".db"): + logging.info(f"Loading single LMDB file: {file_path}") + return data.LMDBDataset( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + + logging.info(f"Attempting to load as LMDB: {file_path}") + return data.LMDBDataset( + file_path, + r_max=r_max, + z_table=z_table, + heads=heads, + head=head_config.head_name, + ) + + +def combine_datasets(datasets, head_name): + """ + Combine multiple datasets which might be of different types. + + Args: + datasets: List of datasets (can be mixed types) + head_name: Name of the current head + + Returns: + Combined dataset + """ + if not datasets: + return [] + + if all(isinstance(ds, list) for ds in datasets): + logging.info(f"Combining {len(datasets)} list datasets for head '{head_name}'") + return [item for sublist in datasets for item in sublist] + + if all(not isinstance(ds, list) for ds in datasets): + logging.info( + f"Combining {len(datasets)} Dataset objects for head '{head_name}'" + ) + return ConcatDataset(datasets) if len(datasets) > 1 else datasets[0] + + logging.info(f"Converting mixed dataset types for head '{head_name}'") + + try: + all_items = [] + for ds in datasets: + if isinstance(ds, list): + all_items.extend(ds) + else: + all_items.extend([ds[i] for i in range(len(ds))]) + return all_items + except Exception as e: # pylint: disable=W0703 + logging.warning(f"Failed to convert mixed datasets to list: {e}") + + try: + dataset_objects = [] + for ds in datasets: + if isinstance(ds, list): + from torch.utils.data import TensorDataset + + # Convert list to a Dataset + dataset_objects.append( + TensorDataset(*[torch.tensor([i]) for i in range(len(ds))]) + ) + else: + dataset_objects.append(ds) + return ConcatDataset(dataset_objects) + except Exception as e: # pylint: disable=W0703 + logging.warning(f"Failed to convert mixed datasets to ConcatDataset: {e}") + + logging.warning( + "Could not combine datasets of different types. Using only the first dataset." + ) + return datasets[0] diff --git a/models/mace/mace/tools/scatter.py b/models/mace/mace/tools/scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1139a999e5d741b0b57f500d1d349a10092db9 --- /dev/null +++ b/models/mace/mace/tools/scatter.py @@ -0,0 +1,112 @@ +"""basic scatter_sum operations from torch_scatter from +https://github.com/mir-group/pytorch_runstats/blob/main/torch_runstats/scatter_sum.py +Using code from https://github.com/rusty1s/pytorch_scatter, but cut down to avoid a dependency. +PyTorch plans to move these features into the main repo, but until then, +to make installation simpler, we need this pure python set of wrappers +that don't require installing PyTorch C++ extensions. +See https://github.com/pytorch/pytorch/issues/63780. +""" + +from typing import Optional + +import torch + + +def _broadcast(src: torch.Tensor, other: torch.Tensor, dim: int): + if dim < 0: + dim = other.dim() + dim + if src.dim() == 1: + for _ in range(0, dim): + src = src.unsqueeze(0) + for _ in range(src.dim(), other.dim()): + src = src.unsqueeze(-1) + src = src.expand_as(other) + return src + + +def scatter_sum( + src: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: Optional[torch.Tensor] = None, + dim_size: Optional[int] = None, + reduce: str = "sum", +) -> torch.Tensor: + assert reduce == "sum" # for now, TODO + index = _broadcast(index, src, dim) + if out is None: + size = list(src.size()) + if dim_size is not None: + size[dim] = dim_size + elif index.numel() == 0: + size[dim] = 0 + else: + size[dim] = int(index.max()) + 1 + out = torch.zeros(size, dtype=src.dtype, device=src.device) + return out.scatter_add_(dim, index, src) + else: + return out.scatter_add_(dim, index, src) + + +def scatter_std( + src: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: Optional[torch.Tensor] = None, + dim_size: Optional[int] = None, + unbiased: bool = True, +) -> torch.Tensor: + if out is not None: + dim_size = out.size(dim) + + if dim < 0: + dim = src.dim() + dim + + count_dim = dim + if index.dim() <= dim: + count_dim = index.dim() - 1 + + ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) + count = scatter_sum(ones, index, count_dim, dim_size=dim_size) + + index = _broadcast(index, src, dim) + tmp = scatter_sum(src, index, dim, dim_size=dim_size) + count = _broadcast(count, tmp, dim).clamp(1) + mean = tmp.div(count) + + var = src - mean.gather(dim, index) + var = var * var + out = scatter_sum(var, index, dim, out, dim_size) + + if unbiased: + count = count.sub(1).clamp_(1) + out = out.div(count + 1e-6).sqrt() + + return out + + +def scatter_mean( + src: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: Optional[torch.Tensor] = None, + dim_size: Optional[int] = None, +) -> torch.Tensor: + out = scatter_sum(src, index, dim, out, dim_size) + dim_size = out.size(dim) + + index_dim = dim + if index_dim < 0: + index_dim = index_dim + src.dim() + if index.dim() <= index_dim: + index_dim = index.dim() - 1 + + ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) + count = scatter_sum(ones, index, index_dim, None, dim_size) + count[count < 1] = 1 + count = _broadcast(count, out, dim) + if out.is_floating_point(): + out.true_divide_(count) + else: + out.div_(count, rounding_mode="floor") + return out diff --git a/models/mace/mace/tools/scripts_utils.py b/models/mace/mace/tools/scripts_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20d368ce8d73deda33af69f02f7d893df08140b3 --- /dev/null +++ b/models/mace/mace/tools/scripts_utils.py @@ -0,0 +1,1011 @@ +########################################################################################### +# Training utils +# Authors: David Kovacs, Ilyes Batatia +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import argparse +import ast +import dataclasses +import json +import logging +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +import torch.distributed +from e3nn import o3 +from torch.optim.swa_utils import SWALR, AveragedModel + +from mace import data, modules, tools +from mace.data import KeySpecification +from mace.tools.train import SWAContainer + + +@dataclasses.dataclass +class SubsetCollection: + train: data.Configurations + valid: data.Configurations + tests: List[Tuple[str, data.Configurations]] + + +def log_dataset_contents(dataset: data.Configurations, dataset_name: str) -> None: + log_string = f"{dataset_name} [" + for prop_name in dataset[0].properties.keys(): + if prop_name == "dipole": + log_string += f"{prop_name} components: {int(np.sum([np.sum(config.property_weights[prop_name]) for config in dataset]))}, " + else: + log_string += f"{prop_name}: {int(np.sum([config.property_weights[prop_name] for config in dataset]))}, " + log_string = log_string[:-2] + "]" + logging.info(log_string) + + +def get_dataset_from_xyz( + work_dir: str, + train_path: Union[str, List[str]], + valid_path: Optional[Union[str, List[str]]], + valid_fraction: float, + key_specification: KeySpecification, + config_type_weights: Optional[Dict] = None, + test_path: Optional[Union[str, List[str]]] = None, + seed: int = 1234, + keep_isolated_atoms: bool = False, + head_name: str = "Default", + no_data_ok: bool = False, + prefix: Optional[str] = None, +) -> Tuple[SubsetCollection, Optional[Dict[int, float]]]: + """ + Load training, validation, and test datasets from xyz files. + + Args: + work_dir: Working directory for saving split information + train_path: Path or list of paths to training xyz files + valid_path: Path or list of paths to validation xyz files + valid_fraction: Fraction of training data to use for validation if valid_path is None + config_type_weights: Dictionary of weights for each configuration type + key_specification: KeySpecification object for loading data + test_path: Path or list of paths to test xyz files + seed: Random seed for train/validation split + prefix: Optional filename prefix (e.g., potential name) for saved valid indices + keep_isolated_atoms: Whether to keep isolated atoms in the dataset + head_name: Name of the head for multi-head models + no_data_ok: accept files that have no energy/force/stress data + + Returns: + Tuple containing: + - SubsetCollection with train, valid, and test configurations + - Dictionary of atomic energies (or None if not available) + """ + # Convert input paths to lists if they're not already + train_paths = [train_path] if isinstance(train_path, str) else train_path + valid_paths = ( + [valid_path] + if isinstance(valid_path, str) and valid_path is not None + else valid_path + ) + test_paths = ( + [test_path] + if isinstance(test_path, str) and test_path is not None + else test_path + ) + + # Initialize collections and atomic energies tracking + all_train_configs = [] + all_valid_configs = [] + all_test_configs = [] + + # For tracking atomic energies across files + atomic_energies_values = {} # Element Z -> list of energy values + atomic_energies_counts = {} # Element Z -> count of files with this element + + # Process training files + for i, path in enumerate(train_paths): + logging.debug(f"Loading training file: {path}") + ae_dict, train_configs = data.load_from_xyz( + file_path=path, + config_type_weights=config_type_weights, + key_specification=key_specification, + extract_atomic_energies=True, # Extract from all files to average + keep_isolated_atoms=keep_isolated_atoms, + head_name=head_name, + no_data_ok=no_data_ok, + ) + all_train_configs.extend(train_configs) + + # Track atomic energies from each file for averaging + if ae_dict: + for element, energy in ae_dict.items(): + if element not in atomic_energies_values: + atomic_energies_values[element] = [] + atomic_energies_counts[element] = 0 + + atomic_energies_values[element].append(energy) + atomic_energies_counts[element] += 1 + + log_dataset_contents(train_configs, f"Training set {i+1}/{len(train_paths)}") + + # Log total training set info + log_dataset_contents(all_train_configs, "Total Training set") + + # Process validation files if provided + if valid_paths: + for i, path in enumerate(valid_paths): + _, valid_configs = data.load_from_xyz( + file_path=path, + config_type_weights=config_type_weights, + key_specification=key_specification, + extract_atomic_energies=False, + head_name=head_name, + ) + all_valid_configs.extend(valid_configs) + log_dataset_contents( + valid_configs, f"Validation set {i+1}/{len(valid_paths)}" + ) + + # Log total validation set info + log_dataset_contents(all_valid_configs, "Total Validation set") + train_configs = all_train_configs + valid_configs = all_valid_configs + else: + # Split training data if no validation files are provided + logging.info("No validation set provided, splitting training data instead.") + train_configs, valid_configs = data.random_train_valid_split( + all_train_configs, valid_fraction, seed, work_dir, prefix + ) + log_dataset_contents(train_configs, "Random Split Training set") + log_dataset_contents(valid_configs, "Random Split Validation set") + + test_configs_by_type = [] + if test_paths: + for i, path in enumerate(test_paths): + _, test_configs = data.load_from_xyz( + file_path=path, + config_type_weights=config_type_weights, + key_specification=key_specification, + extract_atomic_energies=False, + head_name=head_name, + ) + all_test_configs.extend(test_configs) + + log_dataset_contents(test_configs, f"Test set {i+1}/{len(test_paths)}") + + # Create list of tuples (config_type, list(Atoms)) + test_configs_by_type = data.test_config_types(all_test_configs) + log_dataset_contents(all_test_configs, "Total Test set") + + atomic_energies_dict = {} + for element, values in atomic_energies_values.items(): + if atomic_energies_counts[element] > 1: + atomic_energies_dict[element] = sum(values) / len(values) + logging.debug( + f"Element {element} found in {atomic_energies_counts[element]} files. Using average E0: {atomic_energies_dict[element]:.6f} eV" + ) + else: + atomic_energies_dict[element] = values[0] + logging.debug( + f"Element {element} found in 1 file. Using E0: {atomic_energies_dict[element]:.6f} eV" + ) + + return ( + SubsetCollection( + train=train_configs, valid=valid_configs, tests=test_configs_by_type + ), + atomic_energies_dict if atomic_energies_dict else None, + ) + + +def get_config_type_weights(ct_weights): + """ + Get config type weights from command line argument + """ + try: + config_type_weights = ast.literal_eval(ct_weights) + assert isinstance(config_type_weights, dict) + except Exception as e: # pylint: disable=W0703 + logging.warning( + f"Config type weights not specified correctly ({e}), using Default" + ) + config_type_weights = {"Default": 1.0} + return config_type_weights + + +def print_git_commit(): + try: + import git + + repo = git.Repo(search_parent_directories=True) + commit = repo.head.commit.hexsha + logging.debug(f"Current Git commit: {commit}") + return commit + except Exception as e: # pylint: disable=W0703 + logging.debug(f"Error accessing Git repository: {e}") + return "None" + + +def extract_config_mace_model(model: torch.nn.Module) -> Dict[str, Any]: + if model.__class__.__name__ not in ["ScaleShiftMACE", "MACELES"]: + return {"error": "Model is not a ScaleShiftMACE or MACELES model"} + + def radial_to_name(radial_type): + if radial_type == "BesselBasis": + return "bessel" + if radial_type == "GaussianBasis": + return "gaussian" + if radial_type == "ChebychevBasis": + return "chebyshev" + return radial_type + + def radial_to_transform(radial): + if not hasattr(radial, "distance_transform"): + return None + if radial.distance_transform.__class__.__name__ == "AgnesiTransform": + return "Agnesi" + if radial.distance_transform.__class__.__name__ == "SoftTransform": + return "Soft" + return radial.distance_transform.__class__.__name__ + + scale = model.scale_shift.scale + shift = model.scale_shift.shift + heads = model.heads if hasattr(model, "heads") else ["default"] + model_mlp_irreps = ( + o3.Irreps(str(model.readouts[-1].hidden_irreps)) + if model.num_interactions.item() > 1 + else 1 + ) + try: + correlation = ( + len(model.products[0].symmetric_contractions.contractions[0].weights) + 1 + ) + except AttributeError: + correlation = model.products[0].symmetric_contractions.contraction_degree + config = { + "r_max": model.r_max.item(), + "num_bessel": len(model.radial_embedding.bessel_fn.bessel_weights), + "num_polynomial_cutoff": model.radial_embedding.cutoff_fn.p.item(), + "max_ell": model.spherical_harmonics._lmax, # pylint: disable=protected-access + "interaction_cls": model.interactions[-1].__class__, + "interaction_cls_first": model.interactions[0].__class__, + "num_interactions": model.num_interactions.item(), + "num_elements": len(model.atomic_numbers), + "hidden_irreps": o3.Irreps(str(model.products[0].linear.irreps_out)), + "edge_irreps": model.edge_irreps if hasattr(model, "edge_irreps") else None, + "MLP_irreps": ( + o3.Irreps(f"{model_mlp_irreps.count((0, 1)) // len(heads)}x0e") + if model.num_interactions.item() > 1 + else 1 + ), + "gate": ( + model.readouts[-1] # pylint: disable=protected-access + .non_linearity._modules["acts"][0] + .f + if model.num_interactions.item() > 1 + else None + ), + "use_reduced_cg": ( + model.use_reduced_cg if hasattr(model, "use_reduced_cg") else False + ), + "use_so3": model.use_so3 if hasattr(model, "use_so3") else False, + "use_edge_irreps_first": ( + model.use_edge_irreps_first + if hasattr(model, "use_edge_irreps_first") + else False + ), + "use_agnostic_product": ( + model.use_agnostic_product + if hasattr(model, "use_agnostic_product") + else False + ), + "use_last_readout_only": ( + model.use_last_readout_only + if hasattr(model, "use_last_readout_only") + else False + ), + "use_embedding_readout": (hasattr(model, "embedding_readout")), + "readout_cls": model.readouts[-1].__class__, + "cueq_config": model.cueq_config if hasattr(model, "cueq_config") else None, + "atomic_energies": model.atomic_energies_fn.atomic_energies.cpu().numpy(), + "avg_num_neighbors": model.interactions[0].avg_num_neighbors, + "atomic_numbers": model.atomic_numbers, + "correlation": correlation, + "radial_type": radial_to_name( + model.radial_embedding.bessel_fn.__class__.__name__ + ), + "embedding_specs": ( + model.embedding_specs if hasattr(model, "embedding_specs") else None + ), + "apply_cutoff": model.apply_cutoff if hasattr(model, "apply_cutoff") else True, + "radial_MLP": extract_radial_MLP(model), + "pair_repulsion": hasattr(model, "pair_repulsion_fn"), + "distance_transform": radial_to_transform(model.radial_embedding), + "atomic_inter_scale": scale.cpu().numpy(), + "atomic_inter_shift": shift.cpu().numpy(), + "heads": heads, + } + if model.__class__.__name__ == "AtomicDielectricMACE": + config["use_polarizability"] = model.use_polarizability + config["only_dipole"] = False # model.only_dipole + config["gate"] = torch.nn.functional.silu + return config + + +def extract_load(f: str, map_location: str = "cpu") -> torch.nn.Module: + return extract_model( + torch.load(f=f, map_location=map_location), map_location=map_location + ) + + +def extract_radial_MLP(model: torch.nn.Module) -> List[int]: + try: + return model.interactions[0].conv_tp_weights.hs[1:-1] + except AttributeError: + try: + return [ + int( + model.interactions[0] + .conv_tp_weights.net[k] + .__dict__["normalized_shape"][0] + ) + for k in range(1, len(model.interactions[0].conv_tp_weights.net), 3) + ] + except AttributeError: + return [] + + +def remove_pt_head( + model: torch.nn.Module, head_to_keep: Optional[str] = None +) -> torch.nn.Module: + """Converts a multihead MACE model to a single head model by removing the pretraining head. + + Args: + model (ScaleShiftMACE): The multihead MACE model to convert + head_to_keep (Optional[str]): The name of the head to keep. If None, keeps the first non-PT head. + + Returns: + ScaleShiftMACE: A new MACE model with only the specified head + + Raises: + ValueError: If the model is not a multihead model or if the specified head is not found + """ + if not hasattr(model, "heads") or len(model.heads) <= 1: + raise ValueError("Model must be a multihead model with more than one head") + + # Get index of head to keep + if head_to_keep is None: + # Find first non-PT head + try: + head_idx = next(i for i, h in enumerate(model.heads) if h != "pt_head") + except StopIteration as e: + raise ValueError("No non-PT head found in model") from e + else: + try: + head_idx = model.heads.index(head_to_keep) + except ValueError as e: + raise ValueError(f"Head {head_to_keep} not found in model") from e + + # Extract config and modify for single head + model_config = extract_config_mace_model(model) + model_config["heads"] = [model.heads[head_idx]] + model_config["atomic_energies"] = ( + model.atomic_energies_fn.atomic_energies[head_idx] + .unsqueeze(0) + .detach() + .cpu() + .numpy() + ) + model_config["atomic_inter_scale"] = model.scale_shift.scale[head_idx].item() + model_config["atomic_inter_shift"] = model.scale_shift.shift[head_idx].item() + mlp_count_irreps = model_config["MLP_irreps"].count((0, 1)) + + new_model = model.__class__(**model_config) + state_dict = model.state_dict() + new_state_dict = {} + + for name, param in state_dict.items(): + if "atomic_energies" in name: + new_state_dict[name] = param[head_idx : head_idx + 1] + elif "scale" in name or "shift" in name: + new_state_dict[name] = param[head_idx : head_idx + 1] + elif "embedding_readout.linear" in name: + new_state_dict[name] = param.reshape(-1, len(model.heads))[ + :, head_idx + ].flatten() + + elif "readouts" in name: + channels_per_head = param.shape[0] // len(model.heads) + start_idx = head_idx * channels_per_head + end_idx = start_idx + channels_per_head + if "linear_2.weight" in name: + end_idx = start_idx + channels_per_head // 2 + if "linear.weight" in name: + new_state_dict[name] = param.reshape(-1, len(model.heads))[ + :, head_idx + ].flatten() + elif "linear_1.weight" in name: + new_state_dict[name] = param.reshape( + -1, len(model.heads), mlp_count_irreps + )[:, head_idx, :].flatten() + elif "linear_1.bias" in name: + if param.shape == torch.Size([0]): + continue + new_state_dict[name] = param.reshape( + len(model.heads), mlp_count_irreps + )[head_idx, :].flatten() + elif "linear_mid.weight" in name: + new_state_dict[name] = param.reshape( + len(model.heads), + mlp_count_irreps, + len(model.heads), + mlp_count_irreps, + )[head_idx, :, head_idx, :].flatten() / (len(model.heads) ** 0.5) + elif "linear_mid.bias" in name: + if param.shape == torch.Size([0]): + continue + new_state_dict[name] = param.reshape( + len(model.heads), + mlp_count_irreps, + )[head_idx, :].flatten() + elif "linear_2.weight" in name: + new_state_dict[name] = param.reshape( + len(model.heads), -1, len(model.heads) + )[head_idx, :, head_idx].flatten() / (len(model.heads) ** 0.5) + elif "linear_2.bias" in name: + if param.shape == torch.Size([0]): + continue + new_state_dict[name] = param[head_idx].flatten() + else: + new_state_dict[name] = param[start_idx:end_idx] + + else: + new_state_dict[name] = param + + # Load state dict into new model + new_model.load_state_dict(new_state_dict, strict=False) + + return new_model + + +def extract_model(model: torch.nn.Module, map_location: str = "cpu") -> torch.nn.Module: + model_copy = model.__class__(**extract_config_mace_model(model)) + model_copy.load_state_dict(model.state_dict()) + return model_copy.to(map_location) + + +def convert_to_json_format(dict_input): + for key, value in dict_input.items(): + if isinstance(value, (np.ndarray, torch.Tensor)): + dict_input[key] = value.tolist() + # # check if the value is a class and convert it to a string + elif hasattr(value, "__class__"): + dict_input[key] = str(value) + return dict_input + + +def convert_from_json_format(dict_input): + dict_output = dict_input.copy() + if ( + dict_input["interaction_cls"] + == "" + ): + dict_output["interaction_cls"] = ( + modules.blocks.RealAgnosticResidualInteractionBlock + ) + if ( + dict_input["interaction_cls"] + == "" + ): + dict_output["interaction_cls"] = modules.blocks.RealAgnosticInteractionBlock + if ( + dict_input["interaction_cls_first"] + == "" + ): + dict_output["interaction_cls_first"] = ( + modules.blocks.RealAgnosticResidualInteractionBlock + ) + if ( + dict_input["interaction_cls_first"] + == "" + ): + dict_output["interaction_cls_first"] = ( + modules.blocks.RealAgnosticInteractionBlock + ) + dict_output["r_max"] = float(dict_input["r_max"]) + dict_output["num_bessel"] = int(dict_input["num_bessel"]) + dict_output["num_polynomial_cutoff"] = float(dict_input["num_polynomial_cutoff"]) + dict_output["max_ell"] = int(dict_input["max_ell"]) + dict_output["num_interactions"] = int(dict_input["num_interactions"]) + dict_output["num_elements"] = int(dict_input["num_elements"]) + dict_output["hidden_irreps"] = o3.Irreps(dict_input["hidden_irreps"]) + dict_output["MLP_irreps"] = o3.Irreps(dict_input["MLP_irreps"]) + dict_output["avg_num_neighbors"] = float(dict_input["avg_num_neighbors"]) + dict_output["gate"] = torch.nn.functional.silu + dict_output["atomic_energies"] = np.array(dict_input["atomic_energies"]) + dict_output["atomic_numbers"] = dict_input["atomic_numbers"] + dict_output["correlation"] = int(dict_input["correlation"]) + dict_output["radial_type"] = dict_input["radial_type"] + dict_output["radial_MLP"] = ast.literal_eval(dict_input["radial_MLP"]) + dict_output["pair_repulsion"] = ast.literal_eval(dict_input["pair_repulsion"]) + dict_output["distance_transform"] = dict_input["distance_transform"] + dict_output["atomic_inter_scale"] = float(dict_input["atomic_inter_scale"]) + dict_output["atomic_inter_shift"] = float(dict_input["atomic_inter_shift"]) + + return dict_output + + +def load_from_json(f: str, map_location: str = "cpu") -> torch.nn.Module: + extra_files_extract = {"commit.txt": None, "config.json": None} + model_jit_load = torch.jit.load( + f, _extra_files=extra_files_extract, map_location=map_location + ) + model_load_yaml = modules.ScaleShiftMACE( + **convert_from_json_format(json.loads(extra_files_extract["config.json"])) + ) + model_load_yaml.load_state_dict(model_jit_load.state_dict()) + return model_load_yaml.to(map_location) + + +def get_atomic_energies(E0s, train_collection, z_table) -> dict: + if E0s is not None: + logging.info( + "Isolated Atomic Energies (E0s) not in training file, using command line argument" + ) + if E0s.lower() == "average": + logging.info( + "Computing average Atomic Energies using least squares regression" + ) + # catch if colections.train not defined above + try: + assert train_collection is not None + atomic_energies_dict = data.compute_average_E0s( + train_collection, z_table + ) + except Exception as e: + raise RuntimeError( + f"Could not compute average E0s if no training xyz given, error {e} occured" + ) from e + else: + if E0s.endswith(".json"): + logging.info(f"Loading atomic energies from {E0s}") + with open(E0s, "r", encoding="utf-8") as f: + atomic_energies_dict = json.load(f) + atomic_energies_dict = { + int(key): value for key, value in atomic_energies_dict.items() + } + else: + try: + atomic_energies_eval = ast.literal_eval(E0s) + if not all( + isinstance(value, dict) + for value in atomic_energies_eval.values() + ): + atomic_energies_dict = atomic_energies_eval + else: + atomic_energies_dict = atomic_energies_eval + assert isinstance(atomic_energies_dict, dict) + except Exception as e: + raise RuntimeError( + f"E0s specified invalidly, error {e} occured" + ) from e + else: + raise RuntimeError( + "E0s not found in training file and not specified in command line" + ) + return atomic_energies_dict + + +def get_avg_num_neighbors(head_configs, args, train_loader, device): + if all(head_config.compute_avg_num_neighbors for head_config in head_configs): + logging.info("Computing average number of neighbors") + avg_num_neighbors = modules.compute_avg_num_neighbors(train_loader) + if args.distributed: + num_graphs = torch.tensor(len(train_loader.dataset)).to(device) + num_neighbors = num_graphs * torch.tensor(avg_num_neighbors).to(device) + torch.distributed.all_reduce(num_graphs, op=torch.distributed.ReduceOp.SUM) + torch.distributed.all_reduce( + num_neighbors, op=torch.distributed.ReduceOp.SUM + ) + avg_num_neighbors_out = (num_neighbors / num_graphs).item() + else: + avg_num_neighbors_out = avg_num_neighbors + else: + assert any( + head_config.avg_num_neighbors is not None for head_config in head_configs + ), "Average number of neighbors must be provided in the configuration" + avg_num_neighbors_out = max( + head_config.avg_num_neighbors + for head_config in head_configs + if head_config.avg_num_neighbors is not None + ) + if avg_num_neighbors_out < 2 or avg_num_neighbors_out > 100: + logging.warning( + f"Unusual average number of neighbors: {avg_num_neighbors_out:.1f}" + ) + else: + logging.info(f"Average number of neighbors: {avg_num_neighbors_out}") + return avg_num_neighbors_out + + +def get_loss_fn( + args: argparse.Namespace, + dipole_only: bool, + compute_dipole: bool, +) -> torch.nn.Module: + if args.loss == "weighted": # NOTE default loss + + loss_fn = modules.WeightedEnergyForcesLoss( + energy_weight=args.energy_weight, forces_weight=args.forces_weight + ) + + elif args.loss == "ours_mae": # NOTE Added our MAE loss + # NOTE No argument means both energy and force weights are set to 1 + loss_fn = modules.WeightedEnergyForcesMAELoss(energy_weight=args.energy_weight, forces_weight=args.forces_weight) + + + elif args.loss == "forces_only": + loss_fn = modules.WeightedForcesLoss(forces_weight=args.forces_weight) + + + elif args.loss == "virials": + loss_fn = modules.WeightedEnergyForcesVirialsLoss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + virials_weight=args.virials_weight, + ) + elif args.loss == "stress": + loss_fn = modules.WeightedEnergyForcesStressLoss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + stress_weight=args.stress_weight, + ) + elif args.loss == "huber": + loss_fn = modules.WeightedHuberEnergyForcesStressLoss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + stress_weight=args.stress_weight, + huber_delta=args.huber_delta, + ) + elif args.loss == "universal": + loss_fn = modules.UniversalLoss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + stress_weight=args.stress_weight, + huber_delta=args.huber_delta, + ) + elif args.loss == "l1l2energyforces": + loss_fn = modules.WeightedEnergyForcesL1L2Loss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + ) + elif args.loss == "dipole": + assert ( + dipole_only is True + ), "dipole loss can only be used with AtomicDipolesMACE model" + loss_fn = modules.DipoleSingleLoss( + dipole_weight=args.dipole_weight, + ) + elif args.loss == "dipole_polar": + loss_fn = modules.DipolePolarLoss( + dipole_weight=args.dipole_weight, + polarizability_weight=args.polarizability_weight, + ) + elif args.loss == "energy_forces_dipole": + assert dipole_only is False and compute_dipole is True + loss_fn = modules.WeightedEnergyForcesDipoleLoss( + energy_weight=args.energy_weight, + forces_weight=args.forces_weight, + dipole_weight=args.dipole_weight, + ) + else: + loss_fn = modules.WeightedEnergyForcesLoss(energy_weight=1.0, forces_weight=1.0) + return loss_fn + + +def get_swa( + args: argparse.Namespace, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + swas: List[bool], + dipole_only: bool = False, +): + assert dipole_only is False, "Stage Two for dipole fitting not implemented" + swas.append(True) + if args.start_swa is None: + args.start_swa = max(1, args.max_num_epochs // 4 * 3) + else: + if args.start_swa >= args.max_num_epochs: + logging.warning( + f"Start Stage Two must be less than max_num_epochs, got {args.start_swa} > {args.max_num_epochs}" + ) + swas[-1] = False + if args.loss == "forces_only": + raise ValueError("Can not select Stage Two with forces only loss.") + if args.loss == "virials": + loss_fn_energy = modules.WeightedEnergyForcesVirialsLoss( + energy_weight=args.swa_energy_weight, + forces_weight=args.swa_forces_weight, + virials_weight=args.swa_virials_weight, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight}, virials_weight: {args.swa_virials_weight} and learning rate : {args.swa_lr}" + ) + elif args.loss == "stress": + loss_fn_energy = modules.WeightedEnergyForcesStressLoss( + energy_weight=args.swa_energy_weight, + forces_weight=args.swa_forces_weight, + stress_weight=args.swa_stress_weight, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight}, stress weight : {args.swa_stress_weight} and learning rate : {args.swa_lr}" + ) + elif args.loss == "dipole_polar": + loss_fn_energy = modules.DipolePolarLoss( + dipole_weight=args.swa_dipole_weight, + polarizability_weight=args.swa_polarizability_weight, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, dipole weight : {args.swa_dipole_weight}, polarizability weight : {args.swa_polarizability_weight}, and learning rate : {args.swa_lr}" + ) + elif args.loss == "energy_forces_dipole": + loss_fn_energy = modules.WeightedEnergyForcesDipoleLoss( + args.swa_energy_weight, + forces_weight=args.swa_forces_weight, + dipole_weight=args.swa_dipole_weight, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, with energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight}, dipole weight : {args.swa_dipole_weight} and learning rate : {args.swa_lr}" + ) + elif args.loss == "universal": + loss_fn_energy = modules.UniversalLoss( + energy_weight=args.swa_energy_weight, + forces_weight=args.swa_forces_weight, + stress_weight=args.swa_stress_weight, + huber_delta=args.huber_delta, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, with energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight}, stress weight : {args.swa_stress_weight} and learning rate : {args.swa_lr}" + ) + else: + loss_fn_energy = modules.WeightedEnergyForcesLoss( + energy_weight=args.swa_energy_weight, + forces_weight=args.swa_forces_weight, + ) + logging.info( + f"Stage Two (after {args.start_swa} epochs) with loss function: {loss_fn_energy}, with energy weight : {args.swa_energy_weight}, forces weight : {args.swa_forces_weight} and learning rate : {args.swa_lr}" + ) + swa = SWAContainer( + model=AveragedModel(model), + scheduler=SWALR( + optimizer=optimizer, + swa_lr=args.swa_lr, + anneal_epochs=1, + anneal_strategy="linear", + ), + start=args.start_swa, + loss_fn=loss_fn_energy, + ) + return swa, swas + + +def get_params_options( + args: argparse.Namespace, model: torch.nn.Module +) -> Dict[str, Any]: + decay_interactions = {} + no_decay_interactions = {} + for name, param in model.interactions.named_parameters(): + if "linear.weight" in name or "skip_tp_full.weight" in name: + decay_interactions[name] = param + else: + no_decay_interactions[name] = param + + param_options = dict( + params=[ + { + "name": "embedding", + "params": model.node_embedding.parameters(), + "weight_decay": 0.0, + }, + { + "name": "interactions_decay", + "params": list(decay_interactions.values()), + "weight_decay": args.weight_decay, + }, + { + "name": "interactions_no_decay", + "params": list(no_decay_interactions.values()), + "weight_decay": 0.0, + }, + { + "name": "products", + "params": model.products.parameters(), + "weight_decay": args.weight_decay, + }, + { + "name": "readouts", + "params": model.readouts.parameters(), + "weight_decay": 0.0, + }, + ], + lr=args.lr, + amsgrad=args.amsgrad, + betas=(args.beta, 0.999), + ) + if hasattr(model, "joint_embedding") and model.joint_embedding is not None: + param_options["params"].append( + { + "name": "joint_embedding", + "params": model.joint_embedding.parameters(), + "weight_decay": 0.0, + } + ) + if hasattr(model, "embedding_readout") and model.embedding_readout is not None: + param_options["params"].append( + { + "name": "embedding_readout", + "params": model.embedding_readout.parameters(), + "weight_decay": 0.0, + } + ) + if hasattr(model, "les_readouts") and model.les_readouts is not None: + param_options["params"].append( + { + "name": "les_readouts", + "params": model.les_readouts.parameters(), + "weight_decay": 0.0, + } + ) + return param_options + + +def get_optimizer( + args: argparse.Namespace, param_options: Dict[str, Any] +) -> torch.optim.Optimizer: + if args.optimizer == "adamw": + optimizer = torch.optim.AdamW(**param_options) + elif args.optimizer == "schedulefree": + try: + from schedulefree import adamw_schedulefree + except ImportError as exc: + raise ImportError( + "`schedulefree` is not installed. Please install it via `pip install schedulefree` or `pip install mace-torch[schedulefree]`" + ) from exc + _param_options = {k: v for k, v in param_options.items() if k != "amsgrad"} + optimizer = adamw_schedulefree.AdamWScheduleFree(**_param_options) + else: + optimizer = torch.optim.Adam(**param_options) + return optimizer + + +def setup_wandb(args: argparse.Namespace): + logging.info("Using Weights and Biases for logging") + import wandb + + wandb_config = {} + args_dict = vars(args) + + for key, value in args_dict.items(): + if isinstance(value, np.ndarray): + args_dict[key] = value.tolist() + + class CustomEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, KeySpecification): + return o.__dict__ + return super().default(o) + + args_dict_json = json.dumps(args_dict, cls=CustomEncoder) + for key in args.wandb_log_hypers: + wandb_config[key] = args_dict[key] + tools.init_wandb( + project=args.wandb_project, + entity=args.wandb_entity, + name=args.wandb_name, + config=wandb_config, + directory=args.wandb_dir, + ) + wandb.run.summary["params"] = args_dict_json + + +def get_files_with_suffix(dir_path: str, suffix: str) -> List[str]: + return [ + os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.endswith(suffix) + ] + + +def dict_to_array(input_data, heads): + if all(isinstance(value, np.ndarray) for value in input_data.values()): + return np.array([input_data[head] for head in heads]) + if not all(isinstance(value, dict) for value in input_data.values()): + return np.array([[input_data[head]] for head in heads]) + unique_keys = set() + for inner_dict in input_data.values(): + unique_keys.update(inner_dict.keys()) + unique_keys = list(unique_keys) + sorted_keys = sorted([int(key) for key in unique_keys]) + result_array = np.zeros((len(input_data), len(sorted_keys))) + for _, (head_name, inner_dict) in enumerate(input_data.items()): + for key, value in inner_dict.items(): + key_index = sorted_keys.index(int(key)) + head_index = heads.index(head_name) + result_array[head_index][key_index] = value + return result_array + + +class LRScheduler: + def __init__(self, optimizer, args) -> None: + self.scheduler = args.scheduler + self._optimizer_type = ( + args.optimizer + ) # Schedulefree does not need an optimizer but checkpoint handler does. + if args.scheduler == "ExponentialLR": + self.lr_scheduler = torch.optim.lr_scheduler.ExponentialLR( + optimizer=optimizer, gamma=args.lr_scheduler_gamma + ) + elif args.scheduler == "ReduceLROnPlateau": + self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer=optimizer, + factor=args.lr_factor, + patience=args.scheduler_patience, + ) + else: + raise RuntimeError(f"Unknown scheduler: '{args.scheduler}'") + + def step(self, metrics=None, epoch=None): # pylint: disable=E1123 + if self._optimizer_type == "schedulefree": + return # In principle, schedulefree optimizer can be used with a scheduler but the paper suggests it's not necessary + if self.scheduler == "ExponentialLR": + self.lr_scheduler.step(epoch=epoch) + elif self.scheduler == "ReduceLROnPlateau": + self.lr_scheduler.step( # pylint: disable=E1123 + metrics=metrics, epoch=epoch + ) + + def __getattr__(self, name): + if name == "step": + return self.step + return getattr(self.lr_scheduler, name) + + +def check_folder_subfolder(folder_path): + entries = os.listdir(folder_path) + for entry in entries: + full_path = os.path.join(folder_path, entry) + if os.path.isdir(full_path): + return True + return False + + +def check_path_ase_read(filename: Optional[str]) -> bool: + if filename is None: + return False + filepath = Path(filename) + if filepath.is_dir(): + num_h5_files = len(list(filepath.glob("*.h5"))) + num_hdf5_files = len(list(filepath.glob("*.hdf5"))) + num_ldb_files = len(list(filepath.glob("*.lmdb"))) + num_aselmbd_files = len(list(filepath.glob("*.aselmdb"))) + num_mdb_files = len(list(filepath.glob("*.mdb"))) + if ( + num_h5_files + + num_hdf5_files + + num_ldb_files + + num_aselmbd_files + + num_mdb_files + == 0 + ): + # print all the files in the directory extension in the directory for debugging + for file in os.listdir(filepath): + print(file) + raise RuntimeError(f"No supported files found in directory '{filename}'") + return False + if filepath.suffix in (".h5", ".hdf5", ".lmdb", ".aselmdb", ".mdb"): + return False + return True + + +def dict_to_namespace(dictionary): + # Convert the dictionary into an argparse.Namespace + namespace = argparse.Namespace() + for key, value in dictionary.items(): + setattr(namespace, key, value) + return namespace diff --git a/models/mace/mace/tools/slurm_distributed.py b/models/mace/mace/tools/slurm_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9379b80995480b2065edbc45305df0ac8bd732 --- /dev/null +++ b/models/mace/mace/tools/slurm_distributed.py @@ -0,0 +1,51 @@ +########################################################################################### +# Slurm environment setup for distributed training. +# This code is refactored from rsarm's contribution at: +# https://github.com/Lumi-supercomputer/lumi-reframe-tests/blob/main/checks/apps/deeplearning/pytorch/src/pt_distr_env.py +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import os + +try: + import hostlist +except ImportError: + hostlist = None # Only needed on SLURM systems + + +class DistributedEnvironment: + def __init__(self): + self._setup_distr_env() + self.master_addr = os.environ["MASTER_ADDR"] + self.master_port = os.environ["MASTER_PORT"] + self.world_size = int(os.environ["WORLD_SIZE"]) + self.local_rank = int(os.environ["LOCAL_RANK"]) + self.rank = int(os.environ["RANK"]) + + def _setup_distr_env(self): + if "SLURM_JOB_NODELIST" in os.environ: + hostname = hostlist.expand_hostlist(os.environ["SLURM_JOB_NODELIST"])[0] + os.environ["MASTER_ADDR"] = hostname + os.environ["MASTER_PORT"] = os.environ.get("MASTER_PORT", "33333") + os.environ["WORLD_SIZE"] = os.environ.get( + "SLURM_NTASKS", + str( + int(os.environ["SLURM_NTASKS_PER_NODE"]) + * int(os.environ["SLURM_NNODES"]) + ), + ) + os.environ["LOCAL_RANK"] = os.environ["SLURM_LOCALID"] + os.environ["RANK"] = os.environ["SLURM_PROCID"] + else: + # Assume local manual run with torchrun + os.environ.setdefault("MASTER_ADDR", "localhost") + os.environ.setdefault("MASTER_PORT", "33333") + os.environ.setdefault("WORLD_SIZE", "1") + os.environ.setdefault("LOCAL_RANK", "0") + os.environ.setdefault("RANK", "0") + + def __repr__(self): + return ( + f"DistributedEnvironment(master_addr={self.master_addr}, master_port={self.master_port}, " + f"world_size={self.world_size}, local_rank={self.local_rank}, rank={self.rank})" + ) diff --git a/models/mace/mace/tools/tables_utils.py b/models/mace/mace/tools/tables_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b38abd9dd2ead48efd582d4595cdb91732c43a --- /dev/null +++ b/models/mace/mace/tools/tables_utils.py @@ -0,0 +1,262 @@ +import logging +from typing import Dict, List, Optional + +import torch +from prettytable import PrettyTable + +from mace.tools import evaluate + + +def custom_key(key): + """ + Helper function to sort the keys of the data loader dictionary + to ensure that the training set, and validation set + are evaluated first + """ + if key == "train": + return (0, key) + if key == "valid": + return (1, key) + return (2, key) + + +def create_error_table( + table_type: str, + all_data_loaders: dict, + model: torch.nn.Module, + loss_fn: torch.nn.Module, + output_args: Dict[str, bool], + log_wandb: bool, + device: str, + distributed: bool = False, + skip_heads: Optional[List[str]] = None, +) -> PrettyTable: + if log_wandb: + import wandb + skip_heads = skip_heads or [] + table = PrettyTable() + if table_type == "TotalRMSE": + table.field_names = [ + "config_type", + "RMSE E / meV", + "RMSE F / meV / A", + "relative F RMSE %", + ] + elif table_type == "PerAtomRMSE": + table.field_names = [ + "config_type", + "RMSE E / meV / atom", + "RMSE F / meV / A", + "relative F RMSE %", + ] + elif table_type == "PerAtomRMSEstressvirials": + table.field_names = [ + "config_type", + "RMSE E / meV / atom", + "RMSE F / meV / A", + "relative F RMSE %", + "RMSE Stress (Virials) / meV / A (A^3)", + ] + elif table_type == "PerAtomMAEstressvirials": + table.field_names = [ + "config_type", + "MAE E / meV / atom", + "MAE F / meV / A", + "relative F MAE %", + "MAE Stress (Virials) / meV / A (A^3)", + ] + elif table_type == "TotalMAE": + table.field_names = [ + "config_type", + "MAE E / meV", + "MAE F / meV / A", + "relative F MAE %", + ] + elif table_type == "PerAtomMAE": + table.field_names = [ + "config_type", + "MAE E / meV / atom", + "MAE F / meV / A", + "relative F MAE %", + ] + elif table_type == "DipoleRMSE": + table.field_names = [ + "config_type", + "RMSE MU / mDebye / atom", + "relative MU RMSE %", + ] + elif table_type == "DipoleMAE": + table.field_names = [ + "config_type", + "MAE MU / mDebye / atom", + "relative MU MAE %", + ] + elif table_type == "DipolePolarRMSE": + table.field_names = [ + "config_type", + "RMSE MU / me A / atom", + "relative MU RMSE %", + "RMSE ALPHA e A^2 / V / atom", + ] + elif table_type == "EnergyDipoleRMSE": + table.field_names = [ + "config_type", + "RMSE E / meV / atom", + "RMSE F / meV / A", + "rel F RMSE %", + "RMSE MU / mDebye / atom", + "rel MU RMSE %", + ] + + for name in sorted(all_data_loaders, key=custom_key): + if any(skip_head in name for skip_head in skip_heads): + logging.info(f"Skipping evaluation of {name} (in skip_heads list)") + continue + data_loader = all_data_loaders[name] + logging.info(f"Evaluating {name} ...") + _, metrics = evaluate( + model, + loss_fn=loss_fn, + data_loader=data_loader, + output_args=output_args, + device=device, + ) + if distributed: + torch.distributed.barrier() + + del data_loader + torch.cuda.empty_cache() + if log_wandb: + wandb_log_dict = { + name + + "_final_rmse_e_per_atom": metrics["rmse_e_per_atom"] + * 1e3, # meV / atom + name + "_final_rmse_f": metrics["rmse_f"] * 1e3, # meV / A + name + "_final_rel_rmse_f": metrics["rel_rmse_f"], + } + wandb.log(wandb_log_dict) + if table_type == "TotalRMSE": + table.add_row( + [ + name, + f"{metrics['rmse_e'] * 1000:8.1f}", + f"{metrics['rmse_f'] * 1000:8.1f}", + f"{metrics['rel_rmse_f']:8.2f}", + ] + ) + elif table_type == "PerAtomRMSE": + table.add_row( + [ + name, + f"{metrics['rmse_e_per_atom'] * 1000:8.1f}", + f"{metrics['rmse_f'] * 1000:8.1f}", + f"{metrics['rel_rmse_f']:8.2f}", + ] + ) + elif ( + table_type == "PerAtomRMSEstressvirials" + and metrics["rmse_stress"] is not None + ): + table.add_row( + [ + name, + f"{metrics['rmse_e_per_atom'] * 1000:8.1f}", + f"{metrics['rmse_f'] * 1000:8.1f}", + f"{metrics['rel_rmse_f']:8.2f}", + f"{metrics['rmse_stress'] * 1000:8.1f}", + ] + ) + elif ( + table_type == "PerAtomRMSEstressvirials" + and metrics["rmse_virials"] is not None + ): + table.add_row( + [ + name, + f"{metrics['rmse_e_per_atom'] * 1000:8.1f}", + f"{metrics['rmse_f'] * 1000:8.1f}", + f"{metrics['rel_rmse_f']:8.2f}", + f"{metrics['rmse_virials'] * 1000:8.1f}", + ] + ) + elif ( + table_type == "PerAtomMAEstressvirials" + and metrics["mae_stress"] is not None + ): + table.add_row( + [ + name, + f"{metrics['mae_e_per_atom'] * 1000:8.1f}", + f"{metrics['mae_f'] * 1000:8.1f}", + f"{metrics['rel_mae_f']:8.2f}", + f"{metrics['mae_stress'] * 1000:8.1f}", + ] + ) + elif ( + table_type == "PerAtomMAEstressvirials" + and metrics["mae_virials"] is not None + ): + table.add_row( + [ + name, + f"{metrics['mae_e_per_atom'] * 1000:8.1f}", + f"{metrics['mae_f'] * 1000:8.1f}", + f"{metrics['rel_mae_f']:8.2f}", + f"{metrics['mae_virials'] * 1000:8.1f}", + ] + ) + elif table_type == "TotalMAE": + table.add_row( + [ + name, + f"{metrics['mae_e'] * 1000:8.1f}", + f"{metrics['mae_f'] * 1000:8.1f}", + f"{metrics['rel_mae_f']:8.2f}", + ] + ) + elif table_type == "PerAtomMAE": + table.add_row( + [ + name, + f"{metrics['mae_e_per_atom'] * 1000:8.1f}", + f"{metrics['mae_f'] * 1000:8.1f}", + f"{metrics['rel_mae_f']:8.2f}", + ] + ) + elif table_type == "DipoleRMSE": + table.add_row( + [ + name, + f"{metrics['rmse_mu_per_atom'] * 1000:8.2f}", + f"{metrics['rel_rmse_mu']:8.1f}", + ] + ) + elif table_type == "DipoleMAE": + table.add_row( + [ + name, + f"{metrics['mae_mu_per_atom'] * 1000:8.2f}", + f"{metrics['rel_mae_mu']:8.1f}", + ] + ) + elif table_type == "DipolePolarRMSE": + table.add_row( + [ + name, + f"{metrics['rmse_mu_per_atom'] * 1000:.2f}", + f"{metrics['rel_rmse_mu']:.1f}", + f"{metrics['rmse_polarizability_per_atom'] * 1000:.2f}", + ] + ) + elif table_type == "EnergyDipoleRMSE": + table.add_row( + [ + name, + f"{metrics['rmse_e_per_atom'] * 1000:8.1f}", + f"{metrics['rmse_f'] * 1000:8.1f}", + f"{metrics['rel_rmse_f']:8.1f}", + f"{metrics['rmse_mu_per_atom'] * 1000:8.1f}", + f"{metrics['rel_rmse_mu']:8.1f}", + ] + ) + return table diff --git a/models/mace/mace/tools/torch_geometric/README.md b/models/mace/mace/tools/torch_geometric/README.md new file mode 100644 index 0000000000000000000000000000000000000000..261ebbbc7e2671440a8b5ef2481678780134ce8b --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/README.md @@ -0,0 +1,12 @@ +# Trimmed-down `pytorch_geometric` + +MACE uses [`pytorch_geometric`](https://pytorch-geometric.readthedocs.io/en/latest/) [1, 2] framework. However as only use a very limited subset of that library: the most basic graph data structures. + +We follow the same approach to NequIP (https://github.com/mir-group/nequip/tree/main/nequip) and copy their code here. + +To avoid adding a large number of unnecessary second-degree dependencies, and to simplify installation, we include and modify here the small subset of `torch_geometric` that is necessary for our code. + +We are grateful to the developers of PyTorch Geometric for their ongoing and very useful work on graph learning with PyTorch. + +[1] Fey, M., & Lenssen, J. E. (2019). Fast Graph Representation Learning with PyTorch Geometric (Version 2.0.1) [Computer software]. https://github.com/pyg-team/pytorch_geometric
+[2] https://arxiv.org/abs/1903.02428 diff --git a/models/mace/mace/tools/torch_geometric/__init__.py b/models/mace/mace/tools/torch_geometric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..486f0d09d41acfdffba0c1d6e29828bc4fe9ba75 --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/__init__.py @@ -0,0 +1,7 @@ +from .batch import Batch +from .data import Data +from .dataloader import DataLoader +from .dataset import Dataset +from .seed import seed_everything + +__all__ = ["Batch", "Data", "Dataset", "DataLoader", "seed_everything"] diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/__init__.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3401588f54991efa3381cd498d9d65af3cb9c7e Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/__init__.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/batch.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/batch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b932f46a3583970f707bc6c217563937dda2fa5f Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/batch.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/data.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d215cfbc31e60b2d6a20e0472089f28a3ff68c8e Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/data.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/dataloader.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/dataloader.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60cc71684b6e28eee82b93ce791d400fd9741c62 Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/dataloader.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/dataset.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec010205b3c5a6216febda80450fad569de48342 Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/dataset.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/seed.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/seed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a18dba0410a60cc61d801c8aa8318c835ea0b4 Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/seed.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/__pycache__/utils.cpython-310.pyc b/models/mace/mace/tools/torch_geometric/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b2b01e002613230a798d72f7f1c5ad3326f319a Binary files /dev/null and b/models/mace/mace/tools/torch_geometric/__pycache__/utils.cpython-310.pyc differ diff --git a/models/mace/mace/tools/torch_geometric/batch.py b/models/mace/mace/tools/torch_geometric/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..be5ec9d0cf418c9edc79fc503f143065e6450434 --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/batch.py @@ -0,0 +1,257 @@ +from collections.abc import Sequence +from typing import List + +import numpy as np +import torch +from torch import Tensor + +from .data import Data +from .dataset import IndexType + + +class Batch(Data): + r"""A plain old python object modeling a batch of graphs as one big + (disconnected) graph. With :class:`torch_geometric.data.Data` being the + base class, all its methods can also be used here. + In addition, single graphs can be reconstructed via the assignment vector + :obj:`batch`, which maps each node to its respective graph identifier. + """ + + def __init__(self, batch=None, ptr=None, **kwargs): + super(Batch, self).__init__(**kwargs) + + for key, item in kwargs.items(): + if key == "num_nodes": + self.__num_nodes__ = item + else: + self[key] = item + + self.batch = batch + self.ptr = ptr + self.__data_class__ = Data + self.__slices__ = None + self.__cumsum__ = None + self.__cat_dims__ = None + self.__num_nodes_list__ = None + self.__num_graphs__ = None + + @classmethod + def from_data_list(cls, data_list, follow_batch=[], exclude_keys=[]): + r"""Constructs a batch object from a python list holding + :class:`torch_geometric.data.Data` objects. + The assignment vector :obj:`batch` is created on the fly. + Additionally, creates assignment batch vectors for each key in + :obj:`follow_batch`. + Will exclude any keys given in :obj:`exclude_keys`.""" + + keys = list(set(data_list[0].keys) - set(exclude_keys)) + assert "batch" not in keys and "ptr" not in keys + + batch = cls() + for key in data_list[0].__dict__.keys(): + if key[:2] != "__" and key[-2:] != "__": + batch[key] = None + + batch.__num_graphs__ = len(data_list) + batch.__data_class__ = data_list[0].__class__ + for key in keys + ["batch"]: + batch[key] = [] + batch["ptr"] = [0] + + device = None + slices = {key: [0] for key in keys} + cumsum = {key: [0] for key in keys} + cat_dims = {} + num_nodes_list = [] + for i, data in enumerate(data_list): + for key in keys: + item = data[key] + + # Increase values by `cumsum` value. + cum = cumsum[key][-1] + if isinstance(item, Tensor) and item.dtype != torch.bool: + if not isinstance(cum, int) or cum != 0: + item = item + cum + elif isinstance(item, (int, float)): + item = item + cum + + # Gather the size of the `cat` dimension. + size = 1 + cat_dim = data.__cat_dim__(key, data[key]) + # 0-dimensional tensors have no dimension along which to + # concatenate, so we set `cat_dim` to `None`. + if isinstance(item, Tensor) and item.dim() == 0: + cat_dim = None + cat_dims[key] = cat_dim + + # Add a batch dimension to items whose `cat_dim` is `None`: + if isinstance(item, Tensor) and cat_dim is None: + cat_dim = 0 # Concatenate along this new batch dimension. + item = item.unsqueeze(0) + device = item.device + elif isinstance(item, Tensor): + size = item.size(cat_dim) + device = item.device + + batch[key].append(item) # Append item to the attribute list. + + slices[key].append(size + slices[key][-1]) + inc = data.__inc__(key, item) + if isinstance(inc, (tuple, list)): + inc = torch.tensor(inc) + cumsum[key].append(inc + cumsum[key][-1]) + + if key in follow_batch: + if isinstance(size, Tensor): + for j, size in enumerate(size.tolist()): + tmp = f"{key}_{j}_batch" + batch[tmp] = [] if i == 0 else batch[tmp] + batch[tmp].append( + torch.full((size,), i, dtype=torch.long, device=device) + ) + else: + tmp = f"{key}_batch" + batch[tmp] = [] if i == 0 else batch[tmp] + batch[tmp].append( + torch.full((size,), i, dtype=torch.long, device=device) + ) + + if hasattr(data, "__num_nodes__"): + num_nodes_list.append(data.__num_nodes__) + else: + num_nodes_list.append(None) + + num_nodes = data.num_nodes + if num_nodes is not None: + item = torch.full((num_nodes,), i, dtype=torch.long, device=device) + batch.batch.append(item) + batch.ptr.append(batch.ptr[-1] + num_nodes) + + batch.batch = None if len(batch.batch) == 0 else batch.batch + batch.ptr = None if len(batch.ptr) == 1 else batch.ptr + batch.__slices__ = slices + batch.__cumsum__ = cumsum + batch.__cat_dims__ = cat_dims + batch.__num_nodes_list__ = num_nodes_list + + ref_data = data_list[0] + for key in batch.keys: + items = batch[key] + item = items[0] + cat_dim = ref_data.__cat_dim__(key, item) + cat_dim = 0 if cat_dim is None else cat_dim + if isinstance(item, Tensor): + batch[key] = torch.cat(items, cat_dim) + elif isinstance(item, (int, float)): + batch[key] = torch.tensor(items) + + # if torch_geometric.is_debug_enabled(): + # batch.debug() + + return batch.contiguous() + + def get_example(self, idx: int) -> Data: + r"""Reconstructs the :class:`torch_geometric.data.Data` object at index + :obj:`idx` from the batch object. + The batch object must have been created via :meth:`from_data_list` in + order to be able to reconstruct the initial objects.""" + + if self.__slices__ is None: + raise RuntimeError( + ( + "Cannot reconstruct data list from batch because the batch " + "object was not created using `Batch.from_data_list()`." + ) + ) + + data = self.__data_class__() + idx = self.num_graphs + idx if idx < 0 else idx + + for key in self.__slices__.keys(): + item = self[key] + if self.__cat_dims__[key] is None: + # The item was concatenated along a new batch dimension, + # so just index in that dimension: + item = item[idx] + else: + # Narrow the item based on the values in `__slices__`. + if isinstance(item, Tensor): + dim = self.__cat_dims__[key] + start = self.__slices__[key][idx] + end = self.__slices__[key][idx + 1] + item = item.narrow(dim, start, end - start) + else: + start = self.__slices__[key][idx] + end = self.__slices__[key][idx + 1] + item = item[start:end] + item = item[0] if len(item) == 1 else item + + # Decrease its value by `cumsum` value: + cum = self.__cumsum__[key][idx] + if isinstance(item, Tensor): + if not isinstance(cum, int) or cum != 0: + item = item - cum + elif isinstance(item, (int, float)): + item = item - cum + + data[key] = item + + if self.__num_nodes_list__[idx] is not None: + data.num_nodes = self.__num_nodes_list__[idx] + + return data + + def index_select(self, idx: IndexType) -> List[Data]: + if isinstance(idx, slice): + idx = list(range(self.num_graphs)[idx]) + + elif isinstance(idx, Tensor) and idx.dtype == torch.long: + idx = idx.flatten().tolist() + + elif isinstance(idx, Tensor) and idx.dtype == torch.bool: + idx = idx.flatten().nonzero(as_tuple=False).flatten().tolist() + + elif isinstance(idx, np.ndarray) and idx.dtype == np.int64: + idx = idx.flatten().tolist() + + elif isinstance(idx, np.ndarray) and idx.dtype == np.bool: + idx = idx.flatten().nonzero()[0].flatten().tolist() + + elif isinstance(idx, Sequence) and not isinstance(idx, str): + pass + + else: + raise IndexError( + f"Only integers, slices (':'), list, tuples, torch.tensor and " + f"np.ndarray of dtype long or bool are valid indices (got " + f"'{type(idx).__name__}')" + ) + + return [self.get_example(i) for i in idx] + + def __getitem__(self, idx): + if isinstance(idx, str): + return super(Batch, self).__getitem__(idx) + elif isinstance(idx, (int, np.integer)): + return self.get_example(idx) + else: + return self.index_select(idx) + + def to_data_list(self) -> List[Data]: + r"""Reconstructs the list of :class:`torch_geometric.data.Data` objects + from the batch object. + The batch object must have been created via :meth:`from_data_list` in + order to be able to reconstruct the initial objects.""" + return [self.get_example(i) for i in range(self.num_graphs)] + + @property + def num_graphs(self) -> int: + """Returns the number of graphs in the batch.""" + if self.__num_graphs__ is not None: + return self.__num_graphs__ + elif self.ptr is not None: + return self.ptr.numel() - 1 + elif self.batch is not None: + return int(self.batch.max()) + 1 + else: + raise ValueError diff --git a/models/mace/mace/tools/torch_geometric/data.py b/models/mace/mace/tools/torch_geometric/data.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1ab3084d584dcf5af7289e3159c353327ec539 --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/data.py @@ -0,0 +1,441 @@ +import collections +import copy +import re + +import torch + +# from ..utils.num_nodes import maybe_num_nodes + +__num_nodes_warn_msg__ = ( + "The number of nodes in your data object can only be inferred by its {} " + "indices, and hence may result in unexpected batch-wise behavior, e.g., " + "in case there exists isolated nodes. Please consider explicitly setting " + "the number of nodes for this data object by assigning it to " + "data.num_nodes." +) + + +def size_repr(key, item, indent=0): + indent_str = " " * indent + if torch.is_tensor(item) and item.dim() == 0: + out = item.item() + elif torch.is_tensor(item): + out = str(list(item.size())) + elif isinstance(item, list) or isinstance(item, tuple): + out = str([len(item)]) + elif isinstance(item, dict): + lines = [indent_str + size_repr(k, v, 2) for k, v in item.items()] + out = "{\n" + ",\n".join(lines) + "\n" + indent_str + "}" + elif isinstance(item, str): + out = f'"{item}"' + else: + out = str(item) + + return f"{indent_str}{key}={out}" + + +class Data(object): + r"""A plain old python object modeling a single graph with various + (optional) attributes: + + Args: + x (Tensor, optional): Node feature matrix with shape :obj:`[num_nodes, + num_node_features]`. (default: :obj:`None`) + edge_index (LongTensor, optional): Graph connectivity in COO format + with shape :obj:`[2, num_edges]`. (default: :obj:`None`) + edge_attr (Tensor, optional): Edge feature matrix with shape + :obj:`[num_edges, num_edge_features]`. (default: :obj:`None`) + y (Tensor, optional): Graph or node targets with arbitrary shape. + (default: :obj:`None`) + pos (Tensor, optional): Node position matrix with shape + :obj:`[num_nodes, num_dimensions]`. (default: :obj:`None`) + normal (Tensor, optional): Normal vector matrix with shape + :obj:`[num_nodes, num_dimensions]`. (default: :obj:`None`) + face (LongTensor, optional): Face adjacency matrix with shape + :obj:`[3, num_faces]`. (default: :obj:`None`) + + The data object is not restricted to these attributes and can be extended + by any other additional data. + + Example:: + + data = Data(x=x, edge_index=edge_index) + data.train_idx = torch.tensor([...], dtype=torch.long) + data.test_mask = torch.tensor([...], dtype=torch.bool) + """ + + def __init__( + self, + x=None, + edge_index=None, + edge_attr=None, + y=None, + pos=None, + normal=None, + face=None, + **kwargs, + ): + self.x = x + self.edge_index = edge_index + self.edge_attr = edge_attr + self.y = y + self.pos = pos + self.normal = normal + self.face = face + for key, item in kwargs.items(): + if key == "num_nodes": + self.__num_nodes__ = item + else: + self[key] = item + + if edge_index is not None and edge_index.dtype != torch.long: + raise ValueError( + ( + f"Argument `edge_index` needs to be of type `torch.long` but " + f"found type `{edge_index.dtype}`." + ) + ) + + if face is not None and face.dtype != torch.long: + raise ValueError( + ( + f"Argument `face` needs to be of type `torch.long` but found " + f"type `{face.dtype}`." + ) + ) + + @classmethod + def from_dict(cls, dictionary): + r"""Creates a data object from a python dictionary.""" + data = cls() + + for key, item in dictionary.items(): + data[key] = item + + return data + + def to_dict(self): + return {key: item for key, item in self} + + def to_namedtuple(self): + keys = self.keys + DataTuple = collections.namedtuple("DataTuple", keys) + return DataTuple(*[self[key] for key in keys]) + + def __getitem__(self, key): + r"""Gets the data of the attribute :obj:`key`.""" + return getattr(self, key, None) + + def __setitem__(self, key, value): + """Sets the attribute :obj:`key` to :obj:`value`.""" + setattr(self, key, value) + + def __delitem__(self, key): + r"""Delete the data of the attribute :obj:`key`.""" + return delattr(self, key) + + @property + def keys(self): + r"""Returns all names of graph attributes.""" + keys = [key for key in self.__dict__.keys() if self[key] is not None] + keys = [key for key in keys if key[:2] != "__" and key[-2:] != "__"] + return keys + + def __len__(self): + r"""Returns the number of all present attributes.""" + return len(self.keys) + + def __contains__(self, key): + r"""Returns :obj:`True`, if the attribute :obj:`key` is present in the + data.""" + return key in self.keys + + def __iter__(self): + r"""Iterates over all present attributes in the data, yielding their + attribute names and content.""" + for key in sorted(self.keys): + yield key, self[key] + + def __call__(self, *keys): + r"""Iterates over all attributes :obj:`*keys` in the data, yielding + their attribute names and content. + If :obj:`*keys` is not given this method will iterative over all + present attributes.""" + for key in sorted(self.keys) if not keys else keys: + if key in self: + yield key, self[key] + + def __cat_dim__(self, key, value): + r"""Returns the dimension for which :obj:`value` of attribute + :obj:`key` will get concatenated when creating batches. + + .. note:: + + This method is for internal use only, and should only be overridden + if the batch concatenation process is corrupted for a specific data + attribute. + """ + if bool(re.search("(index|face)", key)): + return -1 + return 0 + + def __inc__(self, key, value): + r"""Returns the incremental count to cumulatively increase the value + of the next attribute of :obj:`key` when creating batches. + + .. note:: + + This method is for internal use only, and should only be overridden + if the batch concatenation process is corrupted for a specific data + attribute. + """ + # Only `*index*` and `*face*` attributes should be cumulatively summed + # up when creating batches. + return self.num_nodes if bool(re.search("(index|face)", key)) else 0 + + @property + def num_nodes(self): + r"""Returns or sets the number of nodes in the graph. + + .. note:: + The number of nodes in your data object is typically automatically + inferred, *e.g.*, when node features :obj:`x` are present. + In some cases however, a graph may only be given by its edge + indices :obj:`edge_index`. + PyTorch Geometric then *guesses* the number of nodes + according to :obj:`edge_index.max().item() + 1`, but in case there + exists isolated nodes, this number has not to be correct and can + therefore result in unexpected batch-wise behavior. + Thus, we recommend to set the number of nodes in your data object + explicitly via :obj:`data.num_nodes = ...`. + You will be given a warning that requests you to do so. + """ + if hasattr(self, "__num_nodes__"): + return self.__num_nodes__ + for key, item in self("x", "pos", "normal", "batch"): + return item.size(self.__cat_dim__(key, item)) + if hasattr(self, "adj"): + return self.adj.size(0) + if hasattr(self, "adj_t"): + return self.adj_t.size(1) + # if self.face is not None: + # logging.warning(__num_nodes_warn_msg__.format("face")) + # return maybe_num_nodes(self.face) + # if self.edge_index is not None: + # logging.warning(__num_nodes_warn_msg__.format("edge")) + # return maybe_num_nodes(self.edge_index) + return None + + @num_nodes.setter + def num_nodes(self, num_nodes): + self.__num_nodes__ = num_nodes + + @property + def num_edges(self): + """ + Returns the number of edges in the graph. + For undirected graphs, this will return the number of bi-directional + edges, which is double the amount of unique edges. + """ + for key, item in self("edge_index", "edge_attr"): + return item.size(self.__cat_dim__(key, item)) + for key, item in self("adj", "adj_t"): + return item.nnz() + return None + + @property + def num_faces(self): + r"""Returns the number of faces in the mesh.""" + if self.face is not None: + return self.face.size(self.__cat_dim__("face", self.face)) + return None + + @property + def num_node_features(self): + r"""Returns the number of features per node in the graph.""" + if self.x is None: + return 0 + return 1 if self.x.dim() == 1 else self.x.size(1) + + @property + def num_features(self): + r"""Alias for :py:attr:`~num_node_features`.""" + return self.num_node_features + + @property + def num_edge_features(self): + r"""Returns the number of features per edge in the graph.""" + if self.edge_attr is None: + return 0 + return 1 if self.edge_attr.dim() == 1 else self.edge_attr.size(1) + + def __apply__(self, item, func): + if torch.is_tensor(item): + return func(item) + elif isinstance(item, (tuple, list)): + return [self.__apply__(v, func) for v in item] + elif isinstance(item, dict): + return {k: self.__apply__(v, func) for k, v in item.items()} + else: + return item + + def apply(self, func, *keys): + r"""Applies the function :obj:`func` to all tensor attributes + :obj:`*keys`. If :obj:`*keys` is not given, :obj:`func` is applied to + all present attributes. + """ + for key, item in self(*keys): + self[key] = self.__apply__(item, func) + return self + + def contiguous(self, *keys): + r"""Ensures a contiguous memory layout for all attributes :obj:`*keys`. + If :obj:`*keys` is not given, all present attributes are ensured to + have a contiguous memory layout.""" + return self.apply(lambda x: x.contiguous(), *keys) + + def to(self, device, *keys, **kwargs): + r"""Performs tensor dtype and/or device conversion to all attributes + :obj:`*keys`. + If :obj:`*keys` is not given, the conversion is applied to all present + attributes.""" + return self.apply(lambda x: x.to(device, **kwargs), *keys) + + def cpu(self, *keys): + r"""Copies all attributes :obj:`*keys` to CPU memory. + If :obj:`*keys` is not given, the conversion is applied to all present + attributes.""" + return self.apply(lambda x: x.cpu(), *keys) + + def cuda(self, device=None, non_blocking=False, *keys): + r"""Copies all attributes :obj:`*keys` to CUDA memory. + If :obj:`*keys` is not given, the conversion is applied to all present + attributes.""" + return self.apply( + lambda x: x.cuda(device=device, non_blocking=non_blocking), *keys + ) + + def clone(self): + r"""Performs a deep-copy of the data object.""" + return self.__class__.from_dict( + { + k: v.clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in self.__dict__.items() + } + ) + + def pin_memory(self, *keys): + r"""Copies all attributes :obj:`*keys` to pinned memory. + If :obj:`*keys` is not given, the conversion is applied to all present + attributes.""" + return self.apply(lambda x: x.pin_memory(), *keys) + + def debug(self): + if self.edge_index is not None: + if self.edge_index.dtype != torch.long: + raise RuntimeError( + ( + "Expected edge indices of dtype {}, but found dtype " " {}" + ).format(torch.long, self.edge_index.dtype) + ) + + if self.face is not None: + if self.face.dtype != torch.long: + raise RuntimeError( + ( + "Expected face indices of dtype {}, but found dtype " " {}" + ).format(torch.long, self.face.dtype) + ) + + if self.edge_index is not None: + if self.edge_index.dim() != 2 or self.edge_index.size(0) != 2: + raise RuntimeError( + ( + "Edge indices should have shape [2, num_edges] but found" + " shape {}" + ).format(self.edge_index.size()) + ) + + if self.edge_index is not None and self.num_nodes is not None: + if self.edge_index.numel() > 0: + min_index = self.edge_index.min() + max_index = self.edge_index.max() + else: + min_index = max_index = 0 + if min_index < 0 or max_index > self.num_nodes - 1: + raise RuntimeError( + ( + "Edge indices must lay in the interval [0, {}]" + " but found them in the interval [{}, {}]" + ).format(self.num_nodes - 1, min_index, max_index) + ) + + if self.face is not None: + if self.face.dim() != 2 or self.face.size(0) != 3: + raise RuntimeError( + ( + "Face indices should have shape [3, num_faces] but found" + " shape {}" + ).format(self.face.size()) + ) + + if self.face is not None and self.num_nodes is not None: + if self.face.numel() > 0: + min_index = self.face.min() + max_index = self.face.max() + else: + min_index = max_index = 0 + if min_index < 0 or max_index > self.num_nodes - 1: + raise RuntimeError( + ( + "Face indices must lay in the interval [0, {}]" + " but found them in the interval [{}, {}]" + ).format(self.num_nodes - 1, min_index, max_index) + ) + + if self.edge_index is not None and self.edge_attr is not None: + if self.edge_index.size(1) != self.edge_attr.size(0): + raise RuntimeError( + ( + "Edge indices and edge attributes hold a differing " + "number of edges, found {} and {}" + ).format(self.edge_index.size(), self.edge_attr.size()) + ) + + if self.x is not None and self.num_nodes is not None: + if self.x.size(0) != self.num_nodes: + raise RuntimeError( + ( + "Node features should hold {} elements in the first " + "dimension but found {}" + ).format(self.num_nodes, self.x.size(0)) + ) + + if self.pos is not None and self.num_nodes is not None: + if self.pos.size(0) != self.num_nodes: + raise RuntimeError( + ( + "Node positions should hold {} elements in the first " + "dimension but found {}" + ).format(self.num_nodes, self.pos.size(0)) + ) + + if self.normal is not None and self.num_nodes is not None: + if self.normal.size(0) != self.num_nodes: + raise RuntimeError( + ( + "Node normals should hold {} elements in the first " + "dimension but found {}" + ).format(self.num_nodes, self.normal.size(0)) + ) + + def __repr__(self): + cls = str(self.__class__.__name__) + has_dict = any([isinstance(item, dict) for _, item in self]) + + if not has_dict: + info = [size_repr(key, item) for key, item in self] + return "{}({})".format(cls, ", ".join(info)) + else: + info = [size_repr(key, item, indent=2) for key, item in self] + return "{}(\n{}\n)".format(cls, ",\n".join(info)) diff --git a/models/mace/mace/tools/torch_geometric/dataloader.py b/models/mace/mace/tools/torch_geometric/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..396b7e7285ac192cb8d6d5e26f686321734d132b --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/dataloader.py @@ -0,0 +1,87 @@ +from collections.abc import Mapping, Sequence +from typing import List, Optional, Union + +import torch.utils.data +from torch.utils.data.dataloader import default_collate + +from .batch import Batch +from .data import Data +from .dataset import Dataset + + +class Collater: + def __init__(self, follow_batch, exclude_keys): + self.follow_batch = follow_batch + self.exclude_keys = exclude_keys + + def __call__(self, batch): + elem = batch[0] + if isinstance(elem, Data): + return Batch.from_data_list( + batch, + follow_batch=self.follow_batch, + exclude_keys=self.exclude_keys, + ) + elif isinstance(elem, torch.Tensor): + return default_collate(batch) + elif isinstance(elem, float): + return torch.tensor(batch, dtype=torch.float) + elif isinstance(elem, int): + return torch.tensor(batch) + elif isinstance(elem, str): + return batch + elif isinstance(elem, Mapping): + return {key: self([data[key] for data in batch]) for key in elem} + elif isinstance(elem, tuple) and hasattr(elem, "_fields"): + return type(elem)(*(self(s) for s in zip(*batch))) + elif isinstance(elem, Sequence) and not isinstance(elem, str): + return [self(s) for s in zip(*batch)] + + raise TypeError(f"DataLoader found invalid type: {type(elem)}") + + def collate(self, batch): # Deprecated... + return self(batch) + + +class DataLoader(torch.utils.data.DataLoader): + r"""A data loader which merges data objects from a + :class:`torch_geometric.data.Dataset` to a mini-batch. + Data objects can be either of type :class:`~torch_geometric.data.Data` or + :class:`~torch_geometric.data.HeteroData`. + Args: + dataset (Dataset): The dataset from which to load the data. + batch_size (int, optional): How many samples per batch to load. + (default: :obj:`1`) + shuffle (bool, optional): If set to :obj:`True`, the data will be + reshuffled at every epoch. (default: :obj:`False`) + follow_batch (List[str], optional): Creates assignment batch + vectors for each key in the list. (default: :obj:`None`) + exclude_keys (List[str], optional): Will exclude each key in the + list. (default: :obj:`None`) + **kwargs (optional): Additional arguments of + :class:`torch.utils.data.DataLoader`. + """ + + def __init__( + self, + dataset: Dataset, + batch_size: int = 1, + shuffle: bool = False, + follow_batch: Optional[List[str]] = [None], + exclude_keys: Optional[List[str]] = [None], + **kwargs, + ): + if "collate_fn" in kwargs: + del kwargs["collate_fn"] + + # Save for PyTorch Lightning < 1.6: + self.follow_batch = follow_batch + self.exclude_keys = exclude_keys + + super().__init__( + dataset, + batch_size, + shuffle, + collate_fn=Collater(follow_batch, exclude_keys), + **kwargs, + ) diff --git a/models/mace/mace/tools/torch_geometric/dataset.py b/models/mace/mace/tools/torch_geometric/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..b4aeb2be9149ed68be67cc9009531ac809ac6787 --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/dataset.py @@ -0,0 +1,280 @@ +import copy +import os.path as osp +import re +import warnings +from collections.abc import Sequence +from typing import Any, Callable, List, Optional, Tuple, Union + +import numpy as np +import torch.utils.data +from torch import Tensor + +from .data import Data +from .utils import makedirs + +IndexType = Union[slice, Tensor, np.ndarray, Sequence] + + +class Dataset(torch.utils.data.Dataset): + r"""Dataset base class for creating graph datasets. + See `here `__ for the accompanying tutorial. + + Args: + root (string, optional): Root directory where the dataset should be + saved. (optional: :obj:`None`) + transform (callable, optional): A function/transform that takes in an + :obj:`torch_geometric.data.Data` object and returns a transformed + version. The data object will be transformed before every access. + (default: :obj:`None`) + pre_transform (callable, optional): A function/transform that takes in + an :obj:`torch_geometric.data.Data` object and returns a + transformed version. The data object will be transformed before + being saved to disk. (default: :obj:`None`) + pre_filter (callable, optional): A function that takes in an + :obj:`torch_geometric.data.Data` object and returns a boolean + value, indicating whether the data object should be included in the + final dataset. (default: :obj:`None`) + """ + + @property + def raw_file_names(self) -> Union[str, List[str], Tuple]: + r"""The name of the files to find in the :obj:`self.raw_dir` folder in + order to skip the download.""" + raise NotImplementedError + + @property + def processed_file_names(self) -> Union[str, List[str], Tuple]: + r"""The name of the files to find in the :obj:`self.processed_dir` + folder in order to skip the processing.""" + raise NotImplementedError + + def download(self): + r"""Downloads the dataset to the :obj:`self.raw_dir` folder.""" + raise NotImplementedError + + def process(self): + r"""Processes the dataset to the :obj:`self.processed_dir` folder.""" + raise NotImplementedError + + def len(self) -> int: + raise NotImplementedError + + def get(self, idx: int) -> Data: + r"""Gets the data object at index :obj:`idx`.""" + raise NotImplementedError + + def __init__( + self, + root: Optional[str] = None, + transform: Optional[Callable] = None, + pre_transform: Optional[Callable] = None, + pre_filter: Optional[Callable] = None, + ): + super().__init__() + + if isinstance(root, str): + root = osp.expanduser(osp.normpath(root)) + + self.root = root + self.transform = transform + self.pre_transform = pre_transform + self.pre_filter = pre_filter + self._indices: Optional[Sequence] = None + + if "download" in self.__class__.__dict__.keys(): + self._download() + + if "process" in self.__class__.__dict__.keys(): + self._process() + + def indices(self) -> Sequence: + return range(self.len()) if self._indices is None else self._indices + + @property + def raw_dir(self) -> str: + return osp.join(self.root, "raw") + + @property + def processed_dir(self) -> str: + return osp.join(self.root, "processed") + + @property + def num_node_features(self) -> int: + r"""Returns the number of features per node in the dataset.""" + data = self[0] + if hasattr(data, "num_node_features"): + return data.num_node_features + raise AttributeError( + f"'{data.__class__.__name__}' object has no " + f"attribute 'num_node_features'" + ) + + @property + def num_features(self) -> int: + r"""Alias for :py:attr:`~num_node_features`.""" + return self.num_node_features + + @property + def num_edge_features(self) -> int: + r"""Returns the number of features per edge in the dataset.""" + data = self[0] + if hasattr(data, "num_edge_features"): + return data.num_edge_features + raise AttributeError( + f"'{data.__class__.__name__}' object has no " + f"attribute 'num_edge_features'" + ) + + @property + def raw_paths(self) -> List[str]: + r"""The filepaths to find in order to skip the download.""" + files = to_list(self.raw_file_names) + return [osp.join(self.raw_dir, f) for f in files] + + @property + def processed_paths(self) -> List[str]: + r"""The filepaths to find in the :obj:`self.processed_dir` + folder in order to skip the processing.""" + files = to_list(self.processed_file_names) + return [osp.join(self.processed_dir, f) for f in files] + + def _download(self): + if files_exist(self.raw_paths): # pragma: no cover + return + + makedirs(self.raw_dir) + self.download() + + def _process(self): + f = osp.join(self.processed_dir, "pre_transform.pt") + if osp.exists(f) and torch.load(f) != _repr(self.pre_transform): + warnings.warn( + f"The `pre_transform` argument differs from the one used in " + f"the pre-processed version of this dataset. If you want to " + f"make use of another pre-processing technique, make sure to " + f"sure to delete '{self.processed_dir}' first" + ) + + f = osp.join(self.processed_dir, "pre_filter.pt") + if osp.exists(f) and torch.load(f) != _repr(self.pre_filter): + warnings.warn( + "The `pre_filter` argument differs from the one used in the " + "pre-processed version of this dataset. If you want to make " + "use of another pre-fitering technique, make sure to delete " + "'{self.processed_dir}' first" + ) + + if files_exist(self.processed_paths): # pragma: no cover + return + + print("Processing...") + + makedirs(self.processed_dir) + self.process() + + path = osp.join(self.processed_dir, "pre_transform.pt") + torch.save(_repr(self.pre_transform), path) + path = osp.join(self.processed_dir, "pre_filter.pt") + torch.save(_repr(self.pre_filter), path) + + print("Done!") + + def __len__(self) -> int: + r"""The number of examples in the dataset.""" + return len(self.indices()) + + def __getitem__( + self, + idx: Union[int, np.integer, IndexType], + ) -> Union["Dataset", Data]: + r"""In case :obj:`idx` is of type integer, will return the data object + at index :obj:`idx` (and transforms it in case :obj:`transform` is + present). + In case :obj:`idx` is a slicing object, *e.g.*, :obj:`[2:5]`, a list, a + tuple, a PyTorch :obj:`LongTensor` or a :obj:`BoolTensor`, or a numpy + :obj:`np.array`, will return a subset of the dataset at the specified + indices.""" + if ( + isinstance(idx, (int, np.integer)) + or (isinstance(idx, Tensor) and idx.dim() == 0) + or (isinstance(idx, np.ndarray) and np.isscalar(idx)) + ): + data = self.get(self.indices()[idx]) + data = data if self.transform is None else self.transform(data) + return data + + else: + return self.index_select(idx) + + def index_select(self, idx: IndexType) -> "Dataset": + indices = self.indices() + + if isinstance(idx, slice): + indices = indices[idx] + + elif isinstance(idx, Tensor) and idx.dtype == torch.long: + return self.index_select(idx.flatten().tolist()) + + elif isinstance(idx, Tensor) and idx.dtype == torch.bool: + idx = idx.flatten().nonzero(as_tuple=False) + return self.index_select(idx.flatten().tolist()) + + elif isinstance(idx, np.ndarray) and idx.dtype == np.int64: + return self.index_select(idx.flatten().tolist()) + + elif isinstance(idx, np.ndarray) and idx.dtype == np.bool: + idx = idx.flatten().nonzero()[0] + return self.index_select(idx.flatten().tolist()) + + elif isinstance(idx, Sequence) and not isinstance(idx, str): + indices = [indices[i] for i in idx] + + else: + raise IndexError( + f"Only integers, slices (':'), list, tuples, torch.tensor and " + f"np.ndarray of dtype long or bool are valid indices (got " + f"'{type(idx).__name__}')" + ) + + dataset = copy.copy(self) + dataset._indices = indices + return dataset + + def shuffle( + self, + return_perm: bool = False, + ) -> Union["Dataset", Tuple["Dataset", Tensor]]: + r"""Randomly shuffles the examples in the dataset. + + Args: + return_perm (bool, optional): If set to :obj:`True`, will return + the random permutation used to shuffle the dataset in addition. + (default: :obj:`False`) + """ + perm = torch.randperm(len(self)) + dataset = self.index_select(perm) + return (dataset, perm) if return_perm is True else dataset + + def __repr__(self) -> str: + arg_repr = str(len(self)) if len(self) > 1 else "" + return f"{self.__class__.__name__}({arg_repr})" + + +def to_list(value: Any) -> Sequence: + if isinstance(value, Sequence) and not isinstance(value, str): + return value + else: + return [value] + + +def files_exist(files: List[str]) -> bool: + # NOTE: We return `False` in case `files` is empty, leading to a + # re-processing of files on every instantiation. + return len(files) != 0 and all([osp.exists(f) for f in files]) + + +def _repr(obj: Any) -> str: + if obj is None: + return "None" + return re.sub("(<.*?)\\s.*(>)", r"\1\2", obj.__repr__()) diff --git a/models/mace/mace/tools/torch_geometric/seed.py b/models/mace/mace/tools/torch_geometric/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..be27fcaa1636632a9c95022990b4d9a9ac21744d --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/seed.py @@ -0,0 +1,17 @@ +import random + +import numpy as np +import torch + + +def seed_everything(seed: int): + r"""Sets the seed for generating random numbers in :pytorch:`PyTorch`, + :obj:`numpy` and Python. + + Args: + seed (int): The desired seed. + """ + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) diff --git a/models/mace/mace/tools/torch_geometric/utils.py b/models/mace/mace/tools/torch_geometric/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f53b8f8098a1efcd39669b9dbe94dc0399a2190f --- /dev/null +++ b/models/mace/mace/tools/torch_geometric/utils.py @@ -0,0 +1,54 @@ +import os +import os.path as osp +import ssl +import urllib +import zipfile + + +def makedirs(dir): + os.makedirs(dir, exist_ok=True) + + +def download_url(url, folder, log=True): + r"""Downloads the content of an URL to a specific folder. + + Args: + url (string): The url. + folder (string): The folder. + log (bool, optional): If :obj:`False`, will not print anything to the + console. (default: :obj:`True`) + """ + + filename = url.rpartition("/")[2].split("?")[0] + path = osp.join(folder, filename) + + if osp.exists(path): # pragma: no cover + if log: + print("Using exist file", filename) + return path + + if log: + print("Downloading", url) + + makedirs(folder) + + context = ssl._create_unverified_context() + data = urllib.request.urlopen(url, context=context) + + with open(path, "wb") as f: + f.write(data.read()) + + return path + + +def extract_zip(path, folder, log=True): + r"""Extracts a zip archive to a specific folder. + + Args: + path (string): The path to the tar archive. + folder (string): The folder. + log (bool, optional): If :obj:`False`, will not print anything to the + console. (default: :obj:`True`) + """ + with zipfile.ZipFile(path, "r") as f: + f.extractall(folder) diff --git a/models/mace/mace/tools/torch_tools.py b/models/mace/mace/tools/torch_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..f839350df23c7247dcf729d01d47f19f1a38ffd8 --- /dev/null +++ b/models/mace/mace/tools/torch_tools.py @@ -0,0 +1,160 @@ +########################################################################################### +# Tools for torch +# Authors: Ilyes Batatia, Gregor Simm +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import logging +from contextlib import contextmanager +from typing import Dict, Union + +import numpy as np +import torch +from e3nn.io import CartesianTensor + +TensorDict = Dict[str, torch.Tensor] + + +def to_one_hot(indices: torch.Tensor, num_classes: int) -> torch.Tensor: + """ + Generates one-hot encoding with classes from + :param indices: (N x 1) tensor + :param num_classes: number of classes + :param device: torch device + :return: (N x num_classes) tensor + """ + shape = indices.shape[:-1] + (num_classes,) + oh = torch.zeros(shape, device=indices.device).view(shape) + + # scatter_ is the in-place version of scatter + oh.scatter_(dim=-1, index=indices, value=1) + + return oh.view(*shape) + + +def count_parameters(module: torch.nn.Module) -> int: + return int(sum(np.prod(p.shape) for p in module.parameters())) + + +def tensor_dict_to_device(td: TensorDict, device: torch.device) -> TensorDict: + return {k: v.to(device) if v is not None else None for k, v in td.items()} + + +def set_seeds(seed: int) -> None: + np.random.seed(seed) + torch.manual_seed(seed) + + +def to_numpy(t: torch.Tensor) -> np.ndarray: + return t.cpu().detach().numpy() + + +def init_device(device_str: str) -> torch.device: + if "cuda" in device_str: + assert torch.cuda.is_available(), "No CUDA device available!" + if ":" in device_str: + # Check if the desired device is available + assert int(device_str.split(":")[-1]) < torch.cuda.device_count() + logging.info( + f"CUDA version: {torch.version.cuda}, CUDA device: {torch.cuda.current_device()}" + ) + torch.cuda.init() + return torch.device(device_str) + if device_str == "mps": + assert torch.backends.mps.is_available(), "No MPS backend is available!" + logging.info("Using MPS GPU acceleration") + return torch.device("mps") + if device_str == "xpu": + torch.xpu.is_available() + devices = torch.xpu.device_count() + is_available = devices > 0 + assert is_available, logging.info("No XPU backend is available") + torch.xpu.memory_stats() + logging.info("Using XPU GPU acceleration") + return torch.device("xpu") + + logging.info("Using CPU") + return torch.device("cpu") + + +dtype_dict = {"float32": torch.float32, "float64": torch.float64} + + +def set_default_dtype(dtype: str) -> None: + torch.set_default_dtype(dtype_dict[dtype]) + + +def get_change_of_basis() -> torch.Tensor: + return CartesianTensor("ij=ji").reduced_tensor_products().change_of_basis + + +def spherical_to_cartesian(t: torch.Tensor, change_of_basis: torch.Tensor): + # Optionally handle device mismatch + if change_of_basis.device != t.device: + change_of_basis = change_of_basis.to(t.device) + return torch.einsum("ijk,...i->...jk", change_of_basis, t) + + +def cartesian_to_spherical(t: torch.Tensor): + """ + Convert cartesian notation to spherical notation + """ + stress_cart_tensor = CartesianTensor("ij=ji") + stress_rtp = stress_cart_tensor.reduced_tensor_products() + return stress_cart_tensor.to_cartesian(t, rtp=stress_rtp) + + +def voigt_to_matrix(t: torch.Tensor): + """ + Convert voigt notation to matrix notation + :param t: (6,) tensor or (3, 3) tensor or (9,) tensor + :return: (3, 3) tensor + """ + if t.shape == (3, 3): + return t + if t.shape == (6,): + return torch.tensor( + [ + [t[0], t[5], t[4]], + [t[5], t[1], t[3]], + [t[4], t[3], t[2]], + ], + dtype=t.dtype, + ) + if t.shape == (9,): + return t.view(3, 3) + + raise ValueError( + f"Stress tensor must be of shape (6,) or (3, 3), or (9,) but has shape {t.shape}" + ) + + +def init_wandb(project: str, entity: str, name: str, config: dict, directory: str): + import wandb + + wandb.init( + project=project, + entity=entity, + name=name, + config=config, + dir=directory, + resume="allow", + ) + + +@contextmanager +def default_dtype(dtype: Union[torch.dtype, str]): + """Context manager for configuring the default_dtype used by torch + + Args: + dtype (torch.dtype|str): the default dtype to use within this context manager + """ + init = torch.get_default_dtype() + if isinstance(dtype, str): + set_default_dtype(dtype) + else: + torch.set_default_dtype(dtype) + + yield + + torch.set_default_dtype(init) diff --git a/models/mace/mace/tools/train.py b/models/mace/mace/tools/train.py new file mode 100644 index 0000000000000000000000000000000000000000..eccd63578d31278864e78151e176bd4e05b9171d --- /dev/null +++ b/models/mace/mace/tools/train.py @@ -0,0 +1,767 @@ +########################################################################################### +# Training script +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import dataclasses +import logging +import time +from collections import defaultdict +from contextlib import nullcontext +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +import torch.distributed +from torch.nn.parallel import DistributedDataParallel +from torch.optim import LBFGS +from torch.optim.swa_utils import SWALR, AveragedModel +from torch.utils.data import DataLoader +from torch.utils.data.distributed import DistributedSampler +from torch_ema import ExponentialMovingAverage +from torchmetrics import Metric + +from mace.cli.visualise_train import TrainingPlotter + +from . import torch_geometric +from .checkpoint import CheckpointHandler, CheckpointState +from .torch_tools import to_numpy +from .utils import ( + MetricsLogger, + compute_mae, + compute_q95, + compute_rel_mae, + compute_rel_rmse, + compute_rmse, + filter_nonzero_weight, +) + +# NOTE Add tqdm (...) +from tqdm import tqdm + + +@dataclasses.dataclass +class SWAContainer: + model: AveragedModel + scheduler: SWALR + start: int + loss_fn: torch.nn.Module + + +def valid_err_log( + valid_loss, + eval_metrics, + logger, + log_errors, + epoch=None, + valid_loader_name="Default", +): + eval_metrics["mode"] = "eval" + eval_metrics["epoch"] = epoch + eval_metrics["head"] = valid_loader_name + logger.log(eval_metrics) + if epoch is None: + inintial_phrase = "Initial" + else: + inintial_phrase = f"Epoch {epoch}" + if log_errors == "PerAtomRMSE": + error_e = eval_metrics["rmse_e_per_atom"] * 1e3 + error_f = eval_metrics["rmse_f"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_E_per_atom={error_e:8.2f} meV, RMSE_F={error_f:8.2f} meV / A" + ) + elif ( + log_errors == "PerAtomRMSEstressvirials" + and eval_metrics["rmse_stress"] is not None + ): + error_e = eval_metrics["rmse_e_per_atom"] * 1e3 + error_f = eval_metrics["rmse_f"] * 1e3 + error_stress = eval_metrics["rmse_stress"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_E_per_atom={error_e:8.2f} meV, RMSE_F={error_f:8.2f} meV / A, RMSE_stress={error_stress:8.2f} meV / A^3", + ) + elif ( + log_errors == "PerAtomRMSEstressvirials" + and eval_metrics["rmse_virials_per_atom"] is not None + ): + error_e = eval_metrics["rmse_e_per_atom"] * 1e3 + error_f = eval_metrics["rmse_f"] * 1e3 + error_virials = eval_metrics["rmse_virials_per_atom"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_E_per_atom={error_e:8.2f} meV, RMSE_F={error_f:8.2f} meV / A, RMSE_virials_per_atom={error_virials:8.2f} meV", + ) + elif ( + log_errors == "PerAtomMAEstressvirials" + and eval_metrics["mae_stress_per_atom"] is not None + ): + error_e = eval_metrics["mae_e_per_atom"] * 1e3 + error_f = eval_metrics["mae_f"] * 1e3 + error_stress = eval_metrics["mae_stress"] * 1e3 + logging.info( + f"{inintial_phrase}: loss={valid_loss:8.8f}, MAE_E_per_atom={error_e:8.2f} meV, MAE_F={error_f:8.2f} meV / A, MAE_stress={error_stress:8.2f} meV / A^3" + ) + elif ( + log_errors == "PerAtomMAEstressvirials" + and eval_metrics["mae_virials_per_atom"] is not None + ): + error_e = eval_metrics["mae_e_per_atom"] * 1e3 + error_f = eval_metrics["mae_f"] * 1e3 + error_virials = eval_metrics["mae_virials"] * 1e3 + logging.info( + f"{inintial_phrase}: loss={valid_loss:8.8f}, MAE_E_per_atom={error_e:8.2f} meV, MAE_F={error_f:8.2f} meV / A, MAE_virials={error_virials:8.2f} meV" + ) + elif log_errors == "TotalRMSE": + error_e = eval_metrics["rmse_e"] * 1e3 + error_f = eval_metrics["rmse_f"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_E={error_e:8.2f} meV, RMSE_F={error_f:8.2f} meV / A", + ) + elif log_errors == "PerAtomMAE": + error_e = eval_metrics["mae_e_per_atom"] * 1e3 + error_f = eval_metrics["mae_f"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, MAE_E_per_atom={error_e:8.2f} meV, MAE_F={error_f:8.2f} meV / A", + ) + elif log_errors == "TotalMAE": + error_e = eval_metrics["mae_e"] * 1e3 + error_f = eval_metrics["mae_f"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, MAE_E={error_e:8.2f} meV, MAE_F={error_f:8.2f} meV / A", + ) + elif log_errors == "DipoleRMSE": + error_mu = eval_metrics["rmse_mu_per_atom"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_MU_per_atom={error_mu:8.2f} mDebye", + ) + elif log_errors == "DipolePolarRMSE": + error_mu = eval_metrics["rmse_mu_per_atom"] * 1e3 + error_polarizability = eval_metrics["rmse_polarizability_per_atom"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:.4f}, RMSE_MU_per_atom={error_mu:.2f} me A, RMSE_polarizability_per_atom={error_polarizability:.2f} me A^2 / V", + ) + elif log_errors == "EnergyDipoleRMSE": + error_e = eval_metrics["rmse_e_per_atom"] * 1e3 + error_f = eval_metrics["rmse_f"] * 1e3 + error_mu = eval_metrics["rmse_mu_per_atom"] * 1e3 + logging.info( + f"{inintial_phrase}: head: {valid_loader_name}, loss={valid_loss:8.8f}, RMSE_E_per_atom={error_e:8.2f} meV, RMSE_F={error_f:8.2f} meV / A, RMSE_Mu_per_atom={error_mu:8.2f} mDebye", + ) + + +def train( + model: torch.nn.Module, + loss_fn: torch.nn.Module, + train_loader: DataLoader, + valid_loaders: Dict[str, DataLoader], + optimizer: torch.optim.Optimizer, + lr_scheduler: torch.optim.lr_scheduler.ExponentialLR, + start_epoch: int, + max_num_epochs: int, + patience: int, + checkpoint_handler: CheckpointHandler, + logger: MetricsLogger, + eval_interval: int, + output_args: Dict[str, bool], + device: torch.device, + log_errors: str, + swa: Optional[SWAContainer] = None, + ema: Optional[ExponentialMovingAverage] = None, + max_grad_norm: Optional[float] = 10.0, + log_wandb: bool = False, + distributed: bool = False, + save_all_checkpoints: bool = False, + plotter: TrainingPlotter = None, + distributed_model: Optional[DistributedDataParallel] = None, + train_sampler: Optional[DistributedSampler] = None, + rank: Optional[int] = 0, +): + lowest_loss = np.inf + valid_loss = np.inf + patience_counter = 0 + swa_start = True + keep_last = False + if log_wandb: + import wandb + + if max_grad_norm is not None: + logging.info(f"Using gradient clipping with tolerance={max_grad_norm:.3f}") + + logging.info("") + logging.info("===========TRAINING===========") + logging.info("Started training, reporting errors on validation set") + logging.info("Loss metrics on validation set") + epoch = start_epoch + + # log validation loss before _any_ training + for valid_loader_name, valid_loader in valid_loaders.items(): + valid_loss_head, eval_metrics = evaluate( + model=model, + loss_fn=loss_fn, + data_loader=valid_loader, + output_args=output_args, + device=device, + ) + valid_err_log( + valid_loss_head, eval_metrics, logger, log_errors, None, valid_loader_name + ) + valid_loss = valid_loss_head # consider only the last head for the checkpoint + + # variable used for broadcast by rank == 0 if epoch loop is exited early, e.g. patience + exit_now = torch.zeros(1, device=device) if distributed else None + while epoch < max_num_epochs: + # LR scheduler and SWA update + if swa is None or epoch < swa.start: + if epoch > start_epoch: + lr_scheduler.step( + metrics=valid_loss + ) # Can break if exponential LR, TODO fix that! + else: + if swa_start: + logging.info("Changing loss based on Stage Two Weights") + lowest_loss = np.inf + swa_start = False + keep_last = True + loss_fn = swa.loss_fn + swa.model.update_parameters(model) + if epoch > start_epoch: + swa.scheduler.step() + + # Train + if distributed: + train_sampler.set_epoch(epoch) + if "ScheduleFree" in type(optimizer).__name__: + optimizer.train() + train_one_epoch( + model=model, + loss_fn=loss_fn, + data_loader=train_loader, + optimizer=optimizer, + epoch=epoch, + output_args=output_args, + max_grad_norm=max_grad_norm, + ema=ema, + logger=logger, + device=device, + distributed=distributed, + distributed_model=distributed_model, + rank=rank, + ) + if distributed: + torch.distributed.barrier() + + # Validate + if epoch % eval_interval == 0: + model_to_evaluate = ( + model if distributed_model is None else distributed_model + ) + param_context = ( + ema.average_parameters() if ema is not None else nullcontext() + ) + if "ScheduleFree" in type(optimizer).__name__: + optimizer.eval() + with param_context: + wandb_log_dict = {} + for valid_loader_name, valid_loader in valid_loaders.items(): + valid_loss_head, eval_metrics = evaluate( + model=model_to_evaluate, + loss_fn=loss_fn, + data_loader=valid_loader, + output_args=output_args, + device=device, + ) + if rank == 0: + valid_err_log( + valid_loss_head, + eval_metrics, + logger, + log_errors, + epoch, + valid_loader_name, + ) + if log_wandb: + wandb_log_dict[valid_loader_name] = { + "epoch": epoch, + "valid_loss": valid_loss_head, + "valid_rmse_e_per_atom": eval_metrics[ + "rmse_e_per_atom" + ], + "valid_rmse_f": eval_metrics["rmse_f"], + } + if plotter and epoch % plotter.plot_frequency == 0: + try: + plotter.plot(epoch, model_to_evaluate, rank) + except Exception as e: # pylint: disable=broad-except + logging.debug(f"Plotting failed: {e}") + valid_loss = ( + valid_loss_head # consider only the last head for the checkpoint + ) + if log_wandb: + wandb.log(wandb_log_dict) + if rank == 0: + if valid_loss >= lowest_loss: + patience_counter += 1 + if patience_counter >= patience: + if swa is not None and epoch < swa.start: + logging.info( + f"Stopping optimization after {patience_counter} epochs without improvement and starting Stage Two" + ) + epoch = swa.start + else: + logging.info( + f"Stopping optimization after {patience_counter} epochs without improvement" + ) + if exit_now is not None: + exit_now.fill_(1) + if save_all_checkpoints: + param_context = ( + ema.average_parameters() + if ema is not None + else nullcontext() + ) + with param_context: + checkpoint_handler.save( + state=CheckpointState(model, optimizer, lr_scheduler), + epochs=epoch, + keep_last=True, + ) + else: + lowest_loss = valid_loss + patience_counter = 0 + param_context = ( + ema.average_parameters() if ema is not None else nullcontext() + ) + with param_context: + checkpoint_handler.save( + state=CheckpointState(model, optimizer, lr_scheduler), + epochs=epoch, + keep_last=keep_last, + ) + keep_last = False or save_all_checkpoints + if distributed: + torch.distributed.barrier() + if exit_now is not None: + torch.distributed.broadcast(exit_now, src=0) + if exit_now == 1: + break + + epoch += 1 + + logging.info("Training complete") + + +def train_one_epoch( + model: torch.nn.Module, + loss_fn: torch.nn.Module, + data_loader: DataLoader, + optimizer: torch.optim.Optimizer, + epoch: int, + output_args: Dict[str, bool], + max_grad_norm: Optional[float], + ema: Optional[ExponentialMovingAverage], + logger: MetricsLogger, + device: torch.device, + distributed: bool, + distributed_model: Optional[DistributedDataParallel] = None, + rank: Optional[int] = 0, +) -> None: + model_to_train = model if distributed_model is None else distributed_model + + if isinstance(optimizer, LBFGS): + _, opt_metrics = take_step_lbfgs( + model=model_to_train, + loss_fn=loss_fn, + data_loader=data_loader, + optimizer=optimizer, + ema=ema, + output_args=output_args, + max_grad_norm=max_grad_norm, + device=device, + distributed=distributed, + rank=rank, + ) + opt_metrics["mode"] = "opt" + opt_metrics["epoch"] = epoch + if rank == 0: + logger.log(opt_metrics) + else: + for batch in tqdm(data_loader, desc="Training"): + _, opt_metrics = take_step( + model=model_to_train, + loss_fn=loss_fn, + batch=batch, + optimizer=optimizer, + ema=ema, + output_args=output_args, + max_grad_norm=max_grad_norm, + device=device, + ) + opt_metrics["mode"] = "opt" + opt_metrics["epoch"] = epoch + if rank == 0: + logger.log(opt_metrics) + + +def take_step( + model: torch.nn.Module, + loss_fn: torch.nn.Module, + batch: torch_geometric.batch.Batch, + optimizer: torch.optim.Optimizer, + ema: Optional[ExponentialMovingAverage], + output_args: Dict[str, bool], + max_grad_norm: Optional[float], + device: torch.device, +) -> Tuple[float, Dict[str, Any]]: + start_time = time.time() + batch = batch.to(device) + batch_dict = batch.to_dict() + + + def closure(): + optimizer.zero_grad(set_to_none=True) + output = model( + batch_dict, + training=True, + compute_force=output_args["forces"], + compute_virials=output_args["virials"], + compute_stress=output_args["stress"], + ) + + # Our loss + #force_loss, energy_loss, loss = loss_fn(pred=output, ref=batch, do_eval=True) + #print(f'Energy Loss: {energy_loss.item()} Force Loss: {force_loss.item()}') + loss = loss_fn(pred=output, ref=batch) + + + + loss.backward() + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_grad_norm) + + return loss + + loss = closure() + optimizer.step() + + if ema is not None: + ema.update() + + loss_dict = { + "loss": to_numpy(loss), + "time": time.time() - start_time, + } + + return loss, loss_dict + + +def take_step_lbfgs( + model: torch.nn.Module, + loss_fn: torch.nn.Module, + data_loader: DataLoader, + optimizer: torch.optim.Optimizer, + ema: Optional[ExponentialMovingAverage], + output_args: Dict[str, bool], + max_grad_norm: Optional[float], + device: torch.device, + distributed: bool, + rank: int, +) -> Tuple[float, Dict[str, Any]]: + start_time = time.time() + logging.debug( + f"Max Allocated: {torch.cuda.max_memory_allocated() / 1024**2:.2f} MB" + ) + + total_sample_count = 0 + for batch in data_loader: + total_sample_count += batch.num_graphs + + if distributed: + global_sample_count = torch.tensor(total_sample_count, device=device) + torch.distributed.all_reduce( + global_sample_count, op=torch.distributed.ReduceOp.SUM + ) + total_sample_count = global_sample_count.item() + + signal = torch.zeros(1, device=device) if distributed else None + + def closure(): + if distributed: + if rank == 0: + signal.fill_(1) + torch.distributed.broadcast(signal, src=0) + + for param in model.parameters(): + torch.distributed.broadcast(param.data, src=0) + + optimizer.zero_grad(set_to_none=True) + total_loss = torch.tensor(0.0, device=device) + + # Process each batch and then collect the results we pass to the optimizer + for batch in data_loader: + batch = batch.to(device) + batch_dict = batch.to_dict() + output = model( + batch_dict, + training=True, + compute_force=output_args["forces"], + compute_virials=output_args["virials"], + compute_stress=output_args["stress"], + ) + batch_loss = loss_fn(pred=output, ref=batch) + batch_loss = batch_loss * (batch.num_graphs / total_sample_count) + + batch_loss.backward() + total_loss += batch_loss + + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_grad_norm) + + if distributed: + torch.distributed.all_reduce(total_loss, op=torch.distributed.ReduceOp.SUM) + return total_loss + + if distributed: + if rank == 0: + loss = optimizer.step(closure) + signal.fill_(0) + torch.distributed.broadcast(signal, src=0) + else: + while True: + # Other ranks wait for signals from rank 0 + torch.distributed.broadcast(signal, src=0) + if signal.item() == 0: + break + if signal.item() == 1: + loss = closure() + + for param in model.parameters(): + torch.distributed.broadcast(param.data, src=0) + else: + loss = optimizer.step(closure) + + if ema is not None: + ema.update() + + loss_dict = { + "loss": to_numpy(loss), + "time": time.time() - start_time, + } + + return loss, loss_dict + + +def evaluate( + model: torch.nn.Module, + loss_fn: torch.nn.Module, + data_loader: DataLoader, + output_args: Dict[str, bool], + device: torch.device, +) -> Tuple[float, Dict[str, Any]]: + for param in model.parameters(): + param.requires_grad = False + + metrics = MACELoss(loss_fn=loss_fn).to(device) + + start_time = time.time() + for batch in tqdm(data_loader, desc="Validation"): + batch = batch.to(device) + batch_dict = batch.to_dict() + output = model( + batch_dict, + training=False, + compute_force=output_args["forces"], + compute_virials=output_args["virials"], + compute_stress=output_args["stress"], + ) + avg_loss, aux = metrics(batch, output) + + avg_loss, aux = metrics.compute() + aux["time"] = time.time() - start_time + metrics.reset() + + for param in model.parameters(): + param.requires_grad = True + + return avg_loss, aux + + +class MACELoss(Metric): + def __init__(self, loss_fn: torch.nn.Module): + super().__init__() + self.loss_fn = loss_fn + self.add_state("total_loss", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("num_data", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("E_computed", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("delta_es", default=[], dist_reduce_fx="cat") + self.add_state("delta_es_per_atom", default=[], dist_reduce_fx="cat") + self.add_state("Fs_computed", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("fs", default=[], dist_reduce_fx="cat") + self.add_state("delta_fs", default=[], dist_reduce_fx="cat") + self.add_state( + "stress_computed", default=torch.tensor(0.0), dist_reduce_fx="sum" + ) + self.add_state("delta_stress", default=[], dist_reduce_fx="cat") + self.add_state( + "virials_computed", default=torch.tensor(0.0), dist_reduce_fx="sum" + ) + self.add_state("delta_virials", default=[], dist_reduce_fx="cat") + self.add_state("delta_virials_per_atom", default=[], dist_reduce_fx="cat") + self.add_state("Mus_computed", default=torch.tensor(0.0), dist_reduce_fx="sum") + self.add_state("mus", default=[], dist_reduce_fx="cat") + self.add_state("delta_mus", default=[], dist_reduce_fx="cat") + self.add_state("delta_mus_per_atom", default=[], dist_reduce_fx="cat") + self.add_state( + "polarizability_computed", default=torch.tensor(0.0), dist_reduce_fx="sum" + ) + self.add_state("delta_polarizability", default=[], dist_reduce_fx="cat") + self.add_state( + "delta_polarizability_per_atom", default=[], dist_reduce_fx="cat" + ) + + def update(self, batch, output): # pylint: disable=arguments-differ + loss = self.loss_fn(pred=output, ref=batch) + self.total_loss += loss + self.num_data += batch.num_graphs + + if output.get("energy") is not None and batch.energy is not None: + self.delta_es.append(batch.energy - output["energy"]) + self.delta_es_per_atom.append( + (batch.energy - output["energy"]) / (batch.ptr[1:] - batch.ptr[:-1]) + ) + self.E_computed += filter_nonzero_weight( + batch, self.delta_es, batch.weight, batch.energy_weight + ) + if output.get("forces") is not None and batch.forces is not None: + self.fs.append(batch.forces) + self.delta_fs.append(batch.forces - output["forces"]) + self.Fs_computed += filter_nonzero_weight( + batch, + self.delta_fs, + batch.weight, + batch.forces_weight, + spread_atoms=True, + ) + if output.get("stress") is not None and batch.stress is not None: + self.delta_stress.append(batch.stress - output["stress"]) + self.stress_computed += filter_nonzero_weight( + batch, self.delta_stress, batch.weight, batch.stress_weight + ) + if output.get("virials") is not None and batch.virials is not None: + self.delta_virials.append(batch.virials - output["virials"]) + self.delta_virials_per_atom.append( + (batch.virials - output["virials"]) + / (batch.ptr[1:] - batch.ptr[:-1]).view(-1, 1, 1) + ) + self.virials_computed += filter_nonzero_weight( + batch, self.delta_virials, batch.weight, batch.virials_weight + ) + if output.get("dipole") is not None and batch.dipole is not None: + self.mus.append(batch.dipole) + self.delta_mus.append(batch.dipole - output["dipole"]) + self.delta_mus_per_atom.append( + (batch.dipole - output["dipole"]) + / (batch.ptr[1:] - batch.ptr[:-1]).unsqueeze(-1) + ) + self.Mus_computed += filter_nonzero_weight( + batch, + self.delta_mus, + batch.weight, + batch.dipole_weight, + spread_quantity_vector=False, + ) + if ( + output.get("polarizability") is not None + and batch.polarizability is not None + ): + self.delta_polarizability.append( + batch.polarizability - output["polarizability"] + ) + self.delta_polarizability_per_atom.append( + (batch.polarizability - output["polarizability"]) + / (batch.ptr[1:] - batch.ptr[:-1]).unsqueeze(-1).unsqueeze(-1) + ) + self.polarizability_computed += filter_nonzero_weight( + batch, + self.delta_polarizability, + batch.weight, + batch.polarizability_weight, + spread_quantity_vector=False, + ) + + def convert(self, delta: Union[torch.Tensor, List[torch.Tensor]]) -> np.ndarray: + if isinstance(delta, list): + delta = torch.cat(delta) + return to_numpy(delta) + + def compute(self): + + class NoneMultiply: + def __mul__(self, other): + return NoneMultiply() + + def __rmul__(self, other): + return NoneMultiply() + + def __imul__(self, other): + return NoneMultiply() + + def __format__(self, format_spec): + return str(None) + + aux = defaultdict(NoneMultiply) + aux["loss"] = to_numpy(self.total_loss / self.num_data).item() + if self.E_computed: + delta_es = self.convert(self.delta_es) + delta_es_per_atom = self.convert(self.delta_es_per_atom) + aux["mae_e"] = compute_mae(delta_es) + aux["mae_e_per_atom"] = compute_mae(delta_es_per_atom) + aux["rmse_e"] = compute_rmse(delta_es) + aux["rmse_e_per_atom"] = compute_rmse(delta_es_per_atom) + aux["q95_e"] = compute_q95(delta_es) + if self.Fs_computed: + fs = self.convert(self.fs) + delta_fs = self.convert(self.delta_fs) + aux["mae_f"] = compute_mae(delta_fs) + aux["rel_mae_f"] = compute_rel_mae(delta_fs, fs) + aux["rmse_f"] = compute_rmse(delta_fs) + aux["rel_rmse_f"] = compute_rel_rmse(delta_fs, fs) + aux["q95_f"] = compute_q95(delta_fs) + if self.stress_computed: + delta_stress = self.convert(self.delta_stress) + aux["mae_stress"] = compute_mae(delta_stress) + aux["rmse_stress"] = compute_rmse(delta_stress) + aux["q95_stress"] = compute_q95(delta_stress) + if self.virials_computed: + delta_virials = self.convert(self.delta_virials) + delta_virials_per_atom = self.convert(self.delta_virials_per_atom) + aux["mae_virials"] = compute_mae(delta_virials) + aux["rmse_virials"] = compute_rmse(delta_virials) + aux["rmse_virials_per_atom"] = compute_rmse(delta_virials_per_atom) + aux["q95_virials"] = compute_q95(delta_virials) + if self.Mus_computed: + mus = self.convert(self.mus) + delta_mus = self.convert(self.delta_mus) + delta_mus_per_atom = self.convert(self.delta_mus_per_atom) + aux["mae_mu"] = compute_mae(delta_mus) + aux["mae_mu_per_atom"] = compute_mae(delta_mus_per_atom) + aux["rel_mae_mu"] = compute_rel_mae(delta_mus, mus) + aux["rmse_mu"] = compute_rmse(delta_mus) + aux["rmse_mu_per_atom"] = compute_rmse(delta_mus_per_atom) + aux["rel_rmse_mu"] = compute_rel_rmse(delta_mus, mus) + aux["q95_mu"] = compute_q95(delta_mus) + if self.polarizability_computed: + delta_polarizability = self.convert(self.delta_polarizability) + delta_polarizability_per_atom = self.convert( + self.delta_polarizability_per_atom + ) + aux["mae_polarizability"] = compute_mae(delta_polarizability) + aux["mae_polarizability_per_atom"] = compute_mae( + delta_polarizability_per_atom + ) + aux["rmse_polarizability"] = compute_rmse(delta_polarizability) + aux["rmse_polarizability_per_atom"] = compute_rmse( + delta_polarizability_per_atom + ) + aux["q95_polarizability"] = compute_q95(delta_polarizability) + + return aux["loss"], aux diff --git a/models/mace/mace/tools/utils.py b/models/mace/mace/tools/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ae2c9bf3f2e840e3b05bffa716511e67fc49df6a --- /dev/null +++ b/models/mace/mace/tools/utils.py @@ -0,0 +1,207 @@ +########################################################################################### +# Statistics utilities +# Authors: Ilyes Batatia, Gregor Simm, David Kovacs +# This program is distributed under the MIT License (see MIT.md) +########################################################################################### + +import json +import logging +import os +import sys +from pathlib import Path +from typing import Any, Dict, Iterable, Optional, Sequence, Union + +import numpy as np +import torch + +from .torch_tools import to_numpy + + +def compute_mae(delta: np.ndarray) -> float: + return np.mean(np.abs(delta)).item() + + +def compute_rel_mae(delta: np.ndarray, target_val: np.ndarray) -> float: + target_norm = np.mean(np.abs(target_val)) + return np.mean(np.abs(delta)).item() / (target_norm + 1e-9) * 100 + + +def compute_rmse(delta: np.ndarray) -> float: + return np.sqrt(np.mean(np.square(delta))).item() + + +def compute_rel_rmse(delta: np.ndarray, target_val: np.ndarray) -> float: + target_norm = np.sqrt(np.mean(np.square(target_val))).item() + return np.sqrt(np.mean(np.square(delta))).item() / (target_norm + 1e-9) * 100 + + +def compute_q95(delta: np.ndarray) -> float: + return np.percentile(np.abs(delta), q=95) + + +def compute_c(delta: np.ndarray, eta: float) -> float: + return np.mean(np.abs(delta) < eta).item() + + +def get_tag(name: str, seed: int) -> str: + return f"{name}_run-{seed}" + + +def setup_logger( + level: Union[int, str] = logging.INFO, + tag: Optional[str] = None, + directory: Optional[str] = None, + rank: Optional[int] = 0, +): + # Create a logger + logger = logging.getLogger() + logger.setLevel(logging.DEBUG) # Set to DEBUG to capture all levels + + # Create formatters + formatter = logging.Formatter( + "%(asctime)s.%(msecs)03d %(levelname)s: %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + # Add filter for rank + logger.addFilter(lambda _: rank == 0) + + # Create console handler + ch = logging.StreamHandler(stream=sys.stdout) + ch.setLevel(level) + ch.setFormatter(formatter) + logger.addHandler(ch) + + if directory is not None and tag is not None: + os.makedirs(name=directory, exist_ok=True) + + # Create file handler for non-debug logs + main_log_path = os.path.join(directory, f"{tag}.log") + fh_main = logging.FileHandler(main_log_path) + fh_main.setLevel(level) + fh_main.setFormatter(formatter) + logger.addHandler(fh_main) + + # Create file handler for debug logs + debug_log_path = os.path.join(directory, f"{tag}_debug.log") + fh_debug = logging.FileHandler(debug_log_path) + fh_debug.setLevel(logging.DEBUG) + fh_debug.setFormatter(formatter) + fh_debug.addFilter(lambda record: record.levelno >= logging.DEBUG) + logger.addHandler(fh_debug) + + +class AtomicNumberTable: + def __init__(self, zs: Sequence[int]): + self.zs = zs + + def __len__(self) -> int: + return len(self.zs) + + def __str__(self): + return f"AtomicNumberTable: {tuple(s for s in self.zs)}" + + def index_to_z(self, index: int) -> int: + return self.zs[index] + + def z_to_index(self, atomic_number: str) -> int: + return self.zs.index(atomic_number) + + +def get_atomic_number_table_from_zs(zs: Iterable[int]) -> AtomicNumberTable: + z_set = set() + for z in zs: + z_set.add(z) + return AtomicNumberTable(sorted(list(z_set))) + + +def atomic_numbers_to_indices( + atomic_numbers: np.ndarray, z_table: AtomicNumberTable +) -> np.ndarray: + to_index_fn = np.vectorize(z_table.z_to_index) + return to_index_fn(atomic_numbers) + + +class UniversalEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, np.integer): + return int(o) + if isinstance(o, np.floating): + return float(o) + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, torch.Tensor): + return to_numpy(o) + return json.JSONEncoder.default(self, o) + + +class MetricsLogger: + def __init__(self, directory: str, tag: str) -> None: + self.directory = directory + self.filename = tag + ".txt" + self.path = os.path.join(self.directory, self.filename) + + def log(self, d: Dict[str, Any]) -> None: + os.makedirs(name=self.directory, exist_ok=True) + with open(self.path, mode="a", encoding="utf-8") as f: + f.write(json.dumps(d, cls=UniversalEncoder)) + f.write("\n") + + +# pylint: disable=abstract-method, arguments-differ +class LAMMPS_MP(torch.autograd.Function): + @staticmethod + def forward(ctx, *args): + feats, data = args # unpack + ctx.vec_len = feats.shape[-1] + ctx.data = data + out = torch.empty_like(feats) + data.forward_exchange(feats, out, ctx.vec_len) + return out + + @staticmethod + def backward(ctx, *grad_outputs): + (grad,) = grad_outputs # unpack + gout = torch.empty_like(grad) + ctx.data.reverse_exchange(grad, gout, ctx.vec_len) + return gout, None + + +def get_cache_dir() -> Path: + # get cache dir from XDG_CACHE_HOME if set, otherwise appropriate default + return Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "mace" + + +def filter_nonzero_weight( + batch, + quantity_l, + weight, + quantity_weight, + spread_atoms=False, + spread_quantity_vector=True, +) -> float: + quantity = quantity_l[-1] + # repeat with interleaving for per-atom quantities + if spread_atoms: + weight = torch.repeat_interleave( + weight, batch.ptr[1:] - batch.ptr[:-1] + ).unsqueeze(-1) + quantity_weight = torch.repeat_interleave( + quantity_weight, batch.ptr[1:] - batch.ptr[:-1] + ).unsqueeze(-1) + + # repeat for additional dimensions + if len(quantity.shape) > 1: + repeats = [1] + list(quantity.shape[1:]) + view = [-1] + [1] * (len(quantity.shape) - 1) + weight = weight.view(*view).repeat(*repeats) + if spread_quantity_vector: + quantity_weight = quantity_weight.view(*view).repeat(*repeats) + filtered_q = quantity[weight * quantity_weight > 0] + + if len(filtered_q) == 0: + quantity_l.pop() + return 0.0 + + quantity_l[-1] = filtered_q + return 1.0 diff --git a/models/mace/runs/mace_mh_1_42_run-42.model b/models/mace/runs/mace_mh_1_42_run-42.model new file mode 100644 index 0000000000000000000000000000000000000000..da80b5fa2c5d78be4636d2c4b0510022263093eb --- /dev/null +++ b/models/mace/runs/mace_mh_1_42_run-42.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdc5be8e2925cbc9aa61d708d080cf34ec313bae10aa04eb9ca621fd54ab36bb +size 28766104 diff --git a/models/mace/runs/mace_seed42.model b/models/mace/runs/mace_seed42.model new file mode 100644 index 0000000000000000000000000000000000000000..34561d81d5a01746e8ab122f598cb0ada1f95f9a --- /dev/null +++ b/models/mace/runs/mace_seed42.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:424d742e10d9e6a9ef4e8c846e173c8c9c01abad79fe4ab47d4ba07cf84c7727 +size 13750002 diff --git a/models/mace/runs/matpes_seed42_run-42.model b/models/mace/runs/matpes_seed42_run-42.model new file mode 100644 index 0000000000000000000000000000000000000000..bc292429b3e3b936b0ec78fcee655fb0dfda599b --- /dev/null +++ b/models/mace/runs/matpes_seed42_run-42.model @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c607bb8a8190931531f812fc2cdb6dad0236f35488ca52fc89077de4956f6ca4 +size 7012544 diff --git a/models/mace/scripts/run_mace.sh b/models/mace/scripts/run_mace.sh new file mode 100755 index 0000000000000000000000000000000000000000..66accc26260c4346d3208afe4e729ecb899c57d9 --- /dev/null +++ b/models/mace/scripts/run_mace.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +set -euo pipefail + + + +# ---------------------------- +# User settings (edit these) +# ---------------------------- +MACE_REPO_DIR="" # repo root (contains "mace/" folder) +NAME="new_testing" +CHECKPOINT_DIR="new_models/" + +TRAIN_FILE="" +VALID_FILE="" +TEST_FILE="" + +# If you want a fixed validation set instead of valid_fraction, replace VALID_FRACTION with VALID_FILE below. +VALID_FRACTION="0.5" +# VALID_FILE="valid.xyz" # uncomment and use this instead of --valid_fraction if desired + + + + +# From the docs screenshot: +CONFIG_TYPE_WEIGHTS='{"Default":1.0}' + +# IMPORTANT: Replace these example E0s with your actual values if needed. +# The screenshot shows a dict with element keys; keep as a single-quoted string. +E0S='{1: 2.467478445, 6: 8.0273263225, 8: 3.334308855, 22: 4.879036065}' +#E0S='{1: 1.0, 6: 1.0, 8: 1.0, 22: 1.0}' +ATOMIC_NUMBERS='[1,6,8,22]' + +MODEL="MACE" +HIDDEN_IRREPS="128x0e + 128x1o" +R_MAX="6.0" +BATCH_SIZE="2" +VALID_BATCH_SIZE="2" +START_SWA="1200" +EMA_DECAY="0.99" +SEED="11" + +DEVICE="cuda" +MAX_NUM_EPOCHS="10" + +# ---------------------------- +# Detect number of visible GPUs +# ---------------------------- +if command -v nvidia-smi &> /dev/null; then + NGPUS="$(nvidia-smi -L | wc -l | tr -d ' ')" +else + NGPUS="1" +fi +NGPUS="${NGPUS:-1}" + +echo "Using NGPUS=${NGPUS}" +echo "MACE_REPO_DIR=${MACE_REPO_DIR}" +echo "Train=${TRAIN_FILE} Test=${TEST_FILE}" +echo "Checkpoint_dir=${CHECKPOINT_DIR}" + +# ---------------------------- +# Go to repo root and expose it to Python +cd "${MACE_REPO_DIR}" +export PYTHONPATH="$(pwd):${PYTHONPATH:-}" + +unset SLURM_JOB_NODELIST SLURM_NTASKS SLURM_NTASKS_PER_NODE SLURM_NNODES SLURM_LOCALID SLURM_PROCID SLURM_NODEID SLURM_JOB_ID + +# ---------------------------- +# Per-run output folders +# ---------------------------- +RUN_TAG="${NAME}_run-${SEED}" +RUN_DIR="${CHECKPOINT_DIR}/${RUN_TAG}" + +RUN_CHECKPOINTS_DIR="${RUN_DIR}/checkpoints" +RUN_MODELS_DIR="${RUN_DIR}/models" +RUN_RESULTS_DIR="${RUN_DIR}/results" +RUN_LOGS_DIR="${RUN_DIR}/logs" +RUN_WANDB_DIR="${RUN_DIR}/wandb" + +mkdir -p \ + "${RUN_CHECKPOINTS_DIR}" \ + "${RUN_MODELS_DIR}" \ + "${RUN_RESULTS_DIR}" \ + "${RUN_LOGS_DIR}" \ + "${RUN_WANDB_DIR}" + +echo "RUN_DIR=${RUN_DIR}" + +WAND_PROJECT="testing_mace_wandb" + +# ---------------------------- +# Launch training +# ---------------------------- +torchrun --standalone --nproc_per_node=$NGPUS -m mace.cli.run_train \ + --name="${NAME}" \ + --seed="${SEED}" \ + --checkpoints_dir="${RUN_CHECKPOINTS_DIR}" \ + --model_dir="${RUN_MODELS_DIR}" \ + --results_dir="${RUN_RESULTS_DIR}" \ + --log_dir="${RUN_LOGS_DIR}" \ + \ + \ + --max_num_epochs="${MAX_NUM_EPOCHS}" \ + --train_file="${TRAIN_FILE}" \ + --valid_file="${VALID_FILE}" \ + --test_file="${TEST_FILE}" \ + \ + \ + --hidden_irreps="${HIDDEN_IRREPS}" \ + --config_type_weights="${CONFIG_TYPE_WEIGHTS}" \ + --E0s="${E0S}" \ + --model="${MODEL}" \ + --r_max="${R_MAX}" \ + \ + \ + --batch_size="${BATCH_SIZE}" \ + --valid_batch_size="${VALID_BATCH_SIZE}" \ + --ema \ + --ema_decay="${EMA_DECAY}" \ + --amsgrad \ + --device="${DEVICE}" \ + --atomic_numbers "${ATOMIC_NUMBERS}" \ + \ + \ + --energy_key "energy" \ + --forces_key "forces" \ + \ + \ + --loss "ours_mae" \ + --forces_weight 1.0 \ + --energy_weight 1.0 \ + --default_dtype "float32" \ + \ + \ + --distributed \ + \ + \ + --wandb \ + --wandb_dir "${RUN_WANDB_DIR}" \ + --wandb_project "${WAND_PROJECT}" \ + --wandb_name "${NAME}" \ + \ + --swa \ + diff --git a/models/matris/run_matris_calc.py b/models/matris/run_matris_calc.py index 90bdcf97bc492e4fdd406f9d8120763a6e0fdf66..9bade924f97e0d80de78f2d986e51336211c4337 100644 --- a/models/matris/run_matris_calc.py +++ b/models/matris/run_matris_calc.py @@ -109,14 +109,14 @@ class MatRISCalculator(Calculator): if __name__ == "__main__": - input_structure = "/proj/cvl/users/x_anmka/cataliust_icml/calc_results/run_001/ML_relaxed_POSCAR" + input_structure = "" device = "cuda" if torch.cuda.is_available() else "cpu" atoms = read(input_structure) calc = MatRISCalculator( # Option 1: your fine-tuned checkpoint - checkpoint="/proj/cvl/users/x_anmka/research/matris/ddp_checkpoints_matris/matris_seed2000_no_cons_ddp_new_loss_higher_weights_2026-05-03_22-02-31/best_epoch=0021_val_loss=0.171674_val_e_atom=0.007562_val_f_comp=0.026773.pt", + checkpoint="", # Option 2 instead: # model_name="matris_10m_mp",