# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# import math
# import torch
# import torch.nn.functional as F
# from fairseq import utils
# from fairseq.criterions import FairseqCriterion, register_criterion

# @register_criterion('dirichlet_criterion')
# class DirichletCriterionOptimized(FairseqCriterion):
#     def __init__(self, args, task, annealing_step=10000):
#         super().__init__(args, task)
#         self.annealing_step = annealing_step
#         self.step = 0

#     def compute_loss(self, model, net_output, sample, reduce=True):
#         # 1. 初始化和维度检查
#         epoch = getattr(model, 'epoch', 0)
#         annealing_coef = min(1.0, epoch / 20)  # 线性调度
#         evidence = net_output[0]  # [B, T, V]
#         max_evidence = 50.0 * (1 - annealing_coef) + 10.0 * annealing_coef
#         evidence = torch.clamp(evidence, min=1e-10, max=max_evidence)
#         alpha = evidence + 1
#         target = model.get_targets(sample, net_output).view(-1)

#         B, T, V = evidence.size(0), evidence.size(1), evidence.size(2)
#         device = alpha.device
#         k = 10  # 设置Top-K为10

#         # 2. 获取Top-K的值和索引
#         top_k_alpha, top_k_indices = torch.topk(alpha, k, dim=-1)  # [B, T, k]

#         # 3. 生成one-hot，标记目标是否在Top-K中
#         target = target.view(B, T)  # [B, T]
#         target_expanded = target.unsqueeze(-1)  # [B, T, 1]
#         target_one_hot = (top_k_indices == target_expanded).float()  # [B, T, k]
#         target_in_topk = target_one_hot.sum(-1) > 0  # [B, T]

#         # 4. 计算error_term，仅对Top-K内的预测
#         probs = top_k_alpha / torch.sum(top_k_alpha, dim=-1, keepdim=True)  # [B, T, k]
#         error_term = torch.sum(torch.square(target_one_hot - probs), dim=-1)  # [B, T]
#         error_term = torch.where(target_in_topk, error_term, torch.zeros_like(error_term))  # 仅保留Top-K内的误差

#         # 5. 计算missed_topk_loss，针对未进入Top-K的样本
#         missed_topk_loss = torch.where(~target_in_topk, torch.ones_like(error_term) * 10.0, torch.zeros_like(error_term))  # 惩罚未进入Top-K的样本

#         # 6. 计算variance_term
#         S = torch.sum(top_k_alpha, dim=-1, keepdim=True)  # [B, T, 1]
#         variance_term = torch.sum(
#             top_k_alpha * (S - top_k_alpha) / (S.pow(2) * (S + 1)),
#             dim=-1
#         )  # [B, T]
#         variance_term = torch.clamp(variance_term, max=50.0)  # 裁剪

#         # 7. 计算KL散度
#         alpha_tilde = torch.ones_like(top_k_alpha) + (~target_one_hot.bool()).float() * (top_k_alpha - 1).clamp(min=1e-6)
#         S_tilde = torch.sum(alpha_tilde, dim=-1, keepdim=True)
#         kl_term = (
#             torch.lgamma(S_tilde).squeeze(-1)
#             - torch.lgamma(torch.tensor(k, device=device).float())
#             - torch.sum(torch.lgamma(alpha_tilde), dim=-1)
#             + torch.sum(torch.lgamma(torch.ones_like(alpha_tilde)), dim=-1)
#             + torch.sum(
#                 (alpha_tilde - 1) * (torch.digamma(alpha_tilde) - torch.digamma(S_tilde)),
#                 dim=-1
#             )
#         )

#         # 8. 动态调整KL权重
#         top1_pred = top_k_indices[:, :, 0]  # 取概率最大的类别
#         top1_correct = (top1_pred == target).float()
#         top1_acc = top1_correct.mean().item()
#         kl_weight = min(1.0, top1_acc * 2)

#         # 9. 计算排名损失，确保目标是Top-10中最大的
#         # 获取目标分数
#         target_scores = alpha.gather(dim=-1, index=target.unsqueeze(-1)).squeeze(-1)  # [B, T]

#         # 获取Top-10中的其他分数
#         # 排除目标本身
#         mask = (top_k_indices != target.unsqueeze(-1)).float()  # [B, T, k]
#         other_scores = top_k_alpha * mask  # 将目标的位置置0

#         # 计算目标分数与其他分数的差值
#         margin = 1.0  # 可以调整这个边际值
#         ranking_loss = torch.clamp(other_scores - target_scores.unsqueeze(-1) + margin, min=0).sum(dim=-1)  # [B, T]

#         # 只对目标在Top-K中的样本计算排名损失
#         ranking_loss = ranking_loss * target_in_topk.float()

#         # 10. 最终损失计算
#         main_loss = error_term * 5 + variance_term  # 调整权重
#         loss = main_loss + kl_weight * kl_term + missed_topk_loss + ranking_loss  # 添加ranking_loss到总损失中

#         topk_acc = target_in_topk.float().mean().item()
#         top1_acc = top1_correct.mean().item()
#         print(f"\nPrediction Statistics:")
#         print(f"Top-{k} Accuracy: {topk_acc:.4f}")
#         print(f"Top-1 Accuracy: {top1_acc:.4f}")
#         print(f"Loss Components - Main: {main_loss.mean().item():.4f}, KL: {kl_term.mean().item():.4f}, Missed Top-K Loss: {missed_topk_loss.mean().item():.4f}, Ranking Loss: {ranking_loss.mean().item():.4f}")

#         if reduce:
#             main_loss = main_loss.sum()
#             kl_term = kl_term.sum()
#             missed_topk_loss = missed_topk_loss.sum()
#             ranking_loss = ranking_loss.sum()
#             loss = loss.sum()

#         return loss, main_loss, kl_term, missed_topk_loss, ranking_loss

#     def forward(self, model, sample, reduce=True):
#         """Compute the loss for the given sample."""
#         net_output = model(**sample['net_input'])
#         loss, main_loss, kl_div, missed_topk_loss, ranking_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,
#             'main_loss': utils.item(main_loss.data) if reduce else main_loss.data,
#             'kl_loss': utils.item(kl_div.data) if reduce else kl_div.data,
#             'missed_topk_loss': utils.item(missed_topk_loss.data) if reduce else missed_topk_loss.data,
#             'ranking_loss': utils.item(ranking_loss.data) if reduce else ranking_loss.data,
#             'ntokens': sample['ntokens'],
#             'nsentences': sample['target'].size(0),
#             'sample_size': sample_size,
#         }

#         self.step += 1
#         return loss, sample_size, logging_output

#     @staticmethod
#     def aggregate_logging_outputs(logging_outputs):
#         """Aggregate logging outputs from data parallel training."""
#         loss_sum = sum(log.get('loss', 0) for log in logging_outputs)
#         main_loss_sum = sum(log.get('main_loss', 0) for log in logging_outputs)
#         kl_loss_sum = sum(log.get('kl_loss', 0) for log in logging_outputs)
#         missed_topk_loss_sum = sum(log.get('missed_topk_loss', 0) for log in logging_outputs)
#         ranking_loss_sum = sum(log.get('ranking_loss', 0) for log in logging_outputs)
#         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)

#         agg_output = {
#             'loss': loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'main_loss': main_loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'kl_loss': kl_loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'missed_topk_loss': missed_topk_loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'ranking_loss': ranking_loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'ntokens': ntokens,
#             'nsentences': nsentences,
#             'sample_size': sample_size,
#         }
#         return agg_output

#     @staticmethod
#     def logging_outputs_can_be_summed() -> bool:
#         return True
import math
import torch.nn.functional as F

from fairseq import utils

from . import FairseqCriterion, register_criterion


@register_criterion('cross_entropy')
class CrossEntropyCriterion(FairseqCriterion):

    def __init__(self, args, task):
        super().__init__(args, task)

    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'])
        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(loss.data) if reduce else 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):
        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)
        loss = F.nll_loss(
            lprobs,
            target,
            ignore_index=self.padding_idx,
            reduction='sum' if reduce else 'none',
        )
        return loss, loss

    @staticmethod
    def aggregate_logging_outputs(logging_outputs):
        """Aggregate logging outputs from data parallel training."""
        loss_sum = sum(log.get('loss', 0) for log in logging_outputs)
        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)
        agg_output = {
            'loss': loss_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
            'ntokens': ntokens,
            'nsentences': nsentences,
            'sample_size': sample_size,
        }
        if sample_size != ntokens:
            agg_output['nll_loss'] = loss_sum / ntokens / math.log(2)
        return agg_output
