Yes, torch_geometricdoes provide implementations for Graph Transformer layers, most notably the TransformerConv operator.
Graph Transformers are a rapidly evolving area in Graph Neural Networks, inspired by the success of Transformers in Natural Language Processing. They aim to capture long-range dependencies and potentially overcome some limitations of traditional message-passing GNNs (like over-smoothing or limited receptive field).
torch_geometric.nn.TransformerConv
This is the primary layer in PyG that implements a Graph Transformer-like operation. It's an attention-based message-passing operator.
Key Features of TransformerConv:
Multi-Head Attention: It applies multi-head self-attention mechanisms over the neighborhood of each node.
Learnable Query/Key/Value Projections: Similar to standard Transformers, it projects node features into query, key, and value spaces.
Edge Features: It can optionally incorporate edge features (edge_dim) into the attention mechanism, allowing for more expressive relationships.
Beta Parameter: It includes an optional learnable parameter beta to weigh the importance of the initial node features against the aggregated attention output.
Root Weight: Similar to GCNs, it has an optional root_weight parameter to add a learnable self-loop.
How it works (Simplified):
For each node i:
It computes query (Qi), key (Kj), and value (Vj) representations for itself and its neighbors j.
Attention scores are calculated between Qi and Kj for all neighbors j, optionally incorporating edge features.
These attention scores are normalized (e.g., using softmax).
The values Vj are aggregated based on these attention scores.
Multiple "heads" perform this process in parallel, and their outputs are typically concatenated or averaged.
The result is usually passed through a non-linearity.
Example Usage:
python
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import TransformerConv
from torch_geometric.transforms import NormalizeFeatures
# 1. Load a dataset
dataset = Planetoid(root='/tmp/Cora', name='Cora', transform=NormalizeFeatures())
data = dataset[0]
# 2. Define a simple Graph Transformer Model
class GraphTransformerNet(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, heads=4):
super(GraphTransformerNet, self).__init__()
# TransformerConv applies multi-head attention
# `concat=True` means the output of each head is concatenated (default)
self.conv1 = TransformerConv(in_channels, hidden_channels, heads=heads, concat=True, beta=True)
# For the second layer, we need to adjust in_channels if heads were concatenated
self.conv2 = TransformerConv(hidden_channels * heads, out_channels, heads=1, concat=False, beta=True)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index)
x = F.relu(x)
x = F.dropout(x, p=0.5, training=self.training)
x = self.conv2(x, edge_index)
return F.log_softmax(x, dim=1)
# 3. Instantiate the model, optimizer, and move to device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = GraphTransformerNet(dataset.num_features, 64, dataset.num_classes, heads=8).to(device)
data = data.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.005, weight_decay=5e-4)
# 4. Training loop
def train():
model.train()
optimizer.zero_grad()
out = model(data.x, data.edge_index)
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
return loss.item()
@torch.no_grad()
def test():
model.eval()
out = model(data.x, data.edge_index)
pred = out.argmax(dim=1)
train_correct = pred[data.train_mask] == data.y[data.train_mask]
train_acc = int(train_correct.sum()) / int(data.train_mask.sum())
val_correct = pred[data.val_mask] == data.y[data.val_mask]
val_acc = int(val_correct.sum()) / int(data.val_mask.sum())
test_correct = pred[data.test_mask] == data.y[data.test_mask]
test_acc = int(test_correct.sum()) / int(data.test_mask.sum())
return train_acc, val_acc, test_acc
print(f"Using device: {device}")
for epoch in range(1, 201):
loss = train()
train_acc, val_acc, test_acc = test()
if epoch % 20 == 0:
print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}, Train Acc: {train_acc:.4f}, Val Acc: {val_acc:.4f}, Test Acc: {test_acc:.4f}')
Beyond TransformerConv
While TransformerConv is the most direct answer, it's important to note:
Graph Attention Networks (GAT):GATConv is another attention-based operator in PyG. While not a "Transformer" in the purest sense (it predates the full Transformer architecture and doesn't explicitly use Q/K/V projections or multi-head in the same way TransformerConv does for message aggregation), it pioneered the use of attention for message passing in GNNs. TransformerConv can be seen as building upon these ideas with more direct inspiration from the NLP Transformer.
Positional Encodings: A critical component of successful Transformers in NLP is positional encoding. For graphs, this is more complex as there's no inherent sequential order. PyG's convolution layers themselves don't typically handle this directly. Instead, you would compute structural/positional encodings (e.g., Laplacian positional encodings, random walk encodings) as additional features for your nodes and feed them into the model alongside the original features.
Full Graph Transformers: Some "Graph Transformer" architectures involve more than just a TransformerConv layer. They might include techniques like global attention pooling, read-out mechanisms, or sophisticated ways to incorporate structural information. PyG provides the building blocks (TransformerConv, pooling layers, global attention modules) that allow you to construct these more complex architectures.
In summary, torch_geometric provides robust tools like TransformerConv to implement Graph Transformer-like architectures, allowing researchers and practitioners to explore the benefits of attention mechanisms for graph-structured data.