vgg.py 8.15 KB
Newer Older
1
2
from typing import Union, List, Dict, Any, cast

3
import torch
4
import torch.nn as nn
5

6
from .._internally_replaced_utils import load_state_dict_from_url
7
from ..utils import _log_api_usage_once
8
9
10


__all__ = [
11
12
13
14
15
16
17
18
19
    "VGG",
    "vgg11",
    "vgg11_bn",
    "vgg13",
    "vgg13_bn",
    "vgg16",
    "vgg16_bn",
    "vgg19_bn",
    "vgg19",
20
21
22
]


23
model_urls = {
24
25
26
27
28
29
30
31
    "vgg11": "https://download.pytorch.org/models/vgg11-8a719046.pth",
    "vgg13": "https://download.pytorch.org/models/vgg13-19584684.pth",
    "vgg16": "https://download.pytorch.org/models/vgg16-397923af.pth",
    "vgg19": "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth",
    "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",
32
33
34
}


Soumith Chintala's avatar
Soumith Chintala committed
35
class VGG(nn.Module):
36
37
38
    def __init__(
        self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5
    ) -> None:
39
        super().__init__()
40
        _log_api_usage_once(self)
41
        self.features = features
42
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
43
44
45
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
46
            nn.Dropout(p=dropout),
47
48
            nn.Linear(4096, 4096),
            nn.ReLU(True),
49
            nn.Dropout(p=dropout),
Karan Dwivedi's avatar
Karan Dwivedi committed
50
            nn.Linear(4096, num_classes),
51
        )
52
53
        if init_weights:
            self._initialize_weights()
54

55
    def forward(self, x: torch.Tensor) -> torch.Tensor:
56
        x = self.features(x)
57
        x = self.avgpool(x)
58
        x = torch.flatten(x, 1)
59
60
61
        x = self.classifier(x)
        return x

62
    def _initialize_weights(self) -> None:
63
64
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
65
                nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
66
                if m.bias is not None:
67
                    nn.init.constant_(m.bias, 0)
68
            elif isinstance(m, nn.BatchNorm2d):
69
70
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
71
            elif isinstance(m, nn.Linear):
72
73
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)
74

75

76
77
def make_layers(cfg: List[Union[str, int]], batch_norm: bool = False) -> nn.Sequential:
    layers: List[nn.Module] = []
78
79
    in_channels = 3
    for v in cfg:
80
        if v == "M":
81
82
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
83
            v = cast(int, v)
84
85
86
87
88
89
90
91
92
            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)


93
cfgs: Dict[str, List[Union[str, int]]] = {
94
95
96
97
    "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"],
98
99
100
}


101
def _vgg(arch: str, cfg: str, batch_norm: bool, pretrained: bool, progress: bool, **kwargs: Any) -> VGG:
102
    if pretrained:
103
        kwargs["init_weights"] = False
104
105
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    if pretrained:
106
        state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
107
108
109
110
        model.load_state_dict(state_dict)
    return model


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

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
118
        progress (bool): If True, displays a progress bar of the download to stderr
119
    """
120
    return _vgg("vgg11", "A", False, pretrained, progress, **kwargs)
121
122


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

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
130
        progress (bool): If True, displays a progress bar of the download to stderr
131
    """
132
    return _vgg("vgg11_bn", "A", True, pretrained, progress, **kwargs)
133
134


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

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


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

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


159
def vgg16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VGG:
160
    r"""VGG 16-layer model (configuration "D")
161
    `"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_.
162
    The required minimum input size of the model is 32x32.
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", "D", False, pretrained, progress, **kwargs)
169
170


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

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


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

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
190
        progress (bool): If True, displays a progress bar of the download to stderr
191
    """
192
    return _vgg("vgg19", "E", False, pretrained, progress, **kwargs)
193
194


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

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