Post

GNN Training and Debugging Best Practices

GNN Training and Debugging Best Practices

GNN Training and Debugging Best Practices

Training Graph Neural Networks can be tricky due to graph sparsity, neighborhood explosion, and message passing dynamics. This post summarizes practical tips to help you get stable training runs and quickly debug issues.

1) Data and Graph Sanity Checks

  • Node/edge feature ranges: standardize/normalize; watch out for extreme scales.
  • Self-loops: ensure consistent handling; many layers (e.g., GCN) assume them.
  • Isolated nodes: decide whether to drop or add virtual self-loops.
  • Class imbalance: inspect label distribution; consider weighted loss or focal loss.
  • Train/val/test leakage: split by connected components or time where applicable.

2) Batching and Sampling

  • Prefer neighbor sampling (GraphSAGE, PyG NeighborLoader, DGL Samplers) for large graphs.
  • Tune fanouts per layer (e.g., [15, 10] or [10, 10, 5]) to balance compute vs. coverage.
  • Fix seeds and use deterministic samplers to reproduce results during debugging.
  • For small graphs, full-batch training is simpler and usually more stable.

3) Architecture Choices

  • Shallow works: start with 2 layers; deeper GNNs may over-smooth.
  • Residual/JK connections help when going deeper.
  • Pick aggregators for the task: mean/max for robustness, attention for interpretability, GIN for expressiveness.
  • Use edge features where relevant (MPNN-style message functions).

4) Optimization Settings

  • Optimizer: Adam or AdamW with weight decay 1e-4 to 5e-3.
  • Learning rate: 1e-3 is a good start; cosine decay or StepLR can help.
  • Gradient clipping (e.g., 1.0) stabilizes training with large fanouts.
  • Warmup for large-batch sampling; watch for exploding variance early on.

5) Regularization Against Over-smoothing

  • DropEdge: randomly drop edges per-iteration (5–20%).
  • PairNorm/BatchNorm on node embeddings.
  • Node/feature dropout; stochastic depth for deeper stacks.
  • Early stopping on validation with patience 20–50 steps.

6) Diagnostics: What To Log

  • Layer-wise embedding norms and their coefficient of variation.
  • Training vs. validation accuracy/loss; watch for generalization gaps.
  • Attention entropy (for GAT): low entropy may indicate over-confident heads.
  • Neighbor counts per hop after sampling (mean, p95) to detect explosion.

7) Common Failure Modes and Fixes

  • Vanishing signal (all nodes similar): reduce depth, add residual/PairNorm, DropEdge.
  • Instability with high-degree nodes: cap degree, use importance sampling, gradient clip.
  • Poor performance on rare labels: class-weighted loss, oversampling, focal loss.
  • Slow training: reduce fanouts, cluster graphs (GraphSAINT/Cluster-GCN), mixed precision.

8) Evaluation Protocols

  • Temporal splits for dynamic graphs; avoid leakage from future edges.
  • Multi-run reporting (e.g., 10 seeds) with mean±std; graphs are high-variance.
  • Calibrated thresholds for link prediction; report AUROC/AP.
  • Node classification: also report macro-F1 when classes are imbalanced.

9) Reproducibility

  • Fix random seeds across Python/NumPy/torch; control cuDNN determinism.
  • Snapshot datasets and preprocessing scripts; pin PyG/DGL versions.
  • Save full config (hyperparams, fanouts, seed, commit hash) with each run.

10) Minimal PyTorch Geometric Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import torch
from torch import nn
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import SAGEConv

class GraphSAGE(nn.Module):
    def __init__(self, in_dim, hidden_dim, out_dim):
        super().__init__()
        self.conv1 = SAGEConv(in_dim, hidden_dim)
        self.conv2 = SAGEConv(hidden_dim, out_dim)
        self.dropout = nn.Dropout(p=0.5)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index).relu()
        x = self.dropout(x)
        x = self.conv2(x, edge_index)
        return x

# Usage sketch (assumes data.x, data.y, data.edge_index, train_idx, val_idx):
# loader = NeighborLoader(data, num_neighbors=[15, 10], batch_size=1024, input_nodes=train_idx)
# model = GraphSAGE(data.num_features, 256, num_classes).to(device)
# optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=5e-4)

Takeaways

  • Start simple, log aggressively, and change one thing at a time.
  • Sampling, normalization, and regularization are the levers that most often fix GNN training.
  • Always validate with multiple seeds and clear, leakage-free splits.
This post is licensed under CC BY 4.0 by the author.

© . Some rights reserved.

Using the Chirpy theme for Jekyll.