
    ڧg,                     h   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 Zd Zd Z ed          d             Zej        j        	 	 	 ddedeeee         f         dee         dedededefd            Z G 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                        fd}|S )zkLazily wrap a function with torch.compile on the first call

    This avoids eagerly importing dynamo.
    c                 J     t          j                    fd            }|S )Nc                      t          j        fi } t          j                  |          t	                      j        <    || i |S N)torchcompile	functoolswrapsglobals__name__)argskwargscompiled_fncompile_kwargsfns      U/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/ops/roi_align.pycompile_hookz7lazy_compile.<locals>.decorate_fn.<locals>.compile_hook   sS    -==n==K%8Y_R%8%8%E%EGIIbk";////    )r   r   )r   r!   r   s   ` r    decorate_fnz!lazy_compile.<locals>.decorate_fn   s?    				0 	0 	0 	0 	0 
		0
 r"    )r   r#   s   ` r    lazy_compiler%      s$         r"   c                                                       \  }}}|                    d          }|                    d          }|                                }	|                                }
t          j        |	|dz
  k    |dz
  |	dz             }t          j        |	|dz
  k    |dz
  |	          }	t          j        |	|dz
  k    |                     j                  |          }t          j        |
|dz
  k    |dz
  |
dz             }t          j        |
|dz
  k    |dz
  |
          }
t          j        |
|dz
  k    |                     j                  |          }||	z
  }||
z
  }d|z
  }d|z
  } fd} ||	|
          } ||	|          } |||
          } |||          }d } |||          } |||          } |||          } |||          }||z  ||z  z   ||z  z   ||z  z   }|S )Nr   minr         ?c                 f   JJ t          j        d d d d d f         | d          } t          j        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 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)r   wherearanger,   )yxchannelsinputroi_batch_indxmaskymasks     r    masked_indexz+_bilinear_interpolate.<locals>.masked_indexB   s     $$$E!!!T111*-q!44AE!!!T111*-q!44A!!!T4tT9:L%,777aaatTSW8WXaaaqqq$4'(aaatQQQaaa'(*
 	
r"   c           	      T    | d d d d d d d d d f         |d d d d d d d d d f         z  S r   r$   )r/   r0   s     r    
outer_prodz)_bilinear_interpolate.<locals>.outer_prodW   sI    D!!!T111d*+a4qqq$0I.JJJr"   )sizeclampintr   r-   todtype)r2   r3   r/   r0   r5   r4   _heightwidthy_lowx_lowy_highx_highlylxhyhxr6   v1v2v3v4r8   w1w2w3w4valr1   s   ``  ``                      @r    _bilinear_interpolaterR   #   sQ    "'Ax 	
AA	AAEEGGEEEGGE[&1*,fqj%!)DDFK!+VaZ??EEVaZ'ek):):A>>A[%!)+UQY	BBFK*EAIu==EEUQY&U[(9(91==A	
UB	
UB	rB	rB

 
 
 
 
 
 
 
 
 
eU	#	#B	eV	$	$B	fe	$	$B	ff	%	%BK K K 
B		B	B		B	B		B	B		B
r'BG
b2g
%R
/CJr"   c                     t          j                    r0| j        r)| j        t           j        k    r|                                 S | S r   )r   is_autocast_enabledis_cudar=   doublefloat)tensors    r    
maybe_castrY   e   s=     "" v~ &,%,:V:V||~~r"   T)dynamicc           
      ^   | j         }t          |           } t          |          }|                                 \  }}}	}
t          j        || j                  }t          j        || j                  }|d d df                                         }|rdnd}|d d df         |z  |z
  }|d d df         |z  |z
  }|d d df         |z  |z
  }|d d df         |z  |z
  }||z
  }||z
  }|s,t          j        |d	
          }t          j        |d	
          }||z  }||z  }|dk    }|r|nt          j        ||z            }|r|nt          j        ||z            }	 |rNt          ||z  d          }t          j        || j                  }t          j        || j                  }d }d }nt          j        ||z  d
          }t          j        |	| j                  }t          j        |
| j                  }|d d d f         |d d d f         k     }|d d d f         |d d d f         k     }d } ||          |d d d d f          ||          z  z   |d d d d f         dz   
                    | j                    |||z            z  z   }  ||          |d d d d f          ||          z  z   |d d d d f         dz   
                    | j                    |||z            z  z   }!t          | || |!||          }"|sLt          j        |d d d d d d d d f         |"d          }"t          j        |d d d d d d d d f         |"d          }"|"                    d          }#t          |t          j                  r|#|d d d d d f         z  }#n|#|z  }#|#
                    |          }#|#S )Nr+   r   g      ?g        r   r         r)   r'   c                     | d d d d f         S r   r$   )ts    r    from_Kz_roi_align.<locals>.from_K   s    D$r"   ))r=   rY   r9   r   r.   r,   r;   r:   ceilmaxr<   rR   r-   sum
isinstancer   )$r2   roisspatial_scalepooled_heightpooled_widthsampling_ratioaligned
orig_dtyper>   r?   r@   phpwr3   offsetroi_start_wroi_start_h	roi_end_w	roi_end_h	roi_width
roi_height
bin_size_h
bin_size_wexact_samplingroi_bin_grid_hroi_bin_grid_wcountiyixr5   r4   r`   r/   r0   rQ   outputs$                                       r    
_roi_alignr   r   sg   JuEdD**,,Aq&%	mEL	9	9	9B	l5<	8	8	8B
 AJNN$$M$SSFqqq!t*},v5Kqqq!t*},v5KQQQT
]*V3IQQQT
]*V3IK'I[(J 6K	s333	[555
m+J\)J#a'N'5a^^5:jS`F`;a;aN'5_^^5:iR^F^;_;_N  6N^3Q77\.>>>\.>>>N^;CCC \&666\%55547nQQQW5547nQQQW55      	{
T111d]
ffZ00
0	1dD!!!ms"
&
&u{
3
3ffZ.=X6Y6Y
Y	Z  	{
T111d]
ffZ00
0	1dD!!!ms"
&
&u{
3
3ffZ.=X6Y6Y
Y	Z 
  }aE5
I
IC  Gk%4tQQQ <=sAFFk%4tT111 <=sAFFWWXF%&& %4t+,,%YYz""FMr"   r)   ra   Fr2   boxesoutput_sizerh   rk   rl   returnc           	         t           j                                        s2t           j                                        st	          t
                     t          |           |}t          |          }t          |t           j	                  st          |          }t           j                                        sit                      r!t          j                    rH| j        s| 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   jitis_scripting
is_tracingr   	roi_alignr   r	   rf   r   r   r   $are_deterministic_algorithms_enabledrU   is_mpsr   r,   typer   r
   opstorchvision)r2   r   r   rh   rk   rl   rg   s          r    r   r      sK   R 9!!## 'EI,@,@,B,B 'I&&&%   D$$KdEL)) 1*4009!!## s

	s$IKK	sQVQ^	sbgbn	s"5<#455	s eT=+a.+VW.Zhjqrrr9 **t]KNKNNT[  r"   c            	            e Zd ZdZ	 ddee         dededef fdZde	d	e
e	ee	         f         d
e	fdZd
efdZ xZS )RoIAlignz 
    See :func:`roi_align`.
    Fr   rh   rk   rl   c                     t                                                       t          |            || _        || _        || _        || _        d S r   )super__init__r   r   rh   rk   rl   )selfr   rh   rk   rl   	__class__s        r    r   zRoIAlign.__init__  sL     	D!!!&*,r"   r2   rg   r   c                 R    t          ||| j        | j        | j        | j                  S r   )r   r   rh   rk   rl   )r   r2   rg   s      r    forwardzRoIAlign.forward  s'    d&68JDL_aeamnnnr"   c           
      d    | j         j         d| j         d| j         d| j         d| j         d
}|S )Nz(output_size=z, spatial_scale=z, sampling_ratio=z
, aligned=))r   r   r   rh   rk   rl   )r   ss     r    __repr__zRoIAlign.__repr__  sh    ~&  + #1  !% 3  	   	
 r"   )F)r   
__module____qualname____doc__r   r;   rW   boolr   r   r   r   r   strr   __classcell__)r   s   @r    r   r     s           &s+  	
      oV o5f1E+F o6 o o o o	# 	 	 	 	 	 	 	 	r"   r   )r)   ra   F)"r   typingr   r   r   torch.fxr   r   torch._dynamo.utilsr   torch.jit.annotationsr   torch.nn.modules.utilsr	   torchvision.extensionr
   r   utilsr   _utilsr   r   r%   rR   rY   r   fxwrapr;   rW   r   r   Moduler   r$   r"   r    <module>r      s                         4 4 4 4 4 4 3 3 3 3 3 3 ( ( ( ( ( ( ; ; ; ; ; ; ; ; ' ' ' ' ' ' F F F F F F F F  &= = =D   dU U Up 
 7 77f%&7 #3'7 	7
 7 7 7 7 7 7t    ry     r"   