Skip to content

Commit c96e794

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

File tree

6 files changed

+402
-0
lines changed

6 files changed

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