Binary cross-entropy straight from logits
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.
def 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.