Tan_pytorch_segmentation/pytorch_segmentation/PV_Model/Agent-Attention.py

247 lines
11 KiB
Python
Raw Normal View History

2025-05-19 20:48:24 +08:00
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
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from torch.nn.init import trunc_normal_
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 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 = SEBlock(dim)
def forward(self, x):
# Applying different convolutions and combining results
out1 = self.conv1x1(x)
out2 = self.conv3x3(x)
out3 = self.conv5x5(x)
out = out1 + out2 + out3
out = self.bn(out)
out = self.se(out)
out = out + out1 + out3
return out
class AgentAttention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.,
agent_num=49, window=14, **kwargs):
super().__init__()
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = 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)
self.softmax = nn.Softmax(dim=-1)
self.agent_num = agent_num
self.window = window
self.dwc = nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=(3, 3),
padding=1, groups=dim)
self.an_bias = nn.Parameter(torch.zeros(num_heads, agent_num, 7, 7))
self.na_bias = nn.Parameter(torch.zeros(num_heads, agent_num, 7, 7))
self.ah_bias = nn.Parameter(torch.zeros(1, num_heads, agent_num, window, 1))
self.aw_bias = nn.Parameter(torch.zeros(1, num_heads, agent_num, 1, window))
self.ha_bias = nn.Parameter(torch.zeros(1, num_heads, window, 1, agent_num))
self.wa_bias = nn.Parameter(torch.zeros(1, num_heads, 1, window, agent_num))
self.ac_bias = nn.Parameter(torch.zeros(1, num_heads, agent_num, 1))
self.ca_bias = nn.Parameter(torch.zeros(1, num_heads, 1, agent_num))
trunc_normal_(self.an_bias, std=.02)
trunc_normal_(self.na_bias, std=.02)
trunc_normal_(self.ah_bias, std=.02)
trunc_normal_(self.aw_bias, std=.02)
trunc_normal_(self.ha_bias, std=.02)
trunc_normal_(self.wa_bias, std=.02)
trunc_normal_(self.ac_bias, std=.02)
trunc_normal_(self.ca_bias, std=.02)
pool_size = int(agent_num ** 0.5)
self.pool = nn.AdaptiveAvgPool2d(output_size=(pool_size, pool_size))
def forward(self, x):
b, n, c = x.shape
h = int(n ** 0.5)
w = int(n ** 0.5)
if h * w != n:
raise ValueError("Input feature map size must be a square.")
num_heads = self.num_heads
head_dim = c // num_heads
qkv = self.qkv(x).reshape(b, n, 3, c).permute(2, 0, 1, 3)
q, k, v = qkv[0], qkv[1], qkv[2]
agent_tokens = self.pool(q.reshape(b, h, w, c).permute(0, 3, 1, 2)).reshape(b, c, -1).permute(0, 2, 1)
q = q.reshape(b, n, num_heads, head_dim).permute(0, 2, 1, 3)
k = k.reshape(b, n, num_heads, head_dim).permute(0, 2, 1, 3)
v = v.reshape(b, n, num_heads, head_dim).permute(0, 2, 1, 3)
agent_tokens = agent_tokens.reshape(b, self.agent_num, num_heads, head_dim).permute(0, 2, 1, 3)
# Adjust position_bias shape to match the shape of (agent_tokens * self.scale) @ k.transpose(-2, -1)
position_bias1 = nn.functional.interpolate(self.an_bias, size=(self.window, self.window), mode='bilinear')
position_bias1 = position_bias1.reshape(1, num_heads, self.agent_num, -1).repeat(b, 1, 1, 1)
position_bias2 = (self.ah_bias + self.aw_bias).reshape(1, num_heads, self.agent_num, -1).repeat(b, 1, 1, 1)
position_bias = position_bias1 + position_bias2
position_bias = torch.cat([self.ac_bias.repeat(b, 1, 1, 1), position_bias], dim=-1)
k_transposed = k.transpose(-2, -1)
k_transposed = k_transposed.reshape(b, num_heads, n, head_dim) # Ensure shape compatibility
agent_attn = self.softmax((agent_tokens * self.scale) @ k_transposed + position_bias)
agent_attn = self.attn_drop(agent_attn)
agent_v = agent_attn @ v
agent_bias1 = nn.functional.interpolate(self.na_bias, size=(self.window, self.window), mode='bilinear')
agent_bias1 = agent_bias1.reshape(1, num_heads, self.agent_num, -1).permute(0, 1, 3, 2).repeat(b, 1, 1, 1)
agent_bias2 = (self.ha_bias + self.wa_bias).reshape(1, num_heads, -1, self.agent_num).repeat(b, 1, 1, 1)
agent_bias = agent_bias1 + agent_bias2
agent_bias = torch.cat([self.ca_bias.repeat(b, 1, 1, 1), agent_bias], dim=-2)
agent_tokens_transposed = agent_tokens.transpose(-2, -1)
agent_tokens_transposed = agent_tokens_transposed.reshape(b, num_heads, head_dim, self.agent_num) # Ensure shape compatibility
q_attn = self.softmax((q * self.scale) @ agent_tokens_transposed + agent_bias)
q_attn = self.attn_drop(q_attn)
x = q_attn @ agent_v
x = x.transpose(1, 2).reshape(b, n, c)
v_ = v[:, :, 1:, :].transpose(1, 2).reshape(b, h, w, c).permute(0, 3, 1, 2)
x[:, 1:, :] = x[:, 1:, :] + self.dwc(v_).permute(0, 2, 3, 1).reshape(b, n - 1, c)
x = self.proj(x)
x = self.proj_drop(x)
return x
class GlobalLocalAttention(nn.Module):
def __init__(self, dim=256, num_heads=16, qkv_bias=False, window_size=8, relative_pos_embedding=True, agent_num=49, window=14):
super(GlobalLocalAttention, self).__init__()
self.local1 = ImprovedLocalAttention(dim)
self.global_attention = AgentAttention(dim, num_heads, qkv_bias, window_size=window_size, agent_num=agent_num, window=window)
def forward(self, x):
B, C, H, W = x.shape
x_flat = x.view(B, H * W, C) # reshape to (B, N, C)
local = self.local1(x)
global_attn = self.global_attention(x_flat)
global_attn = global_attn.view(B, H, W, C).permute(0, 3, 1, 2) # reshape back to (B, C, H, W)
return local + global_attn
# Testing the model with a random tensor
gl_attention = GlobalLocalAttention(dim=256, num_heads=16, qkv_bias=False, window_size=8, relative_pos_embedding=True, agent_num=49, window=14)
x = torch.randn(1, 256, 64, 64)
output = gl_attention(x)
print(output.shape) # Output should be (1, 256, 64, 64)