TGraphX › Insights › Tensor Shape Semantics for GNN Researchers: A Notation Guide
← Back to Insights

Tensor Shape Semantics for GNN Researchers: A Notation Guide

Topic: Shape validation, testing and debugging

With flat node features, X ∈ ℝ^{N×F} says almost everything. With node features such as [N, C, H, W], a reader also needs to know what each axis means, which axes a layer changes, and how edges are oriented. This note proposes one notation for tensor-valued graphs and ties each symbol to the matching object in TGraphX, so that you can reuse it in your own write-ups.

For a layer-by-layer treatment of the same ideas, see Shape Algebra Through GNN Layers. Examples tested with TGraphX 1.5.1.

The core symbols

Take a graph with N nodes and E directed edges.

Symbol Meaning Shape TGraphX name
N number of nodes integer g.num_nodes
E number of directed edges integer g.num_edges
X node features [N, *s] g.node_features, alias g.x
s per-node trailing shape tuple g.feature_shape
I edge index, integer [2, E] g.edge_index
Eᶠ edge features [E, *s_e] g.edge_features, alias g.edge_attr
s_e per-edge trailing shape tuple g.edge_feature_shape
M messages, one per edge [E, *s_m] output of a message function
A aggregated messages (not the adjacency matrix) [N, *s_m] output of aggregation
X' updated node features [N, *s'] layer output
B number of graphs in a batch integer batch.num_graphs
b node-to-graph map [N] batch.batch
K number of classes integer num_classes

In a batch, N is the total number of nodes over all graphs.

C is reserved for channels, H and W for height and width, D for volume depth, and F for the width of a vector feature. That keeps classes (K) and vector widths (F) from colliding with spatial letters.

Many other pages on this site write vector features as [N, D]; that is [N, F] here. Likewise, the E_{i→j} of the message-passing articles is Eᶠ[e], the features of the edge e that runs from node i to node j.

Edge direction. Edge number e goes from node i = I[0, e] (source) to node j = I[1, e] (destination). Messages travel from source to destination and are aggregated at the destination. State this in every write-up: without it, a phrase such as "the neighbours of node j" is ambiguous on a directed graph.

Leading count, trailing shape. The first axis counts things (N, E or B); everything after it describes one item. g.feature_shape reports only the trailing part.

None of the layers named in this note takes N in its constructor, but they describe the trailing shape in three common ways:

  • ConvMessagePassing, LinearMessagePassing and AttentionMessagePassing take per-item shapes as tuples: in_shape and out_shape.
  • TensorGraphSAGELayer, TensorGATLayer and TensorGINLayer take channel counts, in_channels and out_channels, plus spatial_rank (2 by default, 3 for volumes).
  • Vector layers such as GCNConv and GATv2Conv take two widths, in_dim and out_dim.

There are exceptions, so check the signature: RGCNConv takes in_channels, out_channels and num_relations without spatial_rank, and APPNP takes no feature width at all.

Rank conventions for node features

The rank of X includes the leading node axis.

Rank of X s Example node TGraphX 1.5.1 layers (examples)
2 (F,) embedding vector GCNConv, GATv2Conv, LinearMessagePassing, AttentionMessagePassing
3 (C, L) 1-D sequence or signal no message-passing layer models it as a sequence or signal (see below)
4 (C, H, W) image patch or feature map ConvMessagePassing, TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer, AttentionMessagePassing
5 (C, D, H, W) volume block ConvMessagePassing; the SAGE, GAT and GIN layers with spatial_rank=3

Rank 3 needs care, because not every layer rejects it. ConvMessagePassing, the SAGE, GAT and GIN tensor layers, GCNConv and GATv2Conv raise on [N, C, L]. LinearMessagePassing and AttentionMessagePassing built with in_shape=(L,) run without an error and return [N, C, F'], where F' is the output width. The models NodeClassifier and NodeRegressor, built on LinearMessagePassing, run too. All of them project only the last axis, treating its L values as a plain feature vector. LinearMessagePassing keeps the C rows independent; AttentionMessagePassing links them through an attention score summed over C.

Check x.dim() == 2 yourself before a vector layer. To use the sequence structure, encode it first, for example with torch.nn.Conv1d on [N, C, L], or with TGraphX's experimental tgraphx.mining.GraphSequenceEncoder, an LSTM that expects [N, L, C].

Channels come first. Graph cannot tell a channels-last tensor [N, H, W, C] from a channels-first one; a layer will either fail on the channel count or, if the sizes happen to match, treat the wrong axis as channels.

The TGraphX arXiv preprint describes the rank-4 case: CNN feature maps are used as node features, messages are formed with 1×1 convolutions and refined by a convolutional aggregator, so each node keeps its spatial layout instead of being flattened to a single vector.

Shapes through one round of message passing

With the symbols fixed, the pipeline in Inside Tensor Message Passing can be annotated like this:

text
gather     X_src = X[I[0]],  X_dst = X[I[1]]      [N, *s]    -> [E, *s]     leading N -> E
message    M_e = φ(X_src[e], X_dst[e], Eᶠ[e])     [E, *s]    -> [E, *s_m]   trailing may change
aggregate  A_j = AGG { M_e : I[1, e] = j }        [E, *s_m]  -> [N, *s_m]   leading E -> N
update     X'_j = ψ(X_j, A_j)                     [N, *s_m]  -> [N, *s']    trailing may change
pool       z_q = R { X'_j : b_j = q }             [N, *s']   -> [B, *s']    leading N -> B

In the last line q is a graph index, from 0 to B - 1, and R is the readout. The leading axis changes three times: gathering node features onto edges (N to E), aggregation (E back to N) and graph pooling (N to B). The message and update functions keep the leading axis and may change the trailing shape. In TGraphX, message() and aggregate() are methods of TensorMessagePassingLayer, the base class of ConvMessagePassing and LinearMessagePassing; the SAGE, GAT and GIN tensor layers implement the same steps inside forward().

global_mean_pool, global_sum_pool and global_max_pool change only the leading axis. Applied to [N, C, H, W], they return [B, C, H, W].

Edge rank conventions

Edges follow the same leading-count rule. Graph accepts any edge tensor with at least two dimensions and first axis E, but each layer supports less. A layer must also be built with use_edge_features=True.

Shape of Eᶠ Layer support in TGraphX 1.5.1
[E, F_e] SAGE and GIN with edge_features_kind="vector"; GAT (affects attention scores only); LinearMessagePassing and AttentionMessagePassing, only if F_e equals the node width
[E, C_e, H, W] ConvMessagePassing and AttentionMessagePassing, only if C_e equals the node channels; SAGE and GIN (their default "spatial" kind); GAT, which averages over H, W first
[E, C_e, D, H, W] ConvMessagePassing, SAGE, GIN and GAT in their 3-D form, with the same conditions; AttentionMessagePassing has no 3-D form

Give spatial edge maps the same spatial size as the node maps, and assert it yourself. ConvMessagePassing and TensorGraphSAGELayer raise on a mismatch. TensorGINLayer and AttentionMessagePassing do not catch every case: an edge axis of size 1 is broadcast silently, so [E, C_e, 1, 1] or [E, C_e, H, 1] edge maps run with H × W node maps. GAT averages the edge maps, so it accepts any spatial size.

The edge-feature notes in the repository show the constructor options. One more trap: ConvMessagePassing, LinearMessagePassing and AttentionMessagePassing built without use_edge_features=True ignore any edge_features you pass, without an error. The SAGE, GAT and GIN tensor layers raise instead.

python
import torch
import tgraphx as tgx

torch.manual_seed(0)
edge_index = tgx.build_grid_graph(4, 4)          # [2, 64], includes self-loops
x = torch.randn(16, 3, 8, 8)                     # [N, C, H, W]
E = edge_index.shape[1]

sage = tgx.TensorGraphSAGELayer(3, 16, use_edge_features=True, edge_dim=5,
                                edge_features_kind="vector")
out = sage(x, edge_index, edge_features=torch.randn(E, 5))
assert out.shape == (16, 16, 8, 8)

conv = tgx.ConvMessagePassing((3, 8, 8), (16, 8, 8), use_edge_features=True,
                              dropout_prob=0.0)
out = conv(x, edge_index, edge_features=torch.randn(E, 3, 8, 8))   # C_e = C = 3
assert out.shape == (16, 16, 8, 8)

attention = tgx.AttentionMessagePassing((3, 8, 8), (16, 8, 8), use_edge_features=True)
out = attention(x, edge_index, edge_features=torch.randn(E, 3, 8, 8))   # C_e = C = 3
assert out.shape == (16, 16, 8, 8)

# Trap: GIN broadcasts size-1 spatial edge axes instead of raising.
gin = tgx.TensorGINLayer(3, 16, use_edge_features=True, edge_dim=5)
edge_maps = torch.randn(E, 5, 1, 1)                # node maps are 8x8
out = gin(x, edge_index, edge_features=edge_maps)  # no error
assert out.shape == (16, 16, 8, 8)
# Your own guard before the call: assert edge_maps.shape[2:] == x.shape[2:]

The notation applied end to end

Take two graphs, each a 4×4 grid of patch nodes, so B = 2, N = 32 and E = 128. Then X ∈ ℝ^{32×3×8×8} and I has shape [2, 128]. Two convolutional layers map s from (3, 8, 8) to (32, 8, 8) and then (64, 8, 8). A spatial mean reduces s to (64,), graph pooling reduces N to B, and a linear head produces K = 5 scores per graph.

python
import torch
import tgraphx as tgx
from tgraphx import Graph, GraphBatch

torch.manual_seed(0)
grid = tgx.build_grid_graph(4, 4)
graphs = [Graph(node_features=torch.randn(16, 3, 8, 8), edge_index=grid)
          for _ in range(2)]
batch = GraphBatch(graphs)

assert graphs[0].feature_shape == (3, 8, 8)
assert (batch.node_features.shape[0], batch.edge_index.shape[1], batch.num_graphs) == (32, 128, 2)
assert batch.batch.shape == (32,)

layer1 = tgx.ConvMessagePassing((3, 8, 8), (32, 8, 8), dropout_prob=0.0)
layer2 = tgx.ConvMessagePassing((32, 8, 8), (64, 8, 8), dropout_prob=0.0)
head = torch.nn.Linear(64, 5)

h1 = layer1(batch.node_features, batch.edge_index)    # [N, 32, 8, 8]
h2 = layer2(h1, batch.edge_index)                     # [N, 64, 8, 8]
v = h2.mean(dim=(-2, -1))                             # [N, 64]
z = tgx.global_mean_pool(v, batch.batch)              # [B, 64]
logits = head(z)                                      # [B, K]

for name, t in [("h1", h1), ("h2", h2), ("v", v), ("z", z), ("logits", logits)]:
    print(name, list(t.shape))

Output:

text
h1 [32, 32, 8, 8]
h2 [32, 64, 8, 8]
v [32, 64]
z [2, 64]
logits [2, 5]

Each line names the axis that changed: trailing shape in the two layers, spatial axes in the mean, leading axis in the pool. A reviewer can check this bookkeeping without running the model.

What notation and validation cannot check

The Graph constructor checks leading counts and the edge index. validate_graph re-checks some of those structural invariants (edge index shape and upper bound, edge-feature and mask lengths, devices), which is useful after you change tensors on an existing graph. It does not look for negative indices; g.validate() does. It can also add two checks the constructor does not make: check_finite=True reports NaN or Inf in node and edge features, and allow_vector_features=False rejects node features of rank below 3. Neither is on by default. The result is a report with ok and issues, and it raises only with strict=True.

python
import torch
import tgraphx as tgx
from tgraphx import Graph

edge_index = torch.tensor([[0, 1], [1, 2]])

nan_graph = Graph(node_features=torch.full((4, 3, 8, 8), float("nan")),
                  edge_index=edge_index)                    # the constructor accepts NaN
assert tgx.validate_graph(nan_graph)["ok"]                  # not checked by default
report = tgx.validate_graph(nan_graph, check_finite=True)
assert report["issues"] == ["node_features contains NaN/Inf values."]

vector_graph = Graph(node_features=torch.randn(4, 12), edge_index=edge_index)
assert tgx.validate_graph(vector_graph)["ok"]
assert not tgx.validate_graph(vector_graph, allow_vector_features=False)["ok"]

# A vector layer does not reject [N, C, L].
out = tgx.LinearMessagePassing((12,), (4,))(torch.randn(4, 3, 12), edge_index)
assert out.shape == (4, 3, 4)

assert_tensor_native(g, min_rank=3) only checks that node_features has at least min_rank dimensions. Neither function knows that your (C, H, W) means channels, height and width. Document the meaning of every axis in s and s_e, and for an unusual layout write the shape out instead of expecting readers to infer it.

If you need to present this notation visually, see drawing tensor-shape diagrams.

Related guides

Conclusion

Four habits make a shape claim checkable: write the leading count and the trailing shape separately, say which way edges point, name what every axis means, and say which step changes which axis.