# 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
# import torch.nn.functional as F
# from fairseq import utils
# from fairseq.criterions import FairseqCriterion, register_criterion

# @register_criterion('dirichlet_criterion')
# class OptimizedDirichletCriterion(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
#         current_max_evidence = evidence.max().item()
#         print(f"Step {self.step}: Max evidence = {current_max_evidence:.4f}")
#         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. 计算主损失（论文中的分类损失）
#         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=error_term*20
#         # error_term = torch.where(target_in_topk, error_term, torch.zeros_like(error_term))  # 仅保留Top-K内的误差
#         S = torch.sum(top_k_alpha, dim=-1, keepdim=True)  # [B, T, 1]
#         variance_term = torch.sum(
#             (probs*(1-probs))/(S+1)
#         )  # [B, T]
#         variance_term=torch.clamp(variance_term, min=1e-10, max=40)
#         main_loss=error_term+variance_term
#         # 5. 计算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
#             )
#         )
#         # 6. target如果不在前k个，不确定性应该为1，反之为0
#         uncertainty_est=1-target_one_hot.sum(-1)
#         uncertainty_pre=10/S.sum(-1)
#         uncertainty_penalty=abs(uncertainty_pre-uncertainty_est)
#         uncertainty_penalty=uncertainty_penalty*5
#         lambda_reg = 1.0  # 正则化项的权重，可以调整
#         print(f"Does main_loss require grad? {main_loss.requires_grad}")
#         print(f"Does kl_term require grad? {kl_term.requires_grad}")
#         print(f"Does uncertainty_penalty require grad? {uncertainty_penalty.requires_grad}")
        
#         # 7. 计算准确率
#         topk_acc = target_in_topk.float().mean().item()
#         top1_pred = top_k_indices[:, :, 0]
#         top1_correct = (top1_pred == target).float()
#         top1_acc = top1_correct.mean().item()
#         # 8. 日志记录
#         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}, Un_Penalty: {uncertainty_penalty.mean().item():.4f}")
#         loss = main_loss + kl_term*annealing_coef+ uncertainty_penalty
#         if reduce:
#             loss = loss.sum()
#             kl_term=kl_term.sum()
#             main_loss=main_loss.sum()

#         return loss, main_loss, kl_term

#     def forward(self, model, sample, reduce=True):
#         """Compute the loss for the given sample."""
#         net_output = model(**sample['net_input'])
#         loss, main_loss, kl_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_loss.data) if reduce else kl_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)
#         penalty_sum = sum(log.get('penalty', 0) for log in logging_outputs)
#         uncertainty_reg_sum = sum(log.get('uncertainty_reg', 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.,
#             'penalty': penalty_sum / sample_size / math.log(2) if sample_size > 0 else 0.,
#             'uncertainty_reg': uncertainty_reg_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
# 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 CustomLabelSmoothedCrossEntropyCriterion(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'])
        loss, kl_loss,uncertainty = 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,
            'kl_loss': utils.item(kl_loss.data) if reduce else kl_loss.data,
            'uncertainty': utils.item(uncertainty.data) if reduce else kl_loss.data,
            'ntokens': sample['ntokens'],
            'nsentences': sample['target'].size(0),
            'sample_size': sample_size,
        }
        sample['uncertainty']=uncertainty
        return loss, sample_size, logging_output

    # def compute_loss(self, model, net_output, sample, reduce=True):
    #     logits = net_output[0]  # 获取logits
    #     target = model.get_targets(sample, net_output)

    #     # Convert logits to alpha (logits + 1)

    #     alpha = logits + 1
    #     print("alpha=",alpha[0])
    #     target_one_hot = F.one_hot(target, num_classes=logits.size(-1)).float()
    #     print("target=",target_one_hot[0])
    #     # Compute probs
    #     probs = alpha / torch.sum(alpha, dim=-1, keepdim=True)

    #     # Compute error_term
    #     error_term = torch.sum(torch.square(target_one_hot - probs), dim=-1)

    #     # Compute S
    #     S = torch.sum(alpha, dim=-1, keepdim=True)

    #     # Compute variance_term
    #     variance_term = torch.sum(
    #         (probs * (1 - probs)) / (S + 1),
    #         dim=-1
    #     )

    #     # Compute final loss
    #     loss = error_term + variance_term

    #     # Compute NLL loss for logging
    #     nll_loss = -torch.log(probs.gather(dim=-1, index=target.unsqueeze(-1))).squeeze(-1)

    #     if reduce:
    #         loss = loss.sum()
    #         nll_loss = nll_loss.sum()

    #     return loss, nll_loss

    def compute_loss(self, model, net_output, sample, reduce=True):
        epoch = getattr(model, 'epoch',0)
        logits = net_output[0]  # 获取logits
        logits = F.relu(logits)
        target = model.get_targets(sample, net_output)

        # 将 logits 转换为 alpha (logits + 1)
        alpha = logits + 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)

        # 计算不确定性 U = K / S
        K = logits.size(-1)
        print(S)
        print(K)
        uncertainty = K / S.squeeze(-1)  # S 的维度为 [batch_size, 1]，需要去掉最后一维
        print(uncertainty)
        variance_term = torch.sum(
            (probs * (1 - probs)) / (S + 1),
            dim=-1
        )
        
        # 计算 KL 散度
        sum_alpha = torch.sum(alpha, dim=-1, keepdim=True)
        log_gamma_sum_alpha = torch.lgamma(sum_alpha).squeeze(-1)
        log_gamma_alpha = torch.sum(torch.lgamma(alpha), dim=-1)
        log_gamma_K = torch.lgamma(torch.tensor(K, dtype=alpha.dtype, device=alpha.device))
        psi_alpha = torch.digamma(alpha)
        psi_sum_alpha = torch.digamma(sum_alpha).squeeze(-1)
        kl_div = log_gamma_sum_alpha - log_gamma_K - log_gamma_alpha + K * torch.sum((alpha - 1) * (psi_alpha - psi_sum_alpha.unsqueeze(-1)), dim=-1)
        print(kl_div)
        # 计算 annealing_coef，线性增长从0到1
        annealing_coef = min(1.0, epoch / 10)
        kl_div = annealing_coef * kl_div
        print(kl_div)
        # 计算最终的损失
        loss = error_term + kl_div + variance_term
        
        loss=torch.sum(loss)
        kl_div=torch.sum(kl_div)
        uncertainty=torch.sum(uncertainty)

        return loss, kl_div, uncertainty

    @staticmethod
    def aggregate_logging_outputs(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)
        
        total_loss = sum(log.get('loss', 0) for log in logging_outputs)
        total_nll_loss = sum(log.get('nll_loss', 0) for log in logging_outputs)
        total_kl_loss = sum(log.get('kl_loss', 0) for log in logging_outputs)
        total_uncertainty = sum(log.get('uncertainty', 0) for log in logging_outputs)
        
        return {
            'loss': (total_loss / sample_size) / math.log(2) if sample_size > 0 else 0.,
            'nll_loss': (total_nll_loss / ntokens) / math.log(2) if ntokens > 0 else 0.,
            'kl_loss': total_kl_loss / sample_size if sample_size > 0 else 0.,
            'uncertainty': total_uncertainty / sample_size if sample_size > 0 else 0.,
            'ntokens': ntokens,
            'nsentences': nsentences,
            'sample_size': sample_size,
        }