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

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

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

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

  • Sample 1: moderate valuessigmoid_and_log([-2.0, 0.0, 3.0])
  • Sample 2: very negative log-sigmoid is exactsigmoid_and_log([-1000.0, -50.0])[1]
  • Test 3: very positivesigmoid_and_log([1000.0])