|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn.functional as F |
| 5 | +from torch import Tensor |
| 6 | +from torch.nn import BatchNorm1d, Linear, Sequential |
| 7 | +from torch_geometric.nn.conv import MessagePassing |
| 8 | +from torch_geometric.typing import Adj, OptTensor, PairTensor, Size |
| 9 | + |
| 10 | +from matdeeplearn.common.registry import registry |
| 11 | +from matdeeplearn.models.base_model import BaseModel |
| 12 | + |
| 13 | + |
| 14 | +@registry.register_model("DOSPredict") |
| 15 | +class DOSPredict(BaseModel): |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + edge_steps, |
| 19 | + self_loop, |
| 20 | + data, |
| 21 | + dim1=64, |
| 22 | + dim2=64, |
| 23 | + pre_fc_count=1, |
| 24 | + gc_count=3, |
| 25 | + batch_norm=True, |
| 26 | + batch_track_stats=True, |
| 27 | + dropout_rate=0.0, |
| 28 | + **kwargs, |
| 29 | + ): |
| 30 | + super(DOSPredict, self).__init__(edge_steps, self_loop) |
| 31 | + self.dim1 = dim1 |
| 32 | + self.dim2 = dim2 |
| 33 | + self.pre_fc_count = pre_fc_count |
| 34 | + self.gc_count = gc_count |
| 35 | + self.num_features = data.num_features |
| 36 | + self.num_edge_features = data.num_edge_features |
| 37 | + self.batch_norm = batch_norm |
| 38 | + self.batch_track_stats = batch_track_stats |
| 39 | + self.dropout_rate = dropout_rate |
| 40 | + |
| 41 | + # Determine gc dimension and post_fc dimension |
| 42 | + assert gc_count > 0, "Need at least 1 GC layer" |
| 43 | + if pre_fc_count == 0: |
| 44 | + self.gc_dim, self.post_fc_dim = data.num_features, data.num_features |
| 45 | + else: |
| 46 | + self.gc_dim, self.post_fc_dim = dim1, dim1 |
| 47 | + |
| 48 | + # Determine output dimension length |
| 49 | + self.output_dim = 1 if data[0].scaled.ndim == 0 else len(data[0].scaled[0]) |
| 50 | + |
| 51 | + # setup layers |
| 52 | + self.pre_lin_list = self._setup_pre_gnn_layers() |
| 53 | + self.conv_list, self.bn_list = self._setup_gnn_layers() |
| 54 | + |
| 55 | + self.dos_mlp = Sequential( |
| 56 | + Linear(self.post_fc_dim, self.dim2), |
| 57 | + torch.nn.PReLU(), |
| 58 | + Linear(self.dim2, self.output_dim), |
| 59 | + torch.nn.PReLU(), |
| 60 | + ) |
| 61 | + |
| 62 | + self.scaling_mlp = Sequential( |
| 63 | + Linear(self.post_fc_dim, self.dim2), |
| 64 | + torch.nn.PReLU(), |
| 65 | + Linear(self.dim2, 1), |
| 66 | + ) |
| 67 | + |
| 68 | + def _setup_pre_gnn_layers(self): |
| 69 | + """Sets up pre-GNN dense layers (NOTE: in v0.1 this is always set to 1 layer).""" |
| 70 | + pre_lin_list = torch.nn.ModuleList() |
| 71 | + if self.pre_fc_count > 0: |
| 72 | + pre_lin_list = torch.nn.ModuleList() |
| 73 | + for i in range(self.pre_fc_count): |
| 74 | + if i == 0: |
| 75 | + lin = torch.nn.Linear(self.num_features, self.dim1) |
| 76 | + else: |
| 77 | + lin = torch.nn.Linear(self.dim1, self.dim1) |
| 78 | + |
| 79 | + pre_lin_list.append(Sequential(lin, torch.nn.PReLU())) |
| 80 | + |
| 81 | + return pre_lin_list |
| 82 | + |
| 83 | + def _setup_gnn_layers(self): |
| 84 | + """Sets up GNN layers.""" |
| 85 | + conv_list = torch.nn.ModuleList() |
| 86 | + bn_list = torch.nn.ModuleList() |
| 87 | + for i in range(self.gc_count): |
| 88 | + conv = GCBlock(self.gc_dim, self.num_edge_features, aggr="mean") |
| 89 | + conv_list.append(conv) |
| 90 | + # Track running stats set to false can prevent some instabilities; this causes other issues with different val/test performance from loader size? |
| 91 | + if self.batch_norm: |
| 92 | + bn = BatchNorm1d( |
| 93 | + self.gc_dim, track_running_stats=self.batch_track_stats, affine=True |
| 94 | + ) |
| 95 | + bn_list.append(bn) |
| 96 | + |
| 97 | + return conv_list, bn_list |
| 98 | + |
| 99 | + def forward(self, data): |
| 100 | + |
| 101 | + # Pre-GNN dense layers |
| 102 | + for i in range(0, len(self.pre_lin_list)): |
| 103 | + if i == 0: |
| 104 | + out = self.pre_lin_list[i](data.x.float()) |
| 105 | + else: |
| 106 | + out = self.pre_lin_list[i](out) |
| 107 | + |
| 108 | + # GNN layers |
| 109 | + for i in range(0, len(self.conv_list)): |
| 110 | + if len(self.pre_lin_list) == 0 and i == 0: |
| 111 | + out = self.conv_list[i](data.x, data.edge_index, data.edge_attr.float()) |
| 112 | + else: |
| 113 | + out = self.conv_list[i](out, data.edge_index, data.edge_attr.float()) |
| 114 | + if self.batch_norm: |
| 115 | + out = self.bn_list[i](out) |
| 116 | + |
| 117 | + out = F.dropout(out, p=self.dropout_rate, training=self.training) |
| 118 | + # Post-GNN dense layers |
| 119 | + dos_out = self.dos_mlp(out) |
| 120 | + scaling = self.scaling_mlp(out) |
| 121 | + |
| 122 | + if dos_out.shape[1] == 1: |
| 123 | + return dos_out.view(-1), scaling.view(-1) |
| 124 | + else: |
| 125 | + return dos_out, scaling.view(-1) |
| 126 | + |
| 127 | + |
| 128 | +class GCBlock(MessagePassing): |
| 129 | + def __init__( |
| 130 | + self, |
| 131 | + channels: int | tuple[int, int], |
| 132 | + dim: int = 0, |
| 133 | + aggr: str = "mean", |
| 134 | + **kwargs, |
| 135 | + ): |
| 136 | + super(GCBlock, self).__init__(aggr=aggr, **kwargs) |
| 137 | + self.channels = channels |
| 138 | + self.dim = dim |
| 139 | + |
| 140 | + if isinstance(channels, int): |
| 141 | + channels = (channels, channels) |
| 142 | + |
| 143 | + self.mlp = Sequential( |
| 144 | + Linear(sum(channels) + dim, channels[1]), |
| 145 | + torch.nn.PReLU(), |
| 146 | + ) |
| 147 | + self.mlp2 = Sequential( |
| 148 | + Linear(dim, dim), |
| 149 | + torch.nn.PReLU(), |
| 150 | + ) |
| 151 | + |
| 152 | + def forward( |
| 153 | + self, |
| 154 | + x: Tensor | PairTensor, |
| 155 | + edge_index: Adj, |
| 156 | + edge_attr: OptTensor = None, |
| 157 | + size: Size = None, |
| 158 | + ) -> Tensor: |
| 159 | + |
| 160 | + if isinstance(x, Tensor): |
| 161 | + x: PairTensor = (x, x) |
| 162 | + |
| 163 | + # propagate_type: (x: PairTensor, edge_attr: OptTensor) |
| 164 | + out = self.propagate(edge_index, x=x, edge_attr=edge_attr, size=size) |
| 165 | + out += x[1] |
| 166 | + return out |
| 167 | + |
| 168 | + def message(self, x_i, x_j, edge_attr: OptTensor) -> Tensor: |
| 169 | + z = torch.cat([x_i, x_j, self.mlp2(edge_attr)], dim=-1) |
| 170 | + z = self.mlp(z) |
| 171 | + return z |
0 commit comments