<jupyter_start><jupyter_text>Batch Norm Folding> Fold the batchnorm and the conv layers together to reduce computation<jupyter_code>#all_slow
#hide
from nbdev.showdoc import *

%config InlineBackend.figure_format = 'retina'
#export
from fastai.vision.all import *

import torch
import torch.nn as nn
import torch.nn.functional as F<jupyter_output><empty_output><jupyter_text>Batch Normalization is a technique which takes care of normalizing the input of each layer to make the training process faster and more stable. In practice, it is an extra layer that we generally add after the computation layer and before the non-linearity.It consists of 2 steps:1. Normalize the batch by first subtracting its mean $\mu$, then dividing it by its standard deviation $\sigma$.2. Further scale by a factor $\gamma$ and shift by a factor $\beta$. Those are the parameters of the batch normalization layer, required in case of the network not needing the data to have a mean of $0$ and a standard deviation of $1$. $$\begin{aligned}\mu_{\mathcal{B}} & \leftarrow \frac{1}{m} \sum_{i=1}^{m} x_{i} \\ \sigma_{\mathcal{B}}^{2} & \leftarrow \frac{1}{m} \sum_{i=1}^{m}\left(x_{i}-\mu_{\mathcal{B}}\right)^{2} \\ \widehat{x}_{i} & \leftarrow \frac{x_{i}-\mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^{2}+\epsilon}} \\ y_{i} & \leftarrow \gamma \widehat{x}_{i}+\beta \equiv \mathrm{BN}_{\gamma, \beta}\left(x_{i}\right) \end{aligned}$$ Due to its efficiency for training neural networks, batch normalization is now widely used. But how useful is it at inference time?Once the training has ended, each batch normalization layer possesses a specific set of $\gamma$ and $\beta$, but also $\mu$ and $\sigma$, the latter being computed using an exponentially weighted average during training. It means that during inference, the batch normalization acts as a simple linear transformation of what comes out of the previous layer, often a convolution.As a convolution is also a linear transformation, it also means that both operations can be merged into a single linear transformation!This would remove some unnecessary parameters but also reduce the number of operations to be performed at inference time. With a little bit of math, we can easily rearrange the terms of the convolution to take the batch normalization into account.As a little reminder, the convolution operation followed by the batch normalization operation can be expressed, for an input $x$, as: $$\begin{aligned} z &=W * x+b \\ \mathrm{out} &=\gamma \cdot \frac{z-\mu}{\sqrt{\sigma^{2}+\epsilon}}+\beta \end{aligned}$$ So, if we re-arrange the $W$ and $b$ of the convolution to take the parameters of the batch normalization into account, as such: $$\begin{aligned} w_{\text {fold }} &=\gamma \cdot \frac{W}{\sqrt{\sigma^{2}+\epsilon}} \\ b_{\text {fold }} &=\gamma \cdot \frac{b-\mu}{\sqrt{\sigma^{2}+\epsilon}}+\beta \end{aligned}$$ This is how to do it with fasterai !<jupyter_code>path = untar_data(URLs.PETS)
files = get_image_files(path/"images")

def label_func(f): return f[0].isupper()
dls = ImageDataLoaders.from_name_func(path, files, label_func, item_tfms=Resize(64))
learn = Learner(dls, resnet18(num_classes=2), metrics=accuracy)
learn.fit_one_cycle(5)
#export
import copy

class BN_Folder():
    def __init__(self):
        super().__init__()
        
    def fold(self, model):

        new_model = copy.deepcopy(model)

        module_names = list(new_model._modules)

        for k, name in enumerate(module_names):

            if len(list(new_model._modules[name]._modules)) > 0:
                new_model._modules[name] = self.fold(new_model._modules[name])

            else:
                if isinstance(new_model._modules[name], nn.BatchNorm2d):
                    if isinstance(new_model._modules[module_names[k-1]], nn.Conv2d):

                        # Folded BN
                        folded_conv = self._fold_conv_bn_eval(new_model._modules[module_names[k-1]], new_model._modules[name])

                        # Replace old weight values
                        #new_model._modules.pop(name) # Remove the BN layer
                        new_model._modules[module_names[k]] = nn.Identity()
                        new_model._modules[module_names[k-1]] = folded_conv # Replace the Convolutional Layer by the folded version

        return new_model


    def _bn_folding(self, conv_w, conv_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b):
        if conv_b is None:
            conv_b = bn_rm.new_zeros(bn_rm.shape)
        bn_var_rsqrt = torch.rsqrt(bn_rv + bn_eps)

        w_fold = conv_w * (bn_w * bn_var_rsqrt).view(-1, 1, 1, 1)
        b_fold = (conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b

        return torch.nn.Parameter(w_fold), torch.nn.Parameter(b_fold)


    def _fold_conv_bn_eval(self, conv, bn):
        assert(not (conv.training or bn.training)), "Fusion only for eval!"
        fused_conv = copy.deepcopy(conv)

        fused_conv.weight, fused_conv.bias = self._bn_folding(fused_conv.weight, fused_conv.bias,
                                 bn.running_mean, bn.running_var, bn.eps, bn.weight, bn.bias)

        return fused_conv
bn = BN_Folder()
#hide
def count_parameters(model):
    return sum(p.numel() for p in model.parameters())
new_model = bn.fold(learn.model)<jupyter_output><empty_output><jupyter_text>The batch norm layers have been replaced by an Identity layer, and the weights of the convolutions have been modified accordingly.<jupyter_code>new_model<jupyter_output><empty_output><jupyter_text>We can see that the new model possess fewer parameters<jupyter_code>count_parameters(learn.model)
count_parameters(new_model)<jupyter_output><empty_output><jupyter_text>But is also faster to run !<jupyter_code>x,y = dls.one_batch()
%%timeit
learn.model(x[0][None].cuda())
%%timeit
new_model(x[0][None].cuda())<jupyter_output>4.14 ms ± 446 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)<jupyter_text>But most importantly, has the exact same perfomance as before:<jupyter_code>new_learn = Learner(dls, new_model, metrics=accuracy)
new_learn.validate()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11282640827722122, 'fraction_numerical': 0.007226145508293644, 'mean_word_length': 3.9192245557350565, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '422716', 'license': 'Apache-2.0', 'n_tokens_mistral': 1925, 'n_tokens_neox': 1828, 'n_words': 593, 'path': 'nbs/06_bn_folding.ipynb', 'repo_name': 'nathanhubens/fasterai', 'size': '6089'}