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.
def 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.