code
stringlengths
17
6.64M
def rla_mobilenetv2_k12(): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k12......') model = RLA_MobileNetV2(rla_channel=12) return model
def rla_mobilenetv2_k12_eca(eca=True): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k12_eca......') model = RLA_MobileNetV2(rla_channel=12, ECA=eca) return model
def rla_mobilenetv2_k24(): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k24......') model = RLA_MobileNetV2(rla_channel=24) return model
def rla_mobilenetv2_k24_eca(eca=True): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k24_eca......') model = RLA_MobileNetV2(rla_channel=24, ECA=eca) return model
def rla_mobilenetv2_k32(): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k32......') model = RLA_MobileNetV2(rla_channel=32) return model
def rla_mobilenetv2_k32_eca(eca=True): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k32_eca......') model = RLA_MobileNetV2(rla_channel=32, ECA=eca) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) if (self.downsample is not None): identity = self.downsample(x) out += identity out = self.relu(out) return out
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0], SE, ECA[0]) self.layer2 = self._make_layer(block, 128, layers[1], SE, ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) self.layer3 = self._make_layer(block, 256, layers[2], SE, ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) self.layer4 = self._make_layer(block, 512, layers[3], SE, ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear((512 * block.expansion), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, SE, ECA_size, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def resnet50(): ' Constructs a ResNet-50 model.\n default: \n num_classes=1000, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing resnet50......') model = ResNet(Bottleneck, [3, 4, 6, 3]) return model
def resnet50_se(): ' Constructs a ResNet-50_SE model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnet50_se......') model = ResNet(Bottleneck, [3, 4, 6, 3], SE=True) return model
def resnet50_eca(k_size=[5, 5, 5, 7]): 'Constructs a ResNet-50_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n num_classes:The classes of classification\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' print('Constructing resnet50_eca......') model = ResNet(Bottleneck, [3, 4, 6, 3], ECA=k_size) return model
def resnet101(): ' Constructs a ResNet-101 model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnet101......') model = ResNet(Bottleneck, [3, 4, 23, 3]) return model
def resnet101_se(): ' Constructs a ResNet-101_SE model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnet101_se......') model = ResNet(Bottleneck, [3, 4, 23, 3], SE=True) return model
def resnet101_eca(k_size=[5, 5, 5, 7]): 'Constructs a ResNet-101_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n ' print('Constructing resnet101_eca......') model = ResNet(Bottleneck, [3, 4, 23, 3], ECA=k_size) return model
def resnet152(): ' Constructs a ResNet-152 model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnet152......') model = ResNet(Bottleneck, [3, 8, 36, 3]) return model
def resnet152_se(): ' Constructs a ResNet-152_SE model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnet152_se......') model = ResNet(Bottleneck, [3, 8, 36, 3], SE=True) return model
def resnet152_eca(k_size=[5, 5, 5, 7]): 'Constructs a ResNet-152_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n ' print('Constructing resnet152_eca......') model = ResNet(Bottleneck, [3, 8, 36, 3], ECA=k_size) return model
def resnext50_32x4d(): ' Constructs a ResNeXt50_32x4d model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnext50_32x4d......') model = ResNet(Bottleneck, [3, 4, 6, 3], groups=32, width_per_group=4) return model
def resnext50_32x4d_se(): ' Constructs a ResNeXt50_32x4d_SE model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnext50_32x4d_se......') model = ResNet(Bottleneck, [3, 4, 6, 3], SE=True, groups=32, width_per_group=4) return model
def resnext50_32x4d_eca(k_size=[5, 5, 5, 7]): 'Constructs a ResNeXt50_32x4d_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n ' print('Constructing resnext50_32x4d_eca......') model = ResNet(Bottleneck, [3, 4, 6, 3], ECA=k_size, groups=32, width_per_group=4) return model
def resnext101_32x4d(): ' Constructs a ResNeXt101_32x4d model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnext101_32x4d......') model = ResNet(Bottleneck, [3, 4, 23, 3], groups=32, width_per_group=4) return model
def resnext101_32x4d_se(): ' Constructs a ResNeXt101_32x4d_SE model.\n default: \n num_classes=1000, SE=False, ECA=None\n ' print('Constructing resnext101_32x4d_se......') model = ResNet(Bottleneck, [3, 4, 23, 3], SE=True, groups=32, width_per_group=4) return model
def resnext101_32x4d_eca(k_size=[5, 5, 5, 7]): 'Constructs a ResNeXt101_32x4d_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n ' print('Constructing resnext101_32x4d_eca......') model = ResNet(Bottleneck, [3, 4, 23, 3], ECA=k_size, groups=32, width_per_group=4) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) if (self.downsample is not None): identity = self.downsample(x) out += identity out = self.relu(out) return out
class ResNet_k(nn.Module): def __init__(self, block, layers, num_classes=1000, SE=False, ECA=None, channel_k=32, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet_k, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 self.expansion = 4 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) add_k = int((channel_k / self.expansion)) self.layer1 = self._make_layer(block, (64 + add_k), layers[0], SE, ECA[0]) self.layer2 = self._make_layer(block, (128 + add_k), layers[1], SE, ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) self.layer3 = self._make_layer(block, (256 + add_k), layers[2], SE, ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) self.layer4 = self._make_layer(block, (512 + add_k), layers[3], SE, ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 + add_k) * block.expansion), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, SE, ECA_size, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def resnet50_k(channel_k=32): ' Constructs a ResNet-50 model.\n default: \n num_classes=1000, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing resnet50_k......') model = ResNet_k(Bottleneck, [3, 4, 6, 3], channel_k=channel_k) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLA_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLA_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h)
class RLA_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLA_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLA_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() h = torch.zeros(batch, self.rla_channel, height, width, device=torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))) for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h) = layer(x, h) y_out = conv_out(y) h = (h + y_out) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rla_resnet50(rla_channel=32): ' Constructs a RLA_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rla_resnet50......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 6, 3]) return model
def rla_resnet50_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLA_ResNet-50_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rla_resnet50_eca......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 6, 3], rla_channel=rla_channel, ECA=k_size) return model
def rla_resnet101(rla_channel=32): ' Constructs a RLA_ResNet-101 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnet101......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 23, 3]) return model
def rla_resnet101_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLA_ResNet-101_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rla_resnet101_eca......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 23, 3], ECA=k_size) return model
def rla_resnet152(rla_channel=32): ' Constructs a RLA_ResNet-152 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnet152......') model = RLA_ResNet(RLA_Bottleneck, [3, 8, 36, 3]) return model
def rla_resnet152_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLA_ResNet-101_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rla_resnet101_eca......') model = RLA_ResNet(RLA_Bottleneck, [3, 8, 36, 3], ECA=k_size) return model
def rla_resnext50_32x4d(rla_channel=32): ' Constructs a RLA_ResNeXt50_32x4d model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnext50_32x4d......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 6, 3], groups=32, width_per_group=4) return model
def rla_resnext50_32x4d_se(rla_channel=32): ' Constructs a RLA_ResNeXt50_32x4d_SE model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnext50_32x4d_se......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 6, 3], SE=True, groups=32, width_per_group=4) return model
def rla_resnext50_32x4d_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLA_ResNeXt50_32x4d_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rla_resnext50_32x4d_eca......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 6, 3], ECA=k_size, groups=32, width_per_group=4) return model
def rla_resnext101_32x4d(rla_channel=32): ' Constructs a RLA_ResNeXt101_32x4d model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnext101_32x4d......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 23, 3], groups=32, width_per_group=4) return model
def rla_resnext101_32x4d_se(rla_channel=32): ' Constructs a RLA_ResNeXt101_32x4d_SE model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ' print('Constructing rla_resnext101_32x4d_se......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 23, 3], SE=True, groups=32, width_per_group=4) return model
def rla_resnext101_32x4d_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLA_ResNeXt101_32x4d_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rla_resnext101_32x4d_eca......') model = RLA_ResNet(RLA_Bottleneck, [3, 4, 23, 3], ECA=k_size, groups=32, width_per_group=4) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLA_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLA_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h)
class RLAgru_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAgru_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLA_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_convgru = ConvGRUCell_layer(rla_channel, rla_channel, 3) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_convgru) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_convgru) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h) = layer(x, h) y_out = conv_out(y) y_out = bn(y_out) y_out = self.tanh(y_out) h = recurrent_convgru(y_out, h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlagru_resnet50(rla_channel=32): ' Constructs a RLAgru_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlagru_resnet50......') model = RLAgru_ResNet(RLA_Bottleneck, [3, 4, 6, 3]) return model
def rlagru_resnet50_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLAgru_ResNet-50_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rlagru_resnet50_eca......') model = RLAgru_ResNet(RLA_Bottleneck, [3, 4, 6, 3], rla_channel=rla_channel, ECA=k_size) return model
def rlagru_resnet101(rla_channel=32): ' Constructs a RLAgru_ResNet-101 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlagru_resnet101......') model = RLAgru_ResNet(RLA_Bottleneck, [3, 4, 23, 3]) return model
def rlagru_resnet101_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLAgru_ResNet-101_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rlagru_resnet101_eca......') model = RLAgru_ResNet(RLA_Bottleneck, [3, 4, 23, 3], rla_channel=rla_channel, ECA=k_size) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLA_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLA_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h, c): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) c = self.averagePooling(c) out += identity out = self.relu(out) return (out, y, h, c)
class RLAlstm_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAlstm_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLA_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_convlstm = ConvLSTMCell_layer(rla_channel, rla_channel, (3, 3)) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_convlstm) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) c = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') c = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_convlstm) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, c) = layer(x, h, c) y_out = conv_out(y) y_out = bn(y_out) y_out = self.tanh(y_out) (h, c) = recurrent_convlstm(y_out, (h, c)) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlalstm_resnet50(rla_channel=32): ' Constructs a RLAlstm_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlalstm_resnet50......') model = RLAlstm_ResNet(RLA_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLArh_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLArh_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLArh_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLArh_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLArh_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) y_out = conv_out(y) h = (h + y_out) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlarh_resnet50(rla_channel=32): ' Constructs a RLArh_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlarh_resnet50......') model = RLArh_ResNet(RLArh_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAus_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAus_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=False) self.downsample = downsample self.stride = stride self.conv_out = conv1x1((planes * self.expansion), rla_channel) self.recurrent_conv = conv3x3(rla_channel, rla_channel) self.bn_rla = norm_layer(rla_channel) self.tanh_rla = nn.Tanh() self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) y_out = self.conv_out(y) h = (h + y_out) h = self.bn_rla(h) h = self.tanh_rla(h) h = self.recurrent_conv(h) out = (out + identity) out = self.relu(out) return (out, h)
class RLAus_ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAus_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=False) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) stages = ([None] * 4) stages[0] = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) stages[1] = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) stages[2] = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) stages[3] = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.stages = nn.ModuleList(stages) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAus_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.ModuleList(layers) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for layers in self.stages: for layer in layers: (x, h) = layer(x, h) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlaus_resnet50(rla_channel=32): ' Constructs a RLAus_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlaus_resnet50......') model = RLAus_ResNet(RLAus_Bottleneck, [3, 4, 6, 3]) return model
def rlaus_resnet101(rla_channel=32): ' Constructs a RLAus_ResNet-101 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlaus_resnet101......') model = RLAus_ResNet(RLAus_Bottleneck, [3, 4, 23, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv1_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv1_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv1_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv1_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv1_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() h = torch.zeros(batch, self.rla_channel, height, width, device=torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))) for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) y_out = conv_out(y) h = (h + y_out) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) h = self.bn2(h) h = self.tanh(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlav1_resnet50(rla_channel=32): ' Constructs a RLAv1_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlav1_resnet50......') model = RLAv1_ResNet(RLAv1_Bottleneck, [3, 4, 6, 3]) return model
def rlav1_resnet50_eca(rla_channel=32, k_size=[5, 5, 5, 7]): 'Constructs a RLAv1_ResNet-50_ECA model.\n Args:\n k_size: Adaptive selection of kernel size\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n ' print('Constructing rlav1_resnet50_eca......') model = RLAv1_ResNet(RLAv1_Bottleneck, [3, 4, 6, 3], rla_channel=rla_channel, ECA=k_size) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv1p_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv1p_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv1p_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv1p_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv1p_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) y_out = conv_out(y) h = (h + y_out) h = recurrent_conv(h) h = bn(h) h = self.tanh(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlav1p_resnet50(rla_channel=32): ' Constructs a RLAv1p_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlav1p_resnet50......') model = RLAv1p_ResNet(RLAv1p_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv2_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv2_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv2_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv2_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv2_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) y_out = conv_out(y) h = (h + y_out) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlav2_resnet50(rla_channel=32): ' Constructs a RLAv2_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlav2_resnet50......') model = RLAv2_ResNet(RLAv2_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv3_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv3_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv3_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv3_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv3_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) x_out = conv_out(x) h = (h + x_out) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlav3_resnet50(rla_channel=32): ' Constructs a RLAv3_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlav3_resnet50......') model = RLAv3_ResNet(RLAv3_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv4_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv4_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv4_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv4_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv4_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) x_out = conv_out(x) h = (h + x_out) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)
def rlav4_resnet50(rla_channel=32): ' Constructs a RLAv4_ResNet-50 model.\n default: \n num_classes=1000, rla_channel=32, SE=False, ECA=None\n ECA: a list of kernel sizes in ECA\n ' print('Constructing rlav4_resnet50......') model = RLAv4_ResNet(RLAv4_Bottleneck, [3, 4, 6, 3]) return model
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class RLAv5_Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16): super(RLAv5_Bottleneck, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d width = (int((planes * (base_width / 64.0))) * groups) self.conv1 = conv1x1((inplanes + rla_channel), width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, (planes * self.expansion)) self.bn3 = norm_layer((planes * self.expansion)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.averagePooling = None if ((downsample is not None) and (stride != 1)): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) self.se = None if SE: self.se = SELayer((planes * self.expansion), reduction) self.eca = None if (ECA_size != None): self.eca = eca_layer((planes * self.expansion), int(ECA_size)) def forward(self, x, h): identity = x x = torch.cat((x, h), dim=1) out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.se != None): out = self.se(out) if (self.eca != None): out = self.eca(out) y = out if (self.downsample is not None): identity = self.downsample(identity) if (self.averagePooling is not None): h = self.averagePooling(h) out += identity out = self.relu(out) return (out, y, h, identity)
class RLAv5_ResNet(nn.Module): '\n rla_channel: the number of filters of the shared(recurrent) conv in RLA\n SE: whether use SE or not \n ECA: None: not use ECA, or specify a list of kernel sizes\n ' def __init__(self, block, layers, num_classes=1000, rla_channel=32, SE=False, ECA=None, zero_init_last_bn=True, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(RLAv5_ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if (replace_stride_with_dilation is None): replace_stride_with_dilation = [False, False, False] if (len(replace_stride_with_dilation) != 3): raise ValueError('replace_stride_with_dilation should be None or a 3-element tuple, got {}'.format(replace_stride_with_dilation)) if (ECA is None): ECA = ([None] * 4) elif (len(ECA) != 4): raise ValueError('argument ECA should be a 4-element tuple, got {}'.format(ECA)) self.rla_channel = rla_channel self.flops = False self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) conv_outs = ([None] * 4) recurrent_convs = ([None] * 4) stages = ([None] * 4) stage_bns = ([None] * 4) (stages[0], stage_bns[0], conv_outs[0], recurrent_convs[0]) = self._make_layer(block, 64, layers[0], rla_channel=rla_channel, SE=SE, ECA_size=ECA[0]) (stages[1], stage_bns[1], conv_outs[1], recurrent_convs[1]) = self._make_layer(block, 128, layers[1], rla_channel=rla_channel, SE=SE, ECA_size=ECA[1], stride=2, dilate=replace_stride_with_dilation[0]) (stages[2], stage_bns[2], conv_outs[2], recurrent_convs[2]) = self._make_layer(block, 256, layers[2], rla_channel=rla_channel, SE=SE, ECA_size=ECA[2], stride=2, dilate=replace_stride_with_dilation[1]) (stages[3], stage_bns[3], conv_outs[3], recurrent_convs[3]) = self._make_layer(block, 512, layers[3], rla_channel=rla_channel, SE=SE, ECA_size=ECA[3], stride=2, dilate=replace_stride_with_dilation[2]) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stages = nn.ModuleList(stages) self.stage_bns = nn.ModuleList(stage_bns) self.tanh = nn.Tanh() self.bn2 = norm_layer(rla_channel) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(((512 * block.expansion) + rla_channel), num_classes) 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.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) if zero_init_last_bn: for m in self.modules(): if isinstance(m, RLAv5_Bottleneck): nn.init.constant_(m.bn3.weight, 0) def _make_layer(self, block, planes, blocks, rla_channel, SE, ECA_size, stride=1, dilate=False): conv_out = conv1x1((planes * block.expansion), rla_channel) recurrent_conv = conv3x3(rla_channel, rla_channel) norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(conv1x1(self.inplanes, (planes * block.expansion), stride), norm_layer((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=previous_dilation, norm_layer=norm_layer)) self.inplanes = (planes * block.expansion) for _ in range(1, blocks): layers.append(block(self.inplanes, planes, rla_channel=rla_channel, SE=SE, ECA_size=ECA_size, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) bns = [norm_layer(rla_channel) for _ in range(blocks)] return (nn.ModuleList(layers), nn.ModuleList(bns), conv_out, recurrent_conv) def _forward_impl(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) (batch, _, height, width) = x.size() if self.flops: h = torch.zeros(batch, self.rla_channel, height, width) else: h = torch.zeros(batch, self.rla_channel, height, width, device='cuda') for (layers, bns, conv_out, recurrent_conv) in zip(self.stages, self.stage_bns, self.conv_outs, self.recurrent_convs): for (layer, bn) in zip(layers, bns): (x, y, h, identity) = layer(x, h) identity_out = conv_out(identity) h = (h + identity_out) h = bn(h) h = self.tanh(h) h = recurrent_conv(h) h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x)