This is a PyTorch implementation of the paper Graph Attention Networks.

GATs work on graph data. A graph consists of nodes and edges connecting nodes. For example, in Cora dataset the nodes are research papers and the edges are citations that connect the papers.

GAT uses masked self-attention, kind of similar to transformers. GAT consists of graph attention layers stacked on top of each other. Each graph attention layer gets node embeddings as inputs and outputs transformed embeddings. The node embeddings pay attention to the embeddings of other nodes it's connected to. The details of graph attention layers are included alongside the implementation.

Here is the training code for training a two-layer GAT on Cora dataset.

```
28import torch
29from torch import nn
30
31from labml_helpers.module import Module
```

This is a single graph attention layer. A GAT is made up of multiple such layers.

It takes $h={h_{1} ,h_{2} ,…,h_{N} }$, where $h_{i} ∈R_{F}$ as input and outputs $h_{′}={h_{1} ,h_{2} ,…,h_{N} }$, where $h_{i} ∈R_{F_{′}}$.

`34class GraphAttentionLayer(Module):`

`in_features`

, $F$, is the number of input features per node`out_features`

, $F_{′}$, is the number of output features per node`n_heads`

, $K$, is the number of attention heads`is_concat`

whether the multi-head results should be concatenated or averaged`dropout`

is the dropout probability`leaky_relu_negative_slope`

is the negative slope for leaky relu activation

```
48 def __init__(self, in_features: int, out_features: int, n_heads: int,
49 is_concat: bool = True,
50 dropout: float = 0.6,
51 leaky_relu_negative_slope: float = 0.2):
```

```
60 super().__init__()
61
62 self.is_concat = is_concat
63 self.n_heads = n_heads
```

Calculate the number of dimensions per head

```
66 if is_concat:
67 assert out_features % n_heads == 0
```

If we are concatenating the multiple heads

```
69 self.n_hidden = out_features // n_heads
70 else:
```

If we are averaging the multiple heads

`72 self.n_hidden = out_features`

Linear layer for initial transformation; i.e. to transform the node embeddings before self-attention

`76 self.linear = nn.Linear(in_features, self.n_hidden * n_heads, bias=False)`

Linear layer to compute attention score $e_{ij}$

`78 self.attn = nn.Linear(self.n_hidden * 2, 1, bias=False)`

The activation for attention score $e_{ij}$

`80 self.activation = nn.LeakyReLU(negative_slope=leaky_relu_negative_slope)`

Softmax to compute attention $α_{ij}$

`82 self.softmax = nn.Softmax(dim=1)`

Dropout layer to be applied for attention

`84 self.dropout = nn.Dropout(dropout)`

`h`

, $h$ is the input node embeddings of shape`[n_nodes, in_features]`

.`adj_mat`

is the adjacency matrix of shape`[n_nodes, n_nodes, n_heads]`

. We use shape`[n_nodes, n_nodes, 1]`

since the adjacency is the same for each head.

Adjacency matrix represent the edges (or connections) among nodes. `adj_mat[i][j]`

is `True`

if there is an edge from node `i`

to node `j`

.

`86 def forward(self, h: torch.Tensor, adj_mat: torch.Tensor):`

Number of nodes

`97 n_nodes = h.shape[0]`

The initial transformation, $g_{i} =W_{k}h_{i} $ for each head. We do single linear transformation and then split it up for each head.

`102 g = self.linear(h).view(n_nodes, self.n_heads, self.n_hidden)`

We calculate these for each head $k$. *We have omitted $⋅_{k}$ for simplicity*.

$e_{ij}=a(Wh_{i} ,Wh_{j} )=a(g_{i} ,g_{j} )$

$e_{ij}$ is the attention score (importance) from node $j$ to node $i$. We calculate this for each head.

$a$ is the attention mechanism, that calculates the attention score. The paper concatenates $g_{i} $, $g_{j} $ and does a linear transformation with a weight vector $a∈R_{2F_{′}}$ followed by a $LeakyReLU$.

$e_{ij}=LeakyReLU(a_{⊤}[g_{i} ∥g_{j} ])$

First we calculate $[g_{i} ∥g_{j} ]$ for all pairs of $i,j$.

`g_repeat`

gets ${g_{1} ,g_{2} ,…,g_{N} ,g_{1} ,g_{2} ,…,g_{N} ,...}$ where each node embedding is repeated `n_nodes`

times.

`133 g_repeat = g.repeat(n_nodes, 1, 1)`

`g_repeat_interleave`

gets ${g_{1} ,g_{1} ,…,g_{1} ,g_{2} ,g_{2} ,…,g_{2} ,...}$ where each node embedding is repeated `n_nodes`

times.

`138 g_repeat_interleave = g.repeat_interleave(n_nodes, dim=0)`

Now we concatenate to get ${g_{1} ∥g_{1} ,g_{1} ∥g_{2} ,…,g_{1} ∥g_{N} ,g_{2} ∥g_{1} ,g_{2} ∥g_{2} ,…,g_{2} ∥g_{N} ,...}$

`146 g_concat = torch.cat([g_repeat_interleave, g_repeat], dim=-1)`

Reshape so that `g_concat[i, j]`

is $g_{i} ∥g_{j} $

`148 g_concat = g_concat.view(n_nodes, n_nodes, self.n_heads, 2 * self.n_hidden)`

Calculate $e_{ij}=LeakyReLU(a_{⊤}[g_{i} ∥g_{j} ])$ `e`

is of shape `[n_nodes, n_nodes, n_heads, 1]`

`156 e = self.activation(self.attn(g_concat))`

Remove the last dimension of size `1`

`158 e = e.squeeze(-1)`

The adjacency matrix should have shape `[n_nodes, n_nodes, n_heads]`

or`[n_nodes, n_nodes, 1]`

```
162 assert adj_mat.shape[0] == 1 or adj_mat.shape[0] == n_nodes
163 assert adj_mat.shape[1] == 1 or adj_mat.shape[1] == n_nodes
164 assert adj_mat.shape[2] == 1 or adj_mat.shape[2] == self.n_heads
```

Mask $e_{ij}$ based on adjacency matrix. $e_{ij}$ is set to $−∞$ if there is no edge from $i$ to $j$.

`167 e = e.masked_fill(adj_mat == 0, float('-inf'))`

We then normalize attention scores (or coefficients) $α_{ij}=softmax_{j}(e_{ij})=∑_{k∈N_{i}}exp(e_{ik})exp(e_{ij}) $

where $N_{i}$ is the set of nodes connected to $i$.

We do this by setting unconnected $e_{ij}$ to $−∞$ which makes $exp(e_{ij})∼0$ for unconnected pairs.

`177 a = self.softmax(e)`

Apply dropout regularization

`180 a = self.dropout(a)`

Calculate final output for each head $h_{i} =j∈N_{i}∑ α_{ij}g_{j} $

*Note:* The paper includes the final activation $σ$ in $h_{i} $ We have omitted this from the Graph Attention Layer implementation and use it on the GAT model to match with how other PyTorch modules are defined - activation as a separate layer.

`189 attn_res = torch.einsum('ijh,jhf->ihf', a, g)`

Concatenate the heads

`192 if self.is_concat:`

$h_{i} =∥∥ _{k=1}h_{i} $

`194 return attn_res.reshape(n_nodes, self.n_heads * self.n_hidden)`

Take the mean of the heads

`196 else:`

$h_{i} =K1 k=1∑K h_{i} $

`198 return attn_res.mean(dim=1)`