Trained ResNet doesn't work in eval mode, behaves strangely

conor: <p>I’ve trained the stock torchvision ResNet50 to predict classes for images. It achieves 93% accuracy in training.</p>
<p>When I load my model after training and place it in eval mode it gives completely different results, and so accuracy for the same images. The model in .train() mode gives the expected ~93% but in .eval() mode it gives only 50%, as if it hasn’t been trained at all.</p>
<p>I can force the two models (in train and in eval modes) to behave similarly if I run:</p>
<pre><code class="lang-auto">for module in model.modules():
    if isinstance(module, torch.nn.modules.BatchNorm2d):
        module.running_mean = None
        module.running_var = None
</code></pre>
<p>where <code>model</code> is the model in eval mode.</p>
<p>I now get the correct outputs from the .eval() model but <strong>only</strong> if I use the same batch size as in training (64). The output should not depend on batch size.</p>
<p>Is this an issue with the BatchNorm implementation, or am I doing something wrong?</p>

ptrblck: <p>Based on your description it seems that the running stats in batchnorm layers are not able to represent the mean and std of the activations for the validation dataset.<br>
This could happen, if the training and validation datasets do not have similar statistics, which could happen by e.g. a bad dataset split, datasets sampled from different domains, missing preprocessing in the validation dataset etc.</p>
<p>You could try to change the <code>momentum</code> of the batchnorm layers and see, if the stats would represent the activations better. If you remove the internal stats I guess that the batch stats would be used, so it’s expected that the results would thus depend on the batch size.</p>

conor: <p>Thanks for the reply! I’m actually having this problem even when using the exact same data, no train/test split.</p>
<p>For example, I initialise two copies of the model and load the trained weights into both - in the first I do <code>model1.train()</code>, in the other I do <code>model2.eval()</code>. I then load a single batch of data and pass to both models. <code>model1</code> will achieve the correct 93% accuracy in this case, as it did in training, as long as the batch size is the same as in training (64). <code>model2</code> will achieve 50% regardless of batch size.</p>

ptrblck: <p>Thanks for the update. This artifact might then be caused by different distributions even in the training data. It might be similar to <a href="https://discuss.pytorch.org/t/model-eval-gives-incorrect-loss-for-model-with-batchnorm-layers/7561/41">this behavior</a>, i.e. the batchnorm stats would converge to the mean of all samples, while your dataset samples might be coming from distributions with different means.<br>
During the training the activations would be normalized using the batch stats, while the running stats would thus be off.</p>

conor: <p>I’ve plotted the activation mean and variance for the very first layer over 1000 batches. The output of this layer is passed to the first BatchNorm layer so these are the means and variances the BatchNorm layer is using. Is this distribution problematic? It seems they follow a sensible distribution.<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/3/4/34fca313b53861ac5f9c0b66382d00faaa4d08dd.png" alt="download" data-base62-sha1="7yK6foZtJbrR2d3ECpF9Qvj5kkd" width="375" height="262"></p>

conor: <p>And the variance here (only one media file per post, sorry)<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/2/a/2aa0ce12a3c67960f78d004ace168bc577887982.png" alt="download-1" data-base62-sha1="656zLiTKLbvy10sE1q98ObEr76G" width="375" height="262"></p>

Giuseppe_Sarno: <p>Hello,<br>
did anybody found a solution for this problem ?<br>
This looks like the same issue I just posted here <a href="https://discuss.pytorch.org/t/model-resnet34-performs-better-without-model-eval/165493"> Model (resnet34) performs better without model.eval()</a></p>
<p>I am using the same Data Loader and pre-processing functions and I can achieve very high accuracy in model.train and very low with model.eval.</p>
<p>I am running with Pytorch 1.13.0+cu117</p>

ethanh20009: <p>I assume you’ve found a solution already, but to update the forum the problem lay in BatchNorm2d.<br>
I assumed it was behaving differently in train mode (and it was).</p>
<p>the argument ‘track_running_stats’ I assumed was using data tracked only when training, and was therefore causing my model to behave differently in eval.</p>
<p>Fix:</p>
<pre><code class="lang-auto">self.bn = torch.nn.BatchNorm2d(input_features,track_running_stats=False)
</code></pre>
<p>and will behave the same in eval and training.</p>

ptrblck: <aside class="quote no-group" data-username="ethanh20009" data-post="8" data-topic="121242">
<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/ethanh20009/48/58081_2.png" class="avatar"> ethanh20009:</div>
<blockquote>
<p>and will behave the same in eval and training.</p>
</blockquote>
</aside>
<p>If you guarantee to use the same batch size. Without running stats the input batch stats will be used to normalize the activation, which then depends on the batch size and is often not desired during deployment (e.g. as often single samples are used).</p>

Zimo_Zhou: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> Hi, I got the same issue using batchnorm2d in ResNet. If I did not set <strong>track_running_stats=False</strong>, it seems the model get back to random weights after model.eval(). Can I ask what cause this issue? Thank you.</p>

ptrblck: <p>I doubt the model changes its weights in <code>eval</code> mode and you can easily check if e.g. by printing the <code>.abs().sum()</code> of each weight. You are most likely running into an issue where the running stats cannot converge to the activation stats.</p>