Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jantic
GitHub Repository: jantic/deoldify
Path: blob/master/fastai/vision/models/presnet.py
781 views
1
from pdb import set_trace
2
import torch.nn.functional as F
3
import torch.nn as nn
4
import torch
5
import math
6
import torch.utils.model_zoo as model_zoo
7
8
__all__ = ['PResNet', 'presnet18', 'presnet34', 'presnet50', 'presnet101', 'presnet152']
9
10
act_fn = nn.ReLU
11
12
def init_cnn(m):
13
if getattr(m, 'bias', None) is not None: nn.init.constant_(m.bias, 0)
14
if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight)
15
elif isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01)
16
for l in m.children(): init_cnn(l)
17
18
def conv(ni, nf, ks=3, stride=1, bias=False):
19
return nn.Conv2d(ni, nf, kernel_size=ks, stride=stride, padding=ks//2, bias=bias)
20
21
def conv_layer(conv_1st, ni, nf, ks=3, stride=1, zero_bn=False, bias=False):
22
bn = nn.BatchNorm2d(nf if conv_1st else ni)
23
nn.init.constant_(bn.weight, 0. if zero_bn else 1.)
24
res = [act_fn(), bn]
25
cn = conv(ni, nf, ks, stride=stride, bias=bias)
26
res.insert(0 if conv_1st else 2, cn)
27
return nn.Sequential(*res)
28
29
def conv_act(*args, **kwargs): return conv_layer(True , *args, **kwargs)
30
def act_conv(*args, **kwargs): return conv_layer(False, *args, **kwargs)
31
32
class BasicBlock(Module):
33
expansion = 1
34
35
def __init__(self, ni, nf, stride=1, downsample=None):
36
super(BasicBlock, self).__init__()
37
self.conv1 = act_conv(ni, nf, stride=stride)
38
self.conv2 = act_conv(nf, nf, zero_bn=True)
39
self.downsample = downsample
40
self.stride = stride
41
42
def forward(self, x):
43
identity = x if self.downsample is None else self.downsample(x)
44
x = self.conv1(x)
45
x = self.conv2(x)
46
x += identity
47
return x
48
49
class Bottleneck(Module):
50
expansion = 4
51
52
def __init__(self, ni, nf, stride=1, downsample=None):
53
super(Bottleneck, self).__init__()
54
self.conv1 = act_conv(ni, nf, 1)
55
self.conv2 = act_conv(nf, nf, stride=stride)
56
self.conv3 = act_conv(nf, nf*self.expansion, 1)
57
self.downsample = downsample
58
self.stride = stride
59
60
def forward(self, x):
61
identity = x if self.downsample is None else self.downsample(x)
62
x = self.conv1(x)
63
x = self.conv2(x)
64
x = self.conv3(x)
65
x += identity
66
return x
67
68
class PResNet(Module):
69
70
def __init__(self, block, layers, num_classes=1000):
71
self.ni = 64
72
super().__init__()
73
self.conv1 = conv_act(3, 16, stride=2)
74
self.conv2 = conv_act(16, 32)
75
self.conv3 = conv_act(32, 64)
76
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
77
self.layer1 = self._make_layer(block, 64, layers[0])
78
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
79
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
80
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
81
ni = 512*block.expansion
82
self.avgpool = nn.Sequential(
83
act_fn(), nn.BatchNorm2d(ni), nn.AdaptiveAvgPool2d(1))
84
self.fc = nn.Linear(ni, num_classes)
85
86
init_cnn(self)
87
88
def _make_layer(self, block, nf, blocks, stride=1):
89
downsample = None
90
if stride != 1 or self.ni != nf*block.expansion:
91
layers = [act_fn(), nn.BatchNorm2d(self.ni),
92
nn.AvgPool2d(kernel_size=2)] if stride==2 else []
93
layers.append(conv(self.ni, nf*block.expansion))
94
downsample = nn.Sequential(*layers)
95
96
layers = [block(self.ni, nf, stride, downsample)]
97
self.ni = nf*block.expansion
98
for i in range(1, blocks): layers.append(block(self.ni, nf))
99
return nn.Sequential(*layers)
100
101
def forward(self, x):
102
x = self.conv1(x)
103
x = self.conv2(x)
104
x = self.conv3(x)
105
x = self.maxpool(x)
106
107
x = self.layer1(x)
108
x = self.layer2(x)
109
x = self.layer3(x)
110
x = self.layer4(x)
111
112
x = self.avgpool(x)
113
x = x.view(x.size(0), -1)
114
x = self.fc(x)
115
116
return x
117
118
model_urls = dict(presnet34='presnet34', presnet50='presnet50')
119
120
def presnet(block, n_layers, name, pre=False, **kwargs):
121
model = PResNet(block, n_layers, **kwargs)
122
#if pre: model.load_state_dict(model_zoo.load_url(model_urls[name]))
123
if pre: model.load_state_dict(torch.load(model_urls[name]))
124
return model
125
126
def presnet18(pretrained=False, **kwargs):
127
return presnet(BasicBlock, [2, 2, 2, 2], 'presnet18', pre=pretrained, **kwargs)
128
129
def presnet34(pretrained=False, **kwargs):
130
return presnet(BasicBlock, [3, 4, 6, 3], 'presnet34', pre=pretrained, **kwargs)
131
132
def presnet50(pretrained=False, **kwargs):
133
return presnet(Bottleneck, [3, 4, 6, 3], 'presnet50', pre=pretrained, **kwargs)
134
135
def presnet101(pretrained=False, **kwargs):
136
return presnet(Bottleneck, [3, 4, 23, 3], 'presnet101', pre=pretrained, **kwargs)
137
138
def presnet152(pretrained=False, **kwargs):
139
return presnet(Bottleneck, [3, 8, 36, 3], 'presnet152', pre=pretrained, **kwargs)
140
141
142