Skip to content

HGTLoader

HGTLoader(
    data: HeteroGraphData,
    num_samples: Union[list[int], dict[str, list[int]]],
    input_nodes: Union[str, tuple[str, Optional[array]]],
    batch_size: int = 1,
    shuffle: bool = False,
    sampler: Optional[Iterable[int]] = None,
)

Bases: _HeteroNeighborLoader

Heterogeneous mini-batch loader using the layer-wise sampling of "Heterogeneous Graph Transformer" (HGSampling), as PyG's HGTLoader.

Instead of a number of neighbors per node (NeighborLoader), each hop samples a node budget per node type: every node type keeps a budget of candidate nodes, adjacent to the nodes sampled so far. Each sampled node adds 1 / degree to the budget of each of its (not yet sampled) neighbors, for every edge type pointing to it (nodes with more than 50 neighbors only add 1 / 50 to 50 random ones). At hop l, num_samples[node_type][l] nodes of each type are drawn from its budget without replacement, with probability proportional to the squared budget, which favours nodes connected to many sampled nodes. The mini-batch is the subgraph induced by the sampled nodes (for destination nodes with more than 50 neighbors, edges to 50 random ones, as in PyG).

Sampling runs on the host with NumPy (seed it with np.random.seed).

The first batch_size nodes of the seed node type are the seed nodes, so the loss is computed on them:

for batch in loader:
    out = model(batch.edge_index_dict, batch.node_features_dict)
    n = batch.batch_size
    loss = loss_fn(out["paper"][:n], batch.node_labels_dict["paper"][:n])

Each batch is a HeteroGraphData with the same attributes as the batches of NeighborLoader: edge_index_dict (local ids per node type), node_features_dict, node_labels_dict, edge_features_dict, n_id_dict (global id of every sampled node), e_id_dict (original position of every sampled edge), batch_size, input_type, num_nodes_dict, num_sampled_nodes_dict (number of nodes added at each hop, starting with the seeds), and the per-node attributes of data (e.g. paper_train_mask) sliced to the sampled nodes. Every node type and edge type is present, possibly empty.

Parameters:

Name Type Description Default
data HeteroGraphData

The full graph.

required
num_samples Union[list[int], dict[str, list[int]]]

Number of nodes to sample per hop, either one list for every node type (e.g. [512] * 4) or a dict mapping each node type to its own list. Node types missing from the dict, or with a shorter list, sample no nodes at the missing hops.

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

The seed node type and which of its nodes to iterate over: "paper" (all papers), ("paper", indices) or ("paper", boolean_mask).

required
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
sampler Optional[Iterable[int]]

Iterable yielding positions in input_nodes for each epoch (e.g. an ImbalancedSampler). Overrides shuffle. Duplicate seeds within a mini-batch are merged, so batch_size is then the number of distinct seeds.

None

Example:

from mlx_graphs.datasets import DBLP
from mlx_graphs.loaders import HGTLoader

data = DBLP()[0]
loader = HGTLoader(
    data,
    num_samples={
        "author": [512] * 2,
        "paper": [512] * 2,
        "term": [256] * 2,
        "conference": [20] * 2,
    },
    input_nodes=("author", data.author_train_mask),
    batch_size=128,
    shuffle=True,
)
batch = next(iter(loader))

Methods:

Name Description
sample

Samples the subgraph of a mini-batch.

Source code in mlx_graphs/loaders/hgt_loader.py
def __init__(
    self,
    data: HeteroGraphData,
    num_samples: Union[list[int], dict[str, list[int]]],
    input_nodes: Union[str, tuple[str, Optional[mx.array]]],
    batch_size: int = 1,
    shuffle: bool = False,
    sampler: Optional[Iterable[int]] = None,
):
    if not isinstance(data, HeteroGraphData):
        raise TypeError(
            f"HGTLoader needs a HeteroGraphData, got {type(data).__name__}"
        )
    if isinstance(input_nodes, mx.array) or input_nodes is None:
        raise ValueError(
            "`input_nodes` must name the seed node type: 'paper', "
            "('paper', indices) or ('paper', boolean_mask)."
        )
    super().__init__(
        data,
        num_neighbors=[],
        input_nodes=input_nodes,
        batch_size=batch_size,
        shuffle=shuffle,
        sampler=sampler,
    )
    node_types = list(self.num_nodes)
    if isinstance(num_samples, dict):
        unknown = [t for t in num_samples if t not in self.num_nodes]
        if unknown:
            raise ValueError(f"Unknown node types in num_samples: {unknown}")
        num_samples = {t: list(num_samples.get(t, [])) for t in node_types}
    else:
        num_samples = {t: list(num_samples) for t in node_types}
    if any(n < 0 for v in num_samples.values() for n in v):
        raise ValueError("num_samples must be non-negative")
    self.num_samples = num_samples
    self.num_hops = max((len(v) for v in num_samples.values()), default=0)

    self._colptr = {et: np.asarray(v) for et, v in self._colptr_dict.items()}
    self._row = {et: np.asarray(v) for et, v in self._row_dict.items()}
    self._perm = {et: np.asarray(v) for et, v in self._perm_dict.items()}
    self._edge_types = list(data.edge_index_dict)

sample

sample(seed_nodes: ndarray) -> tuple[dict, dict, dict, dict]

Samples the subgraph of a mini-batch.

Parameters:

Name Type Description Default
seed_nodes ndarray

Global ids of the (distinct) seed nodes of self.input_type.

required

Returns:

Type Description
dict

(n_id_dict, edge_index_dict, e_id_dict, num_sampled_nodes_dict)

as NumPy arrays

the sampled nodes per node type (seeds first),

dict

the induced edges in local ids, their original edge positions, and

dict

the number of nodes added per hop.

Source code in mlx_graphs/loaders/hgt_loader.py
def sample(self, seed_nodes: np.ndarray) -> tuple[dict, dict, dict, dict]:
    """Samples the subgraph of a mini-batch.

    Args:
        seed_nodes: Global ids of the (distinct) seed nodes of
            ``self.input_type``.

    Returns:
        ``(n_id_dict, edge_index_dict, e_id_dict, num_sampled_nodes_dict)``
        as NumPy arrays: the sampled nodes per node type (seeds first),
        the induced edges in local ids, their original edge positions, and
        the number of nodes added per hop.
    """
    node_types = list(self.num_nodes)
    nodes = {t: [] for t in node_types}
    counts = {t: [0] for t in node_types}
    local = {t: np.full(self.num_nodes[t], -1, dtype=np.int64) for t in node_types}
    budget = {t: np.zeros(self.num_nodes[t]) for t in node_types}

    def add(node_type, new):
        local[node_type][new] = sum(len(n) for n in nodes[node_type]) + np.arange(
            new.size
        )
        nodes[node_type].append(new)
        budget[node_type][new] = 0.0

    add(self.input_type, seed_nodes)
    counts[self.input_type][0] = seed_nodes.size
    self._update_budget(budget, local, self.input_type, seed_nodes)

    for hop in range(self.num_hops):
        samples = {}
        for node_type in node_types:
            plan = self.num_samples[node_type]
            k = plan[hop] if hop < len(plan) else 0
            candidates = np.nonzero(budget[node_type] > 0)[0]
            samples[node_type] = _weighted_sample(
                candidates, budget[node_type][candidates] ** 2, k
            )
            add(node_type, samples[node_type])
            counts[node_type].append(samples[node_type].size)
        if hop < self.num_hops - 1:
            for node_type, new in samples.items():
                self._update_budget(budget, local, node_type, new)

    n_id = {
        t: np.concatenate(v) if v else np.zeros(0, dtype=np.int64)
        for t, v in nodes.items()
    }

    # Induced subgraph (at most 50 random in-neighbors per destination).
    edge_index, e_id = {}, {}
    for edge_type in self._edge_types:
        src, _, dst = edge_type
        owner, pos, _ = _capped_neighbors(self._colptr[edge_type], n_id[dst])
        src_local = local[src][self._row[edge_type][pos]]
        keep = src_local >= 0
        edge_index[edge_type] = np.stack([src_local[keep], owner[keep]])
        e_id[edge_type] = self._perm[edge_type][pos[keep]]
    return n_id, edge_index, e_id, counts

from mlx_graphs.loaders import HGTLoader · mlx_graphs/loaders/hgt_loader.py