TGraphX › Insights › Tensor-Valued Edge Features in Graph Neural Networks
← Back to Insights

Tensor-Valued Edge Features in Graph Neural Networks

Topic: Tensor-valued nodes, edges and message passing

Many GNN examples treat an edge feature as an optional scalar: a weight, a distance, a type label. That covers a lot of problems. In some, though, the relation itself has structure, such as a pairwise comparison map between two image regions or a spatial overlap mask between two detected objects.

TGraphX lets edge_features have any trailing shape, and its tensor layers can consume spatial edge tensors as well as vector ones. They do not all use them the same way, so this guide shows what each layer accepts, how to build and sample such graphs, and where the limits are. The examples were tested with TGraphX 1.5.1 on CPU.


Why Edge Features Are Different from Node Features

In message passing, the update for node v is:

h_v' = UPDATE( h_v, AGGREGATE( {MSG(h_u, h_v, e_uv) : u ∈ N(v)} ) )

Here e_uv belongs to the directed edge from u to v: column k of edge_index holds (u, v) and row k of edge_features holds e_uv. After aggregation there is one value per destination node and no edge axis left, so an edge tensor has to be consumed inside the message function (or the attention score) before aggregation. How it is combined with the node tensor depends on the layer.


How Each Layer Consumes Edge Features

All four layers below are built with use_edge_features=True. The defaults assume 2-D spatial nodes [N, C, H, W]; pass spatial_rank=3 for volumes (not needed for ConvMessagePassing, which reads the rank from in_shape).

Layer Accepted edge tensors How they are used
TensorGINLayer "spatial" (default) [E, edge_dim, H, W], meant to use the node H×W (size-1 dimensions broadcast silently), or "vector" [E, edge_dim] message = ReLU(h_u + φ(e_uv)), where φ is a 1×1 convolution (spatial; the identity if edge_dim equals the node channels) or a linear layer broadcast over H×W (vector)
TensorGraphSAGELayer the same two kinds, same keyword edge_features_kind; spatial maps need exactly the node H×W spatial: concatenated to the source map before the neighbor transform; vector: projected to a per-channel bias added to the message
TensorGATLayer no kind argument; inferred from the rank: [E, edge_dim] or [E, edge_dim, H_e, W_e] spatial maps are mean-pooled first; the result only biases the attention score of each head
ConvMessagePassing spatial only, with the node channel count and H×W source, destination and edge maps are concatenated, then convolved

The GIN form with edge features follows GINE (Hu et al., "Strategies for Pre-training Graph Neural Networks", ICLR 2020). There is no 1-D spatial mode: spatial_rank must be 2 or 3.


Spatial and Vector Modes with GIN

Spatial mode. Each edge carries its own map with the same height and width as the node maps:

python
import torch
from tgraphx.layers.gin import TensorGINLayer

torch.manual_seed(0)
N, C, H, W = 50, 16, 8, 8
E = 200

layer = TensorGINLayer(
    in_channels=C,
    out_channels=32,
    use_edge_features=True,
    edge_dim=8,                    # channels of the edge tensor
    edge_features_kind="spatial",  # [E, 8, H, W]
)

x = torch.randn(N, C, H, W)
edge_index = torch.randint(0, N, (2, E))
edge_feats = torch.randn(E, 8, H, W)

out = layer(x, edge_index, edge_features=edge_feats)
print(out.shape)  # torch.Size([50, 32, 8, 8])

Vector mode. Each edge carries a flat vector. It is projected to C channels and broadcast over the spatial grid:

python
layer_vec = TensorGINLayer(
    in_channels=C,
    out_channels=32,
    use_edge_features=True,
    edge_dim=4,
    edge_features_kind="vector",   # [E, 4]
)

edge_feats_vec = torch.randn(E, 4)
out_vec = layer_vec(x, edge_index, edge_features=edge_feats_vec)
print(out_vec.shape)  # torch.Size([50, 32, 8, 8])

In vector mode the edge term is the same at every spatial position. In spatial mode the edge tensor can add something different at each position.


GraphSAGE, GAT and ConvMessagePassing

python
from tgraphx import ConvMessagePassing
from tgraphx.layers.sage import TensorGraphSAGELayer
from tgraphx.layers.gat import TensorGATLayer

# SAGE: spatial edge maps are concatenated to the source node maps
sage_layer = TensorGraphSAGELayer(
    in_channels=C, out_channels=32,
    use_edge_features=True, edge_dim=8, edge_features_kind="spatial",
)
print(sage_layer(x, edge_index, edge_features=edge_feats).shape)

# GAT: vector edge features become a per-head attention bias
gat_layer = TensorGATLayer(
    in_channels=C, out_channels=32, num_heads=4,
    use_edge_features=True, edge_dim=4,
)
print(gat_layer(x, edge_index, edge_features=edge_feats_vec).shape)

# GAT also accepts spatial edge maps of another size; they are mean-pooled
print(gat_layer(x, edge_index, edge_features=torch.randn(E, 4, 3, 3)).shape)

# ConvMessagePassing: edge channels must equal node channels (16 here)
conv_layer = ConvMessagePassing(
    (C, H, W), (32, H, W), use_edge_features=True, dropout_prob=0.0,
)
print(conv_layer(x, edge_index, edge_features=torch.randn(E, C, H, W)).shape)
# each call prints torch.Size([50, 32, 8, 8])

Two behaviours are easy to miss. TensorGINLayer, TensorGraphSAGELayer and TensorGATLayer raise an error if you pass edge features to a layer built without use_edge_features=True, but ConvMessagePassing silently ignores them. And in GAT the edge features only reweight incoming messages: a softmax over a single incoming edge is always 1, so for a node with one incoming edge (and no self-loop) they have no effect at all. Tensor-Valued Edges in TGraphX demonstrates both and goes through the per-layer math.

The node-side behaviour of the SAGE layer is covered in the GraphSAGE layer deep dive.


Use Cases: When Tensor-Valued Edges Make Sense

These are candidate designs rather than demonstrated results. Compare each against a plain vector edge feature before adopting it.

Scene graph edges. Nodes are objects represented by image crops, and an edge describes the relation between two of them, for example an overlap mask or a relative-position map. That is naturally a [C_e, H, W] tensor.

Brain connectivity. Diffusion tensor imaging estimates a 3×3 symmetric diffusion tensor per voxel, not per connection. For region-to-region edges, a practical representation is a vector of tract summaries (for example mean fractional anisotropy, mean diffusivity and streamline count), used in "vector" mode as [E, 3]. A 3×3 matrix per edge is not a spatial map; if you need its components, flatten them into the vector.

Molecular bonds. Bond type, bond order and bond length form a vector per edge. This needs vector mode, not spatial mode.

Multimodal knowledge graphs. tgraphx.kg.KnowledgeGraph can store a tensor per triple through triple_features=, such as an image supporting a fact. The knowledge graph scoring models do not read these tensors, so using them in a model is your own code. For how entity-side tensors enter a KG model, see knowledge graph embedding with tensor features.


Constructing a Graph with Edge Features

python
from tgraphx import Graph

x = torch.randn(N, C, H, W)
edge_index = torch.randint(0, N, (2, E))
edge_feats = torch.randn(E, 8, H, W)  # [E, edge_dim, H, W]

g = Graph(node_features=x, edge_index=edge_index, edge_features=edge_feats)

print(g.edge_features.shape)  # torch.Size([200, 8, 8, 8])
print(g.edge_attr.shape)      # PyG-style alias for the same tensor

# The leading dimension must equal the number of edges
try:
    Graph(node_features=x, edge_index=edge_index, edge_features=edge_feats[:-1])
except ValueError as err:
    print(err)
else:
    raise AssertionError("expected a ValueError")

Edge features must be at least 2-D, so a single scalar per edge is stored as [E, 1] or passed as edge_weight instead.


Edge Features in Mini-Batch Sampling

NeighborLoader and the GraphSAINT loader slice edge_features together with the sampled edges. The sampling metadata records which original edges were kept, so you can check the alignment:

python
from tgraphx import NeighborLoader, GraphSAINTNodeSampler, GraphSAINTLoader

train_mask = torch.zeros(N, dtype=torch.bool)
train_mask[:30] = True
loader = NeighborLoader(g, fanouts=[10, 5], mask=train_mask, batch_size=16, seed=42)

for batch in loader:
    edge_ids = batch.graph.metadata["sampling"]["original_edge_ids"]
    assert torch.equal(batch.edge_features, g.edge_features[edge_ids])
    assert torch.equal(batch.input_nodes[batch.edge_index], g.edge_index[:, edge_ids])

    out = layer(batch.node_features, batch.edge_index,
                edge_features=batch.edge_features)
    seed_out = batch.seed_logits(out)  # rows for the seed nodes only

sampler = GraphSAINTNodeSampler(g, budget=20, num_steps=2, seed=0)
for sub in GraphSAINTLoader(sampler, num_norm_samples=10):
    edge_ids = sub.metadata["sampling"]["original_edge_ids"]
    assert torch.equal(sub.edge_features, g.edge_features[edge_ids])

Always pass mask= to NeighborLoader: without it every node, including validation and test nodes, is used as a seed. Note also that a sampled subgraph contains all edges between the visited nodes, which can be more than the fanouts suggest.


The Graph Object: Edge Features vs Edge Weight vs Edge Labels

TGraphX keeps three edge-level tensors apart:

Attribute Shape Purpose
edge_features [E, ...] Per-edge inputs to message passing
edge_weight [E] Scalar that multiplies each message before aggregation (in GAT, after the attention softmax)
edge_labels [E, ...] Targets for edge-level supervision

Layers do not read these from the Graph object; you pass edge_features= and edge_weight= to the layer call. Weights are not normalised for you: mean-aggregating SAGE still divides by the number of incoming edges. A quick check that the weight acts on messages is that all-zero weights give the same output as having no edges:

python
gin = TensorGINLayer(C, 32)
no_edges = torch.zeros(2, 0, dtype=torch.long)
with torch.no_grad():
    assert torch.allclose(gin(x, edge_index, edge_weight=torch.zeros(E)),
                          gin(x, no_edges))

Memory and Limitations

Memory. Spatial edge tensors cost E × edge_dim × H × W values. With 10,000 edges and [8, 8, 8] edge features that is 5.12 million float32 values, about 20 MB. The messages are larger than the input when the node channel count is higher: with 16 node channels, one GIN layer builds a 10,000 × 16 × 8 × 8 message buffer, about 41 MB. The tensor layers accept chunk_size= in forward to process edges in pieces:

python
with torch.no_grad():
    full = layer(x, edge_index, edge_features=edge_feats)
    chunked = layer(x, edge_index, edge_features=edge_feats, chunk_size=64)
assert torch.allclose(full, chunked, atol=1e-5)

Chunking mainly helps inference under torch.no_grad(). During training, autograd still keeps intermediate tensors for the backward pass.

Shape rules differ by layer. In spatial mode, SAGE and ConvMessagePassing require edge maps with exactly the node's spatial size, and ConvMessagePassing needs matching channels as well. GIN does not check the spatial size: it adds the projected edge map to the source map with normal broadcasting, so size-1 spatial dimensions (for example [E, edge_dim, 1, 1] or [E, edge_dim, 1, 8] with 8×8 nodes) are accepted silently, and other mismatches raise. If that would be a bug in your data, assert edge_features.shape[2:] == x.shape[2:] before the call. GAT averages the edge map's spatial positions away. As with the node features, the 1×1 convolutions in GIN and SAGE never mix neighbouring positions.

No dedicated edge readout layer. For a graph-level summary of edge tensors you can reuse the node pooling functions with a graph id per edge:

python
from tgraphx import GraphBatch, global_mean_pool

def ring_graph(n):
    ring = torch.arange(n)
    return Graph(node_features=torch.randn(n, C, H, W),
                 edge_index=torch.stack([ring, (ring + 1) % n]),
                 edge_features=torch.randn(n, 8, H, W))

two = GraphBatch([ring_graph(4), ring_graph(6)])
edge_graph = two.batch[two.edge_index[0]]  # graph id of every edge
summary = global_mean_pool(two.edge_features, edge_graph)
print(summary.shape)                       # torch.Size([2, 8, 8, 8])

If a graph in the batch can have no edges, check the number of rows you get back.


Related Articles