import argparse
import os
import random
import shutil
import time
from torch.autograd import Variable

import warnings
import copy 
import datetime
from sqlalchemy import true
import torchvision.datasets as dset
from datasets import ImagenetNoise
from networks import Ensemble  
from utils import check_dir, prepare_dset, update_print, get_relative_maha_distance, maha, \
    get_pretrained_model, get_maha_distance, MahaDistNormalizer, ranking_loss, LogitsMinMax
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision
import torch.nn.functional as F
import numpy as np
import pickle
from torch.utils.tensorboard import SummaryWriter


model_names = sorted(name for name in models.__dict__
                     if name.islower() and not name.startswith("__")
                     and callable(models.__dict__[name]))

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--maha_file', default='./ssl/maha_dict.npy', type=str)
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet34')
parser.add_argument('--pretrained', default='', type=str,
                    help='path to moco pretrained checkpoint')
parser.add_argument('--pretrained_model', default='vit', type=str, help='SSL feature map type')
parser.add_argument('--comp_dis', action='store_true', default=False)
parser.add_argument('--net', default='resnet34', type=str)

parser.add_argument('--loss_type', default='rank0', type=str, help='rank0/margin_rank')
parser.add_argument('--rank_weight', default=1.0, type=float, help='ranking loss weight')
parser.add_argument('--e_lambda', default=0.3, type=float, help='entropy weight')
parser.add_argument('--warmup', default=-1, type=int)
parser.add_argument('--rank_epo', default=-1, type=int)

parser.add_argument('--gpu', default='0', type=str)
parser.add_argument('--dataset', default='imagenet', type=str, help='cifar10/cifar100')
parser.add_argument('--left', default=1.0, type=float)
parser.add_argument('--right', default=1.0, type=float)
parser.add_argument('--T', default=1.0, type=float)

parser.add_argument('--epsilon_p', default=2.0, type=float)
parser.add_argument('--data',
                    metavar='DIR',
                    default='/data/LargeData/Large/ImageNet',
                    help='path to dataset')
parser.add_argument('--lr',
                    '--learning-rate',
                    default=0.1,
                    type=float,
                    metavar='LR',
                    help='initial learning rate',
                    dest='lr')
parser.add_argument('-j',
                    '--workers',
                    default=4,
                    type=int,
                    metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs',
                    default=120,
                    type=int,
                    metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch',
                    default=0,
                    type=int,
                    metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b',
                    '--batch-size',
                    default=512,
                    type=int,
                    metavar='N',
                    help='mini-batch size (default: 3200), this is the total '
                    'batch size of all GPUs on the current node when '
                    'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--momentum',
                    default=0.9,
                    type=float,
                    metavar='M',
                    help='momentum')
parser.add_argument('--local_rank',
                    default=-1,
                    type=int,
                    help='node rank for distributed training')
parser.add_argument('--wd',
                    '--weight-decay',
                    default=1e-4,
                    type=float,
                    metavar='W',
                    help='weight decay (default: 1e-4)',
                    dest='weight_decay')
parser.add_argument('-p',
                    '--print-freq',
                    default=80,
                    type=int,
                    metavar='N',
                    help='print frequency (default: 10)')
parser.add_argument('-e',
                    '--evaluate',
                    dest='evaluate',
                    action='store_true',
                    help='evaluate model on validation set')
parser.add_argument('--seed',
                    default=None,
                    type=int,
                    help='seed for initializing training. ')

parser.add_argument('--epsilon',
                    default=1.0,
                    type=float,
                    help='Coefficient of Label Smoothing')

parser.add_argument('--alpha',
                    default=0.05,
                    type=float,
                    help='Coefficient of L1 Norm')

parser.add_argument('--fgamma',
                    default=1.0,
                    type=float,
                    help='Coefficient of Focal Loss')
parser.add_argument('--method', default='ce', type=str, help='ce, ls, l1, focal')

parser.add_argument('--ynoise_type', default='symmetric', type=str, help='symmetric/pairflip')
parser.add_argument('--ynoise_rate', default=0.0, type=float, help='label noise rate')
parser.add_argument('--xnoise_rate', default=0.0, type=float)
parser.add_argument('--xnoise_type', default='contrast', type=str)
parser.add_argument('--xnoise_arg', default=5, type=str)

parser.add_argument('--ensemble_num', default=1, type=int, help="number of model to ensumble")
parser.add_argument('--random_state', type=int, default=0)
parser.add_argument('--num_classes', type=int, default=1000)
parser.add_argument('--stop', type=int, default=1000)


def reduce_mean(tensor, nprocs):
    rt = tensor.clone()
    dist.all_reduce(rt, op=dist.ReduceOp.SUM)
    rt /= nprocs
    return rt



def main():
    args = parser.parse_args()
    args.nprocs = torch.cuda.device_count()
    filename =  args.net +'_deep_ens'+str(args.ensemble_num) + '_'+ args.dataset \
            + '_' + args.arch + '_' + args.loss_type
    check_dir('./checkpoint')
    base_dir = os.path.join('./checkpoint', 'deep_ens')
    check_dir(base_dir)
    args_root = os.path.join(base_dir, filename + '_args.pkl')
    print('Saving args to '+ args_root)
    # pickle.dump(args, open(args_root, 'wb'))
    torch.save(args, args_root)
    print(args)
    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')
    main_worker(args.local_rank, args.nprocs, args)


def main_worker(local_rank, nprocs, args):
    best_acc1 = .0

    dist.init_process_group(backend='nccl')
    # # create model
    # if args.pretrained:
    #     print("=> using pre-trained model '{}'".format(args.arch))
    #     model = models.__dict__[args.arch](pretrained=True)
    # else:
    #     print("=> creating model '{}'".format(args.arch))
    #     model = models.__dict__[args.arch]()
    if args.ensemble_num > 1:
        model = Ensemble(args.ensemble_num, args.num_classes) # use resnet 18
    else:
        if args.net == 'resnet18':
            model = torchvision.models.resnet18(num_classes=args.num_classes)
        if args.net == 'resnet34':
            model = torchvision.models.resnet34(num_classes=args.num_classes)
        if args.net == 'resnet50':
            model = torchvision.models.resnet50(num_classes=args.num_classes)
        if args.net == 'resnet101':
            model = torchvision.models.resnet101(num_classes=args.num_classes)
        if args.net == 'densenet121':
            model = torchvision.models.densenet.densenet121(num_classes=args.num_classes)
    torch.cuda.set_device(local_rank)
    model.cuda(local_rank)
    # When using a single GPU per process and per
    # DistributedDataParallel, we need to divide the batch size
    # ourselves based on the total number of GPUs we have
    args.batch_size = int(args.batch_size / nprocs)
    model = torch.nn.parallel.DistributedDataParallel(model,
                                                      device_ids=[local_rank])

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda(local_rank)

    # ranking loss setting
    if args.loss_type.startswith('rank0'):
        rank_criterion = nn.MarginRankingLoss().cuda(local_rank)
    else:
        rank_criterion = ranking_loss().cuda(local_rank)
    
    
    pretrain_model = get_pretrained_model(args).cuda()
    if not args.arch.startswith('clip'):
        pretrain_model.cuda(local_rank)
        pretrain_model = torch.nn.parallel.DistributedDataParallel(pretrain_model,
                                                        device_ids=[local_rank])
    pretrain_model.eval()
    # load parameters of Gaussian distributed
    maha_intermediate_dict = np.load(args.maha_file, allow_pickle='TRUE')
    class_cov_invs = maha_intermediate_dict.item()['class_cov_invs']
    class_means = maha_intermediate_dict.item()['class_means']
    cov_invs = maha_intermediate_dict.item()['cov_inv']
    means = maha_intermediate_dict.item()['mean']

    optimizer = torch.optim.SGD(model.parameters(),
                                args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay)

    cudnn.benchmark = True

    # Data loading code
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])

    train_dataset = ImagenetNoise(
        transform=transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]),
        xnoise_rate=args.xnoise_rate,
        xnoise_arg=args.xnoise_arg,
        xnoise_type=args.xnoise_type,
        ynoise_type=args.ynoise_type,
        ynoise_rate=args.ynoise_rate,
        random_state=args.random_state,
        num_classes=args.num_classes
    )
    if local_rank == 0:
        train_dataset.report_noise()
    train_sampler = torch.utils.data.distributed.DistributedSampler(
        train_dataset)
    train_loader = torch.utils.data.DataLoader(train_dataset,
                                               batch_size=args.batch_size,
                                               num_workers=2,
                                               pin_memory=True,
                                               sampler=train_sampler)
    metric_dataset = copy.deepcopy(train_dataset)
    metric_dataset.transform = transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ])

    val_dataset = ImagenetNoise(
        train=False,
        transform=transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ]),
        num_classes=args.num_classes
    )
    val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset)
    val_loader = torch.utils.data.DataLoader(val_dataset,
                                             batch_size=args.batch_size,
                                             num_workers=2,
                                             pin_memory=True,
                                             sampler=val_sampler)

    # scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs), 1e-5)
    if args.evaluate:
        validate(val_loader, model, criterion, local_rank, args)
        return

    for epoch in range(args.start_epoch, args.epochs):
        if epoch > args.stop: break
        train_sampler.set_epoch(epoch)
        val_sampler.set_epoch(epoch)

        adjust_learning_rate(optimizer, epoch, args)

        # train for one epoch
        train(train_loader, model, pretrain_model, criterion, rank_criterion, optimizer, epoch, local_rank,
              args,class_cov_invs, class_means, cov_invs, means)
        # scheduler.step()

        # evaluate on validation set
        acc1 = validate(val_loader, model, criterion, local_rank, args)

        # remember best acc@1 and save checkpoint
        filename =  args.net +'_deep_ens'+str(args.ensemble_num) + '_'+ args.dataset \
            + '_' + args.arch + '_' + args.loss_type
        is_best = acc1 > best_acc1
        best_acc1 = max(acc1, best_acc1)
        if args.local_rank == 0 and epoch<=130:
            save_checkpoint(
                {
                    'epoch': epoch + 1,
                    'arch': args.arch,
                    'net': model.module.state_dict(),
                    'acc': best_acc1,
                }, is_best, filename)

        # if epoch % args.save_period == 0:
        #     eval_metric(metric_loader, model, epoch, local_rank, args)
    print('Best Acc1:', best_acc1)

class weighted_ce(nn.Module):
    def __init__(self):
        super(weighted_ce, self).__init__()
    
    def forward(self,x_input, y_target, weight):
        # print(rank_input1)
        weight = weight.reshape(-1, 1)
        x_input = F.log_softmax(x_input, 1)
        y_target = F.one_hot(y_target, num_classes=1000)
        loss = -torch.sum(x_input * y_target, 1)
        # print(loss.shape)
        # print(loss)
        loss = torch.mean(loss * weight)

        return loss



def ECELoss(logits, labels, n_bins = 15):
    """
    Calculates the Expected Calibration Error of a model.
    (This isn't necessary for temperature scaling, just a cool metric).
    The input to this loss is the logits of a model, NOT the softmax scores.
    This divides the confidence outputs into equally-sized interval bins.
    In each bin, we compute the confidence gap:
    bin_gap = | avg_confidence_in_bin - accuracy_in_bin |
    We then return a weighted average of the gaps, based on the number
    of samples in each bin
    See: Naeini, Mahdi Pakdaman, Gregory F. Cooper, and Milos Hauskrecht.
    "Obtaining Well Calibrated Probabilities Using Bayesian Binning." AAAI.
    2015.
    """

    bin_boundaries = torch.linspace(0, 1, n_bins + 1)
    bin_lowers = bin_boundaries[:-1]
    bin_uppers = bin_boundaries[1:]
    softmaxes = F.softmax(logits, dim=1)
    confidences, predictions = torch.max(softmaxes, 1)
    accuracies = predictions.eq(labels)
    ece = torch.zeros(1, device=logits.device)
    for bin_lower, bin_upper in zip(bin_lowers, bin_uppers):
        # Calculated |confidence - accuracy| in each bin
        in_bin = confidences.gt(bin_lower.item()) * confidences.le(bin_upper.item())
        prop_in_bin = in_bin.float().mean()
        if prop_in_bin.item() > 0:
            accuracy_in_bin = accuracies[in_bin].float().mean()
            avg_confidence_in_bin = confidences[in_bin].mean()
            ece += torch.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin

    return ece
 
class entropy_ce(nn.Module):
    def __init__(self):
        super(entropy_ce, self).__init__()
    
    def forward(self,x_input, y_target, e_lambda):
        p = F.softmax(x_input)
        # p = p.detach()
        # print(weight.shape)
        entropy = - torch.sum(p * F.log_softmax(x_input), dim=1).reshape(-1,1)
        
        
        x_input = F.log_softmax(x_input, 1)
        y_target = F.one_hot(y_target, num_classes=1000)
        loss = - torch.sum(x_input * y_target, 1)
        loss = (1-e_lambda) * torch.mean(loss) -  e_lambda * torch.mean(entropy)

        return loss
        
class weighted_binary_entropy_ce(nn.Module):
    def __init__(self):
        super(weighted_binary_entropy_ce, self).__init__()
    
    def forward(self,x_input, y_target, weight, e_lambda):
        weight = weight.reshape(-1, 1)
        # print(weight.shape)
        p = F.softmax(x_input)
        # logp = F.log_softmax(x_input)
        y_target = F.one_hot(y_target, num_classes=1000)

        # p = p.detach()
        pt = torch.sum(p * y_target, dim=1) + 1e-4
        # logpt=  torch.sum(logp * y_target, dim=1)
        entropy = - (pt* torch.log(torch.clamp(pt,min=1e-5)) + torch.log(torch.clamp(1-pt,min=1e-5)) * (1- pt)).reshape(-1,1)
        # entropy = - torch.sum(p * F.log_softmax(x_input), dim=1).reshape(-1,1)
        # print(entropy)
        # print(rank_input1)
        

        weight_beta = e_lambda * weight
        # weight_1 = torch.ones_like(weight_beta) - weight_beta
        entropy = weight_beta * entropy
        # print(entropy)
        
        x_input = F.log_softmax(x_input, 1)
        loss = - torch.sum( x_input * y_target, 1)
        loss = torch.mean(loss) -  torch.mean(entropy)
        # print(loss)

        return loss

class weighted_entropy_ce(nn.Module):
    def __init__(self):
        super(weighted_entropy_ce, self).__init__()
    
    def forward(self,x_input, y_target, weight, e_lambda):
        weight = weight.reshape(-1, 1)
        # print(weight.shape)
        p = F.softmax(x_input)
        # p = p.detach()
        entropy = - torch.sum(p * F.log_softmax(x_input), dim=1).reshape(-1,1)
        # print(entropy.shape)
        # print(rank_input1)
        

        weight_beta = e_lambda * weight
        # weight_1 = torch.ones_like(weight_beta) - weight_beta
        entropy = weight_beta * entropy
        # print(entropy)
        
        x_input = F.log_softmax(x_input, 1)
        y_target = F.one_hot(y_target, num_classes=1000)
        loss = - torch.sum( x_input * y_target, 1)
        loss = torch.mean(loss) -  torch.mean(entropy)
        # print(loss)

        return loss

class weighted_poly(nn.Module):
    def __init__(self):
        super(weighted_poly, self).__init__()
    
    def forward(self, x_input, y_target, weight):
        weight = weight.reshape(-1, 1)
        # print(weight.shape)
        p = F.softmax(x_input)
        y_target = F.one_hot(y_target, num_classes=1000)
        # p = p.detach()
        pt = torch.sum(p * y_target, dim=1).reshape(-1,1)
        poly_loss = weight * (1. - pt)
        
        x_input = F.log_softmax(x_input, 1)
        
        ce_loss = - torch.sum( x_input * y_target, 1)
        loss = torch.mean(ce_loss + poly_loss)
        # print(loss)

        return loss



n_iter = 0

def softmax(X):
    X -= X.max()
    X_exp = X.exp()
    max = X_exp.max() + 0.001
    # partition = X_exp.sum(dim=1, keepdim=True)
    #print("X size is ", X_exp.size())
    #print("partition size is ", partition, partition.size())
    return X_exp / max  

def train(train_loader, model, pretrain_model, criterion, rank_criterion, optimizer, epoch, local_rank, args, \
    class_cov_invs, class_means, cov_invs, means):
    maha_normalizer = MahaDistNormalizer()
    maha_normalizer1 = MahaDistNormalizer()
    logit_minmax = LogitsMinMax()
    batch_time = AverageMeter('Time', ':6.3f')
    data_time = AverageMeter('Data', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    progress = ProgressMeter(len(train_loader),
                             [batch_time, data_time, losses, top1, top5],
                             prefix="Epoch: [{}]".format(epoch))

    # switch to train mode
    model.train()

    end = time.time()
    for i, (_, (images, xnoisy), (target, true_tar)) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)
        target_bi = torch.zeros(images.size(0), args.num_classes).scatter_(1, target.view(-1,1).long(), 1)
        target_bi = target_bi.cuda(local_rank, non_blocking=True)

        images = images.cuda(local_rank, non_blocking=True)
        target = target.cuda(local_rank, non_blocking=True)

        # compute output
        outputs = model(images)
        # loss = criterion(output, target)
        optimizer.zero_grad()
        
        if epoch > args.warmup:
            # max_logits, _ = torch.max(outputs,1)
            # conf = F.softmax(outputs, dim=1)
            # entropy = -torch.sum(conf * torch.log(conf), dim=1)
            # l_min,l_max = logit_minmax.run(max_logits.cpu().data.numpy())
            # l_min,l_max = max_logits.cpu().data.numpy().min(), max_logits.cpu().data.numpy().max()
            # print(l_min,l_max)
            with torch.no_grad():
                if args.arch.startswith('clip'):
                    if args.arch == 'clip_r50':
                        # print('111111111111')
                        pre_feature = pretrain_model.encode_image(images)
                    elif args.arch == 'clip_r101':
                        pre_feature = pretrain_model.encode_image(images)
                    else:
                        pre_feature = pretrain_model.get_image_features(images)
                else:
                    pre_feature = pretrain_model(images)
                # maha_distance = get_maha_distance(pre_feature.cpu().data.numpy(),class_cov_invs, \
                #     class_means, target.cpu().data.numpy())
                if args.arch.startswith('hug'):
                    pre_feature = pre_feature.logits.cpu().data.numpy()
                else:
                    pre_feature = pre_feature.cpu().data.numpy()
                maha_distance = get_relative_maha_distance(pre_feature,cov_invs, \
                    class_cov_invs, means, class_means, target.cpu().data.numpy())
                maha_distance = torch.from_numpy(maha_distance)
                # print(maha_distance.shape)
                # maha_distance_normalized = F.softmax(maha_distance/args.T,dim=0)
                # maha_distance_normalized = maha_normalizer.run(maha_distance, -1., 1.)
                maha_distance_normalized = maha_normalizer.run(maha_distance, -args.left, args.right)
                # maha_distance_normalized = F.softmax(maha_distance_normalized/args.T,dim=0)
                maha_distance_normalized = softmax(maha_distance_normalized/args.T)
                # print('min',torch.sort(maha_distance_normalized,dim=0)[0][0:10])
                # print('max',torch.sort(maha_distance_normalized,dim=0)[0][-10:-1])
                # print(maha_distance_normalized.shape)
                # maha_distance_normalized = maha_normalizer.run(maha_distance,6,10)
                # maha_distance_normalized = maha_normalizer.run(maha_distance,l_min,l_min+(l_max-l_min)/2.)
                maha_distance_normalized1 = torch.roll(maha_distance_normalized,-1)
                maha_margin = (maha_distance_normalized - maha_distance_normalized1).squeeze()
                maha_distance1 = torch.roll(maha_distance, -1)
                target_rank = torch.randn(outputs.shape[0])
                target_flag = (maha_distance < maha_distance1)

                for j in range(len(target_flag)):
                    if target_flag[j]:
                        target_rank[j] = 1
                    else:
                        target_rank[j] = -1
            # criterion1 = nn.CrossEntropyLoss().cuda(local_rank)
            if args.method == 'baer':
                criterion = weighted_binary_entropy_ce().cuda(local_rank)
                maha_weight = maha_distance_normalized.cuda(local_rank, non_blocking=True)
                # maha_weight = (torch.ones_like(maha_distance_normalized) - maha_distance_normalized).cuda(local_rank, non_blocking=True)
                # maha_weight = (torch.ones_like(maha_distance_normalized)).cuda(local_rank, non_blocking=True)
                ce_loss = criterion(outputs, target, maha_weight, args.e_lambda)

            if args.method == 'aer':
                criterion = weighted_entropy_ce().cuda(local_rank)
                maha_weight = maha_distance_normalized.cuda(local_rank, non_blocking=True)
                # maha_weight = (torch.ones_like(maha_distance_normalized) - maha_distance_normalized).cuda(local_rank, non_blocking=True)
                # maha_weight = (torch.ones_like(maha_distance_normalized)).cuda(local_rank, non_blocking=True)
                ce_loss = criterion(outputs, target, maha_weight, args.e_lambda)
            if args.method == 'w_poly':
                criterion = weighted_poly().cuda(local_rank)
                maha_weight = (0. - maha_distance_normalized).cuda(local_rank, non_blocking=True)
                ce_loss = criterion(outputs, target, maha_weight)
            
            if args.method == 'w_el':
                criterion = weighted_el().cuda(local_rank)
                # maha_weight = maha_distance_normalized.cuda(local_rank, non_blocking=True)
                maha_weight = (torch.ones_like(maha_distance_normalized) - maha_distance_normalized).cuda(local_rank, non_blocking=True)
                ce_loss = criterion(outputs, target, maha_weight)

        else:
            criterion = nn.CrossEntropyLoss().cuda(local_rank)
            if args.method == 'ce':
                ce_loss = criterion(outputs, target)
            elif args.method == 'ls':
                epsilon = args.epsilon
                target_bi_smooth = (1.0 - epsilon) * target_bi + epsilon/args.num_classes
                ce_loss = -torch.mean(torch.sum(torch.nn.functional.log_softmax(outputs, dim=1) * target_bi_smooth, dim=1)) ####################Label Smoothing

            elif args.method == 'l1':
                loss_cla = criterion(outputs, target)
                loss_f1_norm = torch.mean(torch.norm(outputs,p=1,dim=1))
                ce_loss = loss_cla + args.alpha * loss_f1_norm  ########################## L1 Norm

            elif args.method == 'focal':
                target_var = target.view(-1,1)
                logpt = torch.nn.functional.log_softmax(outputs, dim=1)
                logpt = logpt.gather(1,target_var)
                logpt = logpt.view(-1)
                pt = Variable(logpt.exp().data)
                weights = (1-pt)**(args.fgamma)
                ce_loss = -torch.mean(weights * logpt)   ################################## Focal Loss
            elif args.method == 'entropy':
                criterion = entropy_ce().cuda(local_rank)
                # criterion = nn.CrossEntropyLoss().cuda(local_rank)
                ce_loss = criterion(outputs, target, args.e_lambda)
            elif args.method == 'poly':
                p = F.softmax(outputs)
                x_input = F.log_softmax(outputs, 1)
                y_target = F.one_hot(target, num_classes=1000)
                pt = torch.sum(p * y_target, dim=1)
                ce_loss = - torch.sum( x_input * y_target, 1)
        
                # Pick out the probabilities of the actual class                
                # Compute the plain cross entropy
                # ce_loss = -1 * pt.log()
                
                # Compute the contribution of the poly loss
                # poly_loss = 0
                poly_loss = args.epsilon_p * (1. - pt)
                # for j in range(args.N, args.N):
                    # poly_loss += args.epsilon[j - 1] * ((1 - pt) ** j) / j
                
                ce_loss = torch.mean(ce_loss + poly_loss)

        if args.ensemble_num > 1:
            for net_idx in range(args.ensemble_num):
                loss = criterion(outputs[net_idx], target)  # Loss
                loss.backward()
        else:
            loss = ce_loss
            loss.backward()
        optimizer.step()
        # # compute gradient and do SGD step
        # optimizer.zero_grad()
        # loss.backward()
        # optimizer.step()

        # measure accuracy and record loss
        if args.ensemble_num > 1:
            mean_output = F.softmax(torch.stack(outputs),dim=-1).mean(dim=0)
        else:
            mean_output = outputs 
        acc1, acc5 = accuracy(mean_output, target, topk=(1, 5))

        torch.distributed.barrier()
        # reduced_rank_loss = reduce_mean(ranking_loss, args.nprocs)
        reduced_loss = reduce_mean(loss, args.nprocs)
        reduced_acc1 = reduce_mean(acc1, args.nprocs)
        reduced_acc5 = reduce_mean(acc5, args.nprocs)

        losses.update(reduced_loss.item(), images.size(0))
        top1.update(reduced_acc1.item(), images.size(0))
        top5.update(reduced_acc5.item(), images.size(0))

        # measure elapsed time
        batch_time.update(time.time() - end)
        end = time.time()
        

        if i % args.print_freq == 0:
            
            progress.display(i)
    
def validate(val_loader, model, criterion, local_rank, args):
    batch_time = AverageMeter('Time', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    # ece = AverageMeter('ECE', ':6.2f')
    progress = ProgressMeter(len(val_loader), [batch_time, losses, top1, top5],
                             prefix='Test: ')

    # switch to evaluate mode
    model.eval()
    logits_list = []
    labels_list = []

    with torch.no_grad():
        end = time.time()
        for i, (_, images, target) in enumerate(val_loader):
            images = images.cuda(local_rank, non_blocking=True)
            target = target.cuda(local_rank, non_blocking=True)

            # compute output
            output = model(images)
            if args.ensemble_num > 1:
                mean_output = F.softmax(torch.stack(output),dim=-1).mean(dim=0)
            else:
                mean_output = output 
            
            # logits and labels for calculating ECE
            batch_logits = [torch.zeros_like(mean_output) for _ in range(args.nprocs)]
            dist.all_gather(batch_logits, mean_output)
            logits_list.extend(batch_logits)

            batch_labels = [torch.zeros_like(target) for _ in range(args.nprocs)]
            dist.all_gather(batch_labels, target)
            labels_list.extend(batch_labels)

            
            loss = criterion(mean_output, target)
            
            

            # measure accuracy and record loss
            acc1, acc5 = accuracy(mean_output, target, topk=(1, 5))

            torch.distributed.barrier()

            reduced_loss = reduce_mean(loss, args.nprocs)
            reduced_acc1 = reduce_mean(acc1, args.nprocs)
            reduced_acc5 = reduce_mean(acc5, args.nprocs)

            losses.update(reduced_loss.item(), images.size(0))
            top1.update(reduced_acc1.item(), images.size(0))
            top5.update(reduced_acc5.item(), images.size(0))

            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            if i % args.print_freq == 0:
                progress.display(i)
        # calulate ECE
        
        # print(len(logits_list))
        logits = torch.cat(logits_list, 0)
        labels = torch.cat(labels_list,0)
        # print(logits.shape, labels.shape)
        ece = ECELoss(logits, labels)
        # print(ece)

        # TODO: this should also be done with the ProgressMeter
        print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f} ECE {ECE:.3f}'.format(top1=top1,
                                                                    top5=top5, ECE=ece.item()))

    return top1.avg

def save_checkpoint(state, is_best, filename):
    
    if is_best:
        save_point = 'checkpoint'
        check_dir(save_point)
        base_dir = os.path.join(save_point, "deep_ens")
        check_dir(base_dir)
        save_path = os.path.join(base_dir, filename + '.pkl')
        print('Save Model to', save_path)
        torch.save(state, save_path)


class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self, name, fmt=':f'):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
        return fmtstr.format(**self.__dict__)


class ProgressMeter(object):
    def __init__(self, num_batches, meters, prefix=""):
        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
        self.meters = meters
        self.prefix = prefix

    def display(self, batch):
        entries = [self.prefix + self.batch_fmtstr.format(batch)]
        entries += [str(meter) for meter in self.meters]
        print('\t'.join(entries))

    def _get_batch_fmtstr(self, num_batches):
        num_digits = len(str(num_batches // 1))
        fmt = '{:' + str(num_digits) + 'd}'
        return '[' + fmt + '/' + fmt.format(num_batches) + ']'


def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    lr = args.lr * (0.1**(epoch // 30))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr


def accuracy(output, target, topk=(1, )):
    """Computes the accuracy over the k top predictions for the specified values of k"""
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res


if __name__ == '__main__':
    main()