import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from typing import Optional from thop import profile class IRB(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, ksize=3, act_layer=nn.Hardswish, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Conv2d(in_features, hidden_features, 1, 1, 0) self.act = act_layer() self.conv = nn.Conv2d(hidden_features, hidden_features, kernel_size=ksize, padding=ksize // 2, stride=1, groups=hidden_features) self.fc2 = nn.Conv2d(hidden_features, out_features, 1, 1, 0) self.drop = nn.Dropout(drop) def forward(self, x, H, W): B, N, C = x.shape x = x.permute(0, 2, 1).reshape(B, C, H, W) x = self.fc1(x) x = self.act(x) x = self.conv(x) x = self.act(x) x = self.fc2(x) return x.reshape(B, C, -1).permute(0, 2, 1) def drop_path_f(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output class DropPath(nn.Module): def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path_f(x, self.drop_prob, self.training) def window_partition(x, window_size: int): B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows def window_reverse(windows, window_size: int, H: int, W: int): B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class PatchEmbed2(nn.Module): def __init__(self, dim:int, patch_size=2, in_c=3, norm_layer=None): super().__init__() patch_size = (patch_size, patch_size) self.patch_size = patch_size self.in_chans = in_c self.embed_dim = dim self.proj = nn.Conv2d(dim, 2*dim, kernel_size=patch_size, stride=patch_size) self.norm = norm_layer(2*dim) if norm_layer else nn.Identity() def forward(self, x, H, W): B, L, C = x.shape assert L == H * W, "input feature has wrong size" x = x.view(B, H, W, C) pad_input = (H % self.patch_size[0] != 0) or (W % self.patch_size[1] != 0) if pad_input: x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1], 0, self.patch_size[0] - H % self.patch_size[0], 0, 0)) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2) x = self.proj(x) _, _, H, W = x.shape x = x.flatten(2).transpose(1, 2) x = self.norm(x) return x class PatchEmbed(nn.Module): def __init__(self, patch_size=4, in_c=3, embed_dim=96, norm_layer=None): super().__init__() patch_size = (patch_size, patch_size) self.patch_size = patch_size self.in_chans = in_c self.embed_dim = embed_dim self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=patch_size, stride=patch_size) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): _, _, H, W = x.shape # padding # 如果输入图片的H,W不是patch_size的整数倍,需要进行padding pad_input = (H % self.patch_size[0] != 0) or (W % self.patch_size[1] != 0) if pad_input: x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1], 0, self.patch_size[0] - H % self.patch_size[0], 0, 0)) # 下采样patch_size倍 x = self.proj(x) _, _, H, W = x.shape x = x.flatten(2).transpose(1, 2) x = self.norm(x) return x, H, W class PatchMerging(nn.Module): def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x, H, W): B, L, C = x.shape assert L == H * W, "input feature has wrong size" x = x.view(B, H, W, C) pad_input = (H % 2 == 1) or (W % 2 == 1) if pad_input: x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) x0 = x[:, 0::2, 0::2, :] # [B, H/2, W/2, C] x1 = x[:, 1::2, 0::2, :] # [B, H/2, W/2, C] x2 = x[:, 0::2, 1::2, :] # [B, H/2, W/2, C] x3 = x[:, 1::2, 1::2, :] # [B, H/2, W/2, C] x = torch.cat([x0, x1, x2, x3], -1) # [B, H/2, W/2, 4*C] x = x.view(B, -1, 4 * C) # [B, H/2*W/2, 4*C] x = self.norm(x) x = self.reduction(x) # [B, H/2*W/2, 2*C] return x class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.drop1 = nn.Dropout(drop) self.fc2 = nn.Linear(hidden_features, out_features) self.drop2 = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x class WindowAttention(nn.Module): def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.window_size = window_size # [Mh, Mw] self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 # define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # [2*Mh-1 * 2*Mw-1, nH] # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) coords_flatten = torch.flatten(coords, 1) # [2, Mh*Mw] # [2, Mh*Mw, 1] - [2, 1, Mh*Mw] relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # [2, Mh*Mw, Mh*Mw] relative_coords = relative_coords.permute(1, 2, 0).contiguous() # [Mh*Mw, Mh*Mw, 2] relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # [Mh*Mw, Mh*Mw] self.register_buffer("relative_position_index", relative_position_index) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) nn.init.trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask: Optional[torch.Tensor] = None): B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) # [batch_size*num_windows, num_heads, Mh*Mw, embed_dim_per_head] q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) # transpose: -> [batch_size*num_windows, num_heads, embed_dim_per_head, Mh*Mw] # @: multiply -> [batch_size*num_windows, num_heads, Mh*Mw, Mh*Mw] q = q * self.scale attn = (q @ k.transpose(-2, -1)) relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # [nH, Mh*Mw, Mh*Mw] attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nW = mask.shape[0] # num_windows attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x class TransformerBlock(nn.Module): def __init__(self, dim, num_heads, window_sizes=(7,4,2), branch_num=3, mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.num_heads = num_heads self.window_sizes = window_sizes self.branch_num = branch_num self.mlp_ratio = mlp_ratio self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim//branch_num, window_size=(self.window_sizes[0], self.window_sizes[0]), num_heads=num_heads//branch_num, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.attn1 = WindowAttention( dim//branch_num, window_size=(self.window_sizes[1], self.window_sizes[1]), num_heads=num_heads//branch_num, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.attn2 = WindowAttention( dim//branch_num, window_size=(self.window_sizes[2], self.window_sizes[2]), num_heads=num_heads//branch_num, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = IRB(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x, attn_mask): H, W = self.H, self.W B, L, C = x.shape assert L == H * W, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(B, H, W, C) x0 = x[:,:,:,:(C//self.branch_num)] x1 = x[:,:,:,(C//self.branch_num):(2*C//self.branch_num)] x2 = x[:,:,:,(2*C//self.branch_num):] # ---------------------------------------------------------------------------------------------- pad_l = pad_t = 0 pad_r = (self.window_sizes[0] - W % self.window_sizes[0]) % self.window_sizes[0] pad_b = (self.window_sizes[0] - H % self.window_sizes[0]) % self.window_sizes[0] x0 = F.pad(x0, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x0.shape attn_mask = None # partition windows x_windows = window_partition(x0, self.window_sizes[0]) # [nW*B, Mh, Mw, C] x_windows = x_windows.view(-1, self.window_sizes[0] * self.window_sizes[0], C//self.branch_num) # [nW*B, Mh*Mw, C] # W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=attn_mask) # [nW*B, Mh*Mw, C] # merge windows attn_windows = attn_windows.view(-1, self.window_sizes[0], self.window_sizes[0], C//self.branch_num) # [nW*B, Mh, Mw, C] x0 = window_reverse(attn_windows, self.window_sizes[0], Hp, Wp) # [B, H', W', C] if pad_r > 0 or pad_b > 0: # 把前面pad的数据移除掉 x0 = x0[:, :H, :W, :].contiguous() x0 = x0.view(B, H * W, C//self.branch_num) # ---------------------------------------------------------------------------------------------- pad_l = pad_t = 0 pad_r = (self.window_sizes[1] - W % self.window_sizes[1]) % self.window_sizes[1] pad_b = (self.window_sizes[1] - H % self.window_sizes[1]) % self.window_sizes[1] x1 = F.pad(x1, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x1.shape attn_mask = None # partition windows x_windows = window_partition(x1, self.window_sizes[1]) # [nW*B, Mh, Mw, C] x_windows = x_windows.view(-1, self.window_sizes[1] * self.window_sizes[1], C // self.branch_num) # [nW*B, Mh*Mw, C] # W-MSA/SW-MSA attn_windows = self.attn1(x_windows, mask=attn_mask) # [nW*B, Mh*Mw, C] # merge windows attn_windows = attn_windows.view(-1, self.window_sizes[1], self.window_sizes[1], C // self.branch_num) # [nW*B, Mh, Mw, C] x1 = window_reverse(attn_windows, self.window_sizes[1], Hp, Wp) # [B, H', W', C] if pad_r > 0 or pad_b > 0: # 把前面pad的数据移除掉 x1 = x1[:, :H, :W, :].contiguous() x1 = x1.view(B, H * W, C // self.branch_num) # ---------------------------------------------------------------------------------------------- pad_l = pad_t = 0 pad_r = (self.window_sizes[2] - W % self.window_sizes[2]) % self.window_sizes[2] pad_b = (self.window_sizes[2] - H % self.window_sizes[2]) % self.window_sizes[2] x2 = F.pad(x2, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x2.shape attn_mask = None x_windows = window_partition(x2, self.window_sizes[2]) # [nW*B, Mh, Mw, C] x_windows = x_windows.view(-1, self.window_sizes[2] * self.window_sizes[2], C // self.branch_num) # [nW*B, Mh*Mw, C] attn_windows = self.attn2(x_windows, mask=attn_mask) # [nW*B, Mh*Mw, C] attn_windows = attn_windows.view(-1, self.window_sizes[2], self.window_sizes[2], C // self.branch_num) # [nW*B, Mh, Mw, C] x2 = window_reverse(attn_windows, self.window_sizes[2], Hp, Wp) # [B, H', W', C] if pad_r > 0 or pad_b > 0: x2 = x2[:, :H, :W, :].contiguous() x2 = x2.view(B, H * W, C // self.branch_num) x = torch.cat([x0, x1, x2], -1) # FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x), H, W)) return x class BasicLayer(nn.Module): def __init__(self, dim, depth, num_heads, window_size, mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.dim = dim self.depth = depth self.window_size = window_size self.use_checkpoint = use_checkpoint self.shift_size = window_size // 2 # build blocks self.blocks = nn.ModuleList([ TransformerBlock( dim=dim, num_heads=num_heads, window_sizes=(7,4,2), mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)]) # patch merging layer if downsample is not None: self.downsample = downsample(dim=dim, norm_layer=norm_layer) else: self.downsample = None def create_mask(self, x, H, W): Hp = int(np.ceil(H / self.window_size)) * self.window_size Wp = int(np.ceil(W / self.window_size)) * self.window_size img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # [1, Hp, Wp, 1] h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition(img_mask, self.window_size) # [nW, Mh, Mw, 1] mask_windows = mask_windows.view(-1, self.window_size * self.window_size) # [nW, Mh*Mw] attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) # [nW, 1, Mh*Mw] - [nW, Mh*Mw, 1] attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) return attn_mask def forward(self, x, H, W): attn_mask = self.create_mask(x, H, W) # [nW, Mh*Mw, Mh*Mw] for blk in self.blocks: blk.H, blk.W = H, W if not torch.jit.is_scripting() and self.use_checkpoint: x = checkpoint.checkpoint(blk, x, attn_mask) else: x = blk(x, attn_mask) if self.downsample is not None: x = self.downsample(x, H, W) H, W = (H + 1) // 2, (W + 1) // 2 return x, H, W class Transformer(nn.Module): def __init__(self, patch_size=4, in_chans=3, num_classes=1000, embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), window_size=7, mlp_ratio=4., qkv_bias=True, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, norm_layer=nn.LayerNorm, patch_norm=True, use_checkpoint=False, **kwargs): super().__init__() self.num_classes = num_classes self.num_layers = len(depths) self.embed_dim = embed_dim self.patch_norm = patch_norm # stage4输出特征矩阵的channels self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) self.mlp_ratio = mlp_ratio self.patch_embed = PatchEmbed( patch_size=patch_size, in_c=in_chans, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layers = BasicLayer(dim=int(embed_dim * 2 ** i_layer), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchEmbed2 if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layers) self.norm = norm_layer(self.num_features) self.avgpool = nn.AdaptiveAvgPool1d(1) self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): nn.init.trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def forward(self, x): # x: [B, L, C] x, H, W = self.patch_embed(x) x = self.pos_drop(x) for layer in self.layers: x, H, W = layer(x, H, W) x = self.norm(x) # [B, L, C] x = self.avgpool(x.transpose(1, 2)) # [B, C, 1] x = torch.flatten(x, 1) x = self.head(x) return x def MWT(num_classes: int = 1000, **kwargs): model = Transformer(in_chans=3, patch_size=4, # window_sizes=(7,4,2), embed_dim=96, depths=(2, 4, 4, 2), num_heads=(3, 6, 12, 24), num_classes=num_classes, **kwargs) return model if __name__ == '__main__': model = MWT(num_classes=2) input = torch.randn(1, 3, 224, 224) flops, params = profile(model, inputs=(input,)) print(flops) print(params)