| 336 | |
| 337 | |
| 338 | class NextViT(nn.Module): |
| 339 | def __init__(self, stem_chs, depths, path_dropout, attn_drop=0, drop=0, num_classes=1000, |
| 340 | strides=[1, 2, 2, 2], sr_ratios=[8, 4, 2, 1], head_dim=32, mix_block_ratio=0.75, |
| 341 | use_checkpoint=False): |
| 342 | super(NextViT, self).__init__() |
| 343 | self.use_checkpoint = use_checkpoint |
| 344 | |
| 345 | self.stage_out_channels = [[96] * (depths[0]), |
| 346 | [192] * (depths[1] - 1) + [256], |
| 347 | [384, 384, 384, 384, 512] * (depths[2] // 5), |
| 348 | [768] * (depths[3] - 1) + [1024]] |
| 349 | |
| 350 | # Next Hybrid Strategy |
| 351 | self.stage_block_types = [[NCB] * depths[0], |
| 352 | [NCB] * (depths[1] - 1) + [NTB], |
| 353 | [NCB, NCB, NCB, NCB, NTB] * (depths[2] // 5), |
| 354 | [NCB] * (depths[3] - 1) + [NTB]] |
| 355 | |
| 356 | self.stem = nn.Sequential( |
| 357 | ConvBNReLU(3, stem_chs[0], kernel_size=3, stride=2), |
| 358 | ConvBNReLU(stem_chs[0], stem_chs[1], kernel_size=3, stride=1), |
| 359 | ConvBNReLU(stem_chs[1], stem_chs[2], kernel_size=3, stride=1), |
| 360 | ConvBNReLU(stem_chs[2], stem_chs[2], kernel_size=3, stride=2), |
| 361 | ) |
| 362 | input_channel = stem_chs[-1] |
| 363 | features = [] |
| 364 | idx = 0 |
| 365 | dpr = [x.item() for x in torch.linspace(0, path_dropout, sum(depths))] # stochastic depth decay rule |
| 366 | for stage_id in range(len(depths)): |
| 367 | numrepeat = depths[stage_id] |
| 368 | output_channels = self.stage_out_channels[stage_id] |
| 369 | block_types = self.stage_block_types[stage_id] |
| 370 | for block_id in range(numrepeat): |
| 371 | if strides[stage_id] == 2 and block_id == 0: |
| 372 | stride = 2 |
| 373 | else: |
| 374 | stride = 1 |
| 375 | output_channel = output_channels[block_id] |
| 376 | block_type = block_types[block_id] |
| 377 | if block_type is NCB: |
| 378 | layer = NCB(input_channel, output_channel, stride=stride, path_dropout=dpr[idx + block_id], |
| 379 | drop=drop, head_dim=head_dim) |
| 380 | features.append(layer) |
| 381 | elif block_type is NTB: |
| 382 | layer = NTB(input_channel, output_channel, path_dropout=dpr[idx + block_id], stride=stride, |
| 383 | sr_ratio=sr_ratios[stage_id], head_dim=head_dim, mix_block_ratio=mix_block_ratio, |
| 384 | attn_drop=attn_drop, drop=drop) |
| 385 | features.append(layer) |
| 386 | input_channel = output_channel |
| 387 | idx += numrepeat |
| 388 | self.features = nn.Sequential(*features) |
| 389 | |
| 390 | self.norm = nn.BatchNorm2d(output_channel, eps=NORM_EPS) |
| 391 | |
| 392 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) |
| 393 | self.proj_head = nn.Sequential( |
| 394 | nn.Linear(output_channel, num_classes), |
| 395 | ) |
no outgoing calls
no test coverage detected