File size: 4,489 Bytes
da6986a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""HalfEdge GNN model definition (moved from brep_two_pass/scripts/03_infer_halfedge.py)."""
from __future__ import annotations
from typing import Optional

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import (
    HeteroConv, SAGEConv, JumpingKnowledge, BatchNorm,
    global_mean_pool, global_max_pool,
)
from torch_geometric.data import HeteroData


def resolve_reject_label(labels, requested: Optional[str]) -> Optional[str]:
    if requested:
        return requested
    lower_to_name = {name.lower(): name for name in labels}
    for candidate in ("random", "unknown", "other", "misc"):
        if candidate in lower_to_name:
            return lower_to_name[candidate]
    for name in labels:
        lower = name.lower()
        if "random" in lower or "unknown" in lower:
            return name
    return None


class HalfEdgeGNN(nn.Module):
    def __init__(
        self,
        coedge_in: int, face_in: int, edge_in: int, global_in: int,
        hidden=256, layers=6, dropout=0.2, num_classes=3,
        jk_mode="cat", gating_dim=None,
    ):
        super().__init__()
        self.convs = nn.ModuleList(); self.bns = nn.ModuleList()
        self.encoders = nn.ModuleDict({
            "coedge": nn.Sequential(nn.Linear(coedge_in, hidden), nn.ReLU(), nn.Dropout(dropout)),
            "face":   nn.Sequential(nn.Linear(face_in,   hidden), nn.ReLU(), nn.Dropout(dropout)),
            "edge":   nn.Sequential(nn.Linear(edge_in,   hidden), nn.ReLU(), nn.Dropout(dropout)),
        })
        for _ in range(layers):
            conv = HeteroConv({
                ('coedge','next','coedge'):     SAGEConv((hidden, hidden), hidden),
                ('coedge','prev','coedge'):     SAGEConv((hidden, hidden), hidden),
                ('coedge','mate','coedge'):     SAGEConv((hidden, hidden), hidden),
                ('coedge','to_face','face'):    SAGEConv((hidden, hidden), hidden),
                ('face','to_coedge','coedge'):  SAGEConv((hidden, hidden), hidden),
                ('coedge','to_edge','edge'):    SAGEConv((hidden, hidden), hidden),
                ('edge','to_coedge','coedge'):  SAGEConv((hidden, hidden), hidden),
                ('face','to_edge','edge'):      SAGEConv((hidden, hidden), hidden),
                ('edge','to_face','face'):      SAGEConv((hidden, hidden), hidden),
            }, aggr='sum')
            self.convs.append(conv)
            self.bns.append(nn.ModuleDict({
                "coedge": BatchNorm(hidden),
                "face":   BatchNorm(hidden),
                "edge":   BatchNorm(hidden),
            }))
        self.jk = JumpingKnowledge(mode=jk_mode)
        self.jk_out = hidden * layers if jk_mode == "cat" else hidden
        if gating_dim is None:
            gating_dim = hidden
        self.gating_dim = gating_dim
        self.pool_in = self.jk_out * 2
        self.proj = nn.Identity() if self.pool_in == gating_dim else nn.Linear(self.pool_in, gating_dim)

        self.global_mlp = nn.Sequential(
            nn.Linear(global_in, gating_dim),
            nn.ReLU(), nn.Dropout(0.3),
            nn.Linear(gating_dim, 2 * gating_dim),
        )
        self.head = nn.Sequential(
            nn.Linear(gating_dim, hidden),
            nn.ReLU(), nn.Dropout(dropout),
            nn.Linear(hidden, num_classes),
        )

    def forward(self, data: HeteroData):
        x = {
            "coedge": self.encoders["coedge"](data["coedge"].x),
            "face":   self.encoders["face"](data["face"].x),
            "edge":   self.encoders["edge"](data["edge"].x),
        }
        outs = []
        for conv, bn in zip(self.convs, self.bns):
            x_new = conv(x, data.edge_index_dict)
            x = {k: F.relu(bn[k](x_new[k]) + x[k]) for k in x}
            outs.append(x["coedge"])
        xj = self.jk(outs)
        batch = data['coedge'].batch
        g_mean = global_mean_pool(xj, batch)
        g_max  = global_max_pool(xj, batch)
        g = torch.cat([g_mean, g_max], dim=-1)
        g0 = self.proj(g)
        global_x = data["global"].x
        if global_x.dim() == 1:
            global_x = global_x.view(1, -1)
        if global_x.size(0) != g0.size(0):
            raise RuntimeError(f"Global feature batch mismatch: {global_x.size(0)} vs {g0.size(0)}")
        gb = self.global_mlp(global_x)
        gamma, beta = gb.chunk(2, dim=-1)
        gamma = torch.sigmoid(gamma)
        g_mod = g0 * gamma + beta
        return self.head(g_mod)