MACE is being rewritten toward v1.0. The rewrite happens in the open on the
mace-reforge branch, and
tracks progress on its board.
v0.3.x remains the supported line. It keeps taking bug fixes, and nothing
about installing or using MACE changes today. v1.0 will not preserve code
compatibility, and trained checkpoints will migrate through an explicit
converter rather than loading directly; functionality is preserved.
Planning to contribute while this is under way? Read
CONTRIBUTING.md first. It says what we can accept into v0.3
and what belongs in v1. The answer depends on whether we can carry your change
over.
MACE provides fast and accurate machine learning interatomic potentials with higher order equivariant message passing.
This repository contains the MACE reference implementation developed by
Ilyes Batatia, Gregor Simm, David Kovacs, and the group of Gabor Csanyi, and friends (see Contributors).
Also available:
MACE in JAX, currently about 2x times faster at evaluation, but training is recommended in Pytorch for optimal performances.
MACE layers for constructing higher order equivariant graph neural networks for arbitrary 3D point clouds.
Make sure to install PyTorch. Please refer to the official PyTorch installation for the installation instructions. Select the appropriate options for your system.
Installation from PyPI
This is the recommended way to install MACE.
pip install --upgrade pip
pip install mace-torch
Note: The homonymous package on PyPI has nothing to do with this one.
To train a MACE model, you can use the mace_run_train script, which should be in the usual place that pip places binaries (or you can explicitly run python3 <path_to_cloned_dir>/mace/cli/run_train.py)
To give a specific validation set, use the argument --valid_file. To set a larger batch size for evaluating the validation set, specify --valid_batch_size.
To control the model's size, you need to change --hidden_irreps. For most applications, the recommended default model size is --hidden_irreps='256x0e' (meaning 256 invariant messages) or --hidden_irreps='128x0e + 128x1o'. If the model is not accurate enough, you can include higher order features, e.g., 128x0e + 128x1o + 128x2e, or increase the number of channels to 256. It is also possible to specify the model using the --num_channels=128 and --max_L=1keys.
It is usually preferred to add the isolated atoms to the training set, rather than reading in their energies through the command line like in the example above. To label them in the training set, set config_type=IsolatedAtom in their info fields.
When training a model from scratch, if you prefer not to use or do not know the energies of the isolated atoms, you can use the option --E0s="average" which estimates the atomic energies using least squares regression. Note that using fitted E0s corresponds to fitting the deviations of the atomic energies from the average, rather than fitting the atomization energy (which is the case when using isolated-atom E0s), and this will most likely result in less stable potentials for molecular dynamics applications.
When finetuning foundation models, you can use --E0s="estimated", which estimates the atomic reference energies by solving a linear system that optimally corrects the foundation model's predictions on the training data. This approach computes E0 corrections by first running the foundation model on all training configurations, computing the prediction errors (reference energies minus predicted energies), and then solving a least-squares system to find optimal E0 corrections for each element. This is preferable in general over the 'average' option.
If the keyword --stage_two (previously called swa) is enabled, the energy weight of the loss is increased for the last ~20% of the training epochs (from --start_stage_two epochs). This setting usually helps lower the energy errors.
The precision can be changed using the keyword --default_dtype, the default is float64 but float32 gives a significant speed-up (usually a factor of x2 in training).
The keywords --batch_size and --max_num_epochs should be adapted based on the size of the training set. The batch size should be increased when the number of training data increases, and the number of epochs should be decreased. An heuristic for initial settings, is to consider the number of gradient update constant to 200 000, which can be computed as $\text{max-num-epochs}*\frac{\text{num-configs-training}}{\text{batch-size}}$.
The code can handle training set with heterogeneous labels, for example containing both bulk structures with stress and isolated molecules. In this example, to make the code ignore stress on molecules, append to your molecules configuration a config_stress_weight = 0.0.
By default, a figure displaying the progression of loss and RMSEs during training, along with a scatter plot of the model's inferences on the train, validation, and test sets, will be generated in the results folder at the end of training. This can be disabled using --plot False. To track these metrics throughout training (excluding inference on the test set), you can enable periodic plotting for the train and validation sets by specifying --plot_frequency N, which updates the plots every Nth epoch.
Apple Silicon GPU acceleration
To use Apple Silicon GPU acceleration make sure to install the latest PyTorch version and specify --device=mps.
Multi-GPU training
For multi-GPU training, use the --distributed flag. This will use PyTorch's DistributedDataParallel module to train the model on multiple GPUs. Combine with on-line data loading for large datasets (see below). An example slurm script can be found in mace/scripts/distributed_example.sbatch.
YAML configuration
Option to parse all or some arguments using a YAML is available. For example, to train a model using the arguments above, you can create a YAML file your_configs.yaml with the following content:
If you have a large dataset that might not fit into the GPU memory it is recommended to preprocess the data on a CPU and use on-line dataloading for training the model. To preprocess your dataset specified as an xyz file run the preprocess_data.py script. An example is given here:
To see all options and a little description of them run python ./mace/scripts/preprocess_data.py --help . The script will create a number of HDF5 files in the processed_data folder which can be used for training. There will be one folder for training, one for validation and a separate one for each config_type in the test set. To train the model use the run_train.py script as follows:
If you would like to use MACE with Weights and Biases to log your experiments simply install with
pip install ./mace[wandb]
And specify the necessary keyword arguments (--wandb, --wandb_project, --wandb_entity, --wandb_name, --wandb_log_hypers)
Pretrained Foundation Models
We provide a series of pretrained foundation models for various applications. These models can be used directly for inference, or as a starting point for fine-tuning on a new dataset.
Foundation models are a rapidly evolving field. Please look at the MACE-MP GitHub repository and the MACE-OFF23 GitHub repository for the latest releases.
Very good cross domain performance on surfaces/bulk/molecules.
ASL
MACE-MP: Materials Project Force Fields
We have collaborated with the Materials Project (MP) to train a universal MACE potential covering 89 elements on 1.6 M bulk crystals in the MPTrj dataset selected from MP relaxation trajectories.
The models are releaed on GitHub at https://github.com/ACEsuit/mace-foundations.
If you use them please cite our paper which also contains an large range of example applications and benchmarks.
[!CAUTION]
The MACE-MP models are trained on MPTrj raw DFT energies from VASP outputs, and are not directly comparable to the MP's DFT energies or CHGNet's energies, which have been applied MP2020Compatibility corrections for some transition metal oxides, fluorides (GGA/GGA+U mixing corrections), and 14 anions species (anion corrections). For more details, please refer to the MP Documentation and MP2020Compatibility.yaml.
Example usage in ASE
from mace.calculators import mace_mp
from ase import build
atoms = build.molecule('H2O')
calc = mace_mp(model="medium", dispersion=False, default_dtype="float32", device='cuda')
atoms.calc = calc
print(atoms.get_potential_energy())
MACE-OFF: Transferable Organic Force Fields
There is a series (small, medium, large) transferable organic force fields. These can be used for the simulation of organic molecules, crystals and molecular liquids, or as a starting point for fine-tuning on a new dataset. The models are released under the ASL license.
The models are releaed on GitHub at https://github.com/ACEsuit/mace-off.
If you use them please cite our paper which also contains detailed benchmarks and example applications.
Example usage in ASE
from mace.calculators import mace_off
from ase import build
atoms = build.molecule('H2O')
calc = mace_off(model="medium", device='cuda')
atoms.calc = calc
print(atoms.get_potential_energy())
MACE-Polar: Electrostatics foundation models
PolarMACE checkpoints are electrostatics foundation models for molecular chemistry, trained on the OMol25 dataset.
For usage, outputs, and training/finetuning details, see the PolarMACE guide:
To finetune one of the mace-mp-0 foundation model, you can use the mace_run_train script with the extra argument --foundation_model=model_type. For example to finetune the small model on a new dataset, you can use:
Other options are "medium" and "large", or the path to a foundation model.
If you want to finetune another model, the model will be loaded from the path provided --foundation_model=$path_model, all the hypers will be extracted automatically.
Caching
By default automatically downloaded models, like mace_mp, mace_off and data for fine tuning, end up in ~/.cache/mace. The path can be changed by using
the environment variable XDG_CACHE_HOME. When set, the new cache path expands to $XDG_CACHE_HOME/.cache/mace
What changes in MACE v1.0
MACE v1.0 is a rewrite, and it does not carry every surface of the 0.3.x line.
The options, commands, classes and output keys that go away, or that survive
only under a more general mechanism, now say so when you use them: they raise a
FutureWarning and write the same text to the run log. Nothing changes about
what they do in 0.3.x.
A warning fires only for something you asked for. A flag warns when you pass it,
not when it merely has a default, and a command warns when you run it. To see
the whole list at once, including the parts that have no single moment to warn
at, run:
python -m mace.tools.deprecation
Each entry says whether v1.0 removes the feature outright or replaces it with a
more general mechanism, and why. The v1.0 migration guide will carry the new
spellings; these warnings deliberately do not name v1 commands, because the
last 0.3.x release ships before the v1 CLI exists.
Every message starts with MACE v1.0, so one filter silences all of them:
module="mace" does not work here, because the warning is attributed to the
caller that passed the option rather than to a module inside the package.
Development
Before opening a pull request, read CONTRIBUTING.md: while the
v1 rewrite is under way, where a change belongs depends on what it touches.
This project uses pre-commit to execute code formatting and linting on commit.
We also use black, isort, pylint, and mypy.
We recommend setting up your development environment by installing the dev packages
into your python environment:
pip install -e ".[dev]"
pre-commit install
The second line will initialise pre-commit to automaticaly run code checks on commit.
We have CI set up to check this, but we highly recommend that you run those commands
before you commit (and push) to avoid accidentally committing bad code.
Running the tests
The test suite is organised by what each test needs to run:
Directory
Contents
Extra requirements
tests/unit
fast, CPU-only unit tests
—
tests/workflows
end-to-end CLI trainings (subprocess)
—
tests/backends
e3nn ↔ cueq/oeq parity and converters
cueq / oeq extras (GPU for execution)
tests/extensions/<x>
polar / les / torchsim / schedulefree
the extension's dependency
tests/foundations
foundation-model loaders (downloads)
network, opt-in
tests/integrations/<x>
LAMMPS (and future integrations)
see tests/integrations/README.md
tests/benchmarks
performance measurements
GPU
Capabilities a test needs (a GPU, an optional package, network access) are
pytest markers enforced by tests/conftest.py: locally, tests whose
requirements are missing are skipped; CI jobs export MACE_REQUIRE_CAPS to
turn those skips into failures. Network downloads are opt-in via
MACE_CI_ALLOW_NETWORK=1.
pytest tests/unit # quick check
pytest tests -m "not slow and not network" # smoke over everything runnable
Every CI test job runs through the .github/actions/run-tests composite
action, whose inputs (tests, markers, require-caps, allow-network,
splits, coverage, ...) map 1:1 to pytest flags — to reproduce a job
locally, read its with: block in the workflow and run the equivalent pytest
command (e.g. the unit job is pytest tests/unit -m "not slow" -n auto).
We are happy to accept pull requests under an MIT license. Please copy/paste the license text as a comment into your pull request.
Contributing
Bug fixes are always welcome, on both lines. New features are best built
directly in v1; where that is not possible they are accepted into v0.3 if they
are self-contained and tested on numbers we can reproduce. Changes to core or
shared code go into v1 only. See CONTRIBUTING.md for the
details and the reasoning.
References
If you use this code, please cite our papers:
@inproceedings{Batatia2022mace,
title={{MACE}: Higher Order Equivariant Message Passing Neural Networks for Fast and Accurate Force Fields},
author={Ilyes Batatia and David Peter Kovacs and Gregor N. C. Simm and Christoph Ortner and Gabor Csanyi},
booktitle={Advances in Neural Information Processing Systems},
editor={Alice H. Oh and Alekh Agarwal and Danielle Belgrave and Kyunghyun Cho},
year={2022},
url={https://openreview.net/forum?id=YPpSngE-ZU}
}
@misc{Batatia2022Design,
title = {The Design Space of E(3)-Equivariant Atom-Centered Interatomic Potentials},
author = {Batatia, Ilyes and Batzner, Simon and Kov{\'a}cs, D{\'a}vid P{\'e}ter and Musaelian, Albert and Simm, Gregor N. C. and Drautz, Ralf and Ortner, Christoph and Kozinsky, Boris and Cs{\'a}nyi, G{\'a}bor},
year = {2022},
number = {arXiv:2205.06643},
eprint = {2205.06643},
eprinttype = {arxiv},
doi = {10.48550/arXiv.2205.06643},
archiveprefix = {arXiv}
}