vgg.py 8.07 KB
Newer Older
1
import torch
2
import torch.nn as nn
3
from .utils import load_state_dict_from_url
4
from typing import Union, List, Dict, Any, cast
5
6
7
8
9
10
11
12


__all__ = [
    'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
    'vgg19_bn', 'vgg19',
]


13
model_urls = {
14
15
    'vgg11': 'https://download.pytorch.org/models/vgg11-8a719046.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-19584684.pth',
16
17
    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
18
19
20
21
    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
22
23
24
}


Soumith Chintala's avatar
Soumith Chintala committed
25
class VGG(nn.Module):
26

27
28
29
30
31
32
    def __init__(
        self,
        features: nn.Module,
        num_classes: int = 1000,
        init_weights: bool = True
    ) -> None:
33
34
        super(VGG, self).__init__()
        self.features = features
35
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
36
37
38
39
40
41
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
42
            nn.Dropout(),
Karan Dwivedi's avatar
Karan Dwivedi committed
43
            nn.Linear(4096, num_classes),
44
        )
45
46
        if init_weights:
            self._initialize_weights()
47

48
    def forward(self, x: torch.Tensor) -> torch.Tensor:
49
        x = self.features(x)
50
        x = self.avgpool(x)
51
        x = torch.flatten(x, 1)
52
53
54
        x = self.classifier(x)
        return x

55
    def _initialize_weights(self) -> None:
56
57
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
58
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
59
                if m.bias is not None:
60
                    nn.init.constant_(m.bias, 0)
61
            elif isinstance(m, nn.BatchNorm2d):
62
63
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
64
            elif isinstance(m, nn.Linear):
65
66
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
67

68

69
70
def make_layers(cfg: List[Union[str, int]], batch_norm: bool = False) -> nn.Sequential:
    layers: List[nn.Module] = []
71
72
73
74
75
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
76
            v = cast(int, v)
77
78
79
80
81
82
83
84
85
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)


86
cfgs: Dict[str, List[Union[str, int]]] = {
87
88
89
90
91
92
93
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


94
def _vgg(arch: str, cfg: str, batch_norm: bool, pretrained: bool, progress: bool, **kwargs: Any) -> VGG:
95
96
97
98
99
100
101
102
103
104
    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model


105
def vgg11(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
106
    r"""VGG 11-layer model (configuration "A") from
107
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
108
    The required minimum input size of the model is 32x32.
109
110
111

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
112
        progress (bool): If True, displays a progress bar of the download to stderr
113
    """
114
    return _vgg('vgg11', 'A', False, pretrained, progress, **kwargs)
115
116


117
def vgg11_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
118
    r"""VGG 11-layer model (configuration "A") with batch normalization
119
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
120
    The required minimum input size of the model is 32x32.
121
122
123

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
124
        progress (bool): If True, displays a progress bar of the download to stderr
125
    """
126
    return _vgg('vgg11_bn', 'A', True, pretrained, progress, **kwargs)
127
128


129
def vgg13(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
130
    r"""VGG 13-layer model (configuration "B")
131
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
132
    The required minimum input size of the model is 32x32.
133
134
135

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
136
        progress (bool): If True, displays a progress bar of the download to stderr
137
    """
138
    return _vgg('vgg13', 'B', False, pretrained, progress, **kwargs)
139
140


141
def vgg13_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
142
    r"""VGG 13-layer model (configuration "B") with batch normalization
143
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
144
    The required minimum input size of the model is 32x32.
145
146
147

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
148
        progress (bool): If True, displays a progress bar of the download to stderr
149
    """
150
    return _vgg('vgg13_bn', 'B', True, pretrained, progress, **kwargs)
151
152


153
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
154
    r"""VGG 16-layer model (configuration "D")
155
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
156
    The required minimum input size of the model is 32x32.
157
158
159

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
160
        progress (bool): If True, displays a progress bar of the download to stderr
161
    """
162
    return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
163
164


165
def vgg16_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
166
    r"""VGG 16-layer model (configuration "D") with batch normalization
167
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
168
    The required minimum input size of the model is 32x32.
169
170
171

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
172
        progress (bool): If True, displays a progress bar of the download to stderr
173
    """
174
    return _vgg('vgg16_bn', 'D', True, pretrained, progress, **kwargs)
175
176


177
def vgg19(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
178
    r"""VGG 19-layer model (configuration "E")
179
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
180
    The required minimum input size of the model is 32x32.
181
182
183

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
184
        progress (bool): If True, displays a progress bar of the download to stderr
185
    """
186
    return _vgg('vgg19', 'E', False, pretrained, progress, **kwargs)
187
188


189
def vgg19_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
190
    r"""VGG 19-layer model (configuration 'E') with batch normalization
191
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
192
    The required minimum input size of the model is 32x32.
193
194
195

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
196
        progress (bool): If True, displays a progress bar of the download to stderr
197
    """
198
    return _vgg('vgg19_bn', 'E', True, pretrained, progress, **kwargs)