# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ------------------------------------------------------------------------------

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import logging

import torch
import torch.nn as nn
from collections import OrderedDict
import numpy as np
import math
import torch.nn.functional as F


BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)


class SELayer(nn.Module):
    def __init__(self, channel):
        super(SELayer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Conv2d(channel, channel, 1),
            nn.BatchNorm2d(channel),
            nn.ReLU(inplace=True),
            nn.Conv2d(channel, channel, 1),
            nn.Sigmoid()
            #nn.Linear(channel, channel, bias=False),
            #nn.BatchNorm2d(channel),
            #nn.ReLU(inplace=True),
            #nn.Linear(channel, channel, bias=False),
            #nn.Sigmoid()
        )

    def forward(self, x):
        #b, c, _, _ = x.size()
        y = self.avg_pool(x)
        y = self.fc(y)
        return y


#class ScaledDotProductAttention(nn.Module):
#    ''' Scaled Dot-Product Attention '''
#    def __init__(self, temperature, attn_dropout=0.1):
#        super().__init__()
#        self.temperature = temperature

#    def forward(self, q, k, v):
#
#        attn = torch.matmul(q / self.temperature, k.transpose(2, 3))  #(b,16,4,256) matmul (b,16,256,4) = (b,16,4,4)
#
#        attn = F.softmax(attn, dim=-1)
#
#        output = torch.matmul(attn, v) #(b,16,4,4) matmul (b,16,4,256) = (b,16,4,256)
#
#        return output

#class MultiHeadAttention(nn.Module):
#    ''' Multi-Head Attention module '''
#    def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
#        super().__init__()
#        self.n_head = n_head #16
#        self.d_k = d_k #256
#        self.d_v = d_v #256
#        self.d_model = d_model
#
#        self.w_qs = nn.Linear(self.d_model, self.d_model, bias=False)
#        self.w_ks = nn.Linear(self.d_model, self.d_model, bias=False)
#        self.w_vs = nn.Linear(self.d_model, self.d_model, bias=False)
#        self.fc = nn.Linear(self.n_head * self.d_v, self.d_model, bias=False)
#        self.attention = ScaledDotProductAttention(temperature=self.d_k ** 0.5)
#        self.layer_norm = nn.BatchNorm2d(self.d_model,eps=1e-6)
#    def forward(self, q, k, v):

#        residual = q

#        q = self.w_qs(q).view(q.shape[0], q.shape[1], self.n_head, self.d_k) #(b,4/3/5/2/2,16,256)
#        k = self.w_ks(k).view(k.shape[0], k.shape[1], self.n_head, self.d_k)
#        v = self.w_vs(v).view(v.shape[0], v.shape[1], self.n_head, self.d_v)

#        q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) #(b,16,4/3/5/2/2,256)

#        q= self.attention(q, k, v)  #q(b,16,4,256)

        # b,16,4,256 --> b,4,16,256-->b,4,4096
#        q = q.transpose(1, 2).contiguous().view(q.shape[0], residual.shape[1], -1)
#        q=self.fc(q)
#        q += residual
#        return q
#
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):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

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

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
                               bias=False)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion,
                                  momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

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

        out += residual
        out = self.relu(out)

        return out


class HighResolutionModule(nn.Module):
    def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
                 num_channels, fuse_method, multi_scale_output=True):
        super(HighResolutionModule, self).__init__()
        self._check_branches(
            num_branches, blocks, num_blocks, num_inchannels, num_channels)

        self.num_inchannels = num_inchannels
        self.fuse_method = fuse_method
        self.num_branches = num_branches

        self.multi_scale_output = multi_scale_output

        self.branches = self._make_branches(
            num_branches, blocks, num_blocks, num_channels)
        self.fuse_layers = self._make_fuse_layers()
        self.relu = nn.ReLU(True)
       
        if self.num_branches == 2:
            self.senet1_1 = SELayer(channel=32)
            self.senet1_2 = SELayer(channel=32)
        elif self.num_branches == 3:
            self.senet2_1 = SELayer(channel=32)
            self.senet2_2 = SELayer(channel=32)
            self.senet2_3 = SELayer(channel=32)
            self.senet2_4 = SELayer(channel=64)
            self.senet2_5 = SELayer(channel=64)
        else:
            self.senet3_1 = SELayer(channel=32)
            self.senet3_2 = SELayer(channel=32)
            self.senet3_3 = SELayer(channel=32)
            self.senet3_4 = SELayer(channel=32)
            self.senet3_5 = SELayer(channel=64)
            self.senet3_6 = SELayer(channel=64)
            self.senet3_7 = SELayer(channel=64)
            self.senet3_8 = SELayer(channel=128)
            self.senet3_9 = SELayer(channel=128)


    def _check_branches(self, num_branches, blocks, num_blocks,
                        num_inchannels, num_channels):
        if num_branches != len(num_blocks):
            error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(
                num_branches, len(num_blocks))
            logger.error(error_msg)
            raise ValueError(error_msg)

        if num_branches != len(num_channels):
            error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(
                num_branches, len(num_channels))
            logger.error(error_msg)
            raise ValueError(error_msg)

        if num_branches != len(num_inchannels):
            error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(
                num_branches, len(num_inchannels))
            logger.error(error_msg)
            raise ValueError(error_msg)

    def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
                         stride=1):
        downsample = None
        if stride != 1 or \
           self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(
                    self.num_inchannels[branch_index],
                    num_channels[branch_index] * block.expansion,
                    kernel_size=1, stride=stride, bias=False
                ),
                nn.BatchNorm2d(
                    num_channels[branch_index] * block.expansion,
                    momentum=BN_MOMENTUM
                ),
            )

        layers = []
        layers.append(
            block(
                self.num_inchannels[branch_index],
                num_channels[branch_index],
                stride,
                downsample
            )
        )
        self.num_inchannels[branch_index] = \
            num_channels[branch_index] * block.expansion
        for i in range(1, num_blocks[branch_index]):
            layers.append(
                block(
                    self.num_inchannels[branch_index],
                    num_channels[branch_index]
                )
            )

        return nn.Sequential(*layers)

    def _make_branches(self, num_branches, block, num_blocks, num_channels):
        branches = []

        for i in range(num_branches):
            branches.append(
                self._make_one_branch(i, block, num_blocks, num_channels)
            )

        return nn.ModuleList(branches)

    def _make_fuse_layers(self):
        if self.num_branches == 1: 
            return None

        num_branches = self.num_branches  #2/3/4
        num_inchannels = self.num_inchannels
        fuse_layers = []
        for i in range(num_branches if self.multi_scale_output else 1):  #2/3/4
            fuse_layer = []
            for j in range(num_branches):
                if j > i:
                    fuse_layer.append(
                        nn.Sequential(
                            nn.Conv2d(
                                num_inchannels[j],
                                num_inchannels[i],
                                1, 1, 0, bias=False
                            ),
                            nn.BatchNorm2d(num_inchannels[i]),
                            nn.Upsample(scale_factor=2**(j-i), mode='nearest')
                        )
                    )
                elif j == i:
                    fuse_layer.append(None)
                else:
                    conv3x3s = []
                    for k in range(i-j):
                        if k == i - j - 1:
                            num_outchannels_conv3x3 = num_inchannels[i]
                            conv3x3s.append(
                                nn.Sequential(
                                    nn.Conv2d(
                                        num_inchannels[j],
                                        num_outchannels_conv3x3,
                                        3, 2, 1, bias=False
                                    ),
                                    nn.BatchNorm2d(num_outchannels_conv3x3)
                                )
                            )
                        else:
                            num_outchannels_conv3x3 = num_inchannels[j]
                            conv3x3s.append(
                                nn.Sequential(
                                    nn.Conv2d(
                                        num_inchannels[j],
                                        num_outchannels_conv3x3,
                                        3, 2, 1, bias=False
                                    ),
                                    nn.BatchNorm2d(num_outchannels_conv3x3),
                                    nn.ReLU(True)
                                )
                            )
                    fuse_layer.append(nn.Sequential(*conv3x3s))
            fuse_layers.append(nn.ModuleList(fuse_layer))  
            #2---fuse_layers=([0],[1]),  [0] == [None,upsample]  [1] == [downsample,None]
            #3---fuse_layers=([0],[1],[2]),  [0] == [None,upsample,upsample]  [1] == [downsample,None,upsample]  [2] == [downsample,downsample,downsample]
            #4---fuse_layers=([0],[1],[2],[3]),  [0] == [None,upsample,upsample,upsample]  [1] == [downsample,None,upsample,upsample]  [2] == [downsample,downsample,None,upsample]
            #                                    [3] == [downsample,downsample,downsample,None]

        return nn.ModuleList(fuse_layers)

    def get_num_inchannels(self):
        return self.num_inchannels

    def forward(self, x):
        if self.num_branches == 1:
            return [self.branches[0](x[0])]

        for i in range(self.num_branches):
            x[i] = self.branches[i](x[i])  
            #[(b,32,64,64),(b,64,32,32)] / [(b,32,64,64),(b,64,32,32),(b,128,16,16)] / [(b,32,64,64),(b,64,32,32),(b,128,16,16),(b,256,8,8)]

        x_fuse = []

        for i in range(len(self.fuse_layers)):  #len(self.fuse_layers) == 2/3/4
            if len(x) == 2:
                y = (1+self.senet1_1(x[0]))*x[0] if i == 0 else self.fuse_layers[i][0](x[0])
                for j in range(1, self.num_branches): #2
                    if i == j:
                        y = y + x[j]
                    else: 
                        y = y + (1+self.senet1_1(x[0])*self.senet1_2(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])  
                        #self.fuse_layers[i][j](x[j]) is the feature after the 1x1 and upsample (b,32,64,64)
                x_fuse.append(self.relu(y))


            elif len(x) == 3:
                y = (1+self.senet2_1(x[0]))*x[0] if i == 0 else self.fuse_layers[i][0](x[0])
                for j in range(1, self.num_branches): #3
                    if i==0 and j==1:
                        y = y + (1+self.senet2_1(x[0])*self.senet2_2(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])
                    elif i==0 and j==2:
                        y = y + (1+self.senet2_1(x[0])*self.senet2_3(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])

                    elif i==1 and j==1:
                        y = y + (1+self.senet2_4(x[j]))*x[j]
                    elif i==1 and j==2:
                        y = y + (1+self.senet2_4(x[1])*self.senet2_5(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])

                    else: #i==2
                        if i == j:
                            y = y + x[j]
                        else:
                            y = y + self.fuse_layers[i][j](x[j])

                x_fuse.append(self.relu(y))


            else:
                y = (1+self.senet3_1(x[0]))*x[0] if i == 0 else self.fuse_layers[i][0](x[0])
                for j in range(1, self.num_branches): #4
                    if i==0 and j==1:
                        y = y + (1+self.senet3_1(x[0])*self.senet3_2(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])
                    elif i==0 and j==2:
                        y = y + (1+self.senet3_1(x[0])*self.senet3_3(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])
                    elif i==0 and j==3:
                        y = y + (1+self.senet3_1(x[0])*self.senet3_4(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])

                    elif i==1 and j==1:
                        y = y + (1+self.senet3_5(x[j]))*x[j]
                    elif i==1 and j==2:
                        y = y + (1+self.senet3_5(x[1])*self.senet3_6(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])
                    elif i==1 and j==3:
                        y = y + (1+self.senet3_5(x[1])*self.senet3_7(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])

                    elif i==2 and j==1:
                        y = y + self.fuse_layers[i][j](x[j])
                    elif i==2 and j==2:
                        y = y + (1+self.senet3_8(x[j]))*x[j]
                    elif i==2 and j==3:
                        y = y + (1+self.senet3_8(x[2])*self.senet3_9(self.fuse_layers[i][j](x[j])))*self.fuse_layers[i][j](x[j])
                    else: #i==3
                        if i == j:
                            y = y + x[j]
                        else:
                            y = y + self.fuse_layers[i][j](x[j])
                x_fuse.append(self.relu(y))

        return x_fuse


blocks_dict = {
    'BASIC': BasicBlock,
    'BOTTLENECK': Bottleneck
}


class PoseHighResolutionNet(nn.Module):

    def __init__(self, cfg, **kwargs):
        self.inplanes = 64
        extra = cfg['MODEL']['EXTRA']
        super(PoseHighResolutionNet, self).__init__()

        # stem net
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
        self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1,
                               bias=False)
        self.bn2 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = self._make_layer(Bottleneck, 64, 4)

        self.stage2_cfg = extra['STAGE2']
        num_channels = self.stage2_cfg['NUM_CHANNELS']
        block = blocks_dict[self.stage2_cfg['BLOCK']]
        num_channels = [
            num_channels[i] * block.expansion for i in range(len(num_channels))
        ]
        self.transition1 = self._make_transition_layer([256], num_channels)
        self.stage2, pre_stage_channels = self._make_stage(
            self.stage2_cfg, num_channels)

        self.stage3_cfg = extra['STAGE3']
        num_channels = self.stage3_cfg['NUM_CHANNELS']
        block = blocks_dict[self.stage3_cfg['BLOCK']]
        num_channels = [
            num_channels[i] * block.expansion for i in range(len(num_channels))
        ]
        self.transition2 = self._make_transition_layer(
            pre_stage_channels, num_channels)
        self.stage3, pre_stage_channels = self._make_stage(
            self.stage3_cfg, num_channels)

        self.stage4_cfg = extra['STAGE4']
        num_channels = self.stage4_cfg['NUM_CHANNELS']
        block = blocks_dict[self.stage4_cfg['BLOCK']]
        num_channels = [
            num_channels[i] * block.expansion for i in range(len(num_channels))
        ]
        self.transition3 = self._make_transition_layer(
            pre_stage_channels, num_channels)
        self.stage4, pre_stage_channels = self._make_stage(
            self.stage4_cfg, num_channels, multi_scale_output=False)

        self.final_layer = nn.Conv2d(
            in_channels=pre_stage_channels[0],
            out_channels=cfg['MODEL']['NUM_JOINTS'],
            kernel_size=extra['FINAL_CONV_KERNEL'],
            stride=1,
            padding=1 if extra['FINAL_CONV_KERNEL'] == 3 else 0
        )

        self.pretrained_layers = extra['PRETRAINED_LAYERS']

        #self.mha1 = MultiHeadAttention(n_head=4, d_model=4096, d_k=1024, d_v=1024, dropout=0.1)
        #self.mha2 = MultiHeadAttention(n_head=8, d_model=4096, d_k=512, d_v=512, dropout=0.1)
        #self.mha3 = MultiHeadAttention(n_head=8, d_model=4096, d_k=512, d_v=512, dropout=0.1)
        #self.mha4 = MultiHeadAttention(n_head=8, d_model=4096, d_k=512, d_v=512, dropout=0.1)
        #self.mha5 = MultiHeadAttention(n_head=8, d_model=4096, d_k=512, d_v=512, dropout=0.1)

    def _make_transition_layer(
            self, num_channels_pre_layer, num_channels_cur_layer):
        num_branches_cur = len(num_channels_cur_layer)
        num_branches_pre = len(num_channels_pre_layer)

        transition_layers = []
        for i in range(num_branches_cur):
            if i < num_branches_pre:
                if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
                    transition_layers.append(
                        nn.Sequential(
                            nn.Conv2d(
                                num_channels_pre_layer[i],
                                num_channels_cur_layer[i],
                                3, 1, 1, bias=False
                            ),
                            nn.BatchNorm2d(num_channels_cur_layer[i]),
                            nn.ReLU(inplace=True)
                        )
                    )
                else:
                    transition_layers.append(None)
            else:
                conv3x3s = []
                for j in range(i+1-num_branches_pre):
                    inchannels = num_channels_pre_layer[-1]
                    outchannels = num_channels_cur_layer[i] \
                        if j == i-num_branches_pre else inchannels
                    conv3x3s.append(
                        nn.Sequential(
                            nn.Conv2d(
                                inchannels, outchannels, 3, 2, 1, bias=False
                            ),
                            nn.BatchNorm2d(outchannels),
                            nn.ReLU(inplace=True)
                        )
                    )
                transition_layers.append(nn.Sequential(*conv3x3s))

        return nn.ModuleList(transition_layers)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(
                    self.inplanes, planes * block.expansion,
                    kernel_size=1, stride=stride, bias=False
                ),
                nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def _make_stage(self, layer_config, num_inchannels,
                    multi_scale_output=True):
        num_modules = layer_config['NUM_MODULES']
        num_branches = layer_config['NUM_BRANCHES']
        num_blocks = layer_config['NUM_BLOCKS']
        num_channels = layer_config['NUM_CHANNELS']
        block = blocks_dict[layer_config['BLOCK']]
        fuse_method = layer_config['FUSE_METHOD']

        modules = []
        for i in range(num_modules):
            # multi_scale_output is only used last module
            if not multi_scale_output and i == num_modules - 1:
                reset_multi_scale_output = False
            else:
                reset_multi_scale_output = True

            modules.append(
                HighResolutionModule(
                    num_branches,
                    block,
                    num_blocks,
                    num_inchannels,
                    num_channels,
                    fuse_method,
                    reset_multi_scale_output
                )
            )
            num_inchannels = modules[-1].get_num_inchannels()

        return nn.Sequential(*modules), num_inchannels

    def forward(self, x):
        #a1,a2,a3,a4,a5=[],[],[],[],[]
        #c=[]
#x(b,3,256,256)
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
#(b,64,128,128)
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu(x)
#(b,64,64,64)
        x = self.layer1(x)
#(b,256,64,64)

        x_list = []
        for i in range(self.stage2_cfg['NUM_BRANCHES']):
            if self.transition1[i] is not None:
                x_list.append(self.transition1[i](x))
            else:
                x_list.append(x)
#x_list = [(b,32,64,64), (b,64,32,32)]
        y_list = self.stage2(x_list)
#y_list = [(b,32,64,64), (b,64,32,32)]

        x_list = []
        for i in range(self.stage3_cfg['NUM_BRANCHES']):
            if self.transition2[i] is not None:
                x_list.append(self.transition2[i](y_list[-1]))
            else:
                x_list.append(y_list[i])
#x_list = [(b,32,64,64), (b,64,32,32), (b,128,16,16)]
        y_list = self.stage3(x_list)
#y_list = [(b,32,64,64), (b,64,32,32), (b,128,16,16)]

        x_list = []
        for i in range(self.stage4_cfg['NUM_BRANCHES']):
            if self.transition3[i] is not None:
                x_list.append(self.transition3[i](y_list[-1]))
            else:
                x_list.append(y_list[i])
        y_list = self.stage4(x_list)
#y_list = [(b,32,64,64), (b,64,32,32), (b,128,16,16), (b,256,8,8)]

        x = self.final_layer(y_list[0])
#(b,16,64,64)  heatmap

        #(b,16,4096)
#        f_a = x.view(x.shape[0],16,-1)

        '''#(b,4,4096)
        for i in range(x.shape[0]):
            a1.append(f_a[i][0:1,:])
            a1.append(f_a[i][1:2,:])
            a1.append(f_a[i][4:5,:])
            a1.append(f_a[i][5:6,:])             
        f_a_1=torch.cat(a1,dim=0)
        f_a_1=f_a_1.view(x.shape[0],-1,f_a_1.shape[-1])
        #(b,3,4096)
        for i in range(x.shape[0]):
            a2.append(f_a[i][2:3,:])
            a2.append(f_a[i][3:4,:])
            a2.append(f_a[i][6:7,:])           
        f_a_2 = torch.cat(a2,dim=0)
        f_a_2=f_a_2.view(x.shape[0],-1,f_a_2.shape[-1])
        #(b,5,4096)
        for i in range(x.shape[0]):
            a3.append(f_a[i][7:8,:])
            a3.append(f_a[i][8:9,:])
            a3.append(f_a[i][9:10,:])
            a3.append(f_a[i][12:13,:])
            a3.append(f_a[i][13:14,:])             
        f_a_3 = torch.cat(a3,dim=0)
        f_a_3=f_a_3.view(x.shape[0],-1,f_a_3.shape[-1])
        #(b,2,4096)
        for i in range(x.shape[0]):
            a4.append(f_a[i][10:11,:])
            a4.append(f_a[i][11:12,:])           
        f_a_4 = torch.cat(a4,dim=0)
        f_a_4=f_a_4.view(x.shape[0],-1,f_a_4.shape[-1])
        #(b,2,4096)
        for i in range(x.shape[0]):
            a5.append(f_a[i][14:15,:])
            a5.append(f_a[i][15:16,:])           
        f_a_5 = torch.cat(a5,dim=0)
        f_a_5=f_a_5.view(x.shape[0],-1,f_a_5.shape[-1])'''

        #===========================================================================================
        #(b,16,4096)
#        enhanced_f_a_1 = self.mha1(q=f_a,k=f_a,v=f_a)
        '''#(b,3,4096)
        enhanced_f_a_2 = self.mha2(q=f_a_2,k=f_a_2,v=f_a_2)
        #(b,5,4096)
        enhanced_f_a_3 = self.mha3(q=f_a_3,k=f_a_3,v=f_a_3)
        #(b,2,4096)
        enhanced_f_a_4 = self.mha4(q=f_a_4,k=f_a_4,v=f_a_4)
        #(b,2,4096)
        enhanced_f_a_5 = self.mha5(q=f_a_5,k=f_a_5,v=f_a_5)


        #c(b,16,4096)
        for i in range(x.shape[0]):
            c.append(enhanced_f_a_1[i][0:2,:])
            c.append(enhanced_f_a_2[i][0:2,:])
            c.append(enhanced_f_a_1[i][2:4,:])
            c.append(enhanced_f_a_2[i][2:3,:])
            c.append(enhanced_f_a_3[i][0:3,:])
            c.append(enhanced_f_a_4[i][0:2,:])
            c.append(enhanced_f_a_3[i][3:5,:])
            c.append(enhanced_f_a_5[i][0:2,:])
        #(b,16,4096)
        out = torch.cat(c,dim=0)
        out=out.view(x.shape[0],-1,out.shape[-1])'''
        #(b,16,64,64)
#        out = enhanced_f_a_1.view(enhanced_f_a_1.shape[0],enhanced_f_a_1.shape[1],64,-1)
 #       return out
        return x

    def init_weights(self, pretrained=''):
        logger.info('=> init weights from normal distribution')
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                nn.init.normal_(m.weight, std=0.001)
                for name, _ in m.named_parameters():
                    if name in ['bias']:
                        nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.ConvTranspose2d):
                nn.init.normal_(m.weight, std=0.001)
                for name, _ in m.named_parameters():
                    if name in ['bias']:
                        nn.init.constant_(m.bias, 0)

        if os.path.isfile(pretrained):
            pretrained_state_dict = torch.load(pretrained)
            logger.info('=> loading pretrained model {}'.format(pretrained))

            need_init_state_dict = {}
            for name, m in pretrained_state_dict.items():
                if name.split('.')[0] in self.pretrained_layers \
                   or self.pretrained_layers[0] is '*':
                    need_init_state_dict[name] = m
            self.load_state_dict(need_init_state_dict, strict=False)
        elif pretrained:
            logger.error('=> please download pre-trained models first!')
            raise ValueError('{} is not exist!'.format(pretrained))


def get_pose_net(cfg, is_train, **kwargs):
    model = PoseHighResolutionNet(cfg, **kwargs)

    if is_train and cfg['MODEL']['INIT_WEIGHTS']:
        model.init_weights(cfg['MODEL']['PRETRAINED'])

    return model
