TGraphX › Insights › Multidimensional Node Features in PyTorch Geometric
← Back to Insights

Multidimensional Node Features in PyTorch Geometric

Topic: Shape validation, testing and debugging

PyTorch Geometric (PyG; Fey and Lenssen, 2019) does accept node features with more than two dimensions: a Data object holds an x of shape [N, C, H, W] and batching concatenates it along the node axis. The catch is in the layers. Many built-in convolutions treat the second-to-last axis as the node axis, so on an image-valued x they raise an error or, worse, run along the wrong axis. For tensor messages, write a MessagePassing subclass with node_dim=0, reuse one of the few built-ins that can be configured that way, or flatten on purpose.

All code below runs on a CPU with PyTorch 2.15 and PyG 2.8.1 (one section also uses TGraphX 1.5.1), and the blocks share one namespace. Behaviour of individual layers can change between releases, so rerun the survey block on your version.

What Data and the loader accept

Take five nodes, each holding a feature map with 3 channels, 8 rows and 6 columns, and six directed edges. Row 0 of edge_index is the source and row 1 the destination.

python
import torch
import torch.nn as nn
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader

torch.manual_seed(0)
N, C, H, W = 5, 3, 8, 6
x = torch.randn(N, C, H, W)
edge_index = torch.tensor([[0, 1, 2, 3, 4, 0],      # source
                           [1, 2, 3, 4, 0, 2]])     # destination
data = Data(x=x, edge_index=edge_index)
print(data)
print("valid:", data.validate(), "| nodes:", data.num_nodes,
      "| num_node_features:", data.num_node_features)

batch = next(iter(DataLoader([data, data], batch_size=2)))
print(batch.x.shape, batch.edge_index.shape, batch.batch.tolist())
text
Data(x=[5, 3, 8, 6], edge_index=[2, 6])
valid: True | nodes: 5 | num_node_features: 6
torch.Size([10, 3, 8, 6]) torch.Size([2, 12]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Storage and batching work: the loader stacks along the first axis and shifts the edge indices of the second graph. One property is already a warning. num_node_features returns 6, the size of the last axis, which here is the image width. Do not use it to size a layer; use x.size(1) for channels.

Batching also requires every node, in every graph, to have the same C, H and W:

python
other = Data(x=torch.randn(2, 3, 4, 4), edge_index=torch.tensor([[0], [1]]))
try:
    next(iter(DataLoader([data, other], batch_size=2)))
except RuntimeError as error:
    print(str(error).split(". ")[0])
text
Sizes of tensors must match except in dimension 0

Resize or pool every node to one shape first, for example with nn.AdaptiveAvgPool2d. Resizing changes the physical meaning of a pixel when crops come from objects of very different sizes, so if size matters to your task, keep it as a separate attribute.

Why built-in layers misread an image-valued x

PyG's MessagePassing base class has an argument node_dim, "the axis along which to propagate", and its default is -2. That choice supports what PyG calls static graphs: an x of shape [batch, nodes, features] on one shared graph. A four-dimensional tensor is read the same way. In [N, C, H, W], axis -2 is the height, and the last axis, the width, is taken as the feature vector.

So a layer sized to the width runs, and quietly does something you did not ask for:

python
from torch_geometric.nn import GCNConv

conv = GCNConv(W, 4)
out = conv(x, edge_index)
print(out.shape)

# Treat every (node, channel) slice as a separate graph with H "nodes" of W features.
as_rows = torch.stack([torch.stack([conv(x[n, c], edge_index) for c in range(C)])
                       for n in range(N)])
print("identical:", torch.allclose(out, as_rows, atol=1e-6))
text
torch.Size([5, 3, 8, 4])
identical: True

The edges connected rows of each feature map. Node 0 never exchanged anything with node 1. There is no error because the edge indices 0 to 4 happen to be valid row numbers among 8 rows. With more nodes than rows you get an index error instead, which is the lucky case:

python
from torch_geometric.nn import SAGEConv

many = torch.randn(40, C, H, W)
edges_40 = torch.randint(0, 40, (2, 90))
try:
    SAGEConv(W, 4)(many, edges_40)
except IndexError as error:
    print(str(error).split(". ")[0])
text
Found indices in 'edge_index' that are larger than 7 (got 39)

A survey of what happens with defaults

Rather than trusting a table from memory, run the layers. This block calls each one with default arguments on the five-node example, sizing it once with the channel count and once with the width.

python
from torch_geometric import nn as gnn

layers = {
    "GCNConv": lambda d: gnn.GCNConv(d, 4),
    "SAGEConv": lambda d: gnn.SAGEConv(d, 4),
    "GraphConv": lambda d: gnn.GraphConv(d, 4),
    "ChebConv": lambda d: gnn.ChebConv(d, 4, K=2),
    "GATConv": lambda d: gnn.GATConv(d, 4),
    "GATv2Conv": lambda d: gnn.GATv2Conv(d, 4),
    "TransformerConv": lambda d: gnn.TransformerConv(d, 4),
}

def outcome(layer):
    try:
        return f"runs {list(layer(x, edge_index).shape)}"
    except Exception as error:
        return type(error).__name__

print(f"{'layer':16s}{'in_channels = C':22s}in_channels = W")
for name, make in layers.items():
    print(f"{name:16s}{outcome(make(C)):22s}{outcome(make(W))}")
text
layer           in_channels = C       in_channels = W
GCNConv         RuntimeError          runs [5, 3, 8, 4]
SAGEConv        RuntimeError          runs [5, 3, 8, 4]
GraphConv       RuntimeError          runs [5, 3, 8, 4]
ChebConv        RuntimeError          runs [5, 3, 8, 4]
GATConv         AssertionError        AssertionError
GATv2Conv       AssertionError        AssertionError
TransformerConv RuntimeError          RuntimeError

Two patterns appear. Layers that apply a linear map to the last axis raise a shape error when sized to C and run on the wrong axes when sized to W. GATConv, GATv2Conv and TransformerConv set node_dim=0 themselves and expect a vector per node, so they refuse in both cases. None of these is a bug: each layer is defined for feature vectors.

Shapes inside a tensor message passing layer

A table of shapes: five node feature maps with three channels are gathered for six edges, concatenated to six channels, reduced to four channels by a one by one convolution, aggregated back to five nodes and averaged over positions.

Shape propagation
step and ruleoutput shapeelements
0. input [N, C, H, W][5, 3, 8, 6]720
1. x[src] (gather source nodes)one row per edge: 5 nodes → 6 edges[6, 3, 8, 6]864
2. cat of 2 tensors, dim=12 tensors joined along dimension 1: 3·2[6, 6, 8, 6]1,728
3. Conv2d(out=4, k=1, s=1, p=0)H' = ⌊(8 + 2·0 − 1) / 1⌋ + 1 = 8; W' = ⌊(6 + 2·0 − 1) / 1⌋ + 1 = 6[6, 4, 8, 6]1,152
4. aggregate messages per targetone row per target node: 6 messages → 5 nodes[5, 4, 8, 6]960
5. x.mean(dim=(2, 3))mean over H and W[5, 4]20

Step 5 of 5: x.mean(dim=(2, 3)), shape [5, 4].

Step through one layer on the five node example: gather per edge, concatenate sources and destinations, convolve, send back to nodes. Shapes computed from the stated layer rules (the PyTorch formulas without dilation). No weights are run.

A MessagePassing layer for feature maps

The fix is to say where the nodes are, with node_dim=0, and to supply a message function that understands [E, C, H, W]. In PyG's naming, x_j is the source of each edge and x_i the destination (under the default flow="source_to_target"), so i is the receiving node. Some texts use the letters the other way round, so check which node a formula updates before copying it.

python
from torch import Tensor
from torch_geometric.nn import MessagePassing
from torch_geometric.typing import OptTensor

class ImageConv(MessagePassing):
    propagate_type = {"x": Tensor, "edge_weight": OptTensor}    # see the note below

    def __init__(self, in_channels, out_channels):
        super().__init__(aggr="mean", node_dim=0)        # nodes are the FIRST axis
        self.message_conv = nn.Conv2d(2 * in_channels, out_channels, kernel_size=1)
        self.self_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)

    def forward(self, x, edge_index, edge_weight=None):
        aggregated = self.propagate(edge_index, x=x, edge_weight=edge_weight)
        return aggregated + self.self_conv(x)

    def message(self, x_i, x_j, edge_weight):
        pair = torch.cat([x_i, x_j], dim=1)              # concatenate CHANNELS
        message = self.message_conv(pair)                # [E, C_out, H, W]
        if edge_weight is not None:
            message = message * edge_weight.view(-1, 1, 1, 1)
        return message

torch.manual_seed(0)
layer = ImageConv(C, 4)
print(layer(x, edge_index).shape)
text
torch.Size([5, 4, 8, 6])

A note on propagate_type: PyG normally reads your class source to learn which arguments propagate takes, so in an ordinary script the line is not needed. Some code-running tools create the class with exec inside their own program. In that situation we saw Python 3.13 hand PyG lines from the tool's file instead of the class, and the call failed with propagate() got an unexpected keyword argument 'x'. Declaring the types avoids that.

For destination node i with incoming sources N(i), and * meaning convolution, the layer computes:

text
x'_i = W_self * x_i + b_self + mean over j in N(i) of ( W_msg * [x_i || x_j] + b_msg )

Three details matter. torch.cat(..., dim=1) joins channels; the habit of writing dim=-1 from vector code would join image widths. edge_weight has shape [E] and must be reshaped to [E, 1, 1, 1], otherwise broadcasting lines it up with the width. And a 1 x 1 kernel keeps positions separate: pixel (r, c) of a message depends only on pixel (r, c) of the two nodes. Use kernel_size=3, padding=1 if messages should look at neighbouring pixels.

Verify it against a loop

A tensor layer that runs is not necessarily right. Compare it with the formula written out edge by edge:

python
source, destination = edge_index
expected = []
for node in range(N):
    incoming = (destination == node).nonzero().flatten()
    total = torch.zeros(4, H, W)
    for edge in incoming:
        pair = torch.cat([x[node], x[source[edge]]]).unsqueeze(0)
        total += layer.message_conv(pair)[0]
    expected.append(total / max(len(incoming), 1) + layer.self_conv(x[node : node + 1])[0])

print("matches the loop:", torch.allclose(layer(x, edge_index), torch.stack(expected), atol=1e-6))

second = Data(x=torch.randn(4, C, H, W), edge_index=torch.tensor([[0, 1, 2], [3, 3, 0]]))
batch = next(iter(DataLoader([data, second], batch_size=2)))
separate = torch.cat([layer(data.x, data.edge_index), layer(second.x, second.edge_index)])
print("batched equals one by one:",
      torch.allclose(layer(batch.x, batch.edge_index), separate, atol=1e-6))
text
matches the loop: True
batched equals one by one: True

A node with no incoming edges receives an aggregate of zeros, so its output is the self term alone.

What propagate does here

With node_dim=0 there is no magic left. propagate selects rows of x by edge index to build x_j and x_i, calls your message, and aggregates the results by destination along the same axis. The whole layer in plain PyTorch:

python
x_j, x_i = x[source], x[destination]                      # gather along the node axis
messages = layer.message_conv(torch.cat([x_i, x_j], dim=1))
total = torch.zeros(N, 4, H, W).index_add_(0, destination, messages)
count = torch.bincount(destination, minlength=N).clamp(min=1).view(-1, 1, 1, 1)
plain = total / count + layer.self_conv(x)
print(torch.allclose(plain, layer(x, edge_index), atol=1e-6))
text
True

What PyG adds is the plumbing around this: other aggregators, argument collection, hooks and sparse adjacency support. aggr="sum", "mean" and "max" all act separately on every channel and pixel. With max, neighbouring pixels of one output map may therefore come from different source nodes, which is worth knowing before you interpret such a map.

A complete model around the layer

Two such layers, a spatial mean, graph pooling and a linear head make a graph classifier. batch is the vector PyG's loader builds.

python
from torch_geometric.nn import global_mean_pool

class ImageGraphClassifier(nn.Module):
    def __init__(self, in_channels, hidden, classes):
        super().__init__()
        self.conv1 = ImageConv(in_channels, hidden)
        self.conv2 = ImageConv(hidden, hidden)
        self.head = nn.Linear(hidden, classes)

    def forward(self, x, edge_index, batch):
        x = self.conv1(x, edge_index).relu()
        x = self.conv2(x, edge_index).relu()             # still [N, hidden, H, W]
        nodes = x.mean(dim=(2, 3))                       # [N, hidden]
        return self.head(global_mean_pool(nodes, batch))

graphs = [Data(x=torch.randn(N, C, H, W), edge_index=edge_index, y=torch.tensor([label]))
          for label in (0, 1, 1, 0)]
batch = next(iter(DataLoader(graphs, batch_size=4)))
torch.manual_seed(0)
classifier = ImageGraphClassifier(C, 8, 2)
logits = classifier(batch.x, batch.edge_index, batch.batch)
nn.functional.cross_entropy(logits, batch.y).backward()
print(tuple(logits.shape), tuple(batch.y.shape))
print("every parameter has a gradient:",
      all(p.grad is not None for p in classifier.parameters()))
text
(4, 2) (4,)
every parameter has a gradient: True

The spatial dimensions survive both graph layers and are reduced once, just before the head. Where you place that reduction is a design choice: earlier saves memory on every later edge, later keeps positions available to more of the message passing. This block checks shapes and gradient flow on random numbers; it demonstrates nothing about accuracy.

Adding one attention weight per edge

Attention over feature maps needs a decision: one weight per edge, per channel, or per pixel. The cheapest is one weight per edge, scored from spatially averaged features and normalised over the edges entering each node with torch_geometric.utils.softmax:

python
from torch_geometric.utils import softmax

class ImageAttentionConv(MessagePassing):
    propagate_type = {"x": Tensor, "s": Tensor}

    def __init__(self, in_channels, out_channels):
        super().__init__(aggr="sum", node_dim=0)
        self.value = nn.Conv2d(in_channels, out_channels, 1)
        self.score = nn.Linear(2 * in_channels, 1)

    def forward(self, x, edge_index):
        summary = x.mean(dim=(2, 3))                       # [N, C], one vector per node
        return self.propagate(edge_index, x=x, s=summary)

    def message(self, x_j, s_i, s_j, index, size_i):
        logit = self.score(torch.cat([s_i, s_j], dim=1)).squeeze(1)    # [E]
        self.alpha = softmax(logit, index, num_nodes=size_i)           # over incoming edges
        return self.alpha.view(-1, 1, 1, 1) * self.value(x_j)

attention = ImageAttentionConv(C, 4)
print(attention(x, edge_index).shape)
totals = torch.zeros(N).index_add_(0, edge_index[1], attention.alpha.detach())
print([round(v, 3) for v in totals.tolist()])
text
torch.Size([5, 4, 8, 6])
[1.0, 1.0, 1.0, 1.0, 1.0]

The attention is the same for every pixel of a message. Per-pixel attention is possible, with scores of shape [E, 1, H, W], at more memory and with the assumption that pixel positions correspond between nodes.

Tensor edge features and a second image attribute

The same storage rules apply to edges. edge_attr may be [E, C_e, H, W], for example a difference map or an overlap mask per pair of crops. And nothing forces images into x: you can keep vectors there and put maps in an attribute of your own. The loader concatenates both along the first axis.

python
pairs = torch.randn(edge_index.size(1), 2, H, W)           # one 2-channel map per edge
both = Data(x=torch.randn(N, 16), patch=torch.randn(N, C, H, W),
            edge_index=edge_index, edge_attr=pairs)
joined = next(iter(DataLoader([both, both], batch_size=2)))
print(tuple(joined.x.shape), tuple(joined.patch.shape), tuple(joined.edge_attr.shape))

class EdgeImageConv(MessagePassing):
    propagate_type = {"x": Tensor, "edge_attr": Tensor}

    def __init__(self, node_channels, edge_channels, out_channels):
        super().__init__(aggr="sum", node_dim=0)
        self.conv = nn.Conv2d(node_channels + edge_channels, out_channels, 1)

    def forward(self, x, edge_index, edge_attr):
        return self.propagate(edge_index, x=x, edge_attr=edge_attr)

    def message(self, x_j, edge_attr):
        return self.conv(torch.cat([x_j, edge_attr], dim=1))

edge_layer = EdgeImageConv(C, 2, 4)
print(tuple(edge_layer(joined.patch, joined.edge_index, joined.edge_attr).shape))
text
(10, 16) (10, 3, 8, 6) (12, 2, 8, 6)
(10, 4, 8, 6)

Graph transforms treat the edge tensor as an opaque payload. ToUndirected, for instance, gives each added reverse edge a copy of the forward map:

python
from torch_geometric.transforms import ToUndirected

two_way = ToUndirected()(both.clone())
source, destination = two_way.edge_index
forward_edge = ((source == 0) & (destination == 1)).nonzero().item()
reverse_edge = ((source == 1) & (destination == 0)).nonzero().item()
print(tuple(two_way.edge_attr.shape),
      torch.equal(two_way.edge_attr[forward_edge], two_way.edge_attr[reverse_edge]))
text
(12, 2, 8, 6) True

If the map describes direction, such as "destination minus source" or a relative offset, a copy is wrong for the reverse edge. Build both directions yourself in that case. Note also that where both directions are already listed, ToUndirected merges the duplicates and by default adds their maps together.

Built-ins you can reuse, and one to avoid

SimpleConv (aggregation without weights) and GINConv (from Xu and others, 2018; it takes any module for its update) work on feature maps once you pass node_dim=0:

python
mean_of_sources = gnn.SimpleConv(aggr="mean", node_dim=0)(x, edge_index)

update = nn.Conv2d(C, 4, 1)
gin = gnn.GINConv(update, node_dim=0)
sum_of_sources = gnn.SimpleConv(aggr="sum", node_dim=0)(x, edge_index)
print(torch.allclose(gin(x, edge_index), update(x + sum_of_sources), atol=1e-6))

silent = gnn.GINConv(update)(x, edge_index)          # node_dim forgotten
print(silent.shape, "same result:", torch.allclose(silent, gin(x, edge_index)))
text
True
torch.Size([5, 4, 8, 6]) same result: False

Look at the last two lines. Without node_dim=0, GINConv with a convolution returns an output of the expected shape and the wrong values. This is the easiest mistake to ship.

EdgeConv, the layer of Wang and others (2018), is a trap in a different way. Its message is built with torch.cat([x_i, x_j - x_i], dim=-1), which for vectors joins features and for images joins widths:

python
edge_conv = gnn.EdgeConv(nn.Conv2d(C, 4, 1), node_dim=0)
print(edge_conv(x, edge_index).shape)
text
torch.Size([5, 4, 8, 12])

The output is twice as wide and nothing complained. For an edge convolution on feature maps, write the message yourself with dim=1.

Pooling and normalisation

Graph pooling has the same axis convention. global_mean_pool reduces axis -2 of a tensor with two or more dimensions, which is again the height. Name the node axis instead:

python
from torch_geometric.nn.aggr import MeanAggregation

batch_vector = torch.tensor([0, 0, 0, 1, 1])
try:
    gnn.global_mean_pool(x, batch_vector)
except RuntimeError:
    print("global_mean_pool: RuntimeError")

print(MeanAggregation()(x, batch_vector, dim=0).shape)          # [graphs, C, H, W]
print(gnn.global_mean_pool(x.mean(dim=(2, 3)), batch_vector).shape)   # [graphs, C]
text
global_mean_pool: RuntimeError
torch.Size([2, 3, 8, 6])
torch.Size([2, 3])

If the number of nodes happens to equal the height, global_mean_pool(x, batch_vector) does not even raise: it pools rows and returns a plausible tensor. The second line keeps spatial maps per graph; the third averages positions first and is what a classifier head usually needs.

For normalisation, PyG's BatchNorm expects two- or three-dimensional input and rejects [N, C, H, W]. PyTorch's nn.BatchNorm2d and nn.GroupNorm accept it directly, with nodes in the role of the image batch. Remember that BatchNorm2d then mixes statistics across all nodes in a training batch.

Other utilities: check which axis they touch

Utilities that select nodes index the first axis and behave as you would expect. Utilities that transform feature values usually work on the last axis:

python
from torch_geometric.transforms import NormalizeFeatures

small = data.subgraph(torch.tensor([0, 1, 2]))
print(small)

positive = Data(x=torch.rand(N, C, H, W), edge_index=edge_index)
normalised = NormalizeFeatures()(positive)
row_sums = normalised.x.sum(dim=-1)                  # one number per node, channel, row
print(round(row_sums.min().item(), 3), round(row_sums.max().item(), 3))
text
Data(x=[3, 3, 8, 6], edge_index=[2, 3])
1.0 1.0

NormalizeFeatures is documented as row normalisation. In 2.8.1 it subtracts the smallest value in x and divides each last-axis row by its sum (a row summing to less than 1 is left unscaled), so here it rescaled every image row to sum to one. For images, normalise per channel with statistics computed on the training nodes, as you would for a CNN.

Or flatten, deliberately

Flattening is a legitimate choice, and it is reversible: x.flatten(1).view(-1, C, H, W) returns the original tensor. Every built-in layer then applies.

python
flat = x.flatten(1)                                      # [N, C*H*W]
print(flat.shape, torch.equal(flat.view(-1, C, H, W), x))

def count(module):
    return sum(p.numel() for p in module.parameters())

print("SAGEConv on flat vectors:", count(SAGEConv(C * H * W, 4 * H * W)))
print("ImageConv with 1 x 1 kernels:", count(ImageConv(C, 4)))
text
torch.Size([5, 144]) True
SAGEConv on flat vectors: 55488
ImageConv with 1 x 1 kernels: 44

What changes is the computation. A linear layer on the flat vector gives every output pixel its own weights to every input pixel: it can express more relations between positions, and its parameter count grows with the image size. A convolutional message shares weights over positions and assumes that nearby pixels and matching positions mean something. Which suits your data is an empirical question. If positions inside a node do not matter, pooling each map to a vector before the graph layers is smaller than either.

Ready-made tensor layers from TGraphX

TGraphX, a library maintained by the author of this site, provides graph layers that expect [N, C, H, W], and they can be called on a PyG Data object's tensors directly. They are not magic: TensorGraphSAGELayer is two 1 x 1 convolutions and a mean, which you can reproduce with PyG in two lines.

python
import tgraphx as tgx

torch.manual_seed(0)
ready = tgx.TensorGraphSAGELayer(C, 4)

def same_with_pyg(x, edge_index):
    neighbours = gnn.SimpleConv(aggr="mean", node_dim=0)(x, edge_index)
    return ready.W_self(x) + ready.W_neigh(neighbours)     # reuse the same weights

print(ready(data.x, data.edge_index).shape)
print(torch.allclose(ready(data.x, data.edge_index),
                     same_with_pyg(data.x, data.edge_index), atol=1e-6))
text
torch.Size([5, 4, 8, 6])
True

TGraphX also has tensor attention, GIN and convolutional message passing layers. The SAGE, GAT and GIN layers check the rank of x and say what shape they expected. The limits are real: a far smaller catalogue than PyG, one per-node shape per batch, 1 x 1 convolutions in the SAGE, GAT and GIN variants, and no built-in message-passing layer that models a time axis inside the node tensor. If one custom class covers your need, it is a perfectly good solution. The two libraries can also be used side by side, and the accepted shapes per TGraphX layer are listed separately. If you use its converters instead of passing tensors, note that split masks are not copied.

Count the memory before training

Message passing builds one message per edge, each the size of a feature map. For float32, a single layer's message buffer is E * C_out * H * W * 4 bytes:

python
for edges, channels, side in [(10_000, 64, 8), (10_000, 64, 32), (100_000, 64, 8)]:
    mib = edges * channels * side * side * 4 / 2**20
    print(f"E={edges:>7,d}  C={channels}  {side}x{side}:  {mib:8.0f} MiB")
text
E= 10,000  C=64  8x8:       156 MiB
E= 10,000  C=64  32x32:      2500 MiB
E=100,000  C=64  8x8:      1562 MiB

This counts one buffer of one layer. The gathered inputs x_i and x_j, each [E, C_in, H, W], activations saved for the backward pass and optimiser states come on top, so treat it as a lower bound. The practical levers are fewer edges, smaller maps and fewer channels.

Which route to take

Your situation Reasonable route
Positions inside a node do not matter to the relation Pool each node to a vector, use any PyG layer
You want every position to interact with every other Flatten, and watch the parameter count
Matching positions should be combined node_dim=0 with convolutional messages
A plain mean or GIN-style update is enough SimpleConv or GINConv with node_dim=0
You prefer prepared tensor layers A library that provides them, then check its limits

Whichever route you take, keep the loop comparison from above as a unit test. Choose sizes that are all different, the number of edges included, because two equal sizes let an operation on the wrong axis still fit. The example on this page falls short in one place: it has 6 edges and width 6, so an edge_weight of shape [E] that was never reshaped would multiply along the width without any error. In your test use another edge count, add a node without incoming edges and a batch of two unequal graphs, and run it again after every library upgrade.

Common mistakes

  • Sizing a layer from data.num_node_features, which is the last axis.
  • Applying vector transforms such as NormalizeFeatures to images.
  • Trusting an output shape. Compare with a loop on a tiny graph.
  • Forgetting node_dim=0 on a built-in that would otherwise run.
  • Concatenating on dim=-1 instead of dim=1.
  • Pooling with global_mean_pool on a four-dimensional tensor.
  • Assuming that keeping the spatial layout makes a model more accurate. It changes what the model can compute; measure whether that helps.

To see where such features come from and how gradients reach the CNN that produces them, read how to combine a CNN and a GNN in one model.

References

  1. PyTorch Geometric documentation, MessagePassing, including the node_dim argument.
  2. PyTorch Geometric documentation, Creating Message Passing Networks.
  3. PyTorch Geometric documentation, GNN Cheatsheet, which defines static graph support.
  4. PyTorch Geometric documentation, Advanced Mini-Batching.
  5. M. Fey and J. E. Lenssen. "Fast Graph Representation Learning with PyTorch Geometric." 2019. arXiv:1903.02428
  6. Y. Wang, Y. Sun, Z. Liu, S. E. Sarma, M. M. Bronstein and J. M. Solomon. "Dynamic Graph CNN for Learning on Point Clouds." 2018. arXiv:1801.07829
  7. K. Xu, W. Hu, J. Leskovec and S. Jegelka. "How Powerful are Graph Neural Networks?" 2018. arXiv:1810.00826