a0126312d1a282da627f8193f09f597827acb987
[jacinto-ai/pytorch-jacinto-ai-devkit.git] / modules / pytorch_jacinto_ai / vision / models / alexnet.py
1 import torch
2 import torch.nn as nn
3 from .utils import load_state_dict_from_url
6 __all__ = ['AlexNet', 'alexnet']
9 model_urls = {
10 'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
11 }
14 class AlexNet(nn.Module):
16 def __init__(self, num_classes=1000):
17 super(AlexNet, self).__init__()
18 self.features = nn.Sequential(
19 nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
20 nn.ReLU(inplace=True),
21 nn.MaxPool2d(kernel_size=3, stride=2),
22 nn.Conv2d(64, 192, kernel_size=5, padding=2),
23 nn.ReLU(inplace=True),
24 nn.MaxPool2d(kernel_size=3, stride=2),
25 nn.Conv2d(192, 384, kernel_size=3, padding=1),
26 nn.ReLU(inplace=True),
27 nn.Conv2d(384, 256, kernel_size=3, padding=1),
28 nn.ReLU(inplace=True),
29 nn.Conv2d(256, 256, kernel_size=3, padding=1),
30 nn.ReLU(inplace=True),
31 nn.MaxPool2d(kernel_size=3, stride=2),
32 )
33 self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
34 self.classifier = nn.Sequential(
35 nn.Dropout(),
36 nn.Linear(256 * 6 * 6, 4096),
37 nn.ReLU(inplace=True),
38 nn.Dropout(),
39 nn.Linear(4096, 4096),
40 nn.ReLU(inplace=True),
41 nn.Linear(4096, num_classes),
42 )
44 def forward(self, x):
45 x = self.features(x)
46 x = self.avgpool(x)
47 x = torch.flatten(x, 1)
48 x = self.classifier(x)
49 return x
52 def alexnet(pretrained=False, progress=True, **kwargs):
53 r"""AlexNet model architecture from the
54 `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
56 Args:
57 pretrained (bool): If True, returns a model pre-trained on ImageNet
58 progress (bool): If True, displays a progress bar of the download to stderr
59 """
60 model = AlexNet(**kwargs)
61 if pretrained:
62 state_dict = load_state_dict_from_url(model_urls['alexnet'],
63 progress=progress)
64 model.load_state_dict(state_dict)
65 return model