vgg.py 7.6 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
16
17
    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    '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
109
110

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


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

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


127
def vgg13(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
128
    r"""VGG 13-layer model (configuration "B")
129
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
130
131
132

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


138
def vgg13_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
139
    r"""VGG 13-layer model (configuration "B") with batch normalization
140
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
141
142
143

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


149
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
150
    r"""VGG 16-layer model (configuration "D")
151
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
152
153
154

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
155
        progress (bool): If True, displays a progress bar of the download to stderr
156
    """
157
    return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
158
159


160
def vgg16_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
161
    r"""VGG 16-layer model (configuration "D") with batch normalization
162
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
163
164
165

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
166
        progress (bool): If True, displays a progress bar of the download to stderr
167
    """
168
    return _vgg('vgg16_bn', 'D', True, pretrained, progress, **kwargs)
169
170


171
def vgg19(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
172
    r"""VGG 19-layer model (configuration "E")
173
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
174
175
176

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
177
        progress (bool): If True, displays a progress bar of the download to stderr
178
    """
179
    return _vgg('vgg19', 'E', False, pretrained, progress, **kwargs)
180
181


182
def vgg19_bn(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
183
    r"""VGG 19-layer model (configuration 'E') with batch normalization
184
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
185
186
187

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