
    h[V                        S SK r S SKJr  S SKJr  S SKrS SKJrJr  S SKJ	r
  S SKJrJrJrJr   " S S5      r\R"                  R$                  S	\S
\S\S\4S j5       r " S S5      r " S S5      r " S S5      r " S S\5      rS\R0                  S\SS4S jrS\R0                  S\\\4   S\\   4S jr\R"                  R>                  S\S\4S j5       r S\S\S\S\4S  jr! S(S!\"S"\S#\S$\S%\S&\\#\"\4      S\4S' jjr$g))    N)OrderedDict)Optional)nnTensor)
functional)complete_box_iou_lossdistance_box_iou_lossFrozenBatchNorm2dgeneralized_box_iou_lossc                   \    \ rS rSrSrS\S\SS4S jrS\\	   S\
\\	   \\	   4   4S	 jrS
rg)BalancedPositiveNegativeSampler   zX
This class samples batches, ensuring that they contain a fixed proportion of positives
batch_size_per_imagepositive_fractionreturnNc                     Xl         X l        g)z
Args:
    batch_size_per_image (int): number of elements to be selected per image
    positive_fraction (float): percentage of positive elements per batch
Nr   r   )selfr   r   s      [/var/www/auris/envauris/lib/python3.13/site-packages/torchvision/models/detection/_utils.py__init__(BalancedPositiveNegativeSampler.__init__   s     %9!!2    matched_idxsc                    / n/ nU GHy  n[         R                  " US:  5      S   n[         R                  " US:H  5      S   n[        U R                  U R                  -  5      n[        UR                  5       U5      nU R                  U-
  n[        UR                  5       U5      n[         R                  " UR                  5       UR                  S9SU n	[         R                  " UR                  5       UR                  S9SU n
XY   nXj   n[         R                  " U[         R                  S9n[         R                  " U[         R                  S9nSX'   SX'   UR                  U5        UR                  U5        GM|     X#4$ )a  
Args:
    matched_idxs: list of tensors containing -1, 0 or positive values.
        Each tensor corresponds to a specific image.
        -1 values are ignored, 0 are considered as negatives and > 0 as
        positives.

Returns:
    pos_idx (list[tensor])
    neg_idx (list[tensor])

Returns two lists of binary masks for each image.
The first list contains the positive elements that were selected,
and the second list the negative example.
   r   deviceNdtype)torchwhereintr   r   minnumelrandpermr   
zeros_likeuint8append)r   r   pos_idxneg_idxmatched_idxs_per_imagepositivenegativenum_posnum_negperm1perm2pos_idx_per_imageneg_idx_per_imagepos_idx_per_image_maskneg_idx_per_image_masks                  r   __call__(BalancedPositiveNegativeSampler.__call__   sa     &2"{{#9Q#>?BH{{#9Q#>?BH$33d6L6LLMG(..*G4G//'9G(..*G4G NN8>>#3HOOLXgVENN8>>#3HOOLXgVE ( ( &+%5%56LTYT_T_%`"%*%5%56LTYT_T_%`"89"589"5NN12NN125 '38 r   r   )__name__
__module____qualname____firstlineno____doc__r"   floatr   listr   tupler6   __static_attributes__ r   r   r   r      sJ    3S 3U 3t 3. T&\ . eDL$v,<V6W . r   r   reference_boxes	proposalsweightsr   c                    US   nUS   nUS   nUS   nUSS2S4   R                  S5      nUSS2S4   R                  S5      nUSS2S4   R                  S5      n	USS2S4   R                  S5      n
U SS2S4   R                  S5      nU SS2S4   R                  S5      nU SS2S4   R                  S5      nU SS2S4   R                  S5      nX-
  nX-
  nUSU-  -   nUSU-  -   nX-
  nX-
  nUSU-  -   nUSU-  -   nUUU-
  -  U-  nUUU-
  -  U-  nU[        R                  " UU-  5      -  nU[        R                  " UU-  5      -  n[        R                  " UUUU4SS9nU$ )z
Encode a set of proposals with respect to some
reference boxes

Args:
    reference_boxes (Tensor): reference boxes
    proposals (Tensor): boxes to be encoded
    weights (Tensor[4]): the weights for ``(x, y, w, h)``
r   r         N      ?dim)	unsqueezer    logcat)rB   rC   rD   wxwywwwhproposals_x1proposals_y1proposals_x2proposals_y2reference_boxes_x1reference_boxes_y1reference_boxes_x2reference_boxes_y2	ex_widths
ex_heightsex_ctr_xex_ctr_y	gt_widths
gt_heightsgt_ctr_xgt_ctr_y
targets_dx
targets_dy
targets_dw
targets_dhtargetss                               r   encode_boxesrg   J   s    
B	B	B	BQT?,,Q/LQT?,,Q/LQT?,,Q/LQT?,,Q/L(A.88;(A.88;(A.88;(A.88; +I,JcIo-HcJ..H"7I#8J!C)O3H!C*$44Hx(*+i7Jx(*+j8Jeii	I 566Jeii
Z 788JiiZZHaPGNr   c                       \ rS rSrSr\R                  " S5      4S\\\\\4   S\SS4S jjr	S	\
\   S
\
\   S\
\   4S jrS	\S
\S\4S jrS\S\
\   S\4S jrS\S\S\4S jrSrg)BoxCoderz   zr
This class encodes and decodes a set of bounding boxes into
the representation used for training the regressors.
g     @O@rD   bbox_xform_clipr   Nc                     Xl         X l        g)zA
Args:
    weights (4-element tuple)
    bbox_xform_clip (float)
N)rD   rk   )r   rD   rk   s      r   r   BoxCoder.__init__   s     .r   rB   rC   c                     U Vs/ s H  n[        U5      PM     nn[        R                  " USS9n[        R                  " USS9nU R                  X5      nUR	                  US5      $ s  snf )Nr   rI   )lenr    rM   encode_singlesplit)r   rB   rC   bboxes_per_imagerf   s         r   encodeBoxCoder.encode   s`    +:;?a3q6?;))O;IIiQ/	$$_@}}_a00	 <s   A)c                     UR                   nUR                  n[        R                  " U R                  X4S9n[        XU5      nU$ )z
Encode a set of proposals with respect to some
reference boxes

Args:
    reference_boxes (Tensor): reference boxes
    proposals (Tensor): boxes to be encoded
r   r   )r   r   r    	as_tensorrD   rg   )r   rB   rC   r   r   rD   rf   s          r   rp   BoxCoder.encode_single   s?      %% ''//$,,eK7Cr   	rel_codesboxesc                    [         R                  " [        U[        [        45      S5        [         R                  " [        U[         R
                  5      S5        U Vs/ s H  o3R                  S5      PM     nn[         R                  " USS9nSnU H  nXg-  nM	     US:  a  UR                  US5      nU R                  X5      nUS:  a  UR                  USS5      nU$ s  snf )Nz2This function expects boxes of type list or tuple.z5This function expects rel_codes of type torch.Tensor.r   rI      )
r    _assert
isinstancer>   r?   r   sizerM   reshapedecode_single)	r   rz   r{   rr   rs   concat_boxesbox_sumval
pred_boxess	            r   decodeBoxCoder.decode   s    utUm,@	
 	y%,,/C	
 /44e66!9e4yyA."CNG #Q;!))'26I''	@
Q;#++GR;J 5s   C#c                    UR                  UR                  5      nUSS2S4   USS2S4   -
  nUSS2S4   USS2S4   -
  nUSS2S4   SU-  -   nUSS2S4   SU-  -   nU R                  u  pxpUSS2SSS24   U-  nUSS2SSS24   U-  nUSS2SSS24   U	-  nUSS2SSS24   U
-  n[        R                  " XR
                  S9n[        R                  " XR
                  S9nXSS2S4   -  USS2S4   -   nXSS2S4   -  USS2S4   -   n[        R                  " U5      USS2S4   -  n[        R                  " U5      USS2S4   -  n[        R                  " SUR                  UR                  S	9U-  n[        R                  " SUR                  UR                  S	9U-  nUU-
  nUU-
  nUU-   nUU-   n[        R                  " UUUU4SS
9R                  S5      nU$ )z
From a set of original boxes and encoded relative box offsets,
get the decoded boxes.

Args:
    rel_codes (Tensor): encoded boxes
    boxes (Tensor): reference boxes.
NrF   r   rG   r   rH   r~   )maxrw   rI   )tor   rD   r    clamprk   exptensorr   stackflatten)r   rz   r{   widthsheightsctr_xctr_yrN   rO   rP   rQ   dxdydwdh
pred_ctr_x
pred_ctr_ypred_wpred_hc_to_c_hc_to_c_wpred_boxes1pred_boxes2pred_boxes3pred_boxes4r   s                             r   r   BoxCoder.decode_single   s    )q!tuQT{*1+ad+adcFl*adcGm+q!$Q$w"$q!$Q$w"$q!$Q$w"$q!$Q$w"$ [[!5!56[[!5!56D/)E!T'N:
!T'**U1d7^;
2402D!11 <<:+;+;FMMRU[[<<:+;+;FMMRU[[ 8+ 8+ 8+ 8+[[+{K!U[\]eefgh
r   )rk   rD   )r8   r9   r:   r;   r<   mathrL   r?   r=   r   r>   r   rt   rp   r   r   r@   rA   r   r   ri   ri   z   s     TXS[S[\gSh	/UE5%78	/KP	/		/1d6l 1tF| 1PTU[P\ 1V  6   tF|  *)v )f ) )r   ri   c                   Z    \ rS rSrSrSS\SS4S jjrS\S\S\4S	 jrS
\S\S\4S jr	Sr
g)BoxLinearCoder   z
The linear box-to-box transform defined in FCOS. The transformation is parameterized
by the distance from the center of (square) src box to 4 edges of the target box.
normalize_by_sizer   Nc                     Xl         g)zY
Args:
    normalize_by_size (bool): normalize deltas by the size of src (anchor) boxes.
Nr   )r   r   s     r   r   BoxLinearCoder.__init__   s
    
 "3r   rB   rC   c                 ,   SUS   US   -   -  nSUS   US   -   -  nX2S   -
  nXBS   -
  nUS   U-
  nUS   U-
  n[         R                  " XVXx4SS9n	U R                  (       a1  US   US   -
  n
US   US   -
  n[         R                  " XX4SS9nX-  n	U	$ )a  
Encode a set of proposals with respect to some reference boxes

Args:
    reference_boxes (Tensor): reference boxes
    proposals (Tensor): boxes to be encoded

Returns:
    Tensor: the encoded relative box offsets that can be used to
    decode the boxes.

rH   .r   .rF   .r   .rG   r}   rI   )r    r   r   )r   rB   rC   reference_boxes_ctr_xreference_boxes_ctr_ytarget_ltarget_ttarget_rtarget_brf   reference_boxes_wreference_boxes_hreference_boxes_sizes                r   rt   BoxLinearCoder.encode   s     !$v'>QWAX'X Y #v'>QWAX'X Y )V+<<(V+<<V$'<<V$'<<++x8FBO!! / 7/&:Q Q / 7/&:Q Q#(;;"7H\bd$  4Gr   rz   r{   c                 Z   UR                  UR                  S9nSUS   US   -   -  nSUS   US   -   -  nU R                  (       a1  US   US   -
  nUS   US   -
  n[        R                  " XVXV4SS9nX-  nX1S   -
  nXAS   -
  n	X1S   -   n
XAS   -   n[        R                  " XX4SS9nU$ )	a  
From a set of original boxes and encoded relative box offsets,
get the decoded boxes.

Args:
    rel_codes (Tensor): encoded boxes
    boxes (Tensor): reference boxes.

Returns:
    Tensor: the predicted boxes with the encoded relative box offsets.

.. note::
    This method assumes that ``rel_codes`` and ``boxes`` have same size for 0th dimension. i.e. ``len(rel_codes) == len(boxes)``.

r   rH   r   r   r   r   r}   rI   )r   r   r   r    r   )r   rz   r{   r   r   boxes_wboxes_hlist_box_sizer   r   r   r   r   s                r   r   BoxLinearCoder.decode  s    " y/uV}uV}45uV}uV}45!!FmeFm3GFmeFm3G!KK7(LRTUM!1I////////[[+K!U[]^
r   r   )T)r8   r9   r:   r;   r<   boolr   r   rt   r   r@   rA   r   r   r   r      sO    
3$ 3$ 3!f ! !F !F# #v #& #r   r   c            	       t    \ rS rSrSrSrSr\\S.rSS\	S\	S\
S	S
4S jjrS\S	\4S jrS\S\S\S	S
4S jrSrg
)Matcheri9  aa  
This class assigns to each predicted "element" (e.g., a box) a ground-truth
element. Each predicted element will have exactly zero or one matches; each
ground-truth element may be assigned to zero or more predicted elements.

Matching is based on the MxN match_quality_matrix, that characterizes how well
each (ground-truth, predicted)-pair match. For example, if the elements are
boxes, the matrix may contain box IoU overlap values.

The matcher returns a tensor of size N containing the index of the ground-truth
element m that matches to prediction n. If there is no match, a negative value
is returned.
r}   )BELOW_LOW_THRESHOLDBETWEEN_THRESHOLDShigh_thresholdlow_thresholdallow_low_quality_matchesr   Nc                 v    SU l         SU l        [        R                  " X!:*  S5        Xl        X l        X0l        g)aO  
Args:
    high_threshold (float): quality values greater than or equal to
        this value are candidate matches.
    low_threshold (float): a lower quality threshold used to stratify
        matches into three levels:
        1) matches >= high_threshold
        2) BETWEEN_THRESHOLDS matches in [low_threshold, high_threshold)
        3) BELOW_LOW_THRESHOLD matches in [0, low_threshold)
    allow_low_quality_matches (bool): if True, produce additional matches
        for predictions that have only low-quality match candidates. See
        set_low_quality_matches_ for more details.
r}   r   z)low_threshold should be <= high_thresholdN)r   r   r    r   r   r   r   )r   r   r   r   s       r   r   Matcher.__init__P  s8     $& "$m57bc,*)B&r   match_quality_matrixc                    UR                  5       S:X  a)  UR                  S   S:X  a  [        S5      e[        S5      eUR                  SS9u  p#U R                  (       a  UR                  5       nOSnX R                  :  nX R                  :  X R                  :  -  nU R                  X5'   U R                  X6'   U R                  (       a.  Uc  [        R                  " SS5        U$ U R                  X4U5        U$ )aI  
Args:
    match_quality_matrix (Tensor[float]): an MxN tensor, containing the
    pairwise quality between M ground-truth elements and N predicted elements.

Returns:
    matches (Tensor[int64]): an N tensor where N[i] is a matched gt in
    [0, M - 1] or a negative value indicating that prediction i could not
    be matched.
r   zENo ground-truth boxes available for one of the images during trainingzANo proposal boxes available for one of the images during trainingrI   NFzall_matches should not be None)r$   shape
ValueErrorr   r   cloner   r   r   r   r    r   set_low_quality_matches_)r   r   matched_valsmatchesall_matchesbelow_low_thresholdbetween_thresholdss          r   r6   Matcher.__call__e  s      %%'1,#))!,1 !hii !dee !5 8 8Q 8 ?))!--/KK +-?-??*.@.@@\TgTgEgh'+'?'?$&*&=&=#))"e%EF  --gDXYr   r   r   c                 z    UR                  SS9u  pE[        R                  " X4SS2S4   :H  5      nUS   nX'   X'   g)aH  
Produce additional matches for predictions that have only low-quality matches.
Specifically, for each ground-truth find the set of predictions that have
maximum overlap with it (including ties); for each prediction in that set, if
it is unmatched, then match it to the ground-truth with which it has the highest
quality value.
r   rI   N)r   r    r!   )r   r   r   r   highest_quality_foreach_gt_ gt_pred_pairs_of_highest_qualitypred_inds_to_updates           r   r    Matcher.set_low_quality_matches_  sR     )=(@(@Q(@(G%"+0;;7KjkmqjqOr7r+s( ?qA'2'G$r   )r   r   r   r   r   )F)r8   r9   r:   r;   r<   r   r   r"   __annotations__r=   r   r   r   r6   r   r@   rA   r   r   r   r   9  s       #!O
Cu CU C_c Cpt C*&V & &PH HV Hci Hnr Hr   r   c                   L   ^  \ rS rSrS\SS4U 4S jjrS\S\4U 4S jjrSrU =r	$ )	
SSDMatcheri  	thresholdr   Nc                 "   > [         TU ]  XSS9  g )NF)r   )superr   )r   r   	__class__s     r   r   SSDMatcher.__init__  s    Or   r   c                    > [         TU ]  U5      nUR                  SS9u  p4[        R                  " UR                  S5      [        R                  UR                  S9X$'   U$ )Nr   rI   r   rw   )r   r6   r   r    aranger   int64r   )r   r   r   r   highest_quality_pred_foreach_gtr   s        r   r6   SSDMatcher.__call__  sa    '"#78 .B-E-E!-E-L*38<<+0035;;OnOuOu4
0 r   rA   )
r8   r9   r:   r;   r=   r   r   r6   r@   __classcell__)r   s   @r   r   r     s1    P% PD P	V 	 	 	r   r   modelepsc                 l    U R                  5        H   n[        U[        5      (       d  M  Xl        M"     g)a  
This method overwrites the default eps values of all the
FrozenBatchNorm2d layers of the model with the provided value.
This is necessary to address the BC-breaking change introduced
by the bug-fix at pytorch/vision#2933. The overwrite is applied
only when the pretrained weights are loaded to maintain compatibility
with previous versions.

Args:
    model (nn.Module): The model on which we perform the overwrite.
    eps (float): The new value of eps.
N)modulesr   r
   r   )r   r   modules      r   overwrite_epsr     s'     --/f/00J "r   r   c                    U R                   nU R                  5         [        R                  " 5          [	        U R                  5       5      R                  n[        R                  " SSUS   US   4US9nU " U5      n[        U[        R                  5      (       a  [        SU4/5      nUR                  5        Vs/ s H  ofR                  S5      PM     nnSSS5        U(       a  U R                  5         W$ s  snf ! , (       d  f       N,= f)ak  
This method retrieves the number of output channels of a specific model.

Args:
    model (nn.Module): The model for which we estimate the out_channels.
        It should return a single Tensor or an OrderedDict[Tensor].
    size (Tuple[int, int]): The size (wxh) of the input.

Returns:
    out_channels (List[int]): A list of the output channels of the model.
r   rG   r   r   0N)trainingevalr    no_gradnext
parametersr   zerosr   r   r   valuesr   train)r   r   in_trainingr   tmp_imgfeaturesxout_channelss           r   retrieve_out_channelsr    s     ..K	JJL	e&&()00++q!T!Wd1g6vF>h--"S(O#45H+3??+<=+<aq	+<= 
  > 
s   B
C><C9C>9C>>
Dvc                     U $ NrA   )r  s    r   _fake_cast_onnxr    s    Hr   input	orig_kvalaxisc           	      x   [         R                  R                  5       (       d  [        XR	                  U5      5      $ [         R
                  " U 5      U   R                  S5      n[         R                  " [         R                  " [         R                  " U/UR                  S9U4S5      5      n[        U5      $ )aA  
ONNX spec requires the k-value to be less than or equal to the number of inputs along
provided dim. Certain models use the number of elements along a particular axis instead of K
if K exceeds the number of elements along that axis. Previously, python's min() function was
used to determine whether to use the provided k-value or the specified dim axis value.

However, in cases where the model is being exported in tracing mode, python min() is
static causing the model to be traced incorrectly and eventually fail at the topk node.
In order to avoid this situation, in tracing mode, torch.min() is used instead.

Args:
    input (Tensor): The original input tensor.
    orig_kval (int): The provided k-value.
    axis(int): Axis along which we retrieve the input size.

Returns:
    min_kval (int): Appropriately selected k-value.
r   r   )r    jit
is_tracingr#   r   _shape_as_tensorrK   rM   r   r   r  )r  r  r  axis_dim_valmin_kvals        r   	_topk_minr    s    & 99!!9jj.//))%06@@CLyyELL)LDVDV$WYe#fhijkH8$$r   type	box_coderanchors_per_imagematched_gt_boxes_per_imagebbox_regression_per_imagecnfc                    [         R                  " U S;   SU  35        U S:X  a&  UR                  X25      n[        R                  " XFSS9$ U S:X  a7  UR                  X25      nUb  SU;   a  US   OSn[        R
                  " XFSUS	9$ UR                  XB5      nUb  S
U;   a  US
   OSn	U S:X  a  [        XSU	S9$ U S:X  a  [        XSU	S9$ [        XSU	S9$ )N)l1	smooth_l1cioudiougiouzUnsupported loss: r  sum)	reductionr  betag      ?)r  r  r   gHz>r  )r  r   r  )
r    r   rp   Fl1_losssmooth_l1_lossr   r   r	   r   )
r  r  r  r  r  r  target_regressionr  bbox_per_imager   s
             r   	_box_lossr$    s     
MM$EEI[\`[aGbct|%334Nbyy2QVWW		%334Nb!o&C-s6{S 9X]dhii"001J^Oc%j$6>(_djmnn6>(_djmnn'^cilmmr   r  )%r   collectionsr   typingr   r    r   r   torch.nnr   r  torchvision.opsr   r	   r
   r   r   r
  _script_if_tracingrg   ri   r   r   r   Moduler=   r   r?   r"   r>   r  unusedr  r  strdictr$  rA   r   r   <module>r.     s    #    $ u u<  < ~ ,& ,V ,f ,QW , ,^f fRS SlgH gHT    4 $ %S/ d3i < v #  %V % %3 %3 %@ '+n
nn n !'	n
  &n 
$sEz"	#n nr   