from time import time

import torch
from torch import Tensor
import torch.nn as nn
# from .utils import load_state_dict_from_url
from torch.utils import model_zoo
from typing import Type, Any, Callable, Union, List, Optional
import numpy as np
from .GCN import GCN
from .deepgcn.architecture import DeepGCN
from .losses import SupConLoss
from numba import jit
import torch.nn.functional as F
import matplotlib
import matplotlib.pyplot as plt
# matplotlib.use('Qt5Agg')

from .build import BACKBONE_REGISTRY
from .backbone import Backbone

__all__ = ['ResNet', 'mire_resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
           'wide_resnet50_2', 'wide_resnet101_2']


model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
    'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
    'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
    'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}


def EuclideanDistances(a, b):
    sq_a = a ** 2
    sum_sq_a = torch.sum(sq_a, dim=1).unsqueeze(1)  # m->[m, 1]
    sq_b = b ** 2
    sum_sq_b = torch.sum(sq_b, dim=1).unsqueeze(0)  # n->[1, n]
    bt = b.t()
    EucDis = torch.sqrt(sum_sq_a + sum_sq_b - 2 * a.mm(bt))
    EucDis = torch.where(EucDis.isnan(), torch.zeros_like(EucDis), EucDis)
    # edist = nn.PairwiseDistance(p=2)
    return EucDis

def data_normal_2d(orign_data,dim="col"):

    if dim == "col":
        dim = 1
        d_min = torch.min(orign_data,dim=dim)[0]
        d_max = torch.max(orign_data,dim=dim)[0]
        for idx,j in enumerate(d_min):
            orign_data[idx,:] = (orign_data[idx,:] - d_min[idx]) / (d_max[idx] - d_min[idx])

    return orign_data
# def EuclideanDistances(x, y):
#     x_sq = (x ** 2).mean(-1)
#     x_sq_ = torch.stack([x_sq] * y.size(0), dim=1)
#     y_sq = (y ** 2).mean(-1)
#     y_sq_ = torch.stack([y_sq] * x.size(0), dim=0)
#     xy = torch.mm(x, y.t()) / x.size(-1)
#     dist = x_sq_ + y_sq_ - 2 * x
#     return dist

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


def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


class BasicBlock(nn.Module):
    expansion: int = 1

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        if groups != 1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x: Tensor) -> Tensor:
        identity = 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:
            identity = self.downsample(x)

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

        return out


class Bottleneck(nn.Module):
    # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
    # while original implementation places the stride at the first 1x1 convolution(self.conv1)
    # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
    # This variant is also known as ResNet V1.5 and improves accuracy according to
    # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.

    expansion: int = 4

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x: Tensor) -> Tensor:
        identity = 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:
            identity = self.downsample(x)

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

        return out


class ResNet(nn.Module):

    def __init__(
        self,
        block: Type[Union[BasicBlock, Bottleneck]],
        layers: List[int],
        num_classes: int = 1000,
        zero_init_residual: bool = False,
        groups: int = 1,
        width_per_group: int = 64,
        replace_stride_with_dilation: Optional[List[bool]] = None,
        norm_layer: Optional[Callable[..., nn.Module]] = None
    ) -> None:
        super(ResNet, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 64
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self.groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)


        #add ASTR module
        self.num_classes = num_classes
        self.A = torch.zeros((4,self.num_classes,self.num_classes)).cuda()
        self.Abg = torch.zeros((3,self.num_classes,self.num_classes)).cuda()

        self.old_anchor = torch.zeros((4, self.num_classes, 512)).cuda()
        self.new_anchor = torch.zeros((4, self.num_classes, 512)).cuda()

        self.GCN = GCN(nfeat=512, nhid=1024, nclass=512, dropout=0.1).cuda()

        self.criterion_supcon = SupConLoss(temperature=0.1)
        self.criterion_node = nn.CrossEntropyLoss()
        self.head = nn.Linear(512, 512)

        self.sigma = 0.0
        self.epsilon = 0.0
        self.lamda = 0.0
        self.train_domain_label_list = []

        self.out_features = 512 * block.expansion

        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)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)  # type: ignore[arg-type]
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)  # type: ignore[arg-type]

    def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
                    stride: int = 1, dilate: bool = False) -> nn.Sequential:
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
                            self.base_width, previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups=self.groups,
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))

        return nn.Sequential(*layers)


    def crear_resGCN(self,):
        # import argparse
        # parser_gcn = argparse.ArgumentParser(description='For MiRe DG Classification')
        # # ----------------- Model related
        # parser_gcn.add_argument('--k', default=9, type=int, help='neighbor num (default:9)')
        # parser_gcn.add_argument('--block', default='res', type=str, help='graph backbone block type {res, plain, dense}')
        # parser_gcn.add_argument('--conv', default='edge', type=str, help='graph conv layer {edge, mr}')
        # parser_gcn.add_argument('--act', default='relu', type=str, help='activation layer {relu, prelu, leakyrelu}')
        # parser_gcn.add_argument('--norm', default='batch', type=str,
        #                     help='batch or instance normalization {batch, instance}')
        # parser_gcn.add_argument('--bias', default=True, type=bool, help='bias of conv layer True or False')
        # parser_gcn.add_argument('--n_blocks', type=int, default=28, help='number of basic blocks in the backbone')
        # parser_gcn.add_argument('--n_filters', default=64, type=int, help='number of channels of deep features')
        # parser_gcn.add_argument('--in_channels', type=int, default=3, help='Dimension of input ')
        # parser_gcn.add_argument('--n_classes', type=int, default=40, help='Dimension of out_channels ')
        # parser_gcn.add_argument('--emb_dims', type=int, default=1024, metavar='N', help='Dimension of embeddings')
        # parser_gcn.add_argument('--dropout', type=float, default=0.5, help='dropout rate')
        # # dilated knn
        # parser_gcn.add_argument('--use_dilation', default=True, type=bool, help='use dilated knn or not')
        # parser_gcn.add_argument('--epsilon', default=0.2, type=float, help='stochastic epsilon for gcn')
        # parser_gcn.add_argument('--use_stochastic', default=True, type=bool, help='stochastic for gcn, True or False')
        #
        # args_gcn = parser_gcn.parse_args()
        # args_gcn.device = torch.device('cuda')

        # feats = torch.rand((2, 3, 1024, 1), dtype=torch.float).to(args.device)
        # num_neighbors = 20

        # print('Input size {}'.format(feats.size()))
        net = DeepGCN(opt=None).cuda()
        print('Created resGCN to GPU')

        return net
        # out = net(feats)
        # print(net)
        # print('Output size {}'.format(out.size()))

    def forward(self, x, domain_labels=None, cls_labels=None):
        # See note [TorchScript super()]
        #print(self.training)
        tic = time()
        B = x.size(0)

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

        x = self.layer1(x)



        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)

        loss_CCR = 0.0
        if self.training:
            w = np.zeros((B,self.num_classes))
            for i in range(B):
                for cls in range(self.num_classes):
                    w[i,cls] = torch.exp(self.A[domain_labels[i],cls_labels[i],cls]+torch.cosine_similarity(x[i], self.old_anchor[domain_labels[i],cls,:], dim=0) / 2).item()
            w_sum = w.sum(1)
            w_sum = np.expand_dims(w_sum, 1).repeat(self.num_classes, axis=1)
            w = w/w_sum

            theta = 0.3
            x_new = x.clone()
            for i in range(B):
                x_new[i] = (theta * x[i] + (1-theta) * torch.tensor(np.expand_dims(w[i,cls_labels[i]], 0).repeat(512, axis=0)).cuda() * self.old_anchor[domain_labels[i],cls_labels[i]])
            x = x_new

            # self.new_anchor = self.old_anchor.clone()
            self.new_anchor = self.new_anchor.detach()
            for i in range(B):
                self.new_anchor[domain_labels[i],cls_labels[i]] = (theta * x[i] + (1-theta) * self.old_anchor[domain_labels[i],cls_labels[i]]) #这里改为.data反向传播便不会报错


            loc = 0
            for i in self.train_domain_label_list:
                for j in self.train_domain_label_list:
                    if j <= i:
                        continue
                    else:
                        self.Abg[loc] = (((torch.cosine_similarity(self.old_anchor[domain_labels[i],:,:].unsqueeze(1),self.new_anchor[domain_labels[i],:,:].unsqueeze(0), dim=-1) \
                                            + torch.cosine_similarity(self.old_anchor[domain_labels[j],:,:].unsqueeze(1),self.new_anchor[domain_labels[j],:,:].unsqueeze(0), dim=-1)) / 2) \
                                                * torch.cosine_similarity(self.old_anchor[domain_labels[i],:,:].unsqueeze(1),self.new_anchor[domain_labels[j],:,:].unsqueeze(0),dim=-1))
                        #
                        middle,_ = torch.sort(self.Abg[loc].view(self.num_classes*self.num_classes))
                        middle = middle[int(self.num_classes*self.num_classes/2)]
                        self.Abg[loc] = torch.where(self.Abg[loc]<=middle, torch.zeros_like(self.Abg[loc]), self.Abg[loc])
                        loc += 1

            self.Abg = self.Abg.detach()
            # print(self.Abg[0])


            # new_anchor = new_anchor.detach()

            for i in range(self.Abg.size(0)):
                self.Abg[i] = data_normal_2d(self.Abg[i])

            #if use GCN
            loc = 0
            z_list = []
            for i in self.train_domain_label_list:
                for j in self.train_domain_label_list:
                    if j <= i:
                        continue
                    else:
                        z = self.GCN(torch.cat((self.new_anchor[i],self.new_anchor[j]),dim=0), torch.cat((torch.cat((torch.zeros_like(self.Abg[loc]), self.Abg[loc]),dim=1),torch.cat((self.Abg[loc].t(),torch.zeros_like(self.Abg[loc])),dim=1)),dim=0))
                        z = z[:self.num_classes]
                        z = (z - z.min()) / (z.max() - z.min())
                        z_list.append(z)
                        loc += 1

            #if use anchor directly
            # z_list = []
            # for i in self.train_domain_label_list:
            #     z = self.new_anchor[i]
            #     z = (z - z.min()) / (z.max() - z.min())
            #     z_list.append(z)


            #if use resGCN
            # z_list = []
            # print(self.train_domain_label_list)
            # for i in self.train_domain_label_list:
            #     print(new_anchor.unsqueeze(-1).permute(0,2,1,3).size())
            #     z = self.resGCN(new_anchor.unsqueeze(-1).permute(0,2,1,3))
            #     #z = new_anchor[i]
            #     #print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n !!!!!!!!!!!!!!!!!!!!!!!!')
            #     z = (z - z.min()) / (z.max() - z.min())
            #     z_list.append(z)


            # if use MiRe LossCCR 该过程在OfficeHome上，bs=16时，需要7s+
                    # @jit
            # for i in range(self.num_classes):
            #     for j in range(self.num_classes):
            #         for k in range(z_list.__len__()):
            #             for l in range(z_list.__len__()):
            #                 max_z = 0.0
            #                 if k >= l:
            #                     continue
            #                 else:
            #                     if i == j:
            #                         loss_CCR = loss_CCR + EuclideanDistances(z_list[k][i].unsqueeze(0), z_list[l][j].unsqueeze(0))
            #                     else:
            #                         dis_z = self.epsilon - EuclideanDistances(z_list[k][i].unsqueeze(0), z_list[l][j].unsqueeze(0))
            #                         # print(dis_z)
            #                         # print(EuclideanDistances(z_list[k][i].unsqueeze(0), z_list[l][j].unsqueeze(0)))
            #                         if dis_z > max_z:
            #                             max_z = dis_z
            #                             # print(max_z)
            #                 loss_CCR = loss_CCR + max_z
            #                 loss_CCR = self.lamda * loss_CCR / (self.num_classes*self.num_classes * 3)

            #优化LossCCR计算过程
            tic=time()
            for k in range(z_list.__len__()):
                for l in range(z_list.__len__()):
                    max_z = 0.0
                    if k >= l:
                        continue
                    else:
                        dis_z = EuclideanDistances(z_list[k], z_list[l])
                        dis_samecls = dis_z.diag()
                        dis_diffcls_max = (dis_z - torch.diag_embed(dis_samecls)).max()
                        # dis_diffcls = (dis_diffcls - dis_diffcls.min()) / (dis_diffcls.max() - dis_diffcls.min())
                        if (self.epsilon - dis_diffcls_max) < 0.0:
                            dis_diffcls_max = 0.0
                        else:
                            dis_diffcls_max = self.epsilon - dis_diffcls_max
                        loss_CCR = loss_CCR + dis_z.mean() + dis_diffcls_max
                        # print(dis_z.mean(), dis_diffcls_max)

            loss_CCR = self.lamda * loss_CCR / (3)
            # print('max,{:f}'.format(dis_diffcls.max()))
            # print(loss_CCR)
            # print(time()-tic)

            # if use supconloss
            # anchor_labels = torch.tensor((0,1,2,3,4,5,6)).float().cuda()
            # for k in range(z_list.__len__()):
            #     for l in range(z_list.__len__()):
            #         if k >= l:
            #             continue
            #         else:
            #             features = torch.cat([z_list[k].unsqueeze(1), z_list[k].unsqueeze(1)], dim=1)
            #             # features = F.normalize(features, dim=1)
            #             loss_CCR = loss_CCR + self.criterion_supcon(features, anchor_labels)
            #             loss_CCR = loss_CCR / 3
            #

            # if use node classification loss
            # anchor_labels = torch.tensor((0,1,2,3,4,5,6,0,1,2,3,4,5,6)).long().cuda()
            # for i in range(z_list.__len__()):
            #     loss_CCR = loss_CCR + self.criterion_node(z_list[i], anchor_labels)
            #     loss_CCR = loss_CCR / 3





        self.old_anchor = self.new_anchor.detach()
        # print(loss_CCR)
        x = self.fc(x)

        return x, loss_CCR


def _resnet(
    arch: str,
    block: Type[Union[BasicBlock, Bottleneck]],
    layers: List[int],
    pretrained: bool,
    progress: bool,
    **kwargs: Any
) -> ResNet:
    model = ResNet(block, layers, **kwargs)
    if pretrained:
        state_dict = model_zoo.load_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict, strict=False)
    return model

@BACKBONE_REGISTRY.register()
def mire_resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-18 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
                   **kwargs)


def resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-34 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)


def resnet50(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-50 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)


def resnet101(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-101 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
                   **kwargs)


def resnet152(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNet-152 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
                   **kwargs)


def resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNeXt-50 32x4d model from
    `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 4
    return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
                   pretrained, progress, **kwargs)


def resnext101_32x8d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""ResNeXt-101 32x8d model from
    `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 8
    return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
                   pretrained, progress, **kwargs)


def wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""Wide ResNet-50-2 model from
    `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.

    The model is the same as ResNet except for the bottleneck number of channels
    which is twice larger in every block. The number of channels in outer 1x1
    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
    channels, and in Wide ResNet-50-2 has 2048-1024-2048.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['width_per_group'] = 64 * 2
    return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
                   pretrained, progress, **kwargs)


def wide_resnet101_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
    r"""Wide ResNet-101-2 model from
    `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.

    The model is the same as ResNet except for the bottleneck number of channels
    which is twice larger in every block. The number of channels in outer 1x1
    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
    channels, and in Wide ResNet-50-2 has 2048-1024-2048.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['width_per_group'] = 64 * 2
    return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
                   pretrained, progress, **kwargs)
