科研 Skill

MACE机器学习势训练

mace-training

Covers training MACE machine-learned interatomic potentials: extxyz dataset preparation, isolated-atom energies, train/val/test splitting. Use for MACE-specific MLP training workflows.

发布者 Codar安全审核通过v0.1.0更新于 2026-11-18

SKILL.md

MACE Training

Description

This skill covers the full workflow for training MACE (Message-passing Atomic Cluster Expansion) machine-learned interatomic potentials: DFT dataset preparation in extxyz format, isolated atom energy handling, train/validation/test splitting, model architecture selection, loss weighting, training execution, validation error analysis, and deployment to ASE and LAMMPS. Invoke this skill when building a new MACE model from DFT reference data, when diagnosing training failures, or when deciding whether MACE or another MLP architecture is appropriate for a given application.

Domain Context

MACE is an equivariant graph neural network potential that combines two theoretical frameworks: the Atomic Cluster Expansion (ACE) body-ordered basis and E(3)-equivariant message passing. The key physical insight is that the potential energy surface must be invariant to rotations, reflections, and translations of the entire system, while forces — being vectors — must transform equivariantly under rotations. MACE enforces this by representing atomic features as geometric tensors (irreducible representations of SO(3)) and contracting them via Clebsch-Gordan tensor products.

Practical consequences of this architecture:

  • Higher body order per layer: A single MACE interaction block effectively encodes higher-body-order interactions than a standard message-passing layer, because the tensor product at each node combines information from multiple neighbors simultaneously. This allows MACE to reach DFT accuracy with fewer layers than SchNet or DimeNet.
  • Data efficiency: Equivariance acts as a physical inductive bias. A model that does not need to learn rotational symmetry from data requires fewer training structures to reach a given accuracy. MACE typically achieves force MAE < 50 meV/Å on well-sampled datasets with 1,000–10,000 structures.
  • The dataset defines the model's validity domain: MACE is a local potential with a fixed cutoff radius. It cannot extrapolate to compositions, coordination environments, or bond lengths absent from the training set. A low test error on held-out data does not guarantee stability in MD if the MD trajectory visits configurations outside the training distribution.
  • Reference energy convention: DFT total energies are extensive and include core-electron contributions that are not physically meaningful on their own. MACE subtracts isolated atom reference energies (E0) from all structure energies before training. The E0 values must be computed at the same level of DFT theory (functional, pseudopotential, cutoff) as the training data. Errors in E0 shift the predicted formation energy of every structure by a constant and destabilize model training.
  • Stress tensor convention: MACE uses ASE's stress convention: Voigt-ordered Cauchy stress in eV/ų, with tensile stress positive (opposite to engineering convention). VASP outputs stress in kBar with compression positive. The conversion factor and sign flip are a common source of silent dataset errors.

When to Use This Skill

  • Building a system-specific MLP for a new chemical space (new composition, phase, or environment) where universal potentials are insufficiently accurate.
  • Generating a potential for large-scale MD of a well-defined material system where the DFT reference level is fixed.
  • Fine-tuning a universal MACE model (MACE-MP-0, MACE-OFF) to a specific system with modest additional DFT data.
  • Active learning loops where MACE committee models drive DFT oracle queries.
  • Replacing a computationally expensive classical force field for a system outside its validated transferability range.

When Not to Use This Skill

  • When a validated universal potential (MACE-MP-0, CHGNet, M3GNet) already covers your system — universal potentials often achieve acceptable accuracy at zero additional DFT cost; always benchmark them first.
  • For highly reactive systems with complex charge transfer or excited-state dynamics — MACE does not model electronic degrees of freedom. ReaxFF or DFT-MD is more appropriate when bond formation/breaking involves charge redistribution not captured by the training geometry.
  • When fewer than ~200–500 well-converged DFT structures are available — a MACE model trained on very few structures will likely overfit or produce an unstable potential. Expand the dataset via active learning first.
  • For properties requiring long-range electrostatics (ionic solids, polar surfaces, charged defects) — standard MACE uses a local cutoff and has no long-range electrostatic model. MACE-with-long-range extensions or dispersion corrections are required for ionic materials. [EXPERT REVIEW NEEDED]
  • When the target property is an excited-state or electronic property — MLPs fit the ground-state Born-Oppenheimer surface only.

Core Concepts

  • Extxyz format: The standard flat-file format for atomistic ML datasets. Each frame stores the atom count, a comment line with key-value metadata (Lattice, Properties, energy, stress, pbc), and per-atom lines with species and positions. Forces are stored as a per-atom property. This is ASE's native format and the MACE training input.
  • Isolated atom energies (E0): DFT total energy of a single atom of each species in a large vacuum box at the same DFT level as the training data. Subtracted from all structure energies to give formation-like energies centered near zero. Errors in E0 produce systematic shifts in predicted energies. The MACE --E0s="average" option estimates E0 by linear regression from the dataset — convenient but less physically principled.
  • Cutoff radius (r_max): The distance beyond which atom pairs are not included in the neighbor graph. Typical values: 4–6 Å for metallic systems; 5–7 Å for covalent/molecular systems. A larger cutoff captures more long-range interactions but increases cost as O(r_max³). The cutoff must be smaller than half the shortest periodic cell dimension.
  • Angular momentum (max_ell or L): Maximum angular momentum quantum number for the geometric tensor features. L=2 gives up to d-like features; L=3 gives f-like features. Higher L increases expressiveness and cost. L=3 is recommended for metallic systems; L=2 often sufficient for covalent. [EXPERT REVIEW NEEDED]
  • Correlation order (correlation or ν): Body order of the ACE basis used per interaction block. correlation=3 (3-body) is standard. Higher correlation captures more angular complexity but increases cost exponentially.
  • Hidden irreps (hidden_irreps): The channel dimensions and symmetry types of the hidden layer features, specified in e3nn notation: e.g., "128x0e + 128x1o + 128x2e" means 128 scalar (0e), 128 vector (1o), and 128 rank-2 even-parity (2e) channels. Larger hidden irreps increase model capacity and cost.
  • Number of interaction blocks (num_interactions): Depth of the message-passing network. Typically 2–3. Each block increases the effective receptive field by one cutoff radius.
  • Loss function: L = w_E · L_E + w_F · L_F + w_S · L_S, where L_E is per-atom energy RMSE, L_F is per-component force RMSE, and L_S is per-component stress RMSE. Weights (--energy_weight, --forces_weight, --stress_weight) must be tuned. High forces_weight relative to energy_weight is standard for MLPs used in MD (forces drive dynamics); stress weights are required for NPT MD.
  • Exponential moving average (EMA): EMA of model weights (--ema, --ema_decay=0.99) is used for the final model checkpoint. EMA smooths the weight trajectory and typically gives better test performance than the raw optimizer snapshot.
  • Scaling: --scaling="rms_forces_scaling" normalizes the model output by the RMS force in the training set. This makes the loss approximately unit-independent and improves training stability.
  • Precision: Float32 is standard for training on GPU; float64 improves numerical stability for energy-sensitive applications but roughly doubles memory and compute. Always use float64 for final validation on held-out data.

Key Workflows

Full steps for each part are in references/key-workflows/; open the one you need:

Common Failure Modes

FailureSymptomLikely CauseDiagnosticFix
Unit mismatch in datasetEnergy MAE remains high (> 1 eV/atom) despite training; forces correct but energies wrong by a constant offsetEnergy in dataset is in Ry or Ha instead of eV, or distances in bohr instead of ÅCheck raw values: eV/atom for typical metals is −4 to −12 eV/atom; if values are ×13.6 off, units are RyConvert all energies to eV and distances to Å before writing extxyz; use ASE unit conversion constants
Wrong E0 reference energiesSystematic energy offset per species; formation energies wrong; training diverges or plateaus at high energy lossE0 computed with wrong spin state (spin-unpolarized atom vs. correct ground state), wrong functional, or wrong cell sizeCompare --E0s DFT values to atomic reference data; check that atom DFT runs used same ENCUT, POTCAR, and ISMEAR as datasetRecompute E0 for each species as spin-polarized, large-box DFT at identical settings; or use --E0s="average" as fallback
Stress sign/convention errorStress MAE high (> 1 GPa for near-equilibrium structures) despite correct forces; NPT MD box expands or collapses unrealisticallyVASP kBar stress converted without sign flip; tensile/compressive convention mismatchCheck: at equilibrium geometry, stress should be ≈ 0. If all components have wrong sign, apply stress *= -1Apply −kBar × KBAR_TO_EV_A3 conversion (see Workflow 1); validate on equilibrium structure:
Data leakage: train/test correlationTest error unrealistically low; production MD fails earlier than expected; MLP does not generalizeRandom split applied to trajectory frames — adjacent frames are nearly identical, so test set is trivially predictedSplit by trajectory, by rattled-origin, or by config_type rather than randomlyUse split_by_config_type (Workflow 2); or explicitly group trajectory frames and split groups
Force-dominated loss collapseEnergy MAE diverges during training; model correctly predicts forces but energy is unphysical; NPT density wrong--forces_weight set too high relative to --energy_weight (e.g., 100:1); model ignores energy lossPlot energy loss and force loss separately; if energy loss is > 100× force loss per epoch, ratio is wrongReduce --forces_weight to 10–20; use --loss="weighted" with --config_type_weights for fine control
Species absent from trainingCrash during MD on a structure containing a species not seen in training; or garbage forces for that speciesA chemical species appears in the deployment structure but has zero or very few training examplesCount per-species frames in training set; check which species appear only in testAdd DFT calculations covering the missing species in all expected bonding environments; re-train
Unstable MD despite low test errorMD trajectory diverges (energy explosion) within ps; MACE test MAE is < 50 meV/ÅModel evaluated on near-equilibrium structures; MD explores high-temperature or defect configurations outside training distributionMonitor max force during MD; extract frames where force > 10 eV/Å and compare to training set distributionExpand dataset with active learning: run MACE-MD, extract uncertain frames, compute DFT, retrain
Batch size too large for GPUCUDA out-of-memory error during trainingNumber of atoms × batch_size exceeds GPU VRAMStart with --batch_size=4; increase until OOM; for 16 GB GPU, typical limit is batch_size=8–16 for 100-atom structuresReduce --batch_size; use --gradient_clip and --accumulate_gradient_batches for effective larger batches

Best Practices

  • Never include unconverged DFT calculations in the training set. A single frame with wrong forces (from an unconverged SCF) can corrupt training. Always filter by converged_electronic = True and check for NELM reached warnings before including a VASP calculation.
  • Validate the stress sign convention on a known equilibrium structure before training. A near-equilibrium bulk crystal at 0 K should have all Voigt stress components within ±0.01 eV/ų. If the diagonal components are uniformly wrong in sign, apply the sign correction.
  • Always include diverse configurations in the training set. A model trained only on equilibrium bulk structures will fail for surfaces, defects, liquids, and distorted geometries encountered during MD. A minimum viable dataset for MD includes: equilibrium bulk, volumetrically strained bulk (±5%), rattled bulk at target temperatures, and any special environments (surfaces, defects) present in production MD.
  • Use committee models for uncertainty estimation during active learning. Train 4–8 MACE models from different random seeds on the same dataset. Frames where committee force predictions disagree (force std > threshold) are candidates for DFT re-computation.
  • Check per-species and per-config_type errors, not just the global test MAE. A model with excellent overall force MAE may have 10× higher error for a rare species or a minority configuration type that is critical for the target application.
  • Run an NVE energy conservation test before any production NPT MD. Integrate 10,000 steps of NVE MD from the equilibrated structure. Energy drift > 1 meV/atom/ns indicates extrapolation, a timestep too large for the MACE forces, or a sign/units error. [EXPERT REVIEW NEEDED]
  • Use float64 for final validation even if float32 was used for training. Force and energy errors computed at float32 precision can mask small systematic biases.
  • Record the MACE version, model file checksum, and training command in every project README. MACE's default architecture and training defaults have changed between versions; a model trained with v0.3 may produce different behavior when evaluated with a different API version.

Integration with Other Skills

  • dft-dataset-generation: Covers the systematic generation of DFT training configurations via rattling, AIMD snapshots, and active learning oracle calls. Workflow 1 above shows the conversion step; that skill covers the upstream calculation design.
  • dft-convergence: The DFT settings used to generate training data (ENCUT, k-mesh, ISMEAR, SIGMA) must be uniform across the entire dataset. That skill's convergence protocol defines the parameter set that is frozen for dataset generation.
  • vasp-workflow: VASP is the most common DFT oracle for MACE training data. Workflow 1 above parses VASP vasprun.xml output. The ISIF=2 and PREC=Accurate settings from that skill are required for accurate stress labels.
  • quantum-espresso: When QE is used as the DFT oracle, forces are in Ry/bohr and must be converted to eV/Å. Stress in QE is also in Ry/bohr³ with potentially different sign conventions. Use ASE's QE parser to handle unit conversion automatically.
  • lammps-workflow: Workflow 6 above shows MACE deployment in LAMMPS. The no_domain_decomposition flag and element-type mapping requirements described there are prerequisites for correct MACE-LAMMPS deployment.
  • md-equilibration: After MACE deployment, the same equilibration protocol (minimize → NVT ramp → NPT) applies. The NVE energy conservation test described there is the primary check for MACE timestep stability before production.
  • active-learning-mlp: MACE committee models are the uncertainty signal in active learning loops. That skill covers the full loop: uncertainty filtering, DFT oracle selection, dataset augmentation, and retraining protocol.
  • mlp-validation: Formal MLP validation goes beyond test-set MAE to include RDF comparison, phonon spectrum, elastic constants, vacancy formation energies, and MD stability. Consult that skill after training before deploying MACE in production.
  • mlp-to-lammps: Covers compilation of LAMMPS with the MACE pair style, model file format requirements, and parallel scaling limitations of no_domain_decomposition.
  • uncertainty-mlp: Committee models are one uncertainty approach; that skill covers alternatives (deep ensembles, last-layer uncertainty, conformal prediction) and when each is appropriate.
  • fine-tuning-mlp: When a universal MACE model (MACE-MP-0) is close but not accurate enough, fine-tuning on system-specific DFT data is often more efficient than training from scratch. That skill covers the fine-tuning workflow and hyperparameter transfer.
  • universal-potentials: Before committing to training a system-specific MACE model, benchmark MACE-MP-0, CHGNet, or M3GNet on the target system. If universal potential errors are within acceptable tolerances, system-specific training is unnecessary.

Key References

  1. Batatia, I., et al. (2022). MACE: Higher order equivariant message passing neural networks for fast and accurate force fields. Advances in Neural Information Processing Systems, 35. https://arxiv.org/abs/2206.07697
  2. Batatia, I., et al. (2022). The design space of E(3)-equivariant atom-centred interatomic potentials. arXiv:2205.06643. https://arxiv.org/abs/2205.06643
  3. Drautz, R. (2019). Atomic cluster expansion for accurate and transferable interatomic potentials. Physical Review B, 99(1), 014104. https://doi.org/10.1103/PhysRevB.99.014104
  4. Kovács, D. P., et al. (2021). Linear atomic cluster expansion force fields for organic molecules: Beyond RMSE. Journal of Chemical Theory and Computation, 17(12), 7696–7711. https://doi.org/10.1021/acs.jctc.1c00647
  5. Batatia, I., et al. (2023). A foundation model for atomistic simulation of chemistry and materials. arXiv:2401.00096. https://arxiv.org/abs/2401.00096

示例提示词

我想用这批extxyz格式的DFT数据训练一个MACE原子间势模型。

所属插件

计算材料学:第一性原理与原子模拟面向计算材料研究:DFT 与第一性原理(VASP、Quantum ESPRESSO、CP2K、AiiDA)、缺陷/表面/声子/弹性常数、机器学习势函数训练与验证、分子动力学与增强采样、晶体性质图神经网络与生成模型。

安装该插件会一并获得同领域的 35 个 Skill / MCP。

同插件的其他科研 Skill

常见问题

MACE机器学习势训练能做什么?

Covers training MACE machine-learned interatomic potentials: extxyz dataset preparation, isolated-atom energies, train/val/test splitting. Use for MACE-specific MLP training workflows。

如何安装MACE机器学习势训练?

在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「MACE机器学习势训练」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。

MACE机器学习势训练需要哪些权限?

该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。

MACE机器学习势训练经过官方审核吗?

是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。