o
    _{j  ã                   @   sN   d dl Z d dlm  mZ ddlmZ ddlmZ e 	¡ G dd„ deƒƒZ
dS )é    Né   )ÚLOSSESé   )ÚBaseWeightedLossc                       s8   e Zd ZdZ							d‡ fd	d
„	Zdd„ Z‡  ZS )ÚHVULossa/  Calculate the BCELoss for HVU.

    Args:
        categories (tuple[str]): Names of tag categories, tags are organized in
            this order. Default: ['action', 'attribute', 'concept', 'event',
            'object', 'scene'].
        category_nums (tuple[int]): Number of tags for each category. Default:
            (739, 117, 291, 69, 1678, 248).
        category_loss_weights (tuple[float]): Loss weights of categories, it
            applies only if `loss_type == 'individual'`. The loss weights will
            be normalized so that the sum equals to 1, so that you can give any
            positive number as loss weight. Default: (1, 1, 1, 1, 1, 1).
        loss_type (str): The loss type we calculate, we can either calculate
            the BCELoss for all tags, or calculate the BCELoss for tags in each
            category. Choices are 'individual' or 'all'. Default: 'all'.
        with_mask (bool): Since some tag categories are missing for some video
            clips. If `with_mask == True`, we will not calculate loss for these
            missing categories. Otherwise, these missing categories are treated
            as negative samples.
        reduction (str): Reduction way. Choices are 'mean' or 'sum'. Default:
            'mean'.
        loss_weight (float): The loss weight. Default: 1.0.
    ©ÚactionÚ	attributeZconceptÚeventÚobjectÚscene©iã  éu   i#  éE   iŽ  éø   ©r   r   r   r   r   r   ÚallFÚmeanç      ð?c           
         s¼   t ƒ  |¡ || _|| _|| _t| jƒt| jƒksJ ‚| jD ]}|dks&J ‚q|| _|| _|| _dg| _	t
t| jƒd ƒD ]}	| j	 | j	d | j|	  ¡ q=| jdv sUJ ‚| jdv s\J ‚d S )Nr   r   éÿÿÿÿ)Ú
individualr   )r   Úsum)ÚsuperÚ__init__Ú
categoriesÚcategory_numsÚcategory_loss_weightsÚlenÚ	loss_typeÚ	with_maskÚ	reductionÚcategory_startidxÚrangeÚappend)
Úselfr   r   r   r   r   r    Úloss_weightZcategory_loss_weightÚi©Ú	__class__© ú5/root/disk_3tb/HAC/mmaction/models/losses/hvu_loss.pyr   "   s"   

ÿzHVULoss.__init__c                    sL  | j dkrGtj||dd�}| jr3|| }tj|dd�}| jdkr)|tj|dd� }t |¡}t|d�S | jdkr?tj|d	d�}tt |¡d�S | j d
k�ri ‰i ‰t	| j
| j| jƒD ]’\}}}	|dd…|	|	| …f }
|dd…|	|	| …f }tj|
|dd�}| jdkrŒtj|dd�}n| jdkr˜tj|dd�}| j
 |¡}| jrÖ|dd…|f  d	¡}t |¡dk rÇt d¡ ¡ ˆ|› d�< dˆ|› d�< qZt || ¡}|t |¡ }nt |¡}|ˆ|› d�< | j| ˆ|› d�< qZtˆ ¡ ƒ‰ ‡ fdd„ˆ ¡ D ƒ‰t‡‡fdd„ˆD ƒƒ}|ˆd< ˆ ‡fdd„ˆ ¡ D ƒ¡ ˆS td| j › �ƒ‚)aQ  Forward function.

        Args:
            cls_score (torch.Tensor): The class score.
            label (torch.Tensor): The ground truth label.
            mask (torch.Tensor): The mask of tags. 0 indicates that the
                category of this tag is missing in the label of the video.
            category_mask (torch.Tensor): The category mask. For each sample,
                it's a tensor with length `len(self.categories)`, denotes that
                if the category is labeled for this video.

        Returns:
            torch.Tensor: The returned CrossEntropy loss.
        r   Únone)r    r   )Údimr   )Úloss_clsr   r   r   Ng      à?g        Z_LOSSc                    s   i | ]	\}}||ˆ  “qS r)   r)   ©Ú.0ÚkÚv)Úloss_weight_sumr)   r*   Ú
<dictcomp>~   s    ÿÿz$HVULoss._forward.<locals>.<dictcomp>c                    s   g | ]
}ˆ| ˆ |  ‘qS r)   r)   )r/   r0   )Úloss_weightsÚlossesr)   r*   Ú
<listcomp>‚   s    z$HVULoss._forward.<locals>.<listcomp>r-   c                    s,   i | ]\}}|d  t  |¡ ˆ | j¡“qS )Ú_weight)ÚtorchÚtensorÚtoÚdevicer.   )r5   r)   r*   r3   …   s    ÿÿz3loss_type should be 'all' or 'individual', but got )r   ÚFÚ binary_cross_entropy_with_logitsr   r8   r   r    r   ÚdictÚzipr   r   r!   ÚindexÚreshaper9   Úcudar   ÚvaluesÚitemsÚupdateÚ
ValueError)r$   Ú	cls_scoreÚlabelÚmaskÚcategory_maskr-   Z
w_loss_clsÚnameÚnumÚ	start_idxZcategory_scoreZcategory_labelZcategory_lossÚidxZcategory_mask_ir)   )r2   r4   r5   r*   Ú_forward=   sn   
ÿ



þÿ



þþÿzHVULoss._forward)r   r   r   r   Fr   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rO   Ú__classcell__r)   r)   r'   r*   r      s    ør   )r8   Útorch.nn.functionalÚnnÚ
functionalr<   Úregistryr   Úbaser   Úregister_moduler   r)   r)   r)   r*   Ú<module>   s    