TGraphX › Insights › Graph Isomorphism Network (GIN) Explained, with TGraphX Code
← Back to Insights

Graph Isomorphism Network (GIN) Explained, with TGraphX Code

Topic: GNN architectures and learning tasks

Graph Isomorphism Networks were introduced by Xu, Hu, Leskovec and Jegelka ("How Powerful are Graph Neural Networks?", ICLR 2019) to answer a theoretical question about message-passing graph neural networks: how expressive can they be? Their answer is that such networks are at most as powerful as the 1-dimensional Weisfeiler-Lehman (WL) graph isomorphism test, and that GIN can match that bound under specific assumptions. TGraphX provides TensorGINLayer, which applies the GIN update to image-like and volumetric node features.

This article explains GIN's architecture, what its theoretical result assumes, how TensorGINLayer handles tensor features, and why the expressiveness result does not automatically carry over to them.

Examples tested with TGraphX 1.5.1. The PyTorch Geometric comparison also needs torch_geometric.


What GIN Is Trying to Solve

Message-passing GNNs aggregate neighbor information and combine it with the central node's features:

h_v^(k) = COMBINE( h_v^(k-1), AGGREGATE( {h_u^(k-1) : u ∈ N(v)} ) )

The neighbor features form a multiset: the same value can appear several times. To distinguish different neighborhoods, the aggregation should be injective, so that different multisets give different outputs. Mean and max aggregation are not: mean gives the same result for {a, b} and {a, a, b, b}, and max gives the same result for {a, b} and {a, b, b}. A sum can keep the counts.

GIN's update rule is:

h_v^(k) = MLP( (1 + ε) · h_v^(k-1) + Σ_{u ∈ N(v)} h_u^(k-1) )

The ε parameter (fixed or learned) weights the central node's contribution relative to the summed neighborhood.

What the expressiveness result assumes

GIN can be as powerful as 1-WL when all of the following hold:

  • Node features come from a countable set, and neighborhoods have bounded size.
  • The per-element function applied before each sum is chosen so that the sum identifies the multiset. With one-hot input features the first sum already does this; otherwise a suitable transformation is needed before it. In later layers the previous MLP plays this role.
  • ε is chosen so that the center cannot be confused with a neighbor (Xu et al. show that infinitely many values work, including all irrational numbers).
  • The graph-level readout is injective too. Xu et al. use sum readouts over the representations of every layer.
  • There are enough GIN layers: at least as many as the WL refinement rounds needed to tell the graphs apart.

These are existence results. They say suitable functions exist and that an MLP can represent them, not that training will find them. And 1-WL remains the ceiling: GIN cannot separate graphs that 1-WL cannot.

One practical consequence: with ε = 0, a single update cannot tell the center from a neighbor. A node with feature a and neighbor b and a node with feature b and neighbor a produce the same sum. Xu et al. nevertheless evaluated this fixed variant (GIN-0) and reported that it did at least as well on test accuracy as learning ε in their experiments. TensorGINLayer defaults to eps=0.0 and train_eps=False.


GIN with Edge Features: GINEConv

The original GIN does not include edge features. Hu et al. ("Strategies for Pre-training Graph Neural Networks", ICLR 2020) added them by summing node embeddings and edge embeddings, with no ReLU on the individual messages. PyG's GINEConv and TensorGINLayer use a modification of that edge-feature GIN, usually called GINE:

h_v^(k) = MLP( (1 + ε) · h_v^(k-1) + Σ_{u ∈ N(v)} ReLU( h_u^(k-1) + φ(e_uv) ) )

Here φ maps the edge feature e_uv to the node feature shape. The per-message ReLU matters: without a nonlinearity there, the sum would split into Σ h_u + Σ φ(e_uv), so that aggregation would lose which edge feature belongs to which neighbor. TGraphX provides GIN and GINE in one class, switched by the use_edge_features flag.


TGraphX's TensorGINLayer: GIN on Spatial Features

When node features are image patches, sensor maps or volumes, with shapes [N, C, H, W] or [N, C, D, H, W], an nn.Linear MLP requires flattening them. Flattening keeps every value but drops the knowledge of which entries are neighboring pixels. TensorGINLayer instead builds its MLP from 1×1 (or 1×1×1) convolutions, so the spatial layout is preserved:

python
import torch
from tgraphx import TensorGINLayer

torch.manual_seed(0)

layer = TensorGINLayer(
    in_channels=16,
    out_channels=32,
    hidden_channels=64,
    eps=0.0,
    train_eps=True,       # learn epsilon together with the MLP
    use_batchnorm=True,
    spatial_rank=2,       # [N, C, H, W]
)

x = torch.randn(50, 16, 8, 8)
edge_index = torch.randint(0, 50, (2, 200))
out = layer(x, edge_index)
print(out.shape)          # torch.Size([50, 32, 8, 8])

# Volumes: spatial_rank=3 expects [N, C, D, H, W]
volume_layer = TensorGINLayer(2, 8, spatial_rank=3)
print(volume_layer(torch.randn(10, 2, 4, 4, 4), torch.randint(0, 10, (2, 20))).shape)
# torch.Size([10, 8, 4, 4, 4])

Edge features can be spatial maps or vectors:

python
E = edge_index.size(1)

# Spatial edge features [E, edge_dim, H, W]
spatial_edges = TensorGINLayer(16, 32, use_edge_features=True, edge_dim=8,
                               edge_features_kind="spatial")
out_s = spatial_edges(x, edge_index, edge_features=torch.randn(E, 8, 8, 8))

# Vector edge features [E, edge_dim], projected and broadcast over H x W
vector_edges = TensorGINLayer(16, 32, use_edge_features=True, edge_dim=4,
                              edge_features_kind="vector")
out_v = vector_edges(x, edge_index, edge_features=torch.randn(E, 4))
print(out_s.shape, out_v.shape)

What Does Not Carry Over to Tensor Features

The default MLP acts on each spatial position separately, and the neighbor sum is element-wise. So TensorGINLayer behaves like H × W vector GINs with shared weights running side by side on the same graph, each reading only the values at its own position. Stacking more default layers never changes that. (With use_batchnorm=True, positions share only the normalization statistics.)

The following two neighborhoods are different multisets of tensors, yet no stack of default layers can separate them:

python
# Node 0 is the center; nodes 1 and 2 are its neighbors. Each node holds a 1 x 1 x 2 "image".
def star(leaf_a, leaf_b):
    return torch.tensor([[0.0, 0.0], leaf_a, leaf_b]).view(3, 1, 1, 2)

x_a = star([1.0, 2.0], [3.0, 4.0])   # neighbor tensors (1, 2) and (3, 4)
x_b = star([1.0, 4.0], [3.0, 2.0])   # neighbor tensors (1, 4) and (3, 2)
star_edges = torch.tensor([[1, 2, 0, 0], [0, 0, 1, 2]])

gin1, gin2 = TensorGINLayer(1, 8), TensorGINLayer(8, 8)
with torch.no_grad():
    out_a = gin2(gin1(x_a, star_edges), star_edges)
    out_b = gin2(gin1(x_b, star_edges), star_edges)

print(torch.allclose(out_a[0], out_b[0]))           # True: same center embedding
print(torch.allclose(out_a.sum(0), out_b.sum(0)))   # True: same sum readout

The left pixel sees the values {1, 3} in both graphs and the right pixel sees {2, 4}. This is not a matter of unlucky weights: it holds for any weights of the default MLP.

Note also that the raw sums are already equal: (1,2) + (3,4) = (1,4) + (3,2). A module applied after that sum, including a custom mlp= passed to the layer, sees identical input at the center. Positions have to be mixed nonlinearly on each node before the sum that matters, by an encoder in front of the first layer or by a position-mixing mlp= in an earlier layer. A purely linear projection L satisfies Σ L(h_u) = L(Σ h_u) (a bias only adds a multiple of the neighbor count, which is equal here), so it does not by itself resolve a raw-sum collision at that sum. A nonlinear per-node function can:

python
print(torch.equal(x_a[1:].sum(0), x_b[1:].sum(0)))        # True: raw sums collide

def encode(x):
    """Nonlinear position mixing on each node: append the product of both pixels."""
    product = (x[..., 0:1] * x[..., 1:2]).expand_as(x)
    return torch.cat([x, product], dim=1)                 # 2 channels

print(torch.equal(encode(x_a)[1:].sum(0), encode(x_b)[1:].sum(0)))   # False

In a model, a learned per-node encoder (for example a small CNN with kernels larger than 1×1 and nonlinear activations, or a nonlinear MLP on the flattened tensor) takes that role. Whether it separates the cases that matter is then a question of its design and training, not something the GIN theorem guarantees. If you need the vector-GIN behavior over whole tensors, flatten to [N, D] and use a GIN on vectors, preceded by such an encoder.


Memory and Chunked Edges

Materializing one message tensor per edge can be expensive when node features are large. forward() accepts chunk_size, which processes edges in slices; chunking applies when the graph has more edges than chunk_size:

python
layer.eval()
with torch.no_grad():
    full = layer(x, edge_index)
    chunked = layer(x, edge_index, chunk_size=64)     # 200 edges, so 4 chunks
print(torch.allclose(full, chunked, atol=1e-5))       # True

The two paths agree up to floating-point rounding. chunk_size changes only the per-edge work: messages, and their gradients in the backward pass, are processed one slice at a time. Node tensors, including those inside the MLP, are not chunked. Chunking can help only when the per-edge buffers dominate peak memory, and whether they do depends on the number of edges per node, the input and output channel widths, the kind of edge features (spatial edge features add per-edge buffers of their own) and autograd. On sparse graphs with only a few edges per node, chunking saved nothing in some configurations, under torch.no_grad() or in training, and cut the peak substantially in others. In some training checks with edge features, the peak was even higher with chunking.

Autograd also limits what chunking can save. A plain layer whose input does not require gradients (typically the first layer on raw features) does not keep the message tensors. When the input requires gradients (as in later layers of a trainable stack), or when edge features pass through a learnable projection, the per-chunk message tensors, which together still cover every edge, are kept until backward(). These observations come from CPU checks on random graphs with torch 2.15, so measure peak memory both with and without chunking on your own graph before relying on it. Neighbor sampling remains an additional option for large graphs.


Where GIN Fits among TGraphX Layers

All of these are message-passing layers, so without unique node identifiers none of them exceeds 1-WL. They differ in what the aggregation step throws away:

Layer Neighbor aggregation What it can lose Node features
GCNConv Degree-normalized sum, with self-loops Different multisets can give the same normalized sum Vectors
TensorGraphSAGELayer Mean or max, plus a separate self transform How many times a neighbor value occurs Spatial
TensorGATLayer Attention weights that sum to 1 How many times a neighbor value occurs Spatial
TensorGINLayer Plain sum plus (1 + ε) self, then MLP Distinct multisets with equal sums; cross-position structure Spatial (vectors via two unit axes)

TensorGINLayer and PyTorch Geometric's GINConv

PyG's GINConv takes any nn module as its MLP. Its default node_dim=-2 assumes vector features, but with node_dim=0 and a convolutional MLP it computes the same update on [N, C, H, W] tensors:

python
from torch_geometric.nn import GINConv

tgx_layer = TensorGINLayer(3, 16).eval()
# GINConv re-initializes the module it is given; both layers share that module here.
pyg_layer = GINConv(tgx_layer.mlp, eps=0.0, node_dim=0)

patches = torch.randn(6, 3, 5, 5)
ei = torch.randint(0, 6, (2, 14))
with torch.no_grad():
    print(torch.allclose(tgx_layer(patches, ei), pyg_layer(patches, ei), atol=1e-6))  # True

# Vector features with TensorGINLayer: add two unit axes, then flatten
vectors = torch.randn(6, 4)
print(TensorGINLayer(4, 7)(vectors[:, :, None, None], ei).flatten(1).shape)  # [6, 7]

The practical differences are in convenience:

  • TensorGINLayer builds the 1×1 or 1×1×1 convolutional MLP for you.
  • It raises ValueError for a wrong input rank and TypeError for a non-long edge_index. A wrong channel count surfaces as PyTorch's RuntimeError from the convolution.
  • It accepts spatial or vector edge features through edge_features_kind.
  • It does not require PyG.

For ordinary vector-feature graphs, PyG's GINConv is a natural choice. The constructors differ, so treat switching between the two as a code change, not a rename.


A Graph-Level Classifier with GraphBatch

This classifier sum-pools node tensors per graph with global_sum_pool and takes one training step on a batch of four synthetic graphs:

python
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph, GraphBatch, global_sum_pool

class TensorGINClassifier(nn.Module):
    def __init__(self, in_c, hidden_c, out_c, height, width, num_classes):
        super().__init__()
        self.gin1 = TensorGINLayer(in_c, hidden_c, train_eps=True, use_batchnorm=True)
        self.gin2 = TensorGINLayer(hidden_c, out_c, train_eps=True, use_batchnorm=True)
        self.classifier = nn.Linear(out_c * height * width, num_classes)

    def forward(self, x, edge_index, batch=None):
        if batch is None:                                   # a single graph
            batch = torch.zeros(x.size(0), dtype=torch.long, device=x.device)
        x = F.relu(self.gin1(x, edge_index))
        x = F.relu(self.gin2(x, edge_index))
        x = global_sum_pool(x, batch)                       # [B, out_c, H, W]
        return self.classifier(x.flatten(1))

def random_graph(num_nodes, label):
    return Graph(node_features=torch.randn(num_nodes, 3, 8, 8),
                 edge_index=torch.randint(0, num_nodes, (2, 4 * num_nodes)),
                 graph_label=torch.tensor(label))

batch = GraphBatch([random_graph(12, 0), random_graph(20, 1),
                    random_graph(16, 2), random_graph(9, 1)])
model = TensorGINClassifier(3, 16, 32, height=8, width=8, num_classes=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

logits = model(batch.node_features, batch.edge_index, batch.batch)
loss = F.cross_entropy(logits, batch.graph_labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(logits.shape)   # torch.Size([4, 3])

This only demonstrates the shapes and wiring. The classifier has no per-node position mixing (its linear head combines positions only after the sum over nodes), so the limitation in What Does Not Carry Over to Tensor Features applies: put a nonlinear per-node encoder before gin1 if cross-position structure within a node matters. For splits, early stopping and cross-validation, see graph-level classification architectures.


Limitations and Honest Notes

GIN is bounded by 1-WL. It cannot distinguish graphs that the WL test cannot distinguish. Going further needs other machinery, such as higher-order GNNs (Morris et al., "Weisfeiler and Leman Go Neural", AAAI 2019) or additional node information; TensorGINLayer does neither.

The expressiveness result is not a training guarantee. A finite MLP trained by gradient descent need not learn injective functions.

On tensor features the guarantee does not extend to multisets of tensors. As shown above, the default layer works position by position.

train_eps=True adds one scalar parameter per layer. Whether it helps is an empirical question for your task.

Depth problems remain. Too few layers under-reach; many layers can run into the usual deep message-passing issues such as over-squashing and over-smoothing. Keeping spatial dimensions does not remove them.

No benchmark numbers are given here. Results depend on data preprocessing, graph construction, hyperparameters and training setup; see the benchmark disclaimers before citing any.


Where to Go Next