Skip to content

HeteroDictLinear

HeteroDictLinear(
    input_dims: dict[str, int], output_dims: int, bias: bool = True
)

Bases: Module

Applies a separate linear layer to each node type.

The layers are initialized like PyG's HeteroDictLinear (and torch.nn.Linear): weights and biases uniform in [-1/sqrt(input_dims), 1/sqrt(input_dims)], i.e. mlx.nn.Linear's default.

Node types in a heterogeneous graph usually have different numbers of features. This layer maps every node type to the same size, so later layers (e.g. HeteroConv with SAGEConv(out_dim, out_dim)) can use one size for all node types.

Node types in x_dict without a layer are left out of the output, and layers whose node type is missing from x_dict are skipped.

Parameters:

Name Type Description Default
input_dims dict[str, int]

Number of input features per node type, e.g. {"author": 334, "paper": 4231} or data.num_node_features.

required
output_dims int

Number of output features, the same for every node type.

required
bias bool

If set to False the layers will not use a bias. Default is True.

True

Example:

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

x_dict = {"author": mx.ones((4, 334)), "paper": mx.ones((5, 4231))}
proj = HeteroDictLinear({"author": 334, "paper": 4231}, 64)
h = proj(x_dict)
>>> {k: v.shape for k, v in h.items()}
{'author': (4, 64), 'paper': (5, 64)}

Methods:

Name Description
__call__

Projects the features of every node type that has a layer.

Source code in mlx_graphs/nn/linear.py
def __init__(
    self, input_dims: dict[str, int], output_dims: int, bias: bool = True
) -> None:
    super().__init__()
    if not input_dims:
        raise ValueError("input_dims must contain at least one node type")
    self.input_dims = dict(input_dims)
    self.output_dims = output_dims
    self.lins = {
        node_type: nn.Linear(dims, output_dims, bias=bias)
        for node_type, dims in input_dims.items()
    }

__call__

__call__(x_dict: dict[str, array]) -> dict[str, array]

Projects the features of every node type that has a layer.

Parameters:

Name Type Description Default
x_dict dict[str, array]

Node features per node type.

required

Returns:

Type Description
dict[str, array]

Projected node features per node type, each with output_dims

dict[str, array]

features.

Source code in mlx_graphs/nn/linear.py
def __call__(self, x_dict: dict[str, mx.array]) -> dict[str, mx.array]:
    """Projects the features of every node type that has a layer.

    Args:
        x_dict: Node features per node type.

    Returns:
        Projected node features per node type, each with ``output_dims``
        features.
    """
    return {
        node_type: lin(x_dict[node_type])
        for node_type, lin in self.lins.items()
        if node_type in x_dict
    }

from mlx_graphs.nn import HeteroDictLinear · mlx_graphs/nn/linear.py