BatchNorm1d - input shape

adm: <p>As far as I understand the documentation for BatchNorm1d layer we provide number of features as argument to constructor(<code>nn.BatchNorm1d(number of features)</code>).</p>
<p>As an input the layer takes <em>(N, C, L)</em>, where <em>N</em> is batch size (I guess…), <em>C</em> is the number of features (this is the dimension where normalization is computed), and <em>L</em> is the input size.</p>
<p>Let’s assume I have <strong>input</strong> in following shape:<br>
<code>(batch_size, number_of_timesteps, number_of_features)</code><br>
which is usual data shape for time series if <em>batch_first=True</em>.</p>
<p><strong>Question</strong><br>
Should I transpose the input (swap dimension 1 and 2) before running the batch normalization?</p>
<p>In this case I will have to transpose the output again to use it in <em>RNN</em> later. It looks quite weird to me.</p>
<p>Can someone please take a look at below example and let me know if this is the proper way.</p>
<p>E.g.:</p>
<pre><code class="lang-auto">import torch
from torch import nn

# data (batch size, number of time steps, number of features)
x = torch.rand(3, 4, 5)
 
# layers
bn = nn.BatchNorm1d(5)
rnn = nn.RNN(5, 10, 1, batch_first=True)
 
# computation - transpose TWICE
x_normalized = bn(x.transpose(1, 2)).transpose(1, 2)
rnn(x_normalized)
</code></pre>

ptrblck: <p>Your code looks correct, since the batchnorm layer expects an input in <code>[batch_size, features, temp. dim]</code> so you would need to permute it before (and after to match the input of the rnn).<br>
In your code snippet you could of course initialize the tensor in the right shape, but I assume that code is just to show the usage.</p>

raraz15: <p>Isn’t this a fundamentally flawed approach? BatchNorm1d is not working harmoniously with nn.Linear, which is the most fundamental part of PyTorch. This makes it not possible to use BatchNorm and Linear layer in the sequential format. At least to my knowledge.</p>

ptrblck: <p>It depends on what you are trying to achieve and I wouldn’t claim the approach is fundamentally flawed, as I’m not familiar with the use case of <a class="mention" href="/u/adm">@adm</a>.</p>
<aside class="quote no-group" data-username="raraz15" data-post="3" data-topic="91364">
<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/raraz15/48/38741_2.png" class="avatar"> raraz15:</div>
<blockquote>
<p>This makes it not possible to use BatchNorm and Linear layer in the sequential format. At least to my knowledge.</p>
</blockquote>
</aside>
<p>You can use <code>nn.BatchNorm1d</code> layers in an <code>nn.Sequential</code> container as seen here:</p>
<pre data-code-wrap="python"><code class="lang-python">model = nn.Sequential(
    nn.Linear(4, 3),
    nn.BatchNorm1d(3)
)

x = torch.randn(2, 4)
out = model(x)
</code></pre>
<p>If you add another dimension and want to <code>permute</code> the activation, you could write a custom module, which permutes it to the right shape.</p>

raraz15: <p>For 2D Batches it works great. However, when we use fully connected layers for 3D inputs of shape (N=batch size,L=sequence length,C=input size) we have to transpose 2 times to use BatchNorm1D after each linear transformation. Because each linear layer acts upon dim=-1 (our features) and BatchNorm can act only on dim=1, 2 transpositions must be done: before and after the BatchNorm. For example, a fully connected network of 3 layers is given below with BatchNorm before each non-linearity.</p>
<pre><code class="lang-auto">class FC_layer(nn.Module):
    def __init__(self,input_size_FC1,output_size_FC1,output_size_FC2,output_size_FC3):
        super(FC_layer, self).__init__()
        
        self.linear_layer1 = nn.Linear(input_size_FC1,output_size_FC1)
        self.normalization1 = nn.BatchNorm1d(output_size_FC1)
        self.linear_layer2 = nn.Linear(output_size_FC1,output_size_FC2)
        self.normalization2 = nn.BatchNorm1d(output_size_FC2)
        self.linear_layer3 = nn.Linear(output_size_FC2,output_size_FC3)
        self.normalization3 = nn.BatchNorm1d(output_size_FC3)
                        
    def forward(self,x):
    """ 
        x : tensor of shape (N_batch, N_sequence, N_features)
    """
        
        f = nn.ReLU() # Activation functions
        g = nn.LogSoftmax(dim=2)
               
        x_lin1 = self.linear_layer1(x) # Apply linear transformation
        x_lin1 = torch.transpose(x_lin1,1,2) # Transpose for BatchNorm1d
        x_lin1_norm = self.normalization1(x_lin1) # Normalize
        
        layer1_out = f(x_lin1_norm) # Apply non-linearity
        
        layer2_in = torch.transpose(layer1_out,1,2)  # Transpose for next linear transformation
        
        x_lin2 = self.linear_layer2(layer2_in)
        x_lin2 = torch.transpose(x_lin2,1,2)
        x_lin2_norm = self.normalization2(x_lin2)  
        
        layer2_out = f(x_lin2_norm) 
        
        layer3_in = torch.transpose(layer2_out,1,2) # Transpose for next linear transformation
        
        x_lin3 = self.linear_layer3(layer3_in)
        x_lin3 = torch.transpose(x_lin3,1,2)
        x_lin3_norm = self.normalization3(x_lin3)  
        
        layer3_out = g(x_lin3_norm)
        
        output = torch.transpose(layer3_out,1,2)      
                
        return output
</code></pre>
<p>Instead, if BatchNorm1d could act upon the final dimension, we wouldn’t need to worry about the dimensions conversions.</p>
<p>I couldn’t find a way to do this in the sequential container, but you are suggesting that I could write a permutation module with no parametes and use this in the sequential container. Right? I am worried a about  the necessity to do a copy()  or replace the tensor with its transposed version. Also about the contiguous requirment of other pytorch functionalities.</p>

alessio_brini: <p>Is there currently any way to avoid the permutation before and after the BatchNorm1d in a sequential container? I just need to apply that before an LSTM layer and I am not able to do the permutation suggested</p>