Write a sigmoid and log-sigmoid that never overflow
sigmoid(x) = 1 / (1 + exp(-x)) looks harmless, but exp(-x) overflows for x = -1000, and log(sigmoid(x)) becomes log(0) = -inf. Losses like DPO and binary cross-entropy need log-sigmoid that stays exact.
Write sigmoid_and_log(x) that returns (s, ls) for an array x: s = sigmoid(x) and ls = log(sigmoid(x)). Both must be finite and accurate for x anywhere in [-1000, 1000].
def sigmoid_and_log(x)Understand the idea
The sigmoid squashes any number into (0, 1), but the textbook formula breaks at extremes: exp(1000) overflows, and log(sigmoid(-1000)) becomes log(0) = -inf, even though the true answer is about -1000. The fix is to split on the sign so exp only ever sees a number at or below zero. Worked example: x = 0 gives s = 0.5 and log-sigmoid = -0.693. For x = -1000, use s = exp(x) / (1 + exp(x)), which is a tiny finite number, and log-sigmoid = x - log1p(exp(x)) = -1000 - log1p(about 0) = -1000. For x = 1000, s = 1 / (1 + exp(-1000)) = 1, and log-sigmoid = -log1p(exp(-1000)), about 0. A compact rule: log_sigmoid(x) = min(x, 0) - log1p(exp(-|x|)). log1p is accurate when its argument is tiny. Binary cross-entropy, DPO and reward model losses all need a log-sigmoid that never returns -inf.