# base_loss

Python API: `luxonis_train.attached_modules.losses.base_loss`

The base class every loss inherits.

## Classes

### BaseLoss

Base class for all losses.

Every subclass registers itself in the
[LOSSES](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/registry.md)
registry under its class name, unless its class statement passes `register=False`. A `register_name` in the class statement
replaces the class name. A config names a registered loss in the `losses` list of a node. A subclass implements
[forward](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md).

[BaseAttachedModule.get_parameters](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/base_attached_module.md)
describes how
[run](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
fills the parameters of
[forward](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
from predictions and labels.

The trainer calls
[run](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
on each training, validation, and test batch. It sums the main values of all losses into the total loss. The training step
backpropagates only this total.

> **Example**
> The example loss reads the `features` key of the node output. The main value is the mean, and the sub-loss `"max"` is the maximum. [run](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md) multiplies only the main value by `final_loss_weight`. `register=False` keeps the class out of the [LOSSES](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/registry.md) registry.

```pycon
>>> import torch
>>> from torch import Tensor
>>> class MeanLoss(BaseLoss, register=False):
...     def forward(
...         self, features: Tensor
...     ) -> tuple[Tensor, dict[str, Tensor]]:
...         return features.mean(), {"max": features.max()}
>>> loss = MeanLoss(final_loss_weight=2.0)
>>> packet = {"features": torch.tensor([1.0, 3.0])}
>>> main, sub_losses = loss.run(packet, {})
>>> main.item(), sub_losses["max"].item()
(4.0, 3.0)
```

#### Methods

##### init

```python
def __init__(final_loss_weight: float = 1.0, **kwargs):
```

Initialize the loss and store the factor of its main value.

Parameters

 * `final_loss_weight` (`float`): The factor by which
   [run](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
   multiplies the main value of the loss. The sub-losses stay unscaled. The trainer passes the `weight` of the loss config here.
 * `**kwargs`: Keyword arguments forwarded to
   [BaseAttachedModule](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/base_attached_module.md),
   such as `node`.

##### forward

```python
def forward(*args: Tensor | list[Tensor]) -> Tensor | tuple[Tensor, dict[str, Tensor]]:
```

Compute the loss for one batch.

An implementation declares one named parameter for each input.
[run](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
fills the parameters by name, as the class docstring describes, and passes them as keyword arguments. The tensors are copies, so a
change in place does not reach the node output or the labels.

Parameters

 * `*args` (`Tensor | list[Tensor]`): The inputs of the batch. An implementation replaces them with named parameters.

Returns

 * `Tensor | tuple[Tensor, dict[str, Tensor]]`: The main value of the loss, or a tuple of the main value and a dictionary of
   sub-losses. The trainer logs the sub-losses only when `trainer.log_sub_losses` is `True`. The total loss does not include them,
   so they do not reach the gradient.

##### run

```python
def run(inputs: Packet[Tensor], labels: Labels) -> Tensor | tuple[Tensor, dict[str, Tensor]]:
```

Resolve the inputs of
[forward](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
and apply the loss weight.

[BaseAttachedModule.get_parameters](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/base_attached_module.md)
documents how parameter names select predictions and labels.

Parameters

 * `inputs` (`Packet[Tensor]`): The output packet of the node.
 * `labels` (`Labels`): The labels of the batch, keyed `<task_name>/<label>`.

Returns

 * `Tensor | tuple[Tensor, dict[str, Tensor]]`: The result of
   [forward](https://docs.luxonis.com/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md),
   with `final_loss_weight` applied to the main value. Sub-losses remain unscaled.
