|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +from torch.autograd import Variable |
| 5 | +from collections import OrderedDict |
| 6 | +from torch.nn import init |
| 7 | +import math |
| 8 | + |
| 9 | +def conv_bn(inp, oup, stride): |
| 10 | + return nn.Sequential( |
| 11 | + nn.Conv2d(inp, oup, 3, stride, 1, bias=False), |
| 12 | + nn.BatchNorm2d(oup), |
| 13 | + nn.ReLU(inplace=True) |
| 14 | + ) |
| 15 | + |
| 16 | + |
| 17 | +def conv_1x1_bn(inp, oup): |
| 18 | + return nn.Sequential( |
| 19 | + nn.Conv2d(inp, oup, 1, 1, 0, bias=False), |
| 20 | + nn.BatchNorm2d(oup), |
| 21 | + nn.ReLU(inplace=True) |
| 22 | + ) |
| 23 | + |
| 24 | +def channel_shuffle(x, groups): |
| 25 | + batchsize, num_channels, height, width = x.data.size() |
| 26 | + |
| 27 | + channels_per_group = num_channels // groups |
| 28 | + |
| 29 | + # reshape |
| 30 | + x = x.view(batchsize, groups, |
| 31 | + channels_per_group, height, width) |
| 32 | + |
| 33 | + x = torch.transpose(x, 1, 2).contiguous() |
| 34 | + |
| 35 | + # flatten |
| 36 | + x = x.view(batchsize, -1, height, width) |
| 37 | + |
| 38 | + return x |
| 39 | + |
| 40 | +class InvertedResidual(nn.Module): |
| 41 | + def __init__(self, inp, oup, stride, benchmodel): |
| 42 | + super(InvertedResidual, self).__init__() |
| 43 | + self.benchmodel = benchmodel |
| 44 | + self.stride = stride |
| 45 | + assert stride in [1, 2] |
| 46 | + |
| 47 | + oup_inc = oup//2 |
| 48 | + |
| 49 | + if self.benchmodel == 1: |
| 50 | + #assert inp == oup_inc |
| 51 | + self.banch2 = nn.Sequential( |
| 52 | + # pw |
| 53 | + nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False), |
| 54 | + nn.BatchNorm2d(oup_inc), |
| 55 | + nn.ReLU(inplace=True), |
| 56 | + # dw |
| 57 | + nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False), |
| 58 | + nn.BatchNorm2d(oup_inc), |
| 59 | + # pw-linear |
| 60 | + nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False), |
| 61 | + nn.BatchNorm2d(oup_inc), |
| 62 | + nn.ReLU(inplace=True), |
| 63 | + ) |
| 64 | + else: |
| 65 | + self.banch1 = nn.Sequential( |
| 66 | + # dw |
| 67 | + nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False), |
| 68 | + nn.BatchNorm2d(inp), |
| 69 | + # pw-linear |
| 70 | + nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False), |
| 71 | + nn.BatchNorm2d(oup_inc), |
| 72 | + nn.ReLU(inplace=True), |
| 73 | + ) |
| 74 | + |
| 75 | + self.banch2 = nn.Sequential( |
| 76 | + # pw |
| 77 | + nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False), |
| 78 | + nn.BatchNorm2d(oup_inc), |
| 79 | + nn.ReLU(inplace=True), |
| 80 | + # dw |
| 81 | + nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False), |
| 82 | + nn.BatchNorm2d(oup_inc), |
| 83 | + # pw-linear |
| 84 | + nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False), |
| 85 | + nn.BatchNorm2d(oup_inc), |
| 86 | + nn.ReLU(inplace=True), |
| 87 | + ) |
| 88 | + |
| 89 | + @staticmethod |
| 90 | + def _concat(x, out): |
| 91 | + # concatenate along channel axis |
| 92 | + return torch.cat((x, out), 1) |
| 93 | + |
| 94 | + def forward(self, x): |
| 95 | + if 1==self.benchmodel: |
| 96 | + x1 = x[:, :(x.shape[1]//2), :, :] |
| 97 | + x2 = x[:, (x.shape[1]//2):, :, :] |
| 98 | + out = self._concat(x1, self.banch2(x2)) |
| 99 | + elif 2==self.benchmodel: |
| 100 | + out = self._concat(self.banch1(x), self.banch2(x)) |
| 101 | + |
| 102 | + return channel_shuffle(out, 2) |
| 103 | + |
| 104 | + |
| 105 | +class ShuffleNetV2(nn.Module): |
| 106 | + def __init__(self, n_class=1000, input_size=224, width_mult=1.): |
| 107 | + super(ShuffleNetV2, self).__init__() |
| 108 | + |
| 109 | + assert input_size % 32 == 0 |
| 110 | + |
| 111 | + self.stage_repeats = [4, 8, 4] |
| 112 | + # index 0 is invalid and should never be called. |
| 113 | + # only used for indexing convenience. |
| 114 | + if width_mult == 0.5: |
| 115 | + self.stage_out_channels = [-1, 24, 48, 96, 192, 1024] |
| 116 | + elif width_mult == 1.0: |
| 117 | + self.stage_out_channels = [-1, 24, 116, 232, 464, 1024] |
| 118 | + elif width_mult == 1.5: |
| 119 | + self.stage_out_channels = [-1, 24, 176, 352, 704, 1024] |
| 120 | + elif width_mult == 2.0: |
| 121 | + self.stage_out_channels = [-1, 24, 224, 488, 976, 2048] |
| 122 | + else: |
| 123 | + raise ValueError( |
| 124 | + """{} groups is not supported for |
| 125 | + 1x1 Grouped Convolutions""".format(num_groups)) |
| 126 | + |
| 127 | + # building first layer |
| 128 | + input_channel = self.stage_out_channels[1] |
| 129 | + self.conv1 = conv_bn(3, input_channel, 2) |
| 130 | + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) |
| 131 | + |
| 132 | + self.features = [] |
| 133 | + # building inverted residual blocks |
| 134 | + for idxstage in range(len(self.stage_repeats)): |
| 135 | + numrepeat = self.stage_repeats[idxstage] |
| 136 | + output_channel = self.stage_out_channels[idxstage+2] |
| 137 | + for i in range(numrepeat): |
| 138 | + if i == 0: |
| 139 | + #inp, oup, stride, benchmodel): |
| 140 | + self.features.append(InvertedResidual(input_channel, output_channel, 2, 2)) |
| 141 | + else: |
| 142 | + self.features.append(InvertedResidual(input_channel, output_channel, 1, 1)) |
| 143 | + input_channel = output_channel |
| 144 | + |
| 145 | + |
| 146 | + # make it nn.Sequential |
| 147 | + self.features = nn.Sequential(*self.features) |
| 148 | + |
| 149 | + # building last several layers |
| 150 | + self.conv_last = conv_1x1_bn(input_channel, self.stage_out_channels[-1]) |
| 151 | + self.globalpool = nn.Sequential(nn.AvgPool2d(int(input_size/32))) |
| 152 | + |
| 153 | + # building classifier |
| 154 | + self.classifier = nn.Sequential(nn.Linear(self.stage_out_channels[-1], n_class)) |
| 155 | + |
| 156 | + def forward(self, x): |
| 157 | + x = self.conv1(x) |
| 158 | + x = self.maxpool(x) |
| 159 | + x = self.features(x) |
| 160 | + x = self.conv_last(x) |
| 161 | + x = self.globalpool(x) |
| 162 | + x = x.view(-1, self.stage_out_channels[-1]) |
| 163 | + x = self.classifier(x) |
| 164 | + return x |
| 165 | + |
| 166 | +def shufflenetv2(width_mult=1.): |
| 167 | + model = ShuffleNetV2(width_mult=width_mult) |
| 168 | + return model |
| 169 | + |
| 170 | +if __name__ == "__main__": |
| 171 | + """Testing |
| 172 | + """ |
| 173 | + model = ShuffleNetV2() |
| 174 | + print(model) |
0 commit comments