Back to Graph Theory Series

Graph Isomorphism Networks (GIN)

October 4, 2026 Updated November 1, 2026 Wasil Zafar 30 min read

GIN turns a theoretical question into a practical design rule: preserve a neighborhood as a multiset, so repeated features still count. Sum aggregation, an expressive MLP, and an injective graph readout let the architecture match the distinguishing power of 1‑WL within the standard aggregation-based message-passing framework.

Contents

  1. A Bit of History
  2. Mental Model: Neighborhoods Are Multisets
  3. 1-WL and Expressiveness
  4. The GIN Layer
  5. Sum vs. Mean vs. Max
  6. Worked Layer Example
  7. Graph-Level Readout
  8. Complexity Analysis
  9. Implementation
  10. Real-World Applications
  11. Practical Guidance
  12. Exercises
  13. Limitations

A Bit of History

Graph Isomorphism Networks sit at a productive meeting point between classical graph refinement and neural message passing. The key historical move was not merely introducing another layer formula; it was giving common GNN architectures a shared yardstick for structural discrimination.

From Color Refinement to GIN

1968Boris Weisfeiler and Andrei Leman published an algebraic graph-refinement method. Modern 1‑WL, or vertex color refinement, carries the same iterative idea: recolor a vertex from its old color and the multiset of neighboring colors.
2017GCN and GraphSAGE helped establish neighborhood aggregation as a scalable neural pattern, but their mean- and pooling-style aggregators could collapse different neighborhood multisets.
2018Keyulu Xu, Weihua Hu, Jure Leskovec, and Stefanie Jegelka released How Powerful are Graph Neural Networks?, relating aggregation-based GNNs to the Weisfeiler–Leman test and proposing GIN.
2019The paper appeared at ICLR. GIN became a standard reference architecture for discussing GNN expressiveness and graph-level prediction.

Primary reading: the GIN paper, the historical Weisfeiler–Leman paper and translation project, and the earlier Jumping Knowledge Networks paper.

Mental Model: A Neighborhood Is a Multiset

A set records whether an element appears. A multiset also records how many times it appears. That difference matters in graphs: three neighbors with the same label are three messages, not one.

Suppose red and teal nodes use one-hot features, with red $=(1,0)$ and teal $=(0,1)$. The neighborhoods ${\text{red},\text{teal}}$ and ${\text{red},\text{red},\text{teal},\text{teal}}$ contain the same types and proportions, but different multiplicities. A structure-sensitive aggregator should be able to keep them apart.

Two neighborhoods with the same feature types but different multiplicities Neighborhood A contains one red and one teal node. Neighborhood B contains two red and two teal nodes. A set view and mean aggregation hide the repeated elements, while a multiset view preserves their counts. Counts are structural information Neighborhood A RT multiset = {R, T} Neighborhood B RRTT multiset = {R, R, T, T} Same types and proportions; different counts.
Multiplicity is the information that sum aggregation can retain and mean or max aggregation can discard.
Intuition: a shopping list saying “apple, apple, lime” is not equivalent to “apple, lime.” Mean and max often summarize the ingredient profile; sum can also preserve how many items contributed.

The Expressiveness Question: 1-WL as the Ceiling

At refinement round $k$, 1‑WL replaces each node's color with an injective encoding of its previous color and the multiset of neighbor colors:

$$c_v^{(k)}=\operatorname{HASH}\!\left(c_v^{(k-1)},\left\{\!\left\{c_u^{(k-1)}:u\in\mathcal N(v)\right\}\!\right\}\right).$$

The double braces emphasize a multiset. If two graphs produce different color histograms in any round, they are definitely non-isomorphic. If all histograms remain equal, the test is inconclusive; it has not proved that the graphs are isomorphic.

Upper bound

For the aggregation-based GNN class studied in the paper, if a GNN separates two graphs, 1‑WL also separates them. The claim is not about every graph architecture ever devised.

Matching the bound

If neighbor aggregation, node combination, and graph readout are injective, a sufficiently deep model can separate every pair that 1‑WL separates.

Local radius

After $k$ layers, $h_v^{(k)}$ summarizes a rooted $k$-hop unfolding around $v$. Deeper layers expand the structural horizon.

Representation, not proof

A trained finite-width network can still collide because of optimization, limited dimension, floating-point arithmetic, or uninformative input features.

The core bridge: 1‑WL hashes colors; GIN learns vector encodings. Both repeatedly combine a node's current state with the multiset of states around it.

The GIN Layer: Sum, Separate Self, Then Transform

GIN implements the neural analogue with a neighbor sum, a distinct self contribution, and an MLP:

$$h_v^{(k)} = \text{MLP}^{(k)} \left( (1 + \epsilon^{(k)}) \cdot h_v^{(k-1)} + \sum_{u \in \mathcal{N}(v)} h_u^{(k-1)} \right)$$

  • Neighbor sum: retains multiplicity instead of dividing it away.
  • Self coefficient: $(1+\epsilon^{(k)})$ distinguishes the center from its neighbors. GIN‑0 fixes $\epsilon=0$; GIN‑$\epsilon$ learns one scalar per layer.
  • MLP: maps the combined vector through a nonlinear, expressive update. The theory motivates this capacity; it does not guarantee that ordinary training makes every learned MLP globally injective.
Data flow through one Graph Isomorphism Network layer Neighbor embeddings are summed. The center embedding is multiplied by one plus epsilon. These two vectors are added and passed through a multilayer perceptron to create the center node's next embedding. One GIN update for target v neighbors u₁u₂u₃ SUMΣ hᵤ hᵥ× (1 + ε) + MLPnonlinear map h′ᵥ
The explicit self term means an implementation should aggregate an adjacency list without self-loops, unless it deliberately adjusts the formula to avoid double-counting.

Gather

Read the previous-layer embedding of every neighbor.

Sum

Add neighbor vectors coordinate-wise, preserving multiplicity.

Add self

Add $(1+\epsilon)h_v$ so the center has a distinguishable role.

Transform

Pass the combined vector through the layer-specific MLP.

What Sum, Mean, and Max Remember

These aggregators are not simply stronger or weaker numerical recipes; each retains a different summary of a multiset.

AggregatorUsually retainsTypical collisionUseful bias
SumTypes and multiplicities, under the paper's countable/bounded assumptions with a suitable encodingCan still collide with arbitrary raw continuous vectors or a poorly learned encoderGraph size and repeated motifs matter
MeanFeature proportions or distributionsA multiset and a uniformly repeated copy have the same meanNormalize away neighborhood size
MaxWhich strong feature coordinates appearRepeated copies do not change a coordinate-wise maximumPresence matters more than frequency
Sum distinguishes two multisets that mean and max collapse Multiset A has one red vector and one teal vector. Multiset B repeats each vector twice. Their sums are one one and two two, while their means are both zero point five zero point five and their maxima are both one one. Let R = (1, 0) and T = (0, 1) A = {R, T}RT B = {R, R, T, T}RRTT SUM separatesA → (1, 1)B → (2, 2) MEAN collidesA → (0.5, 0.5)B → (0.5, 0.5) MAX collidesA → (1, 1)B → (1, 1) The collision happens before any downstream classifier can recover the lost count.
Once two neighborhoods receive the same aggregate, a deterministic update applied afterward cannot tell which original multiset produced it.

Worked Layer Example

Let target $v$ have previous representation $h_v=(2,1)$ and three neighbor representations

$$h_{u_1}=(1,0),\qquad h_{u_2}=(1,0),\qquad h_{u_3}=(0,3).$$

First sum the neighbors:

$$m_v=(1,0)+(1,0)+(0,3)=(2,3).$$

With $\epsilon=0.25$, the pre-MLP vector is

$$z_v=(1.25)(2,1)+(2,3)=(2.5,1.25)+(2,3)=(4.5,4.25).$$

The MLP then maps $z_v$ to $h_v'$. The MLP is not aggregating the neighborhood from scratch; it operates on a vector where the repeated $(1,0)$ neighbor has already contributed twice.

Do Not Add the Self Node Twice

The formula already includes $(1+\epsilon)h_v$. If the adjacency structure also contains $v\to v$, a naïve implementation adds another $h_v$. Either remove self-loops before neighbor summation or use a deliberately reformulated update.

From Node Embeddings to a Graph Embedding

For graph classification, preserving neighborhood information is not enough; the graph-level readout must also avoid collapsing distinct node multisets. GIN sums node representations independently at every depth, then concatenates those summaries:

$$h_G=\operatorname{CONCAT}\left(\sum_{v\in V}h_v^{(0)},\sum_{v\in V}h_v^{(1)},\ldots,\sum_{v\in V}h_v^{(K)}\right).$$

Early blocks represent local patterns; later blocks represent progressively wider neighborhoods. Concatenation lets the classifier decide which scales matter. This resembles Jumping Knowledge, but the GIN paper uses a specific graph-level concatenation of per-layer readouts.

GIN graph readout sums nodes at each depth and concatenates the results Node matrices from input depth zero and GIN layers one through three are each pooled by summing across nodes. The four pooled vectors are concatenated into one multi-scale graph representation. Keep a summary from every structural radius depth 0input features depth 11-hop patterns depth 22-hop patterns depth 33-hop patterns SUM NODESat each depthseparately CONCATENATEmulti-scale graphembedding hᴳ Concatenation preserves layer identity; adding the vectors would mix those scales.
The input layer may have a different width from hidden layers, another reason concatenation—not element-wise addition—is the natural teaching implementation.

Complexity Analysis

Let $n=|V|$, $m=|E|$, input width $d$, MLP hidden width $p$, and output width $d'$. With a sparse directed edge list:

OperationTime per layerMain storage
Neighbor sum$O(md)$Edge index $O(m)$ and aggregate $O(nd)$
Two-layer MLP$O(ndp+npd')$Activations $O(np+nd')$
Graph readout$O(nd')$ per retained depthPooled vectors and concatenated representation

GIN's sparse aggregation has the same broad linear-in-edges scaling as other message-passing layers. Its extra compute usually comes from the deeper MLP and from retaining multiple layer outputs for graph-level readout. A dense $n\times n$ adjacency teaching implementation instead uses $O(n^2)$ storage and multiplication, which is unsuitable for large sparse graphs.

Implementation

The NumPy version isolates the exact pre-MLP calculation. The PyTorch version uses index_add_ to aggregate only listed edges, avoiding a dense adjacency matrix and making the edge direction explicit.

import numpy as np


def gin_pre_mlp(x, edge_index, eps=0.0):
    """Compute (1 + eps) * x_v + sum_{u in N(v)} x_u.

    edge_index has shape (2, M): row 0 is source, row 1 is target.
    Self-loops are rejected because the formula adds self separately.
    """
    x = np.asarray(x, dtype=float)
    edge_index = np.asarray(edge_index, dtype=int)
    if x.ndim != 2 or edge_index.ndim != 2 or edge_index.shape[0] != 2:
        raise ValueError("Expected x=(N,D) and edge_index=(2,M)")

    source, target = edge_index
    if np.any(source == target):
        raise ValueError("Remove self-loops before the GIN neighbor sum")
    if source.size and (source.min() < 0 or target.min() < 0 or
                        source.max() >= len(x) or target.max() >= len(x)):
        raise IndexError("edge_index contains an invalid node id")

    neighbor_sum = np.zeros_like(x)
    np.add.at(neighbor_sum, target, x[source])
    return (1.0 + eps) * x + neighbor_sum


def graph_readout(layer_outputs):
    """Concatenate the node-sum from every depth."""
    return np.concatenate([h.sum(axis=0) for h in layer_outputs])


# Worked example: nodes 1, 2, and 3 send messages to node 0.
x = np.array([[2, 1], [1, 0], [1, 0], [0, 3]], dtype=float)
edge_index = np.array([[1, 2, 3], [0, 0, 0]])
combined = gin_pre_mlp(x, edge_index, eps=0.25)

print(combined[0])             # [4.5  4.25]
print(graph_readout([x, combined]).shape)  # (4,)
import torch
import torch.nn as nn


class GINLayer(nn.Module):
    """Sparse GIN layer; edge_index excludes self-loops."""

    def __init__(self, in_dim, hidden_dim, out_dim,
                 eps=0.0, train_eps=True):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(in_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, out_dim)
        )
        initial_eps = torch.tensor(float(eps))
        if train_eps:
            self.eps = nn.Parameter(initial_eps)
        else:
            self.register_buffer("eps", initial_eps)

    def forward(self, x, edge_index):
        source, target = edge_index
        if torch.any(source == target):
            raise ValueError("Remove self-loops: GIN adds self separately")

        neighbor_sum = torch.zeros_like(x)
        neighbor_sum.index_add_(0, target, x[source])
        combined = (1.0 + self.eps) * x + neighbor_sum
        return self.mlp(combined)


def global_sum_pool(x, batch, num_graphs):
    """Sum node rows into their graph ids."""
    pooled = x.new_zeros((num_graphs, x.size(-1)))
    pooled.index_add_(0, batch, x)
    return pooled


class GINGraphClassifier(nn.Module):
    def __init__(self, in_dim, hidden_dim, num_classes,
                 num_layers=3, train_eps=True):
        super().__init__()
        dims = [in_dim] + [hidden_dim] * num_layers
        self.layers = nn.ModuleList([
            GINLayer(dims[k], hidden_dim, dims[k + 1],
                     train_eps=train_eps)
            for k in range(num_layers)
        ])
        readout_dim = in_dim + num_layers * hidden_dim
        self.classifier = nn.Linear(readout_dim, num_classes)

    def forward(self, x, edge_index, batch):
        # batch[v] is the graph id containing node v.
        num_graphs = int(batch.max().item()) + 1
        representations = [x]
        h = x
        for layer in self.layers:
            h = layer(h, edge_index)
            representations.append(h)

        pooled_by_depth = [
            global_sum_pool(z, batch, num_graphs)
            for z in representations
        ]
        graph_repr = torch.cat(pooled_by_depth, dim=-1)
        return self.classifier(graph_repr), graph_repr


# One undirected graph: store both directions and no self-loops.
x = torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.5]])
edge_index = torch.tensor([
    [0, 1, 0, 2, 1, 2, 2, 3],  # source
    [1, 0, 2, 0, 2, 1, 3, 2]   # target
])
batch = torch.zeros(4, dtype=torch.long)

model = GINGraphClassifier(2, 8, num_classes=2, num_layers=3)
logits, graph_repr = model(x, edge_index, batch)
print(logits.shape)      # torch.Size([1, 2])
print(graph_repr.shape)  # torch.Size([1, 26]) = 2 + 3 * 8

Real-World Applications

GIN is especially natural when the label belongs to an entire graph and repeated local patterns carry signal.

Molecules

Atom and bond neighborhoods form recurring motifs. Sum aggregation can retain motif multiplicity, while a graph readout supports property prediction. Plain GIN must be extended if bond features need their own message transformation.

Biological Graphs

Protein, enzyme, and interaction graphs can be classified from repeated local arrangements, provided the node and edge features expose the biologically relevant distinctions.

Program Graphs

Abstract-syntax, control-flow, or dependency graphs contain repeated node types and motifs. A multi-depth readout can combine local syntax with wider structural context.

Graph Benchmarks

GIN is a valuable expressiveness-oriented baseline: it tests whether preserving neighborhood multiplicities helps, without requiring attention scores or higher-order tensors.

Practical Guidance

Choose useful starting features

With identical node features, GIN sees structure and degree-driven multiplicities. Add labels, attributes, or positional information when the task depends on distinctions that topology alone cannot reveal.

Control the scale of sums

High-degree nodes and large graphs produce larger magnitudes. Batch normalization, careful initialization, residual connections, and readout normalization may improve optimization, though normalization can alter what counts are retained.

Test both epsilon variants

Fixed $\epsilon=0$ is simple and often competitive. A learned $\epsilon$ lets each layer adjust the relative self contribution, but adds no new neighbor information.

Match readout to the target

Sum pooling suits count-sensitive graph labels. Mean pooling may generalize better when graph size is nuisance variation. Expressiveness is a design consideration, not a universal accuracy guarantee.

Implementation Checklist

both edge directionsno accidental self-loopsum by targetper-layer MLPpool by graph idconcatenate depths

Always unit-test the aggregation on a graph small enough to calculate by hand. Most GIN bugs are indexing, self-loop, batching, or readout mistakes—not errors in the one-line equation.

Exercises

1. Find the Collision

For one-hot vectors $a=(1,0)$ and $b=(0,1)$, compute sum, mean, and coordinate-wise max for $X=\{a,a,b\}$ and $Y=\{a,a,a,a,b,b\}$. Which aggregators collide?

Hint: $Y$ is exactly two copies of $X$.

2. Track Epsilon

Use the worked example with $\epsilon=-0.5$, $0$, and $1$. Compute the three pre-MLP vectors and explain what changes—and what neighbor information does not.

3. Confirm the 1-WL Ceiling

Give every node the same initial feature in a six-cycle $C_6$ and in two disjoint triangles $2C_3$. Show inductively that all six nodes in both graphs receive the same embedding at every GIN layer.

Hint: every node has exactly two neighbors whose embeddings are equal at the previous layer.

4. Prove Permutation Equivariance

Explain why relabeling node indices relabels the output node embeddings in the same way, while the graph-level sum readout stays unchanged.

5. Extend the Code

Batch two graphs with different numbers of nodes, create the batch vector, and verify that global_sum_pool produces one row per graph. Then add a check that every undirected edge is represented in both directions.

Limitations

The 1-WL Ceiling Still Applies

GIN matches rather than exceeds 1‑WL under the theorem's assumptions. With identical initial features, $C_6$ and $2C_3$ both contain six degree-two nodes. Every node therefore receives the same repeated update in every round, and sum readout produces six copies of the same vector for both graphs.

Higher-order, subgraph-aware, or positional architectures can separate some 1‑WL collisions, usually with added computation, memory, or stronger structural assumptions.

  • Theory is an upper-capacity statement: finite width, finite precision, optimization, and regularization can make a trained GIN less discriminative than the ideal construction.
  • Continuous features need care: the clean injective-sum result is stated for a countable feature universe and bounded-size multisets; arbitrary continuous vectors do not automatically inherit the guarantee.
  • Magnitude grows with counts: node degree and graph size affect sum scale, which can complicate optimization or create unwanted size sensitivity.
  • Depth has familiar message-passing problems: oversmoothing, oversquashing, noise propagation, and expanding memory for retained layer outputs still apply.
  • Plain GIN is node-feature-centric: rich edge attributes, directions, temporal information, and geometric coordinates require appropriate message-function extensions.
  • Expressiveness is not accuracy: a weaker inductive bias may generalize better when multiplicity or graph size is irrelevant to the target.