import math
import torch
import torch.nn.functional as F
from fairseq import utils

from . import FairseqCriterion, register_criterion


def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):
    if target.dim() == lprobs.dim() - 1:
        target = target.unsqueeze(-1)
    nll_loss = -lprobs.gather(dim=-1, index=target)
    smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
    if ignore_index is not None:
        non_pad_mask = target.ne(ignore_index)
        nll_loss = nll_loss[non_pad_mask]
        smooth_loss = smooth_loss[non_pad_mask]
    else:
        nll_loss = nll_loss.squeeze(-1)
        smooth_loss = smooth_loss.squeeze(-1)
    if reduce:
        nll_loss = nll_loss.sum()
        smooth_loss = smooth_loss.sum()
    eps_i = epsilon / lprobs.size(-1)
    loss = (1. - epsilon) * nll_loss + eps_i * smooth_loss
    return loss, nll_loss


@register_criterion('label_smoothed_cross_entropy')
class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):

    def __init__(self, args, task):
        super().__init__(args, task)
        self.eps = args.label_smoothing

    @staticmethod
    def add_args(parser):
        """Add criterion-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('--label-smoothing', default=0.1, type=float, metavar='D',
                            help='epsilon for label smoothing, 0 means no label smoothing')
        # fmt: on
    
    def forward(self, model, sample, reduce=True):
        """Compute the loss for the given sample.

        Returns a tuple with three elements:
        1) the loss
        2) the sample size, which is used as the denominator for the gradient
        3) logging outputs to display while training
        """
        net_output = model(**sample['net_input'])
        try:
            self.epoch = sample['epoch'] if 'epoch' in sample else 0
        except:
            self.epoch = 100
        loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce)
        sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
        logging_output = {
            'loss': utils.item(loss.data) if reduce else loss.data,
            'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data,
            'ntokens': sample['ntokens'],
            'nsentences': sample['target'].size(0),
            'sample_size': sample_size,
        }
        return loss, sample_size, logging_output
    def compute_loss(self, model, net_output, sample, reduce=True):
        epoch=self.epoch
        logits = net_output[0]  # 获取logits
        logits_text_only=net_output[2]
        lprobs_mmt = model.get_normalized_probs((net_output[0],), log_probs=True)
        lprobs_nmt = model.get_normalized_probs((net_output[2],), log_probs=True)
        target = model.get_targets(sample, net_output)
        logits = F.relu(logits)
        logits_text_only = F.relu(logits_text_only)
        
        # 将 logits 转换为 alpha (logits + 1)
        alpha = logits + 1
        alpha_text_only=logits_text_only+1
        target_alpha = torch.gather(alpha[0], 1, target[0].unsqueeze(1)).squeeze()
        # print("max_alpha=", torch.max(alpha[0]))
        # print("target_alpha=", target_alpha)
        target_one_hot = F.one_hot(target, num_classes=logits.size(-1)).float()
        probs = alpha / torch.sum(alpha, dim=-1, keepdim=True)
        # (Error Term)
        error_term = torch.sum(torch.square(target_one_hot - probs), dim=-1)
        #  S
        S = torch.sum(alpha, dim=-1, keepdim=True)
        S_text=torch.sum(alpha_text_only, dim=-1, keepdim=True)
        #  U = K / S
        K = logits.size(-1)
        K_text=logits_text_only.size(-1)
        uncertainty = K / S.squeeze(-1)  
        uncertainty_text_only=K_text/S_text.squeeze(-1)
        variance_term = torch.sum(
            (probs * (1 - probs)) / (S + 1),
            dim=-1
        )
        ratio = uncertainty / (uncertainty_text_only + 1e-8)
        diff = F.relu(ratio - 1.0)
        diff= F.relu(uncertainty-uncertainty_text_only)
        diff=torch.sum(diff)
        dir_loss = error_term+variance_term
        # print("diff:",diff)
        # print("uncertainty=",torch.sum(uncertainty))
        # print("TEXT_uncertainty=",torch.sum(uncertainty_text_only))
        dir_loss = torch.sum(dir_loss)
        uncertainty=torch.sum(uncertainty)
        lprobs = model.get_normalized_probs(net_output, log_probs=True)
        lprobs = lprobs.view(-1, lprobs.size(-1))
        target = model.get_targets(sample, net_output).view(-1, 1)
        annealing_rate=min(1.0,epoch/60)
        loss, nll_loss = label_smoothed_nll_loss(
            lprobs, target, self.eps, ignore_index=self.padding_idx, reduce=reduce,
        )
        uncertainty_text_only=torch.sum(uncertainty_text_only)
        total_epochs=40
        lambda_d = max(1 - (epoch>total_epochs),0)
        loss =loss+uncertainty+ 0.5*dir_loss+1*lambda_d*diff
        return loss, nll_loss
    @staticmethod
    def aggregate_logging_outputs(logging_outputs):
        """Aggregate logging outputs from data parallel training."""
        ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)
        nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)
        sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)
        return {
            'loss': sum(log.get('loss', 0) for log in logging_outputs) / sample_size / math.log(2) if sample_size > 0 else 0.,
            'nll_loss': sum(log.get('nll_loss', 0) for log in logging_outputs) / ntokens / math.log(2) if ntokens > 0 else 0.,
            'ntokens': ntokens,
            'nsentences': nsentences,
            'sample_size': sample_size,
        }

       