
    ڧg.                        d dl mZmZmZmZmZ d dl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 ej        j        d	e
d
ee
         de
fd            Z	 	 	 d+dededededef
dZ G d d          Zdee
         de
fdZde
dee         defdZej        j        dee
         deeeef                  dededeee         ef         f
d            Zej        j        d eee
f         d!ee         dee
         fd"            Zej        j        d#ee
         dee
         d$ee         d%ed&eee                  d'ee         de
fd(            Z G d) d*e	j                  Z dS ),    )DictListOptionalTupleUnionN)nnTensorbox_area   )_log_api_usage_once   )	roi_alignlevelsunmerged_resultsreturnc           	         |d         }|j         |j        }}t          j        |                     d          |                    d          |                    d          |                    d          f||          }t          t          |                    D ]}t          j        | |k              d                             dddd          }|	                    |                    d          ||                             d          ||                             d          ||                             d                    }|
                    d|||                   }|S )Nr   r   r      dtypedevice)r   r   torchzerossizerangelenwhereviewexpandscatter)r   r   first_resultr   r   reslevelindexs           S/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/ops/poolers.py_onnx_merge_levelsr'      sL   #A&L &(;6E
+	Q**1--|/@/@/C/C\EVEVWXEYEYZbgpv  C s+,,-- = =FeO,,Q/44RAqAAJJqMMU#((++U#((++U#((++	
 
 kk!U$4U$;<<J          ư>k_mink_maxcanonical_scalecanonical_levelepsc                 (    t          | ||||          S N)LevelMapper)r,   r-   r.   r/   r0   s        r&   initLevelMapperr4   %   s     ue_osKKKr(   c                   R    e Zd ZdZ	 	 	 ddedededed	ef
d
Zdee         defdZ	dS )r3   zDetermine which FPN level each RoI in a set of RoIs should map to based
    on the heuristic in the FPN paper.

    Args:
        k_min (int)
        k_max (int)
        canonical_scale (int)
        canonical_level (int)
        eps (float)
    r)   r*   r+   r,   r-   r.   r/   r0   c                 L    || _         || _        || _        || _        || _        d S r2   )r,   r-   s0lvl0r0   )selfr,   r-   r.   r/   r0   s         r&   __init__zLevelMapper.__init__;   s+     

!#	r(   boxlistsr   c                    t          j        t          j        d |D                                 }t          j        | j        t          j        || j        z            z   t          j        | j        |j	                  z             }t          j
        || j        | j                  }|                    t           j                  | j        z
                      t           j                  S )z<
        Args:
            boxlists (list[BoxList])
        c                 ,    g | ]}t          |          S  r
   ).0boxlists     r&   
<listcomp>z(LevelMapper.__call__.<locals>.<listcomp>O   s     !L!L!L(7"3"3!L!L!Lr(   r   )minmax)r   sqrtcatfloorr8   log2r7   tensorr0   r   clampr,   r-   toint64)r9   r;   starget_lvlss       r&   __call__zLevelMapper.__call__I   s     Juy!L!L8!L!L!LMMNN k$)ejTW.E.E"EUYU]efelHmHmHm"mnnk+4:4:NNNu{++dj8<<U[IIIr(   Nr)   r*   r+   )
__name__
__module____qualname____doc__intfloatr:   r   r	   rO   r>   r(   r&   r3   r3   /   s        	 	  #    	
     Jf J& J J J J J Jr(   r3   boxesc                     t          j        | d          }|j        |j        ct          j        fdt	          |           D             d          }t          j        ||gd          }|S )Nr   )dimc           	      t    g | ]4\  }}t          j        |d d d df         |t           j                  5S )Nr   )r   layoutr   )r   	full_likestrided)r?   ibr   r   s      r&   rA   z*_convert_to_roi_format.<locals>.<listcomp>[   sH    uuu\`\]_`111bqb51E%-PV	W	W	Wuuur(   r   )r   rF   r   r   	enumerate)rW   concat_boxesidsroisr   r   s       @@r&   _convert_to_roi_formatrd   W   s    9U***L ');MFE
)uuuuudmnsdtdtuuu  C 9c<(a000DKr(   featureoriginal_sizec                 X   | j         dd          }g }t          ||          D ]\  }}t          |          t          |          z  }dt          t          j        |                                                                                    z  }|                    |           |d         S )Nr   r   )shapeziprV   r   rI   rH   roundappend)re   rf   r   possible_scaless1s2approx_scalescales           r&   _infer_scalerr   b   s    =D#%OdM** & &BRyy599,U5<55::<<BBDDEEEu%%%%1r(   featuresimage_shapesc                 B   |st          d          d}d}|D ].}t          |d         |          }t          |d         |          }/||ffd| D             }t          j        t          j        |d         t          j                                                             }t          j        t          j        |d         t          j                                                             }	t          t          |          t          |	          ||          }
||
fS )Nzimages list should not be emptyr   r   c                 0    g | ]}t          |          S r>   )rr   )r?   featoriginal_input_shapes     r&   rA   z!_setup_scales.<locals>.<listcomp>z   s$    LLL4l4!566LLLr(   rB   r   r.   r/   )	
ValueErrorrD   r   rH   rI   float32itemr4   rU   )rs   rt   r.   r/   max_xmax_yri   scaleslvl_minlvl_max
map_levelsrx   s              @r&   _setup_scalesr   m   s!     <:;;;EE % %E!He$$E!He$$!5>LLLL8LLLF z%,vayFFFGGLLNNNGz%,vbzGGGHHMMOOOG GG''	  J :r(   xfeatmap_namesc                 p    g }|                                  D ]\  }}||v r|                    |           |S r2   )itemsrl   )r   r   
x_filteredkvs        r&   _filter_inputr      sH    J		 ! !1a   r(   r   output_sizesampling_ratior   mapperc                 6   ||t          d          t          |           }t          |          }|dk    r t          | d         |||d         |          S  ||          }t          |          }	| d         j        d         }
| d         j        | d         j        }}t          j        |	|
f|z   ||          }g }t          t          | |                    D ]\  }\  }}t          j        ||k              d         }||         }t          |||||          }t          j                    r)|                    |                    |                     ~|                    |j                  ||<   t          j                    rt!          ||          }|S )a  
    Args:
        x_filtered (List[Tensor]): List of input tensors.
        boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in
            (x1, y1, x2, y2) format and in the image reference size, not the feature map
            reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
        output_size (Union[List[Tuple[int, int]], List[int]]): size of the output
        sampling_ratio (int): sampling ratio for ROIAlign
        scales (Optional[List[float]]): If None, scales will be automatically inferred. Default value is None.
        mapper (Optional[LevelMapper]): If none, mapper will be automatically inferred. Default value is None.
    Returns:
        result (Tensor)
    Nz$scales and mapper should not be Noner   r   )r   spatial_scaler   r   )rz   r   rd   r   ri   r   r   r   r   r`   rj   r   torchvision_is_tracingrl   rK   r'   )r   rW   r   r   r   r   
num_levelsrc   r   num_roisnum_channelsr   r   resulttracing_resultsr$   per_level_featurerq   idx_in_levelrois_per_levelresult_idx_in_levels                        r&   _multiscale_roi_alignr      s   , ~?@@@ZJ!%((DQqM# ))
 
 
 	
 VE]]F4yyHa=&q)LqM'A)=6E[	
 		
   F O-6s:v7N7N-O-O H H))!5{6U?33A6l+'#)
 
 
 "$$ 
	H""#6#9#9%#@#@AAAA $7#9#9&,#G#GF<     =#FO<<Mr(   c                        e Zd ZdZeee                  ee         dZddddee	         de
eee         ee         f         ded	ed
ef
 fdZdee	ef         dee         deeeef                  defdZde	fdZ xZS )MultiScaleRoIAligna{  
    Multi-scale RoIAlign pooling, which is useful for detection with or without FPN.

    It infers the scale of the pooling via the heuristics specified in eq. 1
    of the `Feature Pyramid Network paper <https://arxiv.org/abs/1612.03144>`_.
    They keyword-only parameters ``canonical_scale`` and ``canonical_level``
    correspond respectively to ``224`` and ``k0=4`` in eq. 1, and
    have the following meaning: ``canonical_level`` is the target level of the pyramid from
    which to pool a region of interest with ``w x h = canonical_scale x canonical_scale``.

    Args:
        featmap_names (List[str]): the names of the feature maps that will be used
            for the pooling.
        output_size (List[Tuple[int, int]] or List[int]): output size for the pooled region
        sampling_ratio (int): sampling ratio for ROIAlign
        canonical_scale (int, optional): canonical_scale for LevelMapper
        canonical_level (int, optional): canonical_level for LevelMapper

    Examples::

        >>> m = torchvision.ops.MultiScaleRoIAlign(['feat1', 'feat3'], 3, 2)
        >>> i = OrderedDict()
        >>> i['feat1'] = torch.rand(1, 5, 64, 64)
        >>> i['feat2'] = torch.rand(1, 5, 32, 32)  # this feature won't be used in the pooling
        >>> i['feat3'] = torch.rand(1, 5, 16, 16)
        >>> # create some random bounding boxes
        >>> boxes = torch.rand(6, 4) * 256; boxes[:, 2:] += boxes[:, :2]
        >>> # original image size, before computing the feature maps
        >>> image_sizes = [(512, 512)]
        >>> output = m(i, [boxes], image_sizes)
        >>> print(output.shape)
        >>> torch.Size([6, 5, 3, 3])

    )r   r   r)   r*   ry   r   r   r   r.   r/   c                   t                                                       t          |            t          |t                    r||f}|| _        || _        t          |          | _        d | _	        d | _
        || _        || _        d S r2   )superr:   r   
isinstancerU   r   r   tupler   r   r   r.   r/   )r9   r   r   r   r.   r/   	__class__s         r&   r:   zMultiScaleRoIAlign.__init__  s     	D!!!k3'' 	5&4K*, --..r(   r   rW   rt   r   c                     t          || j                  }| j        | j        )t	          ||| j        | j                  \  | _        | _        t          ||| j        | j	        | j        | j                  S )a  
        Args:
            x (OrderedDict[Tensor]): feature maps for each level. They are assumed to have
                all the same number of channels, but they can have different sizes.
            boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in
                (x1, y1, x2, y2) format and in the image reference size, not the feature map
                reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
            image_shapes (List[Tuple[height, width]]): the sizes of each image before they
                have been fed to a CNN to obtain feature maps. This allows us to infer the
                scale factor for each one of the levels to be pooled.
        Returns:
            result (Tensor)
        )
r   r   r   r   r   r.   r/   r   r   r   )r9   r   rW   rt   r   s        r&   forwardzMultiScaleRoIAlign.forward!  s|    & #1d&899
;$/"9+8L$*>@T, ,(DK %KO
 
 	
r(   c                 P    | j         j         d| j         d| j         d| j         dS )Nz(featmap_names=z, output_size=z, sampling_ratio=))r   rQ   r   r   r   )r9   s    r&   __repr__zMultiScaleRoIAlign.__repr__C  sV    ~& U Ut7I U U+U U>B>QU U U	
r(   )rQ   rR   rS   rT   r   r   rV   r3   __annotations__strr   rU   r   r:   r   r	   r   r   __classcell__)r   s   @r&   r   r      s/       ! !F "*$u+!6h{F[\\O  # / / /Cy/ 3c
DI56/ 	/ / / / / / / /* 
V 
 F| 
 5c?+	 

 
 
  
  
  
D
# 
 
 
 
 
 
 
 
r(   r   rP   )!typingr   r   r   r   r   r   torch.fxr   r   r	   torchvision.ops.boxesr   utilsr   r   jitunusedr'   rU   rV   r4   r3   rd   rr   fxwrapr   r   r   r   Moduler   r>   r(   r&   <module>r      s;   5 5 5 5 5 5 5 5 5 5 5 5 5 5               * * * * * * ' ' ' ' ' '             v f &    , L LLL L 	L
 
L L L L%J %J %J %J %J %J %J %JP$v, 6    & c u     6l*.uS#X*?RUhk
4;#$   6 T#v+& tCy T&\     PVP<P cP 	P
 T%[!P [!P P P P Pfa
 a
 a
 a
 a
 a
 a
 a
 a
 a
r(   