Computing perplexity

ivoliv: <p>Hi. Hopefully this isn’t off topic, but since my code in is pyTorch I was wondering if someone in this community is able to answer this question.</p>
<p>I’m building a model similar to <a href="https://arxiv.org/pdf/1708.02182.pdf" rel="nofollow noopener">https://arxiv.org/pdf/1708.02182.pdf</a>, and using perplexity as a way to assess performance. I thought I was calculating it correctly, but my model converges to perplexity levels down in the 1.2 range on wikitext-103 (similar for wikitext-2). In my forward function, I concatenate the last output of by biderectional lstm and pass it through a fully-connected layer:</p>
<pre><code>conc = torch.cat((out[-1,:,:self.hidden_dim], out[0,:,self.hidden_dim:]), dim=1)
output = self.dropout(conc)
output = self.fc(output)
return output
</code></pre>
<p>Then, I use cross entropy loss and scale it to the dimensions of the problem (this is where I might be going wrong?), sum it for all batches and finally take the exponent, here’s the validation loop:</p>
<pre><code>       loss_func = nn.CrossEntropyLoss()

       with torch.no_grad():
            for x, y in valid_dl:
                if cuda:
                    x = x.cuda()
                    y = y.cuda()   
                    
                preds = model(x)
                loss = loss_func(preds.view(-1, preds.size(2)), y.view(-1).long())

                val_loss += loss.item() * x.size(0) / x.size(1)

        val_loss /= len(valid_dl)
        
        print('Ppl: {:6.2f},'.format( math.exp(val_loss) )
</code></pre>
<p>I just checked my run and this value has converged to 1.2, should be above 60s.</p>
<p>My data loader is pretty simple and hints at how I build batches:</p>
<pre><code>def __getitem__(self, idx):
    start = self.itoklist.batch_start_end[idx][0]
    end = self.itoklist.batch_start_end[idx][1]
    x = self.itoklist.batch_matrix[start:end, :]
    y = self.itoklist.batch_matrix[start + 1:end + 1, :]
    return x, y.contiguous()
</code></pre>
<p>Any help would be appreciated.</p>
<p>Thanks.</p>

jeremyg: <p>This is a very old thread, but I’m running into the same problem. Did you ever find your issue?</p>

pooya_khandel: <p>Any solutions? I’m running into this issue too. It seems the model is trained but the perplexity is not calculated correctly but when I switch into unidirectional LSTM layers perplexity sounds to be a valid value.</p>

tom: <p>So perplexity for unidirectional models is: after feeding c_0 … c_n, the model outputs a probability distribution p over the alphabet and perplexity is exp(-p(c_{n+1}), where we took c_{n+1} from the ground truth, you take and you take the expectation / average over your validation set.</p>
<p>Now you take a bidirectional model, feed ??? and the model outputs a probability distribution ??? and take the probability of ???.</p>
<p>I don’t think the perplexity makes much sense for bidirectional models, because there is no <em>next character</em> when you feed from both directions.<br>
As a practical example, when I last looked fast.ai trained separate forward and backward LMs and then evaluated the perplexity on either.</p>
<p>Somewhat related: <a href="https://www.scribendi.ai/can-we-use-bert-as-a-language-model-to-assign-score-of-a-sentence/" rel="nofollow noopener">https://www.scribendi.ai/can-we-use-bert-as-a-language-model-to-assign-score-of-a-sentence/</a></p>
<p>Best regards</p>
<p>Thomas</p>
<p>P.S.: I don’t think it’s a good habit to cross post questions to stack overflow without linking that here.</p>

pooya_khandel: <aside class="quote no-group" data-username="tom" data-post="4" data-topic="25792">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tom/48/3162_2.png" class="avatar"> tom:</div>
<blockquote>
<p>As a practical example, when I last looked fast.ai trained separate forward and backward LMs and then evaluated the perplexity on either.</p>
</blockquote>
</aside>
<p>Thanks for your help. I just don’t understand how do we can train separate forward and backward model and evaluate perplexity on both. I have seen some posts and comments in forums that also mentioned about separate training.<br>
When taking bidirectional model we feed the network same input as the unidirectional model, so the input of LSTM is shared between the forward and backward layer then the output of these layers could be summed, average or concatenated to be passed through next layers or final(dense) layer of model that produces output probabilities. We can use these probabilities and the target vector to calculate perplexity. I wanted to asked whether my interpretation is correct?</p>
<p>Thanks.</p>
<p>P.S: Sorry for not referring the link I forgot to do it. I follow the right habit next times.</p>

tom: <p>So if you take the template</p>
<blockquote>
<p>Now you take a bidirectional model, feed ??? and the model outputs a probability distribution ??? and take the probability of ???.</p>
</blockquote>
<p>and try to make it as precise as the I did for the unidirectional case:</p>
<blockquote>
<p>after feeding c_0 … c_n, the model outputs a probability distribution p over the alphabet and perplexity is exp(-p(c_{n+1}), where we took c_{n+1} from the ground truth, you take and you take the expectation / average over your validation set.</p>
</blockquote>
<p>you find that it is hard (impossible?) to do without having the target somehow showing up in the input.</p>
<p>So in your version, you put in “the input” and “the target” where you would have to specify what the input is and what the target is. You could try to feed in prefixes of sentences and then predict the next word, but the internal states are quite different to what they would be if you fed in the next word as well. This is in stark contrast to the unidirectional case.</p>
<p>Best regards</p>
<p>Thomas</p>

pooya_khandel: <p>I did some more research, I found some suggestions to the problem, as <a class="mention" href="/u/tom">@tom</a> explains the problem of training language model with “bidirectional” LSTMs as:</p>
<aside class="quote no-group quote-modified" data-username="tom" data-post="6" data-topic="25792">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tom/48/3162_2.png" class="avatar"> tom:</div>
<blockquote>
<p>So if you take the template</p>
<blockquote>
<p>Now you take a bidirectional model, feed ??? and the model outputs a probability distribution ??? and take the probability of ???.</p>
</blockquote>
<p>and try to make it as precise as the I did for the unidirectional case:</p>
<blockquote>
<p>after feeding c_0 … c_n, the model outputs a probability distribution p over the alphabet and perplexity is exp(-p(c_{n+1}), where we took c_{n+1} from the ground truth, you take and you take the expectation / average over your validation set.</p>
</blockquote>
<p>you find that it is hard (impossible?) to do without having the target somehow showing up in the input.</p>
</blockquote>
</aside>
<p>To help this problem it is suggested in this <a href="https://medium.com/@plusepsilon/the-bidirectional-language-model-1f3961d1fb27" rel="noopener nofollow ugc">blog post</a> is first to append each sentence with start and end of sentecne tags then instead of concatenating coressponding outputs of each layer, concatenate forward and backawad layers so that they are predicting on the same token.</p>
<p>There is also further explanations in this <a href="https://www.aclweb.org/anthology/E17-1096" rel="noopener nofollow ugc">paper</a></p>