import torch
import torch.nn.functional as F
import torch.nn as nn
bn=nn.BatchNorm2d
BIAS=False
class Linear(nn.Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`

    This module supports :ref:`TensorFloat32<tf32_on_ampere>`.

    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``

    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.

    Attributes:
        weight: the learnable weights of the module of shape
            :math:`(\text{out\_features}, \text{in\_features})`. The values are
            initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
            :math:`k = \frac{1}{\text{in\_features}}`
        bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                If :attr:`bias` is ``True``, the values are initialized from
                :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                :math:`k = \frac{1}{\text{in\_features}}`

    Examples::

        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
    """
    __constants__ = ['in_features', 'out_features']
    in_features: int
    out_features: int
    weight: torch.Tensor

    def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = nn.Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        #self.bn=nn.BatchNorm1d(in_features,affine=False)
        self.reset_parameters()

    def reset_parameters(self) -> None:
        import math
        nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            nn.init.uniform_(self.bias, -bound, bound)

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        #if self.training:
        #    input=self.bn(input)+torch.mean(input,0,keepdim=True)
        #else:
        #    input=self.bn(input)+self.bn.running_mean
        return F.linear(input, torch.sigmoid(self.weight), self.bias)

    def extra_repr(self) -> str:
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )

def decorrelated_loss(x):
    w=torch.transpose(x,0,1)
    #print(w.size())
    w=w.reshape(w.size(0),-1)
    w_len=torch.sum(w*w,1,keepdim=True)+1e-8
    w=w/torch.sqrt(w_len)
    cor=torch.mm(w,w.t())
    cor2=cor*cor
    return torch.sum(cor2)-w.size(0)

class BasicBlock(nn.Module):
    """Basic Block for resnet 18 and resnet 34



    """

    # BasicBlock and BottleNeck block

    # have different output size

    # we use class attribute expansion

    # to distinct

    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()

        # residual function

        self.residual_function = nn.Sequential(

            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=BIAS),

            bn(out_channels),

            nn.ReLU(inplace=False),

            nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=BIAS),

            bn(out_channels * BasicBlock.expansion)

        )

        # shortcut

        self.shortcut = nn.Sequential()

        # the shortcut output dimension is not the same with residual function

        # use 1*1 convolution to match the dimension

        if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
            if stride !=1:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride,stride=stride),
                    nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, bias=BIAS),
                    bn(out_channels * BasicBlock.expansion)
                )
            else:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride, stride=stride),
                    nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, bias=BIAS),
                    bn(out_channels * BasicBlock.expansion)
                )
        self.relu=nn.ReLU(inplace=False)

    def forward(self, x):
        return self.residual_function(x) + self.shortcut(x)
        #return self.relu(self.residual_function(x) + self.shortcut(x))
        #return self.residual_function(x)

class ChannelAttention(nn.Module):
    def __init__(self,in_channels):
        super().__init__()
        #self.register_buffer('running_mean', torch.zeros(1))
        self.a = nn.Parameter(torch.ones(1, in_channels, 1, 1))
        self.b=nn.Parameter(torch.zeros(1,in_channels,1,1))
        self.loss=0
        #self.bn=nn.BatchNorm2d(in_channels,affine=False)
    def forward(self,x):
        #self.loss = decorrelated_loss(x)
        x= x+self.b
        return x
        '''
        return self.bn(x)
        if self.training:
            temp=torch.mean(x)
            #temp=torch.mean(x,[0,1,2],keepdim=True)
            x=x-temp+self.b
            self.running_mean=self.running_mean*0.999+temp.data*0.001
        else:
            x=x-self.running_mean+self.b
        return x
        '''

class BasicBlock_nobn(nn.Module):
    """Basic Block for resnet 18 and resnet 34



    """

    # BasicBlock and BottleNeck block

    # have different output size

    # we use class attribute expansion

    # to distinct

    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()

        # residual function

        self.residual_function = nn.Sequential(

            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=BIAS),

            ChannelAttention(out_channels),

            nn.ReLU(inplace=False),

            nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=BIAS),

            ChannelAttention(out_channels* BasicBlock.expansion)

        )

        # shortcut

        self.shortcut = nn.Sequential()

        # the shortcut output dimension is not the same with residual function

        # use 1*1 convolution to match the dimension

        if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
            if stride !=1:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride,stride=stride),
                    nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, bias=BIAS),
                    ChannelAttention(out_channels* BasicBlock.expansion)
                )
            else:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride, stride=stride),
                    nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, bias=BIAS),
                    ChannelAttention(out_channels * BasicBlock.expansion)
                )
        self.relu=nn.ReLU(inplace=False)

    def forward(self, x):
        return self.residual_function(x) + self.shortcut(x)
class BottleNeck(nn.Module):
    """Residual block for resnet over 50 layers



    """

    expansion = 4

    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()

        self.residual_function = nn.Sequential(

            nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=BIAS),

            nn.BatchNorm2d(out_channels),

            nn.ReLU(inplace=False),

            nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=BIAS),

            nn.BatchNorm2d(out_channels),

            nn.ReLU(inplace=False),

            nn.Conv2d(out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=BIAS),

            nn.BatchNorm2d(out_channels * BottleNeck.expansion),

        )

        self.shortcut = nn.Sequential()

        if stride != 1 or in_channels != BottleNeck.expansion * out_channels:
            if stride != 1:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride, stride=stride),
                    nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=BIAS),
                    nn.BatchNorm2d(out_channels * BasicBlock.expansion)
                )
            else:
                self.shortcut = nn.Sequential(
                    nn.AvgPool2d(kernel_size=stride, stride=stride),
                    nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=BIAS),
                    nn.BatchNorm2d(out_channels * BasicBlock.expansion)
                )

    def forward(self, x):
        return self.residual_function(x) + self.shortcut(x)

class ResNet(nn.Module):

    def __init__(self, block, num_block, indim=3,num_classes=10,batchnorm=True):
        super().__init__()

        self.in_channels = 64
        temp=self.in_channels

        if batchnorm:
            self.conv1 = nn.Sequential(

                nn.Conv2d(indim, temp, kernel_size=3, padding=1, bias=BIAS),

                bn(temp),

                nn.ReLU(inplace=False))
        else:
            self.conv1 = nn.Sequential(
                nn.Conv2d(indim, temp, kernel_size=3, padding=1, bias=BIAS),
                ChannelAttention(temp),
                nn.ReLU(inplace=False))

        # we use a different inputsize than the original paper

        # so conv2_x's stride is 1

        self.conv2_x = self._make_layer(block, temp, num_block[0], 1)

        self.conv3_x = self._make_layer(block, temp*2, num_block[1], 2)

        self.conv4_x = self._make_layer(block,temp*4, num_block[2], 2)


        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.relu=nn.ReLU(inplace=False)
        self.fc = nn.Linear(temp*4 * block.expansion, num_classes,bias=True)
        self.weights_init()

    def _make_layer(self, block, out_channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)

        layers = []

        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))

            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)
    def weights_init(m):
        classname = m.__class__.__name__
        if classname.find('Linear') != -1:
            m.weight.data.normal_(0.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('BatchNorm') != -1:
            m.weight.data.normal_(1.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('Conv' or 'SNConv') != -1:
            m.weight.data.normal_(0.0, 0.02)

    def forward(self, x,feature=True):
        iii = torch.LongTensor(range(x.size(0))).cuda()

        out1 = self.conv1(x)

        out2 = self.conv2_x(out1)
        out3 = self.conv3_x(out2)

        out4 = self.conv4_x(out3)

        h0=self.relu(out4)
        h = h0.view(h0.size(0), -1)
        h0 = self.avg_pool(h0)

        output = h0.view(h0.size(0), -1)
        output = self.fc(output)
        if feature:
            return output,h
        else:
            return output

class ResNet_nomid(nn.Module):

    def __init__(self, block, num_block, indim=3,num_classes=10,batchnorm=True):
        super().__init__()

        self.in_channels = 64
        temp=self.in_channels

        if batchnorm:
            self.conv1 = nn.Sequential(

                nn.Conv2d(indim, temp, kernel_size=3, padding=1, bias=BIAS),

                bn(temp),

                nn.ReLU(inplace=False))
        else:
            self.conv1 = nn.Sequential(
                nn.Conv2d(indim, temp, kernel_size=3, padding=1, bias=BIAS),
                ChannelAttention(temp),
                nn.ReLU(inplace=False))

        # we use a different inputsize than the original paper

        # so conv2_x's stride is 1

        self.conv2_x = self._make_layer(block, temp, num_block[0], 1)

        self.conv3_x = self._make_layer(block, temp*2, num_block[1], 2)

        self.conv4_x = self._make_layer(block,temp*4, num_block[2], 2)


        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.relu=nn.ReLU(inplace=False)
        self.fc = nn.Linear(temp*4 * block.expansion, num_classes,bias=True)
        self.weights_init()

    def _make_layer(self, block, out_channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)

        layers = []

        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))

            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)
    def weights_init(m):
        classname = m.__class__.__name__
        if classname.find('Linear') != -1:
            m.weight.data.normal_(0.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('BatchNorm') != -1:
            m.weight.data.normal_(1.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('Conv' or 'SNConv') != -1:
            m.weight.data.normal_(0.0, 0.02)

    def forward(self, x,after=True,mid=False):
        iii = torch.LongTensor(range(x.size(0))).cuda()

        out1 = self.conv1(x)

        out2 = self.conv2_x(out1)
        out3 = self.conv3_x(out2)

        out4 = self.conv4_x(out3)

        h0=self.relu(out4)
        h=h0.view(h0.size(0), -1)
        output = self.avg_pool(h0)

        output = output.view(output.size(0), -1)
        output = self.fc(output)
        if mid:
            return output,h0
        else:
            return output

class Final(nn.Module):
    def __init__(self,in_channels,num_classes):
        super().__init__()
        self.gap=nn.AdaptiveAvgPool2d((1, 1))
        self.fc=nn.Linear(in_channels, num_classes,bias=False)
        self.relu=nn.ReLU(inplace=False)
    def weights_init(m):
        classname = m.__class__.__name__
        if classname.find('Linear') != -1:
            m.weight.data.normal_(0.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('BatchNorm') != -1:
            m.weight.data.normal_(1.0, 0.02)
            m.bias.data.fill_(0)
        elif classname.find('Conv' or 'SNConv') != -1:
            m.weight.data.normal_(0.0, 0.02)
    def forward(self, x):
        x=self.gap(x)
        out=self.fc(x.view(x.size(0),-1))
        return out
def resnet18(indim=3,num_class=10,batchnorm=True):
    """ return a ResNet 18 object

    """

    if batchnorm:
        return ResNet(BasicBlock, [2, 2, 2, 2],indim=indim,num_classes=num_class,batchnorm=batchnorm)
    else:
        return ResNet(BasicBlock_nobn, [2, 2, 2, 2], indim=indim, num_classes=num_class, batchnorm=batchnorm)

def resnet18_nomid(indim=3,num_class=10,batchnorm=True):
    """ return a ResNet 18 object

    """

    if batchnorm:
        return ResNet_nomid(BasicBlock, [2, 2, 2, 2],indim=indim,num_classes=num_class,batchnorm=batchnorm)
    else:
        return ResNet_nomid(BasicBlock_nobn, [2, 2, 2, 2], indim=indim, num_classes=num_class, batchnorm=batchnorm)

def resnet34(indim=3,num_class=10):
    """ return a ResNet 34 object

    """

    return ResNet(BasicBlock, [3, 4, 6, 3],indim=indim,num_classes=num_class)


def resnet50(indim=3,num_class=10):
    """ return a ResNet 50 object

    """

    return ResNet(BottleNeck, [3, 4, 6, 3],indim=indim,num_classes=num_class)


def resnet101():
    """ return a ResNet 101 object

    """

    return ResNet(BottleNeck, [3, 4, 23, 3])


def resnet152():
    """ return a ResNet 152 object

    """

    return ResNet(BottleNeck, [3, 8, 36, 3])