Skip to content

MessageNormalization

MessageNormalization(learn_scale: bool = False)

Bases: Module

Applies message normalization over the aggregated messages as described in the "DeeperGCNs: All You Need to Train Deeper GCNs" paper.

\[ \mathbf{x}_i^{\prime} = \mathrm{MLP} \left( \mathbf{x}_{i} + s \cdot {\| \mathbf{x}_i \|}_2 \cdot \frac{\mathbf{m}_{i}}{{\|\mathbf{m}_i\|}_2} \right) \]

The layer computes the normalized messages \(s \cdot {\| \mathbf{x}_i \|}_2 \cdot \mathbf{m}_{i} / {\|\mathbf{m}_i\|}_2\); adding them to \(\mathbf{x}_i\) and applying the MLP is left to the caller. Also available as MessageNorm, its PyG name.

Parameters:

Name Type Description Default
learn_scale bool

If set to True, the scaling factor \(s\) is learnable. Default: False

False

Example:

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

norm = MessageNormalization(learn_scale=True)
node_features = mx.random.normal((5, 16))
messages = mx.random.normal((5, 16))

>>> norm(node_features, messages).shape
(5, 16)

Methods:

Name Description
__call__

Normalizes the messages and rescales them to the norm of the node

Source code in mlx_graphs/nn/norm/msg_norm.py
def __init__(self, learn_scale: bool = False):
    super().__init__()
    self.learn_scale = learn_scale
    self.scale = mx.ones((1,))
    if not learn_scale:
        self.freeze(keys=["scale"], recurse=False)

__call__

__call__(node_features: array, messages: array, p: float = 2.0) -> array

Normalizes the messages and rescales them to the norm of the node features.

Parameters:

Name Type Description Default
node_features array

Node features \(\mathbf{x}\) of shape [num_nodes, num_features].

required
messages array

Aggregated messages \(\mathbf{m}\) of shape [num_nodes, num_features].

required
p float

The norm \(p\) used for the normalization. Default: 2.0

2.0

Returns:

Type Description
array

The normalized messages.

Source code in mlx_graphs/nn/norm/msg_norm.py
def __call__(
    self, node_features: mx.array, messages: mx.array, p: float = 2.0
) -> mx.array:
    """Normalizes the messages and rescales them to the norm of the node
    features.

    Args:
        node_features: Node features :math:`\\mathbf{x}` of shape
            ``[num_nodes, num_features]``.
        messages: Aggregated messages :math:`\\mathbf{m}` of shape
            ``[num_nodes, num_features]``.
        p: The norm :math:`p` used for the normalization. Default: ``2.0``

    Returns:
        The normalized messages.
    """
    # Same epsilon as `torch.nn.functional.normalize`.
    messages = messages / mx.maximum(_p_norm(messages, p), 1e-12)
    return messages * _p_norm(node_features, p) * self.scale

from mlx_graphs.nn import MessageNormalization · mlx_graphs/nn/norm/msg_norm.py