Computing sigmoid then log loses precision and can produce log(0). The fused, stable form for logit and target is
Implement bce_with_logits(z, y, pos_weight=1.0) returning the mean loss, where pos_weight multiplies the positive term (as in PyTorch): . Also implement bce_with_logits_grad(z, y, pos_weight=1.0), the gradient of the mean loss with respect to z.