Skip to content

← Normalization step 5 of 6

Medium Primitives

Implement Dropout

Dropout is a training-time regularization technique that randomly drops some activations. In inverted dropout, the values that remain are scaled up by the reciprocal of their keep probability.

This exercise supplies the mask directly. Your function applies that mask and scaling; it must not sample random values or create a new mask.

Your task

Implement dropout(x, mask, p=0.5) using basic elementwise operations. Do not call a built-in dropout layer or function.

  • x is a finite floating-point tensor of any shape.
  • mask has the same shape, dtype and device as x. Its values are 1 for keep and 0 for drop.
  • p is a scalar drop probability with 0 <= p < 1; the keep probability is 1 - p. The case p=1 is outside this exercise's contract.

Compute:

output = x * mask / (1 - p)

Return the same shape and dtype as x, leaving the inputs unchanged. Apply the supplied mask even if its observed fraction of zeros differs from p. Do not infer a new scaling factor from the mask or the number of kept entries.

For x=[-2, 4, 6], mask=[1, 0, 1] and p=0.5, return [-4, 0, 12]. For an all-zero mask, return zeros. For an all-one mask, still divide by 1 - p. With p=0, the expression reduces to x * mask.

Why scale the kept values?

If a random mask keeps each activation with probability 1 - p, then its average multiplier is (1 - p) / (1 - p) = 1. This preserves each activation's expected value over repeated random masks. It does not preserve the sum or mean for every individual mask.

During ordinary evaluation, inverted dropout is disabled and inputs pass through unchanged. This function has no evaluation-mode flag: it always applies the supplied training-time mask and scale.