§
    ­¸jyT  ã                  ó8  — d dl mZ d dlmZ d dlmZmZ d dlZd dlm	c m
Z d dlmZm	Z	 d dlmZmZ d dlmZmZ  G d„ d	ej        j        ¦  «        Z G d
„ de	j        ¦  «        Z G d„ de	j        ¦  «        Z G d„ de	j        ¦  «        Zd$d„Z	 	 d%d&d!„Zd'd#„ZdS )(é    )Úannotations)ÚCallable)ÚAnyÚcastN)ÚTensorÚnn)Úconv2d_inputÚconv2d_weight)Ú_bilinear_grid_sampleÚ_nearest_grid_samplec                  óB   — e Zd ZdZedd„¦   «         Zedd„¦   «         ZdS )Ú_DepthwiseConvWithoutCuDNNa»  Depthwise conv2d with cuDNN disabled in both forward and backward.

    ``torch.backends.cudnn.flags(enabled=False)`` as a context manager only covers operations executed within its scope.
    ``nn.Conv2d`` records the forward op in the autograd graph; the corresponding backward kernels run later,
    **outside** that scope, with cuDNN re-enabled.  On some CUDA stacks (T4 / P100 on Kaggle / Colab) cuDNN fails engine
    selection for depthwise conv backward, raising::

        RuntimeError: GET was unable to find an engine to execute this computation

    This ``Function`` disables cuDNN in ``backward`` as well, fixing the crash.

    See: https://github.com/roboflow/rf-detr/issues/731
    Úctxú#torch.autograd.function.FunctionCtxÚxr   ÚweightÚbiasúTensor | NoneÚstrideútuple[int, ...]ÚpaddingÚdilationÚgroupsÚintÚreturnc           
     ó,  — |                       ||¦  «         |du| _        || _        || _        || _        || _        t          j        j         	                    d¬¦  «        5  t          j        |||||||¬¦  «        cddd¦  «         S # 1 swxY w Y   dS )a  Run depthwise conv2d forward with cuDNN disabled.

        Args:
            ctx: Autograd context.
            x: Input feature map ``(N, C, H, W)``.
            weight: Convolution weight tensor.
            bias: Optional convolution bias tensor.
            stride: Convolution stride.
            padding: Convolution padding.
            dilation: Convolution dilation.
            groups: Number of groups (equals ``C`` for depthwise).

        Returns:
            Output feature map ``(N, C, H, W)``.
        NF©Úenabled©r   r   r   r   )Úsave_for_backwardÚhas_biasr   r   r   r   ÚtorchÚbackendsÚcudnnÚflagsÚFÚconv2d)r   r   r   r   r   r   r   r   s           úp/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/models/heads/segmentation.pyÚforwardz"_DepthwiseConvWithoutCuDNN.forward#   sö   € ð4 	×Ò˜a Ñ(Ô(Ð(Ø 4Ð'ˆŒØˆŒ
ØˆŒØˆŒØˆŒ
õ
 Œ^Ô!×'Ò'°Ð'Ñ6Ô6ð 	oð 	oÝ”8˜A˜v t°FÀGÐV^ÐgmÐnÑnÔnð	oð 	oð 	oð 	oñ 	oô 	oð 	oð 	oð 	oð 	oð 	oð 	oøøøð 	oð 	oð 	oð 	oð 	oð 	os   Á!B	Â	BÂBÚgrad_outputúJtuple[Tensor | None, Tensor | None, Tensor | None, None, None, None, None]c           
     ó   — | j         \  }}| j        d         }| j        d         }| j        o| j        d         }d}d}d}	|s|rÓ|                     |j        ¬¦  «        }
t
          j        j                             d¬¦  «        5  |r/t          |j
        ||
| j        | j        | j        | j        ¬¦  «        }|rHt          |                     |j        ¬¦  «        |j
        |
| j        | j        | j        | j        ¬¦  «        }ddd¦  «         n# 1 swxY w Y   |r/|                     |j        ¬¦  «                             d	¬
¦  «        }	|||	ddddfS )u“  Compute gradients with cuDNN disabled.

        Args:
            ctx: Autograd context with saved tensors and conv parameters.
            grad_output: Upstream gradient ``(N, C, H, W)``.

        Returns:
            Gradients for each ``forward`` input.  Inputs that do not require gradients (``ctx.needs_input_grad[i]`` is
            ``False``) get ``None``. Non-tensor inputs always get ``None``.

        Note:
            Under AMP (``"bf16-mixed"`` or ``"16-mixed"``), ``grad_output`` may arrive in a reduced dtype while the
            saved ``weight`` stays ``fp32``.  Both tensors are upcast to ``weight.dtype`` before calling
            ``conv2d_input`` / ``conv2d_weight``.  ``grad_input`` is kept in ``weight.dtype`` (fp32) so that upstream
            gradient accumulation into fp32 leaf parameters stays in fp32 â€” matching standard ``F.conv2d`` backward
            behaviour.  Casting back to the activation dtype (``x.dtype``) would propagate a reduced-precision gradient
            to fp32 backbone parameters, causing a ``params, grads, exp_avgs, and exp_avg_sqs must have same dtype``
            crash in fused AdamW (see issue #959).
        r   é   é   N)ÚdtypeFr   r   )r   r.   é   ©Údim)Úsaved_tensorsÚneeds_input_gradr!   Útor/   r"   r#   r$   r%   r	   Úshaper   r   r   r   r
   Úsum)r   r*   r   r   Úneeds_x_gradÚneeds_w_gradÚneeds_b_gradÚ
grad_inputÚgrad_weightÚ	grad_biasÚgrad_output_casts              r(   Úbackwardz#_DepthwiseConvWithoutCuDNN.backwardJ   s³  € ð0 Ô%‰	ˆˆ6àÔ+¨AÔ.ˆØÔ+¨AÔ.ˆØ”|Ð?¨Ô(<¸QÔ(?ˆàˆ
ØˆØˆ	àð 	˜<ð 	ð
  +Ÿ~š~°F´L˜~ÑAÔAÐå”Ô%×+Ò+°EÐ+Ñ:Ô:ð ð Øð 	Ý!-ØœØØ(Ø"œzØ #¤Ø!$¤Ø"œzð"ñ "ô "�Jð  ð 	Ý"/ØŸš 6¤<˜Ñ0Ô0ØœØ(Ø"œzØ #¤Ø!$¤Ø"œzð#ñ #ô #�Kðð ð ñ ô ð ð ð ð ð ð øøøð ð ð ð ð, ð 	NØ#Ÿš¨V¬\˜Ñ:Ô:×>Ò>À9Ð>ÑMÔMˆIà˜;¨	°4¸¸tÀTÐIÐIs   ÂA<DÄDÄDN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r*   r   r   r+   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústaticmethodr)   r?   © ó    r(   r   r      so   € € € € € ðð ð ð$oð $oð $oñ „\ð$oðL ðAJð AJð AJñ „\ðAJð AJð AJrF   r   c                  ó6   ‡ — e Zd ZdZddˆ fd	„Zdd„Zdd„Zˆ xZS )ÚDepthwiseConvBlockz1Simplified ConvNeXt block without the MLP subnet.r   r2   r   Úlayer_scale_init_valueÚfloatr   ÚNonec                óŽ  •— t          ¦   «                              ¦   «          t          j        ||dd|¬¦  «        | _        t          j        |d¬¦  «        | _        t          j        ||¦  «        | _        t          j	        ¦   «         | _
        |dk    r+t          j        |t          j        |¦  «        z  d¬¦  «        nd | _        d S )	Nr0   r-   )Úkernel_sizer   r   g�íµ ÷Æ°>)Úepsr   T©Úrequires_grad)ÚsuperÚ__init__r   ÚConv2dÚdwconvÚ	LayerNormÚnormÚLinearÚpwconv1ÚGELUÚactÚ	Parameterr"   ÚonesÚgamma©Úselfr2   rI   Ú	__class__s      €r(   rR   zDepthwiseConvBlock.__init__’   s¬   ø€ Ý‰Œ×ÒÑÔÐÝ”i  S°aÀÈ3ÐOÑOÔOˆŒÝ”L ¨$Ð/Ñ/Ô/ˆŒ	Ý”y  cÑ*Ô*ˆŒÝ”7‘9”9ˆŒð &¨Ò)Ð)õ ŒLÐ/µ%´*¸S±/´/ÑAÐQUÐVÑVÔVÐVàð 	Œ
ˆ
ˆ
rF   r   r   c           	     óô   — t          t          dt          f         t          j        ¦  «        } ||| j        j        | j        j        | j        j        | j        j	        | j        j
        | j        j        ¦  «        S )N.)r   r   r   r   ÚapplyrT   r   r   r   r   r   r   )r_   r   Údepthwise_convs      r(   Ú_depthwise_convz"DepthwiseConvBlock._depthwise_convž   sg   € õ
 �h s­F {Ô3Õ5OÔ5UÑVÔVˆØˆ~ØØŒKÔØŒKÔØŒKÔØŒKÔØŒKÔ ØŒKÔñ
ô 
ð 	
rF   c                ó:  — |}|                       |¦  «        }|                     dddd¦  «        }|                      |¦  «        }|                      |¦  «        }|                      |¦  «        }| j        �
| j        |z  }|                     dddd¦  «        }||z   S )Nr   r.   r0   r-   )rd   ÚpermuterV   rX   rZ   r]   )r_   r   Úinputs      r(   r)   zDepthwiseConvBlock.forward®   s’   € ØˆØ× Ò  Ñ#Ô#ˆØ�IŠI�a˜˜A˜qÑ!Ô!ˆØ�IŠI�a‰LŒLˆØ�LŠL˜‰OŒOˆØ�HŠH�Q‰KŒKˆØŒ:Ð!Ø”
˜Q‘ˆAØ�IŠI�a˜˜A˜qÑ!Ô!ˆà�5‰yÐrF   ©r   ©r2   r   rI   rJ   r   rK   ©r   r   r   r   )r@   rA   rB   rC   rR   rd   r)   Ú__classcell__©r`   s   @r(   rH   rH   �   sp   ø€ € € € € Ø<Ð<ð

ð 

ð 

ð 

ð 

ð 

ð 

ð
ð 
ð 
ð 
ð ð ð ð ð ð ð ð rF   rH   c                  ó*   ‡ — e Zd Zddˆ fd„Zdd„Zˆ xZS )ÚMLPBlockr   r2   r   rI   rJ   r   rK   c                óœ  •— t          ¦   «                              ¦   «          t          j        |¦  «        | _        t          j        t          j        ||dz  ¦  «        t          j        ¦   «         t          j        |dz  |¦  «        g¦  «        | _        |dk    r+t          j	        |t          j        |¦  «        z  d¬¦  «        nd | _        d S )Né   r   TrO   )rQ   rR   r   rU   Únorm_inÚ
ModuleListrW   rY   Úlayersr[   r"   r\   r]   r^   s      €r(   rR   zMLPBlock.__init__½   s²   ø€ Ý‰Œ×ÒÑÔÐÝ”| CÑ(Ô(ˆŒÝ”må”	˜#˜s Q™wÑ'Ô'Ý”‘	”	Ý”	˜# ™' 3Ñ'Ô'ðñ
ô 
ˆŒð &¨Ò)Ð)õ ŒLÐ/µ%´*¸S±/´/ÑAÐQUÐVÑVÔVÐVàð 	Œ
ˆ
ˆ
rF   r   r   c                ó†   — |}|                       |¦  «        }| j        D ]} ||¦  «        }Œ| j        �
| j        |z  }||z   S )N)rq   rs   r]   )r_   r   rg   Úlayers       r(   r)   zMLPBlock.forwardÍ   sS   € ØˆØ�LŠL˜‰OŒOˆØ”[ð 	ð 	ˆEØ��a‘”ˆAˆAØŒ:Ð!Ø”
˜Q‘ˆAØ�5‰yÐrF   rh   ri   rj   )r@   rA   rB   rR   r)   rk   rl   s   @r(   rn   rn   ¼   sV   ø€ € € € € ð
ð 
ð 
ð 
ð 
ð 
ð 
ð ð ð ð ð ð ð ð rF   rn   c                  óN   ‡ — e Zd Zddˆ fd
„Zdd„Z	 ddd„Z	 ddd„Z	 ddd„Zˆ xZS )ÚSegmentationHeadr-   rp   Úin_dimr   Ú
num_blocksÚbottleneck_ratioÚdownsample_ratior   rK   c                ó<  •‡— t          ¦   «                              ¦   «          || _        |�‰|z  n‰| _        t	          j        ˆfd„t          |¦  «        D ¦   «         ¦  «        | _        |€t	          j        ¦   «         nt	          j	        ‰| j        d¬¦  «        | _
        t          ‰¦  «        | _        |€t	          j        ¦   «         nt	          j        ‰| j        ¦  «        | _        t	          j        t!          j        d¦  «        d¬¦  «        | _        d| _        d S )Nc                ó.   •— g | ]}t          ‰¦  «        ‘ŒS rE   )rH   )Ú.0Ú_rx   s     €r(   ú
<listcomp>z-SegmentationHead.__init__.<locals>.<listcomp>Ý   s"   ø€ Ð$[Ð$[Ð$[ÀAÕ%7¸Ñ%?Ô%?Ð$[Ð$[Ð$[rF   r-   )rM   TrO   F)rQ   rR   r{   Úinteraction_dimr   rr   ÚrangeÚblocksÚIdentityrS   Úspatial_features_projrn   Úquery_features_blockrW   Úquery_features_projr[   r"   Úzerosr   Ú_export)r_   rx   ry   rz   r{   r`   s    `   €r(   rR   zSegmentationHead.__init__Ø   sþ   øø€ Ý‰Œ×ÒÑÔÐà 0ˆÔØ=MÐ=Y˜vÐ)9Ñ9Ð9Ð_eˆÔÝ”mÐ$[Ð$[Ð$[Ð$[ÍÈzÑIZÔIZÐ$[Ñ$[Ô$[Ñ\Ô\ˆŒà-Ð5�BŒK‰MŒMˆM½2¼9ÀVÈTÔMaÐopÐ;qÑ;qÔ;qð 	Ô"õ %-¨VÑ$4Ô$4ˆÔ!à-Ð5�BŒK‰MŒMˆM½2¼9ÀVÈTÔMaÑ;bÔ;bð 	Ô õ ”L¥¤¨Q¡¤¸tÐDÑDÔDˆŒ	àˆŒˆˆrF   c                ó  — d| _         | j        | _        | j        | _        |                      ¦   «         D ]T\  }}t          |d¦  «        r?t          |j        ¦  «        r+t          |d¦  «        r|j         s|                     ¦   «          ŒUd S )NTÚexportr‰   )r‰   r)   Ú_forward_originÚforward_exportÚnamed_modulesÚhasattrÚcallabler‹   )r_   ÚnameÚms      r(   r‹   zSegmentationHead.exportë   s“   € ØˆŒØ#œ|ˆÔØÔ*ˆŒØ×)Ò)Ñ+Ô+ð 	ð 	‰GˆD�!Ý�q˜(Ñ#Ô#ð ­°´Ñ(:Ô(:ð ½wÀqÈ)Ñ?TÔ?Tð Ð]^Ô]fð Ø—’‘
”
�
øð	ð 	rF   FÚspatial_featuresr   Úquery_featuresúlist[Tensor]Ú
image_sizeútuple[int, int]Úskip_blocksÚboolc                óÊ  — |d         | j         z  |d         | j         z  f}t          j        ||dd¬¦  «        }g }|s•t          | j        |¦  «        D ]~\  }} ||¦  «        }|                      |¦  «        }	|                      |                      |¦  «        ¦  «        }|                     t          j
        d|	|¦  «        | j        z   ¦  «         Œn‘t          |¦  «        dk    s
J d¦   «         ‚|                      |¦  «        }	|                      |                      |d         ¦  «        ¦  «        }|                     t          j
        d|	|¦  «        | j        z   ¦  «         |S )Nr   r-   ÚbilinearF©ÚsizeÚmodeÚalign_cornersúbchw,bnc->bnhwú9skip_blocks is only supported for length 1 query features)r{   r&   ÚinterpolateÚziprƒ   r…   r‡   r†   Úappendr"   Úeinsumr   Úlen)
r_   r“   r”   r–   r˜   Útarget_sizeÚmask_logitsÚblockÚqfr…   s
             r(   r)   zSegmentationHead.forwardó   s„  € ð " !”}¨Ô(=Ñ=¸zÈ!¼}ÐPTÔPeÑ?eÐfˆÝœ=Ð)9ÀÐR\ÐlqÐrÑrÔrÐàˆØð 
	fÝ  ¤¨nÑ=Ô=ð jð j‘	��rØ#( 5Ð)9Ñ#:Ô#:Ð Ø(,×(BÒ(BÐCSÑ(TÔ(TÐ%Ø×-Ò-¨d×.GÒ.GÈÑ.KÔ.KÑLÔL�Ø×"Ò"¥5¤<Ð0@ÐBWÐY[Ñ#\Ô#\Ð_cÔ_hÑ#hÑiÔiÐiÐið	jõ �~Ñ&Ô&¨!Ò+Ð+Ð+Ð-hÑ+Ô+Ð+Ø$(×$>Ò$>Ð?OÑ$PÔ$PÐ!Ø×)Ò)¨$×*CÒ*CÀNÐSTÔDUÑ*VÔ*VÑWÔWˆBØ×Ò�uœ|Ð,<Ð>SÐUWÑXÔXÐ[_Ô[dÑdÑeÔeÐeàÐrF   úlist[dict[str, Tensor]]c                ó~  — |d         | j         z  |d         | j         z  f}t          j        ||dd¬¦  «        }g }|s‚t          | j        |¦  «        D ]k\  }} ||¦  «        }|                      |¦  «        }	|                      |                      |¦  «        ¦  «        }|                     |	|| j	        dœ¦  «         Œln~t          |¦  «        dk    s
J d¦   «         ‚|                      |¦  «        }	|                      |                      |d         ¦  «        ¦  «        }|                     |	|| j	        dœ¦  «         |S )Nr   r-   r›   Frœ   )r“   r”   r   r¡   )r{   r&   r¢   r£   rƒ   r…   r‡   r†   r¤   r   r¦   )
r_   r“   r”   r–   r˜   r§   Úoutput_dictsr©   rª   r…   s
             r(   Úsparse_forwardzSegmentationHead.sparse_forward  s„  € ð " !”}¨Ô(=Ñ=¸zÈ!¼}ÐPTÔPeÑ?eÐfˆÝœ=Ð)9ÀÐR\ÐlqÐrÑrÔrÐð 13ˆàð 	Ý  ¤¨nÑ=Ô=ð ð ‘	��rØ#( 5Ð)9Ñ#:Ô#:Ð Ø(,×(BÒ(BÐCSÑ(TÔ(TÐ%Ø×-Ò-¨d×.GÒ.GÈÑ.KÔ.KÑLÔL�à×#Ò#à,AØ*,Ø $¤	ðð ñô ð ð ðõ �~Ñ&Ô&¨!Ò+Ð+Ð+Ð-hÑ+Ô+Ð+à$(×$>Ò$>Ð?OÑ$PÔ$PÐ!Ø×)Ò)¨$×*CÒ*CÀNÐSTÔDUÑ*VÔ*VÑWÔWˆBà×Òà(=Ø&(Ø œIðð ñô ð ð ÐrF   c                óž  — t          |¦  «        dk    s
J d¦   «         ‚|d         | j        z  |d         | j        z  f}t          j        ||dd¬¦  «        }|s| j        D ]} ||¦  «        }Œ|                      |¦  «        }|                      |                      |d         ¦  «        ¦  «        }t          j	        d||¦  «        | j
        z   gS )Nr-   zCat export time, segmentation head expects exactly one query featurer   r›   Frœ   r    )r¦   r{   r&   r¢   rƒ   r…   r‡   r†   r"   r¥   r   )	r_   r“   r”   r–   r˜   r§   r©   r…   rª   s	            r(   r�   zSegmentationHead.forward_export=  sí   € õ �>Ñ"Ô" aÒ'Ð'Ð'Ð)nÑ'Ô'Ð'à! !”}¨Ô(=Ñ=¸zÈ!¼}ÐPTÔPeÑ?eÐfˆÝœ=Ð)9ÀÐR\ÐlqÐrÑrÔrÐàð 	;Øœð ;ð ;�Ø#( 5Ð)9Ñ#:Ô#:Ð Ð à $× :Ò :Ð;KÑ LÔ LÐà×%Ò% d×&?Ò&?ÀÈqÔ@QÑ&RÔ&RÑSÔSˆÝ”Ð-Ð/DÀbÑIÔIÈDÌIÑUÐVÐVrF   )r-   rp   )
rx   r   ry   r   rz   r   r{   r   r   rK   )r   rK   )F)
r“   r   r”   r•   r–   r—   r˜   r™   r   r•   )
r“   r   r”   r•   r–   r—   r˜   r™   r   r«   )	r@   rA   rB   rR   r‹   r)   r®   r�   rk   rl   s   @r(   rw   rw   ×   s»   ø€ € € € € ðð ð ð ð ð ð ð&ð ð ð ð "ðð ð ð ð ðB "ð,ð ,ð ,ð ,ð ,ðf "ðWð Wð Wð Wð Wð Wð Wð Wð WrF   rw   rg   r   Úpoint_coordsÚkwargsr   r   c                ó˜  — d}|                      ¦   «         dk    rd}|                     d¦  «        }d|z  dz
  }|                     dd¦  «        }|                     d	d¦  «        }|                     d
d¦  «        }|dk    rz|rFd                     t	          |                     ¦   «         ¦  «        ¦  «        }t          d|› �¦  «        ‚|dvrt          j        | ||||¬¦  «        }	nKt          | |||¬¦  «        }	n7|dk    r|s|dv rt          | |||¬¦  «        }	nt          j        | |f|||dœ|¤Ž}	|r|	                     d¦  «        }	|	S )aý  A wrapper around :func:`~rfdetr.utilities.tensors._bilinear_grid_sample` to support 3D point_coords tensors.
    Unlike :func:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside [0, 1] x [0, 1] square.

    Args:
        input: A tensor of shape (N, C, H, W) that contains features map on a H x W grid.
        point_coords: A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains
            [0, 1] x [0, 1] normalized point coordinates.

    Returns:
        A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains
            features for points in `point_coords`. The features are obtained via bilinear
            interpolation from `input` the same way as :func:`~rfdetr.utilities.tensors._bilinear_grid_sample`.
    Fr0   Tr.   g       @g      ð?rž   r›   rŸ   Úpadding_modeÚborderz, z2Unexpected keyword argument(s) for bilinear mode: )rˆ   r´   )rž   r³   rŸ   )r³   rŸ   Únearest)r2   Ú	unsqueezeÚpopÚjoinÚsortedÚkeysÚ	TypeErrorr&   Úgrid_sampler   r   Úsqueeze)
rg   r°   r±   Úadd_dimÚgridrž   rŸ   r³   Ú
unexpectedÚoutputs
             r(   Úpoint_samplerÂ   S  sº  € ð €GØ×ÒÑÔ˜QÒÐØˆØ#×-Ò-¨aÑ0Ô0ˆð �Ñ Ñ#€Dð �:Š:�f˜jÑ)Ô)€DØ—J’J˜°Ñ6Ô6€MØ—:’:˜n¨hÑ7Ô7€LàˆzÒÐØð 	_ØŸš¥6¨&¯+ª+©-¬-Ñ#8Ô#8Ñ9Ô9ˆJÝÐ]ÐQ[Ð]Ð]Ñ^Ô^Ð^ð Ð2Ð2Ð2Ý”]ØØØØ)Ø+ðñ ô ˆFˆFõ +ØØØ)Ø+ð	ñ ô ˆFˆFð 
�Ò	Ð	 6Ð	¨lÐ>QÐ.QÐ.Qõ
 & e¨TÀÐ\iÐjÑjÔjˆˆõ ”ØØð
ð Ø%Ø'ð
ð 
ð ð
ð 
ˆð ð #Ø—’ Ñ"Ô"ˆØ€MrF   r0   ç      è?Úcoarse_logitsÚuncertainty_funcúCallable[[Tensor], Tensor]Ú
num_pointsr   Úoversample_ratioÚimportance_sample_ratiorJ   c           	     óØ  — |dk    sJ ‚|dk    r|dk    sJ ‚| j         d         }t          ||z  ¦  «        }t          j        ||d| j        ¬¦  «        }t          | |d¬¦  «        } ||¦  «        }	t          ||z  ¦  «        }
||
z
  }t          j        |	dd…ddd…f         |
d¬¦  «        d         }|t          j        |t          j        | j        ¬	¦  «        z  }||dd…df         z  }| 	                    d
d¦  «        | 	                    d
¦  «        dd…f          	                    ||
d¦  «        }|dk    r3t          j
        |t          j        ||d| j        ¬¦  «        gd¬¦  «        }|S )a’  Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty.

    The uncertainties are calculated for each point using 'uncertainty_func' function that takes point's logit
    prediction as input. See PointRend paper for details.

    Args:
        coarse_logits: A tensor of shape (N, C, Hmask, Wmask) or (N, 1, Hmask, Wmask) for
            class-specific or class-agnostic prediction.
        uncertainty_func: A function that takes a Tensor of shape (N, C, P) or (N, 1, P) that
            contains logit predictions for P points and returns their uncertainties as a Tensor of shape (N, 1, P).
        num_points: The number of points P to sample.
        oversample_ratio: Oversampling parameter.
        importance_sample_ratio: Ratio of points that are sampled via importance sampling.

    Returns:
        A tensor of shape (N, P, 2) that contains the coordinates of sampled points.
    r-   r   r.   )ÚdeviceF)rŸ   N)Úkr2   )r/   rË   éÿÿÿÿr1   )r6   r   r"   ÚrandrË   rÂ   ÚtopkÚarangeÚlongÚviewÚcat)rÄ   rÅ   rÇ   rÈ   rÉ   Ú	num_boxesÚnum_sampledr°   Úpoint_logitsÚpoint_uncertaintiesÚnum_uncertain_pointsÚnum_random_pointsÚidxÚshifts                 r(   Ú*get_uncertain_point_coords_with_randomnessrÜ   œ  sª  € ð0 ˜qÒ Ð Ð Ð Ø" aÒ'Ð'Ð,CÀqÒ,HÐ,HÐ,HÐHØÔ# AÔ&€IÝ�jÐ#3Ñ3Ñ4Ô4€KÝ”:˜i¨°aÀÔ@TÐUÑUÔU€LÝ ¨|È5ÐQÑQÔQ€Lð +Ð*¨<Ñ8Ô8ÐÝÐ6¸ÑCÑDÔDÐØ"Ð%9Ñ9ÐÝ
Œ*Ð(¨¨¨¨A¨q¨q¨q¨Ô1Ð5IÈqÐ
QÑ
QÔ
QÐRSÔ
T€CØ�%œ, y½¼
È=ÔK_Ð`Ñ`Ô`Ñ`€EØˆ5����D�Œ>Ñ€CØ×$Ò$ R¨Ñ+Ô+¨C¯HªH°R©L¬L¸!¸!¸!¨OÔ<×AÒAÀ)ÐMaÐcdÑeÔe€LØ˜1ÒÐÝ”yàÝ”
˜9Ð&7¸À=ÔCWÐXÑXÔXðð ð
ñ 
ô 
ˆð ÐrF   Úlogitsc                óz   — | j         d         dk    sJ ‚|                      ¦   «         }t          j        |¦  «         S )a"  We estimate uncertainty as L1 distance between 0.0 and the logit prediction in 'logits' for the foreground class
    in `classes`.

    Args:
        logits: A tensor of shape (R, 1, ...) for class-specific or
            class-agnostic, where R is the total number of predicted masks in all images and C is the number of
            foreground classes. The values are logits.

    Returns:
        A tensor of shape (R, 1, ...) that contains uncertainty scores with the most uncertain locations having the
        highest uncertainty score.
    r-   )r6   Úcloner"   Úabs)rÝ   Úgt_class_logitss     r(   Úcalculate_uncertaintyrâ   Ó  s;   € ð Œ<˜Œ?˜aÒÐÐÐØ—l’l‘n”n€OÝŒY�Ñ'Ô'Ð(Ð(rF   )rg   r   r°   r   r±   r   r   r   )r0   rÃ   )rÄ   r   rÅ   rÆ   rÇ   r   rÈ   r   rÉ   rJ   r   r   )rÝ   r   r   r   )Ú
__future__r   Úcollections.abcr   Útypingr   r   r"   Útorch.nn.functionalr   Ú
functionalr&   r   Útorch.nn.gradr	   r
   Úrfdetr.utilities.tensorsr   r   ÚautogradÚFunctionr   ÚModulerH   rn   rw   rÂ   rÜ   râ   rE   rF   r(   ú<module>rí      sÞ  ðð #Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð Ð Ð à €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ø 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5à PÐ PÐ PÐ PÐ PÐ PÐ PÐ PðxJð xJð xJð xJð xJ ¤Ô!8ñ xJô xJð xJðv*ð *ð *ð *ð *˜œñ *ô *ð *ðZð ð ð ð ˆrŒyñ ô ð ð6yWð yWð yWð yWð yW�r”yñ yWô yWð yWðxFð Fð Fð FðZ Ø%)ð4ð 4ð 4ð 4ð 4ðn)ð )ð )ð )ð )ð )rF   