modules.py 1.39 KB
Newer Older
xnouhz's avatar
xnouhz committed
1
2
3
4
5
6
7
8
9
10
11
12
import torch
import torch.nn as nn
import torch.nn.functional as F


class MLP(nn.Sequential):
    r"""

    Description
    -----------
    From equation (5) in "DeeperGCN: All You Need to Train Deeper GCNs <https://arxiv.org/abs/2006.07739>"
    """
13
14

    def __init__(self, channels, act="relu", dropout=0.0, bias=True):
xnouhz's avatar
xnouhz committed
15
        layers = []
16

xnouhz's avatar
xnouhz committed
17
18
19
20
21
22
        for i in range(1, len(channels)):
            layers.append(nn.Linear(channels[i - 1], channels[i], bias))
            if i < len(channels) - 1:
                layers.append(nn.BatchNorm1d(channels[i], affine=True))
                layers.append(nn.ReLU())
                layers.append(nn.Dropout(dropout))
23

xnouhz's avatar
xnouhz committed
24
25
26
27
28
        super(MLP, self).__init__(*layers)


class MessageNorm(nn.Module):
    r"""
29

xnouhz's avatar
xnouhz committed
30
31
32
33
34
35
36
37
38
    Description
    -----------
    Message normalization was introduced in "DeeperGCN: All You Need to Train Deeper GCNs <https://arxiv.org/abs/2006.07739>"

    Parameters
    ----------
    learn_scale: bool
        Whether s is a learnable scaling factor or not. Default is False.
    """
39

xnouhz's avatar
xnouhz committed
40
41
    def __init__(self, learn_scale=False):
        super(MessageNorm, self).__init__()
42
43
44
        self.scale = nn.Parameter(
            torch.FloatTensor([1.0]), requires_grad=learn_scale
        )
xnouhz's avatar
xnouhz committed
45
46
47
48
49

    def forward(self, feats, msg, p=2):
        msg = F.normalize(msg, p=2, dim=-1)
        feats_norm = feats.norm(p=p, dim=-1, keepdim=True)
        return msg * feats_norm * self.scale