<filename>fairseq/criterions/masked_adlm.py
# 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 metrics, utils
from fairseq.criterions import FairseqCriterion, register_criterion


@register_criterion('masked_adlm')
class MaskedAdLmLoss(FairseqCriterion):
    """
    Implementation for the loss used in masked language model (MLM) training.
    """


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

        self.vocab = self.task.source_dictionary
        self.margins = self.register_buffer(torch.zeros(self.vocab.count, 1))
        self.margins.requires_grad = False

        self.margin_lambda = args.margin_lambda
        self.margin_lr = args.margin_lr

    @staticmethod
    def add_args(parser):
        """Add criterion-specific arguments to the parser."""
        super(MaskedAdLmLoss,
              MaskedAdLmLoss).add_args(parser)
        parser.add_argument('--margin_lambda', default=100.0, type=float, metavar='D',
                            help='weight for the adaptive margin loss')
        parser.add_argument('--margin_lr', default=0.01, type=float, metavar='D',
                            help='weight for the adaptive margin loss')

    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
        """
        # compute MLM loss
        #self.margins.requires_grad = model.training

        masked_tokens = sample['target'].ne(self.padding_idx)
        sample_size = masked_tokens.int().sum().item()

        # (Rare case) When all tokens are masked, the model results in empty
        # tensor and gives CUDA error.
        if sample_size == 0:
            masked_tokens = None

        logits = model(**sample['net_input'], masked_tokens=masked_tokens)[0]
        targets = model.get_targets(sample, [logits])

        #import IPython
        #IPython.embed()
        if sample_size != 0:
            targets = targets[masked_tokens]

        one_hot = F.one_hot(targets, self.vocab.count)

        m = F.embedding(targets, self.margins).squeeze(dim=-1)
        #m = self.margins(targets).squeeze(dim=-1)
        margin = m * one_hot

        #logits_minus_margin = logits - margin
        log_softmax = F.log_softmax(
                logits.view(-1, logits.size(-1)),
                dim=-1,
                dtype=torch.float32,
            )
        loss = F.nll_loss(
            log_softmax, 
            targets.view(-1),
            reduction='sum',
            ignore_index=self.padding_idx,
        )

        margin_norm = torch.sum(margin)

        total_loss = loss - margin_norm * self.margin_lambda
        logging_output = {
            'loss': utils.item(loss.data) if reduce else loss.data,
            'margin_n':utils.item(margin_norm.data) if reduce else margin_norm.data,
            'ntokens': sample['ntokens'],
            'nsentences': sample['nsentences'],
            'sample_size': sample_size,
        }
        return total_loss, sample_size, logging_output

    @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)
        margin_n = sum(log.get('margin_n', 0) for log in logging_outputs)
        sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)

        metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)
        metrics.log_scalar('margin_norm', margin_n / sample_size / math.log(2), sample_size, round=3)
        metrics.log_derived('ppl', lambda meters: round(2**meters['loss'].avg, 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

<filename>fairseq/criterions/masked_adlm.py
# 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 metrics, utils
from fairseq.criterions import FairseqCriterion, register_criterion


@register_criterion('masked_adlm')
class MaskedAdLmLoss(FairseqCriterion):
    """
    Implementation for the loss used in masked language model (MLM) training.
    """


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

        self.vocab = self.task.source_dictionary
        self.margins = self.register_buffer(torch.zeros(self.vocab.count, 1))
        self.margins.requires_grad = False

        self.margin_lambda = args.margin_lambda
        self.margin_lr = args.margin_lr

    @staticmethod
    def add_args(parser):
        """Add criterion-specific arguments to the parser."""
        super(MaskedAdLmLoss,
              MaskedAdLmLoss).add_args(parser)
        parser.add_argument('--margin_lambda', default=100.0, type=float, metavar='D',
                            help='weight for the adaptive margin loss')
        parser.add_argument('--margin_lr', default=0.01, type=float, metavar='D',
                            help='weight for the adaptive margin loss')

    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
        """
        # compute MLM loss
        #self.margins.requires_grad = model.training

        masked_tokens = sample['target'].ne(self.padding_idx)
        sample_size = masked_tokens.int().sum().item()

        # (Rare case) When all tokens are masked, the model results in empty
        # tensor and gives CUDA error.
        if sample_size == 0:
            masked_tokens = None

        logits = model(**sample['net_input'], masked_tokens=masked_tokens)[0]
        targets = model.get_targets(sample, [logits])

        #import IPython
        #IPython.embed()
        if sample_size != 0:
            targets = targets[masked_tokens]

        one_hot = F.one_hot(targets, self.vocab.count)

        m = F.embedding(targets, self.margins).squeeze(dim=-1)
        #m = self.margins(targets).squeeze(dim=-1)
        margin = m * one_hot

        #logits_minus_margin = logits - margin
        log_softmax = F.log_softmax(
                logits.view(-1, logits.size(-1)),
                dim=-1,
                dtype=torch.float32,
            )
        loss = F.nll_loss(
            log_softmax, 
            targets.view(-1),
            reduction='sum',
            ignore_index=self.padding_idx,
        )

        margin_norm = torch.sum(margin)

        total_loss = loss - margin_norm * self.margin_lambda
        logging_output = {
            'loss': utils.item(loss.data) if reduce else loss.data,
            'margin_n':utils.item(margin_norm.data) if reduce else margin_norm.data,
            'ntokens': sample['ntokens'],
            'nsentences': sample['nsentences'],
            'sample_size': sample_size,
        }
        return total_loss, sample_size, logging_output

    @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)
        margin_n = sum(log.get('margin_n', 0) for log in logging_outputs)
        sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)

        metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)
        metrics.log_scalar('margin_norm', margin_n / sample_size / math.log(2), sample_size, round=3)
        metrics.log_derived('ppl', lambda meters: round(2**meters['loss'].avg, 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

# 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. Implementation for the loss used in masked language model (MLM) training. Add criterion-specific arguments to the parser. 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 # compute MLM loss #self.margins.requires_grad = model.training # (Rare case) When all tokens are masked, the model results in empty # tensor and gives CUDA error. #import IPython #IPython.embed() #m = self.margins(targets).squeeze(dim=-1) #logits_minus_margin = logits - margin Aggregate logging outputs from data parallel training. 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.