Skip to content

DimeNet

DimeNet(
    hidden_channels: int,
    out_channels: int,
    num_blocks: int,
    num_bilinear: int,
    num_spherical: int,
    num_radial: int,
    cutoff: float = 5.0,
    max_num_neighbors: int = 32,
    envelope_exponent: int = 5,
    num_before_skip: int = 1,
    num_after_skip: int = 2,
    num_output_layers: int = 3,
    act: Union[str, Callable] = "swish",
    output_initializer: OutputInitializer = "zeros",
)

Bases: Module

The directional message passing neural network (DimeNet) from the "Directional Message Passing for Molecular Graphs" paper.

DimeNet embeds the directed edges j -> i of the graph of atoms closer than cutoff, and updates them with messages from the edges k -> j transformed with the angle \(\angle kji\) (with a 2D spherical Fourier-Bessel basis), which makes the model invariant to rotations.

The model follows PyG's DimeNet (same arguments, parameters and initialization). It requires the sympy and scipy packages. The interaction graph and the triplets are computed on the host (see radius_graph() and triplets()), the distances and angles on the device, so that the output can be differentiated with respect to pos.

Note

The mini-batches of molecules all have different numbers of atoms, edges and triplets, 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.

required
out_channels int

Size of each output sample.

required
num_blocks int

Number of building blocks.

required
num_bilinear int

Size of the bilinear layer tensor.

required
num_spherical int

Number of spherical harmonics.

required
num_radial int

Number of radial basis functions.

required
cutoff float

Cutoff distance for interatomic interactions. Default: 5.0

5.0
max_num_neighbors int

The maximum number of neighbors of each atom within cutoff. Default: 32

32
envelope_exponent int

Shape of the smooth cutoff. Default: 5

5
num_before_skip int

Number of residual layers in the interaction blocks before the skip connection. Default: 1

1
num_after_skip int

Number of residual layers in the interaction blocks after the skip connection. Default: 2

2
num_output_layers int

Number of linear layers for the output blocks. Default: 3

3
act Union[str, Callable]

The activation function, a name (e.g. "swish") or a callable. Default: "swish"

'swish'
output_initializer OutputInitializer

The initialization of the output layer, "zeros" or "glorot_orthogonal". Default: "zeros"

'zeros'

Example:

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

model = DimeNet(
    hidden_channels=32, out_channels=1, num_blocks=2, num_bilinear=4,
    num_spherical=3, num_radial=4,
)
z = mx.array([6, 1, 1, 1, 1])
pos = mx.random.normal((5, 3))
model(z, pos, mx.zeros(5, dtype=mx.int32)).shape
>>> (1, 1)

Methods:

Name Description
__call__

Predicts the target properties of each molecule.

Source code in mlx_graphs/nn/models/dimenet.py
def __init__(
    self,
    hidden_channels: int,
    out_channels: int,
    num_blocks: int,
    num_bilinear: int,
    num_spherical: int,
    num_radial: int,
    cutoff: float = 5.0,
    max_num_neighbors: int = 32,
    envelope_exponent: int = 5,
    num_before_skip: int = 1,
    num_after_skip: int = 2,
    num_output_layers: int = 3,
    act: Union[str, Callable] = "swish",
    output_initializer: OutputInitializer = "zeros",
):
    super().__init__()
    if num_spherical < 2:
        raise ValueError("'num_spherical' should be greater than 1")
    act = _resolve_act(act)
    self.cutoff = cutoff
    self.max_num_neighbors = max_num_neighbors
    self.num_blocks = num_blocks

    self.rbf = BesselBasisLayer(num_radial, cutoff, envelope_exponent)
    self.sbf = SphericalBasisLayer(
        num_spherical, num_radial, cutoff, envelope_exponent
    )
    self.emb = EmbeddingBlock(num_radial, hidden_channels, act)
    self.output_blocks = [
        OutputBlock(
            num_radial,
            hidden_channels,
            out_channels,
            num_output_layers,
            act,
            output_initializer,
        )
        for _ in range(num_blocks + 1)
    ]
    self.interaction_blocks = [
        InteractionBlock(
            hidden_channels,
            num_bilinear,
            num_spherical,
            num_radial,
            num_before_skip,
            num_after_skip,
            act,
        )
        for _ in range(num_blocks)
    ]

__call__

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

Predicts the target properties 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, out_channels], or

array

[out_channels] if batch_indices is None (as in PyG).

Source code in mlx_graphs/nn/models/dimenet.py
def __call__(
    self,
    z: mx.array,
    pos: mx.array,
    batch_indices: Optional[mx.array] = None,
) -> mx.array:
    """Predicts the target properties 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, out_channels]``, or
        ``[out_channels]`` if ``batch_indices`` is ``None`` (as in PyG).
    """
    num_nodes = z.shape[0]
    edge_index = radius_graph(
        pos,
        r=self.cutoff,
        batch_indices=batch_indices,
        max_num_neighbors=self.max_num_neighbors,
    )
    i, j, idx_i, idx_j, idx_k, idx_kj, idx_ji = triplets(edge_index, num_nodes)

    dist = _safe_norm(pos[i] - pos[j])
    angle = self._angles(pos, idx_i, idx_j, idx_k)

    rbf = self.rbf(dist)
    sbf = self.sbf(dist, angle, idx_kj)

    x = self.emb(z, rbf, i, j)
    P = self.output_blocks[0](x, rbf, i, num_nodes=num_nodes)
    for interaction_block, output_block in zip(
        self.interaction_blocks, self.output_blocks[1:]
    ):
        x = interaction_block(x, rbf, sbf, idx_kj, idx_ji)
        P = P + output_block(x, rbf, i, num_nodes=num_nodes)

    if batch_indices is None:
        return P.sum(axis=0)
    return scatter(P, batch_indices, int(batch_indices.max().item()) + 1, "add")

from mlx_graphs.nn import DimeNet · mlx_graphs/nn/models/dimenet.py