"docs/source/en/api/schedulers/heun.md" did not exist on "5a38033de4824c8d5d9b2856776df45592a8e825"
vgg.py 8.04 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
8
9


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


22
model_urls = {
23
24
25
26
27
28
29
30
    "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",
31
32
33
}


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

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

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

71

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


89
cfgs: Dict[str, List[Union[str, int]]] = {
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
95
96
}


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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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