Skip to content

Commit 8ef76ff

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

File tree

6 files changed

+407
-0
lines changed

6 files changed

+407
-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+
from . import 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('alexnet'))
50+
return model

torchvision/models/model_zoo.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import torch
2+
3+
import hashlib
4+
import os
5+
import re
6+
import shutil
7+
import sys
8+
import tempfile
9+
if sys.version_info[0] == 2:
10+
from urlparse import urlparse
11+
from urllib2 import urlopen
12+
else:
13+
from urllib.request import urlopen
14+
from urllib.parse import urlparse
15+
try:
16+
from tqdm import tqdm
17+
except ImportError:
18+
tqdm = None # defined below
19+
20+
21+
models = {
22+
'resnet18': 'https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth',
23+
'alexnet': 'https://s3.amazonaws.com/pytorch/models/alexnet-owt-4df8aa71.pth',
24+
}
25+
26+
# matches bfd8deac from resnet18-bfd8deac.pth
27+
HASH_REGEX = re.compile(r'-([a-f0-9]*)\.')
28+
29+
30+
def load(model_name):
31+
r"""Returns the state_dict for the given model name"""
32+
return load_url(models[model_name])
33+
34+
35+
def load_url(url, model_dir=None):
36+
if model_dir is None:
37+
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
38+
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
39+
if not os.path.exists(model_dir):
40+
os.makedirs(model_dir)
41+
parts = urlparse(url)
42+
filename = os.path.basename(parts.path)
43+
cached_file = os.path.join(model_dir, filename)
44+
if not os.path.exists(cached_file):
45+
sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
46+
hash_prefix = HASH_REGEX.search(filename).group(1)
47+
download_url_to_file(url, cached_file, hash_prefix)
48+
return torch.load(cached_file)
49+
50+
51+
def download_url_to_file(url, filename, hash_prefix):
52+
u = urlopen(url)
53+
meta = u.info()
54+
if hasattr(meta, 'getheaders'):
55+
file_size = int(meta.getheaders("Content-Length")[0])
56+
else:
57+
file_size = int(meta.get_all("Content-Length")[0])
58+
59+
f = tempfile.NamedTemporaryFile(delete=False)
60+
try:
61+
sha256 = hashlib.sha256()
62+
with tqdm(total=file_size) as pbar:
63+
while True:
64+
buffer = u.read(8192)
65+
if len(buffer) == 0:
66+
break
67+
f.write(buffer)
68+
sha256.update(buffer)
69+
pbar.update(len(buffer))
70+
71+
f.close()
72+
digest = sha256.hexdigest()
73+
if digest[:len(hash_prefix)] != hash_prefix:
74+
raise RuntimeError('invalid hash value (expected "{}", got "{}")'
75+
.format(hash_prefix, digest))
76+
shutil.move(f.name, filename)
77+
finally:
78+
f.close()
79+
if os.path.exists(f.name):
80+
os.remove(f.name)
81+
82+
83+
if tqdm is None:
84+
# fake tqdm if it's not installed
85+
class tqdm(object):
86+
def __init__(self, total):
87+
self.total = total
88+
self.n = 0
89+
90+
def update(self, n):
91+
self.n += n
92+
sys.stderr.write("\r{0:.1f}%".format(100 * self.n / float(self.total)))
93+
sys.stderr.flush()
94+
95+
def __enter__(self):
96+
return self
97+
98+
def __exit__(self, exc_type, exc_val, exc_tb):
99+
sys.stderr.write('\n')

torchvision/models/resnet.py

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
import torch.nn as nn
2+
import math
3+
from . import 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('resnet18'))
150+
return model
151+
152+
153+
def resnet34():
154+
return ResNet(BasicBlock, [3, 4, 6, 3])
155+
156+
157+
def resnet50():
158+
return ResNet(Bottleneck, [3, 4, 6, 3])
159+
160+
161+
def resnet101():
162+
return ResNet(Bottleneck, [3, 4, 23, 3])
163+
164+
165+
def resnet152():
166+
return ResNet(Bottleneck, [3, 8, 36, 3])

0 commit comments

Comments
 (0)