Batch Norm Folding

Fold the batchnorm and the conv layers together to reduce computation

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}\]

In practice, this can be achieved in FasterAI with the BN_folder class


BN_Folder.fold

 BN_Folder.fold (model)

A tutorial about how to use the BN_Folder functionalities can be found here