"""Definitions of loss reducers.Loss reducers are usually used as the last step in loss computation to averageor sum the loss maps from dense predictions or object detections."""from__future__importannotationsfromtypingimportCallablefromtorchimportTensorLossReducer=Callable[[Tensor],Tensor]
[docs]defidentity_loss(loss:Tensor)->Tensor:"""Make no change to the loss."""returnloss
[docs]defmean_loss(loss:Tensor)->Tensor:"""Average the loss tensor values to a single value. Args: loss (Tensor): Input multi-dimentional tensor. Returns: Tensor: Tensor containing a single loss value. """returnloss.mean()
[docs]defsum_loss(loss:Tensor)->Tensor:"""Sum the loss tensor values to a single value. Args: loss (Tensor): Input multi-dimentional tensor. Returns: Tensor: Tensor containing a single loss value. """returnloss.sum()
[docs]classSumWeightedLoss:"""A loss reducer to calculated weighted sum loss."""def__init__(self,weight:float|Tensor,avg_factor:float|Tensor)->None:"""Initialize the loss reducer. Args: weight (float | Tensor): Weights for each loss elements avg_factor (float | Tensor): average factor for the weighted loss """self.weight=weightself.avg_factor=avg_factor
[docs]def__call__(self,loss:Tensor)->Tensor:"""Weight the loss elements and take the sum with the average factor. Args: loss (Tensor): input loss Returns: Tensor: output loss """return(loss*self.weight).sum()/self.avg_factor