o
    pi                     @   sX   d dl Z ddlmZ ddlmZ ddlmZ ddlmZ	 ddl
mZ G d	d
 d
eZdS )    N   CosineSimilarityAvgNonZeroReducer)common_functions)loss_and_miner_utils   )GenericPairLossc                       s:   e Zd ZdZd fdd	Zdd Zdd	 Zd
d Z  ZS )
CircleLossa  
    Circle loss for pairwise labels only.

    Args:
    m:  The relaxation factor that controls the radious of the decision boundary.
    gamma: The scale factor that determines the largest scale of each similarity score.

    According to the paper, the suggested default values of m and gamma are:

    Face Recognition: m = 0.25, gamma = 256
    Person Reidentification: m = 0.25, gamma = 128
    Fine-grained Image Retrieval: m = 0.4, gamma = 80

    By default, we set m = 0.4 and gamma = 80
    皙?P   c                    s~   t  jdddi| t| t || _|| _tjj	dd| _
d| j | _| j | _d| j | _| j| _| jg ddd d S )	Nmat_based_lossTr	   )beta)mgammaopondelta_pdelta_nF)list_of_namesis_stat )super__init__c_fassert_distance_typer   r   r   torchnnSoftplus	soft_plusr   r   r   r   add_to_recordable_attributes)selfr   r   kwargs	__class__r   ^/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_metric_learning/losses/circle_loss.pyr      s   

zCircleLoss.__init__c                 C   s  |  }|  }|| }|| }t|}| j t| j|   || j  ||< | jt| | j  || j	  ||< t
j||ddd}	t
j||ddd}
| |	|
 }ttj|dddktj|dddkB d }t|}d||< || }d|t|ddiS )	NFr	   )	keep_maskadd_onedim)r)   r   losselement)lossesindicesreduction_type)boolr   
zeros_liker   relur   detachr   r   r   lmu	logsumexpr    wheresum	ones_liker   torch_arange_from_size)r"   matpos_maskneg_maskpos_mask_boolneg_mask_boolanchor_positiveanchor_negativenew_matlogsumexp_poslogsumexp_negr,   	zero_rows
final_maskr   r   r&   _compute_loss*   sL   
"
zCircleLoss._compute_lossc                 C      t  S Nr   r"   r   r   r&   get_default_reducerS      zCircleLoss.get_default_reducerc                 C   rF   rG   r   rH   r   r   r&   get_default_distanceV   rJ   zCircleLoss.get_default_distance)r   r   )	__name__
__module____qualname____doc__r   rE   rI   rK   __classcell__r   r   r$   r&   r   
   s    )r   )r   	distancesr   reducersr   utilsr   r   r   r3   generic_pair_lossr
   r   r   r   r   r&   <module>   s    