import torch import torch.nn as nn import torch.nn.functional as F from core.submodule import * import timm class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes) self.norm2 = nn.BatchNorm2d(planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes) self.norm2 = nn.InstanceNorm2d(planes) if not (stride == 1 and in_planes == planes): self.norm3 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() if not (stride == 1 and in_planes == planes): self.norm3 = nn.Sequential() if stride == 1 and in_planes == planes: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) def forward(self, x): y = x y = self.conv1(y) y = self.norm1(y) y = self.relu(y) y = self.conv2(y) y = self.norm2(y) y = self.relu(y) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) class BottleneckBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(BottleneckBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0) self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=stride) self.conv3 = nn.Conv2d(planes//4, planes, kernel_size=1, padding=0) self.relu = nn.ReLU(inplace=True) num_groups = planes // 8 if norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4) self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) if not stride == 1: self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) elif norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(planes//4) self.norm2 = nn.BatchNorm2d(planes//4) self.norm3 = nn.BatchNorm2d(planes) if not stride == 1: self.norm4 = nn.BatchNorm2d(planes) elif norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(planes//4) self.norm2 = nn.InstanceNorm2d(planes//4) self.norm3 = nn.InstanceNorm2d(planes) if not stride == 1: self.norm4 = nn.InstanceNorm2d(planes) elif norm_fn == 'none': self.norm1 = nn.Sequential() self.norm2 = nn.Sequential() self.norm3 = nn.Sequential() if not stride == 1: self.norm4 = nn.Sequential() if stride == 1: self.downsample = None else: self.downsample = nn.Sequential( nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4) def forward(self, x): y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) y = self.relu(self.norm3(self.conv3(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y) class BasicEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0, downsample=3): super(BasicEncoder, self).__init__() self.norm_fn = norm_fn self.downsample = downsample if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(64) elif self.norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(64) elif self.norm_fn == 'none': self.norm1 = nn.Sequential() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3) self.relu1 = nn.ReLU(inplace=True) self.in_planes = 64 self.layer1 = self._make_layer(64, stride=1) self.layer2 = self._make_layer(96, stride=1 + (downsample > 1)) self.layer3 = self._make_layer(128, stride=1 + (downsample > 0)) # output convolution self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1) self.dropout = None if dropout > 0: self.dropout = nn.Dropout2d(p=dropout) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): if m.weight is not None: nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0) def _make_layer(self, dim, stride=1): layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) layers = (layer1, layer2) self.in_planes = dim return nn.Sequential(*layers) def forward(self, x, dual_inp=False): # if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.conv2(x) if self.training and self.dropout is not None: x = self.dropout(x) if is_list: x = x.split(split_size=batch_dim, dim=0) return x class MultiBasicEncoder(nn.Module): def __init__(self, output_dim=[128], norm_fn='batch', dropout=0.0, downsample=3): super(MultiBasicEncoder, self).__init__() self.norm_fn = norm_fn self.downsample = downsample # self.norm_111 = nn.BatchNorm2d(128, affine=False, track_running_stats=False) # self.norm_222 = nn.BatchNorm2d(128, affine=False, track_running_stats=False) if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_fn == 'batch': self.norm1 = nn.BatchNorm2d(64) elif self.norm_fn == 'instance': self.norm1 = nn.InstanceNorm2d(64) elif self.norm_fn == 'none': self.norm1 = nn.Sequential() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3) self.relu1 = nn.ReLU(inplace=True) self.in_planes = 64 self.layer1 = self._make_layer(64, stride=1) self.layer2 = self._make_layer(96, stride=1 + (downsample > 1)) self.layer3 = self._make_layer(128, stride=1 + (downsample > 0)) self.layer4 = self._make_layer(128, stride=2) self.layer5 = self._make_layer(128, stride=2) output_list = [] for dim in output_dim: conv_out = nn.Sequential( ResidualBlock(128, 128, self.norm_fn, stride=1), nn.Conv2d(128, dim[2], 3, padding=1)) output_list.append(conv_out) self.outputs04 = nn.ModuleList(output_list) output_list = [] for dim in output_dim: conv_out = nn.Sequential( ResidualBlock(128, 128, self.norm_fn, stride=1), nn.Conv2d(128, dim[1], 3, padding=1)) output_list.append(conv_out) self.outputs08 = nn.ModuleList(output_list) output_list = [] for dim in output_dim: conv_out = nn.Conv2d(128, dim[0], 3, padding=1) output_list.append(conv_out) self.outputs16 = nn.ModuleList(output_list) if dropout > 0: self.dropout = nn.Dropout2d(p=dropout) else: self.dropout = None for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)): if m.weight is not None: nn.init.constant_(m.weight, 1) if m.bias is not None: nn.init.constant_(m.bias, 0) def _make_layer(self, dim, stride=1): layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) layers = (layer1, layer2) self.in_planes = dim return nn.Sequential(*layers) def forward(self, x, dual_inp=False, num_layers=3): x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) if dual_inp: v = x x = x[:(x.shape[0]//2)] outputs04 = [f(x) for f in self.outputs04] if num_layers == 1: return (outputs04, v) if dual_inp else (outputs04,) y = self.layer4(x) outputs08 = [f(y) for f in self.outputs08] if num_layers == 2: return (outputs04, outputs08, v) if dual_inp else (outputs04, outputs08) z = self.layer5(y) outputs16 = [f(z) for f in self.outputs16] return (outputs04, outputs08, outputs16, v) if dual_inp else (outputs04, outputs08, outputs16) class SubModule(nn.Module): def __init__(self): super(SubModule, self).__init__() def weight_init(self): for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.Conv3d): n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm3d): m.weight.data.fill_(1) m.bias.data.zero_() class Feature(SubModule): def __init__(self, freeze): super(Feature, self).__init__() pretrained = True self.model = timm.create_model('mobilenetv2_100', pretrained=pretrained, features_only=True) if freeze: for p in self.model.parameters(): p.requires_grad = False layers = [1,2,3,5,6] chans = [16, 24, 32, 96, 160] self.conv_stem = self.model.conv_stem self.bn1 = self.model.bn1 self.act1 = self.model.act1 self.block0 = torch.nn.Sequential(*self.model.blocks[0:layers[0]]) self.block1 = torch.nn.Sequential(*self.model.blocks[layers[0]:layers[1]]) self.block2 = torch.nn.Sequential(*self.model.blocks[layers[1]:layers[2]]) self.block3 = torch.nn.Sequential(*self.model.blocks[layers[2]:layers[3]]) self.block4 = torch.nn.Sequential(*self.model.blocks[layers[3]:layers[4]]) self.deconv32_16 = Conv2x_IN(chans[4], chans[3], deconv=True, concat=True) self.deconv16_8 = Conv2x_IN(chans[3]*2, chans[2], deconv=True, concat=True) self.deconv8_4 = Conv2x_IN(chans[2]*2, chans[1], deconv=True, concat=True) self.conv4 = BasicConv_IN(chans[1]*2, chans[1]*2, kernel_size=3, stride=1, padding=1) def forward(self, x): x = self.act1(self.bn1(self.conv_stem(x))) x2 = self.block0(x) x4 = self.block1(x2) x8 = self.block2(x4) x16 = self.block3(x8) x32 = self.block4(x16) x16 = self.deconv32_16(x32, x16) x8 = self.deconv16_8(x16, x8) x4 = self.deconv8_4(x8, x4) x4 = self.conv4(x4) return [x4, x8, x16, x32]