| 127 | |
| 128 | |
| 129 | class ResNet(nn.Module): |
| 130 | |
| 131 | def __init__(self, block, layers, width=1, in_channel=3, zero_init_residual=False, |
| 132 | groups=1, width_per_group=64, replace_stride_with_dilation=None, |
| 133 | norm_layer=None): |
| 134 | super(ResNet, self).__init__() |
| 135 | if norm_layer is None: |
| 136 | norm_layer = nn.BatchNorm2d |
| 137 | self._norm_layer = norm_layer |
| 138 | |
| 139 | self.inplanes = max(int(64 * width), 64) |
| 140 | self.base = int(64 * width) |
| 141 | self.dilation = 1 |
| 142 | if replace_stride_with_dilation is None: |
| 143 | # each element in the tuple indicates if we should replace |
| 144 | # the 2x2 stride with a dilated convolution instead |
| 145 | replace_stride_with_dilation = [False, False, False] |
| 146 | if len(replace_stride_with_dilation) != 3: |
| 147 | raise ValueError("replace_stride_with_dilation should be None " |
| 148 | "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) |
| 149 | self.groups = groups |
| 150 | self.base_width = width_per_group |
| 151 | self.conv1 = nn.Conv2d(in_channel, self.inplanes, kernel_size=7, stride=2, padding=3, |
| 152 | bias=False) |
| 153 | self.bn1 = norm_layer(self.inplanes) |
| 154 | self.relu = nn.ReLU(inplace=True) |
| 155 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) |
| 156 | self.layer1 = self._make_layer(block, self.base, layers[0]) |
| 157 | self.layer2 = self._make_layer(block, self.base * 2, layers[1], stride=2, |
| 158 | dilate=replace_stride_with_dilation[0]) |
| 159 | self.layer3 = self._make_layer(block, self.base * 4, layers[2], stride=2, |
| 160 | dilate=replace_stride_with_dilation[1]) |
| 161 | self.layer4 = self._make_layer(block, self.base * 8, layers[3], stride=2, |
| 162 | dilate=replace_stride_with_dilation[2]) |
| 163 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) |
| 164 | |
| 165 | # comment out fc layer for unsupervised learning, will have another head |
| 166 | # self.fc = nn.Linear(512 * block.expansion, num_classes) |
| 167 | |
| 168 | for m in self.modules(): |
| 169 | if isinstance(m, nn.Conv2d): |
| 170 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') |
| 171 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): |
| 172 | nn.init.constant_(m.weight, 1) |
| 173 | nn.init.constant_(m.bias, 0) |
| 174 | |
| 175 | # Zero-initialize the last BN in each residual branch, |
| 176 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. |
| 177 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 |
| 178 | if zero_init_residual: |
| 179 | for m in self.modules(): |
| 180 | if isinstance(m, Bottleneck): |
| 181 | nn.init.constant_(m.bn3.weight, 0) |
| 182 | elif isinstance(m, BasicBlock): |
| 183 | nn.init.constant_(m.bn2.weight, 0) |
| 184 | |
| 185 | def _make_layer(self, block, planes, blocks, stride=1, dilate=False): |
| 186 | norm_layer = self._norm_layer |