Binary cross-entropy straight from logits

EasyLosses

Applying sigmoid and then log loss in two steps is unstable. Frameworks fuse them into one stable formula that works directly on logits:

loss = max(z, 0) - z * y + log(1 + exp(-|z|))

Write bce_with_logits(z, y) that returns the mean loss over all elements as a float. z are logits and y are 0/1 targets.

Signaturedef bce_with_logits(z, y)

Understand the idea

Binary cross-entropy measures how wrong a probability is for a 0/1 target. Doing sigmoid first and then log can produce log(0) and return inf or nan for confident logits. The fused form computes the same number straight from the logit z and never passes a large positive number to exp. Worked example: z = 2, y = 1. Fused: max(2, 0) - 2 x 1 + log(1 + exp(-2)) = 0 + log(1.135) = 0.127, which equals -log(sigmoid(2)) = -log(0.881). For z = -2, y = 1: 0 + 2 + 0.127 = 2.127, a big loss for a confident wrong answer. For z = 1000, y = 0, the two-step version breaks, but the fused one gives 1000 - 0 + log(1 + ~0) = 1000. Rule: loss = max(z, 0) - z y + log(1 + exp(-|z|)), averaged over all elements. PyTorch's BCEWithLogitsLoss uses this form, and it trains binary classifiers and reward heads.

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

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

  • Sample 1: small logitsbce_with_logits([0.0, 2.0, -1.0], [1, 1, 0])
  • Sample 2: confident and wrongbce_with_logits([800.0, -800.0], [0, 1])
  • Test 3: confident and rightbce_with_logits([50.0], [1])