§
    ezniçE  ã                   óÞ  — d Z ddlZddlZddlmZ ddlmc mZ ddlm	Z	m
Z
 ddlmZ ddlmZmZmZ dZ G d„ d	ej        ¦  «        Z G d
„ de¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        Z G d„ dej        ¦  «        ZdS )zTransformer modules.é    N)Ú	constant_Úxavier_uniform_é   )ÚConv)Ú_get_clonesÚinverse_sigmoidÚ#multi_scale_deformable_attn_pytorch)
ÚTransformerEncoderLayerÚTransformerLayerÚTransformerBlockÚMLPBlockÚLayerNorm2dÚAIFIÚDeformableTransformerDecoderÚ!DeformableTransformerDecoderLayerÚMSDeformAttnÚMLPc                   óx   ‡ — e Zd ZdZddd ej        ¦   «         dfˆ fd„	Zedd„¦   «         Zdd	„Z	dd
„Z
dd„Zˆ xZS )r
   z2Defines a single layer of the transformer encoder.é   é   ç        Fc                 ó.  •— t          ¦   «                              ¦   «          ddlm} |st	          d¦  «        ‚t          j        |||d¬¦  «        | _        t          j        ||¦  «        | _	        t          j        ||¦  «        | _
        t          j        |¦  «        | _        t          j        |¦  «        | _        t          j        |¦  «        | _        t          j        |¦  «        | _        t          j        |¦  «        | _        || _        || _        dS )zAInitialize the TransformerEncoderLayer with specified parameters.é   )Ú	TORCH_1_9z]TransformerEncoderLayer() requires torch>=1.9 to use nn.MultiheadAttention(batch_first=True).T)ÚdropoutÚbatch_firstN)ÚsuperÚ__init__Úutils.torch_utilsr   ÚModuleNotFoundErrorÚnnÚMultiheadAttentionÚmaÚLinearÚfc1Úfc2Ú	LayerNormÚnorm1Únorm2ÚDropoutr   Údropout1Údropout2ÚactÚnormalize_before)	ÚselfÚc1ÚcmÚ	num_headsr   r-   r.   r   Ú	__class__s	           €ú‚/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/ultralytics/nn/modules/transformer.pyr   z TransformerEncoderLayer.__init__   sø   ø€ å‰Œ×ÒÑÔÐØ2Ð2Ð2Ð2Ð2Ð2Øð 	qÝ%Øoñqô qð qåÔ'¨¨I¸wÐTXÐYÑYÔYˆŒå”9˜R Ñ$Ô$ˆŒÝ”9˜R Ñ$Ô$ˆŒå”\ "Ñ%Ô%ˆŒ
Ý”\ "Ñ%Ô%ˆŒ
Ý”z 'Ñ*Ô*ˆŒÝœ
 7Ñ+Ô+ˆŒÝœ
 7Ñ+Ô+ˆŒàˆŒØ 0ˆÔÐÐó    Nc                 ó   — |€| n| |z   S )z2Add position embeddings to the tensor if provided.© ©ÚtensorÚposs     r4   Úwith_pos_embedz&TransformerEncoderLayer.with_pos_embed*   ó   € ð ˜ˆvˆv¨&°3©,Ð6r5   c           	      óÂ  — |                       ||¦  «        x}}|                      |||||¬¦  «        d         }||                      |¦  «        z   }|                      |¦  «        }|                      |                      |                      |                      |¦  «        ¦  «        ¦  «        ¦  «        }||                      |¦  «        z   }|  	                    |¦  «        S )z.Performs forward pass with post-normalization.©ÚvalueÚ	attn_maskÚkey_padding_maskr   )
r;   r#   r+   r(   r&   r   r-   r%   r,   r)   )r/   ÚsrcÚsrc_maskÚsrc_key_padding_maskr:   ÚqÚkÚsrc2s           r4   Úforward_postz$TransformerEncoderLayer.forward_post/   s¼   € à×#Ò# C¨Ñ-Ô-Ð-ˆˆAØ�wŠw�q˜! 3°(ÐMaˆwÑbÔbÐcdÔeˆØ�D—M’M $Ñ'Ô'Ñ'ˆØ�jŠj˜‰oŒoˆØ�xŠx˜Ÿš T§X¢X¨d¯hªh°s©m¬mÑ%<Ô%<Ñ=Ô=Ñ>Ô>ˆØ�D—M’M $Ñ'Ô'Ñ'ˆØ�zŠz˜#‰ŒÐr5   c           	      óÂ  — |                       |¦  «        }|                      ||¦  «        x}}|                      |||||¬¦  «        d         }||                      |¦  «        z   }|                      |¦  «        }|                      |                      |                      |                      |¦  «        ¦  «        ¦  «        ¦  «        }||  	                    |¦  «        z   S )z-Performs forward pass with pre-normalization.r>   r   )
r(   r;   r#   r+   r)   r&   r   r-   r%   r,   )r/   rB   rC   rD   r:   rG   rE   rF   s           r4   Úforward_prez#TransformerEncoderLayer.forward_pre9   s¼   € à�zŠz˜#‰ŒˆØ×#Ò# D¨#Ñ.Ô.Ð.ˆˆAØ�wŠw�q˜! 4°8ÐNbˆwÑcÔcÐdeÔfˆØ�D—M’M $Ñ'Ô'Ñ'ˆØ�zŠz˜#‰ŒˆØ�xŠx˜Ÿš T§X¢X¨d¯hªh°t©n¬nÑ%=Ô%=Ñ>Ô>Ñ?Ô?ˆØ�T—]’] 4Ñ(Ô(Ñ(Ð(r5   c                 óp   — | j         r|                      ||||¦  «        S |                      ||||¦  «        S )z8Forward propagates the input through the encoder module.)r.   rJ   rH   )r/   rB   rC   rD   r:   s        r4   ÚforwardzTransformerEncoderLayer.forwardC   sD   € àÔ ð 	NØ×#Ò# C¨Ð3GÈÑMÔMÐMØ× Ò   hÐ0DÀcÑJÔJÐJr5   ©N©NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   ÚGELUr   Ústaticmethodr;   rH   rJ   rL   Ú__classcell__©r3   s   @r4   r
   r
      s»   ø€ € € € € Ø<Ð<à"¨a¸À'À"Ä'Á)Ä)Ð^cð 1ð 1ð 1ð 1ð 1ð 1ð* ð7ð 7ð 7ñ „\ð7ðð ð ð ð)ð )ð )ð )ðKð Kð Kð Kð Kð Kð Kð Kr5   r
   c                   ój   ‡ — e Zd ZdZddd ej        ¦   «         dfˆ fd„	Zˆ fd„Zedd
„¦   «         Z	ˆ xZ
S )r   z#Defines the AIFI transformer layer.r   r   r   Fc                 óT   •— t          ¦   «                              ||||||¦  «         dS )z7Initialize the AIFI instance with specified parameters.N)r   r   )r/   r0   r1   r2   r   r-   r.   r3   s          €r4   r   zAIFI.__init__M   s,   ø€ å‰Œ×Ò˜˜R ¨G°SÐ:JÑKÔKÐKÐKÐKr5   c                 ó¬  •— |j         dd…         \  }}}|                      |||¦  «        }t          ¦   «                              |                     d¦  «                             ddd¦  «        |                     |j        |j        ¬¦  «        ¬¦  «        }|                     ddd¦  «         	                    d|||g¦  «         
                    ¦   «         S )z,Forward pass for the AIFI transformer layer.r   Né   r   )ÚdeviceÚdtype)r:   éÿÿÿÿ)ÚshapeÚ"build_2d_sincos_position_embeddingr   rL   ÚflattenÚpermuteÚtor[   r\   ÚviewÚ
contiguous)r/   ÚxÚcÚhÚwÚ	pos_embedr3   s         €r4   rL   zAIFI.forwardQ   s´   ø€ à”'˜!˜"˜"”+‰ˆˆ1ˆaØ×;Ò;¸A¸qÀ!ÑDÔDˆ	å‰GŒG�OŠO˜AŸIšI a™LœL×0Ò0°°A°qÑ9Ô9¸y¿|º|ÐSTÔS[ÐcdÔcj¸|Ñ?kÔ?kˆOÑlÔlˆØ�yŠy˜˜A˜qÑ!Ô!×&Ò&¨¨A¨q°! }Ñ5Ô5×@Ò@ÑBÔBÐBr5   é   ç     ˆÃ@c                 óÊ  — t          j        t          | ¦  «        t           j        ¬¦  «        }t          j        t          |¦  «        t           j        ¬¦  «        }t          j        ||d¬¦  «        \  }}|dz  dk    s
J d¦   «         ‚|dz  }t          j        |t           j        ¬¦  «        |z  }d||z  z  }|                     ¦   «         d         |d	         z  }|                     ¦   «         d         |d	         z  }	t          j        t          j        |¦  «        t          j        |¦  «        t          j        |	¦  «        t          j        |	¦  «        gd
¦  «        d	         S )z)Builds 2D sine-cosine position embedding.©r\   Úij)Úindexingé   r   zHEmbed dimension must be divisible by 4 for 2D sin-cos position embeddingg      ð?©.NNr   )	ÚtorchÚarangeÚintÚfloat32Úmeshgridr`   ÚcatÚsinÚcos)
rh   rg   Ú	embed_dimÚtemperatureÚgrid_wÚgrid_hÚpos_dimÚomegaÚout_wÚout_hs
             r4   r_   z'AIFI.build_2d_sincos_position_embeddingY   s0  € õ ”�c !™fœf­E¬MÐ:Ñ:Ô:ˆÝ”�c !™fœf­E¬MÐ:Ñ:Ô:ˆÝœ¨°ÀÐFÑFÔF‰ˆ�Ø˜1‰} Ò!Ð!Ð!ØVñ "Ô!Ð!à˜q‘.ˆÝ”˜W­E¬MÐ:Ñ:Ô:¸WÑDˆØ�k UÑ*Ñ+ˆà—’Ñ Ô  Ô+¨e°D¬kÑ9ˆØ—’Ñ Ô  Ô+¨e°D¬kÑ9ˆåŒy�%œ) EÑ*Ô*­E¬I°eÑ,<Ô,<½e¼iÈÑ>NÔ>NÕPUÔPYÐZ_ÑP`ÔP`ÐaÐcdÑeÔeÐfjÔkÐkr5   )rj   rk   )rO   rP   rQ   rR   r!   rS   r   rL   rT   r_   rU   rV   s   @r4   r   r   J   s£   ø€ € € € € Ø-Ð-à"¨a¸ÀÀÄÁ	Ä	Ð\að Lð Lð Lð Lð Lð LðCð Cð Cð Cð Cð ðlð lð lñ „\ðlð lð lð lð lr5   r   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )r   zeTransformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance).c                 ó–  •— t          ¦   «                              ¦   «          t          j        ||d¬¦  «        | _        t          j        ||d¬¦  «        | _        t          j        ||d¬¦  «        | _        t          j        ||¬¦  «        | _        t          j        ||d¬¦  «        | _	        t          j        ||d¬¦  «        | _
        dS )z]Initializes a self-attention mechanism using linear transformations and multi-head attention.F)Úbias)rz   r2   N)r   r   r!   r$   rE   rF   Úvr"   r#   r%   r&   )r/   rf   r2   r3   s      €r4   r   zTransformerLayer.__init__n   s¬   ø€ å‰Œ×ÒÑÔÐÝ”˜1˜a eÐ,Ñ,Ô,ˆŒÝ”˜1˜a eÐ,Ñ,Ô,ˆŒÝ”˜1˜a eÐ,Ñ,Ô,ˆŒÝÔ'°!¸yÐIÑIÔIˆŒÝ”9˜Q ¨Ð.Ñ.Ô.ˆŒÝ”9˜Q ¨Ð.Ñ.Ô.ˆŒˆˆr5   c                 ó
  — |                       |                      |¦  «        |                      |¦  «        |                      |¦  «        ¦  «        d         |z   }|                      |                      |¦  «        ¦  «        |z   S )z?Apply a transformer block to the input x and return the output.r   )r#   rE   rF   r…   r&   r%   ©r/   re   s     r4   rL   zTransformerLayer.forwardx   s`   € à�GŠG�D—F’F˜1‘I”I˜tŸvšv a™yœy¨$¯&ª&°©)¬)Ñ4Ô4°QÔ7¸!Ñ;ˆØ�xŠx˜Ÿš ™œÑ$Ô$ qÑ(Ð(r5   ©rO   rP   rQ   rR   r   rL   rU   rV   s   @r4   r   r   k   sM   ø€ € € € € ØoÐoð/ð /ð /ð /ð /ð)ð )ð )ð )ð )ð )ð )r5   r   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )r   z4Vision Transformer https://arxiv.org/abs/2010.11929.c                 ó,  •‡‡— t          ¦   «                              ¦   «          d| _        |‰k    rt          |‰¦  «        | _        t	          j        ‰‰¦  «        | _        t	          j        ˆˆfd„t          |¦  «        D ¦   «         Ž | _	        ‰| _
        dS )zaInitialize a Transformer module with position embedding and specified number of heads and layers.Nc              3   ó8   •K  — | ]}t          ‰‰¦  «        V — Œd S rM   )r   )Ú.0Ú_Úc2r2   s     €€r4   ú	<genexpr>z,TransformerBlock.__init__.<locals>.<genexpr>ˆ   s.   øè è € Ð!]Ð!]ÀaÕ"2°2°yÑ"AÔ"AÐ!]Ð!]Ð!]Ð!]Ð!]Ð!]r5   )r   r   Úconvr   r!   r$   ÚlinearÚ
SequentialÚrangeÚtrrŽ   )r/   r0   rŽ   r2   Ú
num_layersr3   s     `` €r4   r   zTransformerBlock.__init__�   s‡   øøø€ å‰Œ×ÒÑÔÐØˆŒ	Ø�Š8ˆ8Ý˜R ™œˆDŒIÝ”i  BÑ'Ô'ˆŒÝ”-Ð!]Ð!]Ð!]Ð!]Ð!]Í5ÐQ[ÑK\ÔK\Ð!]Ñ!]Ô!]Ð^ˆŒØˆŒˆˆr5   c                 ó\  — | j         �|                       |¦  «        }|j        \  }}}}|                     d¦  «                             ddd¦  «        }|                      ||                      |¦  «        z   ¦  «                             ddd¦  «                             || j        ||¦  «        S )z;Forward propagates the input through the bottleneck module.NrZ   r   r   )r�   r^   r`   ra   r”   r‘   ÚreshaperŽ   )r/   re   Úbr�   rh   rg   Úps          r4   rL   zTransformerBlock.forward‹   s”   € àŒ9Ð Ø—	’	˜!‘”ˆAØ”W‰
ˆˆ1ˆa�Ø�IŠI�a‰LŒL× Ò   A qÑ)Ô)ˆØ�wŠw�q˜4Ÿ;š; q™>œ>Ñ)Ñ*Ô*×2Ò2°1°a¸Ñ;Ô;×CÒCÀAÀtÄwÐPQÐSTÑUÔUÐUr5   rˆ   rV   s   @r4   r   r   ~   sT   ø€ € € € € Ø>Ð>ðð ð ð ð ðVð Vð Vð Vð Vð Vð Vr5   r   c                   óT   ‡ — e Zd ZdZej        fˆ fd„	Zdej        dej        fd„Z	ˆ xZ
S )r   z6Implements a single block of a multi-layer perceptron.c                 óÎ   •— t          ¦   «                              ¦   «          t          j        ||¦  «        | _        t          j        ||¦  «        | _         |¦   «         | _        dS )zcInitialize the MLPBlock with specified embedding dimension, MLP dimension, and activation function.N)r   r   r!   r$   Úlin1Úlin2r-   )r/   Úembedding_dimÚmlp_dimr-   r3   s       €r4   r   zMLPBlock.__init__—   sP   ø€ å‰Œ×ÒÑÔÐÝ”I˜m¨WÑ5Ô5ˆŒ	Ý”I˜g }Ñ5Ô5ˆŒ	Ø�3‘5”5ˆŒˆˆr5   re   Úreturnc                 óx   — |                       |                      |                      |¦  «        ¦  «        ¦  «        S )zForward pass for the MLPBlock.)r�   r-   rœ   r‡   s     r4   rL   zMLPBlock.forwardž   s*   € à�yŠy˜Ÿš $§)¢)¨A¡,¤,Ñ/Ô/Ñ0Ô0Ð0r5   )rO   rP   rQ   rR   r!   rS   r   rr   ÚTensorrL   rU   rV   s   @r4   r   r   ”   sn   ø€ € € € € Ø@Ð@à35´7ð ð ð ð ð ð ð1˜œð 1¨%¬,ð 1ð 1ð 1ð 1ð 1ð 1ð 1ð 1r5   r   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )r   z=Implements a simple multi-layer perceptron (also called FFN).c                 óÚ   •— t          ¦   «                              ¦   «          || _        |g|dz
  z  }t          j        d„ t          |g|z   ||gz   ¦  «        D ¦   «         ¦  «        | _        dS )zXInitialize the MLP with specified input, hidden, output dimensions and number of layers.r   c              3   óF   K  — | ]\  }}t          j        ||¦  «        V — Œd S rM   )r!   r$   )rŒ   ÚnrF   s      r4   r�   zMLP.__init__.<locals>.<genexpr>«   s0   è è € Ð#gÐ#g¹¸¸1¥B¤I¨a°¡O¤OÐ#gÐ#gÐ#gÐ#gÐ#gÐ#gr5   N)r   r   r•   r!   Ú
ModuleListÚzipÚlayers)r/   Ú	input_dimÚ
hidden_dimÚ
output_dimr•   rg   r3   s         €r4   r   zMLP.__init__¦   so   ø€ å‰Œ×ÒÑÔÐØ$ˆŒØˆL˜J¨™NÑ+ˆÝ”mÐ#gÐ#gÅÀYÀKÐRSÁOÐUVÐZdÐYeÑUeÑ@fÔ@fÐ#gÑ#gÔ#gÑgÔgˆŒˆˆr5   c                 ó¦   — t          | j        ¦  «        D ];\  }}|| j        dz
  k     rt          j         ||¦  «        ¦  «        n
 ||¦  «        }Œ<|S )z Forward pass for the entire MLP.r   )Ú	enumerater©   r•   ÚFÚrelu)r/   re   ÚiÚlayers       r4   rL   zMLP.forward­   s]   € å! $¤+Ñ.Ô.ð 	Jð 	J‰HˆAˆuØ$%¨¬¸!Ñ(;Ò$;Ð$;•”�u�u˜Q‘x”xÑ Ô Ð ÀÀÀqÁÄˆAˆAØˆr5   rˆ   rV   s   @r4   r   r   £   sR   ø€ € € € € ØGÐGðhð hð hð hð hðð ð ð ð ð ð r5   r   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )r   a1  
    2D Layer Normalization module inspired by Detectron2 and ConvNeXt implementations.

    Original implementations in
    https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py
    and
    https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py.
    ç�íµ ÷Æ°>c                 ó  •— t          ¦   «                              ¦   «          t          j        t	          j        |¦  «        ¦  «        | _        t          j        t	          j        |¦  «        ¦  «        | _        || _	        dS )z1Initialize LayerNorm2d with the given parameters.N)
r   r   r!   Ú	Parameterrr   ÚonesÚweightÚzerosr„   Úeps)r/   Únum_channelsrº   r3   s      €r4   r   zLayerNorm2d.__init__¾   sZ   ø€ å‰Œ×ÒÑÔÐÝ”l¥5¤:¨lÑ#;Ô#;Ñ<Ô<ˆŒÝ”L¥¤¨\Ñ!:Ô!:Ñ;Ô;ˆŒ	ØˆŒˆˆr5   c                 ó  — |                      dd¬¦  «        }||z
                       d¦  «                              dd¬¦  «        }||z
  t          j        || j        z   ¦  «        z  }| j        dd…ddf         |z  | j        dd…ddf         z   S )z0Perform forward pass for 2D layer normalization.r   T©ÚkeepdimrZ   N)ÚmeanÚpowrr   Úsqrtrº   r¸   r„   )r/   re   ÚuÚss       r4   rL   zLayerNorm2d.forwardÅ   s�   € à�FŠF�1˜dˆFÑ#Ô#ˆØ�‰U�KŠK˜‰NŒN×Ò ¨4ÐÑ0Ô0ˆØ�‰U•e”j  T¤X¡Ñ.Ô.Ñ.ˆØŒ{˜1˜1˜1˜d D˜=Ô)¨AÑ-°´	¸!¸!¸!¸TÀ4¸-Ô0HÑHÐHr5   )r´   rˆ   rV   s   @r4   r   r   ´   s]   ø€ € € € € ðð ðð ð ð ð ð ðIð Ið Ið Ið Ið Ið Ir5   r   c                   ó2   ‡ — e Zd ZdZd	ˆ fd„	Zd„ Zd
d„Zˆ xZS )r   zØ
    Multi-Scale Deformable Attention Module based on Deformable-DETR and PaddleDetection implementations.

    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
    rj   rp   r   c                 ó  •— t          ¦   «                              ¦   «          ||z  dk    rt          d|› d|› �¦  «        ‚||z  }||z  |k    s
J d¦   «         ‚d| _        || _        || _        || _        || _        t          j	        |||z  |z  dz  ¦  «        | _
        t          j	        |||z  |z  ¦  «        | _        t          j	        ||¦  «        | _        t          j	        ||¦  «        | _        |                      ¦   «          dS )z2Initialize MSDeformAttn with the given parameters.r   z.d_model must be divisible by n_heads, but got z and z(`d_model` must be divisible by `n_heads`é@   rZ   N)r   r   Ú
ValueErrorÚim2col_stepÚd_modelÚn_levelsÚn_headsÚn_pointsr!   r$   Úsampling_offsetsÚattention_weightsÚ
value_projÚoutput_projÚ_reset_parameters)r/   rÉ   rÊ   rË   rÌ   Ú_d_per_headr3   s         €r4   r   zMSDeformAttn.__init__Ô   s  ø€ å‰Œ×ÒÑÔÐØ�WÑ Ò!Ð!ÝÐeÈgÐeÐeÐ\cÐeÐeÑfÔfÐfØ Ñ(ˆà˜WÑ$¨Ò/Ð/Ð/Ð1[Ñ/Ô/Ð/àˆÔàˆŒØ ˆŒØˆŒØ ˆŒå "¤	¨'°7¸XÑ3EÈÑ3PÐSTÑ3TÑ UÔ UˆÔÝ!#¤¨7°G¸hÑ4FÈÑ4QÑ!RÔ!RˆÔÝœ) G¨WÑ5Ô5ˆŒÝœ9 W¨gÑ6Ô6ˆÔà×ÒÑ Ô Ð Ð Ð r5   c                 óž  — t          | j        j        j        d¦  «         t	          j        | j        t          j        ¬¦  «        dt          j	        z  | j        z  z  }t	          j
        |                     ¦   «         |                     ¦   «         gd¦  «        }||                     ¦   «                              dd¬¦  «        d         z                       | j        ddd	¦  «                             d| j        | j        d¦  «        }t'          | j        ¦  «        D ]}|d
d
…d
d
…|d
d
…fxx         |dz   z  cc<   Œ t	          j        ¦   «         5  t+          j        |                     d¦  «        ¦  «        | j        _        d
d
d
¦  «         n# 1 swxY w Y   t          | j        j        j        d¦  «         t          | j        j        j        d¦  «         t3          | j        j        j        ¦  «         t          | j        j        j        d¦  «         t3          | j        j        j        ¦  «         t          | j        j        j        d¦  «         d
S )zReset module parameters.r   rm   g       @r]   Tr½   r   r   rZ   N)r   rÍ   r¸   Údatarr   rs   rË   ru   ÚmathÚpiÚstackry   rx   ÚabsÚmaxrc   ÚrepeatrÊ   rÌ   r“   Úno_gradr!   r¶   r„   rÎ   r   rÏ   rÐ   )r/   ÚthetasÚ	grid_initr±   s       r4   rÑ   zMSDeformAttn._reset_parametersë   sH  € å�$Ô'Ô.Ô3°RÑ8Ô8Ð8Ý”˜dœlµ%´-Ð@Ñ@Ô@ÀCÍ$Ì'ÁMÐTXÔT`ÑD`ÑaˆÝ”K §¢¡¤¨v¯zªz©|¬|Ð <¸bÑAÔAˆ	Ø §¢¡¤×!4Ò!4°RÀÐ!4Ñ!FÔ!FÀqÔ!IÑI×OÒOÐPTÔP\Ð^_ÐabÐdeÑfÔf×mÒmØˆtŒ}˜dœm¨Qñ0ô 0ˆ	å�t”}Ñ%Ô%ð 	+ð 	+ˆAØ�a�a�a˜˜˜˜A˜q˜q˜q�jÐ!Ð!Ô! Q¨¡UÑ*Ð!Ð!Ñ!Ð!ÝŒ]‰_Œ_ð 	Jð 	JÝ)+¬°i·n²nÀRÑ6HÔ6HÑ)IÔ)IˆDÔ!Ô&ð	Jð 	Jð 	Jñ 	Jô 	Jð 	Jð 	Jð 	Jð 	Jð 	Jð 	Jøøøð 	Jð 	Jð 	Jð 	Jå�$Ô(Ô/Ô4°bÑ9Ô9Ð9Ý�$Ô(Ô-Ô2°BÑ7Ô7Ð7Ý˜œÔ.Ô3Ñ4Ô4Ð4Ý�$”/Ô&Ô+¨RÑ0Ô0Ð0Ý˜Ô(Ô/Ô4Ñ5Ô5Ð5Ý�$Ô"Ô'Ô,¨bÑ1Ô1Ð1Ð1Ð1s   Å2F
Æ
FÆFNc           	      ó¢  — |j         dd…         \  }}|j         d         }t          d„ |D ¦   «         ¦  «        |k    sJ ‚|                      |¦  «        }|�)|                     |d         t	          d¦  «        ¦  «        }|                     ||| j        | j        | j        z  ¦  «        }|                      |¦  «                             ||| j        | j	        | j
        d¦  «        }	|                      |¦  «                             ||| j        | j	        | j
        z  ¦  «        }
t          j        |
d¦  «                             ||| j        | j	        | j
        ¦  «        }
|j         d         }|dk    rct          j        ||j        |j        ¬¦  «                             d¦  «        }|	|ddddd…ddd…f         z  }|dd…dd…ddd…ddd…f         |z   }nW|d	k    r>|	| j
        z  |dd…dd…ddd…ddd…f         z  d
z  }|dd…dd…ddd…ddd…f         |z   }nt'          d|› d�¦  «        ‚t)          ||||
¦  «        }|                      |¦  «        S )a  
        Perform forward pass for multiscale deformable attention.

        https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py

        Args:
            query (torch.Tensor): [bs, query_length, C]
            refer_bbox (torch.Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
                bottom-right (1, 1), including padding area
            value (torch.Tensor): [bs, value_length, C]
            value_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
            value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements

        Returns:
            output (Tensor): [bs, Length_{query}, C]
        NrZ   r   c              3   ó8   K  — | ]}|d          |d         z  V — ŒdS )r   r   Nr7   )rŒ   rÃ   s     r4   r�   z'MSDeformAttn.forward.<locals>.<genexpr>  s.   è è € Ð5Ð5 1�1�Q”4˜!˜Aœ$‘;Ð5Ð5Ð5Ð5Ð5Ð5r5   rq   r   r]   )r\   r[   rp   g      à?z5Last dim of reference_points must be 2 or 4, but got ú.)r^   ÚsumrÏ   Úmasked_fillÚfloatrc   rË   rÉ   rÍ   rÊ   rÌ   rÎ   r¯   Úsoftmaxrr   Ú	as_tensorr\   r[   ÚfliprÇ   r	   rÐ   )r/   ÚqueryÚ
refer_bboxr?   Úvalue_shapesÚ
value_maskÚbsÚlen_qÚlen_vrÍ   rÎ   Ú
num_pointsÚoffset_normalizerÚaddÚsampling_locationsÚoutputs                   r4   rL   zMSDeformAttn.forwardý   s—  € ð" ”K   ”O‰	ˆˆEØ”˜A”ˆÝÐ5Ð5¨Ð5Ñ5Ô5Ñ5Ô5¸Ò>Ð>Ð>Ð>à—’ Ñ&Ô&ˆØÐ!Ø×%Ò% j°Ô&;½UÀ1¹X¼XÑFÔFˆEØ—
’
˜2˜u d¤l°D´LÀDÄLÑ4PÑQÔQˆØ×0Ò0°Ñ7Ô7×<Ò<¸RÀÈÌÐVZÔVcÐeiÔerÐtuÑvÔvÐØ ×2Ò2°5Ñ9Ô9×>Ò>¸rÀ5È$Ì,ÐX\ÔXeÐhlÔhuÑXuÑvÔvÐÝœIÐ&7¸Ñ<Ô<×AÒAÀ"ÀeÈTÌ\Ð[_Ô[hÐjnÔjwÑxÔxÐàÔ% bÔ)ˆ
Ø˜Š?ˆ?Ý %¤°ÀEÄKÐX]ÔXdÐ eÑ eÔ e× jÒ jÐkmÑ nÔ nÐØ"Ð%6°t¸TÀ4ÈÈÈÈDÐRSÐRSÐRSÐ7SÔ%TÑTˆCØ!+¨A¨A¨A¨q¨q¨q°$¸¸¸¸4ÀÀÀÐ,BÔ!CÀcÑ!IÐÐØ˜1Š_ˆ_Ø" T¤]Ñ2°ZÀÀÀÀ1À1À1ÀdÈAÈAÈAÈtÐUVÐUWÐUWÐ@WÔ5XÑXÐ[^Ñ^ˆCØ!+¨A¨A¨A¨q¨q¨q°$¸¸¸¸4ÀÀ!ÀÐ,CÔ!DÀsÑ!JÐÐåÐbÐU_ÐbÐbÐbÑcÔcÐcÝ4°U¸LÐJ\Ð^oÑpÔpˆØ×Ò Ñ'Ô'Ð'r5   )rj   rp   r   rp   rM   )rO   rP   rQ   rR   r   rÑ   rL   rU   rV   s   @r4   r   r   Í   sj   ø€ € € € € ðð ð!ð !ð !ð !ð !ð !ð.2ð 2ð 2ð$((ð ((ð ((ð ((ð ((ð ((ð ((ð ((r5   r   c                   óp   ‡ — e Zd ZdZdddd ej        ¦   «         ddfˆ fd„	Zed„ ¦   «         Zd	„ Z	dd„Z
ˆ xZS )r   aK  
    Deformable Transformer Decoder Layer inspired by PaddleDetection and Deformable-DETR implementations.

    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py
    rj   r   i   r   rp   c                 ó‚  •— t          ¦   «                              ¦   «          t          j        |||¬¦  «        | _        t          j        |¦  «        | _        t          j        |¦  «        | _        t          ||||¦  «        | _
        t          j        |¦  «        | _        t          j        |¦  «        | _        t          j        ||¦  «        | _        || _        t          j        |¦  «        | _        t          j        ||¦  «        | _        t          j        |¦  «        | _        t          j        |¦  «        | _        dS )zKInitialize the DeformableTransformerDecoderLayer with the given parameters.)r   N)r   r   r!   r"   Ú	self_attnr*   r+   r'   r(   r   Ú
cross_attnr,   r)   r$   Úlinear1r-   Údropout3Úlinear2Údropout4Únorm3)	r/   rÉ   rË   Úd_ffnr   r-   rÊ   rÌ   r3   s	           €r4   r   z*DeformableTransformerDecoderLayer.__init__0  sõ   ø€ å‰Œ×ÒÑÔÐõ Ô.¨w¸ÈÐQÑQÔQˆŒÝœ
 7Ñ+Ô+ˆŒÝ”\ 'Ñ*Ô*ˆŒ
õ ' w°¸'À8ÑLÔLˆŒÝœ
 7Ñ+Ô+ˆŒÝ”\ 'Ñ*Ô*ˆŒ
õ ”y ¨%Ñ0Ô0ˆŒØˆŒÝœ
 7Ñ+Ô+ˆŒÝ”y ¨Ñ0Ô0ˆŒÝœ
 7Ñ+Ô+ˆŒÝ”\ 'Ñ*Ô*ˆŒ
ˆ
ˆ
r5   c                 ó   — |€| n| |z   S )z;Add positional embeddings to the input tensor, if provided.r7   r8   s     r4   r;   z0DeformableTransformerDecoderLayer.with_pos_embedF  r<   r5   c           	      óø   — |                       |                      |                      |                      |¦  «        ¦  «        ¦  «        ¦  «        }||                      |¦  «        z   }|                      |¦  «        S )zHPerform forward pass through the Feed-Forward Network part of the layer.)rù   rø   r-   r÷   rú   rû   )r/   ÚtgtÚtgt2s      r4   Úforward_ffnz-DeformableTransformerDecoderLayer.forward_ffnK  s]   € à�|Š|˜DŸMšM¨$¯(ª(°4·<²<ÀÑ3DÔ3DÑ*EÔ*EÑFÔFÑGÔGˆØ�D—M’M $Ñ'Ô'Ñ'ˆØ�zŠz˜#‰ŒÐr5   Nc                 ón  — |                       ||¦  «        x}}	|                      |                     dd¦  «        |	                     dd¦  «        |                     dd¦  «        |¬¦  «        d                              dd¦  «        }
||                      |
¦  «        z   }|                      |¦  «        }|                      |                       ||¦  «        |                     d¦  «        |||¦  «        }
||                      |
¦  «        z   }|                      |¦  «        }|  	                    |¦  «        S )z:Perform the forward pass through the entire decoder layer.r   r   )r@   rZ   )
r;   rõ   Ú	transposer+   r(   rö   Ú	unsqueezer,   r)   r  )r/   Úembedrè   ÚfeatsÚshapesÚpadding_maskr@   Ú	query_posrE   rF   rÿ   s              r4   rL   z)DeformableTransformerDecoderLayer.forwardQ  s(  € ð ×#Ò# E¨9Ñ5Ô5Ð5ˆˆAØ�nŠn˜QŸ[š[¨¨AÑ.Ô.°·²¸A¸qÑ0AÔ0AÀ5Ç?Â?ÐSTÐVWÑCXÔCXØ'0ð ñ 2ô 2Ø23ô5ß5>²Y¸qÀ!±_´_ð 	à˜Ÿš cÑ*Ô*Ñ*ˆØ—
’
˜5Ñ!Ô!ˆð �oŠo˜d×1Ò1°%¸ÑCÔCÀZ×EYÒEYÐZ[ÑE\ÔE\Ð^cÐekØ*ñ,ô ,ˆà˜Ÿš cÑ*Ô*Ñ*ˆØ—
’
˜5Ñ!Ô!ˆð ×Ò Ñ&Ô&Ð&r5   rN   )rO   rP   rQ   rR   r!   ÚReLUr   rT   r;   r  rL   rU   rV   s   @r4   r   r   (  s    ø€ € € € € ðð ð  #¨A°TÀ2È7È2Ì7É9Ì9Ð_`Ðklð +ð +ð +ð +ð +ð +ð, ð7ð 7ñ „\ð7ðð ð ð'ð 'ð 'ð 'ð 'ð 'ð 'ð 'r5   r   c                   ó0   ‡ — e Zd ZdZdˆ fd„	Z	 	 dd„Zˆ xZS )r   zÌ
    Implementation of Deformable Transformer Decoder based on PaddleDetection.

    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
    r]   c                 ó²   •— t          ¦   «                              ¦   «          t          ||¦  «        | _        || _        || _        |dk    r|n||z   | _        dS )zFInitialize the DeformableTransformerDecoder with the given parameters.r   N)r   r   r   r©   r•   r«   Úeval_idx)r/   r«   Údecoder_layerr•   r  r3   s        €r4   r   z%DeformableTransformerDecoder.__init__l  sT   ø€ å‰Œ×ÒÑÔÐÝ! -°Ñ<Ô<ˆŒØ$ˆŒØ$ˆŒØ$,°¢M M˜˜°zÀHÑ7LˆŒˆˆr5   Nc
                 ó(  — |}
g }g }d}|                      ¦   «         }t          | j        ¦  «        D �]9\  }} ||
||||	| ||¦  «        ¦  «        }
 ||         |
¦  «        }t          j         |t	          |¦  «        z   ¦  «        }| j        rx|                      ||         |
¦  «        ¦  «         |dk    r|                     |¦  «         n~|                     t          j         |t	          |¦  «        z   ¦  «        ¦  «         nF|| j        k    r;|                      ||         |
¦  «        ¦  «         |                     |¦  «          n!|}| j        r|                     ¦   «         n|}�Œ;t          j	        |¦  «        t          j	        |¦  «        fS )z4Perform the forward pass through the entire decoder.Nr   )
Úsigmoidr®   r©   rr   r   ÚtrainingÚappendr  Údetachr×   )r/   r  rè   r  r  Ú	bbox_headÚ
score_headÚpos_mlpr@   r  rò   Ú
dec_bboxesÚdec_clsÚlast_refined_bboxr±   r²   ÚbboxÚrefined_bboxs                     r4   rL   z$DeformableTransformerDecoder.forwardt  s£  € ð ˆØˆ
ØˆØ ÐØ×'Ò'Ñ)Ô)ˆ
Ý! $¤+Ñ.Ô.ð 	Rñ 	R‰HˆAˆuØ�U˜6 :¨u°f¸lÈIÐW^ÐW^Ð_iÑWjÔWjÑkÔkˆFà�9˜Q”< Ñ'Ô'ˆDÝ œ=¨µÀ
Ñ0KÔ0KÑ)KÑLÔLˆLàŒ}ð 	Ø—’˜}˜z¨!œ}¨VÑ4Ô4Ñ5Ô5Ð5Ø˜’6�6Ø×%Ò% lÑ3Ô3Ð3Ð3à×%Ò%¥e¤m°D½?ÐK\Ñ;]Ô;]Ñ4]Ñ&^Ô&^Ñ_Ô_Ð_Ð_Ø�d”mÒ#Ð#Ø—’˜}˜z¨!œ}¨VÑ4Ô4Ñ5Ô5Ð5Ø×!Ò! ,Ñ/Ô/Ð/Ø�à ,ÐØ26´-ÐQ˜×,Ò,Ñ.Ô.Ð.À\ˆJ‰JåŒ{˜:Ñ&Ô&­¬°GÑ(<Ô(<Ð<Ð<r5   )r]   )NNrˆ   rV   s   @r4   r   r   e  si   ø€ € € € € ðð ðMð Mð Mð Mð Mð Mð" Øð%=ð %=ð %=ð %=ð %=ð %=ð %=ð %=r5   r   )rR   rÕ   rr   Útorch.nnr!   Útorch.nn.functionalÚ
functionalr¯   Útorch.nn.initr   r   r�   r   Úutilsr   r   r	   Ú__all__ÚModuler
   r   r   r   r   r   r   r   r   r   r7   r5   r4   ú<module>r#     s‡  ðà Ð à €€€à €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4à Ð Ð Ð Ð Ð Ø TÐ TÐ TÐ TÐ TÐ TÐ TÐ TÐ TÐ Tðg€ð5Kð 5Kð 5Kð 5Kð 5K˜bœiñ 5Kô 5Kð 5Kðplð lð lð lð lÐ"ñ lô lð lðB)ð )ð )ð )ð )�r”yñ )ô )ð )ð&Vð Vð Vð Vð V�r”yñ Vô Vð Vð,1ð 1ð 1ð 1ð 1ˆrŒyñ 1ô 1ð 1ðð ð ð ð ˆ"Œ)ñ ô ð ð"Ið Ið Ið Ið I�"”)ñ Iô Ið Ið2X(ð X(ð X(ð X(ð X(�2”9ñ X(ô X(ð X(ðv:'ð :'ð :'ð :'ð :'¨¬	ñ :'ô :'ð :'ðz4=ð 4=ð 4=ð 4=ð 4= 2¤9ñ 4=ô 4=ð 4=ð 4=ð 4=r5   