Graph attention: weights can change while rankings cannot
图注意力网络
Compute masked neighborhood attention and expose the original GAT score’s static ranking with a GATv2-style counterexample.
graph-attentionStart with the problem
A graph convolution scales edges using degrees. Graph attention instead computes weights from node features. That sounds as if each receiving node can freely choose which neighbor matters most. For the original additive GAT score, that intuition goes too far: among common available neighbors, each head has a ranking that does not depend on the receiving query.
We will calculate a four-node layer, inspect the exact mask, and then build a two-key example where moving the nonlinearity changes what rankings the model can express. The original method comes from Veličković and colleagues; the static-attention diagnosis and GATv2 construction come from Brody, Alon and Yahav.
Definitions and derivation
Let adjacency row i identify the senders j available to receiver i. Add the receiver itself to every neighborhood. Project row-vector features with W, then score a pair using a split attention vector:
The split form is the same as taking one linear score of concatenated projected features, followed by LeakyReLU. Apply softmax only over permitted neighbors, including self:
Set coefficients outside the neighborhood to zero. The example uses an identity output activation; the paper allows a following nonlinearity. Subtract each allowed row maximum before exponentiation for numerical stability. Each row sums to one, and an isolated node has self weight one. These are attention coefficients, not the row sums of symmetric GCN normalization.
Why is the ranking static? For fixed receiver i, its query contribution is one scalar added to every neighbor score. LeakyReLU with positive slopes is strictly increasing, and softmax preserves order:
Thus the order of any two common candidates depends only on their key terms. Query changes can still change the weights, especially when scores cross the nonlinearity’s kink. Different graph neighborhoods also allow different winners. The claim concerns ranking within one head over common available candidates; it does not say that every row or every head has identical weights.
GATv2 applies a learned vector after a vector-valued nonlinearity, rather than applying the nonlinearity after a scalar score. A concrete member of that family is s(q,k)=ℓ(q+k)−ℓ(−q+k), using the two projected coordinates (q+k,−q+k) and output vector (1,−1). For keys −1 and +1, query −1 gives scores (−0.4,−2), preferring −1; query +1 gives (0.4,2), preferring +1. Classic ℓ(q+k) prefers +1 for both queries. This is an expressivity counterexample, not a trained benchmark or a guarantee of higher task accuracy.
The original GAT combines heads by concatenation at intermediate layers and averaging in its described final prediction layer. Each classic head has its own static ranking. Multiple heads do not change the algebra of an individual score.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 program computes one fixed, dropout-free head and the separate two-key score comparison.
import numpy as np
def leaky(x):return np.where(np.asarray(x)>=0,x,.2*np.asarray(x))
def gat(adjacency,features,projection,left,right):
a,h,w,left,right = [np.asarray(v,dtype=float) for v in (adjacency,features,projection,left,right)]
if a.ndim != 2 or a.shape[0] != a.shape[1] or not 1 <= len(a) <= 16 or h.ndim != 2 or len(h) != len(a) or w.ndim != 2 or w.shape[0] != h.shape[1] or left.shape != (w.shape[1],) or right.shape != left.shape or not all(np.isfinite(v).all() for v in (a,h,w,left,right)) or not np.all((a==0)|(a==1)):
raise ValueError('Use a small binary adjacency and compatible finite features and attention parameters.')
mask = (a>0)|np.eye(len(a),dtype=bool) # row=receiver, column=sender
z = h@w; scores = leaky((z@left)[:,None]+(z@right)[None,:])
scores = np.where(mask,scores,-np.inf); shifted = scores-scores.max(axis=1,keepdims=True)
weights = np.exp(shifted); weights /= weights.sum(axis=1,keepdims=True)
return weights@z,weights
def example():
a = np.array([[0,1,0,0],[1,0,1,0],[0,1,0,0],[0,0,0,0]],dtype=float)
h = np.array([[1,0],[0,1],[1,1],[2,-1]],dtype=float); w = np.array([[1,.5],[-.5,1]])
return a,h,w,np.array([.5,-.25]),np.array([1.,.5])
def score_comparison(query,keys):
keys = np.asarray(keys,dtype=float)
classic = leaky(query+keys)
dynamic = leaky(query+keys)-leaky(-query+keys)
return classic,dynamic
if __name__ == '__main__':
output,weights = gat(*example())
print('attention rows',weights.round(9).tolist(),'outputs',output.round(9).tolist())
for query in (-1.,1.):
classic,dynamic = score_comparison(query,[-1.,1.])
print('query',query,'classic scores',classic.tolist(),'GATv2-style scores',dynamic.tolist())
print('isolated-node attention',weights[3].tolist())
Actual output:
attention rows [[0.777299861, 0.222700139, 0.0, 0.0], [0.411960884, 0.176078233, 0.411960884, 0.0], [0.0, 0.240489083, 0.759510917, 0.0], [0.0, 0.0, 0.0, 1.0]] outputs [[0.665949792, 0.611350069], [0.529902209, 1.0], [0.259510917, 1.379755458], [2.5, 0.0]]
query -1.0 classic scores [-0.4, 0.0] GATv2-style scores [-0.4, -2.0]
query 1.0 classic scores [0.0, 2.0] GATv2-style scores [0.4, 2.0]
isolated-node attention [0.0, 0.0, 0.0, 1.0]
Node 0 assigns about 0.77730 to itself and 0.22270 to node 1. Its output is approximately (0.66595,0.61135). Entries for unavailable nodes are exactly zero. Node 3 is isolated, so its output equals its own projected feature (2.5,0). The two-query experiment flips the preferred key only for the GATv2-style score.
An edge-based implementation projects nodes in O(N Fᵢₙ Fₒᵤₜ), then scores and aggregates in O((E+N)Fₒᵤₜ) per head, with an appropriate sparse layout. This teaching implementation materializes all N² scores and weights. Masking a dense matrix does not make its construction sparse.
When the method fails
An attention coefficient describes one computation conditional on features, parameters and graph support. It is not by itself a causal explanation of a prediction. Perturbation tests and task-specific evaluation are needed before using it as evidence about an important relationship.
This example accepts binary adjacency, possibly directed, and always includes self. Weighted or typed edges need an explicitly chosen score/message rule. Large degrees, neighbor sampling and head count change memory and evaluation conditions. The parameters here are illustrative and untrained; compare models under matched data splits and optimization conditions before interpreting accuracy differences.
Exercises with answers
- What is the attention of an isolated node here?
Answer 1: Its self coefficient is one, all others zero, so the output is its projected feature.
- Can classic GAT query changes alter weights without altering common-neighbor ranking?
Answer 2: Yes. LeakyReLU slope changes and normalization can alter magnitudes while the strictly monotone score preserves key order.
- Compute the dynamic scores for q=−1 and keys −1,+1.
Answer 3: They are −0.4 and −2, so the key −1 wins. For q=+1, scores 0.4 and 2 favor +1.
- Does a dense masked score matrix have edge-linear memory?
Answer 4: No. The N×N array is still allocated; edge-linear storage requires an edge-based representation.
Sources and next steps
The original GAT physical pages 3–4 define masked attention and head aggregation. Brody and colleagues’ physical page 4 proves the static ranking; page 5 explains the changed operator order in GATv2. Our numerical counterexample instantiates that operator family without copying training code. Return to graph convolutions to compare degree-based and feature-based weights, or graph neural networks to examine permutation symmetry and structural blind spots.
Make a prediction, then check
What remains query-independent in one classic additive GAT head?
Learning objectives
- Verify masked attention and node-relabeling symmetry.
- Explain static ranking and construct a query-dependent alternative.
Prerequisites & connections
Explore related knowledge →References
- Graph Attention Networks — arXiv v3
Petar Veličković et al. · 2018 - How Attentive are Graph Attention Networks? — arXiv v1
Shaked Brody; Uri Alon; Eran Yahav · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Bilingual SVGs generated with Matplotlib 3.9.1 from executed article functions: input-dependent state retention, regular-graph collisions and static/dynamic attention score rankings. Figures and samples are hash-bound. Parameters are illustrative, graph IDs are not features, and scores are not probabilities.
Source locations checked:
- Graph Attention Networks — arXiv v3 · Physical pages 3–4, Section 2.1 and Equations 4–6: neighborhood masks, normalized attention, intermediate concatenation and final averaging.
- How Attentive are Graph Attention Networks? — arXiv v1 · Physical page 4 Theorem 1: monotone additive score gives query-independent neighbor ranking; page 5 Equations 6–7: GATv2 operator order.
Related topics