Skip to content

Commit fbac266

Browse files
committed
Add ResNet, AlexNet, and VGG model definitions and model zoo
1 parent 3ed4831 commit fbac266

File tree

5 files changed

+313
-0
lines changed

5 files changed

+313
-0
lines changed

torchvision/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from torchvision import models
2+
from torchvision import datasets
3+
from torchvision import transforms
4+
from torchvision import utils

torchvision/models/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .alexnet import *
2+
from .resnet import *
3+
from .vgg import *

torchvision/models/alexnet.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import torch.nn as nn
2+
import torch.utils.model_zoo as model_zoo
3+
4+
5+
__all__ = ['AlexNet', 'alexnet']
6+
7+
8+
class AlexNet(nn.Container):
9+
def __init__(self, num_classes=1000):
10+
super(AlexNet, self).__init__()
11+
self.features = nn.Sequential(
12+
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
13+
nn.ReLU(inplace=True),
14+
nn.MaxPool2d(kernel_size=3, stride=2),
15+
nn.Conv2d(64, 192, kernel_size=5, padding=2),
16+
nn.ReLU(inplace=True),
17+
nn.MaxPool2d(kernel_size=3, stride=2),
18+
nn.Conv2d(192, 384, kernel_size=3, padding=1),
19+
nn.ReLU(inplace=True),
20+
nn.Conv2d(384, 256, kernel_size=3, padding=1),
21+
nn.ReLU(inplace=True),
22+
nn.Conv2d(256, 256, kernel_size=3, padding=1),
23+
nn.ReLU(inplace=True),
24+
nn.MaxPool2d(kernel_size=3, stride=2),
25+
)
26+
self.classifier = nn.Sequential(
27+
nn.Dropout(),
28+
nn.Linear(256 * 6 * 6, 4096),
29+
nn.ReLU(inplace=True),
30+
nn.Dropout(),
31+
nn.Linear(4096, 4096),
32+
nn.ReLU(inplace=True),
33+
nn.Linear(4096, num_classes),
34+
)
35+
36+
def forward(self, x):
37+
x = self.features(x)
38+
x = x.view(x.size(0), 256 * 6 * 6)
39+
x = self.classifier(x)
40+
return x
41+
42+
43+
def alexnet(pretrained=False):
44+
r"""AlexNet model architecture from the "One weird trick" paper.
45+
https://arxiv.org/abs/1404.5997
46+
"""
47+
model = AlexNet()
48+
if pretrained:
49+
model.load_state_dict(model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/alexnet-owt-4df8aa71.pth'))
50+
return model

torchvision/models/resnet.py

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
import torch.nn as nn
2+
import math
3+
import torch.utils.model_zoo as model_zoo
4+
5+
6+
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
7+
'resnet152']
8+
9+
10+
def conv3x3(in_planes, out_planes, stride=1):
11+
"3x3 convolution with padding"
12+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
13+
padding=1, bias=False)
14+
15+
16+
class BasicBlock(nn.Container):
17+
expansion = 1
18+
19+
def __init__(self, inplanes, planes, stride=1, downsample=None):
20+
super(BasicBlock, self).__init__()
21+
self.conv1 = conv3x3(inplanes, planes, stride)
22+
self.bn1 = nn.BatchNorm2d(planes)
23+
self.relu = nn.ReLU(inplace=True)
24+
self.conv2 = conv3x3(planes, planes)
25+
self.bn2 = nn.BatchNorm2d(planes)
26+
self.downsample = downsample
27+
self.stride = stride
28+
29+
def forward(self, x):
30+
residual = x
31+
32+
out = self.conv1(x)
33+
out = self.bn1(out)
34+
out = self.relu(out)
35+
36+
out = self.conv2(out)
37+
out = self.bn2(out)
38+
39+
if self.downsample is not None:
40+
residual = self.downsample(x)
41+
42+
out += residual
43+
out = self.relu(out)
44+
45+
return out
46+
47+
48+
class Bottleneck(nn.Container):
49+
expansion = 4
50+
51+
def __init__(self, inplanes, planes, stride=1, downsample=None):
52+
super(Bottleneck, self).__init__()
53+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
54+
self.bn1 = nn.BatchNorm2d(planes)
55+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
56+
padding=1, bias=False)
57+
self.bn2 = nn.BatchNorm2d(planes)
58+
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
59+
self.bn3 = nn.BatchNorm2d(planes * 4)
60+
self.relu = nn.ReLU(inplace=True)
61+
self.downsample = downsample
62+
self.stride = stride
63+
64+
def forward(self, x):
65+
residual = x
66+
67+
out = self.conv1(x)
68+
out = self.bn1(out)
69+
out = self.relu(out)
70+
71+
out = self.conv2(out)
72+
out = self.bn2(out)
73+
out = self.relu(out)
74+
75+
out = self.conv3(out)
76+
out = self.bn3(out)
77+
78+
if self.downsample is not None:
79+
residual = self.downsample(x)
80+
81+
out += residual
82+
out = self.relu(out)
83+
84+
return out
85+
86+
87+
class ResNet(nn.Container):
88+
def __init__(self, block, layers, num_classes=1000):
89+
self.inplanes = 64
90+
super(ResNet, self).__init__()
91+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
92+
bias=False)
93+
self.bn1 = nn.BatchNorm2d(64)
94+
self.relu = nn.ReLU(inplace=True)
95+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
96+
self.layer1 = self._make_layer(block, 64, layers[0])
97+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
98+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
99+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
100+
self.avgpool = nn.AvgPool2d(7)
101+
self.fc = nn.Linear(512 * block.expansion, num_classes)
102+
103+
for m in self.modules():
104+
if isinstance(m, nn.Conv2d):
105+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
106+
m.weight.data.normal_(0, math.sqrt(2. / n))
107+
elif isinstance(m, nn.BatchNorm2d):
108+
m.weight.data.fill_(1)
109+
m.bias.data.zero_()
110+
111+
def _make_layer(self, block, planes, blocks, stride=1):
112+
downsample = None
113+
if stride != 1 or self.inplanes != planes * block.expansion:
114+
downsample = nn.Sequential(
115+
nn.Conv2d(self.inplanes, planes * block.expansion,
116+
kernel_size=1, stride=stride, bias=False),
117+
nn.BatchNorm2d(planes * block.expansion),
118+
)
119+
120+
layers = []
121+
layers.append(block(self.inplanes, planes, stride, downsample))
122+
self.inplanes = planes * block.expansion
123+
for i in range(1, blocks):
124+
layers.append(block(self.inplanes, planes))
125+
126+
return nn.Sequential(*layers)
127+
128+
def forward(self, x):
129+
x = self.conv1(x)
130+
x = self.bn1(x)
131+
x = self.relu(x)
132+
x = self.maxpool(x)
133+
134+
x = self.layer1(x)
135+
x = self.layer2(x)
136+
x = self.layer3(x)
137+
x = self.layer4(x)
138+
139+
x = self.avgpool(x)
140+
x = x.view(x.size(0), -1)
141+
x = self.fc(x)
142+
143+
return x
144+
145+
146+
def resnet18(pretrained=False):
147+
model = ResNet(BasicBlock, [2, 2, 2, 2])
148+
if pretrained:
149+
model.load_state_dict(model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth'))
150+
return model
151+
152+
153+
def resnet34(pretrained=False):
154+
model = ResNet(BasicBlock, [3, 4, 6, 3])
155+
if pretrained:
156+
model.load_state_dict(model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet34-333f7ec4.pth'))
157+
return model
158+
159+
160+
def resnet50(pretrained=False):
161+
model = ResNet(Bottleneck, [3, 4, 6, 3])
162+
if pretrained:
163+
model.load_state_dict(model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet50-19c8e357.pth'))
164+
return model
165+
166+
167+
def resnet101():
168+
return ResNet(Bottleneck, [3, 4, 23, 3])
169+
170+
171+
def resnet152():
172+
return ResNet(Bottleneck, [3, 8, 36, 3])

torchvision/models/vgg.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import torch.nn as nn
2+
3+
4+
__all__ = [
5+
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
6+
'vgg19_bn', 'vgg19',
7+
]
8+
9+
10+
class VGG(nn.Container):
11+
def __init__(self, features):
12+
super(VGG, self).__init__()
13+
self.features = features
14+
self.classifier = nn.Sequential(
15+
nn.Dropout(),
16+
nn.Linear(512 * 7 * 7, 4096),
17+
nn.ReLU(True),
18+
nn.Dropout(),
19+
nn.Linear(4096, 4096),
20+
nn.ReLU(True),
21+
nn.Linear(4096, 1000),
22+
)
23+
24+
def forward(self, x):
25+
x = self.features(x)
26+
x = x.view(x.size(0), -1)
27+
x = self.classifier(x)
28+
return x
29+
30+
31+
def make_layers(cfg, batch_norm=False):
32+
layers = []
33+
in_channels = 3
34+
for v in cfg:
35+
if v == 'M':
36+
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
37+
else:
38+
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
39+
if batch_norm:
40+
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
41+
else:
42+
layers += [conv2d, nn.ReLU(inplace=True)]
43+
in_channels = v
44+
return nn.Sequential(*layers)
45+
46+
47+
cfg = {
48+
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
49+
'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
50+
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
51+
'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
52+
}
53+
54+
55+
def vgg11():
56+
return VGG(make_layers(cfg['A']))
57+
58+
59+
def vgg11_bn():
60+
return VGG(make_layers(cfg['A'], batch_norm=True))
61+
62+
63+
def vgg13():
64+
return VGG(make_layers(cfg['B']))
65+
66+
67+
def vgg13_bn():
68+
return VGG(make_layers(cfg['B'], batch_norm=True))
69+
70+
71+
def vgg16():
72+
return VGG(make_layers(cfg['D']))
73+
74+
75+
def vgg16_bn():
76+
return VGG(make_layers(cfg['D'], batch_norm=True))
77+
78+
79+
def vgg19():
80+
return VGG(make_layers(cfg['E']))
81+
82+
83+
def vgg19_bn():
84+
return VGG(make_layers(cfg['E'], batch_norm=True))

0 commit comments

Comments
 (0)