{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "

Understanding Graph Attention Networks (GAT)

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "This is 4th in the series of blogs *Explained: Graph Representation Learning*. Let's dive right in, assuming you have read the first three. GAT (Graph Attention Network), is a novel neural network architectures that operate on graph-structured data, leveraging masked self-attentional layers to address the shortcomings of prior methods based on graph convolutions or their approximations. By stacking layers in which nodes are able to attend over their neighborhoods’ features, the method enables (implicitly) specifying different weights to different nodes in a neighborhood, without requiring any kind of costly matrix operation (such as inversion) or depending on knowing the graph structure upfront. In this way, GAT addresses several key challenges of spectral-based graph neural networks simultaneously, and make the model readily applicable to inductive as well as transductive problems.\n", "\n", "Analyzing and Visualizing the learned attentional weights also lead to a more interpretable model in terms of importance of neighbors." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But before getting into the meat of this method, I want you to be familiar and thorough with the Attention Mechanism, because we'll be building GATs on the concept of Self Attention and Multi-Head Attention introduced by Vaswani et al.\n", "If not, you may read this blog, [The Illustrated Transformer](http://jalammar.github.io/illustrated-transformer/) by Jay Alamar.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Can we do better than GCNs?

\n", "\n", "\n", "From Graph Convolutional Network (GCN), we learnt that combining local graph structure and node-level features yields good performance on node classification task. However, the way GCN aggregates messages is structure-dependent, which may hurt its generalizability.\n", "\n", "The fundamental novelty that GAT brings to the table is how the information from the one-hop neighborhood is aggregated. For GCN, a graph convolution operation produces the normalized sum of neighbors' node features as follows:\n", "\n", "$$h_i^{(l+1)}=\\sigma\\left(\\sum_{j\\in \\mathcal{N}(i)} {\\frac{1}{c_{ij}} W^{(l)}h^{(l)}_j}\\right)$$\n", "\n", "where $\\mathcal{N}(i)$ is the set of its one-hop neighbors (to include $v_{i}$ in the set, we simply added a self-loop to each node), $c_{ij}=\\sqrt{|\\mathcal{N}(i)|}\\sqrt{|\\mathcal{N}(j)|}$ is a normalization constant based on graph structure, $\\sigma$ is an activation function (GCN uses ReLU), and $W^{l}$ is a shared weight matrix for node-wise feature transformation.\n", "\n", "GAT introduces the attention mechanism as a substitute for the statically normalized convolution operation. The figure below clearly illustrates the key difference.\n", "\n", "\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "

How does the GAT layer work?

\n", "\n", "The particular attentional setup utilized by GAT closely follows the work of `Bahdanau et al. (2015)` i.e *Additive Attention*, but the framework is agnostic to the particular choice of attention mechanism.\n", "\n", "The input to the layer is a set of node features, $\\mathbf{h} = \\{\\vec{h}_1,\\vec{h}_2,...,\\vec{h}_N\\}, \\vec{h}_i ∈ \\mathbb{R}^{F}$ , where $N$ is the\n", "number of nodes, and $F$ is the number of features in each node. The layer produces a new set of node\n", "features (of potentially different cardinality $F'$ ), $\\mathbf{h} = \\{\\vec{h'}_1,\\vec{h'}_2,...,\\vec{h'}_N\\}, \\vec{h'}_i ∈ \\mathbb{R}^{F'}$, as its output.\n", "\n", "\n", "

The Attentional Layer broken into 4 separate parts:

\n", "\n", "
\n", "\n", "**1)** **Simple linear transformation:** In order to obtain sufficient expressive power to transform the input features into higher level features, atleast one learnable linear transformation is required. To that end, as an initial step, a shared linear transformation, parametrized by a weight matrix, $W ∈ \\mathbb{R}^{F′×F}$ , is applied to every node.\n", "\n", "$$\\begin{split}\\begin{align}\n", "z_i^{(l)}&=W^{(l)}h_i^{(l)},&(1) \\\\\n", "\\end{align}\\end{split}$$\n", "\n", "
\n", " \n", "
\n", "\n", "\n", "
\n", "\n", "**2)** **Attention Coefficients:** We then compute a pair-wise **un-normalized** attention score between two neighbors. Here, it first concatenates the $z$ embeddings of the two nodes, where $||$ denotes concatenation, then takes a dot product of it and a learnable weight vector $\\vec a^{(l)}$, and applies a LeakyReLU in the end. This form of attention is usually called additive attention, in contrast with the dot-product attention used for the Transformer model. We then perform self-attention on the nodes, a shared attentional mechanism $a$ : $\\mathbb{R}^{F′} × \\mathbb{R}^{F′} → \\mathbb{R}$ to compute attention coefficients \n", "$$\\begin{split}\\begin{align}\n", "e_{ij}^{(l)}&=\\text{LeakyReLU}(\\vec a^{(l)^T}(z_i^{(l)}||z_j^{(l)})),&(2)\\\\\n", "\\end{align}\\end{split}$$\n", "\n", "**Q. Is this step the most important step?** \n", "\n", "**Ans.** Yes! This indicates the importance of node $j’s$ features to node $i$. This step allows every node to attend on every other node, dropping all structural information.\n", "\n", "**NOTE:** The graph structure is injected into the mechanism by performing *masked attention*, we only compute $e_{ij}$ for nodes $j$ ∈ $N_{i}$, where $N_{i}$ is some neighborhood of node $i$ in the graph. In all the experiments, these will be exactly the first-order neighbors of $i$ (including $i$).\n", "\n", "\n", "
\n", "\n", "**3)** **Softmax:** This makes coefficients easily comparable across different nodes, we normalize them across all choices of $j$ using the softmax function\n", "\n", "$$\\begin{split}\\begin{align}\n", "\\alpha_{ij}^{(l)}&=\\frac{\\exp(e_{ij}^{(l)})}{\\sum_{k\\in \\mathcal{N}(i)}^{}\\exp(e_{ik}^{(l)})},&(3)\\\\\n", "\\end{align}\\end{split}$$\n", "\n", "\n", "
\n", "\n", "**4)** **Aggregation:** This step is similar to GCN. The embeddings from neighbors are aggregated together, scaled by the attention scores. \n", "\n", "$$\\begin{split}\\begin{align}\n", "h_i^{(l+1)}&=\\sigma\\left(\\sum_{j\\in \\mathcal{N}(i)} {\\alpha^{(l)}_{ij} z^{(l)}_j }\\right),&(4)\n", "\\end{align}\\end{split}$$\n", "\n", "
\n", "\n", "\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "

Multi-head Attention

\n", "\n", "

\n", "\n", "*An illustration of multi-head attention (with K = 3 heads) by node 1 on its neighborhood. Different arrow styles and colors denote independent attention computations. The aggregated features from each head are concatenated or averaged to obtain $\\vec{h'}_{1}$.*\n", "

\n", "\n", "Analogous to multiple channels in ConvNet, GAT introduces multi-head attention to enrich the model capacity and to stabilize the learning process. Specifically, K independent attention mechanisms execute the transformation of Equation 4, and then their outputs can be combined in 2 ways depending on the use:\n", "\n", "* Concatenation\n", " \n", " $$\\textbf{Concatenation}: h^{(l+1)}_{i} =||_{k=1}^{K}\\sigma\\left(\\sum_{j\\in \\mathcal{N}(i)}\\alpha_{ij}^{k}W^{k}h^{(l)}_{j}\\right)$$\n", " \n", " * As can be seen in this settingthe final returned output, $h′$, will consist of $KF′$ features (rather than F′) for each node.\n", "\n", "\n", "* Averaging\n", " * If we perform multi-head attention on the final (prediction) layer of the network, concatenation is no longer sensible and instead, averaging is employed, and delay applying the final nonlinearity (usually a softmax or logistic sigmoid for classification problems) until then:\n", " \n", " $$\\textbf{Average}: h_{i}^{(l+1)}=\\sigma\\left(\\frac{1}{K}\\sum_{k=1}^{K}\\sum_{j\\in\\mathcal{N}(i)}\\alpha_{ij}^{k}W^{k}h^{(l)}_{j}\\right)$$\n", " \n", "Thus concatenation for intermediary layers and average for the final layer are used." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "

Implementing GAT Layer in PyTorch

\n", "\n", "## Imports" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "torch.manual_seed(2020) # seed for reproducible numbers" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class GATLayer(nn.Module):\n", " \"\"\"\n", " Simple PyTorch Implementation of the Graph Attention layer.\n", " \"\"\"\n", "\n", " def __init__(self, in_features, out_features, dropout, alpha, concat=True):\n", " super(GATLayer, self).__init__()\n", " self.dropout = dropout # drop prob = 0.6\n", " self.in_features = in_features # \n", " self.out_features = out_features # \n", " self.alpha = alpha # LeakyReLU with negative input slope, alpha = 0.2\n", " self.concat = concat # conacat = True for all layers except the output layer.\n", "\n", " # Xavier Initialization of Weights\n", " # Alternatively use weights_init to apply weights of choice \n", " self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))\n", " nn.init.xavier_uniform_(self.W.data, gain=1.414)\n", " self.a = nn.Parameter(torch.zeros(size=(2*out_features, 1)))\n", " nn.init.xavier_uniform_(self.a.data, gain=1.414)\n", " \n", " # LeakyReLU\n", " self.leakyrelu = nn.LeakyReLU(self.alpha)\n", "\n", " def forward(self, input, adj):\n", " # Linear Transformation\n", " h = torch.mm(input, self.W)\n", " N = h.size()[0]\n", "\n", " # Attention Mechanism\n", " a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.out_features)\n", " e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))\n", "\n", " # Masked Attention\n", " zero_vec = -9e15*torch.ones_like(e)\n", " attention = torch.where(adj > 0, e, zero_vec)\n", " \n", " attention = F.softmax(attention, dim=1)\n", " attention = F.dropout(attention, self.dropout, training=self.training)\n", " h_prime = torch.matmul(attention, h)\n", "\n", " if self.concat:\n", " return F.elu(h_prime)\n", " else:\n", " return h_prime" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# # Alternate approach to applying weights of choice using weights_init()\n", "# def weights_init(m):\n", "# if isinstance(m, nn.Linear):\n", "# torch.nn.init.xavier_uniform_(m.weight)\n", "\n", "# # Applying just after calling the model class\n", "# model.apply(weights_init)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "

Implementing GAT on Citation Datasets using PyTorch Geometric

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PyG Imports" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from torch_geometric.data import Data\n", "from torch_geometric.nn import GATConv\n", "from torch_geometric.datasets import Planetoid\n", "import torch_geometric.transforms as T\n", "\n", "import matplotlib.pyplot as plt\n", "%matplotlib notebook\n", "\n", "import warnings\n", "warnings.filterwarnings(\"ignore\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dataset" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of Classes in Cora: 7\n", "Number of Node Features in Cora: 1433\n" ] } ], "source": [ "name_data = 'Cora'\n", "dataset = Planetoid(root= '/tmp/' + name_data, name = name_data)\n", "dataset.transform = T.NormalizeFeatures()\n", "\n", "print(f\"Number of Classes in {name_data}:\", dataset.num_classes)\n", "print(f\"Number of Node Features in {name_data}:\", dataset.num_node_features)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Model" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "class GAT(torch.nn.Module):\n", " def __init__(self):\n", " super(GAT, self).__init__()\n", " self.hid = 8\n", " self.in_head = 8\n", " self.out_head = 1\n", " \n", " self.conv1 = GATConv(dataset.num_features, self.hid, heads=self.in_head, dropout=0.6)\n", " self.conv2 = GATConv(self.hid*self.in_head, dataset.num_classes, concat=False,\n", " heads=self.out_head, dropout=0.6)\n", "\n", " def forward(self, data):\n", " x, edge_index = data.x, data.edge_index\n", " \n", " # Dropout before the GAT layer is used to avoid overfitting in small datasets like Cora.\n", " # One can skip them if the dataset is sufficiently large.\n", " \n", " x = F.dropout(x, p=0.6, training=self.training)\n", " x = self.conv1(x, edge_index)\n", " x = F.elu(x)\n", " x = F.dropout(x, p=0.6, training=self.training)\n", " x = self.conv2(x, edge_index)\n", " \n", " return F.log_softmax(x, dim=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Train" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor(1.9467, grad_fn=)\n", "tensor(0.6551, grad_fn=)\n", "tensor(0.5155, grad_fn=)\n", "tensor(0.6176, grad_fn=)\n", "tensor(0.6120, grad_fn=)\n" ] } ], "source": [ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", "\n", "model = GAT().to(device)\n", "\n", "data = dataset[0].to(device)\n", "optimizer = torch.optim.Adam(model.parameters(), lr=0.005, weight_decay=5e-4)\n", "\n", "model.train()\n", "for epoch in range(1000):\n", " model.train()\n", " optimizer.zero_grad()\n", " out = model(data)\n", " loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])\n", " \n", " if epoch%200 == 0:\n", " print(loss)\n", " \n", " loss.backward()\n", " optimizer.step()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Evaluate" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8200\n" ] } ], "source": [ "model.eval()\n", "_, pred = model(data).max(dim=1)\n", "correct = float(pred[data.test_mask].eq(data.y[data.test_mask]).sum().item())\n", "acc = correct / data.test_mask.sum().item()\n", "print('Accuracy: {:.4f}'.format(acc))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "[Graph Attention Networks](https://arxiv.org/abs/1710.10903)\n", "\n", "[Graph attention network, DGL by Zhang et al.](https://docs.dgl.ai/tutorials/models/1_gnn/9_gat.html)\n", "\n", "[Attention Is All You Need](https://arxiv.org/pdf/1706.03762.pdf)\n", "\n", "[The Illustrated Transformer](http://jalammar.github.io/illustrated-transformer/)\n", "\n", "[Mechanics of Seq2seq Models With Attention](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/)\n", "\n", "[Attention? Attention!](https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.5" } }, "nbformat": 4, "nbformat_minor": 2 }