encnet.py 8.83 KB
Newer Older
Zhang's avatar
v0.4.2  
Zhang committed
1
2
3
4
5
6
7
8
9
###########################################################################
# Created by: Hang Zhang 
# Email: zhang.hang@rutgers.edu 
# Copyright (c) 2017
###########################################################################

import torch
from torch.autograd import Variable
import torch.nn as nn
Hang Zhang's avatar
Hang Zhang committed
10
import torch.nn.functional as F
Zhang's avatar
v0.4.2  
Zhang committed
11
12
13

from .base import BaseNet
from .fcn import FCNHead
Hang Zhang's avatar
Hang Zhang committed
14
from ..nn import SyncBatchNorm, Encoding, Mean
Zhang's avatar
v0.4.2  
Zhang committed
15

Hang Zhang's avatar
Hang Zhang committed
16
__all__ = ['EncNet', 'EncModule', 'get_encnet', 'get_encnet_resnet50_pcontext',
Hang Zhang's avatar
Hang Zhang committed
17
18
           'get_encnet_resnet101_pcontext', 'get_encnet_resnet50_ade',
           'get_encnet_resnet101_ade']
Zhang's avatar
v0.4.2  
Zhang committed
19
20

class EncNet(BaseNet):
Hang Zhang's avatar
Hang Zhang committed
21
    def __init__(self, nclass, backbone, aux=True, se_loss=True, lateral=False,
Hang Zhang's avatar
Hang Zhang committed
22
                 norm_layer=SyncBatchNorm, **kwargs):
Hang Zhang's avatar
Hang Zhang committed
23
24
        super(EncNet, self).__init__(nclass, backbone, aux, se_loss,
                                     norm_layer=norm_layer, **kwargs)
Hang Zhang's avatar
Hang Zhang committed
25
        self.head = EncHead(2048, self.nclass, se_loss=se_loss,
Hang Zhang's avatar
Hang Zhang committed
26
27
                            lateral=lateral, norm_layer=norm_layer,
                            up_kwargs=self._up_kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
28
29
30
31
32
        if aux:
            self.auxlayer = FCNHead(1024, nclass, norm_layer=norm_layer)

    def forward(self, x):
        imsize = x.size()[2:]
Hang Zhang's avatar
Hang Zhang committed
33
        features = self.base_forward(x)
Zhang's avatar
v0.4.2  
Zhang committed
34

Hang Zhang's avatar
Hang Zhang committed
35
        x = list(self.head(*features))
Hang Zhang's avatar
Hang Zhang committed
36
        x[0] = F.interpolate(x[0], imsize, **self._up_kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
37
        if self.aux:
Hang Zhang's avatar
Hang Zhang committed
38
            auxout = self.auxlayer(features[2])
Hang Zhang's avatar
Hang Zhang committed
39
            auxout = F.interpolate(auxout, imsize, **self._up_kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
40
41
42
43
44
45
46
47
48
            x.append(auxout)
        return tuple(x)


class EncModule(nn.Module):
    def __init__(self, in_channels, nclass, ncodes=32, se_loss=True, norm_layer=None):
        super(EncModule, self).__init__()
        self.se_loss = se_loss
        self.encoding = nn.Sequential(
Hang Zhang's avatar
Hang Zhang committed
49
            nn.Conv2d(in_channels, in_channels, 1, bias=False),
Hang Zhang's avatar
Hang Zhang committed
50
            norm_layer(in_channels),
Hang Zhang's avatar
Hang Zhang committed
51
            nn.ReLU(inplace=True),
Hang Zhang's avatar
Hang Zhang committed
52
53
            Encoding(D=in_channels, K=ncodes),
            norm_layer(ncodes),
Zhang's avatar
v0.4.2  
Zhang committed
54
            nn.ReLU(inplace=True),
Hang Zhang's avatar
Hang Zhang committed
55
            Mean(dim=1))
Zhang's avatar
v0.4.2  
Zhang committed
56
57
58
59
60
61
62
63
64
65
66
        self.fc = nn.Sequential(
            nn.Linear(in_channels, in_channels),
            nn.Sigmoid())
        if self.se_loss:
            self.selayer = nn.Linear(in_channels, nclass)

    def forward(self, x):
        en = self.encoding(x)
        b, c, _, _ = x.size()
        gamma = self.fc(en)
        y = gamma.view(b, c, 1, 1)
Hang Zhang's avatar
Hang Zhang committed
67
        outputs = [F.relu_(x + x * y)]
Zhang's avatar
v0.4.2  
Zhang committed
68
69
70
71
72
73
        if self.se_loss:
            outputs.append(self.selayer(en))
        return tuple(outputs)


class EncHead(nn.Module):
Hang Zhang's avatar
Hang Zhang committed
74
    def __init__(self, in_channels, out_channels, se_loss=True, lateral=True,
Zhang's avatar
v0.4.2  
Zhang committed
75
76
                 norm_layer=None, up_kwargs=None):
        super(EncHead, self).__init__()
Hang Zhang's avatar
Hang Zhang committed
77
78
79
        self.se_loss = se_loss
        self.lateral = lateral
        self.up_kwargs = up_kwargs
Zhang's avatar
v0.4.2  
Zhang committed
80
81
82
        self.conv5 = nn.Sequential(
            nn.Conv2d(in_channels, 512, 3, padding=1, bias=False),
            norm_layer(512),
Hang Zhang's avatar
Hang Zhang committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
            nn.ReLU(inplace=True))
        if lateral:
            self.connect = nn.ModuleList([
                nn.Sequential(
                    nn.Conv2d(512, 512, kernel_size=1, bias=False),
                    norm_layer(512),
                    nn.ReLU(inplace=True)),
                nn.Sequential(
                    nn.Conv2d(1024, 512, kernel_size=1, bias=False),
                    norm_layer(512),
                    nn.ReLU(inplace=True)),
            ])
            self.fusion = nn.Sequential(
                    nn.Conv2d(3*512, 512, kernel_size=3, padding=1, bias=False),
                    norm_layer(512),
                    nn.ReLU(inplace=True))
Zhang's avatar
v0.4.2  
Zhang committed
99
100
        self.encmodule = EncModule(512, out_channels, ncodes=32,
            se_loss=se_loss, norm_layer=norm_layer)
Hang Zhang's avatar
Hang Zhang committed
101
102
103
104
105
106
107
108
109
110
111
        self.conv6 = nn.Sequential(nn.Dropout2d(0.1, False),
                                   nn.Conv2d(512, out_channels, 1))

    def forward(self, *inputs):
        feat = self.conv5(inputs[-1])
        if self.lateral:
            c2 = self.connect[0](inputs[1])
            c3 = self.connect[1](inputs[2])
            feat = self.fusion(torch.cat([feat, c2, c3], 1))
        outs = list(self.encmodule(feat))
        outs[0] = self.conv6(outs[0])
Zhang's avatar
v0.4.2  
Zhang committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
        return tuple(outs)


def get_encnet(dataset='pascal_voc', backbone='resnet50', pretrained=False,
               root='~/.encoding/models', **kwargs):
    r"""EncNet model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    dataset : str, default pascal_voc
        The dataset that model pretrained on. (pascal_voc, ade20k)
    backbone : str, default resnet50
        The backbone network. (resnet50, 101, 152)
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet(dataset='pascal_voc', backbone='resnet50', pretrained=False)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
137
    kwargs['lateral'] = True if dataset.lower().startswith('p') else False
Zhang's avatar
v0.4.2  
Zhang committed
138
    # infer number of classes
Hang Zhang's avatar
Hang Zhang committed
139
    from ..datasets import datasets, acronyms
Hang Zhang's avatar
Hang Zhang committed
140
    model = EncNet(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs)
Zhang's avatar
v0.4.2  
Zhang committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    if pretrained:
        from .model_store import get_model_file
        model.load_state_dict(torch.load(
            get_model_file('encnet_%s_%s'%(backbone, acronyms[dataset]), root=root)))
    return model

def get_encnet_resnet50_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet_resnet50_pcontext(pretrained=True)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
164
165
    return get_encnet('pcontext', 'resnet50', pretrained, root=root, aux=True,
                      base_size=520, crop_size=480, **kwargs)
Hang Zhang's avatar
Hang Zhang committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

def get_encnet_resnet101_pcontext(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet_resnet101_pcontext(pretrained=True)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
184
185
    return get_encnet('pcontext', 'resnet101', pretrained, root=root, aux=True,
                      base_size=520, crop_size=480, **kwargs)
Hang Zhang's avatar
Hang Zhang committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

def get_encnet_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet_resnet50_ade(pretrained=True)
    >>> print(model)
    """
Hang Zhang's avatar
Hang Zhang committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    return get_encnet('ade20k', 'resnet50', pretrained, root=root, aux=True,
                      base_size=520, crop_size=480, **kwargs)

def get_encnet_resnet101_ade(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet_resnet50_ade(pretrained=True)
    >>> print(model)
    """
    return get_encnet('ade20k', 'resnet101', pretrained, root=root, aux=True,
                      base_size=640, crop_size=576, **kwargs)

def get_encnet_resnet152_ade(pretrained=False, root='~/.encoding/models', **kwargs):
    r"""EncNet-PSP model from the paper `"Context Encoding for Semantic Segmentation"
    <https://arxiv.org/pdf/1803.08904.pdf>`_

    Parameters
    ----------
    pretrained : bool, default False
        Whether to load the pretrained weights for model.
    root : str, default '~/.encoding/models'
        Location for keeping the model parameters.


    Examples
    --------
    >>> model = get_encnet_resnet50_ade(pretrained=True)
    >>> print(model)
    """
    return get_encnet('ade20k', 'resnet152', pretrained, root=root, aux=True,
                      base_size=520, crop_size=480, **kwargs)