Loss functions measure the discrepancy between a model’s predictions and the ground-truth targets, producing a scalar tensor whose gradient drives parameter updates. All Clorch loss functions live inDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/antlobach/clorch/llms.txt
Use this file to discover all available pages before exploring further.
clorch.nn.functional and return regular LibTorch tensors that participate in the autograd graph.
Regression Losses
Mean Squared Error
The standard choice for continuous regression targets. Penalises large errors quadratically.L1 Loss (Mean Absolute Error)
Sums absolute differences rather than squared differences. More robust to outliers than MSE.Smooth L1 Loss (Huber Loss)
Combines the best of MSE and L1: behaves like MSE for small errors (smooth gradient near zero) and like L1 for large errors (bounded gradient, resistant to outliers). Commonly used in object detection.Classification Losses
Cross Entropy
Combineslog-softmax and negative log-likelihood in a single numerically stable operation. Expects raw logits (before any softmax), not probabilities.
NLL Loss — Negative Log Likelihood
Expects log-probabilities as input (e.g. the output ofF/log-softmax). Useful when you want to decouple the softmax step from the loss.
Binary Cross Entropy
For binary classification where each output is an independent probability in(0, 1). Input must already be passed through a sigmoid.
BCE with Logits
Numerically more stable than applying sigmoid then BCE separately. Accepts raw logits directly.Always prefer
F/bce-with-logits-loss over (F/bce-loss (F/sigmoid x) target). The fused version avoids floating-point overflow that can occur when exponentiating very large logits.Usage in a Training Loop
Loss tensors retain the full autograd graph until you callautograd/backward. The canonical pattern is:
Autograd Graph and Retention
Every call to a loss function produces a tensor whose.requires_grad is true as long as at least one input tensor requires gradients. Calling autograd/backward on that tensor computes and accumulates gradients into every leaf parameter.
Multiple backward passes
Multiple backward passes
By default LibTorch frees the intermediate computation graph after a single Retaining the graph keeps all intermediate activations in native memory until you release them explicitly, so use this only when necessary.
backward call. If you need to call backward more than once (e.g. for second-order gradients or gradient accumulation with manual graph retention), pass the :retain-graph true option: