| from __future__ import annotations |
|
|
| import torch |
| import torch.nn as nn |
| from torch_geometric.nn import GINEConv, TransformerConv |
|
|
|
|
| class HybridGINETransformerGraphSpatialEncoder(nn.Module): |
| """Local GINE message passing followed by edge-aware graph attention.""" |
|
|
| def __init__( |
| self, |
| node_in_dim: int, |
| edge_in_dim: int, |
| hidden_dim: int = 384, |
| num_layers: int = 6, |
| dropout: float = 0.1, |
| num_heads: int = 8, |
| ): |
| super().__init__() |
| if hidden_dim % num_heads != 0: |
| raise ValueError(f"hidden_dim={hidden_dim} must be divisible by num_heads={num_heads}.") |
|
|
| self.node_proj = nn.Linear(node_in_dim, hidden_dim) |
| self.edge_proj = nn.Linear(edge_in_dim, hidden_dim) |
| self.dropout = nn.Dropout(dropout) |
|
|
| out_channels = hidden_dim // num_heads |
| self.local_layers = nn.ModuleList() |
| self.attn_layers = nn.ModuleList() |
| self.local_norms = nn.ModuleList() |
| self.attn_norms = nn.ModuleList() |
| self.ff_norms = nn.ModuleList() |
| self.ff_layers = nn.ModuleList() |
|
|
| for _ in range(num_layers): |
| mlp = nn.Sequential( |
| nn.Linear(hidden_dim, hidden_dim), |
| nn.SiLU(), |
| nn.Linear(hidden_dim, hidden_dim), |
| ) |
| self.local_layers.append(GINEConv(mlp, edge_dim=hidden_dim)) |
| self.attn_layers.append( |
| TransformerConv( |
| hidden_dim, |
| out_channels, |
| heads=num_heads, |
| concat=True, |
| beta=True, |
| dropout=dropout, |
| edge_dim=hidden_dim, |
| ) |
| ) |
| self.local_norms.append(nn.LayerNorm(hidden_dim)) |
| self.attn_norms.append(nn.LayerNorm(hidden_dim)) |
| self.ff_norms.append(nn.LayerNorm(hidden_dim)) |
| self.ff_layers.append( |
| nn.Sequential( |
| nn.Linear(hidden_dim, hidden_dim * 4), |
| nn.SiLU(), |
| nn.Linear(hidden_dim * 4, hidden_dim), |
| ) |
| ) |
|
|
| def forward(self, data) -> torch.Tensor: |
| x = self.node_proj(data.x) |
| edge_attr = self.edge_proj(data.edge_attr) |
|
|
| for local, attn, local_norm, attn_norm, ff_norm, ff in zip( |
| self.local_layers, |
| self.attn_layers, |
| self.local_norms, |
| self.attn_norms, |
| self.ff_norms, |
| self.ff_layers, |
| ): |
| local_out = local(x, data.edge_index, edge_attr=edge_attr) |
| x = local_norm(x + self.dropout(local_out)) |
|
|
| attn_out = attn(x, data.edge_index, edge_attr=edge_attr) |
| x = attn_norm(x + self.dropout(attn_out)) |
| x = ff_norm(x + self.dropout(ff(x))) |
|
|
| return x |
|
|