MCPcopy Create free account
hub / github.com/OpenDriveLab/TCP / ResNet

Class ResNet

TCP/resnet.py:144–249  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

142
143
144class ResNet(nn.Module):
145
146 def __init__(
147 self,
148 block: Type[Union[BasicBlock, Bottleneck]],
149 layers: List[int],
150 num_classes: int = 1000,
151 zero_init_residual: bool = False,
152 groups: int = 1,
153 width_per_group: int = 64,
154 replace_stride_with_dilation: Optional[List[bool]] = None,
155 norm_layer: Optional[Callable[..., nn.Module]] = None
156 ) -> None:
157 super(ResNet, self).__init__()
158 if norm_layer is None:
159 norm_layer = nn.BatchNorm2d
160 self._norm_layer = norm_layer
161
162 self.inplanes = 64
163 self.dilation = 1
164 if replace_stride_with_dilation is None:
165 # each element in the tuple indicates if we should replace
166 # the 2x2 stride with a dilated convolution instead
167 replace_stride_with_dilation = [False, False, False]
168 if len(replace_stride_with_dilation) != 3:
169 raise ValueError("replace_stride_with_dilation should be None "
170 "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
171 self.groups = groups
172 self.base_width = width_per_group
173 self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
174 bias=False)
175 self.bn1 = norm_layer(self.inplanes)
176 self.relu = nn.ReLU(inplace=True)
177 self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
178 self.layer1 = self._make_layer(block, 64, layers[0])
179 self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
180 dilate=replace_stride_with_dilation[0])
181 self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
182 dilate=replace_stride_with_dilation[1])
183 self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
184 dilate=replace_stride_with_dilation[2])
185 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
186 self.fc = nn.Linear(512 * block.expansion, num_classes)
187
188 for m in self.modules():
189 if isinstance(m, nn.Conv2d):
190 nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
191 elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
192 nn.init.constant_(m.weight, 1)
193 nn.init.constant_(m.bias, 0)
194
195 # Zero-initialize the last BN in each residual branch,
196 # so that the residual branch starts with zeros, and each residual block behaves like an identity.
197 # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
198 if zero_init_residual:
199 for m in self.modules():
200 if isinstance(m, Bottleneck):
201 nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]

Callers 1

_resnetFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected