Skip to content

NeighborLoader

NeighborLoader(
    data: Union[GraphData, HeteroGraphData, tuple],
    num_neighbors: Union[list[int], dict[EdgeType, list[int]]],
    input_nodes: Union[None, array, str, tuple[str, Optional[array]]] = None,
    batch_size: int = 1,
    shuffle: bool = False,
    replace: bool = False,
    directed: bool = True,
    sampler: Optional[Iterable[int]] = None,
    time_attr: Optional[str] = None,
    input_time: Optional[array] = None,
    temporal_strategy: str = "uniform",
    disjoint: bool = False,
)

Mini-batch loader for node-level tasks on a single large graph.

Uses neighbor sampling to extract K-hop subgraphs around seed nodes. Works on both homogeneous and heterogeneous graphs, following PyG's API: the implementation is picked from the type of data.

  • GraphData: each iteration yields a GraphData holding the sampled subgraph with locally re-indexed edges.
  • HeteroGraphData: each iteration yields a HeteroGraphData with edges re-indexed locally per node type (sampled with mlx_cluster.hetero_neighbor_sample).
  • A (FeatureStore, GraphStore) pair (PyG's remote backend, see FeatureStore): the graph structure is read from the graph store, and only the rows of the sampled nodes (and edges) are gathered from the feature store at every iteration, so node features can stay on disk (MemmapFeatureStore). Store arrays named x / y / edge_attr become node_features / node_labels / edge_features of the mini-batch. For static, non-disjoint sampling, CSC adjacency stored in a MemmapGraphStore is shared with the native sampler on MLX builds that support zero-copy host buffers.

Temporal sampling (homogeneous graphs): with time_attr, only the neighbors whose timestamp is earlier than or equal to the time of their seed are sampled, as in PyG. time_attr names a node-level timestamp (the time of a neighbor is then its node's) or an edge-level one (the time of the edge, which requires input_time). The time of a seed is input_time if given, else its own node timestamp. As in PyG, every seed then gets its own subgraph (disjoint=True): a node sampled for two seeds appears twice, and batch.batch holds the position of the seed of every node. These mini-batches also hold the per-hop counts num_sampled_nodes / num_sampled_edges, and seed_time when input_time is given.

The first batch_size nodes (of the seed node type, for heterogeneous graphs) are always the seed nodes. During training, compute the loss only on these nodes:

# homogeneous
out = model(batch.node_features, batch.edge_index)
loss = loss_fn(out[: batch.batch_size], batch.node_labels[: batch.batch_size])

# heterogeneous
out = model(batch.node_features_dict, batch.edge_index_dict)
n = batch.batch_size
loss = loss_fn(out["author"][:n], batch.node_labels_dict["author"][:n])

Parameters:

Name Type Description Default
data Union[GraphData, HeteroGraphData, tuple]

The full graph, a GraphData or a HeteroGraphData, or a homogeneous graph as a (FeatureStore, GraphStore) pair.

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

Number of neighbors to sample per hop. Its length determines the number of hops; -1 samples all neighbors. E.g. [10, 5] samples 10 neighbors at hop-1, 5 at hop-2. For heterogeneous graphs this can also be a dict mapping each edge type to its own list.

required
input_nodes Union[None, array, str, tuple[str, Optional[array]]]

The seed nodes to iterate over.

  • Homogeneous: a 1-D array of node indices, a boolean mask (e.g. data.train_mask), or None for all nodes.
  • Heterogeneous (required): the seed node type and which of its nodes to use: "author" (all authors), ("author", indices) or ("author", boolean_mask).
None
batch_size int

Number of seed nodes per mini-batch.

1
shuffle bool

Whether to shuffle the seed nodes at the start of 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, for each epoch, the positions in input_nodes of the seeds to use, e.g. an ImbalancedSampler built with the same input_nodes. Overrides shuffle. Seeds drawn several times in a mini-batch are kept as separate seeds for a GraphData (so batch_size counts them all), but merged for a HeteroGraphData (batch_size is then the number of distinct seeds).

None
time_attr Optional[str]

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

None
input_time Optional[array]

Optional time of every seed in input_nodes (overrides the node timestamps; required for an edge-level time_attr).

None
temporal_strategy str

"uniform" samples uniformly among the neighbors valid in time, "last" keeps the most recent ones.

'uniform'
disjoint bool

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

False

Example:

from mlx_graphs.datasets import DBLP
from mlx_graphs.loaders import NeighborLoader

data = DBLP()[0]
loader = NeighborLoader(
    data,
    num_neighbors=[10, 5],
    input_nodes=("author", data.author_train_mask),
    batch_size=128,
    shuffle=True,
)
batch = next(iter(loader))
Source code in mlx_graphs/loaders/neighbor_loader.py
def __init__(
    self,
    data: Union[GraphData, HeteroGraphData, tuple],
    num_neighbors: Union[list[int], dict[EdgeType, list[int]]],
    input_nodes: Union[None, mx.array, str, tuple[str, Optional[mx.array]]] = None,
    batch_size: int = 1,
    shuffle: bool = False,
    replace: bool = False,
    directed: bool = True,
    sampler: Optional[Iterable[int]] = None,
    time_attr: Optional[str] = None,
    input_time: Optional[mx.array] = None,
    temporal_strategy: str = "uniform",
    disjoint: bool = False,
):
    if isinstance(data, HeteroGraphData):
        if time_attr is not None or input_time is not None or disjoint:
            raise NotImplementedError(
                "Temporal and disjoint sampling are only supported for "
                "homogeneous graphs."
            )
        if input_nodes is None or isinstance(input_nodes, mx.array):
            raise ValueError(
                "For a HeteroGraphData, `input_nodes` must name the seed "
                "node type: 'author', ('author', indices) or "
                "('author', boolean_mask)."
            )
        if not directed:
            raise ValueError(
                "`directed=False` is not supported for heterogeneous graphs."
            )
        self._loader = _HeteroNeighborLoader(
            data,
            num_neighbors,
            input_nodes,
            batch_size=batch_size,
            shuffle=shuffle,
            replace=replace,
            sampler=sampler,
        )
    elif isinstance(data, GraphData) or is_store_pair(data):
        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."
            )
        if isinstance(input_nodes, (str, tuple)):
            raise ValueError(
                "Node types in `input_nodes` are only supported for "
                "heterogeneous graphs; pass an array of node indices "
                "for a GraphData."
            )
        self._loader = _HomogeneousNeighborLoader(
            data,
            num_neighbors,
            input_nodes,
            batch_size=batch_size,
            shuffle=shuffle,
            replace=replace,
            directed=directed,
            sampler=sampler,
            time_attr=time_attr,
            input_time=input_time,
            temporal_strategy=temporal_strategy,
            disjoint=disjoint,
        )
    else:
        raise TypeError(
            "`data` must be a GraphData or a HeteroGraphData (or a "
            f"(FeatureStore, GraphStore) pair), got {type(data).__name__}."
        )

from mlx_graphs.loaders import NeighborLoader · mlx_graphs/loaders/neighbor_loader.py