How can I get the mean and variance from a saved CNN model?

Saurav_Pawar: <p>Hi,</p>
<p>How can I get the mean, variance, gamma and beta for batchnorm from a saved CNN model?<br>
Also, how can I use them for inference?</p>
<p>This is my architecture:</p>
<pre><code class="lang-auto">----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1           [-1, 32, 32, 32]             896
       BatchNorm2d-2           [-1, 32, 32, 32]              64
              ReLU-3           [-1, 32, 32, 32]               0
           Dropout-4           [-1, 32, 32, 32]               0
            Conv2d-5           [-1, 64, 32, 32]          18,496
       BatchNorm2d-6           [-1, 64, 32, 32]             128
              ReLU-7           [-1, 64, 32, 32]               0
         AvgPool2d-8           [-1, 64, 16, 16]               0
            Conv2d-9          [-1, 128, 16, 16]          73,856
      BatchNorm2d-10          [-1, 128, 16, 16]             256
             ReLU-11          [-1, 128, 16, 16]               0
          Dropout-12          [-1, 128, 16, 16]               0
           Conv2d-13          [-1, 128, 16, 16]         147,584
      BatchNorm2d-14          [-1, 128, 16, 16]             256
             ReLU-15          [-1, 128, 16, 16]               0
        AvgPool2d-16            [-1, 128, 8, 8]               0
           Conv2d-17            [-1, 256, 8, 8]         295,168
      BatchNorm2d-18            [-1, 256, 8, 8]             512
             ReLU-19            [-1, 256, 8, 8]               0
          Dropout-20            [-1, 256, 8, 8]               0
           Conv2d-21            [-1, 256, 8, 8]         590,080
      BatchNorm2d-22            [-1, 256, 8, 8]             512
             ReLU-23            [-1, 256, 8, 8]               0
        AvgPool2d-24            [-1, 256, 4, 4]               0
          Flatten-25                 [-1, 4096]               0
           Linear-26                   [-1, 32]         131,104
             ReLU-27                   [-1, 32]               0
           Linear-28                   [-1, 10]             330
================================================================
Total params: 1,259,242
Trainable params: 1,259,242
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.01
Forward/backward pass size (MB): 5.38
Params size (MB): 4.80
Estimated Total Size (MB): 10.19
----------------------------------------------------------------
</code></pre>

ptrblck: <p>You can access the affine, trainable parameters via <code>.weight</code> and <code>.bias</code> and the running stats via <code>.running_mean</code> and <code>.running_var</code>.</p>

Saurav_Pawar: <p>Thanks for your response. That worked!<br>
I have a saved pytorch CNN model. While doing the inference, I want to know, what is the exact input and output of the batch normalization layers?</p>
<p>This is my architecture:</p>
<pre><code class="lang-auto">class Cifar10CnnModel(ImageClassificationBase):
    def __init__(self):
        super().__init__()
        self.network = nn.Sequential(
            
            # Conv-1
            nn.Conv2d(3, 32, kernel_size=3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.Dropout(0.25),
            
            # Conv-2
            nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.AvgPool2d(2, 2), # output: 64 x 16 x 16
            
            # Conv-3
            nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.Dropout(0.25),

            # Conv-4
            nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.AvgPool2d(2, 2), # output: 128 x 8 x 8

            # Conv-5
            nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(),
            nn.Dropout(0.25),            
            
            # Conv-6
            nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm2d(256),           
            nn.ReLU(),
            nn.AvgPool2d(2, 2), # output: 256 x 4 x 4

            nn.Flatten(), 
            nn.Linear(256*4*4, 32),
            nn.Dropout(0.25),            
            nn.ReLU(),
            nn.Linear(32, 10))
        
    def forward(self, xb):
        return self.network(xb)
</code></pre>
<p>I want to carry out a verification process that the running mean, running variance, gamma and beta are correct by calculating manually.</p>

ptrblck: <p>Check <a href="https://github.com/ptrblck/pytorch_misc/blob/master/batch_norm_manual.py">this manual implementation</a> which shows how the layer execution is performed internally.</p>

Saurav_Pawar: <p>Thanks for your response. Do you have any <a href="https://discuss.pytorch.org/t/how-can-l-load-my-best-model-as-a-feature-extractor-evaluator/17254/6">similiar</a> thing by using which I can get the input and output for batchnorm layers?</p>

ptrblck: <p>Yes, forward hooks should work with my manual module implementation, too, and you should be able to reuse the provided code.</p>

Saurav_Pawar: <p>Thank you. I was able to solve my solution and have got the output of each layer. I am also trying to verify the values manually and after doing that I can see that the precision is not matching. For eg. I tried calculating the values for batch normalization layer:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/a/0/a006ccf35d32c458e46c203428e9a8dce825a3cc.png" data-download-href="https://discuss.pytorch.org/uploads/default/a006ccf35d32c458e46c203428e9a8dce825a3cc" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/a/0/a006ccf35d32c458e46c203428e9a8dce825a3cc_2_690x423.png" alt="image" data-base62-sha1="mPEXRfqW8m4QCt9kW3lW76FCTLK" width="690" height="423" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/a/0/a006ccf35d32c458e46c203428e9a8dce825a3cc_2_690x423.png, https://discuss.pytorch.org/uploads/default/optimized/3X/a/0/a006ccf35d32c458e46c203428e9a8dce825a3cc_2_1035x634.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/a/0/a006ccf35d32c458e46c203428e9a8dce825a3cc.png 2x" data-dominant-color="F8F9F8"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1304×801 82 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>How can I get the exact precison?</p>

ptrblck: <p>You won’t be able to get bitwise-identical results due to the expected errors caused by the limited floating point precision and a potentially different order of operations.<br>
Compare the output errors against a small <code>eps</code> value or use <code>allclose</code> as was done in my code snippet.</p>

Saurav_Pawar: <p>Okay, thanks!</p>
<p>In batch normalization, will it be ok if I do (modified_input*gamma+beta) where modified_input is ((input - running_mean)/standard deviation) instead of ((input-running_mean)/standard deviation)*gamma+beta?</p>
<p>It might seem trivial, but just wanted to confirm once.</p>
<p>Basically I want to express the entire batch normalization operation in terms of just addition and multiplication.</p>

ptrblck: <p>I don’t fully understand the difference between these approaches as both apply the same operation. The first one seems to store an intermediate result in the <code>modified_input</code> tensor.</p>

Saurav_Pawar: <p>Ok. Also, can you tell me how can I get better precision?</p>
<p>As you mentioned, it can’t be exact but possible to get better than the current one?</p>

ptrblck: <p>You could use a wider <code>dtype</code> such as <code>float64</code> for a smaller error.</p>

Saurav_Pawar: <p>I tried with float64 but still there is a loss of precision. Above you mentioned some reaosns for the loss but are you aware of some more reasons that contributes to the loss in precision. Also, is this dependent on framework, for pytorch the precision is different and for other frameworks it is different?</p>

ptrblck: <p>Using <code>float64</code> would reduce the error you are seeing, but will not reduce it to zero, as it’s expected to see rounding errors using floating point numbers if a different order of operations is used. Note that none of the two values are representing the theoretically “true” value e.g. in this example:</p>
<pre><code class="lang-python">x = torch.randn(100, 100, 100)
s1 = x.sum()
s2 = x.sum(0).sum(0).sum(0)
print((s1 - s2).abs())
# tensor(0.0002)
</code></pre>
<p>as both would suffer from the rounding. <a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format">This Wikipedia article</a> describes the numerical format of <code>float32</code> in more detail and explains how floating point numbers are represented.</p>
<p>The error you are seeing depends on the used algorithms, which is defined by the framework, so I would assume to see a different behavior between PyTorch, TF, etc. unless they call into the same library <em>and</em> a deterministic algorithm.</p>