xdecoder/Instruct-X-Decoder
163
1# --------------------------------------------------------2# FocalNet for Semantic Segmentation3# Copyright (c) 2022 Microsoft4# Licensed under The MIT License [see LICENSE for details]5# Written by Jianwei Yang6# --------------------------------------------------------7import math8import time9import numpy as np10import logging11import torch12import torch.nn as nn13import torch.nn.functional as F14import torch.utils.checkpoint as checkpoint15from timm.models.layers import DropPath, to_2tuple, trunc_normal_16 17from detectron2.utils.file_io import PathManager18from detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec19 20from .registry import register_backbone21 22logger = logging.getLogger(__name__)23 24class Mlp(nn.Module):25 """ Multilayer perceptron."""26 27 def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):28 super().__init__()29 out_features = out_features or in_features30 hidden_features = hidden_features or in_features31 self.fc1 = nn.Linear(in_features, hidden_features)32 self.act = act_layer()33 self.fc2 = nn.Linear(hidden_features, out_features)34 self.drop = nn.Dropout(drop)35 36 def forward(self, x):37 x = self.fc1(x)38 x = self.act(x)39 x = self.drop(x)40 x = self.fc2(x)41 x = self.drop(x)42 return x43 44class FocalModulation(nn.Module):45 """ Focal Modulation46 47 Args:48 dim (int): Number of input channels.49 proj_drop (float, optional): Dropout ratio of output. Default: 0.050 focal_level (int): Number of focal levels51 focal_window (int): Focal window size at focal level 152 focal_factor (int, default=2): Step to increase the focal window53 use_postln (bool, default=False): Whether use post-modulation layernorm54 """55 56 def __init__(self, dim, proj_drop=0., focal_level=2, focal_window=7, focal_factor=2, use_postln=False, use_postln_in_modulation=False, scaling_modulator=False):57 58 super().__init__()59 self.dim = dim60 61 # specific args for focalv362 self.focal_level = focal_level63 self.focal_window = focal_window64 self.focal_factor = focal_factor65 self.use_postln_in_modulation = use_postln_in_modulation66 self.scaling_modulator = scaling_modulator67 68 self.f = nn.Linear(dim, 2*dim+(self.focal_level+1), bias=True)69 self.h = nn.Conv2d(dim, dim, kernel_size=1, stride=1, padding=0, groups=1, bias=True)70 71 self.act = nn.GELU()72 self.proj = nn.Linear(dim, dim)73 self.proj_drop = nn.Dropout(proj_drop)74 self.focal_layers = nn.ModuleList()75 76 if self.use_postln_in_modulation:77 self.ln = nn.LayerNorm(dim)78 79 for k in range(self.focal_level):80 kernel_size = self.focal_factor*k + self.focal_window81 self.focal_layers.append(82 nn.Sequential(83 nn.Conv2d(dim, dim, kernel_size=kernel_size, stride=1, groups=dim, 84 padding=kernel_size//2, bias=False),85 nn.GELU(),86 )87 )88 89 def forward(self, x):90 """ Forward function.91 92 Args:93 x: input features with shape of (B, H, W, C)94 """95 B, nH, nW, C = x.shape96 x = self.f(x)97 x = x.permute(0, 3, 1, 2).contiguous()98 q, ctx, gates = torch.split(x, (C, C, self.focal_level+1), 1)99 100 ctx_all = 0101 for l in range(self.focal_level): 102 ctx = self.focal_layers[l](ctx)103 ctx_all = ctx_all + ctx*gates[:, l:l+1]104 ctx_global = self.act(ctx.mean(2, keepdim=True).mean(3, keepdim=True))105 ctx_all = ctx_all + ctx_global*gates[:,self.focal_level:]106 107 if self.scaling_modulator:108 ctx_all = ctx_all / (self.focal_level + 1)109 110 x_out = q * self.h(ctx_all)111 x_out = x_out.permute(0, 2, 3, 1).contiguous()112 if self.use_postln_in_modulation:113 x_out = self.ln(x_out) 114 x_out = self.proj(x_out)115 x_out = self.proj_drop(x_out)116 return x_out117 118class FocalModulationBlock(nn.Module):119 """ Focal Modulation Block.120 121 Args:122 dim (int): Number of input channels.123 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.124 drop (float, optional): Dropout rate. Default: 0.0125 drop_path (float, optional): Stochastic depth rate. Default: 0.0126 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU127 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm128 focal_level (int): number of focal levels129 focal_window (int): focal kernel size at level 1130 """131 132 def __init__(self, dim, mlp_ratio=4., drop=0., drop_path=0., 133 act_layer=nn.GELU, norm_layer=nn.LayerNorm,134 focal_level=2, focal_window=9, 135 use_postln=False, use_postln_in_modulation=False,136 scaling_modulator=False, 137 use_layerscale=False, 138 layerscale_value=1e-4):139 super().__init__()140 self.dim = dim141 self.mlp_ratio = mlp_ratio142 self.focal_window = focal_window143 self.focal_level = focal_level144 self.use_postln = use_postln145 self.use_layerscale = use_layerscale146 147 self.norm1 = norm_layer(dim)148 self.modulation = FocalModulation(149 dim, focal_window=self.focal_window, focal_level=self.focal_level, proj_drop=drop, use_postln_in_modulation=use_postln_in_modulation, scaling_modulator=scaling_modulator150 ) 151 152 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()153 self.norm2 = norm_layer(dim)154 mlp_hidden_dim = int(dim * mlp_ratio)155 self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)156 157 self.H = None158 self.W = None159 160 self.gamma_1 = 1.0161 self.gamma_2 = 1.0162 if self.use_layerscale:163 self.gamma_1 = nn.Parameter(layerscale_value * torch.ones((dim)), requires_grad=True)164 self.gamma_2 = nn.Parameter(layerscale_value * torch.ones((dim)), requires_grad=True)165 166 def forward(self, x):167 """ Forward function.168 169 Args:170 x: Input feature, tensor size (B, H*W, C).171 H, W: Spatial resolution of the input feature.172 """173 B, L, C = x.shape174 H, W = self.H, self.W175 assert L == H * W, "input feature has wrong size"176 177 shortcut = x178 if not self.use_postln:179 x = self.norm1(x)180 x = x.view(B, H, W, C)181 182 # FM183 x = self.modulation(x).view(B, H * W, C)184 if self.use_postln:185 x = self.norm1(x)186 187 # FFN188 x = shortcut + self.drop_path(self.gamma_1 * x)189 190 if self.use_postln:191 x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))192 else:193 x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))194 195 return x196 197class BasicLayer(nn.Module):198 """ A basic focal modulation layer for one stage.199 200 Args:201 dim (int): Number of feature channels202 depth (int): Depths of this stage.203 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.204 drop (float, optional): Dropout rate. Default: 0.0205 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0206 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm207 downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None208 focal_level (int): Number of focal levels209 focal_window (int): Focal window size at focal level 1210 use_conv_embed (bool): Use overlapped convolution for patch embedding or now. Default: False211 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False212 """213 214 def __init__(self,215 dim,216 depth,217 mlp_ratio=4.,218 drop=0.,219 drop_path=0.,220 norm_layer=nn.LayerNorm,221 downsample=None,222 focal_window=9, 223 focal_level=2, 224 use_conv_embed=False, 225 use_postln=False, 226 use_postln_in_modulation=False, 227 scaling_modulator=False,228 use_layerscale=False, 229 use_checkpoint=False230 ):231 super().__init__()232 self.depth = depth233 self.use_checkpoint = use_checkpoint234 235 # build blocks236 self.blocks = nn.ModuleList([237 FocalModulationBlock(238 dim=dim,239 mlp_ratio=mlp_ratio,240 drop=drop,241 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,242 focal_window=focal_window, 243 focal_level=focal_level, 244 use_postln=use_postln, 245 use_postln_in_modulation=use_postln_in_modulation, 246 scaling_modulator=scaling_modulator,247 use_layerscale=use_layerscale, 248 norm_layer=norm_layer)249 for i in range(depth)])250 251 # patch merging layer252 if downsample is not None:253 self.downsample = downsample(254 patch_size=2,255 in_chans=dim, embed_dim=2*dim, 256 use_conv_embed=use_conv_embed, 257 norm_layer=norm_layer, 258 is_stem=False259 )260 261 else:262 self.downsample = None263 264 def forward(self, x, H, W):265 """ Forward function.266 267 Args:268 x: Input feature, tensor size (B, H*W, C).269 H, W: Spatial resolution of the input feature.270 """271 for blk in self.blocks:272 blk.H, blk.W = H, W273 if self.use_checkpoint:274 x = checkpoint.checkpoint(blk, x)275 else:276 x = blk(x)277 if self.downsample is not None:278 x_reshaped = x.transpose(1, 2).view(x.shape[0], x.shape[-1], H, W)279 x_down = self.downsample(x_reshaped) 280 x_down = x_down.flatten(2).transpose(1, 2) 281 Wh, Ww = (H + 1) // 2, (W + 1) // 2282 return x, H, W, x_down, Wh, Ww283 else:284 return x, H, W, x, H, W285 286 287class PatchEmbed(nn.Module):288 """ Image to Patch Embedding289 290 Args:291 patch_size (int): Patch token size. Default: 4.292 in_chans (int): Number of input image channels. Default: 3.293 embed_dim (int): Number of linear projection output channels. Default: 96.294 norm_layer (nn.Module, optional): Normalization layer. Default: None295 use_conv_embed (bool): Whether use overlapped convolution for patch embedding. Default: False296 is_stem (bool): Is the stem block or not. 297 """298 299 def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None, use_conv_embed=False, is_stem=False):300 super().__init__()301 patch_size = to_2tuple(patch_size)302 self.patch_size = patch_size303 304 self.in_chans = in_chans305 self.embed_dim = embed_dim306 307 if use_conv_embed:308 # if we choose to use conv embedding, then we treat the stem and non-stem differently309 if is_stem:310 kernel_size = 7; padding = 2; stride = 4311 else:312 kernel_size = 3; padding = 1; stride = 2313 self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding) 314 else:315 self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)316 317 if norm_layer is not None:318 self.norm = norm_layer(embed_dim)319 else:320 self.norm = None321 322 def forward(self, x):323 """Forward function."""324 _, _, H, W = x.size()325 if W % self.patch_size[1] != 0:326 x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))327 if H % self.patch_size[0] != 0:328 x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))329 330 x = self.proj(x) # B C Wh Ww331 if self.norm is not None:332 Wh, Ww = x.size(2), x.size(3)333 x = x.flatten(2).transpose(1, 2)334 x = self.norm(x)335 x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)336 337 return x338 339 340class FocalNet(nn.Module):341 """ FocalNet backbone.342 343 Args:344 pretrain_img_size (int): Input image size for training the pretrained model,345 used in absolute postion embedding. Default 224.346 patch_size (int | tuple(int)): Patch size. Default: 4.347 in_chans (int): Number of input image channels. Default: 3.348 embed_dim (int): Number of linear projection output channels. Default: 96.349 depths (tuple[int]): Depths of each Swin Transformer stage.350 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.351 drop_rate (float): Dropout rate.352 drop_path_rate (float): Stochastic depth rate. Default: 0.2.353 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.354 patch_norm (bool): If True, add normalization after patch embedding. Default: True.355 out_indices (Sequence[int]): Output from which stages.356 frozen_stages (int): Stages to be frozen (stop grad and set eval mode).357 -1 means not freezing any parameters.358 focal_levels (Sequence[int]): Number of focal levels at four stages359 focal_windows (Sequence[int]): Focal window sizes at first focal level at four stages360 use_conv_embed (bool): Whether use overlapped convolution for patch embedding361 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.362 """363 364 def __init__(self,365 pretrain_img_size=1600,366 patch_size=4,367 in_chans=3,368 embed_dim=96,369 depths=[2, 2, 6, 2],370 mlp_ratio=4.,371 drop_rate=0.,372 drop_path_rate=0.2,373 norm_layer=nn.LayerNorm,374 patch_norm=True,375 out_indices=[0, 1, 2, 3],376 frozen_stages=-1,377 focal_levels=[2,2,2,2], 378 focal_windows=[9,9,9,9],379 use_conv_embed=False, 380 use_postln=False, 381 use_postln_in_modulation=False, 382 scaling_modulator=False,383 use_layerscale=False, 384 use_checkpoint=False, 385 ):386 super().__init__()387 388 self.pretrain_img_size = pretrain_img_size389 self.num_layers = len(depths)390 self.embed_dim = embed_dim391 self.patch_norm = patch_norm392 self.out_indices = out_indices393 self.frozen_stages = frozen_stages394 395 # split image into non-overlapping patches396 self.patch_embed = PatchEmbed(397 patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,398 norm_layer=norm_layer if self.patch_norm else None, 399 use_conv_embed=use_conv_embed, is_stem=True)400 401 self.pos_drop = nn.Dropout(p=drop_rate)402 403 # stochastic depth404 dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule405 406 # build layers407 self.layers = nn.ModuleList()408 for i_layer in range(self.num_layers):409 layer = BasicLayer(410 dim=int(embed_dim * 2 ** i_layer),411 depth=depths[i_layer],412 mlp_ratio=mlp_ratio,413 drop=drop_rate,414 drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],415 norm_layer=norm_layer,416 downsample=PatchEmbed if (i_layer < self.num_layers - 1) else None,417 focal_window=focal_windows[i_layer], 418 focal_level=focal_levels[i_layer], 419 use_conv_embed=use_conv_embed,420 use_postln=use_postln, 421 use_postln_in_modulation=use_postln_in_modulation,422 scaling_modulator=scaling_modulator,423 use_layerscale=use_layerscale, 424 use_checkpoint=use_checkpoint)425 self.layers.append(layer)426 427 num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]428 self.num_features = num_features429 430 # add a norm layer for each output431 for i_layer in out_indices:432 layer = norm_layer(num_features[i_layer])433 layer_name = f'norm{i_layer}'434 self.add_module(layer_name, layer)435 436 self._freeze_stages()437 438 def _freeze_stages(self):439 if self.frozen_stages >= 0:440 self.patch_embed.eval()441 for param in self.patch_embed.parameters():442 param.requires_grad = False443 444 if self.frozen_stages >= 2:445 self.pos_drop.eval()446 for i in range(0, self.frozen_stages - 1):447 m = self.layers[i]448 m.eval()449 for param in m.parameters():450 param.requires_grad = False451 452 def init_weights(self, pretrained=None):453 """Initialize the weights in backbone.454 455 Args:456 pretrained (str, optional): Path to pre-trained weights.457 Defaults to None.458 """459 460 def _init_weights(m):461 if isinstance(m, nn.Linear):462 trunc_normal_(m.weight, std=.02)463 if isinstance(m, nn.Linear) and m.bias is not None:464 nn.init.constant_(m.bias, 0)465 elif isinstance(m, nn.LayerNorm):466 nn.init.constant_(m.bias, 0)467 nn.init.constant_(m.weight, 1.0)468 469 if isinstance(pretrained, str):470 self.apply(_init_weights)471 logger = get_root_logger()472 load_checkpoint(self, pretrained, strict=False, logger=logger)473 elif pretrained is None:474 self.apply(_init_weights)475 else:476 raise TypeError('pretrained must be a str or None')477 478 def load_weights(self, pretrained_dict=None, pretrained_layers=[], verbose=True):479 model_dict = self.state_dict()480 481 missed_dict = [k for k in model_dict.keys() if k not in pretrained_dict]482 logger.info(f'=> Missed keys {missed_dict}')483 unexpected_dict = [k for k in pretrained_dict.keys() if k not in model_dict]484 logger.info(f'=> Unexpected keys {unexpected_dict}')485 486 pretrained_dict = {487 k: v for k, v in pretrained_dict.items()488 if k in model_dict.keys()489 }490 491 need_init_state_dict = {}492 for k, v in pretrained_dict.items():493 need_init = (494 (495 k.split('.')[0] in pretrained_layers496 or pretrained_layers[0] == '*'497 )498 and 'relative_position_index' not in k499 and 'attn_mask' not in k500 )501 502 if need_init:503 # if verbose:504 # logger.info(f'=> init {k} from {pretrained}')505 506 if ('pool_layers' in k) or ('focal_layers' in k) and v.size() != model_dict[k].size():507 table_pretrained = v508 table_current = model_dict[k]509 fsize1 = table_pretrained.shape[2]510 fsize2 = table_current.shape[2]511 512 # NOTE: different from interpolation used in self-attention, we use padding or clipping for focal conv513 if fsize1 < fsize2:514 table_pretrained_resized = torch.zeros(table_current.shape)515 table_pretrained_resized[:, :, (fsize2-fsize1)//2:-(fsize2-fsize1)//2, (fsize2-fsize1)//2:-(fsize2-fsize1)//2] = table_pretrained516 v = table_pretrained_resized517 elif fsize1 > fsize2:518 table_pretrained_resized = table_pretrained[:, :, (fsize1-fsize2)//2:-(fsize1-fsize2)//2, (fsize1-fsize2)//2:-(fsize1-fsize2)//2]519 v = table_pretrained_resized520 521 522 if ("modulation.f" in k or "pre_conv" in k): 523 table_pretrained = v524 table_current = model_dict[k]525 if table_pretrained.shape != table_current.shape:526 if len(table_pretrained.shape) == 2:527 dim = table_pretrained.shape[1]528 assert table_current.shape[1] == dim529 L1 = table_pretrained.shape[0]530 L2 = table_current.shape[0]531 532 if L1 < L2:533 table_pretrained_resized = torch.zeros(table_current.shape)534 # copy for linear project535 table_pretrained_resized[:2*dim] = table_pretrained[:2*dim]536 # copy for global token gating537 table_pretrained_resized[-1] = table_pretrained[-1]538 # copy for first multiple focal levels539 table_pretrained_resized[2*dim:2*dim+(L1-2*dim-1)] = table_pretrained[2*dim:-1]540 # reassign pretrained weights541 v = table_pretrained_resized542 elif L1 > L2:543 raise NotImplementedError544 elif len(table_pretrained.shape) == 1:545 dim = table_pretrained.shape[0]546 L1 = table_pretrained.shape[0]547 L2 = table_current.shape[0]548 if L1 < L2:549 table_pretrained_resized = torch.zeros(table_current.shape)550 # copy for linear project551 table_pretrained_resized[:dim] = table_pretrained[:dim]552 # copy for global token gating553 table_pretrained_resized[-1] = table_pretrained[-1]554 # copy for first multiple focal levels555 # table_pretrained_resized[dim:2*dim+(L1-2*dim-1)] = table_pretrained[2*dim:-1]556 # reassign pretrained weights557 v = table_pretrained_resized558 elif L1 > L2:559 raise NotImplementedError 560 561 need_init_state_dict[k] = v562 563 self.load_state_dict(need_init_state_dict, strict=False)564 565 566 def forward(self, x):567 """Forward function."""568 tic = time.time()569 x = self.patch_embed(x)570 Wh, Ww = x.size(2), x.size(3)571 572 x = x.flatten(2).transpose(1, 2)573 x = self.pos_drop(x)574 575 outs = {}576 for i in range(self.num_layers):577 layer = self.layers[i]578 x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)579 if i in self.out_indices:580 norm_layer = getattr(self, f'norm{i}')581 x_out = norm_layer(x_out)582 583 out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()584 outs["res{}".format(i + 2)] = out585 586 if len(self.out_indices) == 0:587 outs["res5"] = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()588 589 toc = time.time()590 return outs591 592 def train(self, mode=True):593 """Convert the model into training mode while keep layers freezed."""594 super(FocalNet, self).train(mode)595 self._freeze_stages()596 597 598class D2FocalNet(FocalNet, Backbone):599 def __init__(self, cfg, input_shape):600 601 pretrain_img_size = cfg['BACKBONE']['FOCAL']['PRETRAIN_IMG_SIZE']602 patch_size = cfg['BACKBONE']['FOCAL']['PATCH_SIZE']603 in_chans = 3604 embed_dim = cfg['BACKBONE']['FOCAL']['EMBED_DIM']605 depths = cfg['BACKBONE']['FOCAL']['DEPTHS']606 mlp_ratio = cfg['BACKBONE']['FOCAL']['MLP_RATIO']607 drop_rate = cfg['BACKBONE']['FOCAL']['DROP_RATE']608 drop_path_rate = cfg['BACKBONE']['FOCAL']['DROP_PATH_RATE']609 norm_layer = nn.LayerNorm610 patch_norm = cfg['BACKBONE']['FOCAL']['PATCH_NORM']611 use_checkpoint = cfg['BACKBONE']['FOCAL']['USE_CHECKPOINT']612 out_indices = cfg['BACKBONE']['FOCAL']['OUT_INDICES']613 scaling_modulator = cfg['BACKBONE']['FOCAL'].get('SCALING_MODULATOR', False)614 615 super().__init__(616 pretrain_img_size,617 patch_size,618 in_chans,619 embed_dim,620 depths,621 mlp_ratio,622 drop_rate,623 drop_path_rate,624 norm_layer,625 patch_norm,626 out_indices,627 focal_levels=cfg['BACKBONE']['FOCAL']['FOCAL_LEVELS'],628 focal_windows=cfg['BACKBONE']['FOCAL']['FOCAL_WINDOWS'], 629 use_conv_embed=cfg['BACKBONE']['FOCAL']['USE_CONV_EMBED'], 630 use_postln=cfg['BACKBONE']['FOCAL']['USE_POSTLN'], 631 use_postln_in_modulation=cfg['BACKBONE']['FOCAL']['USE_POSTLN_IN_MODULATION'], 632 scaling_modulator=scaling_modulator,633 use_layerscale=cfg['BACKBONE']['FOCAL']['USE_LAYERSCALE'], 634 use_checkpoint=use_checkpoint,635 )636 637 self._out_features = cfg['BACKBONE']['FOCAL']['OUT_FEATURES']638 639 self._out_feature_strides = {640 "res2": 4,641 "res3": 8,642 "res4": 16,643 "res5": 32,644 }645 self._out_feature_channels = {646 "res2": self.num_features[0],647 "res3": self.num_features[1],648 "res4": self.num_features[2],649 "res5": self.num_features[3],650 }651 652 def forward(self, x):653 """654 Args:655 x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``.656 Returns:657 dict[str->Tensor]: names and the corresponding features658 """659 assert (660 x.dim() == 4661 ), f"SwinTransformer takes an input of shape (N, C, H, W). Got {x.shape} instead!"662 outputs = {}663 y = super().forward(x)664 for k in y.keys():665 if k in self._out_features:666 outputs[k] = y[k]667 return outputs668 669 def output_shape(self):670 return {671 name: ShapeSpec(672 channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]673 )674 for name in self._out_features675 }676 677 @property678 def size_divisibility(self):679 return 32680 681@register_backbone682def get_focal_backbone(cfg):683 focal = D2FocalNet(cfg['MODEL'], 224) 684 685 if cfg['MODEL']['BACKBONE']['LOAD_PRETRAINED'] is True:686 filename = cfg['MODEL']['BACKBONE']['PRETRAINED']687 logger.info(f'=> init from {filename}')688 with PathManager.open(filename, "rb") as f:689 ckpt = torch.load(f)['model']690 focal.load_weights(ckpt, cfg['MODEL']['BACKBONE']['FOCAL'].get('PRETRAINED_LAYERS', ['*']), cfg['VERBOSE'])691 692 return focal