TGraphX › Insights › Explaining GNN Predictions for Vector Features: Saliency and Integrated Gradients
← Back to Insights

Explaining GNN Predictions for Vector Features: Saliency and Integrated Gradients

Topic: GNN architectures and learning tasks

A graph neural network returns a label, not a reason. Attribution methods give a partial answer by assigning a score to each input: which node features, which nodes and which edges moved this particular output. The tgraphx.explain module provides gradient saliency, integrated gradients, and two kinds of edge attribution.

This tutorial uses ordinary vector node features ([N, F]). It builds a model whose correct explanation is known in advance, runs each method on it, and checks the results against that known answer. If your nodes are feature maps rather than flat vectors, attribution for tensor-valued node features covers spatial saliency and edge attribution.

Examples tested with TGraphX 1.5.1 on CPU.


What attribution can and cannot tell you

An attribution score describes how the model's output depends on its input. It does not say why something happens in the real world. If a toxicity classifier highlights a substructure, that is a statement about the classifier; whether the substructure is chemically responsible is a separate question.

That limited statement is still useful. It helps you debug (the model relies on a column it should ignore), audit (compare highlighted inputs with domain knowledge) and report (say which inputs a prediction was sensitive to).


The methods

Gradient saliency

Saliency is the gradient of one output score with respect to the input features:

Saliency(i, k) = | ∂ f_c(x) / ∂ x_ik |

Here f_c is the model's logit for class c, i is a node and k a feature. node_feature_saliency returns this tensor with the same shape as graph.node_features. If you want one number per node or per feature, you reduce it yourself.

Integrated gradients

Plain gradients are local. Where the model has saturated, the gradient can be close to zero although the feature matters. Integrated gradients (Sundararajan, Taly and Yan, ICML 2017, arXiv:1703.01365) average the gradient along a straight path from a baseline input x' to the actual input x:

IG(i, k) = (x_ik − x'_ik) × ∫₀¹ ∂ f_c(x' + α(x − x')) / ∂ x_ik dα

The exact integral satisfies completeness: the attributions sum to f_c(x) − f_c(x'). TGraphX approximates the integral with steps evenly spaced values of α (default 16), so completeness holds only approximately. The default baseline is all zeros.

Edge attribution

Function What it computes Requirement or cost
edge_gradient_attribution ∂ f_c / ∂ edge_weight (absolute value by default) the model must receive and use edge_weight
edge_perturbation_attribution f_c(all edges) − f_c(without edge e) (signed) one forward pass per scored edge; only the first max_edges=256 edges are scored

A model with a known answer

To test an explanation method you need a case where you know what it should say. In the task below each graph has 12 nodes with 6 random features, and the graph label depends only on the mean of feature 0.

The model's forward signature matters. The explain helpers call model(node_features, edge_index, ...) and pass batch, plus edge_weight and edge_features when present. forward has to accept every argument it is given. The graphs here have no edge features, so edge_weight and batch are enough; the signature check under edge attribution below shows what goes wrong otherwise.

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph, GraphBatch, GCNConv, global_mean_pool

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

def ring_with_chords(n, extra):
    ring = torch.arange(n)
    src = torch.cat([ring, torch.randint(0, n, (extra,))])
    dst = torch.cat([(ring + 1) % n, torch.randint(0, n, (extra,))])
    keep = src != dst
    ei = torch.stack([src[keep], dst[keep]])
    return torch.cat([ei, ei.flip(0)], dim=1)        # both directions

def make_graph(n=12, d=6):
    x = torch.randn(n, d)
    label = int(x[:, 0].mean() > 0)                  # only feature 0 matters
    return Graph(node_features=x, edge_index=ring_with_chords(n, 4),
                 graph_label=torch.tensor(label))

train = GraphBatch([make_graph() for _ in range(400)])
test = GraphBatch([make_graph() for _ in range(200)])

class SmallGCN(nn.Module):
    def __init__(self, d=6, h=16, classes=2):
        super().__init__()
        self.conv1 = GCNConv(d, h)
        self.conv2 = GCNConv(h, h)
        self.head = nn.Linear(h, classes)

    def forward(self, x, edge_index, edge_weight=None, batch=None):
        h = F.relu(self.conv1(x, edge_index, edge_weight))
        h = F.relu(self.conv2(h, edge_index, edge_weight))
        if batch is None:
            batch = torch.zeros(x.size(0), dtype=torch.long)
        return self.head(global_mean_pool(h, batch))

model = SmallGCN()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
for epoch in range(80):
    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:.3f}")

On this run the test accuracy was 0.970. An explanation of a model that has not learned the task tells you little about the task, so check this first.


Node saliency

python
from tgraphx.explain import node_feature_saliency

g = make_graph()
with torch.no_grad():
    predicted = model(g.x, g.edge_index).argmax(1).item()

saliency = node_feature_saliency(model, g, target=predicted)
print(saliency.shape)                      # torch.Size([12, 6]): one value per node and feature

feature_share = saliency.sum(0) / saliency.sum()
print([round(v, 2) for v in feature_share.tolist()])

node_score = saliency.norm(dim=1)          # one score per node
print(node_score.topk(4).indices.tolist())

Feature 0 received 0.81 of the total saliency on this run; no other feature received more than 0.07. That matches how the labels were generated.

target is a class index. For a single graph the model returns [1, C], and the helper differentiates the chosen column.


Integrated gradients and a completeness check

python
from tgraphx.explain import integrated_gradients

with torch.no_grad():
    gap = (model(g.x, g.edge_index)
           - model(torch.zeros_like(g.x), g.edge_index))[0, predicted].item()

for steps in (16, 64, 256):
    ig = integrated_gradients(model, g, target=predicted, steps=steps)
    print(f"steps={steps:>3}  sum(IG)={ig.sum().item():.3f}  f(x)-f(baseline)={gap:.3f}")

ig = integrated_gradients(model, g, target=predicted, steps=64)
print(ig.shape)                            # torch.Size([12, 6]), signed values
ig_share = ig.abs().sum(0) / ig.abs().sum()
print([round(v, 2) for v in ig_share.tolist()])

The output gap was 10.162. The attribution sum was 10.214 with 16 steps, 10.165 with 64 and 10.160 with 256. Run this check on your own model and raise steps until the difference is small compared with the effect you are describing. Feature 0 took 0.89 of the absolute attribution.

To use another baseline, pass a tensor with the same shape as the node features, for example a per-feature training-set mean repeated for every node. baseline does not accept strings such as "zeros".


Edge attribution

python
from tgraphx.explain import edge_gradient_attribution, edge_perturbation_attribution

grad_score = edge_gradient_attribution(model, g, target=predicted)
drop_score = edge_perturbation_attribution(model, g, target=predicted,
                                           max_edges=g.num_edges)
print(g.num_edges, grad_score.shape, drop_score.shape)

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}")

Read the two columns differently:

  • A positive drop means the logit of the target class fell when the edge was removed, so the edge supported the prediction. A negative value means removal raised it.
  • grad measures local sensitivity to that edge's weight. It has no sign unless you pass abs_value=False.
  • Each direction of an undirected edge is a separate column of edge_index and gets its own score.

edge_perturbation_attribution scores only the first max_edges edges and returns a tensor of that length, without a warning. The default is 256. To score every edge of a larger graph, set max_edges=graph.num_edges, at one forward pass per edge.

To score only a chosen subset, do not pass a graph with the other edges removed. Each drop would then be measured against a graph that is missing all of them: on this graph, passing only edges 15 to 29 changed the sign of 5 of those 15 scores. Keep every edge, move the chosen ones to the front of edge_index (reordering edge_weight and edge_features the same way), and set max_edges to their number:

python
subset = torch.tensor([21, 4, 11])                         # the edges to score
others = torch.ones(g.num_edges, dtype=torch.bool)
others[subset] = False
order = torch.cat([subset, others.nonzero().flatten()])    # chosen first, none removed

reordered = Graph(
    node_features=g.x,
    edge_index=g.edge_index[:, order],
    edge_weight=None if g.edge_weight is None else g.edge_weight[order],
    edge_features=None if g.edge_features is None else g.edge_features[order],
)
subset_score = edge_perturbation_attribution(model, reordered, target=predicted,
                                             max_edges=len(subset))
print(torch.allclose(subset_score, drop_score[subset], atol=1e-4))     # True

subset_score[k] belongs to edge subset[k] of the original graph. This relies on the model's output not depending on the order of the edge list, as with sum, mean or max aggregation (up to floating-point rounding).

Check the signature: edge weights can be dropped

forward must accept every argument the helper passes: batch always, edge_weight when the graph has weights (and for edge gradients), and edge_features when the graph has edge features. If it rejects any one of them with a TypeError, the helper retries with none of them, so your edge weights never reach the model. For edge gradients you get a warning and a tensor of zeros:

python
import warnings

class MissingBatchArgument(nn.Module):
    def __init__(self, base):
        super().__init__()
        self.base = base

    def forward(self, x, edge_index, edge_weight=None):      # no `batch`
        return self.base(x, edge_index, edge_weight)

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    zeros = edge_gradient_attribution(MissingBatchArgument(model), g, target=predicted)

print(int((zeros != 0).sum()), "non-zero scores")            # 0 non-zero scores
print(str(caught[-1].message))

Node attributions are affected too, and nothing warns you. On a weighted graph the same model is explained as if every edge had weight 1:

python
weighted = Graph(node_features=g.x, edge_index=g.edge_index,
                 edge_weight=torch.rand(g.num_edges))

dropped = node_feature_saliency(MissingBatchArgument(model), weighted, target=predicted)
correct = node_feature_saliency(model, weighted, target=predicted)
unweighted = node_feature_saliency(model, g, target=predicted)

print(torch.allclose(dropped, unweighted))     # True: the weights were ignored
print(torch.allclose(correct, unweighted))     # False: the weights change the result

Integrated gradients and perturbation attribution behave the same way. Edge features trigger it as well: SmallGCN above has no edge_features argument, so on a graph that carries edge features it loses its edge weights despite accepting edge_weight and batch. Add the argument even if the model ignores it:

python
class AcceptsEdgeFeatures(nn.Module):
    def __init__(self, base):
        super().__init__()
        self.base = base

    def forward(self, x, edge_index, edge_weight=None, batch=None, edge_features=None):
        return self.base(x, edge_index, edge_weight=edge_weight, batch=batch)

featured = Graph(node_features=g.x, edge_index=g.edge_index,
                 edge_features=torch.randn(g.num_edges, 3))

lost = edge_gradient_attribution(model, featured, target=predicted)       # warns
kept = edge_gradient_attribution(AcceptsEdgeFeatures(model), featured, target=predicted)
print(int((lost != 0).sum()), "vs", int((kept != 0).sum()), "non-zero scores")   # 0 vs 30 non-zero scores

The safe general form is forward(self, x, edge_index, edge_weight=None, batch=None, edge_features=None).


Comparing methods on the same prediction

python
ig_node_score = ig.norm(dim=1)             # L2 norm per node, the same reduction as node_score
top_saliency = set(node_score.topk(4).indices.tolist())
top_ig = set(ig_node_score.topk(4).indices.tolist())
print(sorted(top_saliency), sorted(top_ig), len(top_saliency & top_ig))
# [2, 4, 7, 8] [0, 3, 4, 5] 1

Use the same reduction for both methods, otherwise it adds a difference of its own. Here only 1 of the top 4 nodes was shared, although both methods agreed that feature 0 carries the signal. The 12 saliency scores also lie close together (about 3.0 to 4.1), so small differences decide which four rank highest. The methods answer different questions. Saliency asks how much the output would move if a node's value changed slightly. Integrated gradients with a zero baseline asks how much the node's current value contributes compared with zero, so a node whose features are near zero receives little attribution even if the model is sensitive to it.

Disagreement therefore does not prove that one method is wrong. State which question you are asking before choosing, and report both when they differ.


Sanity check: randomise the model

An explanation should change when the model changes. Adebayo et al. ("Sanity Checks for Saliency Maps", NeurIPS 2018) proposed comparing attributions from a trained model with those from a model with random weights.

python
torch.manual_seed(1)
untrained = SmallGCN().eval()
random_share = node_feature_saliency(untrained, g, target=predicted).sum(0)
random_share = random_share / random_share.sum()
print([round(v, 2) for v in random_share.tolist()])

With random weights, feature 0 received only 0.13, so the concentration seen above comes from training and not from the method or the graph. If your attributions look the same for a trained and a random model, do not interpret them.


Explaining one node in node classification

For node-level output [N, C], passing the model directly sums the target logit over all nodes. That explains the class score of the whole graph at once, not one prediction. There is no node_idx argument; wrap the model so that it returns only the logits of the node you care about.

python
from tgraphx.explain import node_feature_saliency

torch.manual_seed(0)

class NodeGCN(nn.Module):
    def __init__(self, d=6, h=16, classes=3):
        super().__init__()
        self.conv1 = GCNConv(d, h)
        self.conv2 = GCNConv(h, classes)

    def forward(self, x, edge_index, edge_weight=None, batch=None, edge_features=None):
        return self.conv2(F.relu(self.conv1(x, edge_index, edge_weight)),
                          edge_index, edge_weight)

class OneNode(nn.Module):
    def __init__(self, base, node):
        super().__init__()
        self.base, self.node = base, node

    def forward(self, x, edge_index, edge_weight=None, batch=None, edge_features=None):
        # edge_features is unused, but must be accepted (see the signature check above)
        return self.base(x, edge_index, edge_weight)[self.node]     # shape [C]

path = torch.stack([torch.arange(9), torch.arange(1, 10)])           # 0 -> 1 -> ... -> 9
chain = Graph(node_features=torch.randn(10, 6), edge_index=path)

node_model = NodeGCN()        # untrained: this block only shows which inputs can matter
node_saliency = node_feature_saliency(OneNode(node_model, 5), chain, target=1)
print((node_saliency.sum(1) > 0).nonzero().flatten().tolist())      # [3, 4, 5]

Only nodes 3, 4 and 5 have non-zero gradients. A two-layer message passing network cannot see further than two incoming hops, so this is a useful correctness check: attribution outside the receptive field means your wrapper or your edge direction is not what you think it is.


Visualising node scores

python
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_nodes_from(range(g.num_nodes))
G.add_edges_from(g.edge_index.t().tolist())
pos = nx.spring_layout(G, seed=42)

scores = node_score / node_score.max()
fig, ax = plt.subplots(figsize=(6, 5))
nx.draw_networkx_edges(G, pos, ax=ax, alpha=0.4)
nodes = nx.draw_networkx_nodes(G, pos, ax=ax, node_color=scores.tolist(),
                               cmap="Reds", vmin=0.0, vmax=1.0, edgecolors="black")
nx.draw_networkx_labels(G, pos, ax=ax, font_size=8)
fig.colorbar(nodes, ax=ax, label="saliency (L2 norm, scaled to max 1)")
ax.set_axis_off()
fig.savefig("saliency_map.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Pass ax=ax to colorbar. Colour scales are relative to one graph, so do not compare shades across figures unless you fix a common scale.


Limitations

Gradients are local. Saliency reflects the slope of the model at this input. It can be near zero in saturated regions and can be noisy.

Integrated gradients depend on the baseline. Zeros, a mean vector or a random draw can give different attributions, each satisfying completeness for its own baseline. There is no universally correct choice.

Removing an edge changes more than one message. In a GCN it also changes node degrees and therefore the normalisation of other messages, and the perturbed graph may be unlike anything seen in training.

Perturbation cost grows with the number of edges. Scoring E edges takes E + 1 forward passes.

Deep stacks are harder to explain. With many layers each node's receptive field can cover most of the graph, and over-smoothing makes node representations similar, so attributions can become diffuse.

Diagnostics, not proof. The module's own documentation calls these helpers diagnostic, not causal proof, and the 1.5.1 README labels explainability as Beta.

No learned-mask explainers. tgraphx.explain has no GNNExplainer, PGExplainer or subgraph search. PyTorch Geometric provides GNNExplainer and PGExplainer in torch_geometric.explain if you need them.


Reporting attributions in a paper

  • Name the method and its parameters: target class, baseline, number of steps, max_edges, and how you reduced feature dimensions to a node score.
  • Validate on a controlled example with a known answer, as above, before showing real data.
  • Include a randomised-model comparison.
  • Train several seeds and check whether the highlighted inputs are stable. Agreement across models is more informative than one attractive figure. See reproducibility in GNN research.

Frequently asked questions

Can I use these functions with a model built from PyTorch Geometric layers?
The helpers only call model(node_features, edge_index, ...) on a tgraphx.Graph, so a torch.nn.Module with a forward that accepts the arguments described above can be used. A model that expects a PyG Data object needs a wrapper.

Do the node methods work for tensor-valued features?
Yes. Saliency and integrated gradients return the full shape of node_features, for example [N, C, H, W]. See the tensor-valued attribution note.

Saliency or integrated gradients?
Saliency costs one backward pass and is convenient while debugging. Integrated gradients costs steps backward passes and gives an approximately additive decomposition relative to a baseline, which is easier to describe in a report.

Are there non-gradient views of importance?
Structural measures such as centrality or motif counts describe the graph rather than the model. The graph mining overview covers them. For model setup, see graph classification architectures, MNIST as a graph and shape-aware validation.