Switch off batch norm layers

SU801T: <p>I have the following DenseNet that extracts features from an untrained network and feeds the tensors into a fully connected model as shown by the following:</p>
<pre><code class="lang-auto">class DenseNetConv(torch.nn.Module):
    def __init__(self):
        super(DenseNetConv,self).__init__()
        original_model = models.densenet161(pretrained=False)
        self.features = torch.nn.Sequential(*list(original_model.children())[:-1])
        self.avgpool = nn.AdaptiveAvgPool2d(1)
        for param in self.parameters():
            param.requires_grad = False

    def forward(self, x):
        x = self.features(x)
        x = F.relu(x, inplace=True)
        x = F.avg_pool2d(x, kernel_size=7).view(x.size(0), -1)
        return x

class MyDenseNetDens(torch.nn.Module):
    def __init__(self, nb_out=2):
        super().__init__()
        self.dens1 = torch.nn.Linear(in_features=2208, out_features=512)
        self.dens2 = torch.nn.Linear(in_features=512, out_features=128)
        self.dens3 = torch.nn.Linear(in_features=128, out_features=nb_out)
        
    def forward(self, x):
        x = self.dens1(x)
        x = torch.nn.functional.selu(x)
        x = F.dropout(x, p=0.25, training=self.training)
        x = self.dens2(x)
        x = torch.nn.functional.selu(x)
        x = F.dropout(x, p=0.25, training=self.training)
        x = self.dens3(x)
        return x


class MyDenseNet(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.mrnc = MyDenseNetConv()
        self.mrnd = MyDenseNetDens()
    def forward(self, x):
        x = self.mrnc(x)
        x = self.mrnd(x)
        return x 

densenet = MyDenseNet()
densenet.to(device)
densenet.train()
</code></pre>
<p>However, what is the best way of switching off the batch norm layers in this model for training and inference? I would typically put the feature extraction bit into evaluation mode but wondering if there is a cleaner way as I am combining the feature extractor and dense classification layers in one model…</p>

sudomaze: <p>During inference, <code>batch norm</code> will be frozen. However, during training, it will be updated. To resolve this issue, you will need to explicitly freeze <code>batch norm</code> during training. The best way to do that is by over-writing <code>train()</code> method in your <code>nn.Module</code> (aka model definition) so it will freeze <code>batch norm</code> during training. Here is an example:</p>
<pre><code class="lang-python">class DenseNetConv(torch.nn.Module):
    def __init__(self):
        super(DenseNetConv,self).__init__()
        original_model = models.densenet161(pretrained=False)
        self.features = torch.nn.Sequential(*list(original_model.children())[:-1])
        self.avgpool = nn.AdaptiveAvgPool2d(1)
        for param in self.parameters():
            param.requires_grad = False
    def train(self, mode=True):
        """
        Override the default train() to freeze the BN parameters
        """
        super(DenseNetConv, self).train(mode)

        print("Freezing Mean/Var of BatchNorm2D.")
        print("Freezing Weight/Bias of BatchNorm2D.")

        for m in self.features.modules():
            if isinstance(m, nn.BatchNorm2d):
                m.eval()
                m.weight.requires_grad = False
                m.bias.requires_grad = False
    def forward(self, x):
        x = self.features(x)
        x = F.relu(x, inplace=True)
        x = F.avg_pool2d(x, kernel_size=7).view(x.size(0), -1)
        return x
</code></pre>
<p>Please refer to <a href="https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/10">this thread for more information</a>.</p>

SU801T: <p>Ah ok, so during inference it will be frozen automatically. As I am not using ImageNet, what would be the running stats applied at inference then?</p>

sudomaze: <p>It will be what it was trained on. In your case, your training dataset stats.</p>

SU801T: <p>ah ok and so if the batch norm layers are switched off during training, basically my running stats will be nothing…</p>

SU801T: <p>Would this be appropriate too?</p>
<pre><code class="lang-auto">model = models.densenet161(pretrained=False)
    for param in model.parameters():
        param.requires_grad = False
    num_ftrs = model.classifier.in_features

    for m in model.modules():
            if isinstance(m, nn.BatchNorm2d):
                m.eval()
                m.weight.requires_grad = False
                m.bias.requires_grad = False
    
    model.classifier = torch.nn.Linear(num_ftrs,2)
    print(model.classifier)
    model.to(device)
</code></pre>

sudomaze: <p>Why are you freezing your backbone? Especially if it isn’t pre-trained.</p>
<p>One more thing, it is better to have a little bit deeper MLP (3 layers) with ReLU in between them.</p>
<pre><code class="lang-markdown">densenet161 -&gt; flatten -&gt; linear (relu) [num_ftrs, 256] -&gt; linear (relu) [256, 256] -&gt; linear [256, 2]
</code></pre>
<p>Don’t freeze your backbone and batchnorm if your model wasn’t trained because you will have some inefficient feature extractor, and the MLP can’t have a good representation to learn from for your task.</p>

SU801T: <p>The experiment I am attempting is to investigate how effective the convolutional layers are when they are randomly initialised. Previous research appears to suggest that convnets can be good classifiers even when the convolutional layers are not trained:</p>
<aside class="onebox pdf" data-onebox-src="https://arxiv.org/pdf/2003.00152.pdf">
  <header class="source">

      <a href="https://arxiv.org/pdf/2003.00152.pdf" target="_blank" rel="noopener nofollow ugc">arxiv.org</a>
  </header>

  <article class="onebox-body">
    <a href="https://arxiv.org/pdf/2003.00152.pdf" target="_blank" rel="noopener nofollow ugc"><span class="pdf-onebox-logo"></span></a>

<h3><a href="https://arxiv.org/pdf/2003.00152.pdf" target="_blank" rel="noopener nofollow ugc">2003.00152.pdf</a></h3>

  <p class="filesize">2.14 MB</p>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>

<p>I basically want to see how important batch normalisation is in regard to my classification task.</p>
<p>And yes, I agree that a deeper MLP would be beneficial but I am following the vanilla example provided by PyTorch’s tutorial on transfer learning:</p>
<p><a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" class="onebox" target="_blank" rel="noopener nofollow ugc">https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html</a></p>