nll_loss(x: Tensor, target: Tensor, weight: Tensor | None = None, ignore_index: int = -100, reduction: Reduction = 'mean')Implementing kernel
C++ engine symbols that back this Python API.Negative log-likelihood loss for multi-class classification.
The "back-half" of cross_entropy: assumes the input is
already a tensor of log-probabilities (typically produced by
lucid.nn.functional.log_softmax). Provided as a
separate entry-point so models that need log-probabilities for
downstream use (e.g., beam search) can avoid recomputing them.
Parameters
Log-probabilities of shape or
, or for one unbatched
sample (with a 0-d target, and a 0-d loss under
"none").targetTensorInteger class indices of shape /
; any other shape raises
ValueError. An index outside that is not
ignore_index raises IndexError for a CPU tensor and makes
the loss NaN on Metal.Per-class weight vector . Any other shape raises
ValueError.ignore_indexint= -100Class index whose samples are excluded (default
-100).reductionstr= 'mean'"mean" (default), "sum", or "none".Returns
TensorScalar or per-sample tensor depending on reduction.
Notes
Per-sample loss:
Under "mean" reduction, the divisor is the sum of effective
sample weights — i.e.,
— not the raw count. This matches the standard convention so
that the loss is invariant to a global rescaling of weight.
Examples
>>> import lucid
>>> from lucid.nn.functional import nll_loss, log_softmax
>>> logits = lucid.tensor([[2.0, 0.5, 0.1], [0.0, 1.5, 0.2]])
>>> target = lucid.tensor([0, 1])
>>> nll_loss(log_softmax(logits, dim=1), target)
tensor(0.3597)