Back to Graph Theory Series

Graph Attention Networks (GAT)

October 4, 2026 Updated November 1, 2026 Wasil Zafar 29 min read

GCN fixes neighbor weights from degree; GAT learns feature-dependent weights along existing edges. The graph chooses who may communicate, and attention chooses how strongly.

Contents

  1. A Short History
  2. Working Principle: Learned Attention Coefficients
  3. Mask, Softmax & Aggregate
  4. Multi-Head Attention
  5. Worked Example
  6. GAT vs. GCN
  7. Complexity Analysis
  8. Implementation
  9. Real-World Applications
  10. Can Attention Explain a Prediction?
  11. Exercises
  12. Limitations

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.

2017
GCN and GraphSAGE established two influential neighborhood-aggregation templates: fixed degree normalization and learned inductive aggregation.
2017
Attention Is All You Need accelerated interest in self-attention. GAT emerged in the same broader attention wave, but uses additive masked scoring on graph edges rather than Transformer's scaled dot products over token pairs.
2017–18
Petar Veličković and collaborators released Graph Attention Networks and presented the work at ICLR 2018, showing masked self-attentional layers on graph-structured data.
2021
Brody, Alon, and Yahav analyzed standard GAT's “static attention” limitation and introduced GATv2 by changing the scoring order to make rankings query-dependent.

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.
How GAT computes one directed edge score The target feature hi and neighbor feature hj pass through the same linear transform W. Their transformed vectors are concatenated, projected by attention vector a, and passed through LeakyReLU to produce edge logit eij. Scoring one allowed message j → i hᵢhⱼ WW CONCAT[Whᵢ ‖ Whⱼ] aᵀproject LeakyReLUeᵢⱼ The same W and a score every edge in this head; only endpoint features change.
Attention is directed: the logit for $j\to i$ need not equal the logit for $i\to j$. Self-loops are commonly added so a node may also attend to its own transformed feature.

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.

Three attention heads produce different neighborhood mixtures The same target neighborhood enters three independent attention heads. Each head emphasizes a different neighbor pattern. Their output vectors are concatenated for an intermediate layer or averaged for a final prediction. Independent heads can learn complementary mixtures same neighborhood iabc head 1focuses on neighbor a head 2mixes a and b head 3focuses on neighbor c COMBINE HEADSconcatenate: hidden layeraverage: output layer Heads are independent parameter sets; diversity is possible, not guaranteed.
Multi-head attention can stabilize optimization and represent several neighborhood mixtures. It does not guarantee that heads specialize or remain semantically interpretable.

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).$$

Softmax turns two logits into competing attention weights Neighbor one has logit two and receives attention weight 0.818. Neighbor two has logit 0.5 and receives weight 0.182. The thicker first arrow indicates its larger contribution to target i. From logits to a weighted message neighbor 1e = 2.0 · α = 0.818 neighbor 2e = 0.5 · α = 0.182 target i aggregate(1.364,1.636) The coefficients sum to one within target i's allowed neighborhood.
The coefficient controls the whole transformed vector, not each feature dimension independently. Another target can assign different normalized coefficients to the same two neighbors.

GAT vs. GCN

DimensionGCNGAT
Edge weight$1/\sqrt{\tilde d_i\tilde d_j}$ from topology$\alpha_{ij}$ from endpoint features and learned parameters
Normalizationsymmetric degree scalingdirected softmax over each target neighborhood
Parameters per layerfeature projection $W$$W$ plus attention vector $a$ per head
Graph requirementedges or normalized sparse adjacencyedges for masking and neighborhood grouping
Potential advantagesimple, stable, low overheadfeature-dependent neighbor mixtures

Complexity Analysis

For $n$ nodes, $m$ directed message edges including self-loops, input width $d$, output width $d'$, and $K$ heads:

PhaseOne headWhy
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.

import numpy as np

def masked_softmax_numpy(logits, mask):
    """Stable row softmax; False entries receive exactly zero weight."""
    logits = np.asarray(logits, dtype=float)
    mask = np.asarray(mask, dtype=bool)
    if logits.ndim != 2 or logits.shape != mask.shape:
        raise ValueError("logits and mask must be equal-size matrices")
    if not mask.any(axis=1).all():
        raise ValueError("every target needs at least one permitted source")

    permitted = np.where(mask, logits, -np.inf)
    row_max = permitted.max(axis=1, keepdims=True)
    exp_scores = np.where(mask, np.exp(permitted - row_max), 0.0)
    return exp_scores / exp_scores.sum(axis=1, keepdims=True)


example_logits = np.array([[2.0, 0.5, 99.0]])
example_mask = np.array([[True, True, False]])
print(masked_softmax_numpy(example_logits, example_mask))


import torch
import torch.nn as nn
import torch.nn.functional as F

class DenseGATHead(nn.Module):
    def __init__(self, in_features, out_features, alpha=0.2):
        super().__init__()
        self.proj = nn.Linear(in_features, out_features, bias=False)
        self.attn_target = nn.Parameter(torch.empty(out_features))
        self.attn_source = nn.Parameter(torch.empty(out_features))
        self.negative_slope = alpha
        nn.init.xavier_uniform_(self.proj.weight)
        nn.init.xavier_uniform_(self.attn_target.unsqueeze(0))
        nn.init.xavier_uniform_(self.attn_source.unsqueeze(0))

    def forward(self, h, adj):
        """
        h: (N, in_features)
        adj[i, j]: True when source j may send to target i
        """
        n = h.size(0)
        if adj.shape != (n, n):
            raise ValueError("adj must have shape (N, N)")
        mask = adj.to(device=h.device, dtype=torch.bool)
        mask = mask | torch.eye(n, dtype=torch.bool, device=h.device)

        z = self.proj(h)
        target_term = z @ self.attn_target
        source_term = z @ self.attn_source
        logits = F.leaky_relu(
            target_term[:, None] + source_term[None, :],
            negative_slope=self.negative_slope)
        logits = logits.masked_fill(~mask, float('-inf'))
        attention = torch.softmax(logits, dim=1)
        return F.elu(attention @ z), attention


class MultiHeadGAT(nn.Module):
    def __init__(self, in_features, out_features, num_heads=4):
        super(MultiHeadGAT, self).__init__()
        self.heads = nn.ModuleList([
            DenseGATHead(in_features, out_features) for _ in range(num_heads)
        ])

    def forward(self, h, adj):
        outputs = [head(h, adj)[0] for head in self.heads]
        return torch.cat(outputs, dim=-1)  # concatenate heads


h = torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.5]])
adj = torch.tensor([
    [0, 1, 0, 0],
    [1, 0, 1, 0],
    [0, 1, 0, 1],
    [0, 0, 1, 0]
], dtype=torch.bool)

gat_layer = DenseGATHead(in_features=2, out_features=4)
output, attn_weights = gat_layer(h, adj)
print("Output shape:", output.shape)
print("Attention row sums:", attn_weights.sum(dim=1))
print("Nonedge weights are zero:", bool((attn_weights[~(adj | torch.eye(4, dtype=torch.bool))] == 0).all()))

multi_head = MultiHeadGAT(in_features=2, out_features=4, num_heads=2)
multi_output = multi_head(h, adj)
print("\nMulti-Head GAT Output shape:", multi_output.shape)

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.

Architecture caveat: the GATv2 analysis shows that standard GAT computes a restricted static ranking of keys; GATv2 changes the score construction so neighbor ranking can depend more fully on the query node.

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.