Skip to content
class

NLLLossBackward

NLLLossBackward

Python wrappers

Public Python APIs implemented by this engine symbol.

Autograd node for negative log-likelihood loss.

Operates on log-probabilities (e.g. the output of log_softmax). The per-sample loss is

ℓn=−wyn xn,yn \ell_n = -w_{y_n} \, x_{n, y_n}

and the final scalar is obtained by reducing ℓ\ell according to reduction_; samples whose target equals ignore_index_ are skipped. The backward emits a sparse gradient that is nonzero only at the target class:

∇x[n,c,…]={−wyn gn/N′c=yn0otherwise \nabla_x[n, c, \ldots] = \begin{cases} -w_{y_n} \, g_n / N' & c = y_n \\ 0 & \text{otherwise} \end{cases}

Math

Lnll=−1N′∑n:yn≠ignorewyn xn,yn \mathcal{L}_{\text{nll}} = -\frac{1}{N'} \sum_{n: y_n \neq \text{ignore}} w_{y_n} \, x_{n, y_n}

Attributes

schema_v1OpSchema
"nll_loss", AmpPolicy::ForceFP32.
reduction_Reduction
Reduction mode.
ignore_index_int
Target class to skip; default -100.
has_weight_bool
Whether saved_weight_ is populated.
orig_input_shape_Shape
Full input shape (N, C, ...) for backward reconstruction.
saved_target_Storage
Integer class labels.
saved_weight_Storage
Optional per-class weight vector.
saved_valid_count_Storage
Scalar count of non-ignored samples for the Mean denominator.

Notes

Feeding raw logits or softmax probabilities produces incorrect results — the input must already be in log-probability space. Prefer CrossEntropyBackward when starting from logits.

Static methods

1
static

forward

→TensorImplPtr
int forward(const int & input, const int & target, const int & weight_or_null, Reduction reduction, int ignore_index)

Compute NLL loss with autograd wiring.

Parameters

inputTensorImplPtr
Log-probabilities of shape (N, C) or (N, C, d_1, ...).
targetTensorImplPtr
Integer class labels of shape (N,) or (N, d_1, ...).
weight_or_nullTensorImplPtr
Optional per-class weight vector of length CC; may be null.
reductionReduction
Mean, Sum, or None.
ignore_indexint
Class index excluded from the loss / gradient.

Returns

TensorImplPtr

Reduced or per-sample loss tensor.

Methods

2
fn

apply

int apply(int grad_out)

Backward pass: gradient w.r.t. log-probability input.

fn

release_own_saved

void release_own_saved()