import torch.nn as nn
import torch.nn.functional as F
from .repvgg import get_RepVGG_func_by_name
from .s2dnet import S2DNet


def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution without padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False)


def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)


class BasicBlock(nn.Module):
    def __init__(self, in_planes, planes, stride=1):
        super().__init__()
        self.conv1 = conv3x3(in_planes, planes, stride)
        self.conv2 = conv3x3(planes, planes)
        self.bn1 = nn.BatchNorm2d(planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)

        if stride == 1:
            self.downsample = None
        else:
            self.downsample = nn.Sequential(
                conv1x1(in_planes, planes, stride=stride),
                nn.BatchNorm2d(planes)
            )

    def forward(self, x):
        y = x
        y = self.relu(self.bn1(self.conv1(y)))
        y = self.bn2(self.conv2(y))

        if self.downsample is not None:
            x = self.downsample(x)

        return self.relu(x+y)


class ResNetFPN_8_2(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1/2.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim

        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
        self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
        self.layer2_outconv2 = nn.Sequential(
            conv3x3(block_dims[2], block_dims[2]),
            nn.BatchNorm2d(block_dims[2]),
            nn.LeakyReLU(),
            conv3x3(block_dims[2], block_dims[1]),
        )
        self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
        self.layer1_outconv2 = nn.Sequential(
            conv3x3(block_dims[1], block_dims[1]),
            nn.BatchNorm2d(block_dims[1]),
            nn.LeakyReLU(),
            conv3x3(block_dims[1], block_dims[0]),
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        # FPN
        x3_out = self.layer3_outconv(x3)

        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=True)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=True)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        return {'feats_c': x3_out, 'feats_f': x1_out}
    
    def pro(self, x, profiler):
        with profiler.profile('ResNet Backbone'):
            # ResNet Backbone
            x0 = self.relu(self.bn1(self.conv1(x)))
            x1 = self.layer1(x0)  # 1/2
            x2 = self.layer2(x1)  # 1/4
            x3 = self.layer3(x2)  # 1/8

        with profiler.profile('ResNet FPN'):
            # FPN
            x3_out = self.layer3_outconv(x3)

            x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=True)
            x2_out = self.layer2_outconv(x2)
            x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

            x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=True)
            x1_out = self.layer1_outconv(x1)
            x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

            return {'feats_c': x3_out, 'feats_f': x1_out}

class ResNetFPN_8_2_fix(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1/2.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']

        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
        self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
        self.layer2_outconv2 = nn.Sequential(
            conv3x3(block_dims[2], block_dims[2]),
            nn.BatchNorm2d(block_dims[2]),
            nn.LeakyReLU(),
            conv3x3(block_dims[2], block_dims[1]),
        )
        self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
        self.layer1_outconv2 = nn.Sequential(
            conv3x3(block_dims[1], block_dims[1]),
            nn.BatchNorm2d(block_dims[1]),
            nn.LeakyReLU(),
            conv3x3(block_dims[1], block_dims[0]),
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        # FPN
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else:
                return {'feats_c': x3, 'feats_f': None}


        x3_out = self.layer3_outconv(x3) # n+1

        x3_out_2x = F.interpolate(x3_out, size=((x3_out.size(-2)-1)*2+1, (x3_out.size(-1)-1)*2+1), mode='bilinear', align_corners=True) # 2n+1
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, size=((x2_out.size(-2)-1)*2+1, (x2_out.size(-1)-1)*2+1), mode='bilinear', align_corners=True) # 4n+1
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        return {'feats_c': x3_out, 'feats_f': x1_out}


class ResNetFPN_16_4(nn.Module):
    """
    ResNet+FPN, output resolution are 1/16 and 1/4.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim

        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8
        self.layer4 = self._make_layer(block, block_dims[3], stride=2)  # 1/16

        # 3. FPN upsample
        self.layer4_outconv = conv1x1(block_dims[3], block_dims[3])
        self.layer3_outconv = conv1x1(block_dims[2], block_dims[3])
        self.layer3_outconv2 = nn.Sequential(
            conv3x3(block_dims[3], block_dims[3]),
            nn.BatchNorm2d(block_dims[3]),
            nn.LeakyReLU(),
            conv3x3(block_dims[3], block_dims[2]),
        )

        self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
        self.layer2_outconv2 = nn.Sequential(
            conv3x3(block_dims[2], block_dims[2]),
            nn.BatchNorm2d(block_dims[2]),
            nn.LeakyReLU(),
            conv3x3(block_dims[2], block_dims[1]),
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8
        x4 = self.layer4(x3)  # 1/16

        # FPN
        x4_out = self.layer4_outconv(x4)

        x4_out_2x = F.interpolate(x4_out, scale_factor=2., mode='bilinear', align_corners=True)
        x3_out = self.layer3_outconv(x3)
        x3_out = self.layer3_outconv2(x3_out+x4_out_2x)

        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=True)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        return {'feats_c': x4_out, 'feats_f': x2_out}


class ResNetFPN_8_1(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']

        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
            self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
            self.layer2_outconv2 = nn.Sequential(
                conv3x3(block_dims[2], block_dims[2]),
                nn.BatchNorm2d(block_dims[2]),
                nn.LeakyReLU(),
                conv3x3(block_dims[2], block_dims[1]),
            )
            self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
            self.layer1_outconv2 = nn.Sequential(
                conv3x3(block_dims[1], block_dims[1]),
                nn.BatchNorm2d(block_dims[1]),
                nn.LeakyReLU(),
                conv3x3(block_dims[1], block_dims[0]),
            )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        # FPN
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else:
                return {'feats_c': x3, 'feats_f': None}

        x3_out = self.layer3_outconv(x3)

        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=True)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=True)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        if not self.inter_feat:
            return {'feats_c': x3, 'feats_f': x0_out}
        else:
            return {'feats_c': x3, 'feats_f': x0_out, 'feats_x2': x2, 'feats_x1': x1}


class ResNetFPN_8_1_align(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']
        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
            self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
            self.layer2_outconv2 = nn.Sequential(
                conv3x3(block_dims[2], block_dims[2]),
                nn.BatchNorm2d(block_dims[2]),
                nn.LeakyReLU(),
                conv3x3(block_dims[2], block_dims[1]),
            )
            self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
            self.layer1_outconv2 = nn.Sequential(
                conv3x3(block_dims[1], block_dims[1]),
                nn.BatchNorm2d(block_dims[1]),
                nn.LeakyReLU(),
                conv3x3(block_dims[1], block_dims[0]),
            )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        # FPN
        
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else:
                return {'feats_c': x3, 'feats_f': None}
                
        x3_out = self.layer3_outconv(x3)
        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        if not self.inter_feat:
            return {'feats_c': x3, 'feats_f': x0_out}
        else:
            return {'feats_c': x3, 'feats_f': x0_out, 'feats_x2': x2, 'feats_x1': x1}
    
    def pro(self, x, profiler):
        with profiler.profile('ResNet Backbone'):
            # ResNet Backbone
            x0 = self.relu(self.bn1(self.conv1(x)))
            x1 = self.layer1(x0)  # 1/2
            x2 = self.layer2(x1)  # 1/4
            x3 = self.layer3(x2)  # 1/8

        with profiler.profile('FPN'):
            # FPN
            x3_out = self.layer3_outconv(x3)
            
            if self.skip_fine:
                return [x3_out, None]
            x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
            x2_out = self.layer2_outconv(x2)
            x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

            x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
            x1_out = self.layer1_outconv(x1)
            x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        with profiler.profile('upsample*1'):
            x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        return {'feats_c': x3_out, 'feats_f': x0_out}
    

class ResNetFPN_8_2_align(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1/2.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']
        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
            self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
            self.layer2_outconv2 = nn.Sequential(
                conv3x3(block_dims[2], block_dims[2]),
                nn.BatchNorm2d(block_dims[2]),
                nn.LeakyReLU(),
                conv3x3(block_dims[2], block_dims[1]),
            )
            self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
            self.layer1_outconv2 = nn.Sequential(
                conv3x3(block_dims[1], block_dims[1]),
                nn.BatchNorm2d(block_dims[1]),
                nn.LeakyReLU(),
                conv3x3(block_dims[1], block_dims[0]),
            )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else:
                return {'feats_c': x3, 'feats_f': None}

        # FPN
        x3_out = self.layer3_outconv(x3)

        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        if not self.inter_feat:
            return {'feats_c': x3, 'feats_f': x1_out}
        else:
            return {'feats_c': x3, 'feats_f': x1_out, 'feats_x2': x2, 'feats_x1': x1}


class ResNet_8_1_align(nn.Module):
    """
    ResNet, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim

        # Networks
        self.conv1 = nn.Conv2d(1, initial_dim, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(initial_dim)
        self.relu = nn.ReLU(inplace=True)

        self.layer1 = self._make_layer(block, block_dims[0], stride=1)  # 1/2
        self.layer2 = self._make_layer(block, block_dims[1], stride=2)  # 1/4
        self.layer3 = self._make_layer(block, block_dims[2], stride=2)  # 1/8

        # 3. FPN upsample
        # self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
        # self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
        # self.layer2_outconv2 = nn.Sequential(
        #     conv3x3(block_dims[2], block_dims[2]),
        #     nn.BatchNorm2d(block_dims[2]),
        #     nn.LeakyReLU(),
        #     conv3x3(block_dims[2], block_dims[1]),
        # )
        # self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
        # self.layer1_outconv2 = nn.Sequential(
        #     conv3x3(block_dims[1], block_dims[1]),
        #     nn.BatchNorm2d(block_dims[1]),
        #     nn.LeakyReLU(),
        #     conv3x3(block_dims[1], block_dims[0]),
        # )
        self.layer0_outconv = conv1x1(block_dims[2], block_dims[0])
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # ResNet Backbone
        x0 = self.relu(self.bn1(self.conv1(x)))
        x1 = self.layer1(x0)  # 1/2
        x2 = self.layer2(x1)  # 1/4
        x3 = self.layer3(x2)  # 1/8

        # FPN
        # x3_out = self.layer3_outconv(x3)

        # x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x2_out = self.layer2_outconv(x2)
        # x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        # x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x1_out = self.layer1_outconv(x1)
        # x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        x0_out = F.interpolate(x3, scale_factor=8., mode='bilinear', align_corners=False)
        x0_out = self.layer0_outconv(x0_out)

        return {'feats_c': x3, 'feats_f': x0_out}

class VGG_8_1_align(nn.Module):
    """
    VGG-like backbone, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        self.relu = nn.ReLU(inplace=True)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        c1, c2, c3, c4, c5 = 64, 64, 128, 128, 256

        self.conv1a = nn.Conv2d(1, c1, kernel_size=3, stride=1, padding=1)
        self.conv1b = nn.Conv2d(c1, c1, kernel_size=3, stride=1, padding=1)
        self.conv2a = nn.Conv2d(c1, c2, kernel_size=3, stride=1, padding=1)
        self.conv2b = nn.Conv2d(c2, c2, kernel_size=3, stride=1, padding=1)
        self.conv3a = nn.Conv2d(c2, c3, kernel_size=3, stride=1, padding=1)
        self.conv3b = nn.Conv2d(c3, c3, kernel_size=3, stride=1, padding=1)
        self.conv4a = nn.Conv2d(c3, c4, kernel_size=3, stride=1, padding=1)
        self.conv4b = nn.Conv2d(c4, c4, kernel_size=3, stride=1, padding=1)

        # self.convPa = nn.Conv2d(c4, c5, kernel_size=3, stride=1, padding=1)
        # self.convPb = nn.Conv2d(c5, 65, kernel_size=1, stride=1, padding=0)

        self.convDa = nn.Conv2d(c4, c5, kernel_size=3, stride=1, padding=1)
        self.convDb = nn.Conv2d(
            c5, 256,
            kernel_size=1, stride=1, padding=0)
        self.layer0_outconv = conv1x1(block_dims[2], block_dims[0])
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, dim, stride=1):
        layer1 = block(self.in_planes, dim, stride=stride)
        layer2 = block(dim, dim, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x):
        # Shared Encoder
        x = self.relu(self.conv1a(x))
        x = self.relu(self.conv1b(x))
        x = self.pool(x)
        x = self.relu(self.conv2a(x))
        x = self.relu(self.conv2b(x))
        x = self.pool(x)
        x = self.relu(self.conv3a(x))
        x = self.relu(self.conv3b(x))
        x = self.pool(x)
        x = self.relu(self.conv4a(x))
        x = self.relu(self.conv4b(x))

        cDa = self.relu(self.convDa(x))
        descriptors = self.convDb(cDa)
        x3_out = nn.functional.normalize(descriptors, p=2, dim=1)

        x0_out = F.interpolate(x3_out, scale_factor=8., mode='bilinear', align_corners=False)
        x0_out = self.layer0_outconv(x0_out)
        # ResNet Backbone
        # x0 = self.relu(self.bn1(self.conv1(x)))
        # x1 = self.layer1(x0)  # 1/2
        # x2 = self.layer2(x1)  # 1/4
        # x3 = self.layer3(x2)  # 1/8

        # # FPN
        # x3_out = self.layer3_outconv(x3)

        # x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x2_out = self.layer2_outconv(x2)
        # x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        # x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x1_out = self.layer1_outconv(x1)
        # x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        # x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        return {'feats_c': x3_out, 'feats_f': x0_out}

class RepVGG_8_1_align(nn.Module):
    """
    RepVGG backbone, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        # block = BasicBlock
        # initial_dim = config['initial_dim']
        block_dims = config['block_dims']
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']
        self.leaky = config['leaky']

        # backbone_name='RepVGG-B0'
        if config.get('repvggmodel') is not None:
            backbone_name=config['repvggmodel']
        elif self.leaky:
            backbone_name='RepVGG-A1_leaky'
        else:
            backbone_name='RepVGG-A1'
        repvgg_fn = get_RepVGG_func_by_name(backbone_name)
        backbone = repvgg_fn(False)
        self.layer0, self.layer1, self.layer2, self.layer3 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3 #, backbone.stage4
        # self.layer0, self.layer1, self.layer2, self.layer3, self.layer4 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3, backbone.stage4

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
            self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
            self.layer2_outconv2 = nn.Sequential(
                conv3x3(block_dims[2], block_dims[2]),
                nn.BatchNorm2d(block_dims[2]),
                nn.LeakyReLU(),
                conv3x3(block_dims[2], block_dims[1]),
            )
            self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
            self.layer1_outconv2 = nn.Sequential(
                conv3x3(block_dims[1], block_dims[1]),
                nn.BatchNorm2d(block_dims[1]),
                nn.LeakyReLU(),
                conv3x3(block_dims[1], block_dims[0]),
            )

        # self.layer0_outconv = conv1x1(192, 48)

        for layer in [self.layer0, self.layer1, self.layer2, self.layer3]:
            for m in layer.modules():
                if isinstance(m, nn.Conv2d):
                    nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                    nn.init.constant_(m.weight, 1)
                    nn.init.constant_(m.bias, 0)
        # for layer in [self.layer0, self.layer1, self.layer2, self.layer3, self.layer4]:
        #     for m in layer.modules():
        #         if isinstance(m, nn.Conv2d):
        #             nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
        #         elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
        #             nn.init.constant_(m.weight, 1)
        #             nn.init.constant_(m.bias, 0)

    def forward(self, x):

        out = self.layer0(x) # 1/2
        for module in self.layer1:
            out = module(out) # 1/2
            x1 = out
        for module in self.layer2:
            out = module(out) # 1/4
            x2 = out
        for module in self.layer3:
            out = module(out) # 1/8
            x3 = out
        # for module in self.layer4:
        #     out = module(out)
        #     x3 = out
                
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else: 
                return {'feats_c': x3, 'feats_f': None}
        x3_out = self.layer3_outconv(x3)
        x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        # x_f = F.interpolate(x_c, scale_factor=8., mode='bilinear', align_corners=False)
        # x_f = self.layer0_outconv(x_f)
        return {'feats_c': x3_out, 'feats_f': x0_out}


class RepVGG_8_2_fix(nn.Module):
    """
    RepVGG backbone, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        # block = BasicBlock
        # initial_dim = config['initial_dim']
        block_dims = config['block_dims']
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']

        # backbone_name='RepVGG-B0'
        backbone_name='RepVGG-A1'
        repvgg_fn = get_RepVGG_func_by_name(backbone_name)
        backbone = repvgg_fn(False)
        self.layer0, self.layer1, self.layer2, self.layer3 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3 #, backbone.stage4

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
            self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
            self.layer2_outconv2 = nn.Sequential(
                conv3x3(block_dims[2], block_dims[2]),
                nn.BatchNorm2d(block_dims[2]),
                nn.LeakyReLU(),
                conv3x3(block_dims[2], block_dims[1]),
            )
            self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
            self.layer1_outconv2 = nn.Sequential(
                conv3x3(block_dims[1], block_dims[1]),
                nn.BatchNorm2d(block_dims[1]),
                nn.LeakyReLU(),
                conv3x3(block_dims[1], block_dims[0]),
            )

        # self.layer0_outconv = conv1x1(192, 48)

        for layer in [self.layer0, self.layer1, self.layer2, self.layer3]:
            for m in layer.modules():
                if isinstance(m, nn.Conv2d):
                    nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                    nn.init.constant_(m.weight, 1)
                    nn.init.constant_(m.bias, 0)

    def forward(self, x):

        x0 = self.layer0(x) # 1/2
        out = x0
        for module in self.layer1:
            out = module(out) # 1/2
            x1 = out
        for module in self.layer2:
            out = module(out) # 1/4
            x2 = out
        for module in self.layer3:
            out = module(out) # 1/8
            x3 = out
        # for module in self.layer4:
        #     out = module(out)
        
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else: 
                return {'feats_c': x3, 'feats_f': None}
        x3_out = self.layer3_outconv(x3)
        x3_out_2x = F.interpolate(x3_out, size=((x3_out.size(-2)-1)*2+1, (x3_out.size(-1)-1)*2+1), mode='bilinear', align_corners=True)
        x2_out = self.layer2_outconv(x2)
        x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        x2_out_2x = F.interpolate(x2_out, size=((x2_out.size(-2)-1)*2+1, (x2_out.size(-1)-1)*2+1), mode='bilinear', align_corners=True)
        x1_out = self.layer1_outconv(x1)
        x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        # x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        # x_f = F.interpolate(x_c, scale_factor=8., mode='bilinear', align_corners=False)
        # x_f = self.layer0_outconv(x_f)
        return {'feats_c': x3_out, 'feats_f': x1_out}


class RepVGGnfpn_8_1_align(nn.Module):
    """
    RepVGG backbone, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        # block = BasicBlock
        # initial_dim = config['initial_dim']
        block_dims = config['block_dims']
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']

        # backbone_name='RepVGG-B0'
        backbone_name='RepVGG-A1'
        repvgg_fn = get_RepVGG_func_by_name(backbone_name)
        backbone = repvgg_fn(False)
        self.layer0, self.layer1, self.layer2, self.layer3 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3 #, backbone.stage4

        # 3. FPN upsample
        if not self.skip_fine_feature:
            self.layer0_outconv = conv1x1(block_dims[2], block_dims[0])
        # self.layer0_outconv = conv1x1(192, 48)

        for layer in [self.layer0, self.layer1, self.layer2, self.layer3]:
            for m in layer.modules():
                if isinstance(m, nn.Conv2d):
                    nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                    nn.init.constant_(m.weight, 1)
                    nn.init.constant_(m.bias, 0)

    def forward(self, x):

        x0 = self.layer0(x) # 1/2
        out = x0
        for module in self.layer1:
            out = module(out) # 1/2
            x1 = out
        for module in self.layer2:
            out = module(out) # 1/4
            x2 = out
        for module in self.layer3:
            out = module(out) # 1/8
            x3 = out
        # for module in self.layer4:
        #     out = module(out)
        
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': x3, 'feats_f': None, 'feats_x2': x2, 'feats_x1': x1}
            else: 
                return {'feats_c': x3, 'feats_f': None}
        # x3_out = self.layer3_outconv(x3)
        # x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x2_out = self.layer2_outconv(x2)
        # x2_out = self.layer2_outconv2(x2_out+x3_out_2x)

        # x2_out_2x = F.interpolate(x2_out, scale_factor=2., mode='bilinear', align_corners=False)
        # x1_out = self.layer1_outconv(x1)
        # x1_out = self.layer1_outconv2(x1_out+x2_out_2x)

        # x0_out = F.interpolate(x1_out, scale_factor=2., mode='bilinear', align_corners=False)

        x_f = F.interpolate(x3, scale_factor=8., mode='bilinear', align_corners=False)
        x_f = self.layer0_outconv(x_f)
        # x_f2 = F.interpolate(x3, scale_factor=8., mode='bilinear', align_corners=False)
        # x_f2 = self.layer0_outconv(x_f2)
        return {'feats_c': x3, 'feats_f': x_f}


class s2dnet_8_1_align(nn.Module):
    """
    ResNet+FPN, output resolution are 1/8 and 1.
    Each block has 2 layers.
    """

    def __init__(self, config):
        super().__init__()
        # Config
        block = BasicBlock
        initial_dim = config['initial_dim']
        block_dims = config['block_dims']

        # Class Variable
        self.in_planes = initial_dim
        self.skip_fine_feature = config['coarse_feat_only']
        self.inter_feat = config['inter_feat']
        # Networks
        self.backbone = S2DNet(checkpoint_path = '/cephfs-mvs/3dv-research/hexingyi/code_yf/loftrdev/weights/s2dnet/s2dnet_weights.pth')
        # 3. FPN upsample
        # self.layer3_outconv = conv1x1(block_dims[2], block_dims[2])
        # if not self.skip_fine_feature:
        #     self.layer2_outconv = conv1x1(block_dims[1], block_dims[2])
        #     self.layer2_outconv2 = nn.Sequential(
        #         conv3x3(block_dims[2], block_dims[2]),
        #         nn.BatchNorm2d(block_dims[2]),
        #         nn.LeakyReLU(),
        #         conv3x3(block_dims[2], block_dims[1]),
        #     )
        #     self.layer1_outconv = conv1x1(block_dims[0], block_dims[1])
        #     self.layer1_outconv2 = nn.Sequential(
        #         conv3x3(block_dims[1], block_dims[1]),
        #         nn.BatchNorm2d(block_dims[1]),
        #         nn.LeakyReLU(),
        #         conv3x3(block_dims[1], block_dims[0]),
        #     )

        # for m in self.modules():
        #     if isinstance(m, nn.Conv2d):
        #         nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
        #     elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
        #         nn.init.constant_(m.weight, 1)
        #         nn.init.constant_(m.bias, 0)

    def forward(self, x):
        ret = self.backbone(x)
        ret[2] = F.interpolate(ret[2], scale_factor=2., mode='bilinear', align_corners=False)
        if self.skip_fine_feature:
            if self.inter_feat:
                return {'feats_c': ret[2], 'feats_f': None, 'feats_x2': ret[1], 'feats_x1': ret[0]}
            else:
                return {'feats_c': ret[2], 'feats_f': None,}
    
    def pro(self, x, profiler):
        pass