AI Logic

Architectures

Graph Isomorphism Network (GIN)

Updated:

Structure of GIN. The left side shows the overall flow, where layers that add a node's own and its neighbors' features and pass them through an MLP are stacked K times, and the sums over all nodes at each layer are concatenated to classify the graph; the right side shows the update of one node v and an example where, when all features are identical, only the sum can tell 2 neighbors from 3

Background and Overview

GIN (Graph Isomorphism Network) is a graph neural network that stacks layers which scale a node's own features by (1+ϵ)(1 + \epsilon), add its neighbors' features without normalization, and pass the result through an MLP. Xu, Hu, Leskovec, and Jegelka proposed it in 2018, and it was presented at ICLR 2019.

Graph neural networks such as GCN and GraphSAGE repeatedly "gather features from neighboring nodes and update each node's own features." They worked well in experiments, but it was not well understood theoretically which differences between graphs they can distinguish and which they cannot.

The GIN paper answered this question.

  • Networks that gather from neighbors and update cannot be more powerful than the Weisfeiler-Lehman (WL) procedure used for graph isomorphism testing.
  • If the function that aggregates neighbor features "always maps different neighborhoods to different values" (is injective), the network is as powerful as the WL procedure.
  • Aggregating with the mean (GCN) or the max (GraphSAGE pooling) does not satisfy this condition and can fail to distinguish even simple graphs.

GIN was designed as a simple architecture that satisfies this condition. As the paper's title, "How Powerful are Graph Neural Networks?", suggests, its main contribution is less the method itself than the theory of expressive power it established for graph neural networks.

GIN is especially effective on tasks where differences in the shape of the whole graph determine the answer, such as predicting molecular properties. The paper's experiments also focus on classifying whole graphs rather than nodes.

Theory: The Upper Bound on Expressive Power and the GIN Layer

Viewing neighborhood aggregation as a function on multisets

Neighbors have no order, and several of them may share the same features. The paper therefore treats the collection of neighbor features as a multiset (a set that can contain the same element any number of times). For example, three neighbors with features a, a, b form the multiset "a twice, b once."

The kk-th layer of a graph neural network can generally be written as follows (Equation 2.1 in the paper).

av(k)=AGGREGATE(k)({hu(k−1):u∈N(v)}),hv(k)=COMBINE(k)(hv(k−1),av(k))a_v^{(k)} = \mathrm{AGGREGATE}^{(k)}\left(\{h_u^{(k-1)} : u \in \mathcal{N}(v)\}\right), \qquad h_v^{(k)} = \mathrm{COMBINE}^{(k)}\left(h_v^{(k-1)}, a_v^{(k)}\right)

AGGREGATE gathers from the neighbors, and COMBINE combines the result with the node itself. For the network to distinguish two different neighborhoods, AGGREGATE and COMBINE must always map different multisets to different values (be injective).

Main results of the paper

  1. The WL procedure is an upper bound (Lemma 2): If a network that gathers from neighbors and updates maps two graphs to different representations, the WL procedure also decides that the two are "not isomorphic." In other words, no amount of training lets such a network distinguish more graphs than the WL procedure.
  2. Injective means as powerful as WL (Theorem 3): If neighbor aggregation, combination with the node itself, and the whole-graph readout (READOUT) are all injective, a network with enough layers can distinguish every pair of graphs that the WL procedure can.
  3. Summation can be made injective (Lemma 5, Corollary 6): When the input features come from a countable set, mapping them with a suitably chosen function ff and then taking the sum yields a different value for each multiset. Adding the node's own features scaled by (1+ϵ)(1 + \epsilon) also distinguishes the pair of the node and its neighborhood (an irrational ϵ\epsilon suffices).

The GIN layer

The ff from point 3 and the function applied afterward are approximated with an MLP, since MLPs can approximate any continuous function (the universal approximation theorem). The resulting GIN layer is as follows (Equation 4.1 in the paper).

hv(k)=MLP(k)((1+ϵ(k))⋅hv(k−1)+∑u∈N(v)hu(k−1))h_v^{(k)} = \mathrm{MLP}^{(k)}\left(\left(1 + \epsilon^{(k)}\right) \cdot h_v^{(k-1)} + \sum_{u \in \mathcal{N}(v)} h_u^{(k-1)}\right)

The steps are:

  1. Multiply the node's own previous features by (1+ϵ)(1 + \epsilon).
  2. Sum the neighbors' features as they are, without normalization, and add them to the result of step 1.
  3. Pass the result through an MLP (two layers in the paper).

ϵ\epsilon can be learned (GIN-ϵ\epsilon) or fixed at 0 (GIN-0).

Whole-graph representation (Equation 4.2 in the paper)

To classify a whole graph, the features of all nodes at each layer are aggregated with READOUT (a sum in the paper), and the results from all layers are concatenated.

hG=CONCAT(READOUT({hv(k)∣v∈G}) ∣ k=0,1,…,K)h_G = \mathrm{CONCAT}\left(\mathrm{READOUT}\left(\{h_v^{(k)} \mid v \in G\}\right) \,\Big|\, k = 0, 1, \dots, K\right)

Deeper layers give each node features that reflect structure over a wider range, but features from shallower layers sometimes generalize better. Using all layers keeps both kinds of information.

How It Works: Why Aggregate with a Sum

Sum vs. mean vs. max (Sections 5.2–5.4 and Figures 2 and 3 of the paper)

The mean and max are also order-independent functions, but they are not injective. Each captures a different aspect of a multiset.

AggregatorWhat it capturesExample it cannot distinguishUsed by
SumThe multiset itself (what appears and how many times)None (can be made injective)GIN
MeanProportions of elements (the distribution)a, b vs. a, a, b, b (both are half a and half b)GCN and others
MaxTypes of elements (the set)a, b vs. a, b, b (same types)GraphSAGE pooling

The simplest example is a graph in which every node has the same feature a. For a node with 2 neighbors and one with 3, the sums are 2a2a and 3a3a, which differ, but the mean and max are both aa, so they cannot be told apart. On graphs without node features, aggregating with the mean or max captures no structural information at all.

Aggregating with the mean is not bad in itself. The paper notes that because the mean captures "the distribution of neighbor features," it is about as powerful as the sum on tasks where node features are diverse and rarely repeat. The paper explains that this is why GCN works well on node classification tasks where trends in neighbor features are the key signal, such as classifying documents in citation networks. The max suits tasks that look for "representative elements," such as finding the skeleton of a point cloud.

A one-layer perceptron is not enough (Section 5.1 of the paper)

With schemes like GCN that apply only a single "linear transformation + ReLU" before aggregating, there are pairs of multisets that cannot be distinguished even with a sum (Lemma 7). This is because a one-layer perceptron cannot approximate every function on multisets. GIN uses an MLP to avoid this weakness.

Relation to the Weisfeiler-Lehman procedure

The WL procedure assigns a color to each node and repeatedly hashes the pair "own color and the multiset of neighbor colors" to a new color, always giving different pairs different colors. GIN replaces this hash with the computation "scale by (1+ϵ)(1+\epsilon), sum, and pass through an MLP." WL colors only express "same or different," but GIN's features are vectors, so it can also map similar structures to nearby representations, which the paper says helps generalization.

Experimental Results

Experimental setup (Section 7 of the paper)

The paper used nine graph classification datasets: four bioinformatics datasets (MUTAG, PTC, NCI1, PROTEINS) and five social network datasets (COLLAB, IMDB-BINARY, IMDB-MULTI, REDDIT-BINARY, REDDIT-MULTI5K). To test whether models can learn from structure without relying on node features, the social network data was given no features (all nodes get the same value in REDDIT, and one-hot degrees elsewhere).

ItemValue
Number of layers5 (including the input layer)
MLP2 layers, with batch normalization on each hidden layer
READOUTSum for bioinformatics, mean for social networks (better test accuracy)
OptimizerAdam, learning rate 0.01, multiplied by 0.5 every 50 epochs (step decay)
Tuned hyperparametersHidden dimension, batch size (32 or 128), dropout after the dense layer (0 or 0.5), number of epochs
EvaluationMean and standard deviation over 10-fold cross-validation

Test accuracy (excerpt from Table 1 of the paper; accuracy in %)

"Mean–1-layer" corresponds to GCN and "Max–1-layer" to GraphSAGE, apart from minor differences.

MethodIMDB-BRDT-BRDT-M5KCOLLABMUTAGPROTEINSPTCNCI1
WL subtree kernel73.881.052.578.990.475.059.986.0
GIN-0 (Sum–MLP)75.192.457.580.289.476.264.682.7
GIN-ϵ\epsilon (Sum–MLP)74.392.257.080.189.075.963.782.7
Sum–1-layer74.190.055.180.690.076.263.182.0
Mean–MLP73.750.020.079.283.575.566.680.9
Mean–1-layer (GCN)74.050.020.079.085.676.064.280.2
Max–1-layer (GraphSAGE)72.3———85.175.963.977.7

On all nine datasets, GIN-0 was better than or statistically indistinguishable from the other graph neural networks (on NCI1, the WL subtree kernel was significantly better). In particular, on REDDIT, where every node was given the same feature, the mean-aggregation models captured no structure at all and scored 50.0% on 2 classes and 20.0% on 5 classes, the same as random guessing. GIN, which aggregates with a sum, scored 92.4% and 57.5%.

Fit to the training data (Figure 4 of the paper)

GIN-ϵ\epsilon and GIN-0 fit almost all of the training data perfectly. Models that aggregate with the mean or max, or that use a one-layer perceptron, failed to fit even the training data on many datasets (underfitting), matching the theoretical ranking of expressive power. Meanwhile, no model's training accuracy exceeded that of the WL subtree kernel, which is also consistent with the theory that the WL procedure is the upper bound.

GIN-ϵ\epsilon, which learns ϵ\epsilon, and GIN-0, which fixes it at 0, fit the training data equally well, but GIN-0 had slightly yet consistently higher test accuracy. The paper attributes this to simplicity helping generalization. When in doubt, start with GIN-0.

Practical Considerations

Keep the following points in mind when using GIN.

  • It cannot distinguish graphs that the WL procedure cannot: GIN's power is capped at that of the WL procedure. For example, some "regular graphs," in which every node has the same degree, cannot be distinguished by the WL procedure, and GIN gives them the same representation as well.
  • The theory assumes countable features: The injectivity result applies when input features come from a countable (discrete) set. The paper leaves continuous-valued features to future work. Also, being able to distinguish graphs is a separate question from generalizing well to test data.
  • Summation tends to produce large values: Because it does not divide by the number of neighbors, nodes with higher degree get larger feature values. As in the paper's setup, add batch normalization to the MLP's hidden layers to keep magnitudes in check.
  • Choose READOUT to fit the data: Although the paper recommends the sum on theoretical grounds, it used the mean for social network data because that gave better test accuracy.
  • Where to get it in PyTorch: PyTorch itself does not include it. It can be written as in the implementation example below, or you can use GINConv from PyTorch Geometric (pass in an MLP; train_eps=True learns ϵ\epsilon), global_add_pool for summing over whole graphs, or GINConv from DGL.

"GIN is the most expressive" means the most expressive among networks that gather from neighbors and update (message passing). Graphs that the WL procedure cannot distinguish cannot be distinguished by GIN either, no matter how it is trained. The paper also lists even more powerful models beyond this scheme as future work.

Comparison with Other Methods

Comparing four representative graph neural networks from the same angle gives the following.

MethodHow neighbor features are aggregatedTransformation after aggregationNeighborhoods it can distinguishMain use case
GCNDegree-normalized sum (close to the mean)Linear transformation + activation (one layer)Proportions of features (distribution)Node classification
GraphSAGEMean, LSTM, or max (pooling)Concatenate with self, then linear transformation + activationDistribution with the mean, types with the maxNode classification on large graphs
GATAttention-weighted sum (weights sum to 1)Linear transformation + activationNot addressed in the paperNode classification
GINScale self by (1+ϵ)(1 + \epsilon) and sumMLPWhat appears and how many times (multiset)Whole-graph classification

Rough guidelines for choosing:

  • Classifying whole graphs, such as molecules or social network graphs: GIN is a good fit. The gap over mean-aggregation models grows especially on data with few node features or many identical features.
  • Classifying nodes with rich node features: The distribution of neighbor features is often the key signal, so GCN or GAT may be enough.
  • Classifying nodes in a huge graph: GraphSAGE, which can sample neighborhoods, is easier to work with.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# A small implementation following Equations 4.1 and 4.2 of the paper (PyTorch itself has no GIN layer)
# Multiple graphs are merged into one large graph, and batch[i] tells which graph node i belongs to


class GINLayer(nn.Module):
  def __init__(self, in_dim, out_dim, train_eps=False):
    super().__init__()
    # GIN-0 fixes ε = 0; GIN-ε learns ε
    self.eps = nn.Parameter(torch.zeros(1)) if train_eps else 0.0
    self.mlp = nn.Sequential(          # 2-layer MLP with batch normalization on each hidden layer
      nn.Linear(in_dim, out_dim), nn.BatchNorm1d(out_dim), nn.ReLU(),
      nn.Linear(out_dim, out_dim), nn.BatchNorm1d(out_dim), nn.ReLU(),
    )

  def forward(self, h, edge_index):
    src, dst = edge_index                                   # edge src → dst (include both directions for undirected edges)
    neigh_sum = torch.zeros_like(h).index_add_(0, dst, h[src])  # Σ_{u∈N(v)} h_u (no normalization)
    return self.mlp((1 + self.eps) * h + neigh_sum)


class GIN(nn.Module):
  def __init__(self, in_dim, hidden=64, num_classes=2, num_layers=4, train_eps=False, dropout=0.5):
    super().__init__()
    dims = [in_dim] + [hidden] * num_layers
    self.layers = nn.ModuleList(GINLayer(dims[i], dims[i + 1], train_eps) for i in range(num_layers))
    # predict from the concatenation of the READOUT of every layer (k = 0 … K)
    self.heads = nn.ModuleList(nn.Linear(d, num_classes) for d in dims)
    self.dropout = dropout

  def forward(self, x, edge_index, batch, num_graphs):
    hs = [x]
    for layer in self.layers:
      hs.append(layer(hs[-1], edge_index))
    out = 0
    for h, head in zip(hs, self.heads):
      # READOUT: sum of the nodes in the same graph (summed per graph)
      g = torch.zeros(num_graphs, h.size(1)).index_add_(0, batch, h)
      # applying a linear layer after CONCAT equals summing the outputs of per-layer linear layers
      out = out + F.dropout(head(g), self.dropout, self.training)
    return out


# Usage (an example merging two small graphs; features are one-hot)
x = torch.eye(7)                                           # 7 nodes
edge_index = torch.tensor([[0, 1, 1, 2, 3, 4, 4, 5, 5, 6],
                           [1, 0, 2, 1, 4, 3, 5, 4, 6, 5]])
batch = torch.tensor([0, 0, 0, 1, 1, 1, 1])                # nodes 0–2 belong to graph 0, nodes 3–6 to graph 1
labels = torch.tensor([0, 1])

model = GIN(in_dim=7)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.5)  # multiply by 0.5 every 50 epochs
for epoch in range(100):
  model.train()   # batch normalization uses batch statistics, and dropout is active
  optimizer.zero_grad()
  loss = F.cross_entropy(model(x, edge_index, batch, num_graphs=2), labels)
  loss.backward()
  optimizer.step()
  scheduler.step()

model.eval()      # batch normalization uses statistics collected during training, and dropout is off
with torch.no_grad():
  pred = model(x, edge_index, batch, num_graphs=2).argmax(dim=1)

FAQ

Q. What does "isomorphism" in GIN refer to?
A.

Two graphs are isomorphic if relabeling the nodes of one makes its connections exactly the same as the other's. Graph isomorphism testing is a hard problem, and a widely used approximate procedure is the Weisfeiler-Lehman (WL) procedure. GIN gets its name because it was designed to distinguish exactly as many graphs as the WL procedure.

Q. Why aggregate with a sum instead of a mean?
A.

Because the mean keeps only the proportions of neighbor features. For example, when every node has the same feature aa, the mean is aa whether there are 2 or 3 neighbors, so they cannot be distinguished. With a sum, 2a2a and 3a3a can be told apart. The paper proved that mapping with a suitable function and then summing fully distinguishes what appears and how many times.

Q. Can GIN be used for node classification?
A.

Yes. Using each node's features hv(K)h_v^{(K)} directly for prediction makes it usable for node classification and link prediction. However, for node classification with rich node features, mean-aggregation models such as GCN can be about as strong as the sum, and the paper's experiments focus on whole-graph classification.

References

  1. Xu, K., Hu, W., Leskovec, J., & Jegelka, S. (2019). How Powerful are Graph Neural Networks? ICLR 2019. arXiv:1810.00826.
  2. weihua916/powerful-gnns (the authors' implementation).
  3. Kipf, T. N., & Welling, M. (2017). Semi-Supervised Classification with Graph Convolutional Networks. ICLR 2017. arXiv:1609.02907.
  4. Hamilton, W. L., Ying, R., & Leskovec, J. (2017). Inductive Representation Learning on Large Graphs. NIPS 2017. arXiv:1706.02216.
  5. Veličković, P., Cucurull, G., Casanova, A., Romero, A., Liò, P., & Bengio, Y. (2018). Graph Attention Networks. ICLR 2018. arXiv:1710.10903.