
    ^jV@                        d Z ddlmZ ddlZddlZddlmc m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mZmZmZ dd	lmZ  e       Zd
ZdZ G d dej4                        ZddZy)zFModules to compute the matching cost and solve the corresponding LSAP.    )annotationsN)linear_sum_assignment)nn)compute_keypoint_matching_cost)point_sample)batch_dice_lossbatch_sigmoid_ce_lossbox_cxcywh_to_xyxygeneralized_box_iou)
get_loggerg      ?g       @c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZedd       Z ej                         	 d	 	 	 	 	 	 	 d	d       Z	 xZ
S )
HungarianMatchera,  This class computes an assignment between the targets and the predictions of the network For efficiency reasons,
    the targets don't include the no_object.

    Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the
    best predictions, while the others are un-matched (and thus treated as non-objects).

    Note:
        The focal loss exponent ``gamma`` is fixed at ``_FOCAL_LOSS_GAMMA`` (2.0) and is not
        configurable. Only ``focal_alpha`` can be adjusted at construction time.
    c                   t         |           || _        || _        || _        |dk7  s|dk7  s|dk7  sJ d       || _        || _        || _        |	| _        |
xs g | _	        || _
        || _        || _        || _        d| _        y)a  Creates the matcher.

        Args:
            cost_class: Relative weight of the classification error in the matching cost.
            cost_bbox: Relative weight of the L1 error of the bounding box coordinates.
            cost_giou: Relative weight of the GIoU loss of the bounding box.
            focal_alpha: Alpha parameter for focal loss used in the classification cost.
            use_pos_only: Reserved for future use; currently has no effect.
            use_position_modulated_cost: Reserved for future use; currently has no effect.
            mask_point_sample_ratio: Downsampling ratio for mask point sampling.
            cost_mask_ce: Relative weight of the binary cross-entropy mask cost.
            cost_mask_dice: Relative weight of the Dice mask cost.
        r   zall costs can't be 0FN)super__init__
cost_class	cost_bbox	cost_gioufocal_alphamask_point_sample_ratiocost_mask_cecost_mask_dicenum_keypoints_per_classkeypoint_l1_loss_coefkeypoint_findable_loss_coefkeypoint_visible_loss_coefkeypoint_nll_loss_coef_warned_non_finite_costs)selfr   r   r   r   use_pos_onlyuse_position_modulated_costr   r   r   r   r   r   r   r   	__class__s                  `/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/matcher.pyr   zHungarianMatcher.__init__2   s    < 	$""Q)q.INZDZZB&'>$(,'>'D"$%:"+F(*D'&<#(-%    c                4   t        j                  |       }|j                         r| S t        j                  | j                        }|j                         r| |   }|j                         }||j                         j                         z   t        z   }t        j                  |      s| j                  |j                        }n=t        j                  ||j                        }n| j                  |j                        }| j                         }||| <   |S )a  Replace non-finite cost entries with a large finite sentinel.

        >>> HungarianMatcher._sanitize_cost_matrix(
        ...     torch.tensor([[1.0, float("nan")], [float("inf"), -2.0]])
        ... ).tolist()
        [[1.0, 4.0], [4.0, -2.0]]

        Args:
            cost_matrix: Cost matrix to sanitize before Hungarian assignment.

        Returns:
            Cost matrix with all non-finite entries replaced by a finite sentinel that is no smaller than any valid
            entry.
        )max)torchisfiniteallfinfodtypeanyr&   abs_SANITIZED_COST_MARGIN
new_tensorclampclone)cost_matrixfinite_mask
dtype_infofinite_costsmax_costreplacement_costsanitized_cost_matrixs          r#   _sanitize_cost_matrixz&HungarianMatcher._sanitize_cost_matrix`   s      nn[1??[[!2!23
??&{3L#'')H  (,*:*:*<*@*@*BBE[[>>"23#.#9#9*..#I #(;;/?Z^^#T   +55jnnE + 1 1 3.>{l+$$r$   c                   |d   j                   dd \  }}|d   j                  dd      }|j                         }|d   j                  dd      }t        j                  |D 	cg c]  }	|	d   	 c}	      }
t        j                  |D 	cg c]  }	|	d   	 c}	      }d}d	|d   v }d
|v xr d|d   v }|r(t        j                  |D 	cg c]  }	|	d   	 c}	d      }t        t        |      t        |            }| }| j                  }t        }d|z
  ||z  z  t        j                  |        z  }|d|z
  |z  z  t        j                  |       z  }|dd|
f   |dd|
f   z
  }t        j                  ||d      }|r/t        j                  |D 	cg c]  }	|	d	   	 c}	      }t        |d   t        j                        r|d   j                  dd      }|j                   d   |j                   d   z  | j                  z  }t        j                  d|d|j                         }t#        |j%                  d      |j'                  |j                   d   dd      d      j)                  d      }n|d   d   }|d   d   }|d   d   }|j                   d   |j                   d   z  | j                  z  }t        j                  d|d|j                         }t#        ||j'                  |j                   d   dd      d      }t        j*                  d||      |z   }|j                  dd      }|j-                  |j.                        }t#        |j%                  d      |j'                  |j                   d   dd      dd      j)                  d      }t1        ||      } t3        ||      }!|r|}|dddf   |dddf   z  }"t5        |d
   ||
|"| j6                        \  }#}$}%}&|#j                  dd      }#|$j                  dd      }$|%j                  dd      }%|&j                  dd      }&| j8                  |z  | j:                  |z  z   | j<                  |z  z   }'|r"|'| j>                   z  z   | j@                  !z  z   }'|rB|'| jB                  #z  z   | jD                  $z  z   | jF                  %z  z   | jH                  &z  z   }'|'jK                  ||d      jM                         jO                         }'t        jP                  |'      }(|(jS                         s9| jT                  stV        jY                  d       d| _*        | j[                  |'      }'|D 	cg c]  }	t]        |	d          })}	g }*||z  }+|'j_                  |+d      },ta        |      D ]  }-|,|-   }.tc        |.j_                  |)d            D /0cg c]  \  }/}0te        |0|/          }1}/}0|-dk(  r|1}*Itg        |*|1      D 23cg c]E  \  }2}3ti        jj                  |2d   |3d   |+|-z  z   g      ti        jj                  |2d   |3d   g      fG }*}2}3 |*D /4cg c]O  \  }/}4t        jl                  |/t        jn                        t        jl                  |4t        jn                        fQ c}4}/S c c}	w c c}	w c c}	w c c}	w c c}	w c c}0}/w c c}3}2w c c}4}/w )a  Performs the matching

        Args:
            outputs: Dict containing at least these entries:
                 "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
                 "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
            targets: List of targets (len(targets) = batch_size), where each target is a dict containing:
                 "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
                           objects in the target) containing the class labels
                 "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates "masks": Tensor of
                 dim [num_target_boxes, H, W] containing the target mask coordinates
            group_detr: Number of groups used for matching.

        Returns:
            A list of size batch_size, containing tuples of (index_i, index_j) where:
                - index_i is the indices of the selected predictions (in order)
                - index_j is the indices of the corresponding selected targets (in order)
            For each batch element, it holds:
                len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
        pred_logitsN   r      
pred_boxeslabelsboxesmaskspred_keypoints	keypoints)dim)p
pred_masks)deviceF)align_cornersspatial_featuresquery_featuresbiaszbcp,bnc->bnpnearest)rJ   mode   )all_pred_keypointstarget_keypointstarget_classestarget_areasr   zsNon-finite values detected in matcher cost matrix; replacing with finite sentinel. Check for numerical instability.T)r+   )8shapeflattensigmoidr'   catr   r
   r   _FOCAL_LOSS_GAMMAF
logsigmoidcdist
isinstanceTensorr   randrI   r   	unsqueezerepeatsqueezeeinsumtor+   r	   r   r   r   r   r   r   r   r   r   r   r   r   viewfloatcpur(   r)   r   loggerwarningr9   lensplitrange	enumerater   zipnpconcatenate	as_tensorint64)5r   outputstargets
group_detrbsnum_queriesflat_pred_logitsout_probout_bboxvtgt_idstgt_bboxtgt_keypointsmasks_presentkeypoints_presentgiour   alphagammaneg_cost_classpos_cost_classr   r   	tgt_masks	out_masks
num_pointspoint_coordspred_masks_logitsrK   rL   rM   tgt_masks_flatr   r   rT   cost_l1cost_findablecost_visiblecost_nllr2   r3   sizesindicesg_num_queriescost_matrix_listg_igrouped_cost_matrixic	indices_gindice1indice2js5                                                        r#   forwardzHungarianMatcher.forward   s   6 "-066r:K #=199!Q?#++-<(00A6 ))':QQx[:;99':Qaj:;71:-,7UK7ST:<U!IIw&G!q~&GQOM ##5h#?AST\A]^E	   !
 e)%8Q\\K[J[=\<\]1x<E"9:q||L\?]>]^#AwJ/.G2LL
 KK(a8			w"?!1W:"?@I',/>#L199!Q?	&__R09??23FF$JfJff
$zz!Z9CSCST$0''*L,?,?	PQ@RTUWX,Yin%'!* " $+<#89K#L !(!67G!H|,V4-33B7:J:P:PQS:TTX\XtXtt
$zz!ZCSCZCZ[$0$l&9&9:J:P:PQR:SUVXY&Zjo%! %*LLARTb$cfj$j!$5$=$=a$C!!%6%<%<=I)##A&##IOOA$61=#	
 gaj  11BNSL -->ON!:#AqD>HQTN:L=[#*+;#<!.&)(,(D(D>:G]L( ooa+G)11!Q7M'//15L''1-H nny04??Z3OORVR`R`clRll%(9(9L(HH4K^K^aoKooK,,w6722]BC 11L@A --8	9  Rb1779==? 	 nn[1 007
 15-44[AK*12QQwZ22#z1&,,],B$ 	C"23"7AJK^KdKdejlnKoApqA.qt4qIqax# -0,C
 ) 
GAJQTAT4T'UV
GAJ'?@ 	 lsscgcdfg%++6QVQ\Q\8]^ss ;: 'H* #@d 3 r ts2   #Z	ZZ$Z)Z.<Z3.A
Z9AZ?)r=   r=   r=   g      ?FF   r=   r=   N        r   r   r   )r   rf   r   rf   r   rf   r   rf   r    boolr!   r   r   intr   rf   r   rf   r   zlist[int] | Noner   rf   r   rf   r   rf   r   rf   )r2   torch.Tensorreturnr   )r=   )rs   dictrt   listru   r   r   z'list[tuple[torch.Tensor, torch.Tensor]])__name__
__module____qualname____doc__r   staticmethodr9   r'   no_gradr   __classcell__)r"   s   @r#   r   r   &   s,   	 !",1') !48'*-0,/(+,.,. ,. 	,.
 ,. ,. &*,. "%,. ,. ,. "2,.  %,. &+,. %*,. !&,.\ %% %%N U]]_
 	atat at 	at
 
1at atr$   r   c                d   | j                   | j                  | j                  | j                  t	        | dg       t	        | dd      t	        | dd      t	        | dd      t	        | dd      d	}| j
                  r/t        d	i || j                  | j                  | j                  dS t        d	i |S )
ao  Build a HungarianMatcher from a training argument namespace.

    Args:
        args: Namespace supplying ``focal_alpha``, ``set_cost_class``, ``set_cost_bbox``,
            ``set_cost_giou``, ``segmentation_head``, and optional keypoint cost
            coefficients (``keypoint_l1_loss_coef``, ``keypoint_findable_loss_coef``,
            ``keypoint_visible_loss_coef``, ``keypoint_nll_loss_coef``). When
            ``segmentation_head`` is truthy, also requires ``mask_ce_loss_coef``,
            ``mask_dice_loss_coef``, and ``mask_point_sample_ratio``.

    Returns:
        Configured HungarianMatcher instance.
    r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   r   )r   r   r    )
set_cost_classset_cost_bboxset_cost_giour   getattrsegmentation_headr   mask_ce_loss_coefmask_dice_loss_coefr   )argscommon_kwargss     r#   build_matcherr   -  s      ))''''''#*41JB#O!(/F!L'.t5RTW'X&-d4PRU&V")$0H#"N
M  

//33$($@$@	
 	
  0-00r$   )r   r   )r   
__future__r   numpyro   r'   torch.nn.functionalr   
functionalrZ   scipy.optimizer   rfdetr.models.heads.keypointsr    rfdetr.models.heads.segmentationr   rfdetr.utilities.box_opsr   r	   r
   r   rfdetr.utilities.loggerr   rh   r.   rY   Moduler   r   r   r$   r#   <module>r      s\   $ M "     0  H 9 t t .	  Dtryy DtN"1r$   