code
stringlengths
17
6.64M
def conv_out(in_planes, out_planes): '1x1 convolution' return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, bias=False)
def recurrent_conv(in_planes, out_planes): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, groups=1, bias=False)
def _make_divisible(v: float, divisor: int, min_value: Optional[int]=None) -> int: '\n This function is taken from the original tf repo.\n It ensures that all layers have a channel number that is divisible by 8\n It can be seen here:\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n :param v:\n :param divisor:\n :param min_value:\n :return:\n ' if (min_value is None): min_value = divisor new_v = max(min_value, ((int((v + (divisor / 2))) // divisor) * divisor)) if (new_v < (0.9 * v)): new_v += divisor return new_v
class ConvBNReLU(nn.Sequential): def __init__(self, in_planes: int, out_planes: int, kernel_size: int=3, stride: int=1, groups: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None) -> None: padding = ((kernel_size - 1) // 2) if (norm_layer is None): norm_layer = nn.BatchNorm2d super(ConvBNReLU, self).__init__(nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), norm_layer(out_planes), nn.ReLU6(inplace=True))
class InvertedResidual(nn.Module): def __init__(self, inp: int, oup: int, stride: int, expand_ratio: int, rla_channel: int, norm_layer: Optional[Callable[(..., nn.Module)]]=None, ECA_ksize=None) -> None: super(InvertedResidual, self).__init__() self.stride = stride assert (stride in [1, 2]) if (norm_layer is None): norm_layer = nn.BatchNorm2d hidden_dim = int(round((inp * expand_ratio))) hidden_rla = (hidden_dim + rla_channel) self.use_res_connect = ((self.stride == 1) and (inp == oup)) self.conv1x1 = None if (expand_ratio != 1): self.conv1x1 = ConvBNReLU(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer) layers: List[nn.Module] = [] layers.extend([ConvBNReLU(hidden_rla, hidden_rla, stride=stride, groups=hidden_rla, norm_layer=norm_layer), nn.Conv2d(hidden_rla, oup, 1, 1, 0, bias=False), norm_layer(oup)]) self.eca_ksize = ECA_ksize if (ECA_ksize != None): layers.append(eca_layer(oup, ECA_ksize)) self.conv = nn.Sequential(*layers) self.averagePooling = None if (self.stride != 1): self.averagePooling = nn.AvgPool2d((2, 2), stride=(2, 2)) def forward(self, x: Tensor, h: Tensor) -> Tensor: identity = x if (self.conv1x1 is not None): x = self.conv1x1(x) x = torch.cat((x, h), dim=1) y = self.conv(x) if self.use_res_connect: out = (identity + y) else: out = y if (self.averagePooling is not None): h = self.averagePooling(h) return (out, y, h)
class RLA_MobileNetV2(nn.Module): def __init__(self, num_classes: int=1000, width_mult: float=1.0, rla_channel: int=32, inverted_residual_setting: Optional[List[List[int]]]=None, round_nearest: int=8, block: Optional[Callable[(..., nn.Module)]]=None, norm_layer: Optional[Callable[(..., nn.Module)]]=None, ECA=False) -> None: '\n MobileNet V2 main class\n\n Args:\n num_classes (int): Number of classes\n width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount\n inverted_residual_setting: Network structure\n round_nearest (int): Round the number of channels in each layer to be a multiple of this number\n Set to 1 to turn off rounding\n block: Module specifying inverted residual building block for mobilenet\n norm_layer: Module specifying the normalization layer to use\n\n ' super(RLA_MobileNetV2, self).__init__() if (block is None): block = InvertedResidual if (norm_layer is None): norm_layer = nn.BatchNorm2d input_channel = 32 last_channel = 1280 if (inverted_residual_setting is None): inverted_residual_setting = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1]] if ((len(inverted_residual_setting) == 0) or (len(inverted_residual_setting[0]) != 4)): raise ValueError('inverted_residual_setting should be non-empty or a 4-element list, got {}'.format(inverted_residual_setting)) input_channel = _make_divisible((input_channel * width_mult), round_nearest) self.last_channel = _make_divisible((last_channel * max(1.0, width_mult)), round_nearest) self.conv1 = ConvBNReLU(3, input_channel, stride=2, norm_layer=norm_layer) self.newcell = [0] for i in range(1, len(inverted_residual_setting)): if (inverted_residual_setting[i][3] == 2): self.newcell.append(i) num_stages = len(inverted_residual_setting) stages = ([None] * num_stages) stage_bns = ([None] * num_stages) conv_outs = ([None] * num_stages) recurrent_convs = ([recurrent_conv(rla_channel, rla_channel)] * len(self.newcell)) j = 0 for (t, c, n, s) in inverted_residual_setting: output_channel = _make_divisible((c * width_mult), round_nearest) stages[j] = [] stage_bns[j] = nn.ModuleList([norm_layer(rla_channel) for _ in range(n)]) conv_outs[j] = conv_out(output_channel, rla_channel) for i in range(n): if ECA: if (c < 96): ECA_ksize = 1 else: ECA_ksize = 3 else: ECA_ksize = None stride = (s if (i == 0) else 1) stages[j].append(block(input_channel, output_channel, stride, expand_ratio=t, rla_channel=rla_channel, norm_layer=norm_layer, ECA_ksize=ECA_ksize)) input_channel = output_channel stages[j] = nn.ModuleList(stages[j]) j += 1 self.stages = nn.ModuleList(stages) self.conv_outs = nn.ModuleList(conv_outs) self.recurrent_convs = nn.ModuleList(recurrent_convs) self.stage_bns = nn.ModuleList(stage_bns) self.rla_channel = rla_channel self.flops = False self.conv2 = ConvBNReLU((input_channel + rla_channel), self.last_channel, kernel_size=1, norm_layer=norm_layer) self.bn2 = norm_layer(rla_channel) self.relu = nn.ReLU6(inplace=True) self.tanh = nn.Tanh() self.classifier = nn.Sequential(nn.Dropout(0.2), nn.Linear(self.last_channel, num_classes)) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out') if (m.bias is not None): nn.init.zeros_(m.bias) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.zeros_(m.bias) def _forward_impl(self, x: Tensor) -> Tensor: x = self.conv1(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') j = 0 k = (- 1) for (stage, bns, conv_out) in zip(self.stages, self.stage_bns, self.conv_outs): if (j in self.newcell): k += 1 recurrent_conv = self.recurrent_convs[k] for (layer, bn) in zip(stage, 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) j += 1 h = self.bn2(h) h = self.relu(h) x = torch.cat((x, h), dim=1) x = self.conv2(x) x = nn.functional.adaptive_avg_pool2d(x, (1, 1)).reshape(x.shape[0], (- 1)) x = self.classifier(x) return x def forward(self, x: Tensor) -> Tensor: return self._forward_impl(x)
def rla_mobilenetv2(rla_channel=32): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2......') model = RLA_MobileNetV2(rla_channel=rla_channel) return model
def rla_mobilenetv2_eca(rla_channel=32, eca=True): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_eca......') model = RLA_MobileNetV2(rla_channel=rla_channel, ECA=eca) return model
def rla_mobilenetv2_k6(): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k6......') model = RLA_MobileNetV2(rla_channel=6) return model
def rla_mobilenetv2_k6_eca(eca=True): ' Constructs a RLA_MobileNetV2 model.\n default: \n rla_channel = 32, ECA=False\n ' print('Constructing rla_mobilenetv2_k6_eca......') model = RLA_MobileNetV2(rla_channel=6, ECA=eca) return model
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)