Skip to content

BasicGNN

BasicGNN(
    node_features_dim: Union[int, Tuple[int, int]],
    hidden_features_dim: int,
    num_layers: int,
    out_features_dim: Optional[int] = None,
    dropout: float = 0.0,
    act: Activation = "relu",
    norm: Normalization = None,
    jk: Optional[Literal["cat", "max", "lstm"]] = None,
    **kwargs: Any,
)

Bases: Module

Base class of the ready-to-use GNN models.

Stacks num_layers convolution layers with an activation, an optional normalization and dropout in between. Subclasses only choose the convolution layer by implementing init_conv().

Parameters:

Name Type Description Default
node_features_dim Union[int, Tuple[int, int]]

Size of the input node features, or a (src_dim, dst_dim) tuple for bipartite message passing (as in PyG, every layer then gets separate source and destination weights, e.g. for to_hetero()), if the convolution supports it.

required
hidden_features_dim int

Size of the hidden node embeddings.

required
num_layers int

Number of message passing layers.

required
out_features_dim Optional[int]

Size of the output. If None, the model outputs the hidden embeddings of the last layer. Default: None

None
dropout float

Dropout probability. Default: 0.0

0.0
act Activation

Activation between layers: a name ("relu", "elu", "gelu", "leaky_relu", "silu", "tanh"), a callable or None. Default: "relu"

'relu'
norm Normalization

Normalization between layers: "batch", "layer" or None. Default: None

None
jk Optional[Literal['cat', 'max', 'lstm']]

Jumping Knowledge mode combining the embeddings of all layers: "cat", "max", "lstm" or None (only the last layer is used). With Jumping Knowledge, the output is produced by a final linear layer. Default: None

None
**kwargs Any

Additional arguments of the convolution layer.

{}

Methods:

Name Description
init_conv

Builds one convolution layer. Implemented by subclasses.

__call__

Computes the node embeddings (or predictions).

Source code in mlx_graphs/nn/models/basic_gnn.py
def __init__(
    self,
    node_features_dim: Union[int, Tuple[int, int]],
    hidden_features_dim: int,
    num_layers: int,
    out_features_dim: Optional[int] = None,
    dropout: float = 0.0,
    act: Activation = "relu",
    norm: Normalization = None,
    jk: Optional[Literal["cat", "max", "lstm"]] = None,
    **kwargs: Any,
):
    super().__init__()
    if num_layers < 1:
        raise ValueError("`num_layers` must be at least 1")

    self.node_features_dim = node_features_dim
    self.hidden_features_dim = hidden_features_dim
    self.num_layers = num_layers
    self.out_features_dim = (
        out_features_dim if out_features_dim is not None else hidden_features_dim
    )
    self.act = _resolve_activation(act)
    # Normalization name, for convolutions with inner MLPs (`init_conv`).
    self._norm_name = norm
    self.dropout = nn.Dropout(dropout) if dropout > 0.0 else None
    self._dropout_p = dropout

    # Without Jumping Knowledge the last convolution maps directly to the
    # output size; with it, every convolution outputs hidden embeddings and
    # a final linear layer produces the output.
    conv_out_last = hidden_features_dim
    if out_features_dim is not None and jk is None:
        conv_out_last = out_features_dim
    self._plain_last = out_features_dim is not None and jk is None

    # As in PyG, a (src, dst) input size gives every layer separate
    # source and destination sizes.
    hidden_in: Union[int, Tuple[int, int]] = hidden_features_dim
    if isinstance(node_features_dim, (tuple, list)):
        node_features_dim = tuple(node_features_dim)
        hidden_in = (hidden_features_dim, hidden_features_dim)
    in_dims = [node_features_dim] + [hidden_in] * (num_layers - 1)
    out_dims = [hidden_features_dim] * (num_layers - 1) + [conv_out_last]
    self.convs = [
        self.init_conv(in_dim, out_dim, is_last=(i == num_layers - 1), **kwargs)
        for i, (in_dim, out_dim) in enumerate(zip(in_dims, out_dims))
    ]

    num_post = num_layers - 1 if self._plain_last else num_layers
    if norm is not None:
        self.norms = [
            _make_norm(norm, hidden_features_dim) for _ in range(num_post)
        ]

    if jk is not None:
        self.jk = JumpingKnowledge(jk, hidden_features_dim, num_layers)
        jk_dim = hidden_features_dim * (num_layers if jk == "cat" else 1)
        if out_features_dim is not None or jk == "cat":
            self.lin = Linear(jk_dim, self.out_features_dim)

init_conv

init_conv(
    node_features_dim: int, out_features_dim: int, is_last: bool, **kwargs
) -> Module

Builds one convolution layer. Implemented by subclasses.

Source code in mlx_graphs/nn/models/basic_gnn.py
def init_conv(
    self, node_features_dim: int, out_features_dim: int, is_last: bool, **kwargs
) -> nn.Module:
    """Builds one convolution layer. Implemented by subclasses."""
    raise NotImplementedError

__call__

__call__(
    edge_index: array,
    node_features: array,
    edge_weights: Optional[array] = None,
    edge_features: Optional[array] = None,
) -> array

Computes the node embeddings (or predictions).

Parameters:

Name Type Description Default
edge_index array

Input edge index of shape [2, num_edges]

required
node_features array

Input node features

required
edge_weights Optional[array]

Optional weight of each edge, for models whose convolution supports it.

None
edge_features Optional[array]

Optional features of each edge, for models whose convolution supports it.

None

Returns:

Type Description
array

An array of shape [num_nodes, out_features_dim].

Source code in mlx_graphs/nn/models/basic_gnn.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: mx.array,
    edge_weights: Optional[mx.array] = None,
    edge_features: Optional[mx.array] = None,
) -> mx.array:
    """Computes the node embeddings (or predictions).

    Args:
        edge_index: Input edge index of shape `[2, num_edges]`
        node_features: Input node features
        edge_weights: Optional weight of each edge, for models whose
            convolution supports it.
        edge_features: Optional features of each edge, for models whose
            convolution supports it.

    Returns:
        An array of shape ``[num_nodes, out_features_dim]``.
    """
    conv_kwargs = {}
    if edge_weights is not None:
        if not self.supports_edge_weights:
            raise ValueError(
                f"{type(self).__name__} does not support `edge_weights`"
            )
        conv_kwargs["edge_weights"] = edge_weights
    if edge_features is not None:
        if not self.supports_edge_features:
            raise ValueError(
                f"{type(self).__name__} does not support `edge_features`"
            )
        conv_kwargs["edge_features"] = edge_features

    x = node_features
    xs = []
    for i, conv in enumerate(self.convs):
        x = conv(edge_index, x, **conv_kwargs)
        if not (self._plain_last and i == self.num_layers - 1):
            if "norms" in self:
                x = self.norms[i](x)
            if self.act is not None:
                x = self.act(x)
            if self.dropout is not None:
                x = self.dropout(x)
        xs.append(x)

    if "jk" in self:
        x = self.jk(xs)
    if "lin" in self:
        x = self.lin(x)
    return x

from mlx_graphs.nn import BasicGNN · mlx_graphs/nn/models/basic_gnn.py