# Scaling in Neural Network Dropout Layers (with Pytorch code example)

For several times I confused myself over how and why a dropout layer scales its input. I’m writing down some notes before I forget again.

In Pytorch doc it says:

Furthermore, the outputs are scaled by a factor of 1/(1-p) during training. This means that during evaluation the module simply computes an identity function.

So how is this done and why? Let’s look at some code in Pytorch.

Create a dropout layer `m` with a dropout rate `p=0.4`:

As explained in Pytorch doc:

During training, randomly zeroes some of the elements of the input tensor with probability `p` using samples from a Bernoulli distribution. The elements to zero are randomized on every forward call.

Put a random input through the dropout layer and confirm that ~40% (`p=0.4`) of the elements have become 0:

We now look at the scaling part:

Furthermore, the outputs are scaled by a factor of 1/(1-p) during training.

Create a smaller random input and put it through the dropout layer. Compare input and output:

We can see below that the outputs are scaled by a factor of 1/(1-p) during training, by comparing the non-zero elements in the two tensors below:

We can assert that observation in code:

So why does it does this? In the doc:

This means that during evaluation the module simply computes an identity function.

This basically says during evaluation/test/inference time, the dropout layer becomes an identity function and makes no change to its input.

Because dropout is active only during training time but not inference time, without the scaling, the expected output would be larger during inference time because the elements are no longer being randomly dropped (set to 0). But we want the expected output with and without going through the dropout layer to be the same. Therefore, during training, we compensate by making the output of the dropout layer larger by the scaling factor of `1/(1−p)`. A larger `p` means more aggressive dropout, which means the more compensation we need, i.e. the larger the scaling factor `1/(1−p)`.

​The code below demonstrates how scaling factor put output back to the same scale as the input.

Instead of making the output of the dropout layer larger during training, one could equivalently make the output of the identity function during inference smaller. However the former is easier to implement. There is a discussion on StackOverflow that provides some details. But be careful, `p` in that discussion (from slides of Standford CS231n: Convolutional Neural Networks for Visual Recognition) is the ratio for keeping instead of for dropping.

Software Engineering SMTS at Salesforce Commerce Cloud Einstein

## More from Yang Zhang

Software Engineering SMTS at Salesforce Commerce Cloud Einstein