科研 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.
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_ellorL): 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 (
correlationorν): 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. Highforces_weightrelative toenergy_weightis 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:
- Workflow 1: Dataset preparation from DFT outputs —
references/key-workflows/01-workflow-1-dataset-preparation-from-dft-outputs.md: Convert DFT calculation outputs (VASP or QE) to extxyz format. This is the most error-prone step and the most common source of silent dataset failures. - Workflow 2: Train/validation/test splitting —
references/key-workflows/02-workflow-2-train-validation-test-splitting.md: Atomistic datasets are not i.i.d. — structures from the same MD trajectory or rattled from the same crystal are highly correlated. Random splitting leaks correlated structures into train and test, producing optimistic test errors. - Workflow 3: MACE training — hyperparameter choices —
references/key-workflows/03-workflow-3-mace-training-hyperparameter-choices.md: Architecture selection guide: - Workflow 4: Training monitoring and convergence diagnostics —
references/key-workflows/04-workflow-4-training-monitoring-and-convergence-d.md - Workflow 5: Validation error analysis and outlier inspection —
references/key-workflows/05-workflow-5-validation-error-analysis-and-outlier.md - Workflow 6: Deployment to ASE and LAMMPS —
references/key-workflows/06-workflow-6-deployment-to-ase-and-lammps.md
Common Failure Modes
| Failure | Symptom | Likely Cause | Diagnostic | Fix |
|---|---|---|---|---|
| Unit mismatch in dataset | Energy MAE remains high (> 1 eV/atom) despite training; forces correct but energies wrong by a constant offset | Energy 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 Ry | Convert all energies to eV and distances to Å before writing extxyz; use ASE unit conversion constants |
| Wrong E0 reference energies | Systematic energy offset per species; formation energies wrong; training diverges or plateaus at high energy loss | E0 computed with wrong spin state (spin-unpolarized atom vs. correct ground state), wrong functional, or wrong cell size | Compare --E0s DFT values to atomic reference data; check that atom DFT runs used same ENCUT, POTCAR, and ISMEAR as dataset | Recompute E0 for each species as spin-polarized, large-box DFT at identical settings; or use --E0s="average" as fallback |
| Stress sign/convention error | Stress MAE high (> 1 GPa for near-equilibrium structures) despite correct forces; NPT MD box expands or collapses unrealistically | VASP kBar stress converted without sign flip; tensile/compressive convention mismatch | Check: at equilibrium geometry, stress should be ≈ 0. If all components have wrong sign, apply stress *= -1 | Apply −kBar × KBAR_TO_EV_A3 conversion (see Workflow 1); validate on equilibrium structure: |
| Data leakage: train/test correlation | Test error unrealistically low; production MD fails earlier than expected; MLP does not generalize | Random split applied to trajectory frames — adjacent frames are nearly identical, so test set is trivially predicted | Split by trajectory, by rattled-origin, or by config_type rather than randomly | Use split_by_config_type (Workflow 2); or explicitly group trajectory frames and split groups |
| Force-dominated loss collapse | Energy 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 loss | Plot energy loss and force loss separately; if energy loss is > 100× force loss per epoch, ratio is wrong | Reduce --forces_weight to 10–20; use --loss="weighted" with --config_type_weights for fine control |
| Species absent from training | Crash during MD on a structure containing a species not seen in training; or garbage forces for that species | A chemical species appears in the deployment structure but has zero or very few training examples | Count per-species frames in training set; check which species appear only in test | Add DFT calculations covering the missing species in all expected bonding environments; re-train |
| Unstable MD despite low test error | MD 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 distribution | Monitor max force during MD; extract frames where force > 10 eV/Å and compare to training set distribution | Expand dataset with active learning: run MACE-MD, extract uncertain frames, compute DFT, retrain |
| Batch size too large for GPU | CUDA out-of-memory error during training | Number of atoms × batch_size exceeds GPU VRAM | Start with --batch_size=4; increase until OOM; for 16 GB GPU, typical limit is batch_size=8–16 for 100-atom structures | Reduce --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 = Trueand check forNELM reachedwarnings 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_decompositionflag 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
- 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
- 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
- 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
- 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
- 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原子间势模型。
所属插件
安装该插件会一并获得同领域的 35 个 Skill / MCP。
同插件的其他科研 Skill
- 主动学习构建机器学习势训练集Runs active-learning workflows for ML interatomic potentials: uncertainty-guided MD exploration, DFT oracle labeling, query strategy. Use when expanding an MLP training set.
- AiiDA计算工作流管理Covers AiiDA, a provenance-first Python workflow engine for computational materials science: calculation input generation, remote submission. Use when orchestrating reproducible DFT/MD campaigns.
- ASE原子模拟环境Covers the Atomic Simulation Environment (ASE) as an atomistic workflow hub: Atoms objects, calculators, optimizers, trajectories. Use when scripting or converting structures across DFT/MD codes.
- 粗粒化分子动力学模拟Covers coarse-grained molecular dynamics: mapping atomistic structures to CG beads, parameterizing Martini/IBI/force-matching force fields. Use when atomistic timescales are too short.
- CP2K第一性原理分子动力学Covers end-to-end DFT, AIMD, and atomistic workflows with CP2K using the Gaussian-and-plane-waves method: input construction, convergence testing. Use for CP2K-based simulations.
- 扩散模型生成晶体结构Covers de novo crystal structure generation with score-based diffusion and flow-matching models (MatterGen, DiffCSP, CDVAE). Use when generating candidate structures, not analyzing existing ones.
- 晶体图神经网络性质预测Covers graph neural networks for crystal and periodic-material property prediction: crystal graph construction, periodic neighbor finding. Use when building GNN property predictors for crystals.
- 平面波DFT收敛性测试Covers systematic convergence testing for plane-wave DFT: cutoff energy, k-point mesh density, smearing. Use before trusting DFT energies, forces, or derived properties as converged.
- 机器学习势DFT数据集生成Covers generating DFT-labeled datasets for training ML interatomic potentials: configuration-space coverage. Use when building an MLP training dataset from scratch.
- 点缺陷第一性原理计算Covers first-principles point-defect modeling: vacancy/interstitial/antisite/substitutional construction, charge-state calculations. Use for defect thermodynamics studies.
- 第一性原理声子谱计算Covers lattice dynamics from first principles: phonon dispersion, phonon DOS. Use when computing vibrational or thermodynamic properties from DFT.
- 表面模型DFT计算Covers surface slab model construction and DFT calculation: Miller-index generation, termination selection, slab/vacuum convergence. Use for surface science and catalysis DFT studies.
- 弹性常数计算工作流Computes single-crystal and polycrystalline elastic constants from DFT or MD stress-strain data and checks mechanical stability. Use when deriving stiffness tensors or bulk/shear modulus.
- 增强采样自由能计算Covers enhanced sampling methods for atomistic MD (metadynamics, umbrella sampling. Use for rare-event or slow-transition sampling.
- 状态方程拟合Covers equation-of-state fitting from DFT/ML-potential energy-volume data: Birch-Murnaghan, Vinet, and Murnaghan forms. Use when fitting an EOS to compression data.
- 机器学习势微调迁移训练Covers fine-tuning pretrained universal ML interatomic potentials on system-specific DFT data. Use when adapting a universal MLP to a new system.
- 分子动力学自由能计算Covers quantitative free-energy calculations from MD: alchemical FEP/TI/BAR/MBAR, umbrella-sampling PMF. Use when computing thermodynamic free energies from simulation.
- GROMACS分子动力学工作流Covers end-to-end MD simulations with GROMACS: topology/.mdp construction, energy minimization, NVT/NPT equilibration. Use for GROMACS-based biomolecular or materials MD.
- 高通量DFT自动化筛选Covers automated large-scale DFT screening: workflow graphs with atomate2/jobflow/AiiDA, input-set standardization, custodian error handling. Use for high-throughput DFT screening campaigns.
- LAMMPS分子动力学工作流Covers end-to-end MD simulations with LAMMPS: input script anatomy, force-field deployment, ensemble control, equilibration. Use for LAMMPS-based classical molecular dynamics.
- MatGL图神经网络框架Covers building, applying, validating, and fine-tuning MatGL graph-neural-network models for property prediction and interatomic potentials. Use for pretrained GNN workflows via MatGL.
- 分子动力学轨迹后处理分析Covers quantitative post-processing of atomistic MD trajectories: loading LAMMPS/GROMACS/ASE trajectories and computing RDF, coordination numbers. Use for structural MD trajectory analysis.
- 分子动力学平衡过程设计Covers bringing an atomistic simulation from its initial configuration to a representative equilibrium state before production statistics: ensemble. Use before collecting production MD data.
- 分子动力学力场选型验证Covers selection, validation, and deployment of classical interatomic force fields for MD: physical basis and transferability limits of EAM, MEAM, Tersoff. Use when choosing a force field.
常见问题
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 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。