SDE & MLE Prep

Dropout (Forward & Backward)

Key idea: inverted dropout zeros each activation with probability p during training and scales survivors by 1/(1−p), so the expected activation is unchanged and inference is a no-op. Backward multiplies the gradient by the same mask.

import numpy as np

def dropout_forward(x, p, rng, train=True):
    if not train or p == 0:
        return x, None
    mask = (rng.random(x.shape) >= p) / (1 - p)
    return x * mask, mask

def dropout_backward(dout, mask):
    return dout if mask is None else dout * mask

rng = np.random.default_rng(0)
x = np.ones((1000, 1000))
y, mask = dropout_forward(x, 0.3, rng)
assert abs(y.mean() - 1.0) < 0.01                       # expectation preserved
assert abs((y == 0).mean() - 0.3) < 0.01                # ~30% dropped
assert np.array_equal(dropout_forward(x, 0.3, rng, train=False)[0], x)   # identity at inference
assert np.array_equal(dropout_backward(np.ones_like(x), mask), mask)
print("ok, kept fraction", round(float((y != 0).mean()), 3))