§
    ­¸j‰H  ã                  óT  — 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
„Zdd„Zdd„Zd d„Zdd„Zd!d„Zd!d„ZdZd!d„Zd"d„Zd#d„Zej        dk    renej                             e¦  «        Zd#d„Zej        dk    renej                             e¦  «        ZdS )$z1Utilities for bounding box manipulation and GIoU.é    )ÚannotationsN)ÚTensor)Úbox_area)Úis_compilingÚxr   Úreturnc                ó>  — |                       d¦  «        \  }}}}|d|                     d¬¦  «        z  z
  |d|                     d¬¦  «        z  z
  |d|                     d¬¦  «        z  z   |d|                     d¬¦  «        z  z   g}t          j        |d¬¦  «        S )Néÿÿÿÿg      à?g        ©Úmin©Údim)ÚunbindÚclampÚtorchÚstack)r   Úx_cÚy_cÚwÚhÚbs         úh/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/utilities/box_ops.pyÚbox_cxcywh_to_xyxyr      s£   € Ø—X’X˜b‘\”\�N€Cˆˆa�à	ˆs�Q—W’W �WÑ%Ô%Ñ%Ñ	%Ø	ˆs�Q—W’W �WÑ%Ô%Ñ%Ñ	%Ø	ˆs�Q—W’W �WÑ%Ô%Ñ%Ñ	%Ø	ˆs�Q—W’W �WÑ%Ô%Ñ%Ñ	%ð		€Aõ Œ;�q˜bÐ!Ñ!Ô!Ð!ó    c                ó’   — |                       d¦  «        \  }}}}||z   dz  ||z   dz  ||z
  ||z
  g}t          j        |d¬¦  «        S )Nr
   é   r   )r   r   r   )r   Úx0Úy0Úx1Úy1r   s         r   Úbox_xyxy_to_cxcywhr!   *   sT   € Ø—X’X˜b‘\”\�N€BˆˆB�Ø
ˆr‰'�Q‰˜˜b™ A™¨¨R©°2¸±7Ð<€AÝŒ;�q˜bÐ!Ñ!Ô!Ð!r   Úboxes1Úboxes2útuple[Tensor, Tensor]c                óÈ  — t          | ¦  «        }t          |¦  «        }t          j        | dd…ddd…f         |dd…dd…f         ¦  «        }t          j        | dd…ddd…f         |dd…dd…f         ¦  «        }||z
                       d¬¦  «        }|dd…dd…df         |dd…dd…df         z  }|dd…df         |z   |z
  }d}	||                     |	¬¦  «        z  }
|
|fS )a0  Compute pairwise IoU and union for two sets of boxes.

    Returns:
        iou: the NxM matrix containing the pairwise
            IoU values for every element in boxes1 and boxes2
        union: the NxM matrix containing the pairwise
            union values for every element in boxes1 and boxes2
    Nr   r   r   é   çH¯¼šò×z>)r   r   Úmaxr   r   ©r"   r#   Úarea1Úarea2ÚltÚrbÚwhÚinterÚunionÚepsÚious              r   Úbox_iour3   1   s  € õ �VÑÔ€EÝ�VÑÔ€Eå	Œ�6˜!˜!˜!˜T 2 A 2˜+Ô&¨¨q¨q¨q°"°1°"¨u¬Ñ	6Ô	6€BÝ	Œ�6˜!˜!˜!˜T 1 2 2˜+Ô&¨¨q¨q¨q°!°"°"¨u¬Ñ	6Ô	6€Bà
ˆr‰'�Š˜QˆÑ	Ô	€BØˆqˆqˆq�!�!�!�QˆwŒK˜"˜Q˜Q˜Q    1˜Wœ+Ñ%€Eà�!�!�!�T�'ŒN˜UÑ" UÑ*€Eà
€Cð �%—+’+ #�+Ñ&Ô&Ñ
&€CØ�ˆ:Ðr   ÚNonec                ó”   — | j         d         |j         d         k    r+t          d| j         d         › d|j         d         › �¦  «        ‚dS )zLReject unequal-length operands so a length-1 side cannot silently broadcast.r   zJelementwise box ops expect boxes1 and boxes2 to have the same length, got z and N)ÚshapeÚ
ValueError)r"   r#   s     r   Ú_assert_equal_lengthr8   L   s^   € à„|�A„˜&œ, qœ/Ò)Ð)Ýð;Ø”< ”?ð;ð ;Ø)/¬°a¬ð;ð ;ñ
ô 
ð 	
ð *Ð)r   c                óÄ  — t          | |¦  «         t          | ¦  «        }t          |¦  «        }t          j        | dd…dd…f         |dd…dd…f         ¦  «        }t          j        | dd…dd…f         |dd…dd…f         ¦  «        }||z
                       d¬¦  «        }|dd…df         |dd…df         z  }||z   |z
  }d}	||                     |	¬¦  «        z  }
|
|fS )a  Compute IoU and union for pre-matched box pairs.

    Unlike ``box_iou``, this avoids materializing the full NxN pairwise matrix
    (of which only the diagonal is used for matched pairs), so peak memory is
    O(N) instead of O(N^2). ``boxes1`` and ``boxes2`` must have the same length
    and be in [x0, y0, x1, y1] format; a length mismatch raises ``ValueError``
    rather than silently broadcasting a length-1 operand.

    The numerics (op order and the ``eps=1e-7`` union clamp) are identical to the
    diagonal of ``box_iou``, so results carry no dtype dependence beyond that of
    the pairwise version under FP16/FP32.

    Returns:
        iou: the [N] tensor of IoU values for each matched pair.
        union: the [N] tensor of union areas for each matched pair.
    Nr   r   r   r&   r'   )r8   r   r   r(   r   r   r)   s              r   Úelementwise_box_iour:   U   s   € õ" ˜ Ñ(Ô(Ð(Ý�VÑÔ€EÝ�VÑÔ€Eå	Œ�6˜!˜!˜!˜R˜a˜R˜%”= &¨¨¨¨B¨Q¨B¨¤-Ñ	0Ô	0€BÝ	Œ�6˜!˜!˜!˜Q˜R˜R˜%”= &¨¨¨¨A¨B¨B¨¤-Ñ	0Ô	0€Bà
ˆr‰'�Š˜QˆÑ	Ô	€BØˆqˆqˆq�!ˆtŒH�r˜!˜!˜!˜Q˜$”xÑ€Eà�E‰M˜EÑ!€Eà
€Cð �%—+’+ #�+Ñ&Ô&Ñ
&€CØ�ˆ:Ðr   c                ó¢  — t          | |¦  «         t          | |¦  «        \  }}t          j        | dd…dd…f         |dd…dd…f         ¦  «        }t          j        | dd…dd…f         |dd…dd…f         ¦  «        }||z
                       d¬¦  «        }|dd…df         |dd…df         z  }d}|||z
  |                     |¬¦  «        z  z
  S )aÒ  Generalized IoU from https://giou.stanford.edu/ for pre-matched box pairs.

    Equivalent to the diagonal of ``generalized_box_iou`` but without building the
    NxN matrix, giving O(N) instead of O(N^2) peak memory. The boxes should be in
    [x0, y0, x1, y1] format, and ``boxes1``/``boxes2`` must have the same length; a
    length mismatch raises ``ValueError`` rather than silently broadcasting.

    Returns a [N] tensor, one GIoU value per matched pair.
    Nr   r   r   r&   r'   )r8   r:   r   r   r(   r   ©	r"   r#   r2   r0   r,   r-   r.   Úarear1   s	            r   Úelementwise_generalized_box_iour>   y   sé   € õ ˜ Ñ(Ô(Ð(å$ V¨VÑ4Ô4�J€Cˆå	Œ�6˜!˜!˜!˜R˜a˜R˜%”= &¨¨¨¨B¨Q¨B¨¤-Ñ	0Ô	0€BÝ	Œ�6˜!˜!˜!˜Q˜R˜R˜%”= &¨¨¨¨A¨B¨B¨¤-Ñ	0Ô	0€Bà
ˆr‰'�Š˜QˆÑ	Ô	€BØˆaˆaˆa�ˆdŒ8�b˜˜˜˜A˜”hÑ€Dà
€Cà�$˜‘, $§*¢*° *Ñ"5Ô"5Ñ5Ñ5Ð5r   c                ó’  — t          | |¦  «        \  }}t          j        | dd…ddd…f         |dd…dd…f         ¦  «        }t          j        | dd…ddd…f         |dd…dd…f         ¦  «        }||z
                       d¬¦  «        }|dd…dd…df         |dd…dd…df         z  }d}|||z
  |                     |¬¦  «        z  z
  S )z»Generalized IoU from https://giou.stanford.edu/

    The boxes should be in [x0, y0, x1, y1] format.

    Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2).
    Nr   r   r   r&   r'   )r3   r   r   r(   r   r<   s	            r   Úgeneralized_box_iour@   ’   së   € õ ˜ Ñ(Ô(�J€Cˆå	Œ�6˜!˜!˜!˜T 2 A 2˜+Ô&¨¨q¨q¨q°"°1°"¨u¬Ñ	6Ô	6€BÝ	Œ�6˜!˜!˜!˜T 1 2 2˜+Ô&¨¨q¨q¨q°!°"°"¨u¬Ñ	6Ô	6€Bà
ˆr‰'�Š˜QˆÑ	Ô	€BØˆaˆaˆa����AˆgŒ;˜˜A˜A˜A˜q˜q˜q !˜GœÑ$€Dà
€Cà�$˜‘, $§*¢*° *Ñ"5Ô"5Ñ5Ñ5Ð5r   i   c                ó°  — | j         |j         us| j        d         |j        d         k    rt          j        | |d¬¦  «        S | j         j        rG| j         t          j        t          j        fvr(|                      ¦   «         } |                     ¦   «         }t          ¦   «         r¥|  	                    d¦  «        | 	                    d¦  «        z
   
                    ¦   «         }|j        d         dk    r"|                     |j        dd…         ¦  «        S |d         }t          d|j        d         ¦  «        D ]}||d	|f         z   }Œ|S t          j        | j        dd…         |j        dd…         ¦  «        }| j        d         }|j        d         }| j        d         }g |¢|‘|‘R }	|                     ¦   «         |z  }
|dk    s|
dk    s|dk    r|                      |	¦  «        S t          j        ¦   «          }t!          dt#          |t$          t!          d|
|z  ¦  «        z  ¦  «        ¦  «        }||k    rh|  	                    d¦  «        | 	                    d¦  «        z
  }|r|                     ¦   «         n| 
                    ¦   «                              d¦  «        S |                      |	¦  «        }t          d||¦  «        D ]‘}t#          ||z   |¦  «        }|  	                    d¦  «        |d	||…dd…f          	                    d¦  «        z
  }|r|                     ¦   «         n| 
                    ¦   «                              d¦  «        |d	||…f<   Œ’|S )
aò  Pairwise L1 distance between two sets of boxes.

    Equivalent to ``torch.cdist(boxes1, boxes2, p=1)`` for the box-shaped inputs the
    matcher builds. In eager mode it is bit-identical to it on CPU and between this
    function's own chunked and single-shot branches on every device, for every shape
    and dtype the tests exercise. CUDA-vs-``cdist`` parity is exact in practice but is
    only tested to a numerical tolerance, since kernel reduction order is not guaranteed
    identical across CUDA runner/torch versions. That guarantee is scoped to an equal-dtype
    operand pair -- a mismatched pair delegates to ``torch.cdist`` itself -- with
    narrower-than-float32 operands reduced in float32, the form ``torch.cdist`` is
    handed under autocast and refuses outside one.
    ``torch.cdist`` is a general Minkowski-distance routine: for ``p=1`` on CUDA it
    dispatches to a generic kernel that cannot exploit how small the feature
    dimension is, which makes it the most expensive single operator in the matcher
    despite doing only four subtractions per pair. Broadcasting and reducing over
    the four box coordinates is memory-bound instead, and measured 15-29x faster on
    the shapes RF-DETR's matcher produces. That figure is a CUDA measurement, and the
    trade is device-specific: on CPU the same broadcast form measured 2.7-4.9x *slower*
    than ``torch.cdist``. Training builds this cost matrix on CUDA, so the CPU regression
    is confined to tests and small-scale debugging.

    The broadcast form would materialise ``[*leading, queries, targets, features]``,
    so the target dimension is processed in chunks sized from
    :data:`_L1_COST_ELEMENT_BUDGET`. Chunking cannot change the result because the
    reduction runs over the feature axis only, never across chunks.

    Under ``torch.compile``, this takes one broadcast reduction rather than the eager chunking
    loop. Inductor can fuse that expression without unrolling a target-dependent Python loop;
    eager calls retain the bounded-memory chunked implementation below. The compiled reduction
    adds the coordinates in a fixed left-to-right order, so on CPU it is bit-identical to the
    eager branches and to ``torch.cdist``; on CUDA it carries the same tolerance-only guarantee
    against ``torch.cdist`` as the eager path.

    Args:
        boxes1: Boxes of shape ``[*leading, queries, features]``.
        boxes2: Boxes of shape ``[*leading, targets, features]``, sharing the dtype and
            device of *boxes1*. Its leading dimensions broadcast against *boxes1*'s, as
            they do in ``torch.cdist``.

    Returns:
        Pairwise L1 cost of shape ``[*leading, queries, targets]``, in the operands' dtype
        except for floating dtypes narrower than float32, which are reduced in float32.

    Examples:
        >>> boxes1 = torch.tensor([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]])
        >>> boxes2 = torch.tensor([[0.0, 0.0, 1.0, 1.0]])
        >>> pairwise_box_l1_cost(boxes1, boxes2).tolist()
        [[0.0], [2.0]]
    r
   r&   )Úpéþÿÿÿéýÿÿÿr   N).r   .)Údtyper6   r   ÚcdistÚis_floating_pointÚfloat32Úfloat64Úfloatr   Ú	unsqueezeÚabsÚ	new_zerosÚrangeÚbroadcast_shapesÚnumelÚis_grad_enabledr(   r   Ú_L1_COST_ELEMENT_BUDGETÚabs_ÚsumÚ	new_empty)r"   r#   Ú
differenceÚcostÚfeatureÚleadingÚqueriesÚtargetsÚfeaturesÚ
cost_shapeÚrowsÚreduce_in_placeÚchunkÚstartÚstops                  r   Úpairwise_box_l1_costrc   ³   sJ  € ðd „|˜6œ<Ð'Ð'¨6¬<¸Ô+;¸v¼|ÈBÔ?OÒ+OÐ+Oõ Œ{˜6 6¨QÐ/Ñ/Ô/Ð/à„|Ô%ð 	 ¨&¬,½u¼}ÍeÌmÐ>\Ð*\Ð*\ð —’‘”ˆØ—’‘”ˆå�~„~ð ð ×&Ò& rÑ*Ô*¨V×-=Ò-=¸bÑ-AÔ-AÑA×FÒFÑHÔHˆ
ØÔ˜BÔ 1Ò$Ð$Ø×'Ò'¨
Ô(8¸¸"¸Ô(=Ñ>Ô>Ð>Ø˜&Ô!ˆÝ˜Q 
Ô 0°Ô 4Ñ5Ô5ð 	3ð 	3ˆGØ˜* S¨' \Ô2Ñ2ˆDˆDØˆõ Ô$ V¤\°#°2°#Ô%6¸¼ÀSÀbÀSÔ8IÑJÔJ€GØŒl˜2Ô€GØŒl˜2Ô€GØŒ|˜BÔ€HØ-�7Ð-˜GÐ- WÐ-Ð-€JØ�=Š=‰?Œ?˜WÑ$€DØ�1‚}€}˜ š	˜	 W°¢\ \ð ×Ò 
Ñ+Ô+Ð+õ  Ô/Ñ1Ô1Ð1€Oå�•3�wÕ 7½3¸qÀ$ÈÁ/Ñ;RÔ;RÑ RÑSÔSÑTÔT€EØ�ÒÐØ×%Ò% bÑ)Ô)¨F×,<Ò,<¸RÑ,@Ô,@Ñ@ˆ
Ø%4ÐJ�
—’Ñ!Ô!Ð!¸*¿.º.Ñ:JÔ:J×OÒOÐPRÑSÔSÐSà×Ò˜JÑ'Ô'€DÝ�q˜' 5Ñ)Ô)ð eð eˆÝ�5˜5‘= 'Ñ*Ô*ˆØ×%Ò% bÑ)Ô)¨F°3¸¸d¸
ÀAÀAÀAÐ3EÔ,F×,PÒ,PÐQSÑ,TÔ,TÑTˆ
Ø6EÐ![ §¢Ñ!2Ô!2Ð!2È:Ï>Ê>ÑK[ÔK[× `Ò `ÐacÑ dÔ dˆˆS�%˜�*ˆ_ÑÐØ€Kr   Úmasksc                ó€  — |                       ¦   «         dk    rt          j        d| j        ¬¦  «        S | j        dd…         \  }}t          j        d|t          j        | j        ¬¦  «        }t          j        d|t          j        | j        ¬¦  «        }t          j        ||d¬¦  «        \  }}| |                     d¦  «        z  }| 	                    d	¦  «         
                    d
¦  «        d         }|                     |                      ¦   «          d¦  «         	                    d	¦  «                             d
¦  «        d         }| |                     d¦  «        z  }| 	                    d	¦  «         
                    d
¦  «        d         }	|                     |                      ¦   «          d¦  «         	                    d	¦  «                             d
¦  «        d         }
t          j        ||
||	gd	¦  «        }|  	                    d	¦  «                             d
¦  «        }|                     d¦  «        || <   |S )zçCompute the bounding boxes around the provided masks.

    The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.

    Returns a [N, 4] tensor, with the boxes in xyxy format.
    r   )r   é   )ÚdevicerC   N)rE   rg   Úij)Úindexingr&   r
   g    „×—Arf   )rP   r   Úzerosrg   r6   ÚarangerH   ÚmeshgridrK   Úflattenr(   Úmasked_fillÚboolr   r   ÚanyrM   )rd   r   r   Úyr   Úx_maskÚx_maxÚx_minÚy_maskÚy_maxÚy_minÚboxesÚkeeps                r   Úmasks_to_boxesrz   3  sÙ  € ð ‡{‚{�}„}˜ÒÐÝŒ{˜6¨%¬,Ð7Ñ7Ô7Ð7àŒ;�r�s�sÔ�D€A€qåŒ�Q˜¥¤°u´|ÐDÑDÔD€AÝŒ�Q˜¥¤°u´|ÐDÑDÔD€AÝŒ>˜!˜Q¨Ð.Ñ.Ô.�D€A€qà�Q—[’[ ‘^”^Ñ#€FØ�NŠN˜1ÑÔ×!Ò! "Ñ%Ô% aÔ(€EØ×Ò §¢¡¤˜°Ñ4Ô4×<Ò<¸QÑ?Ô?×CÒCÀBÑGÔGÈÔJ€Eà�Q—[’[ ‘^”^Ñ#€FØ�NŠN˜1ÑÔ×!Ò! "Ñ%Ô% aÔ(€EØ×Ò §¢¡¤˜°Ñ4Ô4×<Ò<¸QÑ?Ô?×CÒCÀBÑGÔGÈÔJ€EåŒK˜  u¨eÐ4°aÑ8Ô8€Eà�=Š=˜ÑÔ×Ò Ñ#Ô#€DØ—?’? 1Ñ%Ô%€Eˆ4ˆ%�LØ€Lr   Úinputsr[   c                ó$  — |                       ¦   «         } |                      d¦  «        } dt          j        d| |¦  «        z  }|                      d¦  «        dd…df         |                     d¦  «        ddd…f         z   }d|dz   |dz   z  z
  }|S )ag  Compute the DICE loss, similar to generalized IOU for masks.

    Args:
        inputs: A float tensor of arbitrary shape. The predictions for each example.
        targets: A float tensor with the same shape as inputs. Stores the binary
            classification label for each element in inputs (0 for the negative class and 1 for the positive class).
    r&   r   ú	nc,mc->nmr
   N)Úsigmoidrm   r   ÚeinsumrT   )r{   r[   Ú	numeratorÚdenominatorÚlosss        r   Úbatch_dice_lossrƒ   R  s�   € ð �^Š^ÑÔ€FØ�^Š^˜AÑÔ€FØ•E”L ¨f°gÑ>Ô>Ñ>€IØ—*’*˜R‘.”.    D Ô)¨G¯KªK¸©O¬O¸DÀ!À!À!¸GÔ,DÑD€KØ˜	 A™¨+¸©/Ñ:Ñ:€DØ€Kr   )é   é   c                ó*  — | j         d         }t          j        | t          j        | ¦  «        d¬¦  «        }t          j        | t          j        | ¦  «        d¬¦  «        }t          j        d||¦  «        t          j        d|d|z
  ¦  «        z   }||z  S )a†  Compute sigmoid cross-entropy loss for mask predictions.

    Args:
        inputs: A float tensor of arbitrary shape. The predictions for each example.
        targets: A float tensor with the same shape as inputs. Stores the binary
            classification label for each element in inputs (0 for the negative class and 1 for the positive class).

    Returns:
        Loss tensor.
    r&   Únone)Ú	reductionr}   )r6   ÚFÚ binary_cross_entropy_with_logitsr   Ú	ones_likeÚ
zeros_liker   )r{   r[   ÚhwÚposÚnegr‚   s         r   Úbatch_sigmoid_ce_lossr�   g  s‹   € ð 
Œ�aŒ€Bå
Ô
,¨VµU´_ÀVÑ5LÔ5LÐX^Ð
_Ñ
_Ô
_€CÝ
Ô
,¨VµUÔ5EÀfÑ5MÔ5MÐY_Ð
`Ñ
`Ô
`€CåŒ<˜ S¨'Ñ2Ô2µU´\À+ÈsÐUVÐY`ÑU`Ñ5bÔ5bÑb€Dà�"‰9Ðr   )r   r   r   r   )r"   r   r#   r   r   r$   )r"   r   r#   r   r   r4   )r"   r   r#   r   r   r   )rd   r   r   r   )r{   r   r[   r   r   r   )Ú__doc__Ú
__future__r   Úsysr   Útorch.nn.functionalÚnnÚ
functionalr‰   r   Útorchvision.ops.boxesr   Úrfdetr.utilities.compilerr   r   r!   r3   r8   r:   r>   r@   rR   rc   rz   rƒ   Úversion_infoÚjitÚscriptÚbatch_dice_loss_jitr�   Úbatch_sigmoid_ce_loss_jit© r   r   ú<module>rŸ      sÊ  ðð" 8Ð 7à "Ð "Ð "Ð "Ð "Ð "à 
€
€
€
à €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø *Ð *Ð *Ð *Ð *Ð *à 2Ð 2Ð 2Ð 2Ð 2Ð 2ð"ð "ð "ð "ð"ð "ð "ð "ðð ð ð ð6
ð 
ð 
ð 
ð!ð !ð !ð !ðH6ð 6ð 6ð 6ð26ð 6ð 6ð 6ð< +Ð ð}ð }ð }ð }ð@ð ð ð ð>ð ð ð ð$ *-Ô)9¸WÒ)DÐ)D�o�oÈ%Ì)×JZÒJZÐ[jÑJkÔJkÐ ðð ð ð ð. !Ô-°Ò8Ð8ÐÐ¸e¼i×>NÒ>NÐOdÑ>eÔ>eð Ð Ð r   