Models#

Every model takes an AtomicGraph and returns predicted properties such as node_energy and energy. The ForceStressOutput class enables the models to compute atomic forces and stress using autograd. Models are built by name from a config, or constructed directly with the same keys:

from xnn.common.models import available_models, build_model, ForceStressOutput

available_models()               # ['aimnet2', 'allegro', 'ani', ...]
model = build_model(cfg.model)   # Dispatches to <Model>.from_config(cfg.model)

# Wrap the model to compute forces and stress
model = ForceStressOutput(build_model(cfg.model), compute_stress=True)
out = model(graph)               # energy, node_energy, forces, stress

Pre-trained models can be fetched with from_pretrained() from the model hub (see Load a Pre-trained Model for more details). NequIP, MACE, Allegro, CACE, AIMNet2, Equiformer, EquiformerV2 and the SE(3) steerable CNN require the gnn extra dependencies installed (alongside e3nn).

MACE#

The MACE model (ACEsuit/mace) offers the higher-order equivariant message passing framework of Batatia et al., Adv. Neural Inf. Process. Syst. 35, 11423 (2022). Every published MACE-MP, MACE-OFF, etc. checkpoint can be fetched through the xnn’s model hub.

model:
  name: mace
  cutoff: 5.0
  species: [1, 6, 8]
  num_channels: 64
  num_interactions: 2         # Any depth from 0
  max_ell: 3
  correlation: 3
  avg_num_neighbors: 20.0
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}
  # foundation: mace-off23-small   # Uncomment to start from a pretrained checkpoint instead

Other options such as max_L, hidden_irreps, MLP_irreps, radial_type, distance_transform (Agnesi / Soft), pair_repulsion (ZBL), and scale / shift can also be set.

NequIP#

NequIP (mir-group/nequip) is an E(3)-equivariant message passing model with gated nonlinearities (Batzner et al., Nat. Commun. 13, 2453 (2022)).

model:
  name: nequip
  cutoff: 5.0
  species: [1, 6, 8]
  num_features: 32
  n_layers: 3
  l_max: 2
  parity: true
  avg_num_neighbors: 20.0
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including invariant_layers / invariant_neurons, resnet, use_sc, trainable_rbf, and atomic_scales are also available.

Allegro#

Allegro (mir-group/allegro v0.3.0) is a strictly local equivariant many-body potential without message passing (Musaelian et al., Nat. Commun. 14, 579 (2023)).

model:
  name: allegro
  cutoff: 5.0
  species: [1, 6, 8]
  num_layers: 2
  num_tensor_features: 16
  l_max: 1
  two_body_latent: [32, 64]
  latent: [64]
  avg_num_neighbors: 20.0
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including parity, env_embed, edge_eng, latent_resnet, and atomic_scales can also be used.

CACE#

CACE (BingqingCheng/cace) is the Cartesian atomic cluster expansion of Cheng, npj Comput. Mater. 10, 157 (2024). It builds body-ordered invariants from Cartesian monomials, with optional message passing.

model:
  name: cace
  cutoff: 5.5
  species: [1, 6, 8]
  n_atom_basis: 3
  max_l: 3
  max_nu: 3
  num_message_passing: 1      # 0 gives plain Cartesian ACE
  avg_num_neighbors: 10.0

Other options, including message_types (M / Ar / Bchi), n_rbf, readout_hidden and atomic_energies, are also available.

AIMNet2#

AIMNet2 (isayevlab/aimnetcentral) is the atoms-in-molecules network of Anstine et al., Chem. Sci. 16, 10228 (2025) for neutral, charged and open-shell molecules. It predicts partial charges that sum exactly to the net charge and adds their Coulomb energy. The six published families can be fetched through the model hub.

from xnn.common.models import from_pretrained

model = from_pretrained("aimnet2")                                    # wB97M-D3, with its D3 term
model = from_pretrained("aimnet2", model_options={"coulomb": "pme"})  # Periodic cells: dsf / ewald / pme

The net charge and spin multiplicity come from the structure. To train from scratch, set n_features, n_rbf, n_interactions, hidden, aim_size, charge_channels (2 for open shells), coulomb and lr_cutoff. The outputs also include charges and dipole.

SchNet#

SchNet (schnetpack) is the continuous-filter convolutional network of Schütt et al., Adv. Neural Inf. Process. Syst. 30 (2017). Its defaults are those of the reference code.

model:
  name: schnet
  cutoff: 5.0
  n_features: 128
  n_interactions: 6
  n_rbf: 20
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

configs/model/schnet.yaml lists every option with its default, and the paper’s settings.

DimeNet and DimeNet++#

DimeNet and DimeNetPP (gasteigerjo/dimenet) are the directional message passing networks of Gasteiger et al., Int. Conf. Learn. Represent. (2020) and Gasteiger et al., NeurIPS Workshop on Machine Learning for Molecules (2020). Messages live on directed edges and are updated from the distances and angles of neighboring edges. DimeNet++ replaces the bilinear interaction with a cheaper one.

model:
  name: dimenet++             # Or dimenet
  cutoff: 5.0
  n_features: 128
  n_interactions: 4           # 6 for dimenet
  n_rbf: 6
  n_spherical: 7
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including n_bilinear (DimeNet), n_triplet_features / n_basis_features / n_output_features (DimeNet++), p and trainable_rbf, are also available.

GemNet#

GemNet (TUM-DAML/gemnet_pytorch) is the geometric message passing network of Gasteiger et al., Adv. Neural Inf. Process. Syst. 34, 6790 (2021). Edge embeddings are updated from neighboring edges (distances and angles) and, with quadruplets, from edges two hops away (adding dihedral angles). The trainer fits its scaling factors on the training structures before the first epoch.

model:
  name: gemnet
  cutoff: 5.0                 # Embedding cutoff
  n_features: 128
  n_interactions: 4
  n_rbf: 6
  int_cutoff: 10.0            # Graphs are built to this radius
  n_spherical: 7
  quadruplets: true           # false gives GemNet-T
  direct_forces: false        # true gives GemNet-dQ / -dT
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including the feature sizes n_edge_features, n_triplet_features and n_quadruplet_features, scaling_factors and fit_scaling, can also be set. Direct forces are not conservative, so they cannot be combined with LES or dispersion terms or exported to TorchScript.

PaiNN#

PaiNN (schnetpack) is the equivariant message passing network of Schütt et al., Proc. Mach. Learn. Res. 139, 9377 (2021) with scalar and vector features. Its defaults are those of the reference code. Optional heads predict dipole moments and polarizability tensors, trained with dipole_weight / polarizability_weight on data that has dipole / polarizability labels.

model:
  name: painn
  cutoff: 5.0
  n_features: 128
  n_interactions: 3
  n_rbf: 20
  dipole: true                # Outputs the dipole and latent charges
  polarizability: true
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

configs/model/painn.yaml lists every option with its default, and the paper’s settings.

TensorNet#

TensorNet (torchmd/torchmd-net) is the Cartesian tensor network of Simeon and De Fabritiis, Adv. Neural Inf. Process. Syst. 36, 37334 (2023), the model of TorchMD-Net 2.0 (Pelaez et al., J. Chem. Theory Comput. 20, 4076 (2024)). Here, every atom carries rank-2 tensors whose scalar, vector and traceless parts are mixed by matrix products. A total_charge of the structure enters the products.

model:
  name: tensornet
  cutoff: 4.5
  n_features: 128
  n_interactions: 2
  n_rbf: 32
  equivariance_group: O(3)    # SO(3) distinguishes enantiomers
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options:

  • radial_basis: expnorm, gaussian, bessel or smooth_bessel (Kocer et al., AIP Adv. 10, 015021 (2020)).

  • trainable_rbf, activation, energy_shift and energy_scale.

  • readout: mlp (default) or gated. readout_hidden sets its widths.

  • self_pairs: whether each atom is its own neighbor (default true).

The MatGL TensorNet foundation potentials trained on MatPES load with one call:

from xnn.gnn.models import TensorNet

model = TensorNet.from_foundation("tensornet-matpes-pbe-2025.2")   # or tensornet-matpes-r2scan-2025.2
  • They use the smooth spherical Bessel basis, the gated readout and no self pairs.

  • The weights are downloaded from MatGL’s release and keep MatGL’s BSD-3-Clause license.

QET#

QET (MatGL) is the charge-equilibrated TensorNet of Ko et al., arXiv:2511.07249 (2025). TensorNet’s features give every atom an electronegativity and a hardness. The charges follow from them in closed form, at the structure’s total charge, so the cost stays linear in the number of atoms. The atomic energy then reads the charge and the Coulomb potential of the neighbors’ charges.

model:
  name: qet
  cutoff: 5.0
  n_features: 64
  n_interactions: 2
  hardness: environment       # or element: one hardness per element (default)
optim:
  charge_weight: 1.0          # train the charges on "charges" labels

Give each structure its total charge, and optionally an applied potential (V) on some atoms, such as a bias on an electrode:

{"pos": pos, "atomic_numbers": z, "cell": cell, "total_charge": 1.0,
 "external_potential": phi}                   # (N,), optional
  • The model returns "charges" and "electrostatic_potential" next to the energy.

  • The charge widths are the covalent radii; trainable_widths: true learns them.

  • The other options are those of TensorNet. The defaults follow MatGL: 32 Gaussians and no self pairs.

The MatGL QET foundation potentials trained on MatPES load with one call:

from xnn.gnn.models import QET

model = QET.from_foundation("qet-matpes-pbe-2025.2")   # or qet-matpes-r2scan-2025.2
  • The weights are downloaded from MatGL’s release and keep MatGL’s BSD-3-Clause license.

MEGNet#

MEGNet (MatGL) predicts one property per structure, such as a band gap (Chen et al., Chem. Mater. 31, 3564 (2019)). Multi-fidelity MEGNet (Chen et al., Nat. Comput. Sci. 1, 46 (2021)) also takes the fidelity of each label.

model:
  name: megnet
  cutoff: 5.0
  n_state_types: 4            # Number of fidelities
  state_dim: 16
optim:
  property_weight: 1.0

Give each structure its target and fidelity:

{"pos": pos, "atomic_numbers": z, "cell": cell, "properties": 1.1, "state": 2}
  • The loss does not divide properties by the number of atoms.

  • Without n_state_types, state is a list of floats, such as a temperature.

  • MEGNet predicts no energy, so it gives no forces.

  • A disordered site takes the occupancy-weighted mix of its elements, as in the multi-fidelity paper. Give it as "occupancies": [{"Al": 0.3, "Ga": 0.7}, ...], one mapping per site.

MatGL’s pretrained models load with one call:

from xnn.common.data import structure_to_graph
from xnn.gnn.models import MEGNet

model = MEGNet.from_foundation("megnet-mp-2019.4.1-bandgap-mfi")   # or megnet-mp-2018.6.1-eform
s = {"pos": pos, "atomic_numbers": z, "cell": cell, "state": model.state_label("HSE")}
print(model(structure_to_graph(s, model.cutoff))["properties"])     # band gap in eV
  • The band gap fidelities are PBE, GLLB-SC, HSE and SCAN.

  • The band gap model is off by about 1 eV. Train your own model for predicting the band gaps.

  • The weights of the pre-trained models keep MatGL’s BSD-3-Clause license.

CGCNN#

CGCNN is the crystal graph network of Xie and Grossman, Phys. Rev. Lett. 120, 145301 (2018). It predicts one property per crystal from the 12 nearest neighbors of every atom.

model:
  name: cgcnn
  cutoff: 8.0
optim:
  property_weight: 1.0

Each training structure carries its target in properties:

{"pos": pos, "atomic_numbers": z, "cell": cell, "properties": -1.4}
  • CGCNN predicts no energy, so it gives no forces.

  • The atom features come from the authors’ element table, which is downloaded on first use. Set atom_features: onehot to learn one vector per element instead.

  • Set classification: true for a two-class task. The output is then the probability of the second class.

  • For predictions, pass max_neighbors=model.max_neighbors to structure_to_graph. The graphs then keep the same 12 neighbors as in training.

The authors’ pretrained models load with one call:

from xnn.common.data import structure_to_graph
from xnn.gnn.models import CGCNN

model = CGCNN.from_foundation("cgcnn-formation-energy-per-atom")   # or cgcnn-band-gap, ...
s = {"pos": pos, "atomic_numbers": z, "cell": cell}
graph = structure_to_graph(s, model.cutoff, max_neighbors=model.max_neighbors)
print(model(graph)["properties"])                                   # eV/atom
  • The available models are cgcnn-formation-energy-per-atom, cgcnn-final-energy-per-atom, cgcnn-band-gap, cgcnn-efermi, cgcnn-bulk-moduli, cgcnn-shear-moduli, cgcnn-poisson-ratio and cgcnn-semi-metal-classification.

  • The bulk and shear moduli are given in log10(GPa).

  • The classification model gives the probability that a crystal is a metal.

  • The weights and the element table keep the authors’ MIT license.

SE(3) steerable CNN and 3D CNN#

SteerableCNN is the rotation-equivariant convolutional network of Weiler et al., Adv. Neural Inf. Process. Syst. 31 (2018), applied to a voxel grid around each atom (one density channel per species). CNN3D is the conventional 3D CNN baseline with the same grids and readout.

model:
  name: se3cnn                # Or cnn3d
  cutoff: 4.0                 # Half the side of the voxel cube
  species: [1, 6, 8]
  grid_size: 17               # Voxels per axis
  n_features: 32              # Channels of the last block
  n_interactions: 3           # Number of blocks
  l_max: 2                    # Highest field order (se3cnn only)
  kernel_size: 5
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including strides, activation, normalization, bandlimit and sigma, can also be set. Because the grid is discrete, the steerable model is exactly invariant only under rotations that map the grid onto itself, and approximately invariant under all others.

Spherical CNN#

SphericalCNN (jonas-koehler/s2cnn) is the rotation-equivariant network of Cohen et al., Int. Conf. Learn. Represent. (2018). Each atom sees its neighbors as signals on a sphere around it, one channel per species, which spherical convolutions map to rotation-invariant per-atom energies.

model:
  name: s2cnn
  cutoff: 10.0                # Neighbor radius of the potential sums
  species: [1, 6, 7, 8, 16]
  radius: 0.48                # Sphere radius in Angstrom
  bandwidth: 10               # 2b x 2b samples per sphere
  n_features: 160             # Channels of the last block
  n_interactions: 5           # ResNet blocks, as in the paper
  atomic_energies: {1: -13.6, 6: -1029.9, 7: -1485.3, 8: -2042.8, 16: -10831.3}

Other options, including features / bandwidths per block, set_readout (the paper’s DeepSet readout), normalization and activation, are also available.

ANI#

ANI (aiqm/torchani) is the per-element network over atomic environment vectors of Smith et al., Chem. Sci. 8, 3192 (2017). The published parameterizations are presets, and each has its training set in the data hub:

from xnn.dnn.models import ANI

ANI.ani1(species=[1, 6, 7, 8])      # ANI-1
ANI.ani1x(species=[1, 6, 7, 8])     # ANI-1x
ANI.ani1ccx(species=[1, 6, 7, 8])   # ANI-1ccx, coupled-cluster self energies
ANI.ani2x()                         # ANI-2x, seven elements (H, C, N, O, S, F, Cl)

In a config, set preset: ani-2x (or ani-1, ani-1x, ani-1ccx). Without a preset, species, radial_cutoff, angular_cutoff, hidden, activation and atomic_energies define the model.

PhysNet#

PhysNet (MMunibas/PhysNet) is the message passing network of Unke and Meuwly, J. Chem. Theory Comput. 15, 3678 (2019) with explicit electrostatics and D3 dispersion, translated from TensorFlow to PyTorch. It embeds elements directly, so it needs no species list, and also returns charges and dipole.

model:
  name: physnet
  cutoff: 10.0
  n_features: 128
  n_rbf: 64
  n_interactions: 5
  use_electrostatics: true
  use_dispersion: true

HDNNP#

High-dimensional neural network potentials cover the four generations of the classification of Behler, Chem. Rev. 121, 10037 (2021) and match the RuNNer code:

  • 1G (nnp1g): one network maps the interatomic distances of a fixed system to its energy.

  • 2G (hdnnp): a sum of atomic energies from one network per element on atom-centered symmetry functions.

  • 3G (generation: 3): a second set of networks predicts charges, whose electrostatic energy is added.

  • 4G (generation: 4): a charge equilibration over the whole structure gives the charges, which allows non-local charge transfer.

from xnn.dnn.common.runner import load_runner_model

model = load_runner_model("runner_model/")   # input.nn, weights and scaling files
model.fit_scaling(train_graphs)              # Fit the symmetry-function scaling

The 3G and 4G models also return charges, energy_elec and dipole. You can also train the charges with charge_weight on charges labels. The configs/model/hdnnp.yaml config file lists every available option.

QRNN#

QRNN is the charge recursive neural network of Jacobson et al., J. Chem. Theory Comput. 18, 2354 (2022), written from the paper. It is an ANI-style HDNNP for neutral and charged closed-shell molecules. Two cycles of element networks predict atomic charges that add up to the net charge, and the charges then enter the atomic energies.

model:
  name: qrnn
  cutoff: 5.2
  extra:
    species: [1, 6, 7, 8, 9, 15, 16, 17]   # H, C, N, O, F, P, S, Cl
    charge_model: recursive                # or qeq, the paper's QeqNN
    coulomb: true                          # set both to false for delta learning
    dispersion: true
  • Give the net charge of every structure as total_charge. The model returns charges and, for molecules, dipole.

  • Train the charges on dipole labels (dipole_weight) or on charges labels (charge_weight), as the paper does.

  • The Coulomb and wB97X-D dispersion terms sum over every atom pair of a molecule. Turn them off for periodic cells.

The configs/model/qrnn.yaml config file lists every available option.

Equivariant Transformer (ET)#

EquivariantTransformer (torchmd/torchmd-net) is the equivariant transformer of Thölke and De Fabritiis, Int. Conf. Learn. Represent. (2022): scalar and vector features updated by a distance-filtered multi-head attention. The default vector_cutoff applies the TorchMD-Net 2.0 fix that makes the energy continuous at the cutoff. Setting it to false corresponds to the original model.

model:
  name: et
  cutoff: 5.0
  n_features: 128
  n_interactions: 6
  n_rbf: 32
  num_heads: 8
  vector_cutoff: true
  species: [1, 6, 8]
  atomic_energies: {1: -13.6, 6: -1029.9, 8: -2042.8}

Other options, including neighbor_embedding, distance_influence (both / keys / values / none), attn_activation, radial_basis (expnorm, gaussian or bessel), trainable_rbf and energy_shift / energy_scale, are also available. The attention weights of a structure are returned by model.attention_weights(graph).

Equiformer#

Equiformer (atomicarchitects/equiformer) is the equivariant graph attention transformer of Liao and Smidt, Int. Conf. Learn. Represent. (2023). Irreps features pass through pre-norm blocks of graph attention and feed-forward networks. The attention combines MLP attention weights with non-linear messages built from depth-wise tensor products.

model:
  name: equiformer
  cutoff: 5.0
  n_features: 128      # even scalars of the paper architecture
  n_interactions: 6
  n_rbf: 32
  l_max: 2             # 1 (OC20), 2 (QM9, MD17) or 3 (MD17)
  e3: false            # true: the E(3) model with both parities
  radial_basis: expnorm
  smooth_cutoff: true  # continuous energy at the cutoff (not in the paper)

n_features scales the irreps of the paper architecture. Explicit irreps (irreps_node_embedding, irreps_head, irreps_mlp_mid) override it. Other options include attention: dot_product (the ablation baseline), nonlinear_message, avg_degree / avg_num_nodes and the dropout rates.

EquiformerV2#

EquiformerV2 (fairchem) is the eSCN-based successor of Liao et al., Int. Conf. Learn. Represent. (2024). The tensor products become SO(2) linear maps in edge-aligned frames, which makes degrees up to 6 or 8 affordable. The attention adds a layer norm on its scalars, the activations act on samples of the sphere, and the layer norm treats degree 0 separately.

model:
  name: equiformer_v2
  cutoff: 5.0
  n_features: 96       # channels per coefficient
  n_interactions: 6
  n_rbf: 128
  l_max: 4
  m_max: 4             # orders kept in the edge frames (2 in the OC20 models)
  num_heads: 4
  smooth_cutoff: true
  # direct_forces: true  # the OC20 force head (not conservative)

Forces and stress from autograd include the dependence of the edge frames on the positions, so they are exact derivatives of the energy. The reference code detaches the frames. norm_type (layer_norm_sh / layer_norm / rms_norm_sh), activation (sep_s2 / s2 / gate), use_grid_mlp and grid_resolution select the variants of the paper’s ablations. The reference’s truncation to the nearest max_neighbors atoms is not supported, because it makes the energy discontinuous. Use a smaller cutoff instead.

BAMBOO#

BAMBOO (bytedance/bamboo) is the graph equivariant transformer of Gong et al., Nat. Mach. Intell. 7, 543 (2025) with a charge-equilibrium electrostatic term. It works in kcal/mol and Angstrom and also returns charges, dipole, energy_nn and energy_elec.

model:
  name: bamboo
  cutoff: 5.0
  n_features: 64
  n_interactions: 3
  num_heads: 16
  use_electrostatics: true
  use_dispersion: false       # Optional D3(CSO) term

SpookyNet#

SpookyNet (OUnke/SpookyNet) is the message passing network of Unke et al., Nat. Commun. 12, 7273 (2021) with electronic degrees of freedom and nonlocal effects. The total charge and spin enter as embeddings, and self-attention over all atoms carries nonlocal effects. The saved reference models can be loaded with SpookyNet.from_reference_checkpoint(path).

model:
  name: spookynet
  cutoff: 5.29                # 10 bohr
  n_features: 128
  n_interactions: 6
  n_rbf: 16
  lr_cutoff: 10.0             # Long-range cutoff, needed for periodic cells
  electrostatics: false       # Enable when you have dipole or charge labels
  d4_dispersion: false

Other options, including nonlocal_interactions, attention (favor / exact), zbl_repulsion and ewald, are also available. The outputs also include charges and dipole.

ByteFF and ByteFF-Pol#

ByteFF and ByteFFPol (ByteDance-Seed/byteff2) are classical force fields whose parameters a graph transformer predicts from the two-dimensional molecular graph. ByteFF (Zheng et al., Chem. Sci. 16, 2730 (2025)) has the AMBER functional form. ByteFF-Pol (Zheng et al., Nat. Commun. 17, 8276 (2026)) adds polarization and splits the non-bonded energy into repulsion, dispersion, electrostatics, polarization and charge transfer terms.

from xnn.hybnn.models import ByteFF, ByteFFPol

model = ByteFF.from_foundation("byteff-26")       # five networks, averaged
model.bind("CC(=O)Nc1ccc(O)cc1")                  # SMILES, RDKit Mol or ase.Atoms
params = model.predicted_parameters()             # kcal/mol, Angstrom, radians, e

pol = ByteFFPol.from_foundation()                 # ByteFF-Pol-25
pol.bind(["CCOC(=O)OC", "[Li+]"])                 # a cluster

box = ByteFFPol.from_foundation(cutoff=10.0)      # periodic cells (Ewald sums)
box.bind(["COC(=O)OC"] * 60 + ["[Li+]", "FS(=O)(=O)[N-]S(=O)(=O)F"] * 5)
  • A model is bound to one system. Every structure it evaluates is a conformation of that system, in the atom order of the bound molecules.

  • The parameters are predicted once per distinct molecule and reused until the weights change.

  • Every pair of atoms interacts by default. Both models also take a cutoff (all_pairs: false) for periodic cells. ByteFF truncates or switches its pairs there. ByteFF-Pol truncates its short-range terms, adds their long-range correction and sums the charges and induced dipoles by particle mesh Ewald, as byteff2’s OpenMM setup does. A cell must be at least twice the cutoff wide.

  • For molecular dynamics in a cell, StepGraph evaluates ByteFF-Pol on a step plan (plan_step()): a Verlet pair list, fixed solve lengths and, on a GPU, one replayed CUDA graph per step. predictor: aspc starts each dipole solve from the last steps’ dipoles. Install the vesin extra: it finds the next pair list while a step runs. StepGraph(..., late_checks=True) keeps the GPU busy between steps (see the step plans of AMOEBA and HIPPO below).

  • With a cutoff on a GPU, ByteFF evaluates its terms with the fused kernels of the classical force fields (use_fast), for inference and training alike.

  • Without a cutoff, ByteFF and ByteFF-Pol compile their energy terms on a GPU (use_fast). Compiling takes tens of seconds per system and batch size, so "auto" waits for 1000 evaluations. Pass use_fast=True for molecular dynamics and training.

  • For molecules and clusters on a GPU, GraphedEvaluation (or XNNCalculator(..., cuda_graph=True)) replays an evaluation as one CUDA graph: five to eight times faster for small systems, with the same results.

  • The released networks are licensed for non-commercial use only (CC BY-NC 4.0). They download on first use, and xnn states their terms when they load.

model:
  name: byteff                # or byteff_pol
  cutoff: 0.1                 # Neighbor-list radius; every pair interacts
  structure: CCO
  members: 1

GDML / sGDML#

SGDML is the symmetrized gradient-domain machine-learning force field (Chmiela et al., Sci. Adv. 3, e1603015 (2017); Chmiela et al., Nat. Commun. 9, 3887 (2018); Chmiela et al., Comput. Phys. Commun. 240, 38 (2019)). It models one molecule with its atoms in a fixed order. The energy is a kernel expansion over the training geometries, and its gradient reproduces the training forces.

from xnn.krnn.models import SGDML
from xnn.krnn.common import load_sgdml_model

model = SGDML(species=["C", "C", "O"] + ["H"] * 6, sigma=10.0)
model.fit(train_graphs)                  # Forces, plus energies for the constant
model = load_sgdml_model("m_ethanol.npz")  # A model trained by the sGDML package
  • fit finds the molecule’s permutational symmetries from the training geometries. Use the gdml model to leave them out.

  • Pass a list of sigma values and validation structures to pick the length scale with the lowest force error.

  • Every structure must list the atoms in the model’s order.

  • Large training sets are fitted iteratively when the kernel matrix does not fit in memory. Pass solver="cg" to choose this yourself. The result matches the exact fit to the tolerance tol (1e-4 by default).

The configs/model/sgdml.yaml config file lists every available option.

ReaxFF / ReaxFF-nn#

ReaxFF is the bond-order reactive force field of van Duin et al., J. Phys. Chem. A 105, 9396 (2001) and its neural variant. Bond orders are created from distances. Therefore, bonds break and form smoothly, and any parameter group can be refit by gradient descent.

from xnn.ffnn.models import ReaxFF
from xnn.ffnn.models.ffield import to_forcefield

model = ReaxFF("CHO_cho_2008", trainable=("Desi", "ang_val1"))
to_forcefield(model.export_library()).write("refit.frc")

The parameters come from a shipped .frc field by name, a .frc path or a ReaxFF-nn JSON library (see Working with Force-field Files). For classical fields, the default conventions: lammps reproduces LAMMPS pair_style reaxff. So, a field refit in xnn runs unchanged in LAMMPS.

OPLS / L-OPLS#

OPLS is the fixed-topology force field of Jorgensen et al., J. Am. Chem. Soc. 118, 11225 (1996), matching OpenMM. from_atoms assigns the atom types from the SMARTS templates of the parameter file, so no type names are needed.

from xnn.ffnn.models import OPLS

model = OPLS.from_atoms(atoms, "oplsaa", cutoff=10.0)    # Or "lopls", "oplsaa-1996", "CL&P"
model = OPLS.from_atoms(atoms, "oplsaa", trainable=("dihedral_v",))

Other options such as switch_width and fudge_lj / fudge_qq can also be set.

A refit keeps the molecule’s total charge: the charges the model uses are the trainable per-type values projected onto that constraint (constrain_charge, on by default). Labels on another energy zero than the force field’s, such as formation energies, are taken up by per-element reference energies: set atomic_energies: estimated in the config (or call estimate_atomic_energies()) and add atom_ref to trainable to let them move with the fit. A pull of the parameters toward their starting values, optim.prior_weight, keeps a fit of many parameters against few data well posed (Training).

DREIDING / DREIDING-X6#

Dreiding is the generic force field of Mayo et al., J. Phys. Chem. 94, 8897 (1990), matching the LAMMPS DREIDING styles. Its parameters are generated from per-atom rules, so it covers element combinations nobody tabulated, and those rules are what you train.

from xnn.ffnn.models import Dreiding

model = Dreiding.from_atoms(atoms, "dreiding", cutoff=10.0, charges="gasteiger")
model = Dreiding.from_atoms(atoms, "dreiding/X6")      # Exponential-6 van der Waals

Other options, including bond_style (harmonic / morse), angle_style and hbond, are also available. Set resonance types, such as an amide C_R-N_R, explicitly.

GFN-FF#

GFNFF is the general force field of Spicher et al., Angew. Chem. Int. Ed. 59, 15665 (2020). It needs no atom types and no input topology. The model derives the bonds, hybridization, pi systems, charges and all parameters from the elements, the positions and the total charge. It covers molecules, ions and periodic structures of the elements H to Rn. It is an independent implementation based on the paper, verified against the xtb program as a black box.

from xnn.ffnn.models import GFNFF

model = GFNFF.from_atoms(atoms, charge=0)               # Molecule, ion or periodic ase.Atoms
model = GFNFF(numbers, positions, charge=0, cell=cell)  # Lattice vectors in Angstrom, one per row

model.eval()
terms, gradient = model.energy_and_gradient(positions)  # Hartree, Hartree per Angstrom
  • A model is bound to the structure it was built from. It evaluates conformations of that structure, with the same atoms in the same order.

  • The bonded terms keep the topology of the build structure. Hydrogen and halogen bonds are chosen again for every conformation, as in xtb. Set fixed_lists=True to keep those of the build structure instead.

  • A periodic model evaluates each structure in its own cell. For a cell, energy_and_gradient also returns the gradient with respect to the cell, which gives the stress.

  • As in xtb, different cells of the same crystal can give different energies. In exactly symmetric cells with degenerate pi orbitals, such as some polyacetylene and graphene supercells, the energy depends on round-off. xnn and xtb can then differ by up to about 0.01 Hartree, and xtb itself changes as much when only the atom order changes.

  • By default the model runs fused kernels on CPUs and GPUs, in evaluation and training. They match the eager terms to round-off, including the second derivatives that force and stress training needs. Set use_fast=False for the eager terms, which are differentiable to any order.

  • model.float() switches the model to single precision.

  • The element parameters are downloaded from the xtb repository on first use. They are kept in the model cache with a LICENSE.txt beside them.

The ASE calculator and the MDI engine serve the bound system with forces and stress, for molecules and periodic cells. To serve a checkpoint with xnn mdi, give the structure in the model options of the config: atomic_numbers, positions, charge and, for a periodic system, cell. The model also exports to TorchScript for LAMMPS and other drivers:

from xnn.common.deploy import export_torchscript_potential

export_torchscript_potential(model, cutoff=1.0, path="gfnff.pt")
  • The exported file needs the whole system on one rank, with the atoms in the build order.

  • A periodic export keeps its hydrogen and halogen bonds while every atom stays within half the skin of its starting position. Beyond that, a call raises an error. For longer runs, build the model with a larger skin.

AMBER (ff94)#

Amber is the force field of Cornell et al., J. Am. Chem. Soc. 117, 5179 (1995), matching LAMMPS and the AMBER programs. Its charges belong to residue templates rather than to atom types: from_atoms matches the residues of the parameter file (amino acids with their terminal forms, nucleotides, capping groups, water, ions) to assign types and RESP charges, places the impropers by the AMBER builder’s rules, and types other organic molecules from SMARTS templates (give those their charges with charges=).

from xnn.ffnn.models import Amber

model = Amber.from_atoms(atoms, "ff94", cutoff=10.0)          # a peptide, nucleic acid, water, ions
model = Amber.from_atoms(atoms, "ff94", charges=resp_charges)  # a small molecule with its own charges
model = Amber.from_atoms(atoms, "ff94", trainable=("dihedral_k", "charge"))

The options cutoff, switch_width, fudge_lj and fudge_qq work as for OPLS. A config may give the AMBER divisors scnb and scee instead of the fudge factors. The trainable groups are the barrier heights dihedral_k and improper_k, the bond and angle constants, the van der Waals rstar and epsilon, the per-atom charge and atom_ref. constrain_charge holds the charges to the system’s total charge. The periodicities and phases of the Fourier terms stay fixed. Later AMBER sets with the same functional form are further .frc libraries for this model.

CHARMM22#

Charmm is the all-atom protein force field of MacKerell et al., J. Phys. Chem. B 102, 3586 (1998), matching LAMMPS and NAMD. On top of the AMBER terms it has Urey-Bradley 1,3 terms, harmonic impropers, Lennard-Jones parameters for 1,4 pairs and pair-specific overrides (NBFIX). The 1,4 electrostatics are not scaled. from_atoms assigns types, charges and impropers from the residue templates of the parameter file: amino acids with their terminal, capped and patched forms, TIP3P water and ions. Small model compounds are typed from SMARTS templates.

from xnn.ffnn.models import Charmm

model = Charmm.from_atoms(atoms, "charmm22", cutoff=12.0)   # a peptide, water, ions
model = Charmm.from_atoms(atoms, "charmm22", trainable=("dihedral_k", "ub_k", "charge"))

The options are cutoff, switch_width, fudge_qq (CHARMM’s e14fac) and coulomb_constant. The constant defaults to 332.0716 of the CHARMM program. NAMD uses 332.0636 and LAMMPS 332.06371. The trainable groups are the force constants (bond_k, angle_k, ub_k, dihedral_k, improper_k), the equilibrium values (bond_r0, angle_theta0, ub_s0), the Lennard-Jones rstar and epsilon with their 1,4 and pair-override counterparts, the per-atom charge and atom_ref. Periodicities, phases and improper reference angles stay fixed. The CMAP correction of later CHARMM sets is not implemented, so charmm22 is the 1998 force field.

Note

1,4 interactions in small rings. CHARMM ties its 1,4 pairs to the dihedrals: every dihedral i-j-k-l implies a Lennard-Jones and Coulomb pair between i and l. In a six-membered ring two dihedrals reach the same para pair. In a five-membered ring a “1,4” pair is 1,3 the other way round, and in a four-membered ring it is bonded. The CHARMM rule is that the shortest bond path wins and that a pair counts once. xnn builds its 1,4 list that way from the topology, as CHARMM, NAMD, GROMACS and OpenMM do.

LAMMPS is the exception. Its dihedral_style charmm evaluates the 1,4 pair once per dihedral with a weight from the data file, so a weight of 1 everywhere double counts the para pairs of six-membered rings and adds 1,2 and 1,3 pairs across smaller rings. When comparing with or exporting to LAMMPS, use 1/2 in six-membered rings, 0 in four- and five-membered rings, and 0 on all but one of the terms that share a quadruple. The fidelity notebook derives those weights from xnn’s pair list.

Classical force fields on GPUs and in LAMMPS#

On a GPU, OPLS, AMBER, CHARMM, DREIDING, ReaxFF and ReaxFF-nn evaluate their terms on fused kernels (use_fast="auto"), in evaluation and in training. A stress loss trains on the eager terms. The numbers are those of the eager terms to round-off. For MD, ClassicalStepper and ReaxFFStepper keep a neighbor list with a skin. On a GPU they replay each step as a CUDA graph. On a CPU they run the kernels as C++ loops (Run Models on Fused GPU Kernels). write_lammps_input() writes the inputs that evaluate a model with LAMMPS’s own styles, ReaxFF, AMOEBA and HIPPO included (Export to LAMMPS and TorchScript).

AMOEBA and HIPPO#

Amoeba is the polarizable multipole force field of Ren and Ponder, J. Phys. Chem. B 107, 5933 (2003) and Ponder et al., J. Phys. Chem. B 114, 2549 (2010), with the protein set of Shi et al., J. Chem. Theory Comput. 9, 4046 (2013). Hippo is the HIPPO force field of Rackers et al., J. Chem. Theory Comput. 17, 7056 (2021). Both match Tinker term by term. Forces, torques and the stress come from autograd.

from xnn.ffnn.models import Amoeba, Hippo

water = Amoeba.from_atoms(atoms, "amoeba-water-2003", cutoff=30.0)   # a water cluster
hippo = Hippo.from_atoms(atoms, "hippo-water-2021", cutoff=30.0)
peptide = Amoeba.from_atoms(atoms, "amoebapro13", cutoff=12.0)       # a peptide, water, ions
model, structure = Amoeba.from_tinker_xyz("ubiquitin.xyz", "amoebapro13")
model = Amoeba.from_atoms(atoms, "amoebapro13", trainable=("torsion", "vdw", "polarizability"))

AMOEBA has the valence terms of the papers (anharmonic bonds and angles, stretch-bend, Urey-Bradley, out-of-plane bends, torsions, pi-torsions and torsion-torsion maps), the buffered 14-7 van der Waals term, permanent multipoles in local frames and Thole-damped mutual induction. HIPPO keeps the valence terms and the multipoles. It replaces the intermolecular terms by charge penetration, density-damped induction, Pauli repulsion, damped dispersion, charge transfer and charge flux. A library with exchpol parameters adds the exchange polarization of Chung et al., J. Phys. Chem. B 126, 7579 (2022), where the overlap with each neighbor shrinks an atom’s polarizability along the pair. As in Tinker, a pair takes part when either of its classes is used, and in a cell the term is tapered by the switch of the repulsion. configs/model/amoeba.yaml and configs/model/hippo.yaml list every option with its default.

Ions#

A HIPPO library can add three terms for ions. In a Tinker .prm file they look like this (class numbers, kcal/mol and angstrom):

mbct-form  ceq
ionct      101   1    700.0   3.0          # Li+ with water O
ionct      101   5    650.0   2.8   0.54   # Li+ with PF6- F, x of PF6-
mbct       101   0.14                      # many-body term of Li+
ionpair    101   1    500.0   300.0   3.5  # pair correction
  • ionct is the charge transfer from a partner into a single-atom ion, -A exp(-B R). It replaces HIPPO’s charge transfer for that ion. Give each pair of classes one row, in one order.

  • mbct turns on the many-body charge transfer of every molecule with an atom of that class. It works for single-atom ions and for polyatomic ions such as PF6-. forward reports it as e_mbct.

  • ionpair adds A exp(-beta R) - C f6(beta R) / R^6 to the repulsion and the dispersion of a single-atom ion.

The many-body term corrects the pairwise charge transfer when an ion has several ligands. Each extra ligand gains less charge, so the term saturates. It uses the pair charge transfer of the ion with each ligand molecule: the ionct row if there is one, else HIPPO’s own. For a cation-anion pair, both ions see each other.

x is the ratio of the ion’s hardness to a ligand’s. The mbct row sets it for the ion. An optional last column on an ionct row sets it for that partner’s molecule.

mbct-form picks the form of the term:

  • ceq (default) is a charge equilibration in which no ligand gives charge back to the ion.

  • weighted is the form of xnn 0.26.0, with one x per ion and the setting mbct-c0. A file with mbct-c0 but no mbct-form warns that it now gets ceq. Add mbct-form weighted to keep the old model.

The terms train as the groups ionct, mbct (with the rows’ x) and ionpair. LAMMPS has no counterpart, so such a library has no LAMMPS export.

Molecules#

For a molecule or cluster, every pair within cutoff interacts in full, so choose a cutoff that encloses the whole system. polarization selects mutual, direct or no induction. The default is the library’s setting.

A batch of molecules of up to a thousand atoms each is solved directly, as one block-diagonal system. Larger molecules and cells use conjugate gradients. solver overrides the choice and preconditioner selects "diagonal" (the default), "block", "neumann" or "block-neumann". The others take fewer iterations but rarely give a faster step. polar_eps sets the convergence of the induced dipoles in Debye.

Periodic cells#

A structure with a cell is evaluated with Ewald sums. The multipoles, the induction and HIPPO’s dispersion split into a real-space part within ewald_cutoff and a particle-mesh part. The van der Waals, repulsion and charge-transfer terms are switched off smoothly before their cutoff.

box = Amoeba.from_atoms(water_box, "amoeba-water-2003", cutoff=7.3, vdw_cutoff=7.0, taper=6.3)
out = ForceStressOutput(box, compute_stress=True)(graph)

The defaults follow Tinker. The Ewald coefficient comes from the real-space cutoff (7 Angstrom at most) and the mesh has 1.2 points per Angstrom. Every mesh size, a requested one too, is rounded up to an even size with prime factors 2, 3 and 5, at least 16 (pme_grid=27 gives 30). The mesh sums use the least-squares spline moduli, so the energies match Tinker’s at the same keys even on a coarse mesh.

  • ewald_alpha, pewald_alpha and dewald_alpha set the three Ewald coefficients, pme_grid and pme_order the mesh.

  • vdw_cutoff, repulsion_cutoff, chgtrn_cutoff and dispersion_cutoff set the switched terms, taper the start of the switch. Keep the neighbor cutoff about 0.3 Angstrom above the van der Waals cutoff, because the hydrogen sites of that term sit inside their atoms.

  • mesh_self=True removes the mesh self-interaction of every multipole from the energies, the polarizing field and the dispersion sum. A coarse mesh then comes closer to the converged values, but no longer matches Tinker at the same keys.

  • ewald=False truncates a cell at the cutoff instead.

A slab with two periodic axes is summed on its cell with the Yeh-Berkowitz correction. Leave a vacuum gap of at least the slab thickness along the free axis.

Molecular dynamics#

predictor="aspc" starts each induction solve from dipoles extrapolated from the last steps, which saves a fifth to a third of the iterations. Every backward solve starts from the previous one.

use_fast=True runs the pair terms, the fields, the induction solve and the mesh sums on fused GPU kernels, in evaluation and in training. On a CPU, the same kernels run as C++ loops (see On a CPU). The default "auto" takes them on a GPU at every size and on a CPU from about 50 000 atom pairs. In training the pair kernels give the second derivatives of a force loss and the parameter gradients; the mesh and the solver’s products run eagerly there. The first evaluations pay for the compilation. The kernels give the numbers of the reference implementation to round-off in float64 and in float32. When forces follow, AMOEBA solves its two dipole sets, those of the direct and of the polar field, together in one set of iterations, as Tinker does; its dipoles and forces then agree with the reference to the solver tolerance. A float32 HIPPO model evaluates the radial ladders of its pair terms in float64 and casts. mixed_precision=True evaluates them in float32 throughout, as Tinker9’s mixed precision does. That is ten to thirty percent faster per MD step, depending on the GPU. The energies stay at the float32 round-off and the forces lose up to one digit. It has no effect on a float64 model or on AMOEBA.

model, structure = Hippo.from_tinker_xyz("system.xyz", lib, use_fast=True, mixed_precision=True)
model = model.to("cuda", torch.float32)

plan_step(data, skin, capacity) records the decisions of one evaluation, and model(data, plan) reuses them while the atoms move. The plan keeps a Verlet pair list built with cutoff + skin, and plan.outdated(pos) tells when to rebuild it. The MDI engine turns the predictor on, sets use_fast="auto", runs the steps on a plan on a GPU and replays each step as one CUDA graph (--step-graph).

StepGraph(..., late_checks=True) reads each step’s status (pair list, solve convergence) during the next step, so the GPU does not wait for the host. A step that needed a new pair list or longer solves has then already returned its results. It is counted in late_failures with a warning, and the next step rebuilds or solves longer. In orthorhombic cells the new pair lists are found on the GPU while a step runs. Pass unwrapped positions: a step that wraps an atom back into the cell only fails after it returned. The option is off by default.

from xnn.common.deploy import StepGraph

steps = StepGraph(model, cutoff, skin=1.5)
slow = steps(structure, terms="nonbonded")["forces"]      # outer step, e.g. 2 fs
for _ in range(8):
    ...                                                   # move the atoms by 0.25 fs
    fast = steps(structure, terms="valence")["forces"]    # inner step

StepGraph also splits a step for multiple time step integrators (RESPA):

  • terms="valence" evaluates the bonded terms and the reference energies of an inner step.

  • terms="nonbonded" evaluates the rest of an outer step: pairs, meshes and the induced dipoles.

  • The two subsets add up to the whole energy, forces and stress.

  • Outer steps make every decision of the run. Inner steps replay their own CUDA graph and wait for nothing.

  • Long outer steps move the atoms further between pair lists. A skin of about 1.5 Angstrom rebuilds them less often.

A plan keeps its meshes while the cell changes. An evaluation without a plan picks the meshes for its own cell, so once a box grows past a mesh size the two energies differ by the mesh discretization. For constant pressure, set pme_grid and dpme_grid: the steps then equal fresh evaluations at every volume.

Training and files#

trainable names the parameter groups to refit: the valence tables (bond, angle, strbnd, urey, opbend, torsion, pitors, tortor), vdw, the multipoles (charge, dipole, quadrupole), polarizability, thole, the HIPPO groups (chgpen, chgtrn, repulsion, dispersion, exchpol, cflux), the ion terms (ionct, mbct, ionpair) and atom_ref. While the multipoles train, every molecule keeps its total charge (conserve_charge), the components the library leaves zero by symmetry stay zero (symmetry_mask), and the quadrupoles stay symmetric and traceless. export_library writes the multipoles the model uses.

forward reports every energy term, the monopoles, the induced dipoles and the molecular dipole. Libraries are read from .frc and Tinker .prm files and written back to either. A Tinker .xyz file builds the topology directly.

Semiempirical methods: PM3, PM6, PM6-ORG, PM7#

PM6 and its siblings are the NDDO semiempirical methods of Stewart (PM3: Stewart, J. Comput. Chem. 10, 209 (1989); PM6: Stewart, J. Mol. Model. 13, 1173 (2007); PM7: Stewart, J. Mol. Model. 19, 1 (2013); PM6-ORG: Stewart and Stewart, J. Mol. Model. 29, 284 (2023)), matching MOPAC. With the published parameters (the default) they reproduce MOPAC, and trainable makes parameter groups refittable with exact gradients through the self-consistent field.

from xnn.sqmnn.models import PM6, PM7

model = PM7()                                      # Published parameters
model = PM6(trainable=["BETAS", "BETAP", "ALPB"])  # Refit by gradient descent

energy is the heat of formation in eV and the outputs also include heat_of_formation (kcal/mol), charges and dipole. The methods handle molecules only. The published parameters are downloaded from the MOPAC sources on first use, with a LICENSE.txt beside them and a one-time warning about the license that applies to them.

  • trainable also accepts the constants of the corrections: "YNE" (the acetylenic C-C term: its energy and the start and end of its switch), and for PM7 "DISP" (dispersion scale and damping) and "HBOND" (hydrogen-bond scales and O…O energy). They are not part of a MOPAC parameter file.

  • correction_constants sets the values of these constants, and yne_switch="smooth" gives the acetylenic term a switch with smooth Hessians, and yne_switch="off" removes it.

  • bond_order_terms adds an energy that switches on with the bond order of chosen element pairs, and resonance_overlap rescales the p resonance integrals. Both can be trained, see Compute Hessians and Harmonic Frequencies.

  • Hessians and their parameter gradients are exact, see Compute Hessians and Harmonic Frequencies.

Tight-binding methods: GFN0-xTB, GFN1-xTB, GFN2-xTB#

GFN0, GFN1 and GFN2 are the extended tight-binding methods of Grimme and coworkers. They reproduce the xtb program for molecules with elements up to radon. The methods are described in these papers:

from xnn.sqmnn.models import GFN1, GFN2

model = GFN2()                               # Published parameters
model = GFN1(electronic_temperature=1000.0)  # Fermi smearing at 1000 K
model = GFN2(trainable=["LEV", "GAM"])       # Refit two element tables

with open("refit.param", "w") as f:          # Save a refit in the xtb format
    f.write(model.parameter_text())
model = GFN2(parameters="refit.param")       # Load it again
  • The energy output is the total energy in eV. The outputs also include the atomic charges and each energy term. GFN2-xTB also returns atomic_dipoles and atomic_quadrupoles.

  • Each structure provides its own total_charge and spin_multiplicity.

  • The published parameters are downloaded from the xtb sources on first use. The first download shows a license warning and saves a LICENSE.txt beside the parameter files.

  • The accuracy option controls the convergence of the self-consistent charges, as in xtb. Smaller values converge more tightly. The default is 1.0, and the tightest setting is 0.0001.

  • The scf_converged output tells you whether the self-consistent cycle converged. GFN0-xTB has no such cycle, so accuracy has no effect there.

  • With trainable=True, all element tables become trainable with exact gradients. With trainable="all", every table is trained, including the Slater exponents and the global parameters. The dispersion parameters always stay fixed.

  • The xtb program can also run a parameter file written by parameter_text().

  • Hessians are exact, see Compute Hessians and Harmonic Frequencies.

Density-functional tight binding: DFTB1, DFTB2, DFTB3#

DFTB1, DFTB2 and DFTB3 are the density-functional tight-binding methods of the DFTB+ program (Hourahine et al., J. Chem. Phys. 152, 124101 (2020)), for molecules and periodic cells.

from xnn.sqmnn.models import DFTB2, DFTB3

model = DFTB3()                           # The 3ob-3-1 set
model = DFTB2()                           # The mio-1-1 set
model = DFTB2(parameters="ob2-1-1")       # Long-range corrected exchange
model = DFTB3(parameters="my_skfiles")    # A folder of .skf files
  • The outputs are the total energy (eV), the atomic charges and each energy term. scf_converged reports whether the charges converged.

  • Cells are evaluated at the Gamma point, with stress. kpoints=(4, 4, 4) samples a k-point grid instead.

  • Options: dispersion adds D3 or D4 (with "hh_repulsion": True for DFTB3-D3H5), h5=True the H5 hydrogen-bond correction, spin_constants collinear spin, onsite_correction the onsite correction and orbital_potential DFTB+U (with spin). The ob2-1-1 set turns on long-range corrected exchange and range_separation changes it.

  • trainable=True trains the integral tables, repulsive splines, orbital energies and Hubbard parameters. model.write_set("folder") saves them as .skf files that DFTB+ also reads.

  • export_torchscript_potential deploys any model to LAMMPS and MDI.

  • On a GPU, the fast path (use_fast, on by default) runs the integrals on fused kernels. The first use compiles them, which takes up to a few minutes.

  • The sets mio-1-1, 3ob-3-1, ob2-1-1, pbc-0-3 and matsci-0-3 download on first use. They are licensed CC BY-SA 4.0. Cite the papers named in each set’s README.

Add-ons for any model#

These wrappers add additional physical terms or corrections to any model mentioned above. You can enable them in the model section of a config file. They can combine freely with other models and every deployment channel which can carry them.

Long-range electrostatics (LES)#

LatentEwald implements the latent Ewald summation of Cheng, npj Comput. Mater. 11, 80 (2025). A small network maps each atom’s features to latent charges, and an Ewald sum over them adds the long-range energy.

model:
  name: mace                  # Any model without charges of its own
  long_range: {n_channels: 4, sigma: 1.0, dl: 2.0}
  # long_range: {n_channels: 4, constrain_charge: true}   # Charges sum to the net charge
  # long_range: {n_channels: 4, charge_solve: true}       # Global charge equilibration
  # long_range: {n_channels: 4, method: pme}              # Particle-mesh sum for large cells
  # long_range: {n_channels: 1, constrain_charge: true, dipole_origin: com}  # Fit to dipoles
  # long_range: {n_channels: 1, charge_solve: true, dielectric: 78.4}       # Screened by a solvent

The outputs gain energy_lr, latent_charges, les_charges (in e) and les_dipole. The main options:

  • constrain_charge makes one charge channel sum to the structure’s net charge.

  • charge_solve equilibrates the charges over the whole structure, and fragments: true keeps each molecule or ion at its own charge.

  • les_charge_weight and les_dipole_weight in optim fit the charges to charges and dipole labels, which sets their scale.

  • dielectric screens the long-range energy by a solvent’s dielectric constant, and learn_dielectric: true fits it.

Molecules use the exact real-space sum. Models that predict their own charges (AIMNet2, PhysNet, SpookyNet, BAMBOO, HDNNP 3G/4G) use their own electrostatics instead.

Dispersion (D4, D3)#

D4Dispersion and D3Dispersion add the D4 (Caldeweyher et al., J. Chem. Phys. 150, 154122 (2019)) and D3 (Grimme et al., J. Chem. Phys. 132, 154104 (2010); BJ damping: Grimme et al., J. Comput. Chem. 32, 1456 (2011)) dispersion corrections, matching dftd4 and simple-dftd3. Both also work as standalone models (d4 and d3).

model:
  name: mace
  dispersion: true                                     # PBE0-D4 defaults
  # dispersion: {s6: 1.0, s8: 1.2, a1: 0.4, a2: 5.0}   # D4 with explicit damping
  # dispersion: {name: d3, damping: bj, s9: 1.0}       # D3(BJ) with the three-body term

For condensed phases, shorten the cutoffs and add switching windows so the MD run can stay smooth:

dispersion: {cutoff_pair: 12.0, switch_width_pair: 2.0,
             cutoff_triple: 10.0, switch_width_triple: 1.0,
             tail_correction: true}                    # D4: add back the cut pair tail

The net charge comes from the structure. A model trained on labels with the dispersion removed records it in subtracted_dispersion (see Deployment).