import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import once_differentiable from lib.extensions.cc_attention import _ext # from . import _ext # from libs import InPlaceABN, InPlaceABNSync # BatchNorm2d = functools.partial(InPlaceABNSync, activation='none') def _check_contiguous(*args): if not all([mod is None or mod.is_contiguous() for mod in args]): raise ValueError("Non-contiguous input") class CA_Weight(autograd.Function): @staticmethod def forward(ctx, t, f): # Save context n, c, h, w = t.size() size = (n, h+w-1, h, w) weight = torch.zeros(size, dtype=t.dtype, layout=t.layout, device=t.device) _ext.ca_forward_cuda(t, f, weight) # Output ctx.save_for_backward(t, f) return weight @staticmethod @once_differentiable def backward(ctx, dw): t, f = ctx.saved_tensors dt = torch.zeros_like(t) df = torch.zeros_like(f) _ext.ca_backward_cuda(dw.contiguous(), t, f, dt, df) _check_contiguous(dt, df) return dt, df class CA_Map(autograd.Function): @staticmethod def forward(ctx, weight, g): # Save context out = torch.zeros_like(g) _ext.ca_map_forward_cuda(weight, g, out) # Output ctx.save_for_backward(weight, g) return out @staticmethod @once_differentiable def backward(ctx, dout): weight, g = ctx.saved_tensors dw = torch.zeros_like(weight) dg = torch.zeros_like(g) _ext.ca_map_backward_cuda(dout.contiguous(), weight, g, dw, dg) _check_contiguous(dw, dg) return dw, dg ca_weight = CA_Weight.apply ca_map = CA_Map.apply class CrossAttention(nn.Module): def __init__(self, dim_in, dim_inner, dim_out): super(CrossAttention, self).__init__() self.t_func = nn.Conv2d(in_channels=dim_in, out_channels=dim_inner, kernel_size=1, stride=1, padding=0) self.f_func = nn.Conv2d(in_channels=dim_in, out_channels=dim_inner, kernel_size=1, stride=1, padding=0) self.g_func = nn.Conv2d(in_channels=dim_in, out_channels=dim_out, kernel_size=1, stride=1, padding=0) self.inc = nn.Conv2d(in_channels=dim_out, out_channels=dim_in, kernel_size=1, stride=1, padding=0) nn.init.constant_(self.inc.weight, 0) nn.init.constant_(self.inc.bias, 0) def forward(self, x): t = self.t_func(x) f = self.f_func(x) g = self.g_func(x) w = ca_weight(t, f) w = F.softmax(w, 1) out = ca_map(w, g) x = x + self.inc(out) return x class CrissCrossAttention(nn.Module): """ Pixel-wise attention module""" def __init__(self,in_dim): super(CrissCrossAttention,self).__init__() self.chanel_in = in_dim self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= 1) self.key_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//8 , kernel_size= 1) self.value_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim , kernel_size= 1) self.gamma = nn.Parameter(torch.zeros(1)) def forward(self,x): proj_query = self.query_conv(x) proj_key = self.key_conv(x) proj_value = self.value_conv(x) energy = ca_weight(proj_query, proj_key) attention = F.softmax(energy, 1) out = ca_map(attention, proj_value) out = self.gamma*out + x return out class PAM_Module(nn.Module): """ Position attention module""" #Ref from SAGAN def __init__(self, in_dim): super(PAM_Module, self).__init__() self.chanel_in = in_dim self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1) self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1) self.gamma = nn.Parameter(torch.zeros(1)) def forward(self, x): """ inputs : x : input feature maps( B X C X H X W) returns : out : attention value + input feature attention: B X (HxW) X (HxW) """ m_batchsize, C, height, width = x.size() proj_query = self.query_conv(x).view(m_batchsize, -1, width*height).permute(0, 2, 1) proj_key = self.key_conv(x).view(m_batchsize, -1, width*height) energy = torch.bmm(proj_query, proj_key) attention = F.softmax(energy, 1) proj_value = self.value_conv(x).view(m_batchsize, -1, width*height) out = torch.bmm(proj_value, attention.permute(0, 2, 1)) out = out.view(m_batchsize, C, height, width) out = self.gamma*out + x return out __all__ = ["PAM_Module", "CrissCrossAttention", "CrossAttention", "ca_weight", "ca_map"]