Hello there,

I want to test a pre-trained model (of a low resource language) on its ability to predict masked words. One way to do this is to compute the pseudo-perplexity of the model (based on this paper). In short the approach is as follows:

1. Given a sentence, create N copies of itself for each token in it.
2. Sequentially, insert a mask token, one in each copy for each respective token, all while producing its label tensor as well as its attention tensor.
3. Compute the loss for each masked token, by forwarding the masked tensor, the attention tensor, and the labels tensor.
4. Compute PPPL as given in the paper, in other words, the exponential of the total loss

The problem with this is that it’s expensive to do so for every single token when we have a large number of sentences. In order to make this cheaper, I decided to produce batches by concatenating all the copies of the sentences into one large tensor and then split them into batches. The problem with this solution is that the resulting loss is different for each batch size. I don’t
know why is the loss changing, am I doing something wrong? Also, I would really appreciate any other comments on my code to make it work faster. Thank you very much and have a wonderful day!

Here is my code:

``````# Function to create copies and insert masks

config = BertConfig.from_pretrained(model_path)
tokenizer = BertTokenizer.from_pretrained(model_path, use_fast = True)

# Tokenize all sentences, padding is necessary since we need to fit them into batches

# Creating a masked_input_id tensor, attention mask tensor, and a labels tensor for each sentence
labels.append(label)

# Merge and split the tensors based on the given batch size
labels = torch.cat(labels, 0).split(batch_size)

# Calculate the loss for each token