vgg.py 8.0 KB
Newer Older
L
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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.

from __future__ import absolute_import, division, print_function

import paddle.nn as nn
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
L
littletomatodonkey 已提交
19
from paddle.nn import MaxPool2D
L
littletomatodonkey 已提交
20 21

from ppcls.arch.backbone.base.theseus_layer import TheseusLayer
D
dongshuilong 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

MODEL_URLS = {
    "VGG11":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/VGG11_pretrained.pdparams",
    "VGG13":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/VGG13_pretrained.pdparams",
    "VGG16":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/VGG16_pretrained.pdparams",
    "VGG19":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/VGG19_pretrained.pdparams",
}
__all__ = MODEL_URLS.keys()
L
littletomatodonkey 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47

# VGG config
# key: VGG network depth
# value: conv num in different blocks
NET_CONFIG = {
    11: [1, 1, 2, 2, 2],
    13: [2, 2, 2, 2, 2],
    16: [2, 2, 3, 3, 3],
    19: [2, 2, 4, 4, 4]
}


class ConvBlock(TheseusLayer):
W
weishengyu 已提交
48
    def __init__(self, input_channels, output_channels, groups):
D
dongshuilong 已提交
49
        super().__init__()
L
littletomatodonkey 已提交
50 51

        self.groups = groups
D
dongshuilong 已提交
52
        self.conv1 = Conv2D(
L
littletomatodonkey 已提交
53 54 55 56 57 58 59
            in_channels=input_channels,
            out_channels=output_channels,
            kernel_size=3,
            stride=1,
            padding=1,
            bias_attr=False)
        if groups == 2 or groups == 3 or groups == 4:
D
dongshuilong 已提交
60
            self.conv2 = Conv2D(
L
littletomatodonkey 已提交
61 62 63 64 65 66 67
                in_channels=output_channels,
                out_channels=output_channels,
                kernel_size=3,
                stride=1,
                padding=1,
                bias_attr=False)
        if groups == 3 or groups == 4:
D
dongshuilong 已提交
68
            self.conv3 = Conv2D(
L
littletomatodonkey 已提交
69 70 71 72 73 74 75
                in_channels=output_channels,
                out_channels=output_channels,
                kernel_size=3,
                stride=1,
                padding=1,
                bias_attr=False)
        if groups == 4:
D
dongshuilong 已提交
76
            self.conv4 = Conv2D(
L
littletomatodonkey 已提交
77 78 79 80 81 82 83
                in_channels=output_channels,
                out_channels=output_channels,
                kernel_size=3,
                stride=1,
                padding=1,
                bias_attr=False)

D
dongshuilong 已提交
84 85
        self.max_pool = MaxPool2D(kernel_size=2, stride=2, padding=0)
        self.relu = nn.ReLU()
L
littletomatodonkey 已提交
86

W
weishengyu 已提交
87
    def forward(self, inputs):
D
dongshuilong 已提交
88 89
        x = self.conv1(inputs)
        x = self.relu(x)
L
littletomatodonkey 已提交
90
        if self.groups == 2 or self.groups == 3 or self.groups == 4:
D
dongshuilong 已提交
91 92
            x = self.conv2(x)
            x = self.relu(x)
L
littletomatodonkey 已提交
93
        if self.groups == 3 or self.groups == 4:
D
dongshuilong 已提交
94 95
            x = self.conv3(x)
            x = self.relu(x)
L
littletomatodonkey 已提交
96
        if self.groups == 4:
D
dongshuilong 已提交
97 98 99
            x = self.conv4(x)
            x = self.relu(x)
        x = self.max_pool(x)
L
littletomatodonkey 已提交
100 101 102 103
        return x


class VGGNet(TheseusLayer):
D
dongshuilong 已提交
104 105 106 107 108 109 110 111 112 113
    """
    VGGNet
    Args:
        config: list. VGGNet config.
        stop_grad_layers: int=0. The parameters in blocks which index larger than `stop_grad_layers`, will be set `param.trainable=False`
        class_num: int=1000. The number of classes.
    Returns:
        model: nn.Layer. Specific VGG model depends on args.
    """

114 115 116 117 118
    def __init__(self,
                 config,
                 stop_grad_layers=0,
                 class_num=1000,
                 return_patterns=None):
L
littletomatodonkey 已提交
119 120 121 122
        super().__init__()

        self.stop_grad_layers = stop_grad_layers

W
weishengyu 已提交
123 124 125 126 127
        self.conv_block_1 = ConvBlock(3, 64, config[0])
        self.conv_block_2 = ConvBlock(64, 128, config[1])
        self.conv_block_3 = ConvBlock(128, 256, config[2])
        self.conv_block_4 = ConvBlock(256, 512, config[3])
        self.conv_block_5 = ConvBlock(512, 512, config[4])
L
littletomatodonkey 已提交
128

D
dongshuilong 已提交
129 130
        self.relu = nn.ReLU()
        self.flatten = nn.Flatten(start_axis=1, stop_axis=-1)
L
littletomatodonkey 已提交
131 132

        for idx, block in enumerate([
D
dongshuilong 已提交
133 134
                self.conv_block_1, self.conv_block_2, self.conv_block_3,
                self.conv_block_4, self.conv_block_5
L
littletomatodonkey 已提交
135 136 137 138 139
        ]):
            if self.stop_grad_layers >= idx + 1:
                for param in block.parameters():
                    param.trainable = False

D
dongshuilong 已提交
140 141 142 143
        self.drop = Dropout(p=0.5, mode="downscale_in_infer")
        self.fc1 = Linear(7 * 7 * 512, 4096)
        self.fc2 = Linear(4096, 4096)
        self.fc3 = Linear(4096, class_num)
W
weishengyu 已提交
144 145
        if return_patterns is not None:
            self.update_res(return_patterns)
L
littletomatodonkey 已提交
146

W
weishengyu 已提交
147
    def forward(self, inputs):
W
dbg  
weishengyu 已提交
148 149 150 151 152
        x = self.conv_block_1(inputs)
        x = self.conv_block_2(x)
        x = self.conv_block_3(x)
        x = self.conv_block_4(x)
        x = self.conv_block_5(x)
D
dongshuilong 已提交
153 154 155 156 157 158 159 160
        x = self.flatten(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.drop(x)
        x = self.fc3(x)
L
littletomatodonkey 已提交
161
        return x
D
dongshuilong 已提交
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 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


def _load_pretrained(pretrained, model, model_url, use_ssld):
    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 VGG11(pretrained=False, use_ssld=False, **kwargs):
    """
    VGG11
    Args:
        pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
    Returns:
        model: nn.Layer. Specific `VGG11` model depends on args.
    """
    model = VGGNet(config=NET_CONFIG[11], **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["VGG11"], use_ssld)
    return model


def VGG13(pretrained=False, use_ssld=False, **kwargs):
    """
    VGG13
    Args:
        pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
    Returns:
        model: nn.Layer. Specific `VGG13` model depends on args.
    """
    model = VGGNet(config=NET_CONFIG[13], **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["VGG13"], use_ssld)
    return model


def VGG16(pretrained=False, use_ssld=False, **kwargs):
    """
    VGG16
    Args:
        pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
    Returns:
        model: nn.Layer. Specific `VGG16` model depends on args.
    """
    model = VGGNet(config=NET_CONFIG[16], **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["VGG16"], use_ssld)
    return model


def VGG19(pretrained=False, use_ssld=False, **kwargs):
    """
    VGG19
    Args:
        pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
                    If str, means the path of the pretrained model.
        use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
    Returns:
        model: nn.Layer. Specific `VGG19` model depends on args.
    """
    model = VGGNet(config=NET_CONFIG[19], **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["VGG19"], use_ssld)
    return model