A Short History of Graph Attention
Graph convolution showed that local feature mixing could work without image-like grids, but early layers usually assigned neighbor weights from topology alone. Attention offered a learnable alternative: score each permitted message using node features.
Working Principle: Learned Attention Coefficients
For every permitted message $j\to i$, standard GAT transforms both endpoint features and computes an additive compatibility score:
$$e_{ij} = \text{LeakyReLU}\left( \mathbf{a}^T [W h_i \, \| \, W h_j] \right)$$
- $W \in \mathbb{R}^{d' \times d}$: a shared learnable linear transformation applied to every node's features.
- $\mathbf{a} \in \mathbb{R}^{2d'}$: a learnable attention weight vector.
- $\|$: concatenation of the transformed features of nodes $i$ and $j$.
- $e_{ij}$: an unnormalized compatibility logit, not yet a probability or explanation.
Mask, Softmax & Aggregate
The adjacency mask decides which logits participate. Write $\widetilde{\mathcal N}(i)=\mathcal N(i)\cup\{i\}$ for the closed neighborhood. For target $i$, normalize only over this set:
$$\alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k \in \widetilde{\mathcal{N}}(i)} \exp(e_{ik})}$$
For numerical stability, code subtracts the largest permitted logit before exponentiation. Nonedges receive no coefficient at all—not a small coefficient. The normalized values are positive and sum to one for each target.
$$h_i' = \sigma \left( \sum_{j \in \widetilde{\mathcal{N}}(i)} \alpha_{ij} \, W h_j \right)$$
Transform nodes once
Compute $z_i=Wh_i$ for every node. Each edge reuses its two endpoint vectors.
Score existing directed edges
Evaluate $e_{ij}$ only where the graph permits $j\to i$, including a self-edge if desired.
Normalize per target
Apply a separate softmax to every target's incoming edge group. Coefficients are therefore relative to that neighborhood.
Aggregate messages
Scale $z_j$ by $\alpha_{ij}$, sum incoming messages, and apply the output activation.
Softmax Creates Competition
Increasing one neighbor's logit raises its coefficient and lowers the others, even when their logits do not change. Attention weights are contextual proportions, not independent edge scores.
Multi-Head Attention
A single head commits to one transformed feature space and one scoring vector. GAT runs $K$ independent heads so different heads can form different neighborhood summaries:
$$h_i' = \Big\|_{k=1}^{K} \sigma \left( \sum_{j \in \widetilde{\mathcal{N}}(i)} \alpha_{ij}^{(k)} \, W^{(k)} h_j \right) \quad \text{(concatenation, for intermediate layers)}$$
Concatenating $K$ heads of width $d_h$ produces width $Kd_h$. In the original GAT classification output layer, head predictions are averaged so the class dimension does not grow.
Worked Example
Suppose target $i$ has two permitted incoming neighbors with logits $e_{i1}=2.0$ and $e_{i2}=0.5$. Subtract the maximum before exponentiating:
$$\alpha_{i1}=\frac{e^0}{e^0+e^{-1.5}}\approx0.818,\qquad \alpha_{i2}=\frac{e^{-1.5}}{e^0+e^{-1.5}}\approx0.182.$$
If transformed messages are $z_1=(1,2)$ and $z_2=(3,0)$, the pre-activation aggregate is
$$0.818(1,2)+0.182(3,0)=(1.364,1.636).$$
GAT vs. GCN
| Dimension | GCN | GAT |
|---|---|---|
| Edge weight | $1/\sqrt{\tilde d_i\tilde d_j}$ from topology | $\alpha_{ij}$ from endpoint features and learned parameters |
| Normalization | symmetric degree scaling | directed softmax over each target neighborhood |
| Parameters per layer | feature projection $W$ | $W$ plus attention vector $a$ per head |
| Graph requirement | edges or normalized sparse adjacency | edges for masking and neighborhood grouping |
| Potential advantage | simple, stable, low overhead | feature-dependent neighbor mixtures |
Complexity Analysis
For $n$ nodes, $m$ directed message edges including self-loops, input width $d$, output width $d'$, and $K$ heads:
| Phase | One head | Why |
|---|---|---|
| Feature projection | $O(ndd')$ | compute $Wh_i$ once per node |
| Edge scoring | $O(md')$ | one additive score per permitted directed edge |
| Segment softmax | $O(m)$ | normalize incoming edges by target |
| Weighted aggregation | $O(md')$ | scale and sum transformed messages |
Total sparse work is $O(ndd'+md')$ per head and memory is $O(nd'+m)$ excluding parameters and saved training activations. $K$ independent heads multiply the dominant work and intermediate storage by roughly $K$. A dense all-pairs teaching implementation instead allocates $O(n^2)$ logits—even though most pairs are nonedges.
Implementation
The NumPy helper isolates the most error-prone operation: a stable row-wise softmax over permitted edges. The PyTorch head uses the algebraically equivalent split score $a_L^TWh_i+a_R^TWh_j$, avoiding an explicit $n\times n\times2d'$ concatenation. It remains a dense teaching version; edge-list kernels are preferable for large sparse graphs.
Real-World Applications
GAT is most appealing when connected neighbors plausibly contribute unequally and node features contain evidence for learning that difference.
Traffic networks
Road segments or sensors form nodes. Attention can adapt the mixture of upstream, downstream, and adjacent conditions, usually inside a temporal model.
Fraud and abuse
Accounts, devices, and transactions form interaction graphs. Learned weights can reduce the contribution of routine neighbors while emphasizing task-relevant patterns.
Molecules
Attention can weight neighboring atom messages, though chemistry typically requires edge or bond features beyond the original node-only GAT score.
Knowledge and citation graphs
Feature-dependent aggregation supports node classification and link prediction. Multiple relation types call for relational or heterogeneous extensions.
Can Attention Explain a Prediction?
An attention coefficient answers a narrow internal question: within this head, layer, target neighborhood, and parameter state, what fraction of the transformed-message mixture came through this edge? It does not automatically measure causal importance.
Weights are relative
Softmax couples all incoming edges. Adding an irrelevant neighbor can change every existing coefficient even before the final prediction changes materially.
Values are transformed
A large coefficient multiplies $Wh_j$, whose magnitude and direction also matter. Weight alone does not equal contribution.
Heads and layers interact
A prediction combines several heads, nonlinearities, residual paths, and downstream layers. One coefficient is only one piece of that computation.
Validate explanations
Use edge deletion, feature perturbation, counterfactual tests, gradients, or domain review to check whether highlighted edges actually influence the output.
Exercises
1. Verify masked softmax
Add a third nonedge logit of 100 to the worked example. Show that masking before softmax leaves the two permitted coefficients unchanged.
2. Track softmax competition
Increase $e_{i2}$ from 0.5 to 1.5 while holding $e_{i1}=2$. Recompute both coefficients and explain why the first one decreases.
3. Count parameters
For input width $d$, head width $d'$, and $K$ heads, count the original GAT projection and attention parameters, with and without bias.
4. Test permutation equivariance
Apply one permutation to node-feature rows and both adjacency axes. Verify that the output rows and attention matrix follow the same permutation.
5. Implement sparse edge scoring
Replace the dense $n\times n$ logits with source and target index arrays. Use a segment softmax grouped by target and scatter-add the weighted messages.
Limitations
Quadratic Memory in the Naive Implementation
The dense teaching implementation stores all $n^2$ logits before masking. Production implementations compute scores only for actual directed edges and use segment softmax plus scatter aggregation, reducing topology-dependent storage to $O(m)$.
- Static attention in original GAT: its score factorization restricts how a target can change the ranking of its neighbors; GATv2 addresses this limitation.
- High-degree dilution: softmax distributes unit mass across the neighborhood. Many neighbors can create small coefficients and expensive aggregation.
- Noisy topology: attention reweights edges but does not normally invent a missing edge, and every retained noisy edge remains a candidate message.
- Depth problems remain: attention does not eliminate over-smoothing, over-squashing, or bottlenecks caused by long-range information compression.
- Multi-head cost: more heads increase parameters, activations, and edge-scoring work; heads may also collapse to similar patterns.
- Task dependence: feature-dependent weighting is not automatically better than GCN's structural prior, especially on small or noisy datasets.