Post

Mace训练_2

Mace训练_2

内容来源

https://colab.research.google.com/drive/1ZrTuTvavXiCxTFyjBV4GqlARxgFwYAtX https://colab.research.google.com/drive/1oCSVfMhWrqHTeHbKgUSQN9hTKxLzoNyb

把其中的训练部分的代码整理一下

config.yml 示例

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
# config.yml

model: "MACE"
num_channels: 128
max_L: 1
r_max: 5.0
name: "mace"
model_dir: "MACE_models"
log_dir: "MACE_models"
checkpoints_dir: "MACE_models"
results_dir: "MACE_models"
train_file: "./train.xyz"
valid_file: "./validation.xyz"
test_file: "./test.xyz"
energy_key: "energy"
forces_key: "forces"
E0s: "average"
# device: cpu
device: cuda
batch_size: 1
max_num_epochs: 300
lr: 0.01
swa: True
swa_lr: 0.001
energy_weight: 1.0
forces_weight: 100.0
swa_energy_weight: 1000.0
seed: 42
enable_cueq: False

参数说明

In order to train a MACE potential, one needs to create a configuration file that specifies three kind of information:

  1. Choice your model hyper-parameters.
  2. Specification of the data.
  3. Selection of your optimization parameters.

These informations are required in order to call the mace training script called mace_run_train.

Hyper-parameters

用来确定模型的初始参数

–num_channels

Number of channels. Determines the size of the model. The recommended value is –num_channels=128 but other potential values are 64 for a faster model or 256 for a large but more accurate model.

–max_L

Symmetry of the messages. Determines the symmetry of the messages. A value of –max_L=0 means MACE will pass only invariant information between neigborhoods. It is the parameter that affects the most the computational speed and the accuracy of the model. –max_L=0 are the fastest model, use them to train cheap model to run large and long simulations. –max_L=1 is the default value, it is a good compromise between speed and accuracy. It is recommended to start with that value for a new project. –max_L=2 are the most accurate models, use them to train very accurate but slower models.

–r_max

The cutoff radius. The cutoff used to create the local environment in each layer. r_max=5.0 means atoms separated by a distance of more than 5.0 Å do not directly communicate in a single layer. When the model has multiple message-passing layers, atoms further than 5.0 Å can still communicate through later messages if intermediate proxy atoms exist. The effective receptive field of the model is num_interactions * r_max. The larger the r_max, the slower the model will be. It is recommended to use values between 4.0 Å and 7.0 Å.

下面的参数建议保持默认

  • --num_interactions: Message-passing layers

    Controls the number of message-passing layers in the model. It should always be 2, and it is recommended not to modify it.

  • --correlation: The order of the many-body expansion

    The body order that MACE induces at each layer. Choosing --correlation=3 will create basis functions of up to 4-body (ijkl) indices, for each layer. If the model has multiple layers, the effective correlation order is higher. For example, a two-layer MACE with --correlation=3 has an effective body order of 13.

  • --max_ell: Angular resolution

    The angular resolution describes how well the model can describe angles. This is controlled by max_ell of the spherical harmonics basis (not to be confused with max_L). Larger values will result in more accurate but slower models. The default is max_ell=3, which is appropriate in most cases.

Optimization and data management parameters

下面这些参数用来控制优化过程以及选择数据集

–name

the name of the model

–model_dir, –log_dir, –checkpoints_dir, –results_dir

directory paths. These are the directories where each type of file is saved. For simplicity, we will save all files in the same directory

–train_file

These are the configurations that will be use to train the model

–valid_file

An alternative way to choose the validation set is by using the –valid_fraction keyword. These data configs are used to estimate the model accuracy during training, but not for parameter optimization. The validation set also controls the stopping of the training. At each –eval_interval the model is tested on the validation set. The evaluation of these configs takes place in batches, which can be controlled by –valid_batch_size. If the accuracy of the model stops improving on the validation set for –patience number of epochs, the model will undergo early stopping.

–test_file

This set is entirely independent and only gets evaluated at the end of the training process to estimate the model accuracy on an independent set.

–E0s

Controls how E0s should be determined. The strongly recommended approach is to add these values to the training set with config_type=IsolatedAtom in atoms.info and set E0s=”isolated”. If these values are not available, MACE can estimate them by least square regression over the available data E0s=”average” which can lead to unintended consequences depending on how representative the data is.

如果使用 E0s=”isolated”,需要在准备数据集时加入孤立原子的能量计算,也是这里建议的做法

–energy_key, –forces_key

This key must coincide with the ase.Atoms.info[key]/ase.Atoms.arrays[key] where the energies and forces are stored in the ase.Atoms object. It is very important to get them right.

–device

Can be CPU (cpu), GPU (cuda) or Apple Silicon (mps). Here we will use cuda since the GPU will be significantly faster than the CPU.

–batch_size

Number of configs used to compute the gradients for each full update of the network parameters. This training strategy is called stochastic gradient descent because only a subset of the data (batch_size) is used to change the parameters at each update.

–max_num_epochs

An epoch is completed when the entire training data has been used once in updating the weights batch by batch. A new epoch begins, and the process repeats.

–swa

During training you will notice energy errors are at first much higher than force errors, MACE implements a special protocol that increases the weight on the energy in the loss function (–swa_energy_weight) once the forces are sufficiently accurate. The starting epoch for this special protocol can be controlled by changing –start_swa.

模型训练前期,力的权重要大于能量,所以模型会优先优化力,然后当力优化的不错的时候,提高能量的权重,优化能量,就是此处的意思

–seed

Useful for preparing committee of models.

训练代码

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
import warnings
warnings.filterwarnings("ignore")
from mace.cli.run_train import main as mace_run_train_main
import sys
import logging
from ase.io import read, write
import numpy as np
from ase import Atoms

train_proportion = 0.8
validation_proportion = 0.1
test_proportion = 0.1

# 读取全部结构
all_data = read("./mace.xyz", index=":")
print(f"共有{len(all_data)}个结构")

# 划分数据集
def split_all_data(strus, trp, vp, tsp):
    data = strus.copy()
    np.random.seed(42)
    np.random.shuffle(data)

    n = len(data)
    tr = int(n * trp)
    v  = int(n * vp)
    return data[:tr], data[tr:tr+v], data[tr+v:]

trd, vd, ted = split_all_data(all_data, train_proportion, validation_proportion, test_proportion)

write("train.xyz", trd)
write("validation.xyz", vd)
write("test.xyz", ted)


def train_mace(config_file_path):
    logging.getLogger().handlers.clear()
    sys.argv = ["program", "--config", config_file_path]
    mace_run_train_main()

train_mace("./config.yml")
This post is licensed under CC BY 4.0 by the author.