cross_entropy(x: Tensor, target: Tensor, weight: Tensor | None = None, ignore_index: int = -100, reduction: Reduction = 'mean', label_smoothing: float = 0.0)Implementing kernel
C++ engine symbols that back this Python API.Cross-entropy loss for multi-class classification.
The canonical training objective for categorical classifiers.
Combines lucid.nn.functional.log_softmax and
nll_loss into a single, numerically stable expression —
operating directly on raw logits avoids the catastrophic
cancellation that arises when softmax probabilities are taken
to log(). Implements the full contract: per-class
weight rescaling, ignore_index masking, and
label-smoothing regularisation.
Parameters
"none").targetTensorx; any other shape raises ValueError. An
index outside that is not ignore_index raises
IndexError for a CPU tensor; on Metal, where reading the
target back would stall every step, it makes the loss NaN
instead.ValueError.ignore_indexint= -100-100).
Common for masked / padded targets in sequence models.reductionstr= 'mean'"mean" (default), "sum", or "none". Under
"mean", the divisor is the sum of effective sample weights
(after weight and ignore_index), not the raw element
count — for class-index targets. For class-probability targets
it is the number of samples, and ignore_index must be left
negative.label_smoothingfloat= 0.01.0 the target is the uniform
distribution itself. Acts as a regulariser by discouraging
over-confident predictions. A value outside
raises ValueError.Returns
TensorScalar ("mean"/"sum") or per-sample tensor ("none").
Notes
Per-sample loss:
where is the (smoothed) target distribution.
With label_smoothing = \alpha,
Gradient w.r.t. the logits has the well-known clean form (up to weighting), which is the reason cross-entropy is preferred over MSE for classification: no sigmoid saturation, no vanishing gradient.
Examples
>>> import lucid
>>> from lucid.nn.functional import cross_entropy
>>> logits = lucid.tensor([[2.0, 0.5, 0.1], [0.0, 1.5, 0.2]])
>>> target = lucid.tensor([0, 1])
>>> cross_entropy(logits, target)
tensor(0.3597)