import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import timm class ConvBNReLU(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, norm_layer=nn.BatchNorm2d, bias=False): super(ConvBNReLU, self).__init__( nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2), norm_layer(out_channels), nn.ReLU6() ) class ConvBN(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, norm_layer=nn.BatchNorm2d, bias=False): super(ConvBN, self).__init__( nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2), norm_layer(out_channels) ) class Conv(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, bias=False): super(Conv, self).__init__( nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2) ) class SelfAttention(nn.Module): def __init__(self, dim, num_heads): super(SelfAttention, self).__init__() self.num_heads = num_heads head_dim = dim // self.num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, 3 * dim) self.o_proj = nn.Linear(dim, dim) def forward(self, x): B, C, H, W = x.shape qkv = self.qkv(x).view(B, -1, self.num_heads, 3, H * W).permute(3, 0, 2, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] dots = torch.matmul(q.transpose(-2, -1), k) * self.scale attn = dots.softmax(dim=-1) out = torch.matmul(attn, v).transpose(1, 2).reshape(B, C, H, W) return self.o_proj(out) class SeparableConvBNReLU(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, norm_layer=nn.BatchNorm2d): super(SeparableConvBNReLU, self).__init__( nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, groups=in_channels, bias=False), norm_layer(out_channels), nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.ReLU6() ) class SeparableConvBN(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, norm_layer=nn.BatchNorm2d): super(SeparableConvBN, self).__init__( nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, groups=in_channels, bias=False), norm_layer(out_channels), nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) ) class SeparableConv(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1): super(SeparableConv, self).__init__( nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, groups=in_channels, bias=False), nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) ) # class SEBlock(nn.Module): # def __init__(self, in_channels, reduction=16): # super(SEBlock, self).__init__() # self.avg_pool = nn.AdaptiveAvgPool2d(1) # self.fc = nn.Sequential( # nn.Linear(in_channels, in_channels // reduction, bias=False), # nn.ReLU(inplace=True), # nn.Linear(in_channels // reduction, in_channels, bias=False), # nn.Sigmoid() # ) # # def forward(self, x): # b, c, _, _ = x.size() # y = self.avg_pool(x).view(b, c) # y = self.fc(y).view(b, c, 1, 1) # return x * y.expand_as(x) class SEResidualBlock(nn.Module): def __init__(self, in_channels, reduction=16): super(SEResidualBlock, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(in_channels // reduction, in_channels, bias=False), nn.Sigmoid() ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) y = x * y.expand_as(x) return x + y # 这里添加残差连接 class ImprovedLocalAttention(nn.Module): def __init__(self, dim): super(ImprovedLocalAttention, self).__init__() self.conv1x1 = nn.Conv2d(dim, dim, kernel_size=1, bias=False) self.conv3x3 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False) self.conv5x5 = nn.Conv2d(dim, dim, kernel_size=5, padding=2, bias=False) self.bn = nn.BatchNorm2d(dim) self.se = SEResidualBlock(dim) def forward(self, x): out1 = self.conv1x1(x) out2 = self.conv3x3(x) out3 = self.conv5x5(x) out = out1 + out2 + out3 out = self.bn(out) out = self.se(out) return out class GlobalLocalAttention(nn.Module): def __init__(self, dim=256, num_heads=16, qkv_bias=False, window_size=8, relative_pos_embedding=True): super().__init__() self.num_heads = num_heads head_dim = dim // self.num_heads self.scale = head_dim ** -0.5 self.ws = window_size self.qkv = Conv(dim, 3*dim, kernel_size=1, bias=qkv_bias) # self.local1 = ImprovedLocalAttention(dim) self.local1 = ImprovedLocalAttention(dim) self.proj = SeparableConvBN(dim, dim, kernel_size=window_size) self.attn_x = nn.AvgPool2d(kernel_size=(window_size, 1), stride=1, padding=(window_size//2 - 1, 0)) self.attn_y = nn.AvgPool2d(kernel_size=(1, window_size), stride=1, padding=(0, window_size//2 - 1)) self.relative_pos_embedding = relative_pos_embedding if self.relative_pos_embedding: self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size - 1) * (2 * window_size - 1), num_heads)) coords_h = torch.arange(self.ws) coords_w = torch.arange(self.ws) 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.ws - 1 relative_coords[:, :, 1] += self.ws - 1 relative_coords[:, :, 0] *= 2 * self.ws - 1 relative_position_index = relative_coords.sum(-1) self.register_buffer("relative_position_index", relative_position_index) trunc_normal_(self.relative_position_bias_table, std=.02) def pad(self, x, ps): _, _, H, W = x.size() if W % ps != 0: x = F.pad(x, (0, ps - W % ps), mode='reflect') if H % ps != 0: x = F.pad(x, (0, 0, 0, ps - H % ps), mode='reflect') return x def pad_out(self, x): x = F.pad(x, pad=(0, 1, 0, 1), mode='reflect') return x def forward(self, x): B, C, H, W = x.shape # local = self.local2(x) + self.local1(x) local = self.local1(x) x = self.pad(x, self.ws) B, C, Hp, Wp = x.shape qkv = self.qkv(x) q, k, v = rearrange(qkv, 'b (qkv h d) (hh ws1) (ww ws2) -> qkv (b hh ww) h (ws1 ws2) d', h=self.num_heads, d=C//self.num_heads, hh=Hp//self.ws, ww=Wp//self.ws, qkv=3, ws1=self.ws, ws2=self.ws) dots = (q @ k.transpose(-2, -1)) * self.scale if self.relative_pos_embedding: relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.ws * self.ws, self.ws * self.ws, -1) relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() dots += relative_position_bias.unsqueeze(0) attn = dots.softmax(dim=-1) attn = attn @ v attn = rearrange(attn, '(b hh ww) h (ws1 ws2) d -> b (h d) (hh ws1) (ww ws2)', h=self.num_heads, d=C//self.num_heads, hh=Hp//self.ws, ww=Wp//self.ws, ws1=self.ws, ws2=self.ws) attn = attn[:, :, :H, :W] out = self.attn_x(F.pad(attn, pad=(0, 0, 0, 1), mode='reflect')) + \ self.attn_y(F.pad(attn, pad=(0, 1, 0, 0), mode='reflect')) out = out + local out = self.pad_out(out) out = self.proj(out) out = out[:, :, :H, :W] return out gl_attention = GlobalLocalAttention(dim=256, num_heads=16, qkv_bias=False, window_size=8, relative_pos_embedding=True) x = torch.randn(1, 256, 64, 64) output = gl_attention(x) print(output.shape)