| from __future__ import annotations |
|
|
| import torch |
| import torch.nn as nn |
| from torch_geometric.nn import GATv2Conv |
|
|
|
|
| class GATv2GraphSpatialEncoder(nn.Module): |
| """Per-frame graph encoder using edge-aware GATv2 message passing.""" |
|
|
| 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.layers = nn.ModuleList([ |
| GATv2Conv( |
| hidden_dim, |
| out_channels, |
| heads=num_heads, |
| concat=True, |
| edge_dim=hidden_dim, |
| dropout=dropout, |
| ) |
| for _ in range(num_layers) |
| ]) |
| self.attn_norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(num_layers)]) |
| self.ff_norms = nn.ModuleList([nn.LayerNorm(hidden_dim) for _ in range(num_layers)]) |
| self.ff_layers = nn.ModuleList([ |
| nn.Sequential( |
| nn.Linear(hidden_dim, hidden_dim * 4), |
| nn.SiLU(), |
| nn.Linear(hidden_dim * 4, hidden_dim), |
| ) |
| for _ in range(num_layers) |
| ]) |
|
|
| def forward(self, data) -> torch.Tensor: |
| x = self.node_proj(data.x) |
| edge_attr = self.edge_proj(data.edge_attr) |
|
|
| for conv, attn_norm, ff_norm, ff in zip( |
| self.layers, |
| self.attn_norms, |
| self.ff_norms, |
| self.ff_layers, |
| ): |
| attn_out = conv(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 |
|
|