Skip to content

LinkNeighborLoader

LinkNeighborLoader(
    data: Union[GraphData, HeteroGraphData],
    num_neighbors: Union[list[int], dict[EdgeType, list[int]]],
    edge_label_index: Any = None,
    edge_label: Optional[array] = None,
    neg_sampling: Union[None, str, dict, NegativeSampling] = None,
    neg_sampling_ratio: Optional[float] = None,
    batch_size: int = 1,
    shuffle: bool = False,
    replace: bool = False,
    directed: bool = True,
    sampler: Optional[Iterable[int]] = None,
    edge_label_time: Optional[array] = None,
    time_attr: Optional[str] = None,
    temporal_strategy: str = "uniform",
    disjoint: bool = False,
)

Mini-batch loader for link-level tasks (e.g. link prediction) on a single large graph, following PyG's LinkNeighborLoader.

Iterates over the supervision edges edge_label_index. For each batch of edges (plus optional negative samples), the source and destination nodes are used as seeds of a neighbor sampling (as in NeighborLoader), and the sampled subgraph is returned with the supervision edges relabeled to local node ids.

Each batch holds, besides the sliced subgraph:

  • n_id / e_id: global ids of the sampled nodes and original ids of the sampled edges (n_id_dict / e_id_dict for heterogeneous graphs). The seed nodes come first in n_id.
  • input_id: positions in edge_label_index of the positive edges of the batch.
  • Without negative sampling, or with "binary" negative sampling: edge_label_index ([2, num_pos + num_neg], positives first, as local node ids) and edge_label (1 for positives and 0 for negatives when edge_label is not given; when edge_label is given and contains 0, it is incremented by one so that 0 means "negative").
  • With "triplet" negative sampling: src_index, dst_pos_index ([batch_size]) and dst_neg_index ([batch_size] or [batch_size, amount]), as local node ids.
  • For heterogeneous graphs: input_type, the supervised edge type. edge_label_index row 0 indexes nodes of its source type, row 1 nodes of its destination type.

Supervision edges are not removed from the message-passing graph.

Temporal sampling (homogeneous graphs), as in PyG: with time_attr and edge_label_time, the seeds of every supervision edge (and of its negatives) only sample neighbors whose timestamp is not later than the edge's time, and negatives are drawn among nodes whose timestamp is not later either (node-level time_attr). Every seed then gets its own subgraph (disjoint=True): the sources come first, then the destinations, without merging, so edge_label_index is arange(2 * num_edges).reshape(2, -1) and batch.batch holds, for every node, the position in the mini-batch of its supervision edge. Mini-batches also hold edge_label_time (seed_time for "triplet" negative sampling).

Parameters:

Name Type Description Default
data Union[GraphData, HeteroGraphData]

The full graph, a GraphData or a HeteroGraphData.

required
num_neighbors Union[list[int], dict[EdgeType, list[int]]]

Number of neighbors to sample per hop (see NeighborLoader).

required
edge_label_index Any

The supervision edges. For a GraphData, a [2, num_edges] array (defaults to data.edge_index). For a HeteroGraphData (required), an edge type (all its edges) or a tuple (edge_type, [2, num_edges] array).

None
edge_label Optional[array]

Optional label of every supervision edge.

None
neg_sampling Union[None, str, dict, NegativeSampling]

Negative sampling configuration: a NegativeSampling, a mode string ("binary" or "triplet") or a dict of NegativeSampling arguments.

None
neg_sampling_ratio Optional[float]

Shortcut for neg_sampling=NegativeSampling("binary", neg_sampling_ratio).

None
batch_size int

Number of supervision edges per mini-batch.

1
shuffle bool

Whether to shuffle the supervision edges at each epoch.

False
replace bool

Whether to sample neighbors with replacement.

False
directed bool

Whether to only include edges in the sampling direction. Only True is supported for heterogeneous graphs.

True
sampler Optional[Iterable[int]]

Iterable yielding positions in edge_label_index for each epoch. Overrides shuffle.

None
edge_label_time Optional[array]

Timestamp of every supervision edge (requires time_attr).

None
time_attr Optional[str]

Name of the node-level or edge-level timestamp attribute of data used for temporal sampling (requires edge_label_time). Homogeneous graphs only.

None
temporal_strategy str

"uniform" or "last" (see NeighborLoader).

'uniform'
disjoint bool

Whether every seed gets its own subgraph (always the case with time_attr). Homogeneous graphs only.

False

Example:

from mlx_graphs.loaders import LinkNeighborLoader

loader = LinkNeighborLoader(
    data,
    num_neighbors=[10, 5],
    edge_label_index=train_edge_index,
    neg_sampling_ratio=1.0,
    batch_size=256,
    shuffle=True,
)
for batch in loader:
    h = model(batch.node_features, batch.edge_index)
    src, dst = batch.edge_label_index
    logits = (h[src] * h[dst]).sum(-1)
    loss = bce(logits, batch.edge_label)

Attributes:

Name Type Description
edge_label_index ndarray

The supervision edges (global node ids).

edge_label Optional[array]

The labels of the supervision edges (incremented, see above).

Source code in mlx_graphs/loaders/link_neighbor_loader.py
def __init__(
    self,
    data: Union[GraphData, HeteroGraphData],
    num_neighbors: Union[list[int], dict[EdgeType, list[int]]],
    edge_label_index: Any = None,
    edge_label: Optional[mx.array] = None,
    neg_sampling: Union[None, str, dict, NegativeSampling] = None,
    neg_sampling_ratio: Optional[float] = None,
    batch_size: int = 1,
    shuffle: bool = False,
    replace: bool = False,
    directed: bool = True,
    sampler: Optional[Iterable[int]] = None,
    edge_label_time: Optional[mx.array] = None,
    time_attr: Optional[str] = None,
    temporal_strategy: str = "uniform",
    disjoint: bool = False,
):
    if (edge_label_time is None) != (time_attr is None):
        raise ValueError(
            "Received conflicting 'edge_label_time' and 'time_attr' "
            "arguments: temporal sampling needs both."
        )
    if neg_sampling_ratio is not None and neg_sampling_ratio != 0.0:
        if neg_sampling is not None:
            raise ValueError(
                "Pass either `neg_sampling` or `neg_sampling_ratio`, not both."
            )
        neg_sampling = NegativeSampling("binary", neg_sampling_ratio)
    neg = NegativeSampling.cast(neg_sampling)

    if edge_label is not None and neg is not None:
        if neg.is_triplet():
            raise ValueError(
                "'edge_label' needs to be undefined for 'triplet'-based "
                "negative sampling. Use `src_index`, `dst_pos_index` and "
                "`dst_neg_index` of the returned mini-batch instead."
            )
        if edge_label.size > 0 and mx.min(edge_label).item() == 0:
            # Increment labels such that `zero` now denotes "negative".
            edge_label = edge_label + 1

    if isinstance(data, HeteroGraphData):
        if edge_label_index is None:
            raise ValueError(
                "For a HeteroGraphData, `edge_label_index` must name the "
                "supervised edge type: edge_type or (edge_type, index)."
            )
        if not directed:
            raise ValueError(
                "`directed=False` is not supported for heterogeneous graphs."
            )
        if time_attr is not None or disjoint:
            raise NotImplementedError(
                "Temporal and disjoint sampling are only supported for "
                "homogeneous graphs."
            )
        self._impl: Any = _HeteroLinkNeighborLoader(
            data,
            num_neighbors,
            edge_label_index,
            edge_label,
            neg,
            replace,
        )
    elif isinstance(data, GraphData):
        if isinstance(num_neighbors, dict):
            raise ValueError(
                "A dict of `num_neighbors` per edge type is only supported "
                "for heterogeneous graphs; pass a list for a GraphData."
            )
        self._impl = _HomogeneousLinkNeighborLoader(
            data,
            num_neighbors,
            edge_label_index,
            edge_label,
            neg,
            replace,
            directed,
            time_attr=time_attr,
            edge_label_time=edge_label_time,
            temporal_strategy=temporal_strategy,
            disjoint=disjoint,
        )
    else:
        raise TypeError(
            "`data` must be a GraphData or a HeteroGraphData, "
            f"got {type(data).__name__}."
        )

    num_label_edges = self._impl.edge_label_index.shape[1]
    if edge_label is not None and edge_label.shape[0] != num_label_edges:
        raise ValueError(
            f"`edge_label` has {edge_label.shape[0]} entries but there are "
            f"{num_label_edges} supervision edges."
        )
    if edge_label_time is not None and edge_label_time.size != num_label_edges:
        raise ValueError(
            f"`edge_label_time` has {edge_label_time.size} entries but "
            f"there are {num_label_edges} supervision edges."
        )

    self.data = data
    self.neg_sampling = neg
    self.batch_size = batch_size
    self.shuffle = shuffle
    self.sampler = sampler
    self._indices = np.arange(num_label_edges)
    self._current_index = 0

edge_label_index property

edge_label_index: ndarray

The supervision edges (global node ids).

edge_label property

edge_label: Optional[array]

The labels of the supervision edges (incremented, see above).

from mlx_graphs.loaders import LinkNeighborLoader · mlx_graphs/loaders/link_neighbor_loader.py