xnn.gnn.models.mace.MACE#
- class xnn.gnn.models.mace.MACE(species, cutoff=4.0, max_ell=3, max_L=0, num_channels=32, n_rbf=8, num_interactions=2, correlation=3, MLP_irreps='16x0e', radial_MLP=None, interaction='RealAgnosticResidualInteractionBlock', interaction_first='RealAgnosticResidualInteractionBlock', gate='silu', avg_num_neighbors=1.0, hidden_irreps=None, num_cutoff_basis=5, radial_type='bessel', distance_transform='None', pair_repulsion=False, atomic_energies=None, scale=1.0, shift=0.0)[source]#
Bases:
EquivariantGNNFaithful MACE with a flexible number of interaction layers (T = 0..N).
Subclasses
EquivariantGNN, inheriting species bookkeeping, the per-element reference energyatom_ref, and theSphericalHarmonicEdgeEmbeddingedge featurizer, and adds the MACE-specific interaction blocks and the learned symmetric-contraction product basis. The number of message-passing layersT = num_interactionsis fully flexible (T = 0gives a pureatom_ref/pair-repulsion baseline).- Parameters:
species (list of int) – Atomic numbers of the elements the model supports.
cutoff (float, optional) – Radial cutoff distance
r_maxin angstrom, by default 4.0.max_ell (int, optional) – Maximum degree
lof the spherical-harmonic edge attributes, by default 3.max_L (int, optional) – Maximum output irrep order
Lof the hidden node features, by default 0 (invariant features only).num_channels (int, optional) – Number of feature channels (multiplicity) in the hidden irreps, by default 32.
n_rbf (int, optional) – Number of radial basis functions, by default 8.
num_interactions (int, optional) – Number of message-passing layers
T, by default 2. Must be>= 0.correlation (int or list of int, optional) – Correlation order (body order minus one) of the symmetric contraction, by default 3. An int is broadcast across all interactions.
MLP_irreps (str, optional) – Hidden irreps of the final non-linear readout MLP, by default
"16x0e".radial_MLP (list of int or None, optional) – Hidden layer widths of the radial MLP producing tensor-product weights.
Nonedefaults to[64, 64, 64].interaction (str, optional) – Interaction-block class name for layers after the first, by default
"RealAgnosticResidualInteractionBlock".interaction_first (str, optional) – Interaction-block class name for the first layer, by default
"RealAgnosticResidualInteractionBlock".gate (str or None, optional) – Name of the scalar gate activation for the non-linear readout, by default
"silu".avg_num_neighbors (float, optional) – Average neighbour count used to normalise messages, by default 1.0.
hidden_irreps (str or None, optional) – Explicit hidden irreps.
Nonederives them fromnum_channelsandmax_L.num_cutoff_basis (int, optional) – Polynomial cutoff degree
pfor the edge envelope (and ZBL), by default 5.radial_type (str, optional) – Radial basis type (
"bessel"or"gaussian"), by default"bessel".distance_transform (str, optional) – Chemistry-aware warp of the distance fed to the radial basis (the cutoff envelope always sees the raw distance):
"None"(default),"Agnesi"or"Soft"(seexnn.gnn.featurizers.radial;"Agnesi"is what the MACE-MP-0b and later foundation models use).pair_repulsion (bool, optional) – If
True, add a_ZBLPairRepulsionshort-range term, by defaultFalse.atomic_energies (torch.Tensor or None, optional) – Per-element reference energies (
E0s) used to initialiseatom_ref.scale (float, optional) – Affine rescaling of the per-atom interaction energy (readouts plus pair repulsion),
E_i = E0_i + scale * E_int,i + shift– the upstreamScaleShiftMACEconvention. The defaults (1, 0) recover the plain MACE energy expression, so one class covers both upstream variants.shift (float, optional) – Affine rescaling of the per-atom interaction energy (readouts plus pair repulsion),
E_i = E0_i + scale * E_int,i + shift– the upstreamScaleShiftMACEconvention. The defaults (1, 0) recover the plain MACE energy expression, so one class covers both upstream variants.
- Raises:
ValueError – If
num_interactionsis negative.NotImplementedError – If
distance_transformis not one of the supported options.
- node_features_energy(atomic_numbers, edge_index, edge_vec)[source]#
TorchScript-compatible core: tensors in, features + energies out.
The single implementation reused by
node_energy()(the deploy entry point) andforward(), so it must avoid theAtomicGraphdataclass and any Python-only constructs. Accumulates the interaction energy – the optional ZBL pair-repulsion term plus one readout per round of interaction + product basis – maps it throughscale_shift(identity unless constructed withscale/shift, theScaleShiftMACEconvention) and adds the per-element reference energy. The radial basis sees the (optionallydistance_transform-warped) distance while the cutoff envelope always sees the raw one. The invariant (l = 0) channels of every layer’s node features are collected alongside (whatLatentEwaldconsumes).- Parameters:
atomic_numbers (torch.Tensor) – Per-atom atomic numbers, shape
(N,).edge_index (torch.Tensor) – Edge index of shape
(2, E); row 0 is the source (neighbour) and row 1 the destination (centre) node of each edge.edge_vec (torch.Tensor) – Edge displacement vectors, shape
(E, 3)(already accounting for any periodic cell shifts).
- Returns:
The concatenated invariant node features
(N, node_feature_dim)and the per-atom energy(N,).- Return type:
- node_energy(atomic_numbers, edge_index, edge_vec)[source]#
Per-atom energy, shape
(N,)(thin wrapper overnode_features_energy(); the deploy wrappers call this).
- forward(data)[source]#
Predict per-node and total energy for an atomic graph.
Thin wrapper over
node_energy()(the scriptable tensor core): builds the edge displacement vectors from the graph and aggregates the per-node energies to a per-structure total.- Parameters:
data (xnn.common.data.AtomicGraph) – The input atomic graph (atomic numbers, edge index, positions, …).
- Returns:
"node_energy"(per-node energies) and"energy"(per-structure total energy).- Return type:
dict of str to torch.Tensor
- classmethod from_config(cfg)[source]#
Construct a
MACEfrom a core model config.Reads the MACE-specific hyper-parameters from
cfg.extra(falling back to defaults) and the shared fields fromcfgdirectly. Only the xnn canonical key names are read here; upstream MACE-CLI spellings (r_max,num_radial_basis,atomic_numbers,E0s, …) are translated to these names at config-load time byxnn.common.config.translate. Values copied from an upstream yaml are coerced:speciesaccepts a"[1, 6, 8]"string,radial_MLPa"[64, 64, 64]"string, andatomic_energies(MACEE0s) a list aligned withspecies, a{Z: E0}dict, or the string form of either.Alternatively,
extra["foundation"]names (or points to) a pretrained MACE foundation checkpoint: the model is then built byfrom_foundation()(optionally withextra["head"]andextra["dtype"]) and every architecture key is taken from the checkpoint instead of the config.- Parameters:
cfg (xnn.common.config.schema.ModelConfig) – The core model config, whose
extradict carries the MACE architecture options.- Returns:
The instantiated model.
- Return type:
- classmethod from_foundation(source, head=None, dtype=None)[source]#
Load a pretrained MACE foundation model into an xnn
MACE.Downloads (and caches) the requested checkpoint if needed, unpickles it with the
mace-torchpackage, and converts it weight-for-weight into this implementation – covering theScaleShiftMACEenergy expression, the Agnesi distance transform, ZBL pair repulsion, the density-normalized interaction generation, and multi-head checkpoints (sliced to one head). Seexnn.gnn.models.mace_foundationfor the alias registry and the conversion details.- Parameters:
source (str or Path or torch.nn.Module) – A registered alias (e.g.
"mace-mp-0-medium","mace-off23-small"; seeFOUNDATION_MODELS), a checkpoint URL or local path, or an already-loadedmace-torchmodel instance.head (str, optional) – Which head of a multi-head checkpoint to keep. Defaults to the checkpoint’s only head; required (with the options listed in the error) when there are several.
dtype (torch.dtype or str, optional) – Final dtype of the converted model;
Nonekeeps the checkpoint’s (float64 for most foundation models).
- Returns:
The converted model, ready for evaluation or fine-tuning.
- Return type: