|
| 1 | +""" |
| 2 | +Experiment options: |
| 3 | +- Clip input range?! |
| 4 | +- Sequential or parallel attention, which order? |
| 5 | +- Spatial attention options (see CBAM paper) |
| 6 | +- Which down and up sampling method? Pool, Conv, Shuffle, Interpolation |
| 7 | +- Add vs. concat skips |
| 8 | +- Add FMEN-like Unshuffle/Shuffle |
| 9 | +""" |
| 10 | + |
| 11 | +import torch |
| 12 | +import torch.nn as nn |
| 13 | +import torch.nn.functional as F |
| 14 | +from typing import List |
| 15 | + |
| 16 | + |
| 17 | +class AttentionBlock(nn.Module): |
| 18 | + def __init__(self, dim: int): |
| 19 | + super(AttentionBlock, self).__init__() |
| 20 | + self._spatial_attention_conv = nn.Conv2d(2, dim, kernel_size=3, padding=1) |
| 21 | + |
| 22 | + # Channel attention MLP |
| 23 | + self._channel_attention_conv0 = nn.Conv2d(1, dim, kernel_size=1, padding=0) |
| 24 | + self._channel_attention_conv1 = nn.Conv2d(dim, dim, kernel_size=1, padding=0) |
| 25 | + |
| 26 | + self._out_conv = nn.Conv2d(2 * dim, dim, kernel_size=1, padding=0) |
| 27 | + |
| 28 | + def forward(self, x: torch.Tensor): |
| 29 | + if len(x.shape) != 4: |
| 30 | + raise ValueError(f"Expected [B, C, H, W] input, got {x.shape}.") |
| 31 | + |
| 32 | + # Spatial attention |
| 33 | + mean = torch.mean(x, dim=1, keepdim=True) # Mean/Max on C axis |
| 34 | + max, _ = torch.max(x, dim=1, keepdim=True) |
| 35 | + spatial_attention = torch.cat([mean, max], dim=1) # [B, 2, H, W] |
| 36 | + spatial_attention = self._spatial_attention_conv(spatial_attention) |
| 37 | + spatial_attention = torch.sigmoid(spatial_attention) * x |
| 38 | + |
| 39 | + # Channel attention. TODO: Correct that it only uses average pool contrary to CBAM? |
| 40 | + # NOTE/TODO: This differs from CBAM as it uses Channel pooling, not spatial pooling! |
| 41 | + # In a way, this is 2x spatial attention |
| 42 | + channel_attention = torch.relu(self._channel_attention_conv0(mean)) |
| 43 | + channel_attention = self._channel_attention_conv1(channel_attention) |
| 44 | + channel_attention = torch.sigmoid(channel_attention) * x |
| 45 | + |
| 46 | + attention = torch.cat([spatial_attention, channel_attention], dim=1) # [B, 2*dim, H, W] |
| 47 | + attention = self._out_conv(attention) |
| 48 | + return x + attention |
| 49 | + |
| 50 | + |
| 51 | +# TODO: This is not named in the paper right? |
| 52 | +# It is sort of the InverseResidualBlock but w/o the Channel and Spatial Attentions and without another Conv after ReLU |
| 53 | +class InverseBlock(nn.Module): |
| 54 | + def __init__(self, input_channels: int, channels: int): |
| 55 | + super(InverseBlock, self).__init__() |
| 56 | + |
| 57 | + self._conv0 = nn.Conv2d(input_channels, channels, kernel_size=1) |
| 58 | + self._dw_conv = nn.Conv2d(channels, channels, kernel_size=3, padding=1, groups=channels) |
| 59 | + self._conv1 = nn.Conv2d(channels, channels, kernel_size=1) |
| 60 | + self._conv2 = nn.Conv2d(input_channels, channels, kernel_size=1) |
| 61 | + |
| 62 | + def forward(self, x: torch.Tensor): |
| 63 | + features = self._conv0(x) |
| 64 | + features = F.elu(self._dw_conv(features)) # TODO: Paper is ReLU, authors do ELU |
| 65 | + features = self._conv1(features) |
| 66 | + |
| 67 | + # TODO: The BaseBlock has residuals and one path of convolutions, not 2 separate paths - is this different on purpose? |
| 68 | + x = torch.relu(self._conv2(x)) |
| 69 | + return x + features |
| 70 | + |
| 71 | + |
| 72 | +class BaseBlock(nn.Module): |
| 73 | + def __init__(self, channels: int): |
| 74 | + super(BaseBlock, self).__init__() |
| 75 | + |
| 76 | + self._conv0 = nn.Conv2d(channels, channels, kernel_size=1) |
| 77 | + self._dw_conv = nn.Conv2d(channels, channels, kernel_size=3, padding=1, groups=channels) |
| 78 | + self._conv1 = nn.Conv2d(channels, channels, kernel_size=1) |
| 79 | + |
| 80 | + self._conv2 = nn.Conv2d(channels, channels, kernel_size=1) |
| 81 | + self._conv3 = nn.Conv2d(channels, channels, kernel_size=1) |
| 82 | + |
| 83 | + def forward(self, x: torch.Tensor): |
| 84 | + features = self._conv0(x) |
| 85 | + features = F.elu(self._dw_conv(features)) # TODO: ELU or ReLU? |
| 86 | + features = self._conv1(features) |
| 87 | + x = x + features |
| 88 | + |
| 89 | + features = F.elu(self._conv2(x)) |
| 90 | + features = self._conv3(features) |
| 91 | + return x + features |
| 92 | + |
| 93 | + |
| 94 | +class AttentionTail(nn.Module): |
| 95 | + def __init__(self, channels: int): |
| 96 | + super(AttentionTail, self).__init__() |
| 97 | + |
| 98 | + self._conv0 = nn.Conv2d(channels, channels, kernel_size=7, padding=3) |
| 99 | + self._conv1 = nn.Conv2d(channels, channels, kernel_size=5, padding=2) |
| 100 | + self._conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1) |
| 101 | + |
| 102 | + def forward(self, x: torch.Tensor): |
| 103 | + attention = torch.relu(self._conv0(x)) |
| 104 | + attention = torch.relu(self._conv1(attention)) |
| 105 | + attention = torch.sigmoid(self._conv2(attention)) |
| 106 | + return x * attention |
| 107 | + |
| 108 | + |
| 109 | +class LPIENet(nn.Module): |
| 110 | + def __init__(self, input_channels: int, output_channels: int, encoder_dims: List[int], decoder_dims: List[int]): |
| 111 | + super(LPIENet, self).__init__() |
| 112 | + |
| 113 | + if len(encoder_dims) != len(decoder_dims) + 1 or len(decoder_dims) < 1: |
| 114 | + raise ValueError(f"Unexpected encoder and decoder dims: {encoder_dims}, {decoder_dims}.") |
| 115 | + |
| 116 | + if input_channels != output_channels: |
| 117 | + raise NotImplementedError() |
| 118 | + |
| 119 | + # TODO: We will need an explicit decoder head, consider Unshuffle & Shuffle |
| 120 | + |
| 121 | + encoders = [] |
| 122 | + for i, encoder_dim in enumerate(encoder_dims): |
| 123 | + input_dim = input_channels if i == 0 else encoder_dims[i - 1] |
| 124 | + encoders.append( |
| 125 | + nn.Sequential( |
| 126 | + nn.Conv2d(input_dim, encoder_dim, kernel_size=3, padding=1), |
| 127 | + BaseBlock(encoder_dim), # TODO: one or two base blocks? |
| 128 | + BaseBlock(encoder_dim), |
| 129 | + AttentionBlock(encoder_dim), |
| 130 | + ) |
| 131 | + ) |
| 132 | + self._encoders = nn.ModuleList(encoders) |
| 133 | + |
| 134 | + decoders = [] |
| 135 | + for i, decoder_dim in enumerate(decoder_dims): |
| 136 | + input_dim = encoder_dims[-1] if i == 0 else decoder_dims[i - 1] + encoder_dims[-i - 1] |
| 137 | + decoders.append( |
| 138 | + nn.Sequential( |
| 139 | + nn.Conv2d(input_dim, decoder_dim, kernel_size=3, padding=1), |
| 140 | + BaseBlock(decoder_dim), |
| 141 | + BaseBlock(decoder_dim), |
| 142 | + AttentionBlock(decoder_dim), |
| 143 | + ) |
| 144 | + ) |
| 145 | + self._decoders = nn.ModuleList(decoders) |
| 146 | + |
| 147 | + self._inverse_bock = InverseBlock(encoder_dims[0] + decoder_dims[-1], output_channels) |
| 148 | + self._attention_tail = AttentionTail(output_channels) |
| 149 | + |
| 150 | + def forward(self, x: torch.Tensor): |
| 151 | + if len(x.shape) != 4: |
| 152 | + raise ValueError(f"Expected [B, C, H, W] input, got {x.shape}.") |
| 153 | + global_residual = x |
| 154 | + |
| 155 | + encoder_outputs = [] |
| 156 | + for i, encoder in enumerate(self._encoders): |
| 157 | + x = encoder(x) |
| 158 | + if i != len(self._encoders) - 1: |
| 159 | + encoder_outputs.append(x) |
| 160 | + x = F.max_pool2d(x, kernel_size=2) |
| 161 | + |
| 162 | + for i, decoder in enumerate(self._decoders): |
| 163 | + x = decoder(x) |
| 164 | + x = F.interpolate(x, scale_factor=2, mode="bilinear") |
| 165 | + x = torch.cat([x, encoder_outputs.pop()], dim=1) |
| 166 | + |
| 167 | + x = self._inverse_bock(x) |
| 168 | + x = self._attention_tail(x) |
| 169 | + return x + global_residual |
| 170 | + |
| 171 | + |
| 172 | +model = LPIENet(3, 3, [4, 8, 16], [8, 4]) |
| 173 | +x = torch.rand(1, 3, 16, 16) |
| 174 | +out = model(x) |
| 175 | +print(out.shape) |
0 commit comments