-
Notifications
You must be signed in to change notification settings - Fork 20
/
msdnet.py
232 lines (184 loc) · 8.46 KB
/
msdnet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch.nn as nn
from models.msdnet_layers import MSDLayer,\
MSDFirstLayer,CifarClassifier,Transition
from torch.autograd import Variable
import math
__all__ = ['MSDNet']
class MSDNet(nn.Module):
def __init__(self, args):
"""
The main module for Multi Scale Dense Network.
It holds the different blocks with layers and classifiers of the MSDNet layers
:param args: Network argument
"""
super(MSDNet, self).__init__()
# Init arguments
self.args = args
self.base = self.args.msd_base
self.step = self.args.msd_step
self.step_mode = self.args.msd_stepmode
self.msd_prune = self.args.msd_prune
self.num_blocks = self.args.msd_blocks
self.reduction_rate = self.args.reduction
self.growth = self.args.msd_growth
self.growth_factor = args.msd_growth_factor
self.bottleneck = self.args.msd_bottleneck
self.bottleneck_factor = args.msd_bottleneck_factor
# Set progress
if args.data in ['cifar10', 'cifar100']:
self.image_channels = 3
self.num_channels = 32
self.num_scales = 3
self.num_classes = int(args.data.strip('cifar'))
else:
raise NotImplementedError
# Init MultiScale graph and fill with Blocks and Classifiers
print('| MSDNet-Block {}-{}-{}'.format(self.num_blocks,
self.step,
self.args.data))
(self.num_layers, self.steps) = self.calc_steps()
print('Building network with the steps: {}'.format(self.steps))
self.cur_layer = 1
self.cur_transition_layer = 1
self.subnets = nn.ModuleList(self.build_modules(self.num_channels))
# initialize
for m in self.subnets:
self.init_weights(m)
if hasattr(m,'__iter__'):
for sub_m in m:
self.init_weights(sub_m)
def init_weights(self, m):
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def calc_steps(self):
"""Calculates the number of layers required in each
Block and the total number of layers, according to
the step and stepmod.
:return: number of total layers and list of layers/steps per blocks
"""
# Init steps array
steps = [None]*self.num_blocks
steps[0] = num_layers = self.base
# Fill steps and num_layers
for i in range(1, self.num_blocks):
# Take even steps or calc next linear growth of a step
steps[i] = (self.step_mode == 'even' and self.step) or \
self.step*(i-1)+1
num_layers += steps[i]
return num_layers, steps
def build_modules(self, num_channels):
"""Builds all blocks and classifiers and add it
into an array in the order of the format:
[[block]*num_blocks [classifier]*num_blocks]
where the i'th block corresponds to the (i+num_block) classifier.
:param num_channels: number of input channels
:return: An array with all blocks and classifiers
"""
# Init the blocks & classifiers data structure
modules = [None] * self.num_blocks * 2
for i in range(0, self.num_blocks):
print ('|-----------------Block {:0>2d}----------------|'.format(i+1))
# Add block
modules[i], num_channels = self.create_block(num_channels, i)
# Calculate the last scale (smallest) channels size
channels_in_last_layer = num_channels *\
self.growth_factor[self.num_scales]
# Add a classifier that belongs to the i'th block
modules[i + self.num_blocks] = \
CifarClassifier(channels_in_last_layer, self.num_classes)
return modules
def create_block(self, num_channels, block_num):
'''
:param num_channels: number of input channels to the block
:param block_num: the number of the block (among all blocks)
:return: A sequential container with steps[block_num] MSD layers
'''
block = nn.Sequential()
# Add the first layer if needed
if block_num == 0:
block.add_module('MSD_first', MSDFirstLayer(self.image_channels,
num_channels,
self.num_scales,
self.args))
# Add regular layers
current_channels = num_channels
for _ in range(0, self.steps[block_num]):
# Calculate in and out scales of the layer (use paper heuristics)
if self.msd_prune == 'max':
interval = math.ceil(self.num_layers/
self.num_scales)
in_scales = int(self.num_scales - \
math.floor((max(0, self.cur_layer - 2))/interval))
out_scales = int(self.num_scales - \
math.floor((self.cur_layer - 1)/interval))
else:
raise NotImplementedError
self.print_layer(in_scales, out_scales)
self.cur_layer += 1
# Add an MSD layer
block.add_module('MSD_layer_{}'.format(self.cur_layer - 1),
MSDLayer(current_channels,
self.growth,
in_scales,
out_scales,
self.num_scales,
self.args))
# Increase number of channel (as in densenet pattern)
current_channels += self.growth
# Add a transition layer if required
if (self.msd_prune == 'max' and in_scales > out_scales and
self.reduction_rate):
# Calculate scales transition and add a Transition layer
offset = self.num_scales - out_scales
new_channels = int(math.floor(current_channels*
self.reduction_rate))
block.add_module('Transition', Transition(
current_channels, new_channels, out_scales,
offset, self.growth_factor, self.args))
print('| Transition layer {} was added! |'.
format(self.cur_transition_layer))
current_channels = new_channels
# Increment counters
self.cur_transition_layer += 1
elif self.msd_prune != 'max':
raise NotImplementedError
return block, current_channels
def print_layer(self, in_scales, out_scales):
print('| Layer {:0>2d} input scales {} output scales {} |'.
format(self.cur_layer, in_scales, out_scales))
def forward(self, x, progress=None):
"""
Propagate Input image in all blocks of MSD layers and classifiers
and return a list of classifications
:param x: Input image / batch
:return: a list of classification outputs
"""
outputs = [None] * self.num_blocks
cur_input = x
for block_num in range(0, self.num_blocks):
# Get the current block's output
if self.args.debug:
print("")
print("Forwarding to block %s:" % str(block_num + 1))
block = self.subnets[block_num]
cur_input = block_output = block(cur_input)
# Classify and add current output
if self.args.debug:
print("- Getting %s block's output" % str(block_num + 1))
for s, b in enumerate(block_output):
print("- Output size of this block's scale {}: ".format(s),
b.size())
class_output = \
self.subnets[block_num+self.num_blocks](block_output[-1])
outputs[block_num] = class_output
return outputs