Skip to content

HeteroBatchNormalization

HeteroBatchNormalization(
    in_channels: int,
    num_types: int,
    eps: float = 1e-05,
    momentum: Optional[float] = 0.1,
    affine: bool = True,
    track_running_stats: bool = True,
)

Bases: Module

Applies batch normalization over a batch of heterogeneous features, as described in the "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" paper.

Compared to a standard batch norm, HeteroBatchNorm applies normalization individually for each node or edge type.

Parameters:

Name Type Description Default
in_channels int

Size of each input sample.

required
num_types int

The number of types.

required
eps float

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

1e-05
momentum float

The value used for the running mean and running variance computation. If set to None, a cumulative moving average is used instead. (default: 0.1)

0.1
affine bool

If set to True, this module has learnable affine parameters \(\gamma\) and \(\beta\). (default: True)

True
track_running_stats bool

If set to True, this module tracks the running mean and variance, and when set to False, this module does not track such statistics and always uses batch statistics in both training and eval modes. (default: True)

True

Methods:

Name Description
reset_running_stats

Resets all running statistics of the module.

reset_parameters

Resets all learnable parameters of the module.

__call__

Forward pass.

Source code in mlx_graphs/nn/norm/batch_norm.py
def __init__(
    self,
    in_channels: int,
    num_types: int,
    eps: float = 1e-5,
    momentum: Optional[float] = 0.1,
    affine: bool = True,
    track_running_stats: bool = True,
):
    super().__init__()

    self.in_channels = in_channels
    self.num_types = num_types
    self.eps = eps
    self.momentum = momentum
    self.affine = affine
    self.track_running_stats = track_running_stats

    if self.affine:
        self.weight = mx.ones((num_types, in_channels))
        self.bias = mx.zeros((num_types, in_channels))

    if self.track_running_stats:
        self.running_mean = mx.zeros((num_types, in_channels))
        self.running_var = mx.ones((num_types, in_channels))
        self.num_batches_tracked = mx.array(0)
        # Running stats are not learnable: exclude them from gradients.
        self.freeze(
            keys=["running_mean", "running_var", "num_batches_tracked"],
            recurse=False,
        )

    self.reset_parameters()

reset_running_stats

reset_running_stats()

Resets all running statistics of the module.

Source code in mlx_graphs/nn/norm/batch_norm.py
def reset_running_stats(self):
    r"""Resets all running statistics of the module."""
    if self.track_running_stats:
        self.running_mean = mx.zeros_like(self.running_mean)
        self.running_var = mx.ones_like(self.running_var)
        self.num_batches_tracked = mx.array(0)

reset_parameters

reset_parameters()

Resets all learnable parameters of the module.

Source code in mlx_graphs/nn/norm/batch_norm.py
def reset_parameters(self):
    r"""Resets all learnable parameters of the module."""
    self.reset_running_stats()
    if self.affine:
        self.weight = mx.ones_like(self.weight)
        self.bias = mx.zeros_like(self.bias)

__call__

__call__(x: array, type_vec: array) -> array

Forward pass.

Parameters:

Name Type Description Default
x array

The input features of shape [num_items, in_channels].

required
type_vec array

An integer vector of shape [num_items] that maps each entry to a type in [0, num_types).

required
Source code in mlx_graphs/nn/norm/batch_norm.py
def __call__(self, x: mx.array, type_vec: mx.array) -> mx.array:
    r"""Forward pass.

    Args:
        x (mx.array): The input features of shape
            :obj:`[num_items, in_channels]`.
        type_vec (mx.array): An integer vector of shape
            :obj:`[num_items]` that maps each entry to a type in
            :obj:`[0, num_types)`.
    """
    if not self.training and self.track_running_stats:
        mean, var = self.running_mean, self.running_var
    else:
        mean = scatter(x, type_vec, out_size=self.num_types, aggr="mean")
        mean_sq = scatter(x * x, type_vec, out_size=self.num_types, aggr="mean")
        var = mx.maximum(mean_sq - mean * mean, 0.0)

    if self.training and self.track_running_stats:
        if self.momentum is None:
            self.num_batches_tracked = self.num_batches_tracked + 1
            exp_avg_factor = 1.0 / float(self.num_batches_tracked.item())
        else:
            exp_avg_factor = self.momentum

        # Only update stats for types actually present in this batch,
        # leaving stats for absent types untouched.
        ones = mx.ones((type_vec.shape[0], 1))
        counts = scatter(ones, type_vec, out_size=self.num_types, aggr="add")
        mask = counts > 0

        new_running_mean = (
            1.0 - exp_avg_factor
        ) * self.running_mean + exp_avg_factor * mean
        new_running_var = (
            1.0 - exp_avg_factor
        ) * self.running_var + exp_avg_factor * var

        self.running_mean = mx.where(mask, new_running_mean, self.running_mean)
        self.running_var = mx.where(mask, new_running_var, self.running_var)

    out = (x - mean[type_vec]) / mx.sqrt(mx.maximum(var, self.eps))[type_vec]

    if self.affine:
        out = out * self.weight[type_vec] + self.bias[type_vec]

    return out

from mlx_graphs.nn import HeteroBatchNormalization · mlx_graphs/nn/norm/batch_norm.py