Skip to content

GraphSAINTSampler

GraphSAINTSampler(
    data: GraphData,
    batch_size: int,
    num_steps: int = 1,
    sample_coverage: int = 0,
    save_dir: Optional[str] = None,
)

Base class of the GraphSAINT samplers, from the "GraphSAINT: Graph Sampling Based Inductive Learning Method" paper, following PyG's GraphSAINTSampler.

Each iteration samples a set of nodes (how depends on the subclass) and yields the subgraph they induce, as a GraphData with node- and edge-level attributes sliced to the subgraph, plus n_id (global id of every node, sorted) and e_id (original id of every edge).

If sample_coverage > 0, normalization statistics are estimated beforehand by sampling subgraphs until every node has been sampled sample_coverage times on average, and every batch also holds:

  • node_norm: per-node loss weight, num_samples / (count(v) * N), to use as (node_norm * loss).sum();
  • edge_norm: per-edge aggregation weight, count(target(e)) / count(e), to scale messages with (with the default source -> target message passing, so that, for a sampled node, the expected normalized sum of the messages it receives equals the full-graph sum).
Note

PyG divides the count of the edge's source node instead (count(source(e)) / count(e)), which is the paper's normalization for the reverse edge: aggregations are then biased by count(source) / count(target) (several-fold for nodes of very different degrees). This class follows the paper, \(\alpha_{u,v} = p_{u,v} / p_v\) with \(v\) the aggregating node.

Parameters:

Name Type Description Default
data GraphData

The full graph.

required
batch_size int

Sampling budget of each subgraph (meaning depends on the subclass).

required
num_steps int

Number of subgraphs (iterations) per epoch. Defaults to 1

1
sample_coverage int

Average number of samples per node used to compute the normalization statistics. 0 disables them. Defaults to 0

0
save_dir Optional[str]

Optional directory where the normalization statistics are cached (as .npz) and loaded from. Defaults to None

None
Source code in mlx_graphs/loaders/graph_saint.py
def __init__(
    self,
    data: GraphData,
    batch_size: int,
    num_steps: int = 1,
    sample_coverage: int = 0,
    save_dir: Optional[str] = None,
):
    if batch_size < 1:
        raise ValueError(f"`batch_size` must be positive (got {batch_size})")
    for name in ("node_norm", "edge_norm"):
        if getattr(data, name, None) is not None:
            raise ValueError(f"`data` already has a '{name}' attribute.")

    self.data = data
    self.batch_size = batch_size
    self.num_steps = num_steps
    self.sample_coverage = sample_coverage
    self.save_dir = save_dir

    self.N = data.num_nodes
    self.E = data.num_edges
    self._adj = Adjacency(data.edge_index, self.N)
    self._step = 0

    self.node_norm: Optional[np.ndarray] = None
    self.edge_norm: Optional[np.ndarray] = None
    if sample_coverage > 0:
        path = (
            os.path.join(save_dir, self._filename) if save_dir is not None else None
        )
        if path is not None and os.path.exists(path):
            saved = np.load(path)
            self.node_norm, self.edge_norm = saved["node_norm"], saved["edge_norm"]
        else:
            self.node_norm, self.edge_norm = self._compute_norm()
            if path is not None:
                os.makedirs(save_dir, exist_ok=True)  # type: ignore
                np.savez(path, node_norm=self.node_norm, edge_norm=self.edge_norm)

from mlx_graphs.loaders import GraphSAINTSampler · mlx_graphs/loaders/graph_saint.py