U
    Ð‹Ñh,  ã                
   @   sü   d dl Z d dlmZmZ d dlZd dlZd dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZmZ dd	lmZ d
dlmZmZ dd„ Zdd„ Zdd„ Zedd�dd„ ƒZejjdeeeee f ee eeeedœdd„ƒZG dd„ dej ƒZ!dS )é    N)ÚListÚUnion)ÚnnÚTensor)Úis_compile_supported)ÚBroadcastingList2)Ú_pair)Ú_assert_has_opsÚ_has_opsé   )Ú_log_api_usage_onceé   )Úcheck_roi_boxes_shapeÚconvert_boxes_to_roi_formatc                     s   ‡ fdd„}|S )zkLazily wrap a function with torch.compile on the first call

    This avoids eagerly importing dynamo.
    c                    s   t  ˆ ¡‡‡ fdd„ƒ}|S )Nc                     s.   t jˆfˆ Ž}t ˆ¡|ƒtƒ ˆj< || |ŽS ©N)ÚtorchÚcompileÚ	functoolsÚwrapsÚglobalsÚ__name__)ÚargsÚkwargsZcompiled_fn)Úcompile_kwargsÚfn© úG/tmp/user/2202/pip-unpacked-wheel-mjxxo1pc/torchvision/ops/roi_align.pyÚcompile_hook   s    z7lazy_compile.<locals>.decorate_fn.<locals>.compile_hook)r   r   )r   r   ©r   )r   r   Údecorate_fn   s    z!lazy_compile.<locals>.decorate_fnr   )r   r   r   r   r   Úlazy_compile   s    	r    c                    s”  ˆ  ¡ \}‰ }}|jdd�}|jdd�}| ¡ }	| ¡ }
t |	|d k|d |	d ¡}t |	|d k|d |	¡}	t |	|d k| ˆj¡|¡}t |
|d k|d |
d ¡}t |
|d k|d |
¡}
t |
|d k| ˆj¡|¡}||	 }||
 }d| }d| }‡ ‡‡‡‡fdd„}||	|
ƒ}||	|ƒ}|||
ƒ}|||ƒ}dd„ }|||ƒ}|||ƒ}|||ƒ}|||ƒ}|| ||  ||  ||  }|S )	Nr   ©Úminr   ç      ð?c                    sÐ   ˆd k	rTˆd k	st ‚t ˆd d …d d d …f | d¡} t ˆd d …d d d …f |d¡}ˆˆd d …d d d d d f tjˆ ˆjd�d d d …d d d d f | d d …d d d …d d d …d f |d d …d d d d …d d d …f f S )Nr   ©Údevice)ÚAssertionErrorr   ÚwhereÚaranger%   ©ÚyÚx©ZchannelsÚinputÚroi_batch_indÚxmaskÚymaskr   r   Úmasked_indexB   s      "ýÿz+_bilinear_interpolate.<locals>.masked_indexc              	   S   s@   | d d …d d d …d d d …d f |d d …d d d d …d d d …f  S r   r   r)   r   r   r   Ú
outer_prodW   s    z)_bilinear_interpolate.<locals>.outer_prod)ÚsizeÚclampÚintr   r'   ÚtoÚdtype)r-   r.   r*   r+   r0   r/   Ú_ÚheightÚwidthZy_lowZx_lowZy_highZx_highZlyZlxZhyÚhxr1   Zv1Zv2Zv3Zv4r2   Zw1Zw2Zw3Zw4Úvalr   r,   r   Ú_bilinear_interpolate#   s6    







 r=   c                 C   s*   t  ¡ r"| jr"| jt jkr"|  ¡ S | S d S r   )r   Zis_autocast_enabledÚis_cudar7   ÚdoubleÚfloat)Ztensorr   r   r   Ú
maybe_caste   s    rA   T)Zdynamicc           $   
   C   s:  | j }t| ƒ} t|ƒ}|  ¡ \}}}	}
tj|| jd�}tj|| jd�}|d d …df  ¡ }|rbdnd}|d d …df | | }|d d …df | | }|d d …df | | }|d d …df | | }|| }|| }|sötj|d	d
�}tj|d	d
�}|| }|| }|dk}|�r|nt || ¡}|�r0|nt || ¡}|�r|t	|| dƒ}tj|| jd�}tj|| jd�}d }d }nrtj|| dd
�}tj|	| jd�}tj|
| jd�}|d d d …f |d d …d f k }|d d d …f |d d …d f k }dd„ }||ƒ|d d d …d f ||ƒ  |d d d d …f d  
| j ¡||| ƒ  } ||ƒ|d d d …d f ||ƒ  |d d d d …f d  
| j ¡||| ƒ  }!t| || |!||ƒ}"|�sòt |d d …d d d d d …d f |"d¡}"t |d d …d d d d d d …f |"d¡}"|" d¡}#t|tjƒ�r$|#|d d …d d d f  }#n|#| }#|# 
|¡}#|#S )Nr$   r   g      à?g        r   r   é   é   r#   r!   c                 S   s   | d d …d d f S r   r   )Útr   r   r   Úfrom_K¬   s    z_roi_align.<locals>.from_K)éÿÿÿÿéþÿÿÿ)r7   rA   r3   r   r(   r%   r5   r4   ÚceilÚmaxr6   r=   r'   ÚsumÚ
isinstancer   )$r-   ÚroisÚspatial_scaleZpooled_heightZpooled_widthÚsampling_ratioÚalignedZ
orig_dtyper8   r9   r:   ÚphÚpwr.   ÚoffsetZroi_start_wZroi_start_hZ	roi_end_wZ	roi_end_hZ	roi_widthZ
roi_heightZ
bin_size_hZ
bin_size_wZexact_samplingZroi_bin_grid_hZroi_bin_grid_wÚcountZiyÚixr0   r/   rE   r*   r+   r<   Úoutputr   r   r   Ú
_roi_alignr   sp      ÿ(þÿÿ(þÿ&&

rV   r#   rF   F)r-   ÚboxesÚoutput_sizerM   rN   rO   Úreturnc              	   C   s¸   t j ¡ st j ¡ sttƒ t|ƒ |}t|ƒ}t|t j	ƒsDt
|ƒ}t j ¡ s�tƒ rht  ¡ r�| jsh| jr�t| jjƒr�t| |||d |d ||ƒS tƒ  t jj | |||d |d ||¡S )aj  
    Performs Region of Interest (RoI) Align operator with average pooling, as described in Mask R-CNN.

    Args:
        input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element
            contains ``C`` feature maps of dimensions ``H x W``.
            If the tensor is quantized, we expect a batch size of ``N == 1``.
        boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2)
            format where the regions will be taken from.
            The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
            If a single Tensor is passed, then the first column should
            contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``.
            If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i
            in the batch.
        output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling
            is performed, as (height, width).
        spatial_scale (float): a scaling factor that maps the box coordinates to
            the input coordinates. For example, if your boxes are defined on the scale
            of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of
            the original image), you'll want to set this to 0.5. Default: 1.0
        sampling_ratio (int): number of sampling points in the interpolation grid
            used to compute the output value of each pooled output bin. If > 0,
            then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If
            <= 0, then an adaptive number of grid points are used (computed as
            ``ceil(roi_width / output_width)``, and likewise for height). Default: -1
        aligned (bool): If False, use the legacy implementation.
            If True, pixel shift the box coordinates it by -0.5 for a better alignment with the two
            neighboring pixel indices. This version is used in Detectron2

    Returns:
        Tensor[K, C, output_size[0], output_size[1]]: The pooled RoIs.
    r   r   )r   ZjitZis_scriptingÚ
is_tracingr   Ú	roi_alignr   r   rK   r   r   r
   Z$are_deterministic_algorithms_enabledr>   Zis_mpsr   r%   ÚtyperV   r	   ÚopsZtorchvision)r-   rW   rX   rM   rN   rO   rL   r   r   r   r[   Ë   s:    )
ÿÿÿÿ
þ      ÿr[   c                       s^   e Zd ZdZdee eeedœ‡ fdd„Ze	e
e	ee	 f e	dœdd„Zed	œd
d„Z‡  ZS )ÚRoIAlignz 
    See :func:`roi_align`.
    F)rX   rM   rN   rO   c                    s.   t ƒ  ¡  t| ƒ || _|| _|| _|| _d S r   )ÚsuperÚ__init__r   rX   rM   rN   rO   )ÚselfrX   rM   rN   rO   ©Ú	__class__r   r   r`     s    
zRoIAlign.__init__)r-   rL   rY   c                 C   s   t ||| j| j| j| jƒS r   )r[   rX   rM   rN   rO   )ra   r-   rL   r   r   r   Úforward  s    zRoIAlign.forward)rY   c              
   C   s2   | j j› d| j› d| j› d| j› d| j› d�
}|S )Nz(output_size=z, spatial_scale=z, sampling_ratio=z
, aligned=ú))rc   r   rX   rM   rN   rO   )ra   Úsr   r   r   Ú__repr__  s    ,ÿzRoIAlign.__repr__)F)r   Ú
__module__Ú__qualname__Ú__doc__r   r5   r@   Úboolr`   r   r   r   rd   Ústrrg   Ú__classcell__r   r   rb   r   r^     s   	 ûûr^   )r#   rF   F)"r   Útypingr   r   r   Ztorch.fxr   r   Ztorch._dynamo.utilsr   Ztorch.jit.annotationsr   Ztorch.nn.modules.utilsr   Ztorchvision.extensionr	   r
   Úutilsr   Ú_utilsr   r   r    r=   rA   rV   ZfxÚwrapr5   r@   rk   r[   ÚModuler^   r   r   r   r   Ú<module>   s:   B
X   úù: