o
    _{jÁ	  ã                   @   s    d dl Z G dd„ de jjƒZdS )é    Nc                   @   s(   e Zd ZdZedd„ ƒZedd„ ƒZdS )ÚOHEMHingeLossz¬This class is the core implementation for the completeness loss in
    paper.

    It compute class-wise hinge loss and performs online hard example mining
    (OHEM).
    c              	   C   sL  |  d¡}|t|ƒkrtd|› dt|ƒ› d�ƒ‚tj||jd�}tj||jd�}t|ƒD ]"}	tdd|||	||	 d f   ƒ||	< ||	 dkrJ| nd||	< q,| d|¡ 	¡ }tj
|ddd	�\}
}t|| ƒ}tjd|jd�}t|  d¡ƒD ]}	||
|	d
|…f  ¡ 7 }qv|d
d
…d
|…f | _|| _|| _|  ¡ | _|| _|  d¡| _|S )a÷  Calculate OHEM hinge loss.

        Args:
            pred (torch.Tensor): Predicted completeness score.
            labels (torch.Tensor): Groundtruth class label.
            is_positive (int): Set to 1 when proposals are positive and
                set to -1 when proposals are incomplete.
            ohem_ratio (float): Ratio of hard examples.
            group_size (int): Number of proposals sampled per video.

        Returns:
            torch.Tensor: Returned class-wise hinge loss.
        r   z=Number of samples should be equal to that of labels, but got z samples and z labels.©Údeviceé   éÿÿÿÿT)ÚdimÚ
descendingN)ÚsizeÚlenÚ
ValueErrorÚtorchÚzerosr   ÚrangeÚmaxÚviewÚ
contiguousÚsortÚintÚsumÚ
loss_indexÚlabelsÚslopesÚshapeÚ
group_sizeÚ
num_groups)ÚctxÚpredr   Zis_positiveZ
ohem_ratior   Únum_samplesÚlossesr   ÚiZsorted_lossesÚindicesZkeep_lengthÚloss© r"   ú</root/disk_3tb/HAC/mmaction/models/losses/ohem_hinge_loss.pyÚforward   s2   
ÿ
þ&
zOHEMHingeLoss.forwardc                 C   s†   | j }| j}tj| j| jjd�}t| jƒD ]"}| j| D ]}||| j	  }|| |j
d  |||| d f< qqtj |¡d d d d fS )Nr   r   r   )r   r   r   r   r   r   r   r   r   r   ÚdataÚautogradÚVariable)r   Úgrad_outputr   r   Úgrad_inÚgroupÚidxÚlocr"   r"   r#   Úbackward5   s   ÿþzOHEMHingeLoss.backwardN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústaticmethodr$   r-   r"   r"   r"   r#   r      s    
(r   )r   r&   ÚFunctionr   r"   r"   r"   r#   Ú<module>   s    