agentleFS
SFETNISFETNI/Deep-Matter-Chem-Skills/skills/ml-interatomic-potentials/mlp-to-lammps/SKILL.md

mlp-to-lammps

Skill10 starsChanged 6 months agoMITView on GitHub

This skill covers the full pipeline for deploying trained ML interatomic potentials into LAMMPS for production molecular dynamics: LAMMPS compilation with MLP plugins, pair_style and pair_coeff configuration, species-to-atom-type mapping, unit consistency verification, neighbor list tuning, GPU and MPI parallelism considerations, and validation of LAMMPS inference against the Python/ASE reference before any production run. Covers MACE, NequIP/Allegro, and DeePMD-kit deployment patterns. Invoke this skill after passing mlp-validation and before running production LAMMPS simulations with an ML potential. LAMMPS is the standard…

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Model file checksum: Every LAMMPS run script should record the model file path and its SHA-256 hash.

    line 68
  2. Very specific:

    Run validate_lammps_forces on every new deployment: before any production simulation.

    line 689

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

MLP to LAMMPS Deployment

Description

This skill covers the full pipeline for deploying trained ML interatomic potentials into LAMMPS for production molecular dynamics: LAMMPS compilation with MLP plugins, pair_style and pair_coeff configuration, species-to-atom-type mapping, unit consistency verification, neighbor list tuning, GPU and MPI parallelism considerations, and validation of LAMMPS inference against the Python/ASE reference before any production run. Covers MACE, NequIP/Allegro, and DeePMD-kit deployment patterns. Invoke this skill after passing mlp-validation and before running production LAMMPS simulations with an ML potential.

Domain Context

LAMMPS is the standard platform for large-scale MLP-driven MD because it handles periodic boundary conditions, neighbor list management, ensemble integrators, and output efficiently for systems of thousands to millions of atoms. However, LAMMPS was designed around classical pair potentials; MLP pair styles are added as plugins that wrap TorchScript, TensorFlow, or custom C++ backends. This creates several non-obvious deployment hazards:

The LAMMPS/Python interface is not automatically consistent. The same model file evaluated via MACECalculator (Python/ASE) and via pair_style mace (LAMMPS C++ plugin) should produce identical forces, but will not if: the element ordering in the LAMMPS data file does not match the model's internal species list; the unit system is set incorrectly; or the plugin was compiled against a different version of the model's backend library than the Python environment uses.

LAMMPS units are explicit, not inferred. units metal uses Å, eV, ps, K, bar. A model trained in eV/Å (ASE convention) must be deployed under units metal. units real uses kcal/mol, Å, fs — correct for AMBER/CHARMM classical force fields but fatal for MLPs trained in eV. There is no automatic conversion; LAMMPS passes atom coordinates to the pair style and receives forces back, and if the units declaration does not match what the model expects, forces are silently wrong by a factor of 23.06 (eV vs kcal/mol) with no error message.

The neighbor list must be set correctly. LAMMPS manages the neighbor list; the MLP pair style reads neighbors within the model's cutoff. The skin distance (neigh_modify delay 0 every 1 check yes) must allow the pair style to see all atoms within its cutoff. An insufficient skin distance truncates the neighbor list and silently reduces accuracy; an excessively large skin distance wastes memory. For MACE, the neighbor list must include all atoms within r_max + skin; the default LAMMPS skin of 2.0 Å is usually adequate. [EXPERT REVIEW NEEDED]

Equivariant MLPs and domain decomposition. MACE and NequIP/Allegro use equivariant message passing. Their LAMMPS implementations require no_domain_decomposition (MACE) or newton off with specific MPI protocols (NequIP) because the equivariant operations require access to the full ghost-atom environment, which standard domain decomposition does not guarantee. Running these pair styles without the required flags produces silent, incorrect forces in multi-MPI runs — single-rank runs are correct, but any multi-rank run is corrupted.

Model file versioning. A MACE model file (.model or TorchScript .pt) is generated by a specific version of the MACE Python package. The LAMMPS plugin must be compiled against the same MACE version. Upgrading the Python environment without recompiling LAMMPS (or vice versa) typically produces a libtorch version mismatch error at pair_coeff time, but may silently succeed with subtly wrong behavior in some version combinations.

When to Use This Skill

  • Deploying any trained MACE, NequIP, Allegro, or DeePMD-kit model to LAMMPS for production MD at scales (> 10,000 atoms or > 1 ns) that are impractical in ASE.
  • Setting up LAMMPS for active learning exploration MD with a provisional MLP committee.
  • Verifying that a pre-compiled HPC LAMMPS installation supports the required MLP pair style at the correct version.
  • Debugging a force mismatch or energy discrepancy between LAMMPS and the Python training environment.
  • Configuring GPU-accelerated MLP MD on NVIDIA GPUs via the LAMMPS KOKKOS or ML-MACE packages.
  • Migrating a production simulation from one MLP version or architecture to another and confirming numerical equivalence.

When Not to Use This Skill

  • For system sizes < 1,000 atoms and run times < 1 ns — ASE's MACECalculator is simpler, requires no C++ compilation, and avoids the deployment hazards described above. Use LAMMPS only when scale demands it.
  • Before passing mlp-validation — deploying an unvalidated model to LAMMPS adds a layer of complexity that obscures whether failures originate from the MLP itself or from the LAMMPS deployment. Always validate the model in ASE first.
  • For universal potentials that provide their own LAMMPS interface — MACE-MP-0, CHGNet, and M3GNet have maintained LAMMPS interfaces; use the upstream documentation rather than this skill for those specific models.
  • For LAMMPS workflows that do not require an MLP — this skill is specific to MLP pair styles. Standard classical pair style deployment is covered in lammps-workflow.

Core Concepts

  • LAMMPS units metal: units metal declares Å for distance, eV for energy, ps for time, K for temperature, bar for pressure. This is the correct unit system for any MLP trained on ASE extxyz data (which stores energy in eV and distances in Å). Forces are in eV/Å. Never use units real or units lj with a physics-trained MLP.
  • pair_style and pair_coeff: pair_style mace no_domain_decomposition declares the interaction model; pair_coeff * * model.pt El1 El2 ... specifies the model file and the element assigned to each LAMMPS atom type. The element list in pair_coeff must match the model's internal species list in the correct order. LAMMPS atom types are integers (1, 2, 3, ...); the mapping * * model El1 El2 means type 1 → El1, type 2 → El2, etc.
  • no_domain_decomposition (MACE): Required flag for pair_style mace. With standard domain decomposition, each MPI rank handles a spatial subdomain and only knows about its local atoms and a layer of ghost atoms. MACE's equivariant message passing requires the full 2-hop neighborhood of each atom, which may extend beyond one ghost layer in large parallel runs. no_domain_decomposition disables spatial decomposition entirely and replicates the full atom list across all ranks — correct but limits parallel scaling. See Parallel Execution section.
  • newton off (NequIP/Allegro): NequIP and Allegro LAMMPS pair styles require newton off (disabled Newton's third law), because their internal force summation scheme already handles action-reaction pairs explicitly. Using newton on with NequIP double-counts force contributions in parallel runs.
  • TorchScript model format: MACE and NequIP export models as TorchScript .pt files, which encode the model architecture and weights into a single portable binary that PyTorch's C++ frontend (libtorch) can load without the Python package. The LAMMPS plugin links against libtorch; the .pt file must have been generated by a compatible PyTorch version.
  • DeePMD frozen graph: DeePMD-kit exports a TensorFlow frozen graph (.pb) or a new-format compressed model (.pth for DP2.x). The LAMMPS plugin links against TensorFlow C++ and requires the same TF version at runtime.
  • Neighbor list skin distance: LAMMPS builds neighbor lists every N_neighbor steps with a skin extending skin Å beyond each pair style's declared cutoff. For MACE with r_max=5.5 Å, the pair style declares cutoff 5.5 Å; the neighbor list includes atoms within 5.5 + skin Å. Default LAMMPS skin is 2.0 Å. Increasing skin reduces rebuilds but increases memory. The cutoff declared in pair_coeff must match the model's r_max exactly.
  • Ghost atom communication (comm_modify cutoff): In multi-rank runs, LAMMPS must communicate ghost atom data far enough to build the correct neighbor list. For MACE with no_domain_decomposition, domain decomposition is disabled so this is not needed. For other pair styles where domain decomposition is active, comm_modify cutoff must be ≥ r_max + skin to ensure all required neighbors are available to each rank.
  • Model file checksum: Every LAMMPS run script should record the model file path and its SHA-256 hash. Models are large binary files; a corrupted or accidentally overwritten model file can produce subtly wrong results without any error.

Key Workflows

Workflow 1: LAMMPS compilation and plugin installation

Verifying that the installed LAMMPS supports the required MLP pair style at the correct version. This is the first diagnostic step for any deployment failure.

#!/bin/bash
# ─── STEP 1: Check whether LAMMPS has the required package ───────────────────
lmp -help 2>&1 | grep -i "ML-MACE\|ML-NEQUIP\|ML-IAP\|DEEPMD\|KOKKOS"
# If the package name does not appear, LAMMPS was not compiled with the plugin.

# ─── STEP 2: CMake build flags for MACE ──────────────────────────────────────
# Requires: PyTorch installed, MACE Python package installed,
# libtorch discoverable by CMake (usually via $TORCH_CMAKE_PREFIX_PATH)

export TORCH_CMAKE_PREFIX_PATH=$(python -c "import torch; print(torch.utils.cmake_prefix_path)")

cmake ../lammps \
    -D CMAKE_BUILD_TYPE=Release \
    -D BUILD_MPI=yes \
    -D BUILD_OMP=yes \
    -D PKG_MOLECULE=yes \
    -D PKG_RIGID=yes \
    -D PKG_ML-MACE=yes \
    -D MACE_DOWNLOAD_SOURCES=no \
    -D Torch_DIR=${TORCH_CMAKE_PREFIX_PATH}/Torch \
    -D CMAKE_INSTALL_PREFIX=$HOME/.local \
    2>&1 | tee cmake_output.log

# Check that CMake found libtorch:
grep "Torch" cmake_output.log | grep -E "found|FOUND|version"

cmake --build . --parallel 8
cmake --install .

# ─── STEP 3: Verify the built lmp binary finds libtorch at runtime ────────────
ldd $(which lmp) | grep -i torch
# If any 'not found' lines appear, set LD_LIBRARY_PATH:
export LD_LIBRARY_PATH=$(python -c "import torch; import os; print(os.path.dirname(torch.__file__))")/lib:$LD_LIBRARY_PATH

# ─── STEP 4: Smoke test with a minimal single-atom run ───────────────────────
# (See Workflow 3 for full validation; this just confirms pair_style loads)
cat > /tmp/smoke_test.in << 'EOF'
units           metal
atom_style      atomic
boundary        p p p
lattice         bcc 3.165
region          box block 0 3 0 3 0 3
create_box      1 box
create_atoms    1 box

pair_style      mace no_domain_decomposition
pair_coeff      * * /path/to/model.pt W

run             0
EOF
lmp -in /tmp/smoke_test.in
# Should complete without segfault or 'unknown pair style' error.
# ─── NequIP / Allegro compilation ────────────────────────────────────────────
# NequIP requires LAMMPS pair_nequip package.
# Source: https://github.com/mir-group/pair_nequip

cd /path/to/lammps/src
cp /path/to/pair_nequip/pair_nequip.cpp ./
cp /path/to/pair_nequip/pair_nequip.h ./

# Then recompile with standard make or CMake.
# The pair_nequip plugin requires:
#   libtorch (same version as training PyTorch)
#   nequip-compile exported TorchScript model

# ─── DeePMD-kit compilation ──────────────────────────────────────────────────
# DeePMD-kit provides a pre-built LAMMPS with its plugin via conda:
conda install -c deepmodeling deepmd-kit lammps  # deepmd 2.x + LAMMPS
# This is the recommended route to avoid TensorFlow C++ compatibility issues.

# Verify DeePMD LAMMPS support:
lmp -help 2>&1 | grep -i deepmd

Workflow 2: pair_style configuration and species mapping

The most common source of silent errors. The element list in pair_coeff must match the model's internal species order, not the user's preference.

#!/bin/bash
# ─── Determine the model's internal species order ────────────────────────────
# For MACE models:
python3 << 'PYEOF'
import torch
model = torch.load("W_Ta_mace_run-123_stagetwo.model", map_location="cpu")
# The atomic_numbers_to_index dict maps element Z to model index.
# The model's species are ordered by atomic number by default.
print("Atomic numbers in model:", model.atomic_numbers)
# Or for newer MACE versions:
# print("z_table:", model.z_table.zs)
PYEOF
# Example output: tensor([74, 73])  → W (Z=74), Ta (Z=73)
# So in pair_coeff, atom type 1 = W, atom type 2 = Ta (LAMMPS types in Z-sorted order)
# BUT the pair_coeff element list order must match LAMMPS atom types in the data file.

# ─── Correct LAMMPS input for W-Ta alloy ─────────────────────────────────────
cat > W_Ta_mace.in << 'LMPEOF'
units           metal
atom_style      atomic
boundary        p p p

read_data       W_Ta_bulk.lammps
# W_Ta_bulk.lammps must define:
#   2 atom types
#   Atoms section: atom_id mol_id atom_type x y z
#   where atom_type 1 = W, atom_type 2 = Ta
# CRITICAL: the type assignment in the data file must be consistent with
# the element list in pair_coeff below.

# ─── Pair style ──────────────────────────────────────────────────────────────
pair_style      mace no_domain_decomposition
pair_coeff      * * /path/to/W_Ta_mace_run-123_stagetwo.pt W Ta
# "W Ta" = type 1 is W, type 2 is Ta.
# If the data file has type 1 = Ta and type 2 = W, use "pair_coeff * * model.pt Ta W"
# Mismatch here: forces computed with wrong element identities — no error message.

# ─── Neighbor list ───────────────────────────────────────────────────────────
# MACE with r_max=5.5 Å: LAMMPS will build neighbors within r_max + skin.
# Default skin = 2.0 Å is usually adequate; reduce if memory is tight.
neighbor        2.0 bin
neigh_modify    delay 0 every 1 check yes
# every 1: rebuild every step (conservative; use every 5-10 for cheaper rebuilds
#   in NVT/NPT after equilibration if max displacement per step is small)

# ─── Timestep ────────────────────────────────────────────────────────────────
timestep        0.002   # 2 fs in metal units (ps); standard for metals

# ─── NVE test run ────────────────────────────────────────────────────────────
velocity        all create 300 12345 mom yes rot yes dist gaussian
fix             1 all nve
thermo          100
thermo_style    custom step temp pe ke etotal press vol
run             1000    # Short stability test; see Workflow 6 for full NVE test
LMPEOF
# ─── Verifying species order from the LAMMPS data file perspective ────────────
from ase.io import read, write
import numpy as np

# Read an extxyz structure and write as LAMMPS data
atoms = read("W_Ta_equilibrated.extxyz")
syms = atoms.get_chemical_symbols()
unique_species = sorted(set(syms))  # ASE write sorts by symbol, not Z

print(f"Species in structure: {unique_species}")
print(f"LAMMPS atom type mapping (write order):")
for i, sp in enumerate(unique_species, 1):
    print(f"  type {i} = {sp}")

# Write LAMMPS data file with explicit species order
write(
    "W_Ta_bulk.lammps",
    atoms,
    format="lammps-data",
    specorder=unique_species,  # This controls type 1 = unique_species[0], etc.
    masses=True,
)
print(f"\nIn pair_coeff, use: pair_coeff * * model.pt {' '.join(unique_species)}")
# The specorder here MUST match the element list in pair_coeff.

Workflow 3: Validating LAMMPS forces against ASE before production

This check must pass before any production run. A mismatch above 1 meV/Å is a deployment error — correct it before proceeding.

import numpy as np
from ase.io import read, write
from mace.calculators import MACECalculator
from pathlib import Path
import subprocess
import tempfile
import hashlib


def validate_lammps_forces(
    model_path: str,
    test_structure,
    element_order: list[str],
    lammps_executable: str = "lmp",
    tolerance_meV_A: float = 1.0,
    device: str = "cpu",
) -> dict:
    """
    Compute forces with ASE MACECalculator and LAMMPS pair_style mace.
    Report maximum and mean absolute force difference (meV/Å).

    This validation must be performed on the production hardware before
    running any LAMMPS simulation with a new MLP deployment.

    element_order: e.g. ["W", "Ta"] — must match the data file type ordering.
    """
    # ─── Log the model checksum ───────────────────────────────────────────────
    with open(model_path, "rb") as f:
        model_sha256 = hashlib.sha256(f.read()).hexdigest()
    print(f"Model: {model_path}")
    print(f"SHA-256: {model_sha256[:16]}...")

    # ─── ASE reference forces ─────────────────────────────────────────────────
    calc = MACECalculator(
        model_paths=model_path,
        device=device,
        default_dtype="float64",  # float64 for unbiased comparison
    )
    atoms_ase = test_structure.copy()
    atoms_ase.calc = calc
    f_ase = atoms_ase.get_forces()        # (N, 3) eV/Å
    e_ase = atoms_ase.get_potential_energy()
    print(f"\nASE energy: {e_ase:.8f} eV  ({e_ase / len(atoms_ase):.6f} eV/atom)")

    # ─── LAMMPS forces ────────────────────────────────────────────────────────
    with tempfile.TemporaryDirectory() as tmpdir:
        tmpdir = Path(tmpdir)
        data_file = tmpdir / "test.lammps"
        write(str(data_file), test_structure, format="lammps-data",
              specorder=element_order, masses=True)

        input_script = tmpdir / "validate.in"
        input_script.write_text(
            f"units           metal\n"
            f"atom_style      atomic\n"
            f"boundary        p p p\n"
            f"read_data       {data_file}\n"
            f"\n"
            f"pair_style      mace no_domain_decomposition\n"
            f"pair_coeff      * * {Path(model_path).resolve()} "
            f"{' '.join(element_order)}\n"
            f"\n"
            f"neighbor        2.0 bin\n"
            f"neigh_modify    delay 0 every 1 check yes\n"
            f"\n"
            f"# Single-point evaluation\n"
            f"run             0\n"
            f"write_dump      all custom {tmpdir}/forces.dump "
            f"id type x y z fx fy fz modify sort id\n"
        )

        result = subprocess.run(
            [lammps_executable, "-in", str(input_script)],
            capture_output=True, text=True, cwd=str(tmpdir),
        )
        if result.returncode != 0:
            print(f"LAMMPS error:\n{result.stderr[-3000:]}")
            raise RuntimeError("LAMMPS run failed — see error above")

        # Parse energy from LAMMPS thermo output
        e_lammps = None
        for line in result.stdout.splitlines():
            if line.startswith("Step"):
                continue  # header
            cols = line.split()
            if len(cols) >= 3:
                try:
                    e_lammps = float(cols[2])  # pe column from thermo_style step temp pe
                except ValueError:
                    continue

        # Parse forces from dump
        dump = (tmpdir / "forces.dump").read_text()
        lines = dump.splitlines()
        data_start = next(
            (i + 1 for i, l in enumerate(lines) if l.startswith("ITEM: ATOMS")), None
        )
        if data_start is None:
            raise RuntimeError("Could not parse LAMMPS dump file")

        natoms = len(test_structure)
        f_lammps = np.zeros((natoms, 3))
        for line in lines[data_start:]:
            cols = line.split()
            if len(cols) < 8:
                continue
            atom_id = int(cols[0]) - 1
            f_lammps[atom_id] = [float(cols[5]), float(cols[6]), float(cols[7])]

    # ─── Compare ──────────────────────────────────────────────────────────────
    diff = np.abs(f_ase - f_lammps)
    max_diff_meV = diff.max() * 1000
    mean_diff_meV = diff.mean() * 1000

    print(f"\nForce comparison (ASE float64 vs LAMMPS):")
    print(f"  Max  |ΔF| : {max_diff_meV:.4f} meV/Å")
    print(f"  Mean |ΔF| : {mean_diff_meV:.4f} meV/Å")
    print(f"  N atoms   : {natoms}")

    # Find atoms with largest discrepancy
    worst_atoms = np.argsort(diff.max(axis=1))[-5:][::-1]
    for idx in worst_atoms:
        sym = test_structure[idx].symbol
        print(f"  Atom {idx:>4d} ({sym}): |ΔF| = {diff[idx].max()*1000:.3f} meV/Å")

    passed = max_diff_meV <= tolerance_meV_A
    status = "PASS" if passed else "FAIL"
    print(f"\n[{status}] Max |ΔF| {max_diff_meV:.4f} meV/Å "
          f"(tolerance = {tolerance_meV_A:.1f} meV/Å)")

    if not passed:
        print("\nDebugging checklist:")
        print("  1. Does element order in pair_coeff match the data file type order?")
        print("     Check: ase write specorder matches pair_coeff element list")
        print("  2. Are units set to 'units metal' in the LAMMPS input?")
        print("  3. Does the LAMMPS lmp binary link the same libtorch as the Python env?")
        print("     Check: ldd $(which lmp) | grep torch")
        print("  4. Is the no_domain_decomposition flag present for MACE?")
        print("  5. Is the model file identical to what ASE loaded?")
        print(f"     SHA-256: {model_sha256[:16]}...")

    return {
        "passed": passed,
        "max_diff_meV_A": max_diff_meV,
        "mean_diff_meV_A": mean_diff_meV,
        "model_sha256": model_sha256,
        "n_atoms": natoms,
    }

Workflow 4: NequIP and Allegro deployment

#!/bin/bash
# ─── Export NequIP/Allegro model to TorchScript for LAMMPS ───────────────────
# Must be done in the same Python environment used for training.

# For NequIP:
nequip-deploy build \
    --train-dir /path/to/training_output/ \
    deployed_nequip.pt
# deployed_nequip.pt is a TorchScript file loadable by the LAMMPS plugin.

# For Allegro (extends NequIP):
nequip-deploy build \
    --train-dir /path/to/allegro_training_output/ \
    deployed_allegro.pt

# Verify the deployed model outside LAMMPS:
nequip-evaluate \
    --train-dir /path/to/training_output/ \
    --test-indexes 0 1 2 \
    --output /tmp/nequip_eval.xyz
# ─── NequIP LAMMPS input ──────────────────────────────────────────────────────
units           metal
atom_style      atomic
boundary        p p p

read_data       W_bulk.lammps

# NequIP requires newton off — its force summation is not Newton-3 compatible
# with LAMMPS domain decomposition when newton on.
newton          off

pair_style      nequip
pair_coeff      * * /path/to/deployed_nequip.pt W

# The NequIP model declares its own cutoff internally.
# LAMMPS must be told the cutoff for neighbor list construction:
# pair_style nequip uses the cutoff from the deployed model file automatically.
# If you see "neighbor cutoff too small" warnings, override:
# pair_style      nequip cutoff_skin 2.0

neighbor        2.0 bin
neigh_modify    delay 0 every 1 check yes

# Communication cutoff must cover the model cutoff for ghost atoms.
# For NequIP with r_cut=5.0 Å and skin=2.0 Å:
comm_modify     cutoff 7.0   # r_cut + skin

timestep        0.002

velocity        all create 300 45678 mom yes rot yes
fix             1 all nve
thermo          100
run             1000
# ─── Allegro LAMMPS input (identical to NequIP, just different model file) ───
units           metal
atom_style      atomic
boundary        p p p
read_data       W_Ta_bulk.lammps
newton          off
pair_style      allegro
pair_coeff      * * /path/to/deployed_allegro.pt W Ta
comm_modify     cutoff 8.0   # Allegro often uses larger cutoffs (5-7 Å); adjust
neighbor        2.0 bin
neigh_modify    delay 0 every 1 check yes
timestep        0.002
velocity        all create 1000 99999 mom yes rot yes
fix             1 all nvt temp 1000 1000 0.1
thermo          100
run             5000
# ─── Verifying NequIP LAMMPS forces against nequip-evaluate output ─────────────
import numpy as np
from ase.io import read

# nequip-evaluate writes predicted forces to the output xyz
nequip_pred = read("/tmp/nequip_eval.xyz", index=0)
lammps_forces = np.load("/tmp/lammps_forces.npy")  # from a LAMMPS dump parse

diff = np.abs(nequip_pred.arrays["forces"] - lammps_forces)
print(f"NequIP vs LAMMPS max |ΔF|: {diff.max()*1000:.4f} meV/Å")
# Expected: < 1 meV/Å if newton off is set correctly and comm cutoff is sufficient.

Workflow 5: DeePMD-kit deployment

#!/bin/bash
# ─── Freeze (export) a DeePMD model to the .pb or .pth format ────────────────
# For DeePMD-kit v2.x (TensorFlow backend):
dp freeze -o frozen_model.pb
dp compress -i frozen_model.pb -o compressed_model.pb
# Compressed models run ~3× faster with < 0.1 meV/Å force error. [EXPERT REVIEW NEEDED]

# For DeePMD-kit v3.x (PyTorch backend):
dp freeze --output frozen_model.pth
# The LAMMPS plugin auto-detects the format from the file extension.

# Validate the frozen model against the training data:
dp test -m frozen_model.pb -s /path/to/test_set/ -n 100
# Reports energy MAE (eV/atom) and force MAE (eV/Å).
# ─── DeePMD-kit LAMMPS input (TF backend, v2.x) ──────────────────────────────
units           metal
atom_style      atomic
boundary        p p p

read_data       W_Ta_bulk.lammps
# Data file must list atom types in the same order as the DeePMD type_map.
# type_map is defined in the DeePMD input.json used for training:
#   "type_map": ["W", "Ta"]  → type 1 = W, type 2 = Ta

pair_style      deepmd /path/to/frozen_model.pb
pair_coeff      * *
# DeePMD pair_coeff takes no element list — species mapping is encoded in the .pb.
# The LAMMPS atom types must correspond to DeePMD type indices 0, 1, 2, ... in order.

neighbor        2.0 bin
neigh_modify    delay 0 every 1 check yes
# DeePMD models do not require no_domain_decomposition or newton off.
# Standard domain decomposition works because DeePMD's LAMMPS interface
# handles ghost atom forces via the standard LAMMPS framework.

timestep        0.002

velocity        all create 1000 54321 mom yes rot yes
fix             1 all nvt temp 1000 1000 0.1
thermo_style    custom step temp pe ke etotal press vol density
thermo          100
run             10000
# ─── DeePMD model type_map verification ──────────────────────────────────────
import json
from pathlib import Path

# The training input.json encodes the species ordering:
train_input = json.loads(Path("input.json").read_text())
type_map = train_input.get("model", {}).get("type_map", [])
print(f"DeePMD type_map: {type_map}")
print(f"LAMMPS atom type mapping:")
for i, elem in enumerate(type_map, 1):
    print(f"  LAMMPS type {i} = {elem} (DeePMD index {i-1})")
# When writing the LAMMPS data file, ensure specorder matches type_map order.

from ase.io import write, read
atoms = read("W_Ta_relaxed.extxyz")
write(
    "W_Ta_bulk.lammps",
    atoms,
    format="lammps-data",
    specorder=type_map,  # Critical: use type_map order, not alphabetical
    masses=True,
)

Workflow 6: Parallel execution, GPU deployment, and neighbor list tuning

#!/bin/bash
# ─── MACE parallel execution constraints ─────────────────────────────────────
# MACE with no_domain_decomposition: all ranks hold all atoms.
# This is correct but limits MPI scalability.
# In practice, MACE runs are typically:
#   - Single GPU (KOKKOS): fast for systems up to ~10,000 atoms
#   - 1–4 MPI ranks on CPU: for larger systems where GPU memory is insufficient
# Using > 8 MPI ranks with no_domain_decomposition is generally not beneficial
# because communication overhead dominates. [EXPERT REVIEW NEEDED]

# CPU-only, 4 MPI ranks:
mpirun -n 4 lmp -in mace_production.in

# Single-GPU via KOKKOS package (requires LAMMPS compiled with PKG_KOKKOS=yes):
lmp -k on g 1 -sf kk -in mace_production.in
# -k on g 1: use 1 GPU via Kokkos
# -sf kk: use Kokkos-optimized pair style if available
# Note: not all MLP pair styles have a Kokkos backend; verify support for your version.

# ─── NequIP and Allegro parallel scaling ─────────────────────────────────────
# NequIP with newton off: supports standard MPI domain decomposition.
# Communication cutoff must be ≥ r_cut + skin on every rank.
# Scales well up to ~16–32 MPI ranks for typical simulation cells. [EXPERT REVIEW NEEDED]
mpirun -n 8 lmp -in nequip_production.in

# ─── DeePMD parallel scaling ──────────────────────────────────────────────────
# DeePMD supports standard domain decomposition with good MPI scaling.
# GPU support via LAMMPS KOKKOS or the dedicated deepmd-kit GPU backend.
mpirun -n 16 lmp -in deepmd_production.in
# ─── Neighbor list tuning for production runs ────────────────────────────────
# Default LAMMPS settings are conservative. For production NVT/NPT:

# Rebuild neighbor list every 5 steps instead of every step.
# Safe when max atomic displacement per step < 0.2 × skin.
# For 2 fs timestep and metals at 1000 K, max displacement ~ 0.05 Å/step:
# 5 steps × 0.05 Å = 0.25 Å < 0.2 × 2.0 Å = 0.4 Å → safe.
neigh_modify    delay 5 every 5 check yes
# "check yes": only rebuild if max displacement threshold is exceeded.
# More conservative and usually preferred over fixed-interval rebuilds.

# Reduce skin to 1.5 Å if memory is tight (fewer ghost atoms):
neighbor        1.5 bin
# But verify with check yes that rebuilds are not triggered every step.

# For MACE GPU runs, larger batch (more atoms per kernel call) is faster:
# No LAMMPS input flag; kernel batching is handled internally by the pair style.

# ─── Monitoring neighbor list rebuild frequency ──────────────────────────────
# Add to thermo output to check if neighbor list is rebuilding too often:
compute         neigh_count all property/atom type
thermo_style    custom step temp pe ke etotal press density cpu
# "cpu" column shows wall time per step — large jumps indicate expensive rebuilds.
# ─── Checking LAMMPS log for deployment issues ────────────────────────────────
import re
from pathlib import Path


def check_lammps_log(log_file: str) -> None:
    """
    Parse a LAMMPS log file for common MLP deployment warnings and errors.
    """
    text = Path(log_file).read_text()

    checks = [
        ("no_domain_decomposition", "MACE no_domain_decomposition activated"),
        ("WARNING: Inconsistent image flags", "Atom wrapped across periodic boundary — "
         "may indicate unphysical geometry or wrong box"),
        ("ERROR", "LAMMPS error — see log"),
        ("Lost atoms", "Atoms left the simulation box — MLP likely extrapolating; "
         "reduce timestep or check structure"),
        ("Neighbor list overflow", "Ghost atom buffer too small — increase "
         "comm_modify cutoff and/or neighbor skin"),
        ("WARNING.*newton", "Newton flag warning — check newton on/off for NequIP/Allegro"),
    ]

    for pattern, message in checks:
        if re.search(pattern, text, re.IGNORECASE):
            severity = "ERROR" if "ERROR" in pattern or "Lost atoms" in pattern else "NOTE"
            print(f"[{severity}] {message}")
            # Show context
            for line in text.splitlines():
                if re.search(pattern, line, re.IGNORECASE):
                    print(f"       → {line.strip()}")

    # Check final energy for NaN/Inf
    thermo_lines = [l for l in text.splitlines()
                    if re.match(r"^\s*\d+\s+\d", l)]
    if thermo_lines:
        last = thermo_lines[-1].split()
        for val in last:
            try:
                x = float(val)
                if not (x == x):   # NaN check
                    print("[ERROR] NaN in thermo output — MLP produced garbage forces")
            except ValueError:
                pass

Common Failure Modes

FailureSymptomLikely CauseDiagnosticFix
Wrong species mappingForces wrong by large, structure-specific amounts (> 1 eV/Å at equilibrium); energy per atom is wrong by > 0.5 eV but system does not immediately crashElement list in pair_coeff does not match atom type order in the LAMMPS data file; type 1 = W in pair_coeff but type 1 = Ta in data fileRun validate_lammps_forces (Workflow 3); forces will disagree with ASE by >> 1 meV/Å for the wrong-mapped typesRe-generate the LAMMPS data file with ase write ... specorder=[...] matching the pair_coeff element list exactly; verify with python -c "print(atoms.get_chemical_symbols()[:5])" after read_data
Wrong LAMMPS unitsForces uniformly off by a constant factor (×23.06 for real→metal or ×0.043 for metal→real); energy offset but force direction correct; LAMMPS runs but thermostat behaves incorrectlyunits real or units lj declared instead of units metal for an eV/Å-trained MLPCheck: at equilibrium, pair_style mace forces should be ≈ 0 meV/Å; if they are 23 eV/Å for a near-equilibrium bulk structure, units are real (kcal/mol factor)Change units metal in input script; regenerate LAMMPS data file (ASE write lammps-data defaults to metal units)
Incompatible LAMMPS pluginERROR: Unknown pair style: mace or Segmentation fault (core dumped) at pair_coeff; or libtorch version mismatchLAMMPS binary does not have the ML-MACE package compiled in, or was compiled against a different libtorch version than the current Python environmentRun `lmp -helpgrep ML-MACE; run ldd $(which lmp)grep libtorch; compare torch versions: python -c "import torch; print(torch.version)"`Recompile LAMMPS against the installed PyTorch's libtorch; or use a conda environment that provides a compatible pre-built LAMMPS
Missing model dependenciesRuntimeError: PytorchStreamReader failed at pair_coeff; or model loads but produces NaN forces; for DeePMD: TF_LoadLibrary failedTorchScript model file is corrupt, was generated by a different MACE version, or has broken relative paths to auxiliary filesVerify model loads in Python: torch.load("model.pt"); check file model.pt output — should be zip archive; for DeePMD, test with dp test before LAMMPSRegenerate model file with nequip-deploy build or export from current MACE training code; ensure model version matches LAMMPS plugin version
Incorrect neighbor list — cutoff truncationForces slightly wrong (2–10 meV/Å at equilibrium) but no crash; errors larger for atoms near dense neighborhoods; parallel and serial runs agreepair_coeff cutoff declared smaller than model r_max; or comm_modify cutoff insufficient for NequIP/Allegro in parallelRun validate_lammps_forces with 1 MPI rank and compare to ASE; if single-rank passes but multi-rank fails, comm_modify cutoff is too smallSet neighbor skin to 2.0 Å and comm_modify cutoff r_cut + 2.0 for NequIP; never override the cutoff in pair_style to a value smaller than the model's r_max
Parallel-domain artifacts — no_domain_decomposition missingLAMMPS runs with multiple MPI ranks; forces differ from ASE by 5–100 meV/Å; energy fluctuates with number of MPI ranks; increasing MPI ranks makes errors worsepair_style mace used without no_domain_decomposition flag in a multi-rank run; each rank only has local ghost atoms and misses neighbors from non-adjacent ranksCompare forces from 1-rank and 4-rank runs; if they differ by > 1 meV/Å, domain decomposition is corrupting the equivariant message passingAdd no_domain_decomposition to the pair_style mace declaration; for NequIP use newton off and comm_modify cutoff; for DeePMD standard domain decomposition is correct
Unstable MD despite low static errorSingle-point force validation passes (< 1 meV/Å vs ASE); short NVE run stable; but production NPT at 1500 K diverges after 100 psModel tested at configurations near training distribution; production MD at high temperature samples structures outside the training set; MLP extrapolates into unphysical regionsRun NVE at the target temperature for 50 ps; monitor max force; extract frames with max force > 20 eV/Å and compare to training distribution via SOAP distanceResume active learning at the target temperature (see active-learning-mlp); add high-temperature AIMD snapshots to the training set
Silent force mismatch — float32 vs float64Forces appear to agree at float32 precision but disagree at float64; energy drift in long NVE runs; subtle NPT density error (< 1%)LAMMPS plugin uses float32 internally; ASE validation used float64; 0.1–1 meV/Å systematic difference hidden by float32 precisionRun validation with default_dtype="float32" in ASE to match LAMMPS precision; compare both float32 and float64 ASE results to LAMMPSFor production: use float64 throughout (slower but correct); or accept float32 and verify that the induced force error is below the physical tolerance required for the target property

Best Practices

  • Run validate_lammps_forces on every new deployment before any production simulation. This is a 5-minute check that catches species mapping errors, unit errors, and plugin version mismatches. Record the model SHA-256 and the max force difference in the project log.
  • Always set units metal for MLPs trained on ASE extxyz data. There is no automatic unit detection in LAMMPS. A wrong units declaration produces silently wrong forces with no error message.
  • Pin the species order at data file creation time using ase write ... specorder=element_order and record the order in the project README. Any script that writes a new data file must use the same specorder as the original.
  • Always include no_domain_decomposition for MACE pair_style in every input script, even for single-rank runs. The flag is harmless on a single rank and prevents a critical error if the script is later run with multiple ranks.
  • Set newton off for NequIP and Allegro and verify comm_modify cutoff ≥ r_cut + skin. Failing to set newton off is silent on a single rank but produces wrong forces with multiple MPI ranks.
  • Validate on the production hardware, not just the development workstation. CUDA version, libtorch version, and MKL library configurations differ between workstations and HPC nodes. A deployment that passes locally may fail or produce wrong forces on the cluster due to library version mismatches.
  • Set neigh_modify check yes rather than fixed-interval rebuilds. It avoids both stale neighbor lists (which truncate cutoffs and corrupt forces) and unnecessary rebuilds (which waste compute). Monitor the rebuild frequency via the cpu thermo column.
  • Log the model file path and SHA-256 in every LAMMPS log file. LAMMPS does not automatically record which model file was used in a run. Add a print "Model SHA-256: $(sha256sum /path/to/model.pt | cut -d' ' -f1)" to the submission script before lmp -in ....
  • Test the deployment at the target temperature and pressure with a short (10 ps) equilibration run before committing to production. A model that passes static validation at 300 K may fail at 2000 K or 10 GPa if those conditions were not covered in training.

Integration with Other Skills

  • mace-training: The MACE model file exported from training (the _stagetwo.model checkpoint) is the primary input to this skill. The architecture choices (r_max, element list, hidden_irreps) made during training determine the pair_coeff cutoff and element mapping required here.
  • active-learning-mlp: Exploration MD in the active learning loop uses LAMMPS with a provisional MACE committee. This skill's deployment verification (Workflow 3) should be applied to each committee member before starting exploration runs; a wrong deployment here silently corrupts the uncertainty estimates.
  • mlp-validation: This skill's Workflow 3 (ASE vs. LAMMPS force comparison) is the final gate before the production deployment that mlp-validation evaluated in ASE. All validation performed in mlp-validation is post-training but pre-LAMMPS; this skill adds the LAMMPS-specific layer.
  • lammps-workflow: LAMMPS input script structure, thermostat/barostat settings, thermo output configuration, and restart mechanics from that skill apply directly to MLP-driven runs. This skill focuses on the pair style layer; the simulation setup layer is covered there.
  • md-equilibration: After passing Workflow 3 (force validation) and Workflow 6 (NVE stability), the equilibration protocol from that skill is applied using the LAMMPS MLP pair style. The flying-ice-cube check and multi-stage equilibration sequence are especially important for MLP MD because undetected equilibration artifacts can bias the configurations that trigger active learning.
  • dft-dataset-generation: When LAMMPS deployment reveals that the MLP fails at a new temperature or pressure regime, the remedy is always to generate more DFT data at those conditions and retrain. That skill covers how to design the supplementary DFT calculations.
  • dft-convergence: The model's DFT training settings must be identical to those used for any new DFT reference calculations generated to expand the training set. When a LAMMPS run fails due to model extrapolation, the new DFT oracle calculations must use the frozen settings from the original training campaign.
  • uncertainty-mlp: Running a committee of MACE models in LAMMPS for active learning exploration requires deploying N separate LAMMPS instances or using a custom uncertainty-aware pair style. That skill covers when and how to integrate uncertainty quantification into production LAMMPS runs beyond the simple committee approach shown in active-learning-mlp.
  • universal-potentials: MACE-MP-0, CHGNet, and M3GNet each have their own LAMMPS interfaces and model file formats. This skill's principles (species mapping, unit verification, force validation) apply to those deployments too, but the specific pair_style syntax and compilation instructions differ. Consult that skill for universal-potential-specific deployment details.

Key References

  1. Thompson, A. P., et al. (2022). LAMMPS — A flexible simulation tool for particle-based materials modeling. Computer Physics Communications, 271, 108171. https://doi.org/10.1016/j.cpc.2021.108171
  2. 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
  3. Batzner, S., et al. (2022). E(3)-equivariant graph neural networks for data-efficient and accurate interatomic potentials. Nature Communications, 13, 2453. https://doi.org/10.1038/s41467-022-29939-5
  4. Zeng, J., et al. (2023). DeePMD-kit v2: A software package for deep potential models. Journal of Chemical Physics, 159, 054801. https://doi.org/10.1063/5.0155600
  5. Musaelian, A., et al. (2023). Learning local equivariant representations for large-scale atomistic dynamics. Nature Communications, 14, 579. https://doi.org/10.1038/s41467-023-36329-y

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.