xception.py 12.6 KB
Newer Older
W
WuHaobo 已提交
1
import paddle
littletomatodonkey's avatar
littletomatodonkey 已提交
2 3 4
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
5 6
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
littletomatodonkey's avatar
littletomatodonkey 已提交
7
from paddle.nn.initializer import Uniform
8
import math
C
cuicheng01 已提交
9
import sys
W
WuHaobo 已提交
10

C
cuicheng01 已提交
11 12 13
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

MODEL_URLS = {
littletomatodonkey's avatar
littletomatodonkey 已提交
14 15 16 17 18 19 20
    "Xception41":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/Xception41_pretrained.pdparams",
    "Xception65":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/Xception65_pretrained.pdparams",
    "Xception71":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/Xception71_pretrained.pdparams"
}
C
cuicheng01 已提交
21 22

__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
23 24


littletomatodonkey's avatar
littletomatodonkey 已提交
25
class ConvBNLayer(nn.Layer):
26 27 28 29 30 31 32 33 34
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 groups=1,
                 act=None,
                 name=None):
        super(ConvBNLayer, self).__init__()
W
WuHaobo 已提交
35

36
        self._conv = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
37 38 39
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
40 41 42
            stride=stride,
            padding=(filter_size - 1) // 2,
            groups=groups,
littletomatodonkey's avatar
littletomatodonkey 已提交
43
            weight_attr=ParamAttr(name=name + "_weights"),
44 45 46 47 48 49 50 51 52
            bias_attr=False)
        bn_name = "bn_" + name
        self._batch_norm = BatchNorm(
            num_filters,
            act=act,
            param_attr=ParamAttr(name=bn_name + "_scale"),
            bias_attr=ParamAttr(name=bn_name + "_offset"),
            moving_mean_name=bn_name + '_mean',
            moving_variance_name=bn_name + '_variance')
W
WuHaobo 已提交
53

54 55 56 57
    def forward(self, inputs):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y
W
WuHaobo 已提交
58 59


littletomatodonkey's avatar
littletomatodonkey 已提交
60
class SeparableConv(nn.Layer):
61
    def __init__(self, input_channels, output_channels, stride=1, name=None):
W
wqz960 已提交
62
        super(SeparableConv, self).__init__()
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

        self._pointwise_conv = ConvBNLayer(
            input_channels, output_channels, 1, name=name + "_sep")
        self._depthwise_conv = ConvBNLayer(
            output_channels,
            output_channels,
            3,
            stride=stride,
            groups=output_channels,
            name=name + "_dw")

    def forward(self, inputs):
        x = self._pointwise_conv(inputs)
        x = self._depthwise_conv(x)
        return x


littletomatodonkey's avatar
littletomatodonkey 已提交
80
class EntryFlowBottleneckBlock(nn.Layer):
81 82 83 84 85 86
    def __init__(self,
                 input_channels,
                 output_channels,
                 stride=2,
                 name=None,
                 relu_first=False):
W
wqz960 已提交
87
        super(EntryFlowBottleneckBlock, self).__init__()
88 89
        self.relu_first = relu_first

90
        self._short = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
91 92 93
            in_channels=input_channels,
            out_channels=output_channels,
            kernel_size=1,
W
WuHaobo 已提交
94 95
            stride=stride,
            padding=0,
littletomatodonkey's avatar
littletomatodonkey 已提交
96
            weight_attr=ParamAttr(name + "_branch1_weights"),
W
WuHaobo 已提交
97
            bias_attr=False)
W
wqz960 已提交
98
        self._conv1 = SeparableConv(
99 100 101 102
            input_channels,
            output_channels,
            stride=1,
            name=name + "_branch2a_weights")
W
wqz960 已提交
103
        self._conv2 = SeparableConv(
104 105 106 107
            output_channels,
            output_channels,
            stride=1,
            name=name + "_branch2b_weights")
108
        self._pool = MaxPool2D(kernel_size=3, stride=stride, padding=1)
109 110 111 112 113

    def forward(self, inputs):
        conv0 = inputs
        short = self._short(inputs)
        if self.relu_first:
littletomatodonkey's avatar
littletomatodonkey 已提交
114
            conv0 = F.relu(conv0)
115
        conv1 = self._conv1(conv0)
littletomatodonkey's avatar
littletomatodonkey 已提交
116
        conv2 = F.relu(conv1)
117 118
        conv2 = self._conv2(conv2)
        pool = self._pool(conv2)
119
        return paddle.add(x=short, y=pool)
W
WuHaobo 已提交
120 121


littletomatodonkey's avatar
littletomatodonkey 已提交
122
class EntryFlow(nn.Layer):
123
    def __init__(self, block_num=3):
W
wqz960 已提交
124
        super(EntryFlow, self).__init__()
W
WuHaobo 已提交
125

126 127 128 129 130 131
        name = "entry_flow"
        self.block_num = block_num
        self._conv1 = ConvBNLayer(
            3, 32, 3, stride=2, act="relu", name=name + "_conv1")
        self._conv2 = ConvBNLayer(32, 64, 3, act="relu", name=name + "_conv2")
        if block_num == 3:
W
wqz960 已提交
132
            self._conv_0 = EntryFlowBottleneckBlock(
133
                64, 128, stride=2, name=name + "_0", relu_first=False)
W
wqz960 已提交
134
            self._conv_1 = EntryFlowBottleneckBlock(
135
                128, 256, stride=2, name=name + "_1", relu_first=True)
W
wqz960 已提交
136
            self._conv_2 = EntryFlowBottleneckBlock(
137 138
                256, 728, stride=2, name=name + "_2", relu_first=True)
        elif block_num == 5:
W
wqz960 已提交
139
            self._conv_0 = EntryFlowBottleneckBlock(
140
                64, 128, stride=2, name=name + "_0", relu_first=False)
W
wqz960 已提交
141
            self._conv_1 = EntryFlowBottleneckBlock(
142
                128, 256, stride=1, name=name + "_1", relu_first=True)
W
wqz960 已提交
143
            self._conv_2 = EntryFlowBottleneckBlock(
144
                256, 256, stride=2, name=name + "_2", relu_first=True)
W
wqz960 已提交
145
            self._conv_3 = EntryFlowBottleneckBlock(
146
                256, 728, stride=1, name=name + "_3", relu_first=True)
W
wqz960 已提交
147
            self._conv_4 = EntryFlowBottleneckBlock(
148 149 150
                728, 728, stride=2, name=name + "_4", relu_first=True)
        else:
            sys.exit(-1)
W
WuHaobo 已提交
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    def forward(self, inputs):
        x = self._conv1(inputs)
        x = self._conv2(x)

        if self.block_num == 3:
            x = self._conv_0(x)
            x = self._conv_1(x)
            x = self._conv_2(x)
        elif self.block_num == 5:
            x = self._conv_0(x)
            x = self._conv_1(x)
            x = self._conv_2(x)
            x = self._conv_3(x)
            x = self._conv_4(x)
        return x


littletomatodonkey's avatar
littletomatodonkey 已提交
169
class MiddleFlowBottleneckBlock(nn.Layer):
170
    def __init__(self, input_channels, output_channels, name):
W
wqz960 已提交
171
        super(MiddleFlowBottleneckBlock, self).__init__()
172

W
wqz960 已提交
173
        self._conv_0 = SeparableConv(
174 175
            input_channels,
            output_channels,
W
WuHaobo 已提交
176 177
            stride=1,
            name=name + "_branch2a_weights")
W
wqz960 已提交
178
        self._conv_1 = SeparableConv(
179 180
            output_channels,
            output_channels,
W
WuHaobo 已提交
181 182
            stride=1,
            name=name + "_branch2b_weights")
W
wqz960 已提交
183
        self._conv_2 = SeparableConv(
184 185
            output_channels,
            output_channels,
W
WuHaobo 已提交
186 187 188
            stride=1,
            name=name + "_branch2c_weights")

189
    def forward(self, inputs):
littletomatodonkey's avatar
littletomatodonkey 已提交
190
        conv0 = F.relu(inputs)
191
        conv0 = self._conv_0(conv0)
littletomatodonkey's avatar
littletomatodonkey 已提交
192
        conv1 = F.relu(conv0)
193
        conv1 = self._conv_1(conv1)
littletomatodonkey's avatar
littletomatodonkey 已提交
194
        conv2 = F.relu(conv1)
195
        conv2 = self._conv_2(conv2)
196
        return paddle.add(x=inputs, y=conv2)
197 198


littletomatodonkey's avatar
littletomatodonkey 已提交
199
class MiddleFlow(nn.Layer):
200
    def __init__(self, block_num=8):
W
wqz960 已提交
201
        super(MiddleFlow, self).__init__()
202 203

        self.block_num = block_num
W
wqz960 已提交
204
        self._conv_0 = MiddleFlowBottleneckBlock(
205
            728, 728, name="middle_flow_0")
W
wqz960 已提交
206
        self._conv_1 = MiddleFlowBottleneckBlock(
207
            728, 728, name="middle_flow_1")
W
wqz960 已提交
208
        self._conv_2 = MiddleFlowBottleneckBlock(
209
            728, 728, name="middle_flow_2")
W
wqz960 已提交
210
        self._conv_3 = MiddleFlowBottleneckBlock(
211
            728, 728, name="middle_flow_3")
W
wqz960 已提交
212
        self._conv_4 = MiddleFlowBottleneckBlock(
213
            728, 728, name="middle_flow_4")
W
wqz960 已提交
214
        self._conv_5 = MiddleFlowBottleneckBlock(
215
            728, 728, name="middle_flow_5")
W
wqz960 已提交
216
        self._conv_6 = MiddleFlowBottleneckBlock(
217
            728, 728, name="middle_flow_6")
W
wqz960 已提交
218
        self._conv_7 = MiddleFlowBottleneckBlock(
219 220
            728, 728, name="middle_flow_7")
        if block_num == 16:
W
wqz960 已提交
221
            self._conv_8 = MiddleFlowBottleneckBlock(
222
                728, 728, name="middle_flow_8")
W
wqz960 已提交
223
            self._conv_9 = MiddleFlowBottleneckBlock(
224
                728, 728, name="middle_flow_9")
W
wqz960 已提交
225
            self._conv_10 = MiddleFlowBottleneckBlock(
226
                728, 728, name="middle_flow_10")
W
wqz960 已提交
227
            self._conv_11 = MiddleFlowBottleneckBlock(
228
                728, 728, name="middle_flow_11")
W
wqz960 已提交
229
            self._conv_12 = MiddleFlowBottleneckBlock(
230
                728, 728, name="middle_flow_12")
W
wqz960 已提交
231
            self._conv_13 = MiddleFlowBottleneckBlock(
232
                728, 728, name="middle_flow_13")
W
wqz960 已提交
233
            self._conv_14 = MiddleFlowBottleneckBlock(
234
                728, 728, name="middle_flow_14")
W
wqz960 已提交
235
            self._conv_15 = MiddleFlowBottleneckBlock(
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
                728, 728, name="middle_flow_15")

    def forward(self, inputs):
        x = self._conv_0(inputs)
        x = self._conv_1(x)
        x = self._conv_2(x)
        x = self._conv_3(x)
        x = self._conv_4(x)
        x = self._conv_5(x)
        x = self._conv_6(x)
        x = self._conv_7(x)
        if self.block_num == 16:
            x = self._conv_8(x)
            x = self._conv_9(x)
            x = self._conv_10(x)
            x = self._conv_11(x)
            x = self._conv_12(x)
            x = self._conv_13(x)
            x = self._conv_14(x)
            x = self._conv_15(x)
        return x


littletomatodonkey's avatar
littletomatodonkey 已提交
259
class ExitFlowBottleneckBlock(nn.Layer):
260 261
    def __init__(self, input_channels, output_channels1, output_channels2,
                 name):
W
wqz960 已提交
262
        super(ExitFlowBottleneckBlock, self).__init__()
263

264
        self._short = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
265 266 267
            in_channels=input_channels,
            out_channels=output_channels2,
            kernel_size=1,
W
WuHaobo 已提交
268 269
            stride=2,
            padding=0,
littletomatodonkey's avatar
littletomatodonkey 已提交
270
            weight_attr=ParamAttr(name + "_branch1_weights"),
W
WuHaobo 已提交
271
            bias_attr=False)
W
wqz960 已提交
272
        self._conv_1 = SeparableConv(
273 274 275 276
            input_channels,
            output_channels1,
            stride=1,
            name=name + "_branch2a_weights")
W
wqz960 已提交
277
        self._conv_2 = SeparableConv(
278 279 280 281
            output_channels1,
            output_channels2,
            stride=1,
            name=name + "_branch2b_weights")
282
        self._pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
283 284 285

    def forward(self, inputs):
        short = self._short(inputs)
littletomatodonkey's avatar
littletomatodonkey 已提交
286
        conv0 = F.relu(inputs)
287
        conv1 = self._conv_1(conv0)
littletomatodonkey's avatar
littletomatodonkey 已提交
288
        conv2 = F.relu(conv1)
289 290
        conv2 = self._conv_2(conv2)
        pool = self._pool(conv2)
291
        return paddle.add(x=short, y=pool)
W
WuHaobo 已提交
292 293


littletomatodonkey's avatar
littletomatodonkey 已提交
294
class ExitFlow(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
295
    def __init__(self, class_num):
W
wqz960 已提交
296
        super(ExitFlow, self).__init__()
W
WuHaobo 已提交
297

298
        name = "exit_flow"
W
WuHaobo 已提交
299

W
wqz960 已提交
300
        self._conv_0 = ExitFlowBottleneckBlock(
301
            728, 728, 1024, name=name + "_1")
W
wqz960 已提交
302 303
        self._conv_1 = SeparableConv(1024, 1536, stride=1, name=name + "_2")
        self._conv_2 = SeparableConv(1536, 2048, stride=1, name=name + "_3")
304
        self._pool = AdaptiveAvgPool2D(1)
305 306 307
        stdv = 1.0 / math.sqrt(2048 * 1.0)
        self._out = Linear(
            2048,
littletomatodonkey's avatar
littletomatodonkey 已提交
308
            class_num,
littletomatodonkey's avatar
littletomatodonkey 已提交
309 310
            weight_attr=ParamAttr(
                name="fc_weights", initializer=Uniform(-stdv, stdv)),
311 312 313 314 315
            bias_attr=ParamAttr(name="fc_offset"))

    def forward(self, inputs):
        conv0 = self._conv_0(inputs)
        conv1 = self._conv_1(conv0)
littletomatodonkey's avatar
littletomatodonkey 已提交
316
        conv1 = F.relu(conv1)
317
        conv2 = self._conv_2(conv1)
littletomatodonkey's avatar
littletomatodonkey 已提交
318
        conv2 = F.relu(conv2)
319
        pool = self._pool(conv2)
L
littletomatodonkey 已提交
320
        pool = paddle.flatten(pool, start_axis=1, stop_axis=-1)
321 322
        out = self._out(pool)
        return out
W
WuHaobo 已提交
323

324

littletomatodonkey's avatar
littletomatodonkey 已提交
325
class Xception(nn.Layer):
326 327 328
    def __init__(self,
                 entry_flow_block_num=3,
                 middle_flow_block_num=8,
littletomatodonkey's avatar
littletomatodonkey 已提交
329
                 class_num=1000):
330 331 332
        super(Xception, self).__init__()
        self.entry_flow_block_num = entry_flow_block_num
        self.middle_flow_block_num = middle_flow_block_num
W
wqz960 已提交
333 334
        self._entry_flow = EntryFlow(entry_flow_block_num)
        self._middle_flow = MiddleFlow(middle_flow_block_num)
littletomatodonkey's avatar
littletomatodonkey 已提交
335
        self._exit_flow = ExitFlow(class_num)
336 337 338 339 340 341

    def forward(self, inputs):
        x = self._entry_flow(inputs)
        x = self._middle_flow(x)
        x = self._exit_flow(x)
        return x
W
WuHaobo 已提交
342

littletomatodonkey's avatar
littletomatodonkey 已提交
343

C
cuicheng01 已提交
344 345 346 347 348 349 350 351 352 353 354
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."
        )
littletomatodonkey's avatar
littletomatodonkey 已提交
355

C
cuicheng01 已提交
356 357 358

def Xception41(pretrained=False, use_ssld=False, **kwargs):
    model = Xception(entry_flow_block_num=3, middle_flow_block_num=8, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
359 360
    _load_pretrained(
        pretrained, model, MODEL_URLS["Xception41"], use_ssld=use_ssld)
W
WuHaobo 已提交
361 362 363
    return model


C
cuicheng01 已提交
364
def Xception65(pretrained=False, use_ssld=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
365 366 367 368
    model = Xception(
        entry_flow_block_num=3, middle_flow_block_num=16, **kwargs)
    _load_pretrained(
        pretrained, model, MODEL_URLS["Xception65"], use_ssld=use_ssld)
W
WuHaobo 已提交
369 370 371
    return model


C
cuicheng01 已提交
372
def Xception71(pretrained=False, use_ssld=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
373 374 375 376
    model = Xception(
        entry_flow_block_num=5, middle_flow_block_num=16, **kwargs)
    _load_pretrained(
        pretrained, model, MODEL_URLS["Xception71"], use_ssld=use_ssld)
littletomatodonkey's avatar
littletomatodonkey 已提交
377
    return model