| 93 | |
| 94 | |
| 95 | class ResNet(nn.Module): |
| 96 | |
| 97 | def __init__(self, block, layers, last_conv_stride=2, last_conv_dilation=1): |
| 98 | |
| 99 | self.inplanes = 64 |
| 100 | super(ResNet, self).__init__() |
| 101 | self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, |
| 102 | bias=False) |
| 103 | self.bn1 = nn.BatchNorm2d(64) |
| 104 | self.relu = nn.ReLU(inplace=True) |
| 105 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) |
| 106 | self.layer1 = self._make_layer(block, 64, layers[0]) |
| 107 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2) |
| 108 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2) |
| 109 | self.layer4 = self._make_layer(block, 512, layers[3], stride=last_conv_stride, dilation=last_conv_dilation) |
| 110 | |
| 111 | for m in self.modules(): |
| 112 | if isinstance(m, nn.Conv2d): |
| 113 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels |
| 114 | m.weight.data.normal_(0, math.sqrt(2. / n)) |
| 115 | elif isinstance(m, nn.BatchNorm2d): |
| 116 | m.weight.data.fill_(1) |
| 117 | m.bias.data.zero_() |
| 118 | |
| 119 | def _make_layer(self, block, planes, blocks, stride=1, dilation=1): |
| 120 | downsample = None |
| 121 | if stride != 1 or self.inplanes != planes * block.expansion: |
| 122 | downsample = nn.Sequential( |
| 123 | nn.Conv2d(self.inplanes, planes * block.expansion, |
| 124 | kernel_size=1, stride=stride, bias=False), |
| 125 | nn.BatchNorm2d(planes * block.expansion), |
| 126 | ) |
| 127 | |
| 128 | layers = [] |
| 129 | layers.append(block(self.inplanes, planes, stride, downsample, dilation)) |
| 130 | self.inplanes = planes * block.expansion |
| 131 | for i in range(1, blocks): |
| 132 | layers.append(block(self.inplanes, planes)) |
| 133 | |
| 134 | return nn.Sequential(*layers) |
| 135 | |
| 136 | def forward(self, x): |
| 137 | x = self.conv1(x) |
| 138 | x = self.bn1(x) |
| 139 | x = self.relu(x) |
| 140 | x = self.maxpool(x) |
| 141 | |
| 142 | x = self.layer1(x) |
| 143 | x = self.layer2(x) |
| 144 | x = self.layer3(x) |
| 145 | x = self.layer4(x) |
| 146 | |
| 147 | return x |
| 148 | |
| 149 | |
| 150 | def remove_fc(state_dict): |