Implement inverted dropout

Dropout randomly zeros activations during training. Inverted dropout also scales the survivors by 1 / (1 - p) so the expected value stays the same and nothing changes at inference time.

Write dropout(x, p, training, rng). In training, build the keep mask with rng.random(x.shape) >= p, return x * mask / (1 - p). Not training, or p == 0: return x unchanged (as a float array).

Draw exactly one rng.random call of shape x.shape so results match.

Signaturedef dropout(x, p, training, rng)

Understand the idea

Dropout randomly switches off activations during training so the network cannot rely on any single unit, like a team practising with random players missing. Inverted dropout divides the survivors by (1 - p), so the expected value of each activation stays the same and nothing needs to change at test time. Worked example: x = [2, 4, 6, 8], p = 0.5, and the random draws are [0.7, 0.2, 0.9, 0.4]. Keep where draw >= 0.5, so the mask is [1, 0, 1, 0]. Output = [2, 0, 6, 0] / 0.5 = [4, 0, 12, 0]. On average the kept values make up for the dropped ones. In evaluation mode, or when p = 0, return x unchanged as floats. Rule: mask = rng.random(x.shape) >= p; out = x x mask / (1 - p) in training only. Call rng.random exactly once with the full shape so results are reproducible. Dropout is used in many networks and in some LLM fine-tuning setups.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: trainingdropout(np.ones((2, 4)), 0.5, True, np.random.default_rng(0))
  • Sample 2: eval is identitydropout([1.0, 2.0], 0.5, False, np.random.default_rng(0))
  • Test 3: mean is preservedround(float(dropout(np.ones(20000), 0.3, True, np.random.default_rng(1)).mean()), 1)