import torch


def masked_accuracy(scores,targets,tgt_pad_index = 0):
    """
    Calculate accuracy for a given scores and targets, ignoring it for padding_index
    @params scores(Tensor): output scores - shape(batch, tgt_seq_len-1, tgt_vocab_size)
    @params target(Tensor): gold target - shape(batch,tgt_seq_len) - Discard 1st time step
    @params tgt_pad_index(int): Target pad index for which loss is ignored
    
    @returns accuracy(Float): Accuracy
    """
    with torch.no_grad():
        targets = targets[:,1:]
        mask = (targets!=tgt_pad_index)
        num_words = mask.sum().float()
        preds = torch.argmax(scores, dim=-1)
        truths = (preds == targets)*mask
        accuracy = truths.sum()/num_words
    return accuracy