rednet.py 7.0 KB
Newer Older
jm_12138's avatar
jm_12138 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

C
cuicheng01 已提交
15
# Code was based on https://github.com/d-li14/involution
G
gaotingquan 已提交
16
# reference: https://arxiv.org/abs/2103.06255
C
cuicheng01 已提交
17

18 19 20 21 22
import paddle
import paddle.nn as nn

from paddle.vision.models import resnet

R
root 已提交
23
from ....utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url
24 25 26

MODEL_URLS = {
    "RedNet26":
C
cuicheng01 已提交
27
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet26_pretrained.pdparams",
28
    "RedNet38":
C
cuicheng01 已提交
29
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet38_pretrained.pdparams",
30
    "RedNet50":
C
cuicheng01 已提交
31
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet50_pretrained.pdparams",
32
    "RedNet101":
C
cuicheng01 已提交
33
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet101_pretrained.pdparams",
34
    "RedNet152":
C
cuicheng01 已提交
35
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet152_pretrained.pdparams"
36 37
}

jm_12138's avatar
jm_12138 已提交
38 39 40
__all__ = MODEL_URLS.keys()


41 42 43 44 45 46 47 48 49 50 51 52 53 54
class Involution(nn.Layer):
    def __init__(self, channels, kernel_size, stride):
        super(Involution, self).__init__()
        self.kernel_size = kernel_size
        self.stride = stride
        self.channels = channels
        reduction_ratio = 4
        self.group_channels = 16
        self.groups = self.channels // self.group_channels
        self.conv1 = nn.Sequential(
            ('conv', nn.Conv2D(
                in_channels=channels,
                out_channels=channels // reduction_ratio,
                kernel_size=1,
littletomatodonkey's avatar
littletomatodonkey 已提交
55
                bias_attr=False)),
56
            ('bn', nn.BatchNorm2D(channels // reduction_ratio)),
littletomatodonkey's avatar
littletomatodonkey 已提交
57 58 59 60 61 62
            ('activate', nn.ReLU()))
        self.conv2 = nn.Sequential(('conv', nn.Conv2D(
            in_channels=channels // reduction_ratio,
            out_channels=kernel_size**2 * self.groups,
            kernel_size=1,
            stride=1)))
63 64 65 66
        if stride > 1:
            self.avgpool = nn.AvgPool2D(stride, stride)

    def forward(self, x):
littletomatodonkey's avatar
littletomatodonkey 已提交
67 68
        weight = self.conv2(
            self.conv1(x if self.stride == 1 else self.avgpool(x)))
69
        b, c, h, w = weight.shape
littletomatodonkey's avatar
littletomatodonkey 已提交
70 71
        weight = weight.reshape(
            (b, self.groups, self.kernel_size**2, h, w)).unsqueeze(2)
72

littletomatodonkey's avatar
littletomatodonkey 已提交
73 74 75 76
        out = nn.functional.unfold(x, self.kernel_size, self.stride,
                                   (self.kernel_size - 1) // 2, 1)
        out = out.reshape(
            (b, self.groups, self.group_channels, self.kernel_size**2, h, w))
77 78 79 80 81
        out = (weight * out).sum(axis=3).reshape((b, self.channels, h, w))
        return out


class BottleneckBlock(resnet.BottleneckBlock):
littletomatodonkey's avatar
littletomatodonkey 已提交
82 83 84 85 86 87 88 89 90 91 92 93
    def __init__(self,
                 inplanes,
                 planes,
                 stride=1,
                 downsample=None,
                 groups=1,
                 base_width=64,
                 dilation=1,
                 norm_layer=None):
        super(BottleneckBlock, self).__init__(inplanes, planes, stride,
                                              downsample, groups, base_width,
                                              dilation, norm_layer)
94 95 96 97 98
        width = int(planes * (base_width / 64.)) * groups
        self.conv2 = Involution(width, 7, stride)


class RedNet(resnet.ResNet):
littletomatodonkey's avatar
littletomatodonkey 已提交
99
    def __init__(self, block, depth, class_num=1000, with_pool=True):
100
        super(RedNet, self).__init__(
littletomatodonkey's avatar
littletomatodonkey 已提交
101
            block=block, depth=50, num_classes=class_num, with_pool=with_pool)
102 103 104 105 106 107 108 109 110 111 112 113 114
        layer_cfg = {
            26: [1, 2, 4, 1],
            38: [2, 3, 5, 2],
            50: [3, 4, 6, 3],
            101: [3, 4, 23, 3],
            152: [3, 8, 36, 3]
        }
        layers = layer_cfg[depth]

        self.conv1 = None
        self.bn1 = None
        self.relu = None
        self.inplanes = 64
littletomatodonkey's avatar
littletomatodonkey 已提交
115
        self.class_num = class_num
116 117 118 119 120 121 122 123
        self.stem = nn.Sequential(
            nn.Sequential(
                ('conv', nn.Conv2D(
                    in_channels=3,
                    out_channels=self.inplanes // 2,
                    kernel_size=3,
                    stride=2,
                    padding=1,
littletomatodonkey's avatar
littletomatodonkey 已提交
124
                    bias_attr=False)),
125
                ('bn', nn.BatchNorm2D(self.inplanes // 2)),
littletomatodonkey's avatar
littletomatodonkey 已提交
126
                ('activate', nn.ReLU())),
127 128 129 130 131 132 133 134 135 136
            Involution(self.inplanes // 2, 3, 1),
            nn.BatchNorm2D(self.inplanes // 2),
            nn.ReLU(),
            nn.Sequential(
                ('conv', nn.Conv2D(
                    in_channels=self.inplanes // 2,
                    out_channels=self.inplanes,
                    kernel_size=3,
                    stride=1,
                    padding=1,
littletomatodonkey's avatar
littletomatodonkey 已提交
137 138
                    bias_attr=False)), ('bn', nn.BatchNorm2D(self.inplanes)),
                ('activate', nn.ReLU())))
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

    def forward(self, x):
        x = self.stem(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        if self.with_pool:
            x = self.avgpool(x)

littletomatodonkey's avatar
littletomatodonkey 已提交
157
        if self.class_num > 0:
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
            x = paddle.flatten(x, 1)
            x = self.fc(x)

        return x


def _load_pretrained(pretrained, model, model_url, use_ssld=False):
    if pretrained is False:
        pass
    elif pretrained is True:
        load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
    elif isinstance(pretrained, str):
        load_dygraph_pretrain(model, pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type."
        )


def RedNet26(pretrained=False, **kwargs):
    model = RedNet(BottleneckBlock, 26, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["RedNet26"])
    return model


def RedNet38(pretrained=False, **kwargs):
    model = RedNet(BottleneckBlock, 38, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["RedNet38"])
    return model


def RedNet50(pretrained=False, **kwargs):
    model = RedNet(BottleneckBlock, 50, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["RedNet50"])
    return model


def RedNet101(pretrained=False, **kwargs):
    model = RedNet(BottleneckBlock, 101, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["RedNet101"])
    return model


def RedNet152(pretrained=False, **kwargs):
    model = RedNet(BottleneckBlock, 152, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["RedNet152"])
    return model