# 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 os

from fairseq import logging, metrics, utils
from fairseq.criterions import FairseqCriterion, register_criterion
from torch.nn import parallel


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:
        pad_mask = target.eq(ignore_index)
        nll_loss.masked_fill_(pad_mask, 0.)
        smooth_loss.masked_fill_(pad_mask, 0.)
    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_w_bow')
class LabelSmoothedCrossEntropyWBowCriterion(FairseqCriterion):
    def __init__(self, task, sentence_avg, label_smoothing, bow_weight):
        super().__init__(task)
        self.sentence_avg = sentence_avg
        self.eps = label_smoothing
        self.bow_loss_fn = torch.nn.BCEWithLogitsLoss(reduction="none")
        self.bow_weight = bow_weight

    @staticmethod
    def add_args(parser):
        """Add criterion-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('--label-smoothing', default=0., type=float, metavar='D',
                            help='epsilon for label smoothing, 0 means no label smoothing')
        parser.add_argument("--bow-weight", default=1, type=float)

    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, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce)
        # TODO

        # print("pid: {}, parallel_loss: {}".format(os.getpid(), parallel_loss))
        sample_size = sample['target'].size(0) if self.sentence_avg else sample['ntokens']    
        logging_output = {
            # 'loss': loss.data,
            'nll_loss': nll_loss.data,
            'ntokens': sample['ntokens'],
            'nsentences': sample['target'].size(0),
            'sample_size': sample_size,
        }

        if "nonstop_cls_out" in net_output[1] and "nonstop_label_vector" in sample and model.training:
            nonstop_loss = self.compute_bow_loss(net_output[1]["nonstop_cls_out"], sample["nonstop_label_vector"])
            logging_output["nonstop_loss"] = nonstop_loss.data
            logging_output["num_nonstop_token"] = sample['num_nonstop_token']
            loss += nonstop_loss * self.bow_weight
        else:
            logging_output["nonstop_loss"] = 0
            logging_output["num_nonstop_token"] = 0

        if "stop_cls_out" in net_output[1] and "stop_label_vector" in sample and model.training:
            stop_loss = self.compute_bow_loss(net_output[1]["stop_cls_out"], sample["stop_label_vector"])
            logging_output["stop_loss"] = stop_loss.data
            logging_output["num_stop_token"] = sample['num_stop_token']
            loss += stop_loss * self.bow_weight
        else:
            logging_output["stop_loss"] = 0
            logging_output["num_stop_token"] = 0

        logging_output["loss"] = loss.data
        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, 1)  # sample["target"]
        loss, nll_loss = label_smoothed_nll_loss(
            lprobs, target, self.eps, ignore_index=self.padding_idx, reduce=reduce,
        )
        return loss, nll_loss

    def compute_bow_loss(self, logits, label):
        # print("pid: {}, parallel_input in sample: {}".format(os.getpid(), "parallel_input" in sample))s
        loss = self.bow_loss_fn(logits, label.to(logits)) # [B, V]
        loss = torch.sum(torch.mean(loss, dim=-1))
        return loss

    @staticmethod
    def reduce_metrics(logging_outputs) -> None:
        """Aggregate logging outputs from data parallel training."""
        loss_sum = sum(log.get('loss', 0) for log in logging_outputs)
        nll_loss_sum = sum(log.get('nll_loss', 0) for log in logging_outputs)

        ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)
        sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)
        nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)

        metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)
        metrics.log_scalar('nll_loss', nll_loss_sum / ntokens / math.log(2), ntokens, round=3)
        metrics.log_derived('ppl', lambda meters: utils.get_perplexity(meters['nll_loss'].avg))

        n_nonstop_token = sum(log.get('num_nonstop_token', 0) for log in logging_outputs) + 1e-3
        nonstop_loss_sum = sum(log.get('nonstop_loss', 0) for log in logging_outputs)
        metrics.log_scalar('nonstop_loss', nonstop_loss_sum / nsentences / math.log(2), sample_size, round=3)

        n_stop_token = sum(log.get('num_stop_token', 0) for log in logging_outputs) + 1e-3
        stop_loss_sum = sum(log.get('stop_loss', 0) for log in logging_outputs)
        metrics.log_scalar('stop_loss', stop_loss_sum / nsentences / math.log(2), sample_size, round=3)

    @staticmethod
    def logging_outputs_can_be_summed() -> bool:
        """
        Whether the logging outputs returned by `forward` can be summed
        across workers prior to calling `reduce_metrics`. Setting this
        to True will improves distributed training speed.
        """
        return True
