Example run locallyPython · ML potential · ~1 min (GPU)

Let the model choose its next training data

Run Pt(111)–water MD, measure where two ML potentials disagree, and select the most uncertain frames for DFT labeling.

Download notebook

What you will learn

  • How committee disagreement estimates model uncertainty
  • How to select diverse, uncertain frames
  • How uncertainty-biased MD extends the idea

Set up

pip install mace-torch ase matplotlib numpy scipy

Files for this tutorial:

Put the shared files in common/, next to the active-learning-interfaces/ directory. Run the commands from active-learning-interfaces/.

How it works

  1. Generate configurations

    Ten water molecules on a 3×3×4 Pt(111) slab, 350 K, 1.5 ps of MD with MACE-MP-0 small.

  2. Ask a second model

    MACE-MP-0 medium re-evaluates every saved frame. Uncertainty is the largest per-atom force difference between the two models.

  3. Select

    Frames are ranked by uncertainty. A frame is skipped if it sits too close in time to one already chosen, so the selection stays diverse. The selected frames go to DFT, then into training.

  4. Bias toward the unknown

    HER-AL adds a force that pushes MD toward configurations with high uncertainty, so rare events are found faster than in plain MD.

Run it

The local run used MACE-MP-0 with mace-torch 0.3.17 on an NVIDIA GeForce RTX 5080.

python committee_selection.py

What you should see

Force disagreement by saved frame, with selected frames marked in red.
Output of committee_selection.py (68 s). Max force disagreement had a median of 0.51 eV/Å and peaked at 0.77 eV/Å; red points are the five frames selected for DFT.

How this differs from the paper

The research workflow uses committees or last-layer uncertainty from the model being trained, an explicit bias potential, automated DFT jobs on a supercomputer, and many iterations. This tutorial runs one selection round without labeling.

Full source

committee_selection.py (113 lines)
committee_selection.py
"""Tutorial — Let the model tell you which structures to label next.

Active learning grows a training set only where the ML potential is unsure. The in-preparation
work (HER-AL) adds a bias force that pushes MD toward high-uncertainty configurations, labels
those with DFT, retrains, and repeats.

This tutorial builds the core of that loop with two pretrained models as a "committee":
  1. run short MD of water on a Pt(111) slab with MACE-MP-0 small
  2. re-evaluate every saved frame with MACE-MP-0 medium
  3. uncertainty = largest per-atom force disagreement between the two models
  4. pick the most uncertain, mutually distinct frames and write them out for DFT labeling

Run:   python committee_selection.py            (~3 min on a GPU)
Output: out/uncertainty.png, out/to_label.extxyz (frames you would send to DFT)
"""
import argparse
import sys
from pathlib import Path

import numpy as np
from ase import Atoms, units
from ase.build import fcc111, molecule
from ase.constraints import FixAtoms
from ase.io import write
from ase.md.langevin import Langevin
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common"))
from models import get_calc  # noqa: E402

OUT = Path(__file__).parent / "out"
OUT.mkdir(exist_ok=True)


def pt_water(n_water=10, seed=0):
    slab = fcc111("Pt", size=(3, 3, 4), vacuum=0.0, a=3.92)
    top = slab.positions[:, 2].max()
    slab.cell[2, 2] = top + 14.0
    rng = np.random.default_rng(seed)
    placed = []
    for _ in range(n_water):
        for _ in range(500):
            p = rng.random(3) * [1, 1, 0] @ slab.cell + [0, 0, top + 2.3 + rng.random() * 7]
            if all(np.linalg.norm(p - q) > 2.8 for q in placed):
                placed.append(p)
                break
        w = molecule("H2O")
        w.rotate(rng.random() * 360, rng.normal(size=3))
        w.translate(p - w.positions[0])
        slab += w
    slab.set_constraint(FixAtoms(indices=[a.index for a in slab if a.symbol == "Pt" and a.position[2] < 2.5]))
    slab.pbc = True
    return slab


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--steps", type=int, default=3000, help="0.5 fs steps")
    ap.add_argument("--T", type=float, default=350)
    ap.add_argument("--n-select", type=int, default=5)
    args = ap.parse_args()

    atoms = pt_water()
    atoms.calc = get_calc("mace-small", dtype="float32")
    MaxwellBoltzmannDistribution(atoms, temperature_K=args.T, rng=np.random.default_rng(0))
    dyn = Langevin(atoms, 0.5 * units.fs, temperature_K=args.T, friction=0.02, rng=np.random.default_rng(1))
    frames, f_small = [], []
    for i in range(0, args.steps, 25):
        dyn.run(25)
        frames.append(atoms.copy())
        f_small.append(atoms.get_forces().copy())

    judge = get_calc("mace-medium", dtype="float32")
    sigma = []
    for fr, fs in zip(frames, f_small):
        fr.calc = judge
        dev = np.linalg.norm(fr.get_forces() - fs, axis=1)
        sigma.append(dev.max())
    sigma = np.array(sigma)

    # greedy pick: most uncertain first, skipping frames within 4 saves of an earlier pick (diversity)
    order, picked = np.argsort(sigma)[::-1], []
    for k in order:
        if all(abs(k - j) > 4 for j in picked):
            picked.append(int(k))
        if len(picked) == args.n_select:
            break
    for k in picked:
        frames[k].info["max_force_dev_eV_A"] = float(sigma[k])
        frames[k].calc = None
    write(OUT / "to_label.extxyz", [frames[k] for k in sorted(picked)])
    print("max force disagreement (eV/Å): median %.3f, max %.3f" % (np.median(sigma), sigma.max()))
    print("frames selected for DFT labeling:", sorted(picked))

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    t = np.arange(len(sigma)) * 25 * 0.5e-3
    fig, ax = plt.subplots(figsize=(6.5, 3.6))
    ax.plot(t, sigma, color="#1f6fa8", lw=1.5)
    ax.plot(t[picked], sigma[picked], "o", color="#c2414f", label="selected for DFT")
    ax.set_xlabel("Time (ps)")
    ax.set_ylabel("max |ΔF| small vs medium (eV/Å)")
    ax.set_title("Committee disagreement along Pt(111)–water MD")
    ax.legend(frameon=False)
    fig.tight_layout()
    fig.savefig(OUT / "uncertainty.png", dpi=160)
    print("wrote", OUT / "uncertainty.png")


if __name__ == "__main__":
    main()