File size: 2,135 Bytes
f15a766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from __future__ import annotations

import torch
import torch.nn as nn
from torch_geometric.nn import TransformerConv


class TransformerGraphSpatialEncoder(nn.Module):
    """Per-frame graph encoder using edge-aware PyG TransformerConv layers."""

    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([
            TransformerConv(
                hidden_dim,
                out_channels,
                heads=num_heads,
                concat=True,
                beta=True,
                dropout=dropout,
                edge_dim=hidden_dim,
            )
            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