TGraphX › Insights › How to Combine a CNN and a GNN in One PyTorch Model
← Back to Insights

How to Combine a CNN and a GNN in One PyTorch Model

Topic: Combining CNNs and GNNs

Let the CNN turn each node's image into a feature vector, then hand those vectors to a graph neural network (GNN) together with an edge_index, a two-row table of who sends to whom, so that connected nodes can exchange information. Put both in one nn.Module, compute one loss, and autograd carries the gradient back through the message passing into the convolution filters. The work lies in three places: deciding what a node is, keeping node order consistent where the two networks meet, and shifting edge indices when you batch graphs.

The model below is plain PyTorch with no graph library. A PyTorch Geometric version follows it, including a layer choice that looks reasonable and fails on this task. The code blocks run in order on a CPU and share one namespace. The printed results come from PyTorch 2.15, PyTorch Geometric 2.8.1 and two CPU threads. The main model needs torch and scikit-learn; later sections also import torch_geometric, torchvision and tgraphx (version 1.5.1 here).

Decide what a node is

Before writing code, answer one question: what does a single node stand for? The answer fixes where the CNN runs.

A node is The CNN reads The GNN receives
A separate image: a crop, a view, a photo in a collection All node images, [N, C, H, W] [N, d]
A cell of one image's feature map Whole images, [B, C, H, W] [B*h*w, d]
A region of one image: a detected box or a superpixel Whole images, then one pooled vector per region [regions, d]

Here N counts nodes, B counts images, h and w are the height and width of the CNN's output grid, and d is the feature width you choose.

Edges are the second decision. They can come from geometry (which boxes touch), time (consecutive frames), metadata (the same document or the same site) or similarity of features. Whatever the source, the edges must exist at prediction time, and they must not be built from the labels you want to predict.

Two places to join a CNN to a GNN

Node images[N,C,H,W]CNN on every nodeNode features[N,d]GNN on your edgesWhole images[B,C,H,W]CNN once per imageCells become[B*h*w,d]GNN on cell edges
The same diagram as a table
boxarrows todetail
Node images [N,C,H,W]CNN on every node—
CNN on every nodeNode features [N,d]—
Node features [N,d]GNN on your edges—
GNN on your edges—Edges come from geometry, time, metadata or similarity.
Whole images [B,C,H,W]CNN once per image—
CNN once per imageCells become [B*h*w,d]—
Cells become [B*h*w,d]GNN on cell edgesMove channels last, then flatten the grid.
GNN on cell edges—Grid neighbours, plus any links the grid lacks.

8 boxes and 6 arrows. No box is selected.

Follow either column. They differ in how often the CNN runs and where the edges come from. A schematic drawn from the author's description: nothing is executed or measured.

A task that needs both parts

Each sample is a graph of 12 handwritten digits. Every node receives edges from 3 other nodes, chosen at random. The target of a node is 1 if its digit is larger than the average of the 3 digits it receives from, and 0 otherwise.

No single image contains the answer. The model has to read digits, which is a CNN's job, and compare them along edges, which is a GNN's job. The digit labels are used only to compute the targets; the model never sees them. The images are the 8 x 8 digits that ship with scikit-learn, so nothing is downloaded. This is a synthetic task built to show the mechanism, not a benchmark.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.datasets import load_digits

torch.set_num_threads(2)

digits = load_digits()                      # 8 x 8 images bundled with scikit-learn
images = torch.tensor(digits.images, dtype=torch.float32).unsqueeze(1) / 16.0
digit = torch.tensor(digits.target)         # used to build targets, never as input
print(images.shape)

# Split the source images first: no image appears in two splits.
perm = torch.randperm(len(images), generator=torch.Generator().manual_seed(0))
pools = {"train": perm[:1100], "val": perm[1100:1400], "test": perm[1400:]}
N_NODES, K = 12, 3

def random_edges(gen):
    """Each node receives from K other nodes. Row 0 = source, row 1 = destination."""
    src, dst = [], []
    for i in range(N_NODES):
        others = torch.randperm(N_NODES - 1, generator=gen)[:K]
        src += (others + (others >= i).long()).tolist()     # skip node i itself
        dst += [i] * K
    return torch.tensor([src, dst])

def make_split(name, n_graphs, seed):
    gen = torch.Generator().manual_seed(seed)
    graphs = []
    for _ in range(n_graphs):
        ids = pools[name][torch.randint(len(pools[name]), (N_NODES,), generator=gen)]
        edge_index = random_edges(gen)
        src, dst = edge_index
        value = digit[ids].float()
        neighbour_sum = torch.zeros(N_NODES).index_add_(0, dst, value[src])
        y = (value * K > neighbour_sum).long()       # larger than the neighbour mean?
        graphs.append({"x": images[ids], "edge_index": edge_index, "y": y})
    return graphs

train = make_split("train", 800, seed=1)
val = make_split("val", 200, seed=2)
test = make_split("test", 500, seed=3)
g = train[0]
print(g["x"].shape, g["edge_index"].shape, g["y"].shape)
text
torch.Size([1797, 1, 8, 8])
torch.Size([12, 1, 8, 8]) torch.Size([2, 36]) torch.Size([12])

A sample is three tensors: node images [12, 1, 8, 8], an edge index [2, 36] and one target per node.

Batch graphs by shifting edge indices

A batch of graphs is not a new tensor axis here. Several graphs become one larger graph with no edges between them: stack all node images along the first axis, and add the number of earlier nodes to each graph's edge indices.

python
def collate(graphs):
    """One big graph with no edges between samples: stack nodes, shift edge ids."""
    xs, edges, ys, offset = [], [], [], 0
    for g in graphs:
        xs.append(g["x"])
        edges.append(g["edge_index"] + offset)
        ys.append(g["y"])
        offset += len(g["x"])
    return torch.cat(xs), torch.cat(edges, dim=1), torch.cat(ys)

x, edge_index, y = collate(train[:32])
print(x.shape, edge_index.shape, y.shape, int(edge_index.max()))
text
torch.Size([384, 1, 8, 8]) torch.Size([2, 1152]) torch.Size([384]) 383

This suits the CNN: 32 graphs of 12 nodes are just a batch of 384 images. If you forget the offset, nothing raises an error, because every index still points at a valid node. All edges simply land in the first graph.

The model: CNN encoder, graph layer, head

The encoder is an ordinary small convolutional network, the family described by LeCun and others (1998). The graph layer is a few lines.

python
class Encoder(nn.Module):
    """CNN: one image [1, 8, 8] -> one vector [d]. Runs on every node."""
    def __init__(self, d=32):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(1, 16, 3, padding=1), nn.GroupNorm(4, 16), nn.ReLU(),
            nn.Conv2d(16, 32, 3, padding=1), nn.GroupNorm(4, 32), nn.ReLU(),
            nn.MaxPool2d(2), nn.Flatten(),
            nn.Linear(32 * 4 * 4, d), nn.ReLU())

    def forward(self, x):
        return self.net(x)

class MeanLayer(nn.Module):
    """GNN: combine a node's vector with the mean of the vectors it receives."""
    def __init__(self, d_in, d_out):
        super().__init__()
        self.self_lin = nn.Linear(d_in, d_out, bias=False)
        self.nbr_lin = nn.Linear(d_in, d_out)

    def forward(self, h, edge_index):
        src, dst = edge_index
        total = torch.zeros_like(h).index_add_(0, dst, h[src])
        count = torch.bincount(dst, minlength=len(h)).clamp(min=1).unsqueeze(1)
        return self.self_lin(h) + self.nbr_lin(total / count)

class CNNGNN(nn.Module):
    def __init__(self, d=32):
        super().__init__()
        self.cnn = Encoder(d)
        self.gnn = MeanLayer(d, d)
        self.head = nn.Sequential(nn.Linear(d, d), nn.ReLU(), nn.Linear(d, 2))

    def forward(self, x, edge_index):
        h = self.cnn(x)                          # the join: [N, 1, 8, 8] -> [N, d]
        z = F.relu(self.gnn(h, edge_index))      # [N, d] + [2, E] -> [N, d]
        return self.head(z)                      # [N, 2], one prediction per node

torch.manual_seed(0)
model = CNNGNN()
h = model.cnn(x)
print(x.shape, "->", h.shape, "->", model(x, edge_index).shape)
print({name: sum(p.numel() for p in part.parameters())
       for name, part in model.named_children()})
text
torch.Size([384, 1, 8, 8]) -> torch.Size([384, 32]) -> torch.Size([384, 2])
{'cnn': 21312, 'gnn': 2080, 'head': 1122}

The join is the line h = self.cnn(x). Row i of h is node i, and edge_index refers to exactly those row numbers. Nothing else connects the two networks. If you reorder, filter or drop crops before this line, renumber the edges to match.

Written as equations, with x_i the image of node i and N(j) the set of nodes that send to node j:

text
h_i = f(x_i)                                              CNN, shared by all nodes
z_j = W_self h_j + W_nbr * mean{ h_i : i in N(j) } + b    graph layer
y_j = head( ReLU(z_j) )                                   one prediction per node

This is GraphSAGE with a mean aggregator (Hamilton and others, 2017) without its neighbour sampling and output normalisation, and an instance of the message passing scheme described by Gilmer and others (2017). A node that receives nothing gets a zero mean. One layer is enough here because the target depends only on direct sources. The encoder flattens its last feature map instead of averaging over positions, so that where a stroke sits is still visible to the linear layer.

Shapes through the CNN, the join and the graph layer

A table of shapes for a batch of 384 node images: two convolutions and a pooling step, flattening, a linear layer giving 384 vectors of 32 numbers, gathering one vector per edge, scattering back to 384 nodes and a linear output with two scores per node.

Shape propagation
step and ruleoutput shapeelements
0. input [N, C, H, W][384, 1, 8, 8]24,576
1. Conv2d(out=16, k=3, s=1, p=1)H' = ⌊(8 + 2·1 − 3) / 1⌋ + 1 = 8; W' = ⌊(8 + 2·1 − 3) / 1⌋ + 1 = 8[384, 16, 8, 8]393,216
2. Conv2d(out=32, k=3, s=1, p=1)H' = ⌊(8 + 2·1 − 3) / 1⌋ + 1 = 8; W' = ⌊(8 + 2·1 − 3) / 1⌋ + 1 = 8[384, 32, 8, 8]786,432
3. MaxPool2d(k=2, s=2, p=0)H' = ⌊(8 + 2·0 − 2) / 2⌋ + 1 = 4; W' = ⌊(8 + 2·0 − 2) / 2⌋ + 1 = 4[384, 32, 4, 4]196,608
4. flatten(start_dim=1)32 · 4 · 4 = 512; dimension 0 is kept[384, 512]196,608
5. Linear(out=32)last dimension 512 → 32[384, 32]12,288
6. x[src] (gather source nodes)one row per edge: 384 nodes → 1152 edges[1152, 32]36,864
7. aggregate messages per targetone row per target node: 1152 messages → 384 nodes[384, 32]12,288
8. Linear(out=2)last dimension 32 → 2[384, 2]768

Step 8 of 8: Linear(out=2), shape [384, 2].

Step through the layers. After the linear layer the CNN is finished and the first axis still counts nodes. The two-layer head is drawn as its final linear step. Shapes computed from the stated layer rules (the PyTorch formulas without dilation). No weights are run.

Train both networks with one loss

Nothing special is needed. One optimiser holds all parameters, and the loss is ordinary cross-entropy over nodes. The helper picks the epoch on validation data, and edge_fn lets us change the edges for the controls below.

python
def no_edges(edge_index):
    return edge_index[:, :0]                     # shape [2, 0]

def accuracy(model, graphs, edge_fn=lambda e: e):
    model.eval()
    x, edge_index, y = collate(graphs)
    with torch.no_grad():
        logits = model(x, edge_fn(edge_index))
    return (logits.argmax(1) == y).float().mean().item()

def fit(model, edge_fn=lambda e: e, seed=0, epochs=15):
    gen = torch.Generator().manual_seed(seed)
    opt = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=3e-3)
    best, best_state = 0.0, None
    for _ in range(epochs):
        model.train()
        order = torch.randperm(len(train), generator=gen).tolist()
        for start in range(0, len(train), 32):
            x, edge_index, y = collate([train[i] for i in order[start:start + 32]])
            loss = F.cross_entropy(model(x, edge_fn(edge_index)), y)
            opt.zero_grad()
            loss.backward()
            opt.step()
        score = accuracy(model, val, edge_fn)    # the epoch is chosen on validation data
        if score > best:
            best = score
            best_state = {k: v.clone() for k, v in model.state_dict().items()}
    model.load_state_dict(best_state)
    return model

A high score alone does not show that the graph did anything, or that the CNN learned anything. Four controls help, each run with three seeds:

  • the same model with no edges, which shows what each node can do alone;
  • rewired test edges: the trained model, the same images and targets, different edges;
  • a random encoder: the whole CNN, its final linear layer included, keeps its initial weights;
  • random convolutions: only the two convolution layers keep their initial weights.
python
def build(seed, freeze=None):
    torch.manual_seed(seed)
    model = CNNGNN()
    if freeze == "encoder":
        model.cnn.requires_grad_(False)          # the whole CNN stays random
    elif freeze == "convolutions":
        model.cnn.net[0].requires_grad_(False)   # only the two convolution layers
        model.cnn.net[3].requires_grad_(False)
    return model

def rewire(edge_index, seed=99):
    """Same labels, different neighbours: a test of whether the edges are used."""
    gen = torch.Generator().manual_seed(seed)
    n_graphs = edge_index.shape[1] // (N_NODES * K)
    return torch.cat([random_edges(gen) + g * N_NODES for g in range(n_graphs)], dim=1)

rows = {"CNN + GNN": [], "same model, no edges": [], "CNN + GNN, rewired test edges": [],
        "random encoder + GNN": [], "random convolutions + GNN": []}
for seed in (0, 1, 2):
    full = fit(build(seed), seed=seed)
    alone = fit(build(seed), edge_fn=no_edges, seed=seed)
    encoder_random = fit(build(seed, freeze="encoder"), seed=seed)
    convs_random = fit(build(seed, freeze="convolutions"), seed=seed)
    rows["CNN + GNN"].append(accuracy(full, test))
    rows["same model, no edges"].append(accuracy(alone, test, no_edges))
    rows["CNN + GNN, rewired test edges"].append(accuracy(full, test, rewire))
    rows["random encoder + GNN"].append(accuracy(encoder_random, test))
    rows["random convolutions + GNN"].append(accuracy(convs_random, test))
    if seed == 0:
        model = full

_, _, y_test = collate(test)
print(f"always predict the larger class: {max(y_test.float().mean(), 1 - y_test.float().mean()):.3f}")
for name, scores in rows.items():
    print(f"{name:31s}", " ".join(f"{s:.3f}" for s in scores))
text
always predict the larger class: 0.512
CNN + GNN                       0.917 0.927 0.922
same model, no edges            0.827 0.839 0.834
CNN + GNN, rewired test edges   0.809 0.816 0.812
random encoder + GNN            0.748 0.762 0.794
random convolutions + GNN       0.900 0.907 0.903

How far could a model without edges go? A node alone can only guess from its own digit: a 7 is usually larger than the average of three random digits, and a 2 usually is not. Even with perfect digit reading, expected accuracy has a ceiling, which we can compute exactly:

python
import itertools

counts = torch.bincount(digit[pools["test"]], minlength=10).double()
prob = counts / counts.sum()
best_possible = 0.0
for d in range(10):
    p_larger = sum(float(prob[a] * prob[b] * prob[c])
                   for a, b, c in itertools.product(range(10), repeat=3) if a + b + c < 3 * d)
    best_possible += float(prob[d]) * max(p_larger, 1 - p_larger)
print(f"best possible accuracy from the node's own digit: {best_possible:.3f}")
text
best possible accuracy from the node's own digit: 0.863

The joint model scores above that ceiling, so its advantage cannot come from a better CNN: it comes from information passed along edges. Rewiring the test edges drops it to about 0.81, so predictions depend on the edges you give it.

Read the two random-weight rows together. With the whole encoder random, accuracy is 0.75 to 0.79, lower than the model without edges: the encoder has to learn something. It does not follow that the filters are what matters. With only the convolutions random and the final linear layer trained, accuracy is already 0.90 to 0.91. On these 8 x 8 digits that last layer does most of the encoder's learning, and training the filters adds about two hundredths. This says nothing about larger images, and a pretrained frozen CNN would be a different starting point, which this experiment does not test.

Check that the gradient really crosses the join

A model can sit in one module and still not train end to end, for example when features are computed under torch.no_grad() or passed through .detach(). To check, take the loss of one node and see which input images receive a gradient.

python
model.eval()
x, edge_index, y = collate(test[:2])             # 2 graphs, 24 nodes
x.requires_grad_(True)
target = 0
F.cross_entropy(model(x, edge_index)[target:target + 1], y[target:target + 1]).backward()

reached = (x.grad.abs().sum(dim=(1, 2, 3)) > 0).nonzero().flatten().tolist()
sources = edge_index[0, edge_index[1] == target].tolist()
print("images with a gradient:", reached)
print("node 0 and its sources:", sorted([target] + sources))
print("first CNN filters received a gradient:",
      bool(model.cnn.net[0].weight.grad.abs().sum() > 0))
model.zero_grad()
text
images with a gradient: [0, 2, 3, 11]
node 0 and its sources: [0, 2, 3, 11]
first CNN filters received a gradient: True

The loss of node 0 reaches its own image and the images of its three sources, and no others. This is the point of training jointly: the CNN gets feedback about image 3 because node 0 needed something from it. With L graph layers, the reach extends up to L steps against the edge direction.

Normalisation can break this picture. BatchNorm computes statistics over the whole batch in training mode, so every node image influences every other one, edges or not:

python
def count_reached(norm_layer):
    torch.manual_seed(0)
    net = nn.Sequential(nn.Conv2d(1, 4, 3, padding=1), norm_layer, nn.ReLU(), nn.Flatten())
    xb = x.detach().clone().requires_grad_(True)
    net(xb)[0].sum().backward()                  # a CNN alone, output of image 0 only
    return int((xb.grad.abs().sum(dim=(1, 2, 3)) > 0).sum())

print("GroupNorm:", count_reached(nn.GroupNorm(2, 4)), "of", len(x))
print("BatchNorm in training mode:", count_reached(nn.BatchNorm2d(4)), "of", len(x))
text
GroupNorm: 1 of 24
BatchNorm in training mode: 24 of 24

BatchNorm is not wrong in a CNN-GNN, but it means that "no edges" is no longer "no communication" during training. The encoder above uses GroupNorm (Wu and He, 2018), which normalises each image on its own.

What the gradient looks like

Let δ_j = ∂L/∂z_j be the gradient at the output of the graph layer for node j. Differentiating the layer equation gives, for the CNN feature of node i:

text
∂L/∂h_i = W_self^T δ_i  +  sum over j with i in N(j) of  W_nbr^T δ_j / |N(j)|
∂L/∂θ   = sum over i of  (∂h_i/∂θ)^T ∂L/∂h_i

The first term is the node's own prediction. The second collects every node that listens to i. The CNN parameters θ are shared, so they receive the sum over all nodes. Autograd does exactly this:

python
x, edge_index, y = collate(test[:4])
x = x.double()
check = CNNGNN().double()
check.load_state_dict(model.state_dict())
h = check.cnn(x)
h.retain_grad()
z = check.gnn(h, edge_index)
z.retain_grad()
F.cross_entropy(check.head(F.relu(z)), y).backward()

src, dst = edge_index
degree = torch.bincount(dst, minlength=len(h)).double()
W_self, W_nbr = check.gnn.self_lin.weight, check.gnn.nbr_lin.weight
by_hand = z.grad @ W_self                                        # through the node itself
by_hand.index_add_(0, src, (z.grad @ W_nbr)[dst] / degree[dst, None])   # through receivers
print(torch.allclose(by_hand, h.grad))
text
True

One more test before real data

Before a full run on your own data, do one cheaper check: the model should be able to memorise a handful of graphs. If it cannot, look for a wiring or label mistake before touching hyperparameters.

python
torch.manual_seed(0)
tiny = CNNGNN()
opt = torch.optim.Adam(tiny.parameters(), lr=3e-3)
x_few, edges_few, y_few = collate(train[:4])     # 48 nodes
for step in range(200):
    loss = F.cross_entropy(tiny(x_few, edges_few), y_few)
    opt.zero_grad()
    loss.backward()
    opt.step()
print((tiny(x_few, edges_few).argmax(1) == y_few).float().mean().item())
text
1.0

Passing this test says the pieces are connected and can fit the targets. It says nothing about generalisation, which only held-out data can show.

Predictions per graph or per edge

The model above predicts one label per node. The same two networks serve other targets; only the part after the graph layer changes. Pool the nodes of each graph for one prediction per graph, or combine the two end nodes for one prediction per edge:

python
x, edge_index, y = collate(test[:4])
graph_of_node = torch.arange(4).repeat_interleave(N_NODES)    # which graph a node is in
with torch.no_grad():
    z = F.relu(model.gnn(model.cnn(x), edge_index))           # [48, 32]
    per_graph = torch.zeros(4, 32).index_add_(0, graph_of_node, z) / N_NODES
    source, destination = edge_index
    per_edge = torch.cat([z[source], z[destination]], dim=1)
print(tuple(z.shape), tuple(per_graph.shape), tuple(per_edge.shape))
print(tuple(nn.Linear(32, 5)(per_graph).shape), tuple(nn.Linear(64, 1)(per_edge).shape))
text
(48, 32) (4, 32) (144, 64)
(4, 5) (144, 1)

Targets must match: one per graph for the first head and one per edge column for the second. Concatenating source before destination keeps the direction of the edge; for an undirected relation use something symmetric, such as the elementwise product. When graphs differ in size, divide by each graph's own node count.

The same model with PyTorch Geometric

PyTorch Geometric (PyG, Fey and Lenssen, 2019) supplies graph layers, a graph data object and a loader that does the offsetting. Its SAGEConv with default settings computes the same expression as MeanLayer, so only one line of the model changes. Copying the weights proves it:

python
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
from torch_geometric.nn import SAGEConv

class CNNGNNPyG(nn.Module):
    def __init__(self, d=32):
        super().__init__()
        self.cnn = Encoder(d)
        self.gnn = SAGEConv(d, d)                # mean aggregation by default
        self.head = nn.Sequential(nn.Linear(d, d), nn.ReLU(), nn.Linear(d, 2))

    def forward(self, x, edge_index):
        return self.head(F.relu(self.gnn(self.cnn(x), edge_index)))

pyg_model = CNNGNNPyG().eval()
pyg_model.cnn.load_state_dict(model.cnn.state_dict())
pyg_model.head.load_state_dict(model.head.state_dict())
pyg_model.gnn.lin_l.load_state_dict(model.gnn.nbr_lin.state_dict())     # neighbours
pyg_model.gnn.lin_r.load_state_dict(model.gnn.self_lin.state_dict())    # the node itself

loader = DataLoader([Data(x=g["x"], edge_index=g["edge_index"], y=g["y"]) for g in test],
                    batch_size=4)
batch = next(iter(loader))
x, edge_index, y = collate(test[:4])
print(batch.x.shape, torch.equal(batch.edge_index, edge_index))
with torch.no_grad():
    print("same outputs:", torch.allclose(pyg_model(batch.x, batch.edge_index),
                                          model(x, edge_index), atol=1e-5))
text
torch.Size([48, 1, 8, 8]) True
same outputs: True

Data accepts the image tensor as node features, and the loader concatenates it along the node axis. The CNN reduces it to vectors before any PyG layer sees it, which is what the built-in layers expect.

Choose the graph layer for the question

Layers are not interchangeable. GCNConv (Kipf and Welling, 2017) is a common first choice, so here it is in the same model:

python
from torch_geometric.nn import GCNConv

class CNNGCN(CNNGNN):
    def __init__(self, d=32):
        super().__init__(d)
        self.gnn = GCNConv(d, d)

scores = []
for seed in (0, 1, 2):
    torch.manual_seed(seed)
    scores.append(accuracy(fit(CNNGCN(), seed=seed), test))
print("CNN + GCNConv:", " ".join(f"{s:.3f}" for s in scores))

mass, larger = {}, {}
for t in itertools.product(range(10), repeat=4):      # own digit, then three sources
    w = float(prob[list(t)].prod())
    key = tuple(sorted(t))
    mass[key] = mass.get(key, 0.0) + w
    larger[key] = larger.get(key, 0.0) + w * (3 * t[0] > sum(t[1:]))
ceiling = sum(max(larger[k], mass[k] - larger[k]) for k in mass)
print(f"ceiling if own and received digits cannot be told apart: {ceiling:.3f}")
text
CNN + GCNConv: 0.563 0.562 0.549
ceiling if own and received digits cannot be told apart: 0.589

It barely beats guessing, and this is not a tuning problem. GCNConv adds a self-loop and then applies one weight matrix to the node and its neighbours alike. In these graphs every node has the same number of incoming edges, so all four inputs also get the same coefficient, 1/4. The layer literally cannot know which of the four digits is its own:

python
_, edge_index, _ = collate(test[:1])
conv = GCNConv(5, 3)
h = torch.randn(12, 5)
j = int(edge_index[0, edge_index[1] == 0][0])        # one source of node 0
swapped = h.clone()
swapped[[0, j]] = h[[j, 0]]
print(torch.allclose(conv(swapped, edge_index)[0], conv(h, edge_index)[0]))
text
True

SAGEConv and MeanLayer keep a separate weight for the node itself, which a comparison needs. GCNConv is still a sensible choice where the goal is to smooth evidence over similar neighbours. The page on GCN normalisation worked by hand shows where its coefficients come from.

One image per graph: feature-map cells as nodes

When all nodes come from one picture, do not cut it up first. Run the backbone (a CNN without its classification head) once and treat each cell of its output grid as a node. The reshape is where bugs hide: move channels last before flattening the grid.

python
backbone = nn.Sequential(nn.Conv2d(3, 16, 3, stride=2, padding=1), nn.ReLU(),
                         nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU())
fmap = backbone(torch.randn(4, 3, 32, 32))                   # [B, D, h, w]
B, D, h_, w_ = fmap.shape
nodes = fmap.permute(0, 2, 3, 1).reshape(B * h_ * w_, D)     # [B*h*w, D]

def grid_edges(h, w):
    """4-neighbour grid, both directions."""
    idx = torch.arange(h * w).view(h, w)
    right = torch.stack([idx[:, :-1].flatten(), idx[:, 1:].flatten()])
    down = torch.stack([idx[:-1].flatten(), idx[1:].flatten()])
    one_way = torch.cat([right, down], dim=1)
    return torch.cat([one_way, one_way.flip(0)], dim=1)

one = grid_edges(h_, w_)
grid_index = torch.cat([one + b * h_ * w_ for b in range(B)], dim=1)
image_of_node = torch.arange(B).repeat_interleave(h_ * w_)    # the "batch" vector
print(tuple(fmap.shape), "->", tuple(nodes.shape), tuple(grid_index.shape))

b, r, c = 2, 3, 5                                             # check one position
assert torch.equal(nodes[b * h_ * w_ + r * w_ + c], fmap[b, :, r, c])
out = SAGEConv(D, D)(nodes, grid_index)
back = out.view(B, h_, w_, D).permute(0, 3, 1, 2)             # to a feature map again
assert back.shape == fmap.shape
per_image = torch.zeros(B, D).index_add_(0, image_of_node, out) / (h_ * w_)
print(tuple(back.shape), tuple(per_image.shape))
text
(4, 32, 8, 8) -> (256, 32) (2, 896)
(4, 32, 8, 8) (4, 32)

The cell in row r and column c of image b is node b*h*w + r*w + c. Keep the assert that checks one position: a wrong reshape produces the right shape with the values in the wrong nodes.

Be clear about what a grid graph adds. A mean over grid neighbours with a shared weight cannot tell left from right, which a 3 x 3 convolution can. A graph on feature-map cells becomes interesting when you add links the grid lacks, such as distant cells with similar features. If your only edges are the grid, a convolution is the simpler tool.

Keeping feature maps on the nodes

The join does not have to be a vector. Remove the flattening and each node state stays [C, h, w], with the graph layer written using 1 x 1 convolutions:

python
class MapLayer(nn.Module):
    """The same rule with 1 x 1 convolutions, so node states stay [C, H, W]."""
    def __init__(self, c_in, c_out):
        super().__init__()
        self.self_conv = nn.Conv2d(c_in, c_out, 1, bias=False)
        self.nbr_conv = nn.Conv2d(c_in, c_out, 1)

    def forward(self, h, edge_index):
        src, dst = edge_index
        total = torch.zeros_like(h).index_add_(0, dst, h[src])
        count = torch.bincount(dst, minlength=len(h)).clamp(min=1).view(-1, 1, 1, 1)
        return self.self_conv(h) + self.nbr_conv(total / count)

class CNNMapGNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.cnn = nn.Sequential(                # stops at a map: [N, 32, 4, 4]
            nn.Conv2d(1, 16, 3, padding=1), nn.GroupNorm(4, 16), nn.ReLU(),
            nn.Conv2d(16, 32, 3, padding=1), nn.GroupNorm(4, 32), nn.ReLU(),
            nn.MaxPool2d(2))
        self.gnn = MapLayer(32, 32)
        self.head = nn.Sequential(nn.Flatten(), nn.Linear(32 * 4 * 4, 32), nn.ReLU(),
                                  nn.Linear(32, 2))

    def forward(self, x, edge_index):
        return self.head(F.relu(self.gnn(self.cnn(x), edge_index)))

class CNNFlatGNN(CNNGNN):
    """Control: vectors on the nodes, averaged before any dense layer has read a digit."""
    def __init__(self):
        super().__init__()
        self.cnn = self.cnn.net[:8]              # stop after Flatten: [N, 512]
        self.gnn = MeanLayer(512, 32)

for name, make in [("maps on the nodes", CNNMapGNN), ("flattened, then averaged", CNNFlatGNN)]:
    scores = []
    for seed in (0, 1, 2):
        torch.manual_seed(seed)
        scores.append(accuracy(fit(make(), seed=seed), test))
    print(f"{name:25s}", " ".join(f"{s:.3f}" for s in scores))
print("numbers per map message:", 32 * 4 * 4, "instead of", 32)
text
maps on the nodes         0.902 0.906 0.900
flattened, then averaged  0.911 0.906 0.908
numbers per map message: 512 instead of 32

On this task the map version scores a little lower than the vector version (0.90 to 0.91 against 0.92 to 0.93), with messages 16 times larger. The control suggests why. It keeps vectors on the nodes but removes the encoder's final linear layer, so the flattened convolution output is averaged over neighbours before any dense layer has combined its positions, and it lands near the map version, at 0.91, despite having more parameters than the first model. In the first model a linear layer and ReLU summarise each digit before the averaging; in the other two, three different digits are mixed first. On this one small task, then, the gap appears to come from that order of operations more than from the map shape itself. Keeping maps is an option for tasks where corresponding positions inside nodes should be combined, not an upgrade by default.

You do not have to write the layer yourself. TGraphX, a library maintained by the author of this site, ships tensor layers for [C, H, W] node features. With copied weights its TensorGraphSAGELayer computes the same output as MapLayer, up to rounding:

python
import tgraphx as tgx

x, edge_index, _ = collate(test[:2])
torch.manual_seed(0)
maps = torch.randn(len(x), 8, 4, 4)
layer = MapLayer(8, 8)
ready = tgx.TensorGraphSAGELayer(8, 8)            # 1 x 1 convolutions, mean aggregation
with torch.no_grad():
    ready.W_self.weight.copy_(layer.self_conv.weight)
    ready.W_self.bias.copy_(layer.nbr_conv.bias)  # it keeps the bias on the self path
    ready.W_neigh.weight.copy_(layer.nbr_conv.weight)
    print(torch.allclose(ready(maps, edge_index), layer(maps, edge_index), atol=1e-6))
text
True

Its limits: the 1 x 1 convolutions never mix positions, all nodes need the same shape, and it is only a layer, so the encoder, the edges and the training loop remain yours. PyTorch Geometric can express the same operation with a custom message passing class. The shapes each TGraphX layer accepts are listed separately. The TGraphX preprint (Sajjadi and Eramian, 2025) proposes this family of designs: CNN-produced multi-dimensional node features, message passing with 1 x 1 convolutions and a CNN aggregator.

Using a pretrained backbone

For photographs you would normally start from a pretrained CNN. Replace its classification layer, check the feature width, and give it a smaller learning rate than the new graph layers.

python
from torchvision.models import resnet18

backbone = resnet18(weights=None)                 # real use: weights="DEFAULT" (downloads)
backbone.fc = nn.Identity()                       # output [N, 512]
graph_part = SAGEConv(512, 64)
optimizer = torch.optim.AdamW([
    {"params": backbone.parameters(), "lr": 1e-5},     # gentle on pretrained filters
    {"params": graph_part.parameters(), "lr": 1e-3},
])
crops = torch.randn(10, 3, 64, 64)
print(tuple(graph_part(backbone(crops), torch.tensor([[0, 1], [1, 2]])).shape))

backbone.requires_grad_(False).eval()             # frozen: BatchNorm statistics fixed too
with torch.no_grad():
    cached = backbone(crops)                      # compute once, then train the GNN on it
print(tuple(cached.shape))
text
(10, 64)
(10, 512)

Freezing and caching is not end-to-end training, but it is a cheap first experiment: it shows whether the relations add anything on top of those features. A negative result does not rule out that fine-tuned features would. Remember that model.train() switches BatchNorm back to training mode, so call backbone.eval() again after it if the backbone should stay fixed. Pretrained weights also expect the input normalisation they were trained with.

Moving to your own data

Four things change, in this order. First, the node images: decide the crop or cell, resize to one shape and normalise as your CNN expects. Second, the edges: write the function that builds them from information you have at prediction time, and check a few graphs by eye. Third, the target and head: node, edge or graph, as above. Fourth, the split: group by source before building graphs. Only then tune widths and depth. Keep the no-edge control in your training script from the start, because it is the cheapest way to learn whether the relations carry anything.

Cost and practical limits

  • The CNN runs once per node in the first wiring. A batch of 32 images cut into 196 crops each is 6,272 CNN inputs, and their activations are kept for the backward pass. Use smaller crops or batches, freeze and cache, apply gradient checkpointing, or sample neighbourhoods; see mini-batch sampling methods.
  • One CNN pass per image in the feature-map wiring is much cheaper, but all nodes share the backbone's resolution.
  • Depth. Each graph layer extends the reach by one step, and stacking many tends to make node features alike. Start with one to three and compare.
  • Splits. Crops, patches or frames from one source must stay in the same split. Otherwise the test score partly measures memory.
  • Explanations. To see which nodes or features a prediction used, gradient-based methods apply to the vector features; see saliency and integrated gradients.

When not to combine them

Here is an uncomfortable control. Suppose you do have a digit label for every image, and you know the rule. Then train the CNN to read digits and write the comparison yourself:

python
for seed in (0, 1, 2):
    torch.manual_seed(seed)
    reader = nn.Sequential(Encoder(), nn.Linear(32, 10))     # trained on digit labels
    opt = torch.optim.Adam(reader.parameters(), lr=3e-3)
    gen = torch.Generator().manual_seed(seed)
    for _ in range(30):
        order = pools["train"][torch.randperm(len(pools["train"]), generator=gen)]
        for ids in order.split(64):
            loss = F.cross_entropy(reader(images[ids]), digit[ids])
            opt.zero_grad()
            loss.backward()
            opt.step()
    x, edge_index, y = collate(test)
    with torch.no_grad():
        read = reader(x).argmax(1).float()                   # predicted digit per node
    src, dst = edge_index
    neighbour_sum = torch.zeros(len(read)).index_add_(0, dst, read[src])
    rule = (read * K > neighbour_sum).long()                 # the rule, written by hand
    print(f"seed {seed}: read digits, then compare: {(rule == y).float().mean():.3f}")
text
seed 0: read digits, then compare: 0.986
seed 1: read digits, then compare: 0.986
seed 2: read digits, then compare: 0.987

Two plain steps beat the joint model, 0.99 against 0.92. What the CNN-GNN offered was learning without digit labels and without being told the rule, from yes-or-no targets alone. If you have both, use them. More generally, skip the graph when nothing relates your items, when the only relation is the pixel grid of one image, or when "combining" just means averaging the predictions for repeated views of one object.

Do you need a CNN and a GNN trained together?

Four questions about whether items depend on each other, where relations come from, whether per item labels exist and whether the combining rule is known, leading to five possible designs with a reason and a caveat for each.

Questions
questionyour answer
Q1Does the answer for one item depend on other items?Options: yes, no, not surenot answered
Q2Which relations do you mean?Options: pixel positions in one image, links between items or regionsnot answered
Q3Do you have a label for each item or crop?Options: yes, nonot answered
Q4Can you write down how related items combine?Options: yes, nonot answered

No rule is met yet. Still open: 5 of 5.

All rules, outcomes in alphabetical order
outcome and rulereason and caveat
A CNN on its ownWhen Q1 is no.Now: open: answer Q1No other item carries information about the answer, so there is nothing to pass along edges.Caveat: Confirm by training the same model with and without edges.
CNN and GNN trained togetherWhen Q1 is yes or not sure, and Q2 is links between items or regions, and Q3 is no.Now: open: answer Q1, Q2, Q3Only targets about related items exist. Joint training lets image features adapt to them; frozen pretrained features are a cheaper thing to try first.Caveat: Needs edges at prediction time and more memory than a CNN alone.
Convolutions or attention over one imageWhen Q1 is yes or not sure, and Q2 is pixel positions in one image.Now: open: answer Q1, Q2Stacked convolutions and attention layers already combine positions of a single image.Caveat: A graph can still help if you add links that the grid does not have.
Frozen CNN features, then a GNNWhen Q1 is yes or not sure, and Q2 is links between items or regions, and Q3 is yes, and Q4 is no.Now: open: answer Q1, Q2, Q3, Q4Features learned from item labels are cached and only the small graph model learns relations.Caveat: The frozen features may not hold what the relation needs.
Per item CNN, then your ruleWhen Q1 is yes or not sure, and Q2 is links between items or regions, and Q3 is yes, and Q4 is yes.Now: open: answer Q1, Q2, Q3, Q4Item labels train the CNN directly and a known relation does not have to be learned.Caveat: Errors of the CNN pass straight into the rule.

0 of 4 questions answered. No rule is met yet. Still open: 5 of 5.

Answer all four questions to see which rule is met. These are rules of thumb to test against a baseline, not guarantees. A rule table written by the author: not a measurement, a benchmark or a guarantee that a choice works. An outcome is listed when your answers meet its rule. Outcomes are in alphabetical order, which carries no ranking.

Common mistakes

  • CNN features computed without gradients. The graph part trains, the CNN stays where it started. Run the gradient check above.
  • Edge indices not shifted when batching. No error is raised.
  • Flattening a feature map without permute. The shape is right and the nodes are scrambled.
  • Edges built from labels or from information unavailable at prediction time.
  • A weaker baseline. Give the model without a graph the same encoder and the same training budget.
  • Node order that drifts. Sorting boxes, dropping small crops or shuffling files after the edges were built silently rewires the graph. Carry an explicit id with each crop and build edge_index from the final order.
  • One lucky seed. Across the three seeds above, one configuration (the random encoder) moves by almost five hundredths; repeat before concluding.

If you mostly work in PyG and want tensor layers beside it, see using TGraphX and PyTorch Geometric together.

References

  1. Y. LeCun, L. Bottou, Y. Bengio and P. Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE, 1998. doi.org/10.1109/5.726791
  2. J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals and G. E. Dahl. "Neural Message Passing for Quantum Chemistry." 2017. arXiv:1704.01212
  3. W. L. Hamilton, R. Ying and J. Leskovec. "Inductive Representation Learning on Large Graphs." 2017. arXiv:1706.02216
  4. T. N. Kipf and M. Welling. "Semi-Supervised Classification with Graph Convolutional Networks." ICLR, 2017. arXiv:1609.02907
  5. Y. Wu and K. He. "Group Normalization." 2018. arXiv:1803.08494
  6. M. Fey and J. E. Lenssen. "Fast Graph Representation Learning with PyTorch Geometric." 2019. arXiv:1903.02428
  7. PyTorch Geometric documentation, SAGEConv and Creating Message Passing Networks.
  8. scikit-learn documentation, load_digits.
  9. A. Sajjadi and M. Eramian. "TGraphX: Tensor-Aware Graph Neural Network for Multi-Dimensional Feature Learning." 2025. arXiv:2504.03953