| |
| |
| |
| |
| |
| """ |
| ViTAE Window NoShift Model - Consolidated modular implementation |
| """ |
| from functools import partial |
| import math |
| import torch |
| import torch.nn as nn |
| import numpy as np |
|
|
| |
| from transformers.models.swin.modeling_swin import SwinDropPath as DropPath |
| from transformers import initialization as init |
| trunc_normal_ = init.trunc_normal_ |
| from timm.models.helpers import load_pretrained |
|
|
| |
| def to_2tuple(x): |
| """Convert input to 2-tuple if not already a tuple.""" |
| return x if isinstance(x, tuple) else (x, x) |
|
|
|
|
| |
| |
| |
| class SELayer(nn.Module): |
| def __init__(self, channel, reduction=16): |
| super(SELayer, self).__init__() |
| self.avg_pool = nn.AdaptiveAvgPool1d(1) |
| self.fc = nn.Sequential( |
| nn.Linear(channel, channel // reduction, bias=False), |
| nn.ReLU(inplace=True), |
| nn.Linear(channel // reduction, channel, bias=False), |
| nn.Sigmoid() |
| ) |
|
|
| def forward(self, x): |
| x = torch.transpose(x, 1, 2) |
| b, c, _ = x.size() |
| y = self.avg_pool(x).view(b, c) |
| y = self.fc(y).view(b, c, 1) |
| x = x * y.expand_as(x) |
| x = torch.transpose(x, 1, 2) |
| return x |
|
|
|
|
| |
| |
| |
| def window_partition(x, window_size): |
| """ |
| Args: |
| x: (B, H, W, C) |
| window_size (int): window size |
| Returns: |
| windows: (num_windows*B, window_size, window_size, C) |
| """ |
| 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, H, W): |
| """ |
| Args: |
| windows: (num_windows*B, window_size, window_size, C) |
| window_size (int): Window size |
| H (int): Height of image |
| W (int): Width of image |
| Returns: |
| x: (B, H, W, C) |
| """ |
| 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 WindowAttention(nn.Module): |
| r""" Window based multi-head self attention (W-MSA) module with relative position bias. |
| It supports both of shifted and non-shifted window. |
| """ |
| def __init__(self, in_dim, out_dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0., relative_pos=False): |
| super().__init__() |
| self.in_dim = in_dim |
| self.dim = out_dim |
| self.window_size = window_size |
| self.num_heads = num_heads |
| head_dim = out_dim // num_heads |
| self.scale = qk_scale or head_dim ** -0.5 |
| self.relative_pos = relative_pos |
|
|
| |
| self.relative_position_bias_table = nn.Parameter( |
| torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) |
| if self.relative_pos: |
| print('enable relative pos embedding') |
|
|
| |
| 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) |
| relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] |
| relative_coords = relative_coords.permute(1, 2, 0).contiguous() |
| relative_coords[:, :, 0] += self.window_size[0] - 1 |
| relative_coords[:, :, 1] += self.window_size[1] - 1 |
| relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 |
| relative_position_index = relative_coords.sum(-1) |
| self.register_buffer("relative_position_index", relative_position_index) |
|
|
| self.qkv = nn.Linear(in_dim, out_dim * 3, bias=qkv_bias) |
| self.attn_drop = nn.Dropout(attn_drop) |
| self.proj = nn.Linear(out_dim, out_dim) |
| self.proj_drop = nn.Dropout(proj_drop) |
|
|
| init.trunc_normal_(self.relative_position_bias_table, std=0.02) |
| self.softmax = nn.Softmax(dim=-1) |
|
|
| def forward(self, x, mask=None): |
| """ |
| Args: |
| x: input features with shape of (num_windows*B, N, C) |
| mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None |
| """ |
| B_, N, C = x.shape |
| qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) |
| q, k, v = qkv[0], qkv[1], qkv[2] |
|
|
| q = q * self.scale |
| attn = (q @ k.transpose(-2, -1)) |
|
|
| if self.relative_pos: |
| 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() |
| attn = attn + relative_position_bias.unsqueeze(0) |
|
|
| if mask is not None: |
| nW = mask.shape[0] |
| 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, -1) |
| x = self.proj(x) |
| x = self.proj_drop(x) |
| return x |
|
|
|
|
| class SwinTransformerBlock(nn.Module): |
| r""" Swin Transformer Block.""" |
| def __init__(self, in_dim, out_dim, input_resolution, num_heads, window_size=7, shift_size=0, |
| mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., |
| relative_pos=True, act_layer=nn.GELU, norm_layer=nn.LayerNorm): |
| super().__init__() |
| self.in_dim = in_dim |
| self.dim = out_dim |
| self.input_resolution = input_resolution |
| self.num_heads = num_heads |
| self.window_size = window_size |
| self.shift_size = shift_size |
| self.mlp_ratio = mlp_ratio |
| self.relative_pos = relative_pos |
| if min(self.input_resolution) <= self.window_size: |
| |
| self.shift_size = 0 |
| self.window_size = min(self.input_resolution) |
| assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" |
|
|
| self.norm1 = norm_layer(in_dim) |
| self.attn = WindowAttention( |
| in_dim=in_dim, out_dim=out_dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, |
| qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, relative_pos=relative_pos) |
|
|
| self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() |
| self.norm2 = norm_layer(out_dim) |
| mlp_hidden_dim = int(out_dim * mlp_ratio) |
| self.mlp = Mlp(in_features=out_dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) |
|
|
| if self.shift_size > 0: |
| |
| H, W = self.input_resolution |
| img_mask = torch.zeros((1, H, W, 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) |
| mask_windows = mask_windows.view(-1, self.window_size * self.window_size) |
| attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) |
| attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) |
| else: |
| attn_mask = None |
|
|
| self.register_buffer("attn_mask", attn_mask) |
|
|
| def forward(self, x): |
| H, W = self.input_resolution |
| 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) |
|
|
| |
| if self.shift_size > 0: |
| shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) |
| else: |
| shifted_x = x |
|
|
| |
| x_windows = window_partition(shifted_x, self.window_size) |
| x_windows = x_windows.view(-1, self.window_size * self.window_size, C) |
|
|
| |
| attn_windows = self.attn(x_windows, mask=self.attn_mask) |
|
|
| |
| attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) |
| shifted_x = window_reverse(attn_windows, self.window_size, H, W) |
|
|
| |
| if self.shift_size > 0: |
| x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) |
| else: |
| x = shifted_x |
| x = x.view(B, H * W, C) |
|
|
| |
| x = shortcut + self.drop_path(x) |
| x = x + self.drop_path(self.mlp(self.norm2(x))) |
|
|
| 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.hidden_features = hidden_features |
| self.fc1 = nn.Linear(in_features, hidden_features) |
| self.act = act_layer() |
| self.fc2 = nn.Linear(hidden_features, out_features) |
| self.drop = nn.Dropout(drop) |
|
|
| def forward(self, x): |
| x = self.fc1(x) |
| x = self.act(x) |
| x = self.drop(x) |
| x = self.fc2(x) |
| x = self.drop(x) |
| return x |
|
|
|
|
| class Attention(nn.Module): |
| def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): |
| super().__init__() |
| self.num_heads = num_heads |
| head_dim = dim // num_heads |
| self.scale = qk_scale or head_dim ** -0.5 |
|
|
| 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) |
|
|
| def forward(self, x): |
| 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) |
| q, k, v = qkv[0], qkv[1], qkv[2] |
|
|
| attn = (q @ k.transpose(-2, -1)) * self.scale |
| attn = attn.softmax(dim=-1) |
| 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 AttentionPerformer(nn.Module): |
| def __init__(self, dim, num_heads=1, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., kernel_ratio=0.5): |
| super().__init__() |
| self.head_dim = dim // num_heads |
| self.emb = dim |
| self.kqv = nn.Linear(dim, 3 * self.emb) |
| self.dp = nn.Dropout(proj_drop) |
| self.proj = nn.Linear(self.emb, self.emb) |
| self.head_cnt = num_heads |
| self.norm1 = nn.LayerNorm(dim, eps=1e-6) |
| self.epsilon = 1e-8 |
| self.drop_path = nn.Identity() |
|
|
| self.m = int(self.head_dim * kernel_ratio) |
| self.w = torch.randn(self.head_cnt, self.m, self.head_dim) |
| for i in range(self.head_cnt): |
| self.w[i] = nn.Parameter(nn.init.orthogonal_(self.w[i]) * math.sqrt(self.m), requires_grad=False) |
| self.w.requires_grad_(False) |
|
|
| def prm_exp(self, x): |
| |
| |
| |
| |
| |
| |
| |
| |
| xd = ((x * x).sum(dim=-1, keepdim=True)).repeat(1, 1, 1, self.m) / 2 |
| wtx = torch.einsum('bhti,hmi->bhtm', x.float(), self.w.to(x.device)) |
|
|
| return torch.exp(wtx - xd) / math.sqrt(self.m) |
|
|
| def attn(self, x): |
| B, N, C = x.shape |
| kqv = self.kqv(x).reshape(B, N, 3, self.head_cnt, self.head_dim).permute(2, 0, 3, 1, 4) |
| k, q, v = kqv[0], kqv[1], kqv[2] |
| |
| kp, qp = self.prm_exp(k), self.prm_exp(q) |
| D = torch.einsum('bhti,bhi->bht', qp, kp.sum(dim=2)).unsqueeze(dim=-1) |
| kptv = torch.einsum('bhin,bhim->bhnm', v.float(), kp) |
| y = torch.einsum('bhti,bhni->bhtn', qp, kptv) / (D.repeat(1, 1, 1, self.head_dim) + self.epsilon) |
|
|
| |
| y = y.permute(0, 2, 1, 3).reshape(B, N, self.emb) |
| y = self.dp(self.proj(y)) |
|
|
| return y |
|
|
| def forward(self, x): |
| x = self.attn(x) |
| return x |
|
|
|
|
| |
| |
| |
| class TokenTransformerAttention(nn.Module): |
| def __init__(self, dim, num_heads=8, in_dim = None, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., gamma=False, init_values=1e-4): |
| super().__init__() |
| self.num_heads = num_heads |
| self.in_dim = in_dim |
| head_dim = in_dim // num_heads |
| self.scale = qk_scale or head_dim ** -0.5 |
|
|
| self.qkv = nn.Linear(dim, in_dim * 3, bias=qkv_bias) |
| self.attn_drop = nn.Dropout(attn_drop) |
| self.proj = nn.Linear(in_dim, in_dim) |
| self.proj_drop = nn.Dropout(proj_drop) |
| if gamma: |
| self.gamma1 = nn.Parameter(init_values * torch.ones((in_dim)),requires_grad=True) |
| else: |
| self.gamma1 = 1 |
|
|
| def forward(self, x): |
| B, N, C = x.shape |
|
|
| qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.in_dim // self.num_heads).permute(2, 0, 3, 1, 4) |
| q, k, v = qkv[0], qkv[1], qkv[2] |
|
|
| |
| attn = (q @ k.transpose(-2, -1)) * self.scale |
| attn = attn.softmax(dim=-1) |
| attn = self.attn_drop(attn) |
|
|
| x = (attn @ v).transpose(1, 2).reshape(B, N, self.in_dim) |
| x = self.proj(x) |
| x = self.proj_drop(self.gamma1 * x) |
| v = v.permute(0, 2, 1, 3).view(B, N, self.in_dim).contiguous() |
| |
| x = v + x |
|
|
| return x |
|
|
|
|
| class Token_transformer(nn.Module): |
| def __init__(self, dim, in_dim, num_heads, mlp_ratio=1., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., |
| drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, gamma=False, init_values=1e-4): |
| super().__init__() |
| self.norm1 = norm_layer(dim) |
| self.attn = TokenTransformerAttention( |
| dim, in_dim=in_dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, gamma=gamma, init_values=init_values) |
| self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() |
| self.norm2 = norm_layer(in_dim) |
| self.mlp = Mlp(in_features=in_dim, hidden_features=int(in_dim*mlp_ratio), out_features=in_dim, act_layer=act_layer, drop=drop) |
|
|
| def forward(self, x): |
| x = self.attn(self.norm1(x)) |
| x = x + self.drop_path(self.mlp(self.norm2(x))) |
| return x |
|
|
|
|
| class Token_performer(nn.Module): |
| """ |
| Take Performer as T2T Transformer |
| """ |
| def __init__(self, dim, in_dim, head_cnt=1, kernel_ratio=0.5, dp1=0.1, dp2 = 0.1, gamma=False, init_values=1e-4): |
| super().__init__() |
| self.head_dim = in_dim // head_cnt |
| self.emb = in_dim |
| self.kqv = nn.Linear(dim, 3 * self.emb) |
| self.dp = nn.Dropout(dp1) |
| self.proj = nn.Linear(self.emb, self.emb) |
| self.head_cnt = head_cnt |
| self.norm1 = nn.LayerNorm(dim, eps=1e-6) |
| self.norm2 = nn.LayerNorm(self.emb, eps=1e-6) |
| self.epsilon = 1e-8 |
| self.drop_path = nn.Identity() |
|
|
| self.mlp = nn.Sequential( |
| nn.Linear(self.emb, 1 * self.emb), |
| nn.GELU(), |
| nn.Linear(1 * self.emb, self.emb), |
| nn.Dropout(dp2), |
| ) |
|
|
| self.m = int(self.head_dim * kernel_ratio) |
| self.w = torch.randn(head_cnt, self.m, self.head_dim) |
| for i in range(self.head_cnt): |
| self.w[i] = nn.Parameter(nn.init.orthogonal_(self.w[i]) * math.sqrt(self.m), requires_grad=False) |
| self.w.requires_grad_(False) |
|
|
| if gamma: |
| self.gamma1 = nn.Parameter(init_values * torch.ones((self.emb)),requires_grad=True) |
| else: |
| self.gamma1 = 1 |
|
|
| def prm_exp(self, x): |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| xd = ((x * x).sum(dim=-1, keepdim=True)).repeat(1, 1, 1, self.m) / 2 |
|
|
| |
| wtx = torch.einsum('bhti,hmi->bhtm', x.float(), self.w.to(x.device)) |
|
|
| |
|
|
| return torch.exp(wtx - xd) / math.sqrt(self.m) |
|
|
| def attn(self, x): |
| B, N, C = x.shape |
| |
| kqv = self.kqv(x).reshape(B, N, 3, self.head_cnt, self.head_dim).permute(2, 0, 3, 1, 4) |
| k, q, v = kqv[0], kqv[1], kqv[2] |
|
|
| kp, qp = self.prm_exp(k), self.prm_exp(q) |
| D = torch.einsum('bhti,bhi->bht', qp, kp.sum(dim=2)).unsqueeze(dim=-1) |
| kptv = torch.einsum('bhin,bhim->bhnm', v.float(), kp) |
| y = torch.einsum('bhti,bhni->bhtn', qp, kptv) / (D.repeat(1, 1, 1, self.head_dim) + self.epsilon) |
|
|
| |
|
|
| y = y.permute(0, 2, 1, 3).reshape(B, N, self.emb) |
| v = v.permute(0, 2, 1, 3).reshape(B, N, self.emb) |
|
|
| y = v + self.dp(self.gamma1 * self.proj(y)) |
|
|
| return y |
|
|
| def forward(self, x): |
| x = self.attn(self.norm1(x)) |
| x = x + self.mlp(self.norm2(x)) |
| return x |
|
|
|
|
| |
| |
| |
| class NormalCell(nn.Module): |
| def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., |
| drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, class_token=False, group=64, tokens_type='transformer', |
| shift_size=0, window_size=0, gamma=False, init_values=1e-4, SE=False, img_size=224, relative_pos=False): |
| super().__init__() |
| self.norm1 = norm_layer(dim) |
| self.class_token = class_token |
| self.img_size = img_size |
| self.window_size = window_size |
| if shift_size > 0 and self.img_size > self.window_size: |
| self.shift_size = shift_size |
| else: |
| self.shift_size = 0 |
| self.tokens_type = tokens_type |
| if tokens_type == 'transformer': |
| self.attn = Attention( |
| dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) |
| elif tokens_type == 'performer': |
| self.attn = AttentionPerformer( |
| dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) |
| elif tokens_type == 'swin': |
| if self.shift_size > 0: |
| |
| H, W = self.img_size, self.img_size |
| img_mask = torch.zeros((1, H, W, 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) |
| mask_windows = mask_windows.view(-1, self.window_size * self.window_size) |
| attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) |
| attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) |
| else: |
| attn_mask = None |
|
|
| self.register_buffer("attn_mask", attn_mask) |
| self.attn = WindowAttention( |
| in_dim=dim, out_dim=dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, |
| qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, relative_pos=relative_pos) |
|
|
| 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 = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) |
| self.PCM = nn.Sequential( |
| nn.Conv2d(dim, mlp_hidden_dim, 3, 1, 1, 1, group), |
| nn.BatchNorm2d(mlp_hidden_dim), |
| nn.SiLU(inplace=True), |
| nn.Conv2d(mlp_hidden_dim, dim, 3, 1, 1, 1, group), |
| nn.BatchNorm2d(dim), |
| nn.SiLU(inplace=True), |
| nn.Conv2d(dim, dim, 3, 1, 1, 1, group), |
| ) |
| if gamma: |
| self.gamma1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) |
| self.gamma2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) |
| self.gamma3 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) |
| else: |
| self.gamma1 = 1 |
| self.gamma2 = 1 |
| self.gamma3 = 1 |
| if SE: |
| self.SE = SELayer(dim) |
| else: |
| self.SE = nn.Identity() |
|
|
| def forward(self, x): |
|
|
| b, n, c = x.shape |
| shortcut = x |
| if self.tokens_type == 'swin': |
| H, W = self.img_size, self.img_size |
| assert n == self.img_size * self.img_size, "input feature has wrong size" |
| x = self.norm1(x) |
| x = x.view(b, H, W, c) |
| |
| if self.shift_size > 0: |
| shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) |
| else: |
| shifted_x = x |
| |
| x_windows = window_partition(shifted_x, self.window_size) |
| x_windows = x_windows.view(-1, self.window_size * self.window_size, c) |
| |
| attn_windows = self.attn(x_windows, mask=self.attn_mask) |
|
|
| |
| attn_windows = attn_windows.view(-1, self.window_size, self.window_size, c) |
| shifted_x = window_reverse(attn_windows, self.window_size, H, W) |
|
|
| |
| if self.shift_size > 0: |
| x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) |
| else: |
| x = shifted_x |
| x = x.view(b, H * W, c) |
| else: |
| x = self.gamma1 * self.attn(self.norm1(x)) |
|
|
| if self.class_token: |
| n = n - 1 |
| wh = int(math.sqrt(n)) |
| convX = self.drop_path(self.gamma2 * self.PCM(shortcut[:, 1:, :].view(b, wh, wh, c).permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1).contiguous().view(b, n, c)) |
| x = shortcut + self.drop_path(self.gamma1 * x) |
| x[:, 1:] = x[:, 1:] + convX |
| else: |
| wh = int(math.sqrt(n)) |
| convX = self.drop_path(self.gamma2 * self.PCM(shortcut.view(b, wh, wh, c).permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1).contiguous().view(b, n, c)) |
| x = shortcut + self.drop_path(self.gamma1 * x) + convX |
| |
| x = x + self.drop_path(self.gamma3 * self.mlp(self.norm2(x))) |
| x = self.SE(x) |
| return x |
|
|
|
|
| class PatchEmbedding(nn.Module): |
| def __init__(self, inter_channel=32, out_channels=48, img_size=None): |
| self.img_size = img_size |
| self.inter_channel = inter_channel |
| self.out_channel = out_channels |
| super().__init__() |
| self.conv1 = nn.Sequential( |
| nn.Conv2d(3, inter_channel, kernel_size=3, stride=2, padding=1, bias=False), |
| nn.BatchNorm2d(inter_channel), |
| nn.ReLU(inplace=True) |
| ) |
| self.conv2 = nn.Sequential( |
| nn.Conv2d(inter_channel, out_channels, kernel_size=3, stride=2, padding=1, bias=False), |
| nn.BatchNorm2d(out_channels), |
| nn.ReLU(inplace=True) |
| ) |
| self.conv3 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1) |
|
|
| def forward(self, x): |
| x = self.conv3(self.conv2(self.conv1(x))) |
| b, c, h, w = x.shape |
| x = x.permute(0, 2, 3, 1).reshape(b, h*w, c) |
| return x |
|
|
| def flops(self, ) -> float: |
| flops = 0 |
| flops += 3 * self.inter_channel * self.img_size[0] * self.img_size[1] // 4 * 9 |
| flops += self.img_size[0] * self.img_size[1] // 4 * self.inter_channel |
| flops += self.inter_channel * self.out_channel * self.img_size[0] * self.img_size[1] // 16 * 9 |
| flops += self.img_size[0] * self.img_size[1] // 16 * self.out_channel |
| flops += self.out_channel * self.out_channel * self.img_size[0] * self.img_size[1] // 16 |
| return flops |
|
|
|
|
| class PRM(nn.Module): |
| def __init__(self, img_size=224, kernel_size=4, downsample_ratio=4, dilations=[1,6,12], in_chans=3, embed_dim=64, share_weights=False, op='cat'): |
| super().__init__() |
| self.dilations = dilations |
| self.embed_dim = embed_dim |
| self.downsample_ratio = downsample_ratio |
| self.op = op |
| self.kernel_size = kernel_size |
| self.stride = downsample_ratio |
| self.share_weights = share_weights |
| self.outSize = img_size // downsample_ratio |
|
|
| if share_weights: |
| self.convolution = nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ |
| stride=self.stride, padding=3*dilations[0]//2, dilation=dilations[0]) |
|
|
| else: |
| self.convs = nn.ModuleList() |
| for dilation in self.dilations: |
| padding = math.ceil(((self.kernel_size-1)*dilation + 1 - self.stride) / 2) |
| self.convs.append(nn.Sequential(*[nn.Conv2d(in_channels=in_chans, out_channels=embed_dim, kernel_size=self.kernel_size, \ |
| stride=self.stride, padding=padding, dilation=dilation), |
| nn.GELU()])) |
|
|
| if self.op == 'sum': |
| self.out_chans = embed_dim |
| elif op == 'cat': |
| self.out_chans = embed_dim * len(self.dilations) |
|
|
| def forward(self, x): |
| B, C, W, H = x.shape |
| if self.share_weights: |
| padding = math.ceil(((self.kernel_size-1)*self.dilations[0] + 1 - self.stride) / 2) |
| y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ |
| stride=self.downsample_ratio, padding=padding, dilation=self.dilations[0]).unsqueeze(dim=-1) |
| for i in range(1, len(self.dilations)): |
| padding = math.ceil(((self.kernel_size-1)*self.dilations[i] + 1 - self.stride) / 2) |
| _y = nn.functional.conv2d(x, weight=self.convolution.weight, bias=self.convolution.bias, \ |
| stride=self.downsample_ratio, padding=padding, dilation=self.dilations[i]).unsqueeze(dim=-1) |
| y = torch.cat((y, _y), dim=-1) |
| else: |
| y = self.convs[0](x).unsqueeze(dim=-1) |
| for i in range(1, len(self.dilations)): |
| _y = self.convs[i](x).unsqueeze(dim=-1) |
| y = torch.cat((y, _y), dim=-1) |
| B, C, W, H, N = y.shape |
| if self.op == 'sum': |
| y = y.sum(dim=-1).flatten(2).permute(0,2,1).contiguous() |
| elif self.op == 'cat': |
| y = y.permute(0,4,1,2,3).flatten(3).reshape(B, N*C, W*H).permute(0,2,1).contiguous() |
| else: |
| raise NotImplementedError('no such operation: {} for multi-levels!'.format(self.op)) |
| return y, (W, H) |
|
|
|
|
| class ReductionCell(nn.Module): |
| def __init__(self, img_size=224, in_chans=3, embed_dims=64, token_dims=64, downsample_ratios=4, kernel_size=7, |
| num_heads=1, dilations=[1,2,3,4], share_weights=False, op='cat', tokens_type='performer', group=1, |
| relative_pos=False, drop=0., attn_drop=0., drop_path=0., mlp_ratio=1.0, gamma=False, init_values=1e-4, SE=False, window_size=7): |
| super().__init__() |
|
|
| self.img_size = img_size |
| self.window_size = window_size |
| self.op = op |
| self.dilations = dilations |
| self.num_heads = num_heads |
| self.embed_dims = embed_dims |
| self.token_dims = token_dims |
| self.in_chans = in_chans |
| self.downsample_ratios = downsample_ratios |
| self.kernel_size = kernel_size |
| self.outSize = img_size |
| self.relative_pos = relative_pos |
| PCMStride = [] |
| residual = downsample_ratios // 2 |
| for _ in range(3): |
| PCMStride.append((residual > 0) + 1) |
| residual = residual // 2 |
| assert residual == 0 |
| self.pool = None |
| self.tokens_type = tokens_type |
| if tokens_type == 'pooling': |
| PCMStride = [1, 1, 1] |
| self.pool = nn.MaxPool2d(downsample_ratios, stride=downsample_ratios, padding=0) |
| tokens_type = 'transformer' |
| self.outSize = self.outSize // downsample_ratios |
| downsample_ratios = 1 |
| self.PCM = nn.Sequential( |
| nn.Conv2d(in_chans, embed_dims, kernel_size=(3, 3), stride=PCMStride[0], padding=(1, 1), groups=group), |
| nn.BatchNorm2d(embed_dims), |
| nn.SiLU(inplace=True), |
| nn.Conv2d(embed_dims, embed_dims, kernel_size=(3, 3), stride=PCMStride[1], padding=(1, 1), groups=group), |
| nn.BatchNorm2d(embed_dims), |
| nn.SiLU(inplace=True), |
| nn.Conv2d(embed_dims, token_dims, kernel_size=(3, 3), stride=PCMStride[2], padding=(1, 1), groups=group), |
| ) |
| self.PRM = PRM(img_size=img_size, kernel_size=kernel_size, downsample_ratio=downsample_ratios, dilations=self.dilations, |
| in_chans=in_chans, embed_dim=embed_dims, share_weights=share_weights, op=op) |
| self.outSize = self.outSize // downsample_ratios |
|
|
| in_chans = self.PRM.out_chans |
| if tokens_type == 'performer': |
| |
| self.attn = Token_performer(dim=in_chans, in_dim=token_dims, head_cnt=num_heads, kernel_ratio=0.5, gamma=gamma, init_values=init_values) |
| elif tokens_type == 'performer_less': |
| self.attn = None |
| self.PCM = None |
| elif tokens_type == 'transformer': |
| self.attn = Token_transformer(dim=in_chans, in_dim=token_dims, num_heads=num_heads, mlp_ratio=mlp_ratio, drop=drop, |
| attn_drop=attn_drop, drop_path=drop_path, gamma=gamma, init_values=init_values) |
| elif tokens_type == 'swin': |
| self.attn = SwinTransformerBlock(in_dim=in_chans, out_dim=token_dims, input_resolution=(self.img_size//self.downsample_ratios, self.img_size//self.downsample_ratios), |
| num_heads=num_heads, mlp_ratio=mlp_ratio, drop=drop, |
| attn_drop=attn_drop, drop_path=drop_path, window_size=window_size, shift_size=0, relative_pos=relative_pos) |
|
|
| if gamma: |
| self.gamma2 = nn.Parameter(init_values * torch.ones((token_dims)),requires_grad=True) |
| self.gamma3 = nn.Parameter(init_values * torch.ones((token_dims)),requires_grad=True) |
| else: |
| self.gamma2 = 1 |
| self.gamma3 = 1 |
|
|
| if SE: |
| self.SE = SELayer(token_dims) |
| else: |
| self.SE = nn.Identity() |
|
|
| self.num_patches = (img_size // 2) * (img_size // 2) |
|
|
| def forward(self, x): |
| if len(x.shape) < 4: |
| |
| B, N, C = x.shape |
| n = int(np.sqrt(N)) |
| x = x.view(B, n, n, C).contiguous() |
| x = x.permute(0, 3, 1, 2) |
| if self.pool is not None: |
| x = self.pool(x) |
| shortcut = x |
| PRM_x, _ = self.PRM(x) |
| if self.tokens_type == 'swin': |
| pass |
| B, N, C = PRM_x.shape |
| H, W = self.img_size // self.downsample_ratios, self.img_size // self.downsample_ratios |
| b, _, c = PRM_x.shape |
| assert N == H*W |
| x = self.attn.norm1(PRM_x) |
| x = x.view(B, H, W, C) |
| x_windows = window_partition(x, self.window_size) |
| x_windows = x_windows.view(-1, self.window_size * self.window_size, C) |
| attn_windows = self.attn.attn(x_windows, mask=self.attn.attn_mask) |
| attn_windows = attn_windows.view(-1, self.window_size, self.window_size, self.token_dims) |
| shifted_x = window_reverse(attn_windows, self.window_size, H, W) |
| x = shifted_x |
| x = x.view(B, H * W, self.token_dims) |
|
|
| convX = self.PCM(shortcut) |
| |
| convX = convX.permute(0, 2, 3, 1).view(*x.shape).contiguous() |
| x = x + self.attn.drop_path(convX * self.gamma2) |
| |
| |
| x = x + self.attn.drop_path(self.gamma3 * self.attn.mlp(self.attn.norm2(x))) |
| else: |
| if self.attn is None: |
| return PRM_x |
| convX = self.PCM(shortcut) |
| x = self.attn.attn(self.attn.norm1(PRM_x)) |
| convX = convX.permute(0, 2, 3, 1).view(*x.shape).contiguous() |
| x = x + self.attn.drop_path(convX * self.gamma2) |
| x = x + self.attn.drop_path(self.gamma3 * self.attn.mlp(self.attn.norm2(x))) |
| x = self.SE(x) |
|
|
| return x |
|
|
|
|
| class BasicLayer(nn.Module): |
| def __init__(self, img_size=224, in_chans=3, embed_dims=64, token_dims=64, downsample_ratios=4, kernel_size=7, RC_heads=1, NC_heads=6, dilations=[1, 2, 3, 4], |
| RC_op='cat', RC_tokens_type='performer', NC_tokens_type='transformer', RC_group=1, NC_group=64, NC_depth=2, dpr=0.1, mlp_ratio=4., qkv_bias=True, |
| qk_scale=None, drop=0, attn_drop=0., norm_layer=nn.LayerNorm, class_token=False, gamma=False, init_values=1e-4, SE=False, window_size=7, relative_pos=False): |
| super().__init__() |
| self.img_size = img_size |
| self.in_chans = in_chans |
| self.embed_dims = embed_dims |
| self.token_dims = token_dims |
| self.downsample_ratios = downsample_ratios |
| self.out_size = self.img_size // self.downsample_ratios |
| self.RC_kernel_size = kernel_size |
| self.RC_heads = RC_heads |
| self.NC_heads = NC_heads |
| self.dilations = dilations |
| self.RC_op = RC_op |
| self.RC_tokens_type = RC_tokens_type |
| self.RC_group = RC_group |
| self.NC_group = NC_group |
| self.NC_depth = NC_depth |
| self.relative_pos = relative_pos |
| if RC_tokens_type == 'stem': |
| self.RC = PatchEmbedding(inter_channel=token_dims//2, out_channels=token_dims, img_size=img_size) |
| elif downsample_ratios > 1: |
| self.RC = ReductionCell(img_size, in_chans, embed_dims, token_dims, downsample_ratios, kernel_size, |
| RC_heads, dilations, op=RC_op, tokens_type=RC_tokens_type, group=RC_group, gamma=gamma, init_values=init_values, SE=SE, relative_pos=relative_pos, window_size=window_size) |
| else: |
| self.RC = nn.Identity() |
| self.NC = nn.ModuleList([ |
| NormalCell(token_dims, NC_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, |
| drop_path=dpr[i] if isinstance(dpr, list) else dpr, norm_layer=norm_layer, class_token=class_token, group=NC_group, tokens_type=NC_tokens_type, |
| gamma=gamma, init_values=init_values, SE=SE, img_size=img_size // downsample_ratios, window_size=window_size, shift_size=0, relative_pos=relative_pos) |
| for i in range(NC_depth)]) |
|
|
| def forward(self, x): |
| x = self.RC(x) |
| for nc in self.NC: |
| x = nc(x) |
| return x |
|
|
|
|
| |
| |
| |
| class ViTAE_Window_NoShift_basic(nn.Module): |
| def __init__(self, img_size=224, in_chans=3, stages=4, embed_dims=64, token_dims=64, downsample_ratios=[4, 2, 2, 2], kernel_size=[7, 3, 3, 3], |
| RC_heads=[1, 1, 1, 1], NC_heads=4, dilations=[[1, 2, 3, 4], [1, 2, 3], [1, 2], [1, 2]], |
| RC_op='cat', RC_tokens_type=['performer', 'transformer', 'transformer', 'transformer'], NC_tokens_type='transformer', |
| RC_group=[1, 1, 1, 1], NC_group=[1, 32, 64, 64], NC_depth=[2, 2, 6, 2], mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., |
| attn_drop_rate=0., drop_path_rate=0., norm_layer=partial(nn.LayerNorm, eps=1e-6), num_classes=1000, |
| gamma=False, init_values=1e-4, SE=False, window_size=7, relative_pos=False): |
| super().__init__() |
| self.num_classes = num_classes |
| self.stages = stages |
| repeatOrNot = (lambda x, y, z=list: x if isinstance(x, z) else [x for _ in range(y)]) |
| self.embed_dims = repeatOrNot(embed_dims, stages) |
| self.tokens_dims = token_dims if isinstance(token_dims, list) else [token_dims * (2 ** i) for i in range(stages)] |
| self.downsample_ratios = repeatOrNot(downsample_ratios, stages) |
| self.kernel_size = repeatOrNot(kernel_size, stages) |
| self.RC_heads = repeatOrNot(RC_heads, stages) |
| self.NC_heads = repeatOrNot(NC_heads, stages) |
| self.dilaions = repeatOrNot(dilations, stages) |
| self.RC_op = repeatOrNot(RC_op, stages) |
| self.RC_tokens_type = repeatOrNot(RC_tokens_type, stages) |
| self.NC_tokens_type = repeatOrNot(NC_tokens_type, stages) |
| self.RC_group = repeatOrNot(RC_group, stages) |
| self.NC_group = repeatOrNot(NC_group, stages) |
| self.NC_depth = repeatOrNot(NC_depth, stages) |
| self.mlp_ratio = repeatOrNot(mlp_ratio, stages) |
| self.qkv_bias = repeatOrNot(qkv_bias, stages) |
| self.qk_scale = repeatOrNot(qk_scale, stages) |
| self.drop = repeatOrNot(drop_rate, stages) |
| self.attn_drop = repeatOrNot(attn_drop_rate, stages) |
| self.norm_layer = repeatOrNot(norm_layer, stages) |
| self.relative_pos = relative_pos |
|
|
| self.pos_drop = nn.Dropout(p=drop_rate) |
| depth = np.sum(self.NC_depth) |
| dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] |
| Layers = [] |
| for i in range(stages): |
| startDpr = 0 if i==0 else self.NC_depth[i - 1] |
| Layers.append( |
| BasicLayer(img_size, in_chans, self.embed_dims[i], self.tokens_dims[i], self.downsample_ratios[i], |
| self.kernel_size[i], self.RC_heads[i], self.NC_heads[i], self.dilaions[i], self.RC_op[i], |
| self.RC_tokens_type[i], self.NC_tokens_type[i], self.RC_group[i], self.NC_group[i], self.NC_depth[i], dpr[startDpr:self.NC_depth[i]+startDpr], |
| mlp_ratio=self.mlp_ratio[i], qkv_bias=self.qkv_bias[i], qk_scale=self.qk_scale[i], drop=self.drop[i], attn_drop=self.attn_drop[i], |
| norm_layer=self.norm_layer[i], gamma=gamma, init_values=init_values, SE=SE, window_size=window_size, relative_pos=relative_pos) |
| ) |
| img_size = img_size // self.downsample_ratios[i] |
| in_chans = self.tokens_dims[i] |
| self.layers = nn.ModuleList(Layers) |
|
|
| |
| self.head = nn.Linear(self.tokens_dims[-1], num_classes) if num_classes > 0 else nn.Identity() |
|
|
| self.apply(self._init_weights) |
|
|
| def _init_weights(self, m): |
| if isinstance(m, nn.Linear): |
| init.trunc_normal_(m.weight, std=0.02) |
| if isinstance(m, nn.Linear) and m.bias is not None: |
| init.constant_(m.bias, 0) |
| elif isinstance(m, nn.LayerNorm): |
| init.constant_(m.bias, 0) |
| init.constant_(m.weight, 1.0) |
|
|
| @torch.jit.ignore |
| def no_weight_decay(self): |
| return {'cls_token'} |
|
|
| def get_classifier(self): |
| return self.head |
|
|
| def reset_classifier(self, num_classes): |
| self.num_classes = num_classes |
| self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() |
|
|
| def forward_features(self, x): |
|
|
| for layer in self.layers: |
| x = layer(x) |
|
|
| return torch.mean(x, 1) |
|
|
| def forward(self, x): |
| x = self.forward_features(x) |
| x = self.head(x) |
| return x |
| |
| def train(self, mode=True, tag='default'): |
| self.training = mode |
| if tag == 'default': |
| for module in self.modules(): |
| if module.__class__.__name__ != 'ViTAE_Window_NoShift_basic': |
| module.train(mode) |
| elif tag == 'linear': |
| for module in self.modules(): |
| if module.__class__.__name__ != 'ViTAE_Window_NoShift_basic': |
| module.eval() |
| for param in module.parameters(): |
| param.requires_grad = False |
| elif tag == 'linearLNBN': |
| for module in self.modules(): |
| if module.__class__.__name__ != 'ViTAE_Window_NoShift_basic': |
| if isinstance(module, nn.LayerNorm) or isinstance(module, nn.BatchNorm2d): |
| module.train(mode) |
| for param in module.parameters(): |
| param.requires_grad = True |
| else: |
| module.eval() |
| for param in module.parameters(): |
| param.requires_grad = False |
| self.head.train(mode) |
| for param in self.head.parameters(): |
| param.requires_grad = True |
| return self |
|
|
|
|
| |
| |
| |
| def _cfg(url='', **kwargs): |
| return { |
| 'url': url, |
| 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, |
| 'crop_pct': .9, 'interpolation': 'bicubic', |
| 'mean': (0.485, 0.456, 0.406), 'std': (0.229, 0.224, 0.225), |
| 'classifier': 'head', |
| **kwargs |
| } |
|
|
| default_cfgs = { |
| 'ViTAE_stages3_7': _cfg(), |
| } |
|
|
| |
| def ViTAE_Window_NoShift_12_basic_stages4_14(pretrained=False, **kwargs): |
| |
| |
| model = ViTAE_Window_NoShift_basic(RC_tokens_type=['swin', 'swin', 'transformer', 'transformer'], NC_tokens_type=['swin', 'swin', 'transformer', 'transformer'], stages=4, embed_dims=[64, 64, 128, 256], token_dims=[64, 128, 256, 512], downsample_ratios=[4, 2, 2, 2], |
| NC_depth=[2, 2, 8, 2], NC_heads=[1, 2, 4, 8], RC_heads=[1, 1, 2, 4], mlp_ratio=4., NC_group=[1, 32, 64, 128], RC_group=[1, 16, 32, 64], **kwargs) |
| model.default_cfg = default_cfgs['ViTAE_stages3_7'] |
| if pretrained: |
| load_pretrained( |
| model, num_classes=model.num_classes, in_chans=kwargs.get('in_chans', 3)) |
| return model |
|
|