o
    wi                     @   sT   d dl Z d dlmZmZmZ d dlmZmZmZm	Z	m
Z
 dgZG dd deeZdS )    N)LossTyping	typecheck)
LabelsTypeLengthsTypeLossType
NeuralType	ProbsTypeBCELossc                       sz   e Zd ZdZedd Zedd Zddedd	gd
d
d
fde	de
dejdededef fddZe dd Z  ZS )r
   zk
    Computes Binary Cross Entropy (BCE) loss. The BCELoss class expects output from Sigmoid function.
    c                 C   s$   t dt t dt t dt dS )z'Input types definitions for AnguarLoss.)BTCr   )probslabelstarget_lens)r   r	   r   r   self r   a/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/nemo/collections/asr/losses/bce_loss.pyinput_types   s   


zBCELoss.input_typesc                 C   s   dt t diS )z
        Output types definitions for binary cross entropy loss. Weights for labels can be set using weight variables.
        loss)elements_type)r   r   r   r   r   r   output_types&   s   zBCELoss.output_typesmean      ?g?g?F	reductionalphaweightsorted_predssorted_lossclass_normalizationc                    sP   t    || _|rd| _nd| _|| _tjj| jd| _|| _	|| _
d| _dS )a!  
        A custom loss function that supports class normalization,
        weighted binary cross-entropy, and optional sorting.

        Args:
            reduction (str): Specifies the reduction to apply to the output,
                options are 'mean', 'sum', or 'none'. Default is 'mean'.
            alpha (float): Scaling factor for loss (unused in this implementation). Default is 1.0.
            weight (torch.Tensor): Class weights for the binary cross-entropy loss. Default is [0.1, 0.9].
            sorted_preds (bool): If True, assumes predictions are sorted. Default is False.
            sorted_loss (bool): If True, sorts the loss before reduction. Default is False.
            class_normalization (bool): If True, uses 'none' reduction for per-class loss. Default is False.
        noner   )r   gư>N)super__init__r    r   loss_weighttorchnnr
   loss_fr   r   eps)r   r   r   r   r   r   r    	__class__r   r   r#   -   s   

zBCELoss.__init__c                    s"  fddt jd D } fddt  jd D }tj|ddtj|dd t   }td j	}| j
dv r| j
dv rwd	 jdd| j  }||  }tj|d
dd}||  }|dddf    }n	t   }| j
dv rt   }	   jd  jd	    j	}
|
|	 dk< d	|
 |	 d	k< n$t   }	n| j
dks| j
st   }	t   }| jdkr|  }|S | jdkr|   }|S | jdkr| j
dv r	|	| |    }|S |  }|S )a)  
        Calculate binary cross entropy loss based on probs, labels and target_lens variables.

        Args:
            probs (torch.tensor)
                Predicted probability value which ranges from 0 to 1. Sigmoid output is expected.
            labels (torch.tensor)
                Groundtruth label for the predicted samples.
            target_lens (torch.tensor):
                The actual length of the sequence without zero-padding.

        Returns:
            loss (NeuralType)
                Binary cross entropy loss value.
        c                    &   g | ]} |d | d d f qS Nr   .0k)r   r   r   r   
<listcomp>`      & z#BCELoss.forward.<locals>.<listcomp>r   c                    r+   r,   r   r-   )r   r   r   r   r0   a   r1   )dimg        )classclass_binarybinary)r3   r4      g?r   )minmaxN)r5   r4   r!   sumr   )rangeshaper%   cat
zeros_likedetachclonetensortodevicer    r9   r(   clampr8   	expand_as	ones_liker   r'   r   )r   r   r   r   
probs_listtargets_listnorm_weightr   norm_weight_normbinary_weight
one_weightr   )r   r   r   r   forwardO   sF   

 
$

zBCELoss.forward)__name__
__module____qualname____doc__propertyr   r   r%   r@   strfloatTensorboolr#   r   rL   __classcell__r   r   r)   r   r
      s6    

")r%   nemo.core.classesr   r   r   nemo.core.neural_typesr   r   r   r   r	   __all__r
   r   r   r   r   <module>   s
   