Skip to content
class

BCEWithLogitsBackward

BCEWithLogitsBackward

Autograd node for sigmoid + binary cross-entropy fused for numerical stability.

Equivalent to BCELoss(Sigmoid(x), y) but evaluated using the log-sum-exp identity log⁡(1+ex)=max⁡(x,0)+log⁡(1+e−∣x∣)\log(1 + e^x) = \max(x, 0) + \log(1 + e^{-|x|}) so that no intermediate sigmoid value is required:

ℓ(x,y)=max⁡(x,0)−x⋅y+log⁡(1+e−∣x∣) \ell(x, y) = \max(x, 0) - x \cdot y + \log\bigl(1 + e^{-|x|}\bigr)

When pos_weight is supplied, positive examples are re-weighted as ℓ(x,y)=−p⋅ylog⁡σ(x)−(1−y)log⁡(1−σ(x))\ell(x, y) = -p \cdot y \log \sigma(x) - (1 - y) \log(1 - \sigma(x)) where σ\sigma is the sigmoid; the closed form above is rearranged internally to remain numerically stable.

Math

ℓ(x,y)=max⁡(x,0)−xy+log⁡(1+e−∣x∣) \ell(x, y) = \max(x, 0) - x y + \log\bigl(1 + e^{-|x|}\bigr)

with an additional positive-class scale pp applied to the ylog⁡σ(x)y \log \sigma(x) term when pos_weight is non-trivial.

Attributes

schema_v1OpSchema
"bce_with_logits", AmpPolicy::ForceFP32.
reduction_Reduction
Reduction mode.
orig_shape_Shape
Element-wise shape before reduction.

Notes

Always prefer this op over a manual Sigmoid → BCELoss chain: the fused form preserves gradient magnitude in the saturated regions of the sigmoid where the explicit decomposition produces vanishing gradients.

Static methods

1
static

forward

→TensorImplPtr
int forward(const int & input, const int & target, const int & weight, const int & pos_weight, Reduction reduction)

Compute BCE-with-logits loss with autograd wiring.

Parameters

inputTensorImplPtr
Raw logits (any real value); arbitrary shape.
targetTensorImplPtr
Binary labels in {0,1}\{0, 1\}; same shape as input.
weightTensorImplPtr
Per-element weighting; broadcastable to input.shape().
pos_weightTensorImplPtr
Positive-class re-weighting; shape broadcastable to the channel dimension of input. Pass a ones tensor if unused.
reductionReduction
Mean, Sum, or None.

Returns

TensorImplPtr

Reduced or per-element loss tensor.

Methods

1
fn

apply

int apply(int grad_out)

Backward pass: gradients w.r.t. input, target, weight, pos_weight.