Skip to content

SchNet

SchNet(
    hidden_channels: int = 128,
    num_filters: int = 128,
    num_interactions: int = 6,
    num_gaussians: int = 50,
    cutoff: float = 10.0,
    interaction_graph: Optional[Callable] = None,
    max_num_neighbors: int = 32,
    readout: Literal["add", "sum", "mean"] = "add",
    dipole: bool = False,
    mean: Optional[float] = None,
    std: Optional[float] = None,
    atomref: Optional[array] = None,
)

Bases: Module

The continuous-filter convolutional neural network SchNet from the "SchNet: A Continuous-filter Convolutional Neural Network for Modeling Quantum Interactions" paper, with interaction blocks of the form

\[ \mathbf{x}^{\prime}_i = \sum_{j \in \mathcal{N}(i)} \mathbf{x}_j \odot h_{\mathbf{\Theta}} ( \exp(-\gamma(\mathbf{e}_{j,i} - \mathbf{\mu}))), \]

where \(h_{\mathbf{\Theta}}\) denotes an MLP and \(\mathbf{e}_{j,i}\) the interatomic distances.

The model follows PyG's SchNet (same arguments, parameters and initialization). It takes the atomic numbers z and positions pos of the atoms and returns one prediction per molecule. The interaction graph connects the atoms closer than cutoff (with radius_graph(), which keeps the max_num_neighbors closest neighbors when there are more).

Note

The mini-batches of molecules all have different numbers of atoms and edges, so MLX rarely reuses the buffers it frees and its buffer cache can grow to tens of GB during training. Bound it, e.g. with mx.set_cache_limit(1024**3) before training.

Parameters:

Name Type Description Default
hidden_channels int

Hidden embedding size. Default: 128

128
num_filters int

The number of filters to use. Default: 128

128
num_interactions int

The number of interaction blocks. Default: 6

6
num_gaussians int

The number of gaussians \(\mu\). Default: 50

50
cutoff float

Cutoff distance for interatomic interactions. Default: 10.0

10.0
interaction_graph Optional[Callable]

The function computing the interaction graph and the interatomic distances, given pos and batch_indices. It returns (edge_index, edge_weight). If None, a RadiusInteractionGraph with cutoff and max_num_neighbors. Default: None

None
max_num_neighbors int

The maximum number of neighbors of each atom in the interaction graph. Default: 32

32
readout Literal['add', 'sum', 'mean']

The global aggregation, "add" or "mean". Default: "add"

'add'
dipole bool

If True, predicts the magnitude of the dipole moment (e.g. target 0 of QM9), from atomic charges and the center of mass. Requires the ase package. Default: False

False
mean Optional[float]

The mean of the property to predict. Default: None

None
std Optional[float]

The standard deviation of the property to predict. Default: None

None
atomref Optional[array]

The reference of single-atom properties, of shape [max_atomic_number, 1] (e.g. QM9.atomref(target)). Default: None

None

Example:

import mlx.core as mx
from mlx_graphs.nn import SchNet

model = SchNet(hidden_channels=64, num_interactions=3, cutoff=5.0)
z = mx.array([6, 1, 1, 1, 1, 8, 1, 1])  # CH4 and H2O
pos = mx.random.normal((8, 3))
batch_indices = mx.array([0, 0, 0, 0, 0, 1, 1, 1])
model(z, pos, batch_indices).shape
>>> (2, 1)

Methods:

Name Description
__call__

Predicts the target property of each molecule.

Source code in mlx_graphs/nn/models/schnet.py
def __init__(
    self,
    hidden_channels: int = 128,
    num_filters: int = 128,
    num_interactions: int = 6,
    num_gaussians: int = 50,
    cutoff: float = 10.0,
    interaction_graph: Optional[Callable] = None,
    max_num_neighbors: int = 32,
    readout: Literal["add", "sum", "mean"] = "add",
    dipole: bool = False,
    mean: Optional[float] = None,
    std: Optional[float] = None,
    atomref: Optional[mx.array] = None,
):
    super().__init__()
    if readout not in ("add", "sum", "mean"):
        raise ValueError(f"readout must be 'add' or 'mean' (got '{readout}')")
    self.hidden_channels = hidden_channels
    self.num_filters = num_filters
    self.num_interactions = num_interactions
    self.num_gaussians = num_gaussians
    self.cutoff = cutoff
    self.dipole = dipole
    self.readout = "add" if dipole else readout
    self.mean = mean
    self.std = std
    self.scale = None

    if dipole:
        try:
            import ase.data
        except ImportError:
            raise ImportError(
                "SchNet(dipole=True) needs the atomic masses of the 'ase' "
                "package: pip install ase"
            ) from None
        self.atomic_mass = mx.array(ase.data.atomic_masses.astype(np.float32))

    # N(0, 1) as torch.nn.Embedding. z == 0 is a padding atom: its
    # embedding is zero and gets no gradient (torch's padding_idx=0).
    self.embedding = nn.Embedding(100, hidden_channels)
    weight = mx.random.normal((100, hidden_channels))
    self.embedding.weight = weight * (mx.arange(100) != 0)[:, None]

    if interaction_graph is not None:
        self.interaction_graph = interaction_graph
    else:
        self.interaction_graph = RadiusInteractionGraph(cutoff, max_num_neighbors)

    self.distance_expansion = GaussianSmearing(0.0, cutoff, num_gaussians)
    self.interactions = [
        InteractionBlock(hidden_channels, num_gaussians, num_filters, cutoff)
        for _ in range(num_interactions)
    ]
    self.lin1 = Linear(hidden_channels, hidden_channels // 2)
    self.act = ShiftedSoftplus()
    self.lin2 = Linear(hidden_channels // 2, 1)

    if atomref is not None:
        self.atomref = nn.Embedding(100, 1)
        self.atomref.weight = mx.array(atomref).reshape(100, 1).astype(mx.float32)

    if dipole:
        self.freeze(keys=["atomic_mass"], recurse=False)

__call__

__call__(z: array, pos: array, batch_indices: Optional[array] = None) -> array

Predicts the target property of each molecule.

Parameters:

Name Type Description Default
z array

Atomic number of each atom, of shape [num_atoms].

required
pos array

Coordinates of each atom, of shape [num_atoms, 3].

required
batch_indices Optional[array]

Molecule of each atom, of shape [num_atoms]. Default: None (a single molecule).

None

Returns:

Type Description
array

The predictions, of shape [num_molecules, 1].

Source code in mlx_graphs/nn/models/schnet.py
def __call__(
    self,
    z: mx.array,
    pos: mx.array,
    batch_indices: Optional[mx.array] = None,
) -> mx.array:
    """Predicts the target property of each molecule.

    Args:
        z: Atomic number of each atom, of shape ``[num_atoms]``.
        pos: Coordinates of each atom, of shape ``[num_atoms, 3]``.
        batch_indices: Molecule of each atom, of shape ``[num_atoms]``.
            Default: ``None`` (a single molecule).

    Returns:
        The predictions, of shape ``[num_molecules, 1]``.
    """
    if batch_indices is None:
        batch_indices = mx.zeros(z.shape, dtype=mx.int32)

    h = self.embedding(z) * (z != 0)[:, None]
    edge_index, edge_weight = self.interaction_graph(pos, batch_indices)
    edge_attr = self.distance_expansion(edge_weight)

    for interaction in self.interactions:
        h = h + interaction(h, edge_index, edge_weight, edge_attr)

    h = self.lin2(self.act(self.lin1(h)))

    if self.dipole:
        # charges times positions relative to the center of mass
        mass = self.atomic_mass[z].reshape(-1, 1)
        M = global_add_pool(mass, batch_indices)
        c = global_add_pool(mass * pos, batch_indices) / M
        h = h * (pos - c[batch_indices])

    if not self.dipole and self.mean is not None and self.std is not None:
        h = h * self.std + self.mean

    if not self.dipole and "atomref" in self:
        h = h + self.atomref(z)

    if self.readout == "mean":
        out = global_mean_pool(h, batch_indices)
    else:
        out = global_add_pool(h, batch_indices)

    if self.dipole:
        # the norm, with a zero gradient at 0 as in torch (e.g. one atom)
        sq = (out * out).sum(axis=-1, keepdims=True)
        out = mx.where(sq > 0, mx.sqrt(mx.where(sq > 0, sq, 1.0)), 0.0)

    if self.scale is not None:
        out = self.scale * out

    return out

from mlx_graphs.nn import SchNet · mlx_graphs/nn/models/schnet.py