Back to paper library
Paper notesarXiv 2017ICLR 2018

GAT

Some Neighbors Matter More

Original paper

Graph Attention Networks

Paper authors

Petar Veličković · Guillem Cucurull · Arantxa Casanova · Adriana Romero · Pietro Liò · Yoshua Bengio

Publication
ICLR 2018Conference
First submitted to arXiv
arXiv:1710.10903
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{graphlearninggat2017,
  title = {{Graph Attention Networks}},
  author = {Petar Veličković and Guillem Cucurull and Arantxa Casanova and Adriana Romero and Pietro Liò and Yoshua Bengio},
  year = {2017},
  eprint = {1710.10903},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1710.10903}
}
On this page

After attention proves itself in machine translation, the Transformer goes all in during June 2017, removing RNNs entirely.

Attention does something simple: each position looks at others, decides how much to take based on similarity, and combines their values. This is almost the same as aggregation in graph neural networks; the difference is where the weights come from.

GCN derives them from degrees: the share node ii receives from neighbor jj is fixed at 1/d~id~j1/\sqrt{\tilde d_i\tilde d_j}. Petar Veličković at Cambridge, together with Bengio and colleagues, wants features to determine these shares. The result is GAT.

Defining the Problem

The authors lay out the difficulties of the two existing approaches.

Spectral methods rely on Laplacian eigendecomposition, tying learned filters to that graph's eigenvectors. A graph with a different structure cannot directly reuse the model. GCN simplifies filtering to one-hop neighbors and is faster, but each neighbor's share within a neighborhood still depends only on degrees.

Spatial methods must handle varying neighborhood sizes. GraphSAGE samples a fixed number per node, so inference does not see the full neighborhood. Its best-performing LSTM aggregator also assumes an order, forcing random neighbor shuffling each time.

The desired layer should parallelize, handle nodes of different degrees, assign different importance within one neighborhood, and apply directly to unseen graphs without knowing the whole graph structure in advance.

Solving the Problem

One Attention Head

The input is node features hi∈RFh_i\in\mathbb{R}^F. First, all nodes share a linear transformation W∈RF′×FW\in\mathbb{R}^{F'\times F}. Then compute a score for each pair:

eij=a(Whi, Whj)e_{ij}=a\left(Wh_i,\ Wh_j\right)

eije_{ij} expresses the importance of node jj's features to node ii. In the most general form, every node could see all nodes, discarding the graph structure. The authors instead use masked attention, computing only over neighbors Ni\mathcal N_i, including self, then normalizing with softmax:

αij=softmaxj(eij)=exp⁡(eij)∑k∈Niexp⁡(eik)\alpha_{ij}=\mathrm{softmax}_j(e_{ij})=\frac{\exp(e_{ij})}{\sum_{k\in\mathcal N_i}\exp(e_{ik})}

Attention mechanism aa is a single feedforward layer with weight vector a∈R2F′a\in\mathbb{R}^{2F'}, followed by LeakyReLU with negative slope 0.2. Expanded:

αij=exp⁡(LeakyReLU(a⊤[Whi ∥ Whj]))∑k∈Niexp⁡(LeakyReLU(a⊤[Whi ∥ Whk]))\alpha_{ij}=\frac{\exp\left(\mathrm{LeakyReLU}\left(a^\top\left[Wh_i\,\|\,Wh_j\right]\right)\right)}{\sum_{k\in\mathcal N_i}\exp\left(\mathrm{LeakyReLU}\left(a^\top\left[Wh_i\,\|\,Wh_k\right]\right)\right)}

∥\| denotes concatenation. These coefficients finally weight the neighbors: hi′=σ(∑j∈NiαijWhj)h'_i=\sigma\left(\sum_{j\in\mathcal N_i}\alpha_{ij}Wh_j\right).

Run one head on a five-node graph. Split a⊤[Whi∥Whj]a^\top[Wh_i\|Wh_j] into a half depending only on ii and a half depending only on jj, computing the whole score matrix at once:

Python
import numpy as np
np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(1)

# 5 nodes: 0-1, 0-2, 1-2, 2-3, 3-4, with self-loops
A = np.eye(5)
for i, j in [(0, 1), (0, 2), (1, 2), (2, 3), (3, 4)]:
    A[i, j] = A[j, i] = 1

h = rng.normal(size=(5, 3))          # 3 features per node
W = rng.normal(size=(3, 2))          # Shared linear transformation to 2 output dimensions
a = rng.normal(size=4)               # Attention vector of length 2F' = 4

def leaky_relu(z, slope=0.2):
    return np.where(z > 0, z, slope * z)

def gat_head(h, W, a):
    Wh = h @ W                                             # (5, 2)
    e = leaky_relu((Wh @ a[:2])[:, None] + (Wh @ a[2:])[None, :])   # a^T [Wh_i || Wh_j], (5, 5)
    e = np.where(A > 0, e, -np.inf)                        # Mask: retain only neighbors
    alpha = np.exp(e - e.max(1, keepdims=True))
    alpha /= alpha.sum(1, keepdims=True)                   # Row-wise softmax over neighbors
    return alpha, alpha @ Wh

alpha, out = gat_head(h, W, a)
print("Attention coefficients:")
print(alpha)
print("Output:", out.shape)
Text
Attention coefficients:
[[0.52 0.26 0.23 0.   0.  ]
 [0.52 0.26 0.22 0.   0.  ]
 [0.45 0.23 0.19 0.14 0.  ]
 [0.   0.   0.51 0.26 0.23]
 [0.   0.   0.   0.58 0.42]]
Output: (5, 2)

Every row sums to 1, with zeros at non-neighbor positions. Nodes 0 and 1 both have three neighbors, to which GCN would assign similar shares. Here features determine the shares, and node 0 receives the largest.

Multiple Heads

As with the Transformer, multiple attention heads stabilize training. Each of KK heads has its own WkW^k and aka^k. Intermediate layers concatenate their independently computed outputs to dimension KF′KF'. At the final layer, concatenation would no longer be useful, so outputs are averaged before softmax or sigmoid:

hi′=∥k=1Kσ(∑j∈NiαijkWkhj),hi′=σ(1K∑k=1K∑j∈NiαijkWkhj)h'_i=\Big\|_{k=1}^{K}\sigma\left(\sum_{j\in\mathcal N_i}\alpha^k_{ij}W^kh_j\right),\qquad h'_i=\sigma\left(\frac1K\sum_{k=1}^K\sum_{j\in\mathcal N_i}\alpha^k_{ij}W^kh_j\right)
Figure 1 of the paper: on the left, Wh_i and Wh_j are concatenated, dotted with a, passed through LeakyReLU, then softmaxed over j to obtain α_ij. On the right, node 1 applies three-head attention to six neighbors; three line styles represent the heads, whose outputs are concatenated or averaged into h'_1.
Figure 1 from Veličković et al., taken from PDF page 4. The original caption is omitted.

Cost and Properties

A single head costs O(∣V∣FF′+∣E∣F′)O(|V|FF'+|E|F'), the same order as GCN. Attention can be computed in parallel over edges, and outputs in parallel over nodes, without eigendecomposition. Multiple heads multiply storage and parameters by KK, but run independently.

The attention mechanism is shared across edges and needs no advance knowledge of the entire graph. Directed graphs work by omitting αij\alpha_{ij} when j→ij\rightarrow i is absent; unseen graphs can use the model directly. Compared with GraphSAGE, GAT examines the full neighborhood and assumes no neighbor order.

Discussion

Experimental Setup

Transductive experiments use Cora, Citeseer and Pubmed with GCN's splits and 20 labels per class. The two-layer model has 8 first-layer heads of 8 dimensions each, 64 in total, followed by ELU; the second layer has one head outputting the classes. Regularization is heavy because training sets are small: L2 coefficient 0.0005 and dropout 0.6, applied even to attention coefficients. The authors note that attention dropout effectively gives each node a randomly sampled neighborhood every iteration. Pubmed has only 60 training nodes, so its output layer uses 8 heads and L2 increases to 0.001.

Inductive experiments use PPI, training on 20 graphs, validating on 2 and testing on 2 entirely unseen graphs. The three-layer model uses 4 heads of 256 dimensions in each of the first two layers; the final layer averages 6 heads of 121 dimensions and applies sigmoid for multilabel classification. With enough data, neither L2 nor dropout is used; intermediate layers add skip connections.

Main Results

MethodCoraCiteseerPubmed
GCN81.5%70.3%79.0%
GCN-64*81.4 ± 0.5%70.9 ± 0.5%79.0 ± 0.3%
GAT83.0 ± 0.7%72.5 ± 0.7%79.0 ± 0.3%

GCN-64* widens GCN's hidden layer to GAT's 64 dimensions and reports the better result after trying ReLU and ELU, for a fairer assessment of attention itself. GAT exceeds GCN-64* by 1.6 percentage points on both Cora and Citeseer and ties on Pubmed.

The gap is much larger on PPI:

MethodPPI micro-F1
GraphSAGE-LSTM (original paper)0.612
GraphSAGE* (architecture tuned by the authors)0.768
Const-GAT0.934 ± 0.006
GAT0.973 ± 0.002

Read this table in two steps. Const-GAT keeps the architecture but replaces attention with a constant, weighting all neighbors equally, close to GCN-style aggregation. The jump from 0.768 to 0.934 mostly comes from full neighborhoods and a larger architecture; the rise from 0.934 to 0.973 is attention's own 3.9-percentage-point contribution.

What Did It Learn?

The authors visualize a pretrained model's first-layer outputs on Cora with t-SNE. Seven classes form clear clusters in two dimensions, with edge widths showing attention averaged over eight heads. They caution that properly interpreting these coefficients requires more domain knowledge of the dataset, leaving that to future work.

The Authors' Own Limitations

  • Sparse GAT can make storage linear in nodes and edges, but the frameworks of the time support only sparse multiplication of two-dimensional tensors, limiting batches of multiple graphs.
  • Depending on graph regularity, GPUs may offer little advantage over CPUs for these sparse operations.
  • Receptive-field size is limited by depth, as in GCN.
  • Parallel computation over all edges repeats substantial work where neighborhoods overlap heavily.

Static Attention

In 2021, Brody, Alon and Yahav at Technion publish “How Attentive are Graph Attention Networks?”, identifying a structural limitation in GAT attention. GATv2 abstract

Look back at how the score is computed. a⊤[Whi∥Whj]a^\top[Wh_i\|Wh_j] splits into “a term that depends only on ii” plus “a term that depends only on jj.” LeakyReLU and softmax are both monotonic, so each node's ranking of candidate neighbors is determined by the jj term alone, regardless of the query node ii. On a fully connected graph, every node ranks the candidates in exactly the same order; only the proportions differ. On the original graph, the mask restricts each node to its own neighbors, so each seems to have its own preferences, but whenever two nodes' candidate lists overlap, their rankings agree.

Brody et al. call this static attention. Their fix changes the operation order: multiply [hi∥hj][h_i\|h_j] by weights, apply LeakyReLU, then dot with aa. Placing the nonlinearity in the middle lets rankings depend on the query node. This version, GATv2, beats GAT on 11 benchmarks including OGB with comparable parameter counts.

Conclusion

GAT brings attention to graph neural networks, giving neighbors different, learnable, feature-dependent importance within the same neighborhood. Masking confines attention to neighbors and preserves graph structure; multiple heads stabilize training.

On citation networks it adds 1 to 2 percentage points over GCN. On PPI, a comparison within the same architecture clearly measures attention's contribution.

Remember to apply dropout to attention coefficients: the paper relies on this for small datasets. If your task needs different nodes to prefer different neighbors, compare with GATv2.

Remove the mask and let every node see every other node, and you have Transformer attention. Later Graph Transformers address precisely the graph structure lost at that step.