TGraphX › Insights › Explaining GNNs for Image-Patch Nodes: Saliency, Integrated Gradients, Edge Attribution
← Back to Insights

Explaining GNNs for Image-Patch Nodes: Saliency, Integrated Gradients, Edge Attribution

Topic: GNN architectures and learning tasks

Graph models raise two attribution questions at once: which parts of a node's features mattered, and which edges mattered. When nodes are [C, H, W] tensors, the first question is spatial: which pixels of which patch drove the output. TGraphX answers it with the helpers in tgraphx.explain.

This note is about the tensor-valued case. For the underlying theory, completeness checks and node classification with vector features, read explaining GNN predictions with saliency and integrated gradients.

Examples tested with TGraphX 1.5.1 on CPU.

What changes with tensor-valued nodes

The two node-level methods are defined as follows. Saliency is the gradient of the target class logit with respect to the node features; node_feature_saliency returns its absolute value by default. Integrated gradients (Sundararajan, Taly and Yan, ICML 2017, arXiv:1703.01365) averages that gradient along the straight path from a baseline input to the actual input, then multiplies by input minus baseline.

node_feature_saliency and integrated_gradients return a tensor with the same shape as graph.node_features. For patch nodes that is [N, C, ph, pw]: an attribution map, not one number per node. Three choices then affect what you see:

  • The layer. TensorGraphSAGELayer and TensorGINLayer use 1×1 convolutions, so output pixel (r, c) depends only on pixel (r, c) of the input nodes and attribution stays pixel-aligned. TensorGATLayer also transforms values with 1×1 convolutions, but its attention scores come from spatially averaged features, so any pixel can influence any output position through them. ConvMessagePassing aggregates with 3×3 convolutions, which mix neighbouring positions and spread attribution.
  • The readout. Max pooling sends gradient only through the winning activations, which gives sparse maps. Mean pooling distributes it over all positions.
  • The reduction. To draw a map you collapse channels. Take absolute values first if the attributions are signed, otherwise positive and negative channels cancel.

A patch graph with a known answer

An attribution method should be tested where the correct answer is known. Here a 32×32 noise image either does or does not contain a bright 4×4 square inside one of its 16 patches. image_to_patch_graph returns the patches and a 4-neighbour grid with self-loops.

The model's forward must accept edge_weight and batch, and pass edge_weight to the layers. Edge gradients depend on it. (If your graphs also carry edge features, forward needs an edge_features argument too; see the signature requirement below.)

python
import torch
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx import Graph, GraphBatch, TensorGraphSAGELayer, global_max_pool

torch.manual_seed(0)
torch.use_deterministic_algorithms(True)     # keeps repeated CPU runs identical

def make_image(label):
    image = 0.3 * torch.randn(1, 32, 32)
    mask = torch.zeros(32, 32, dtype=torch.bool)
    if label:
        row, col = torch.randint(0, 4, (2,)).tolist()
        mask[8 * row + 2:8 * row + 6, 8 * col + 2:8 * col + 6] = True
        image[0, mask] += 2.0
    return image, mask

def make_graph(image, label=None):
    patches, edge_index = tgx.image_to_patch_graph(image, patch_size=8)
    target = None if label is None else torch.tensor(label)
    return Graph(node_features=patches, edge_index=edge_index, graph_label=target)

train = GraphBatch([make_graph(make_image(i % 2)[0], i % 2) for i in range(128)])
test = GraphBatch([make_graph(make_image(i % 2)[0], i % 2) for i in range(64)])

class PatchSAGE(nn.Module):
    def __init__(self, hidden=8):
        super().__init__()
        self.conv1 = TensorGraphSAGELayer(1, hidden)
        self.conv2 = TensorGraphSAGELayer(hidden, hidden)
        self.head = nn.Linear(hidden, 2)

    def forward(self, x, edge_index, edge_weight=None, batch=None):
        h = F.relu(self.conv1(x, edge_index, edge_weight=edge_weight))
        h = F.relu(self.conv2(h, edge_index, edge_weight=edge_weight))
        h = h.amax(dim=(2, 3))                       # [N, hidden]
        if batch is None:
            batch = torch.zeros(x.size(0), dtype=torch.long)
        return self.head(global_max_pool(h, batch))

model = PatchSAGE()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for epoch in range(60):
    optimizer.zero_grad()
    logits = model(train.node_features, train.edge_index, batch=train.batch)
    F.cross_entropy(logits, train.graph_labels).backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    test_logits = model(test.node_features, test.edge_index, batch=test.batch)
accuracy = (test_logits.argmax(1) == test.graph_labels).float().mean().item()
print(f"test accuracy: {accuracy:.2f}")

The task is easy by design; the run above reached a test accuracy of 1.00.

Spatial node attribution

patch_saliency_to_image_grid takes [P, C, ph, pw] and the patch grid (n_h, n_w), reduces the channels (reduce="mean" by default) and tiles the patches back in row-major order, the order image_to_patch_graph produces.

python
from tgraphx.explain import (node_feature_saliency, integrated_gradients,
                             patch_saliency_to_image_grid)

image, square = make_image(1)
g = make_graph(image)

saliency = node_feature_saliency(model, g, target=1)        # |gradient|
ig = integrated_gradients(model, g, target=1, steps=64)     # signed, zero baseline
print(saliency.shape, ig.shape)                             # both [16, 1, 8, 8]

# The tiling inverts the patching exactly (single channel here).
assert torch.equal(patch_saliency_to_image_grid(g.node_features, (4, 4)), image[0])

for name, attribution in (("saliency", saliency),
                          ("|input| x saliency", g.node_features.abs() * saliency),
                          ("integrated gradients", ig.abs())):
    heat = patch_saliency_to_image_grid(attribution, grid_shape=(4, 4))
    inside = (heat[square].sum() / heat.sum()).item()
    print(f"{name}: {inside:.2f} of the mass is on the square "
          f"({square.float().mean().item():.3f} of the pixels)")

The square covers 1.6% of the pixels. On this image it held 0.32 of the saliency mass and 0.69 of the absolute integrated-gradients mass, so both methods point at the right place. The sharper integrated-gradients map largely reflects its multiplication by input minus baseline (here the input itself, which is largest on the square by construction), as the 0.74 for saliency times absolute input shows, so it is not by itself evidence that integrated gradients explains the model better. One image is an illustration, not an evaluation; repeat this over many inputs before drawing a conclusion about a method.

A zero baseline suits this data because the background is zero-mean noise. For inputs where zero means something specific (a black pixel, a missing value), pass a baseline tensor of the same shape.

To view the map next to the input:

python
import matplotlib.pyplot as plt

heat = patch_saliency_to_image_grid(ig.abs(), grid_shape=(4, 4))
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].imshow(image[0].numpy(), cmap="gray")
axes[0].set_title("input")
shown = axes[1].imshow(heat.numpy(), cmap="magma")
axes[1].set_title("|integrated gradients|")
fig.colorbar(shown, ax=axes[1], fraction=0.046)
fig.savefig("patch_attribution.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Edge attribution

Method Idea What to know
edge_gradient_attribution gradient of the class logit with respect to edge_weight returns zeros, with a warning, if the model does not use edge_weight
edge_perturbation_attribution logit with all edges minus logit without one edge one forward pass per edge; scores only the first max_edges=256 edges
python
from tgraphx.explain import edge_gradient_attribution, edge_perturbation_attribution

grad_score = edge_gradient_attribution(model, g, target=1)
drop_score = edge_perturbation_attribution(model, g, target=1, max_edges=g.num_edges)
print(g.num_edges, grad_score.shape, drop_score.shape)      # 64 edges, both [64]

for e in drop_score.abs().topk(5).indices.tolist():
    src, dst = g.edge_index[:, e].tolist()
    print(f"{src:>2} -> {dst:<2} drop={drop_score[e].item():+.3f} grad={grad_score[e].item():.3f}")

# The default cap shortens the result on larger graphs.
print(edge_perturbation_attribution(model, g, target=1, max_edges=10).shape)   # [10]

Gradient attribution asks how sensitive the output is to the edge weight right now. Perturbation asks what happens if the edge is not there. A positive drop means the edge supported class 1; a negative value means removing it raised the logit.

The signature requirement. The helpers call model(node_features, edge_index, batch=...), add edge_weight for edge gradients or when the graph has weights, and add edge_features when the graph has edge features. If forward rejects any one of these keywords, the helper retries with none of them. A model that accepts edge_weight but not batch, or a graph with edge features given to a model without an edge_features argument, therefore never receives the weights: edge_gradient_attribution returns all zeros with a warning, while saliency, integrated gradients and perturbation scores are computed without the weights and say nothing. Write forward(self, x, edge_index, edge_weight=None, batch=None, edge_features=None); the last argument may go unused.

Attention weights are a different signal

Calling a TensorGATLayer with return_attention=True, as in gat(x, edge_index, return_attention=True), returns the output together with the attention weights, of shape [E, num_heads] in the default scalar attention mode. It is an argument of the forward call, not of the constructor. attention_to_edge_scores reduces the heads to one value per edge.

python
from tgraphx import TensorGATLayer
from tgraphx.explain import attention_to_edge_scores

torch.manual_seed(0)
gat = TensorGATLayer(1, 8, num_heads=2)          # untrained: only the structure matters here
_, attention = gat(g.node_features, g.edge_index, return_attention=True)
edge_scores = attention_to_edge_scores(attention, g.edge_index)
print(attention.shape, edge_scores.shape)        # [64, 2] and [64]

incoming = torch.zeros(g.num_nodes).index_add_(0, g.edge_index[1], edge_scores)
print(incoming[:4])                              # each destination sums to 1

The weights are normalised over the incoming edges of each destination node. A value of 0.5 at a node with two incoming edges is therefore not comparable with 0.25 at a node with five, and a node with a single incoming edge always gets 1.0, whatever the model learned.

Whether attention can be read as an explanation is debated: Jain and Wallace ("Attention is not Explanation", NAACL 2019) argued that it often cannot, and Wiegreffe and Pinter ("Attention is not not Explanation", EMNLP 2019) disputed parts of that argument. Both studied text models. Treat attention as one signal to corroborate, not as ground truth.

Volumes

For 3-D patches [P, C, pd, ph, pw], patch_saliency_to_volume_projection rebuilds the volume and projects it along one axis (axis=0 is depth). reduce applies to the projection ("max" by default); channels are averaged.

python
from tgraphx.explain import patch_saliency_to_volume_projection

volume_attribution = torch.rand(8, 2, 4, 4, 4)       # stand-in for a real attribution
projection = patch_saliency_to_volume_projection(volume_attribution,
                                                 grid_shape=(2, 2, 2), axis=0)
print(projection.shape)                              # torch.Size([8, 8])

Saving the result

The export helpers write only to the paths you give them.

python
from tgraphx.explain import (export_edge_scores_csv, export_patch_heatmap_json,
                             export_explanation_metadata)

export_edge_scores_csv("explain/edge_scores.csv", g.edge_index, drop_score,
                       method="edge_perturbation")
export_patch_heatmap_json("explain/heatmap.json", heat, grid_shape=(4, 4),
                          method="integrated_gradients")
export_explanation_metadata("explain/explanation_metadata.json",
                            method="integrated_gradients", target=1,
                            extra={"steps": 64, "baseline": "zeros"})

The edge CSV is sorted by absolute score.

Reading attributions responsibly

Attribution explains sensitivity, not causation. A high score means the output depends on that input in this model, not that the input caused the outcome in the world. Raw gradients can be noisy, integrated gradients depends on the baseline, perturbation produces graphs the model may never have seen, and attention is normalised per node. These are diagnostic tools; the 1.5.1 README labels explainability as Beta. Interpreting the output soundly is the user's job.

A corroboration workflow

  1. Confirm that the model performs the task on held-out data.
  2. Compute saliency for a fast first look, then integrated gradients with a justified baseline. Check the completeness gap and raise steps if needed.
  3. For structure, run both edge methods. If the gradient says an edge matters but removing it barely changes the output, local sensitivity did not translate into importance.
  4. Perturb the highly attributed region and confirm that the prediction degrades.
  5. Repeat with a randomly initialised model and with other training seeds.
  6. Report the method, baseline, target class and reduction with every figure.

Related guides

Conclusion

For tensor-valued nodes, attribution comes back with the shape of the input, so it can be tiled into a heatmap and checked against what you know about the image. Give the model a forward that accepts every argument the helpers pass, remember the max_edges cap, and read every map as sensitivity of this model, corroborated across methods.