AI Logic

Architectures

Graph Attention Network (GAT)

Updated:

GAT architecture. Left: the overall flow from node features through two GAT layers and a softmax to output classes. Right: how, in one head, node i computes an attention weight for each neighbor and updates its features with the weighted sum

Background and overview

GAT (Graph Attention Network) is a graph neural network that computes the weights for aggregating features from neighboring nodes with attention over the node features. It was proposed by VeličkoviΔ‡ et al. in 2017 and presented at ICLR 2018.

In GCN, the weights for aggregating from neighbors were determined only by the "degree" (the number of neighbors). If a node has four neighbors, each one is averaged with roughly the same weight. In real graphs, however, neighbors differ in importance. In a citation network, for example, some citations point to papers in the same field, while others point in passing to papers in other fields.

GAT computes these weights from "the combination of a node's own features and its neighbor's features." It applies the idea of attention, used for sequence data, only to a node's neighbors in the graph.

As an analogy, GCN "averages the opinions of all friends with equal weight," while GAT "listens more closely, topic by topic, to the friends who seem most knowledgeable." Whom to listen to more closely is computed each time from one's own features and the other person's.

GAT matched or exceeded GCN's accuracy on three citation-network datasets, and on node classification in separate graphs not seen during training (protein-protein interactions), it greatly outperformed GraphSAGE.

Theory: the graph attention layer

A GAT layer takes node features {hβƒ—1,…,hβƒ—N}\{\vec{h}_1, \dots, \vec{h}_N\} (each FF-dimensional) and outputs new features {hβƒ—1β€²,…,hβƒ—Nβ€²}\{\vec{h}'_1, \dots, \vec{h}'_N\} (each Fβ€²F'-dimensional). For each node ii, it computes the following in order (Section 2.1 of the paper).

  1. Shared linear transform: apply the same weight W∈RFβ€²Γ—F\mathbf{W} \in \mathbb{R}^{F' \times F} to every node.
  2. Compute scores: for each neighbor jj, concatenate Whβƒ—i\mathbf{W}\vec{h}_i and Whβƒ—j\mathbf{W}\vec{h}_j, take the inner product with a weight vector aβƒ—βˆˆR2Fβ€²\vec{\mathbf{a}} \in \mathbb{R}^{2F'}, and pass it through Leaky ReLU (negative slope 0.2). This is the score eije_{ij}, representing "how important node jj's features are to ii."
  3. Normalize over neighbors only: apply a softmax to the scores over ii's neighborhood Ni\mathcal{N}_i (including ii itself), giving weights Ξ±ij\alpha_{ij} that sum to 1.
  4. Take the weighted sum: take the weighted sum of Wh⃗j\mathbf{W}\vec{h}_j with αij\alpha_{ij} and pass it through an activation function σ\sigma.

Steps 2–3 written as a single formula are as follows (Eq. 3 of the paper). βˆ₯\| denotes concatenation.

Ξ±ij=exp⁑(LeakyReLU(aβƒ—βŠ€[Whβƒ—i βˆ₯ Whβƒ—j]))βˆ‘k∈Niexp⁑(LeakyReLU(aβƒ—βŠ€[Whβƒ—i βˆ₯ Whβƒ—k]))\alpha_{ij} = \frac{\exp\left(\mathrm{LeakyReLU}\left(\vec{\mathbf{a}}^\top [\mathbf{W}\vec{h}_i \,\|\, \mathbf{W}\vec{h}_j]\right)\right)}{\sum_{k \in \mathcal{N}_i} \exp\left(\mathrm{LeakyReLU}\left(\vec{\mathbf{a}}^\top [\mathbf{W}\vec{h}_i \,\|\, \mathbf{W}\vec{h}_k]\right)\right)}

Step 4 is the following (Eq. 4 of the paper).

hβƒ—iβ€²=Οƒ(βˆ‘j∈NiΞ±ijWhβƒ—j)\vec{h}'_i = \sigma\left(\sum_{j \in \mathcal{N}_i} \alpha_{ij} \mathbf{W} \vec{h}_j\right)

Computing scores only over neighbors is how GAT uses the graph structure. The paper calls this masked attention, because computing scores over every pair of nodes would lose the information in the graph structure.

The score is computed by a single-layer network that applies the weight a⃗\vec{\mathbf{a}} to the concatenated vector, and the paper describes it as close to Bahdanau et al.'s additive attention. The GAT framework itself, however, does not depend on the type of attention, and the score can be replaced with others such as scaled dot-product attention.

Multi-head attention

To stabilize learning, KK independent attention mechanisms (heads) are run side by side, as in the Transformer (multi-head attention). Each head has its own Wk\mathbf{W}^k and a⃗k\vec{\mathbf{a}}^k, and the results are concatenated (Eq. 5 of the paper). The output is KF′KF'-dimensional.

hβƒ—iβ€²=βˆ₯k=1KΟƒ(βˆ‘j∈NiΞ±ijkWkhβƒ—j)\vec{h}'_i = \Big\Vert_{k=1}^{K} \sigma\left(\sum_{j \in \mathcal{N}_i} \alpha_{ij}^k \mathbf{W}^k \vec{h}_j\right)

In the final (prediction) layer, concatenation is not meaningful, so the results of the KK heads are averaged before applying a softmax or the sigmoid function (Eq. 6 of the paper).

Architecture and training settings

The paper used two configurations, depending on the task (Section 3.3 of the paper).

Node classification within a single graph (Cora, Citeseer, Pubmed)

  1. Layer 1: 8 heads each compute 8-dimensional features, which are concatenated into 64 dimensions and then passed through ELU.
  2. Layer 2 (prediction): a single head computes features of dimension CC (the number of classes) and applies a softmax.

Because the training data has only 20 nodes per class, fairly strong regularization is applied.

ItemValue
Dropoutp=0.6p = 0.6, applied to the inputs of both layers and to the normalized attention weights Ξ±ij\alpha_{ij}
L2 regularization (Weight Decay)Ξ»=0.0005\lambda = 0.0005
OptimizerAdam, learning rate 0.005 (0.01 for Pubmed)
StoppingStop if validation loss and accuracy do not improve for 100 epochs (Early Stopping)
Weight initializationXavier (Glorot) initialization

On Pubmed, which has only 60 training nodes, layer 2 also averages 8 heads, and L2 regularization is strengthened to Ξ»=0.001\lambda = 0.001.

Applying dropout to the attention weights Ξ±ij\alpha_{ij} means that in each training iteration, every node aggregates features from a randomly thinned neighborhood. The model learns to predict even when some neighbors are missing, which helps suppress overfitting.

Node classification on separate graphs (PPI)

  1. Layers 1 and 2: 4 heads each compute 256-dimensional features, which are concatenated (1,024 dimensions) and passed through ELU.
  2. Layer 3 (prediction): 6 heads each compute 121-dimensional features (the number of labels), which are averaged and passed through the sigmoid function (since a node can have multiple labels).

With enough training data, L2 regularization and dropout are not used, and skip connections like those in ResNet are added to the intermediate layer. The batch size is 2 graphs.

How it works and why it is effective

There are three main reasons GAT outperforms GCN.

  • It can assign different weights to each neighbor: GCN's weights are determined only by degree, but GAT computes them from node features. It can weight neighbors of the same class heavily and weakly related neighbors lightly, which increases expressive power. In the paper's PPI experiment, Const-GAT, which uses the same configuration but makes all attention weights equal (an aggregation close to GCN's), reached a micro-F1 of 0.934, versus 0.973 for GAT.
  • It does not need to know the whole graph structure in advance: GCN builds a normalized adjacency matrix from the whole graph, but GAT's weights can be computed from the features of just the two nodes at the ends of each edge. It can therefore be applied as is to graphs not seen during training. And since it simply skips computing Ξ±ij\alpha_{ij} when there is no edge jβ†’ij \to i, it also works on directed graphs.
  • It uses all neighbors and assumes no ordering: GraphSAGE samples a fixed number of neighbors, and its LSTM aggregator treats neighbors as ordered. GAT uses all neighbors, and since it is a softmax-weighted sum, it does not depend on their order.

Complexity

The complexity of a single head is O(∣V∣FFβ€²+∣E∣Fβ€²)O(|\mathcal{V}| F F' + |\mathcal{E}| F') (where ∣V∣|\mathcal{V}| is the number of nodes and ∣E∣|\mathcal{E}| the number of edges), about the same as GCN. Scores can be computed in parallel across all edges, and outputs in parallel across all nodes. No expensive matrix operations such as eigendecomposition are needed. Using KK heads multiplies memory and parameters by KK, but each head can be computed independently in parallel.

The paper notes that inspecting the learned attention weights Ξ±ij\alpha_{ij} shows "which neighbors the prediction relied on," so, like attention in machine translation, they may help interpret predictions.

Experimental results

Node classification within a single graph (Table 2 of the paper; accuracy %)

Models were trained with labels for only 20 nodes per class and evaluated on 1,000 nodes. GAT results are the mean and standard deviation over 100 runs.

MethodCoraCiteseerPubmed
MLP (no graph)55.146.571.4
DeepWalk67.243.265.3
Planetoid75.764.777.2
Chebyshev polynomials (Defferrard et al.)81.269.874.4
GCN81.570.379.0
MoNet81.7 Β± 0.5β€”78.8 Β± 0.3
GCN-64 (hidden layer set to 64 dimensions, same as GAT)81.4 Β± 0.570.9 Β± 0.579.0 Β± 0.3
GAT83.0 Β± 0.772.5 Β± 0.779.0 Β± 0.3

Even compared with GCN-64, which has the same hidden size, GAT was 1.6 points higher on Cora and 1.6 points higher on Citeseer. On Pubmed they were equal.

Node classification on graphs not seen during training (Table 3 of the paper; PPI, micro-F1)

Of 24 protein-protein interaction graphs from various human tissues, 20 were used for training, and evaluation was on 2 graphs not used in training. GAT results are the mean over 10 runs.

Methodmicro-F1
MLP0.422
GraphSAGE-GCN0.500
GraphSAGE-mean0.598
GraphSAGE-LSTM0.612
GraphSAGE-pool0.600
GraphSAGE (best result across configurations)0.768
Const-GAT (GAT with all weights equal)0.934 Β± 0.006
GAT0.973 Β± 0.002

GAT was more than 0.2 higher than the best GraphSAGE configuration. The paper attributes this to being able to look at all neighbors without sampling, and states that the gap to Const-GAT (0.039) directly demonstrates the benefit of assigning different weights to each neighbor.

Practical considerations

Keep the following points in mind when using GAT.

  • Use strong regularization on small data: in the paper's citation-network settings, dropout p=0.6p = 0.6 is applied to both the inputs and the attention weights, along with L2 regularization. Weakening regularization when labels are scarce makes overfitting more likely.
  • The number of layers sets the receptive range: as with GCN, each layer sees only one hop further, so the number of layers caps how far the model can see. When going deeper, add skip connections as in the paper's PPI experiment.
  • Sparse matrix operations are needed: a naive implementation creates an NΓ—NN \times N score matrix, which runs out of memory on large graphs. The paper's authors also built a version using sparse matrix operations, but note that framework limitations at the time restricted batching of multiple graphs. In graphs with heavily overlapping neighborhoods, per-edge parallel computation can also involve a lot of redundant work.
  • Where to get it in PyTorch: it is not in core PyTorch. Besides writing it as in the implementation example below, you can use GATConv in PyTorch Geometric (heads sets the number of heads, concat chooses concatenation or averaging) or GATConv in DGL.

Because GAT's attention takes the softmax within the neighborhood, the weights sum to 1 even for nodes with different numbers of neighbors. In exchange, the weights express only "which neighbors are relatively important," and information about the number of neighbors itself is lost. For example, if a node and all its neighbors have identical features, the weighted sum is the same whether there are 2 neighbors or 3, regardless of how the weights are assigned. For tasks that need to distinguish the number of neighbors or structural differences (such as molecule classification), also compare models such as GIN, which aggregates with a sum.

Comparison with other methods

Comparing four representative graph neural network methods from the same perspectives gives the following.

MethodHow neighbor features are aggregatedPer-neighbor weightsNeighbors usedUse on new graphs
GCNDegree-normalized sumDetermined by degree (not learned)All neighborsThe original paper evaluated only within a single graph
GraphSAGEAggregate with mean, LSTM, or pooling, then concatenateDetermined by the aggregatorA fixed number, sampledPossible
GATAttention-weighted sumLearned from featuresAll neighborsPossible
GINSum, then pass through an MLPAll 1 (just add)All neighborsPossible (mainly whole-graph classification)

Rough guidelines for choosing:

  • Node classification where neighbors likely differ in importance: GAT is a good fit. It matched or exceeded GCN on citation networks and greatly outperformed GraphSAGE on separate graphs.
  • When you just want a simple, fast baseline: start with GCN. Its formula is simple and it has relatively few hyperparameters.
  • Huge graphs with nodes that have very many neighbors: GAT uses all neighbors and therefore needs more memory, so GraphSAGE, which samples neighbors, is easier to handle.
  • To distinguish the shapes of whole graphs: GIN is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# A small implementation following Eqs. 3–6 of the paper (core PyTorch has no GAT layer)
# For clarity, the adjacency matrix is held as a dense matrix (for large graphs, use a sparse implementation or PyTorch Geometric's GATConv)


class GATLayer(nn.Module):
  def __init__(self, in_dim, out_dim, heads=8, concat=True, dropout=0.6):
    super().__init__()
    self.heads, self.out_dim, self.concat, self.dropout = heads, out_dim, concat, dropout
    self.W = nn.Linear(in_dim, heads * out_dim, bias=False)       # W^k of all heads combined
    self.a_src = nn.Parameter(torch.empty(heads, out_dim))        # a = [a_src β€– a_dst] (2Fβ€² dims)
    self.a_dst = nn.Parameter(torch.empty(heads, out_dim))
    nn.init.xavier_uniform_(self.W.weight)
    nn.init.xavier_uniform_(self.a_src)
    nn.init.xavier_uniform_(self.a_dst)

  def forward(self, h, adj):
    # h: [N, in_dim], adj: [N, N] (1 = edge; include self-loops)
    N = h.size(0)
    h = F.dropout(h, self.dropout, self.training)                  # dropout on the input
    wh = self.W(h).view(N, self.heads, self.out_dim)               # W h  [N, K, Fβ€²]
    # Compute aα΅€[W h_i β€– W h_j] = a_dstα΅€ W h_i + a_srcα΅€ W h_j for all pairs at once
    e = (wh * self.a_dst).sum(-1).unsqueeze(1) + (wh * self.a_src).sum(-1).unsqueeze(0)  # [N(i), N(j), K]
    e = F.leaky_relu(e, negative_slope=0.2)
    e = e.masked_fill(adj.unsqueeze(-1) == 0, float("-inf"))      # skip pairs that are not neighbors (mask)
    alpha = torch.softmax(e, dim=1)                                # normalize over neighbors j
    alpha = F.dropout(alpha, self.dropout, self.training)          # dropout on the attention weights
    out = torch.einsum("ijk,jkf->ikf", alpha, wh)                  # Ξ£_j Ξ±_ij W h_j  [N, K, Fβ€²]
    if self.concat:
      return out.reshape(N, self.heads * self.out_dim)             # concatenate heads (Eq. 5; Οƒ is applied outside)
    return out.mean(dim=1)                                         # the last layer averages heads (Eq. 6)


class GAT(nn.Module):
  # The paper's Cora/Citeseer setting: 8 heads Γ— 8 features β†’ ELU β†’ 1 head with the number of classes
  def __init__(self, in_dim, num_classes, hidden=8, heads=8):
    super().__init__()
    self.layer1 = GATLayer(in_dim, hidden, heads=heads, concat=True)
    self.layer2 = GATLayer(hidden * heads, num_classes, heads=1, concat=False)

  def forward(self, x, adj):
    x = F.elu(self.layer1(x, adj))
    return self.layer2(x, adj)  # the softmax is computed inside the loss function


# Usage (example with a small random graph)
N, in_dim, num_classes = 500, 100, 7
x = torch.rand(N, in_dim)
adj = (torch.rand(N, N) < 0.01).float()
adj = ((adj + adj.T + torch.eye(N)) > 0).float()  # make edges undirected and add self-loops (N_i includes i itself)
labels = torch.randint(0, num_classes, (N,))
train_mask = torch.zeros(N, dtype=torch.bool)
train_mask[:140] = True

model = GAT(in_dim, num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.005, weight_decay=5e-4)
for epoch in range(200):
  model.train()   # dropout is active
  optimizer.zero_grad()
  loss = F.cross_entropy(model(x, adj)[train_mask], labels[train_mask])
  loss.backward()
  optimizer.step()

model.eval()      # dropout is off and all neighbors are used
with torch.no_grad():
  pred = model(x, adj).argmax(dim=1)

FAQ

Q. How does GAT's attention differ from Transformer self-attention?
A.

The main difference is that scores are computed only against the node's neighbors in the graph (masked attention). Transformer self-attention computes scores between every pair of positions in a sequence, whereas GAT does so only for nodes connected by an edge (including itself). The score formula also differs: the Transformer uses the inner product of queries and keys, while GAT uses an additive formula that concatenates the two nodes' features, applies the weight a⃗\vec{\mathbf{a}}, and passes the result through Leaky ReLU.

Q. How many heads should I use?
A.

In the paper, the first layer used 8 heads (8 dimensions each) for the citation networks and 4 heads (256 dimensions each) for PPI. More heads tend to stabilize training, but memory and parameters grow in proportion to the number of heads. A good starting point is 4–8 heads, as in the paper.

Q. Is GAT always better than GCN?
A.

Not always. On Pubmed in the paper, GAT and GCN had the same accuracy of 79.0%. On graphs where neighbors do not differ much in importance, the advantage of weighting with attention shrinks. GAT also needs more computation and memory than GCN, so it is a good idea to start with GCN as a baseline and compare.

References

  1. VeličkoviΔ‡, P., Cucurull, G., Casanova, A., Romero, A., LiΓ², P., & Bengio, Y. (2018). Graph Attention Networks. ICLR 2018. arXiv:1710.10903.
  2. PetarV-/GAT (TensorFlow implementation by the authors).
  3. Kipf, T. N., & Welling, M. (2017). Semi-Supervised Classification with Graph Convolutional Networks. ICLR 2017. arXiv:1609.02907.
  4. Hamilton, W. L., Ying, R., & Leskovec, J. (2017). Inductive Representation Learning on Large Graphs. NIPS 2017. arXiv:1706.02216.
  5. Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015. arXiv:1409.0473.
  6. Vaswani, A., et al. (2017). Attention Is All You Need. NIPS 2017. arXiv:1706.03762.
  7. Xu, K., Hu, W., Leskovec, J., & Jegelka, S. (2019). How Powerful are Graph Neural Networks? ICLR 2019. arXiv:1810.00826.