|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +from torch.nn import init |
| 5 | +from torch.nn.parameter import Parameter |
| 6 | + |
| 7 | +from .activations import ACT |
| 8 | +from .activations import ACT_FUNC_DICT |
| 9 | + |
| 10 | +class AGN(nn.Module): |
| 11 | + """Activated Group Normalization |
| 12 | + This gathers a GroupNorm and an activation function in a single module |
| 13 | + Parameters |
| 14 | + ---------- |
| 15 | + num_features : int |
| 16 | + Number of feature channels in the input and output. |
| 17 | + num_groups: int |
| 18 | + Number of groups to separate the channels into |
| 19 | + eps : float |
| 20 | + Small constant to prevent numerical issues. |
| 21 | + affine : bool |
| 22 | + If `True` apply learned scale and shift transformation after normalization. |
| 23 | + activation : str |
| 24 | + Name of the activation functions, one of: `relu`, `leaky_relu`, `elu` or `identity`. |
| 25 | + activation_param : float |
| 26 | + Negative slope for the `leaky_relu` activation. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + num_features, |
| 32 | + num_groups=32, |
| 33 | + eps=1e-5, |
| 34 | + affine=True, |
| 35 | + activation="relu", |
| 36 | + activation_param=0.01, |
| 37 | + ): |
| 38 | + super(AGN, self).__init__() |
| 39 | + self.num_features = num_features |
| 40 | + self.num_groups = num_groups |
| 41 | + self.affine = affine |
| 42 | + self.eps = eps |
| 43 | + self.activation = ACT(activation) |
| 44 | + self.activation_param = activation_param |
| 45 | + if self.affine: |
| 46 | + self.weight = nn.Parameter(torch.ones(num_features)) |
| 47 | + self.bias = nn.Parameter(torch.zeros(num_features)) |
| 48 | + else: |
| 49 | + self.register_parameter("weight", None) |
| 50 | + self.register_parameter("bias", None) |
| 51 | + self.reset_parameters() |
| 52 | + |
| 53 | + def reset_parameters(self): |
| 54 | + if self.affine: |
| 55 | + nn.init.constant_(self.weight, 1) |
| 56 | + nn.init.constant_(self.bias, 0) |
| 57 | + |
| 58 | + def forward(self, x): |
| 59 | + x = F.group_norm(x, self.num_groups, self.weight, self.bias, self.eps) |
| 60 | + func = ACT_FUNC_DICT[self.activation] |
| 61 | + if self.activation == ACT.LEAKY_RELU: |
| 62 | + return func(x, inplace=True, negative_slope=self.activation_param) |
| 63 | + elif self.activation == ACT.ELU: |
| 64 | + return func(x, inplace=True, alpha=self.activation_param) |
| 65 | + else: |
| 66 | + return func(x, inplace=True) |
| 67 | + |
| 68 | + def extra_repr(self): |
| 69 | + rep = "{num_features}, eps={eps}, affine={affine}, activation={activation}" |
| 70 | + if self.activation in ["leaky_relu", "elu"]: |
| 71 | + rep += "[{activation_param}]" |
| 72 | + return rep.format(**self.__dict__) |
0 commit comments