Skip to content

LayerNormalization

LayerNormalization(
    num_features: int,
    eps: float = 1e-05,
    affine: bool = True,
    mode: Literal["graph", "node"] = "graph",
)

Bases: Module

Applies layer normalization over each individual example in a batch of features as described in the Layer Normalization paper.

\[ \mathbf{x}^{\prime}_i = \frac{\mathbf{x} - \textrm{E}[\mathbf{x}]}{\sqrt{\textrm{Var}[\mathbf{x}] + \epsilon}} \odot \gamma + \beta \]

The mean and standard-deviation are calculated across all nodes and all node channels separately for each object in a mini-batch.

Parameters:

Name Type Description Default
num_features int

Size of each input sample.

required
eps float

A value added to the denominator for numerical stability. (default: 1e-5)

1e-05
affine bool

If set to True, this module has learnable affine parameters \(\gamma\) and \(\beta\) (weight and bias, used by both modes, as in PyG). (default: True)

True
mode Literal['graph', 'node']

The normalization mode to use for layer normalization ("graph" or "node"). If "graph" is used, each graph will be considered as an element to be normalized. If "node" is used, each node will be considered as an element to be normalized. (default: "graph")

'graph'

Methods:

Name Description
__call__

Normalizes the features.

Source code in mlx_graphs/nn/norm/layer_norm.py
def __init__(
    self,
    num_features: int,
    eps: float = 1e-5,
    affine: bool = True,
    mode: Literal["graph", "node"] = "graph",
):
    super().__init__()
    if mode not in ("graph", "node"):
        raise ValueError(f"Unknown normalization mode: {mode}")
    self.num_features = num_features
    self.eps = eps
    self.affine = affine
    self.mode = mode

    # Used by both modes, as in PyG.
    if affine:
        self.weight = mx.ones((num_features,))
        self.bias = mx.zeros((num_features,))

__call__

__call__(
    features: array,
    batch: Optional[array] = None,
    batch_size: Optional[int] = None,
) -> array

Normalizes the features.

Parameters:

Name Type Description Default
features array

Features of shape [num_nodes, num_features].

required
batch Optional[array]

Graph of each node, of shape [num_nodes] ("graph" mode). Default: None (all the nodes form one graph).

None
batch_size Optional[int]

Number of graphs. Default: None (inferred from batch).

None

Returns:

Type Description
array

The normalized features.

Source code in mlx_graphs/nn/norm/layer_norm.py
def __call__(
    self,
    features: mx.array,
    batch: Optional[mx.array] = None,
    batch_size: Optional[int] = None,
) -> mx.array:
    """Normalizes the features.

    Args:
        features: Features of shape ``[num_nodes, num_features]``.
        batch: Graph of each node, of shape ``[num_nodes]`` (``"graph"``
            mode). Default: ``None`` (all the nodes form one graph).
        batch_size: Number of graphs. Default: ``None`` (inferred from
            ``batch``).

    Returns:
        The normalized features.
    """
    weight = self.weight if self.affine else None
    bias = self.bias if self.affine else None
    if self.mode == "node":
        return mx.fast.layer_norm(features, weight, bias, self.eps)

    # "graph" mode: statistics over all the nodes and channels of a graph
    if batch is None:
        features = features - features.mean()
        out = features / (mx.sqrt(features.var()) + self.eps)
    else:
        if batch_size is None:
            batch_size = int(batch.max().item()) + 1 if batch.size > 0 else 1
        count = mx.maximum(degree(batch, batch_size), 1) * features.shape[-1]
        count = count.astype(features.dtype).reshape(-1, 1)
        mean = scatter(features, batch, batch_size, "add").sum(
            axis=-1, keepdims=True
        )
        features = features - (mean / count)[batch]
        var = scatter(features * features, batch, batch_size, "add").sum(
            axis=-1, keepdims=True
        )
        out = features / mx.sqrt(var / count + self.eps)[batch]
    if self.affine:
        out = out * weight + bias
    return out

from mlx_graphs.nn import LayerNormalization · mlx_graphs/nn/norm/layer_norm.py