Ë
    îÍ:jÒ$  ã                   ó²   — d Z ddlmZ ddlZddlmZ ddlmZ  G d„ dej                  «      Z	 G d„ d	ej                  «      Z
 G d
„ dej                  «      Zy)a  

Generic interface to various configurations of the Perceiver Resampler, that simply takes in a series of (potentially
time-indexed) contextual embeddings, and "resamples" (compresses) them down to a pre-specified number of latents! Note
that the Perceiver in general resamples based solely off the *long-range* context; there's a nice opportunity here to
prime the Perceiver Resampler with say a single layer's worth of language embeddings (the target domain), and use that
to softly "retrieve & compress" what we need --> this would be a novel contribution we should explore.

References:
    - DeepMind's Flamingo: https://www.deepmind.com/blog/tackling-multiple-tasks-with-a-single-visual-language-model
    - Code borrowed w/ love from: https://github.com/lucidrains/flamingo-pytorch

é    )ÚOptionalNé   )ÚIdeficsConfigc                   ót   ‡ — e Zd Zdededededededdfˆ fd	„Zd
ej                  dej                  fd„Zˆ xZ	S )ÚIdeficsPerceiverResamplerÚconfigÚ	embed_dimÚdepthÚn_headsÚhead_dimÚ	n_latentsÚreturnNc                 ó  •— t         ‰| �  «        ||||f\  | _        | _        | _        | _        |j                  j                  | _        t        j                  t        j                  | j
                  | j                  «      d¬«      | _        t        |j                  d«      s| j                  dz  n|j                  j                  dz  | _        t        j"                  t%        |«      D �cg c]a  }t        j"                  t'        | j                  | j                  | j                  | j                  «      t)        | j                   |«      g«      ‘Œc c}«      | _        t        j,                  | j                  «      | _        yc c}w )ao  
        Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or
        MAE) of a given dimension, performs `depth` blocks of cross-attention with a fixed `n_latents` inputs, then
        returns a Tensor of shape [bsz, n_latents, embed_dim]. :param embed_dim: Dimensionality of embeddings being fed
        to the Perceiver Resampler (also dimensionality of latent embeddings *returned* by the Perceiver Resampler.
        Could be e.g., VIT embed_dim, ResNet pool dim, and so on.

        Args:
            config (`IdeficsConfig`): config object
            embed_dim (`int`): The size of each embedding vector
            depth (`int`): Depth of the Perceiver Resampler (Transformer w/ cross attention). Should be shallow (< 3).
            n_heads (`int`): Number of heads in each Transformer block (for multi-headed self-attention).
            head_dim (`int`): Dimensionality of each head projection in the Transformer block.
            n_latents (`int`):
                Number of latent embeddings to resample ("compress") the input sequence to (usually < 128).

        T)Úrequires_gradr	   é   N)ÚsuperÚ__init__r	   r   r   r   Úperceiver_configÚqk_layer_norms_perceiverÚqk_layer_normsÚnnÚ	ParameterÚtorchÚrandnÚlatentsÚhasattrÚvision_configÚintermediate_dimÚ
ModuleListÚrangeÚIdeficsPerceiverAttentionÚ
IdeficsMLPÚblocksÚ	LayerNormÚ
layer_norm)	Úselfr   r	   r
   r   r   r   Ú_Ú	__class__s	           €úz/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/transformers/models/idefics/perceiver.pyr   z"IdeficsPerceiverResampler.__init__1   s7  ø€ ô( 	‰ÑÔØFOÐQXÐZbÐdmÐFmÑCˆŒ˜œ d¤m°T´^Ø$×5Ñ5×NÑNˆÔô —|‘|¤E§K¡K°·±ÀÇÁÓ$OÐ_cÔdˆŒô ˜6×/Ñ/°Ô=ð �N‰N˜QÒà×%Ñ%×/Ñ/°!Ñ3ð 	Ôô —m‘mô ˜u›öð ô —‘ä1°$·.±.À$Ç,Á,ÐPT×P]ÑP]Ð_c×_rÑ_rÓsÜ" 4×#8Ñ#8¸&ÓAðõòó

ˆŒô Ÿ,™, t§~¡~Ó6ˆ�ùòs   Ã-A&FÚcontextc                 óÎ   — | j                   j                  |j                  d   dd«      }| j                  D ]  \  }} |||«      |z   } ||«      |z   }Œ | j	                  |«      S )zWResample arbitrary length context & *compress* down to self.n_latents latent embeddingsr   r   )r   ÚrepeatÚshaper#   r%   )r&   r*   r   ÚattnÚffs        r)   Úforwardz!IdeficsPerceiverResampler.forward_   sn   € ð —,‘,×%Ñ% g§m¡m°AÑ&6¸¸1Ó=ˆð Ÿ™ò 	,‰HˆD�"Ù˜7 GÓ,¨wÑ6ˆGÙ˜“k GÑ+‰Gð	,ð �‰˜wÓ'Ð'ó    )
Ú__name__Ú
__module__Ú__qualname__r   Úintr   r   ÚTensorr0   Ú__classcell__©r(   s   @r)   r   r   0   s\   ø„ ð,7Ø#ð,7Ø03ð,7Ø<?ð,7ØJMð,7ØY\ð,7Øilð,7à	õ,7ð\
(˜uŸ|™|ð 
(°·±÷ 
(r1   r   c            
       ó„   ‡ — e Zd Zdededededdf
ˆ fd„Zdej                  d	ej                  dej                  fd
„Zˆ xZ	S )r!   r	   r   r   r   r   Nc                 ó˜  •— t         ‰| �  «        |||c| _        | _        | _        || _        t        j                  | j                  «      | _        t        j                  | j                  «      | _	        | j
                  rHt        j                  | j                  «      | _
        t        j                  | j                  «      | _        | j                  dz  | _        t        j                  | j                  | j                  | j                  z  d¬«      | _        t        j                  | j                  | j                  | j                  z  d¬«      | _        t        j                  | j                  | j                  | j                  z  d¬«      | _        t        j                  | j                  | j                  z  |d¬«      | _        y)ziPerceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`g      à¿F©ÚbiasN)r   r   r	   r   r   r   r   r$   Úcontext_layer_normÚlatents_layer_normÚq_layer_normÚk_layer_normÚqk_scaleÚLinearÚq_projÚk_projÚv_projÚoutput_proj)r&   r	   r   r   r   r(   s        €r)   r   z"IdeficsPerceiverAttention.__init__m   s0  ø€ ä‰ÑÔØ6?ÀÈ(Ð3ˆŒ˜œ d¤mØ,ˆÔä"$§,¡,¨t¯~©~Ó">ˆÔÜ"$§,¡,¨t¯~©~Ó">ˆÔØ×ÒÜ "§¡¨T¯]©]Ó ;ˆDÔÜ "§¡¨T¯]©]Ó ;ˆDÔàŸ™ tÑ+ˆŒô —i‘i §¡°·±¸t¿}¹}Ñ0LÐSXÔYˆŒÜ—i‘i §¡°·±¸t¿}¹}Ñ0LÐSXÔYˆŒÜ—i‘i §¡°·±¸t¿}¹}Ñ0LÐSXÔYˆŒäŸ9™9 T§\¡\°D·M±MÑ%AÀ9ÐSXÔYˆÕr1   r*   r   c           	      óŠ  — | j                  |«      }| j                  |«      }|j                  dd \  }}}| j                  |«      }| j	                  t        j                  ||gd¬«      «      }| j                  t        j                  ||gd¬«      «      }|||fD �	cg c]G  }	|	j                  ||	j                  d   | j                  | j                  «      j                  dd«      ‘ŒI c}	\  }}}| j                  r"| j                  |«      }| j                  |«      }t        j                  d|| j                   z  |«      }
|
|
j#                  dd	¬
«      j%                  «       z
  }|j'                  d¬«      }t        j                  d||«      }| j)                  |j                  dd«      j+                  d«      «      S c c}	w )aF  
        Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension!

        Args:
            context (`torch.Tensor`):
                Tensor of shape `[bsz, seq, embed_dim]` representing long-form context to resample.
            latents (`torch.Tensor`):
                Tensor of shape `[bsz, n_latents, embed_dim]` representing fixed length latents to compress to.

        Returns:
            `torch.Tensor`: Tensor of shape `[bsz, n_latents, embed_dim]` representing attention over latents w/ cross
            from context.
        Né   éþÿÿÿ)Údimr   é   z... i d, ... j d -> ... i jéÿÿÿÿT)rJ   Úkeepdimz... i j, ... j d -> ... i d)r=   r>   r-   rC   rD   r   ÚcatrE   Úreshaper   r   Ú	transposer   r?   r@   ÚeinsumrA   ÚamaxÚdetachÚsoftmaxrF   Úflatten)r&   r*   r   Ú
batch_sizeÚ
seq_lengthr	   ÚqÚkÚvÚxÚscoresÚstabilized_scoresr.   Ú	resampleds                 r)   r0   z!IdeficsPerceiverAttention.forward‚   s—  € ð ×)Ñ)¨'Ó2ˆØ×)Ñ)¨'Ó2ˆØ,3¯M©M¸"¸1Ð,=Ñ)ˆ
�J 	ð �K‰K˜Ó ˆØ�K‰KœŸ	™	 7¨GÐ"4¸"Ô=Ó>ˆØ�K‰KœŸ	™	 7¨GÐ"4¸"Ô=Ó>ˆð
 mnÐopÐrsÐktÖuÐfg�1—9‘9˜Z¨¯©°©°T·\±\À4Ç=Á=ÓQ×[Ñ[Ð\]Ð_`ÕaÒu‰ˆˆ1ˆaà×ÒØ×!Ñ! !Ó$ˆAØ×!Ñ! !Ó$ˆAä—‘Ð;¸QÀÇÁÑ=NÐPQÓRˆØ" f§k¡k°bÀ$ kÓ&G×&NÑ&NÓ&PÑQÐØ ×(Ñ(¨RÐ(Ó0ˆô —L‘LÐ!>ÀÀaÓHˆ	à×Ñ 	× 3Ñ 3°A°qÓ 9× AÑ AÀ"Ó EÓFÐFùò vs   ÂAG )
r2   r3   r4   r5   Úboolr   r   r6   r0   r7   r8   s   @r)   r!   r!   l   s]   ø„ ðZ #ð Z°ð Z¸sð ZÐTXð ZÐ]aõ Zð*(G˜uŸ|™|ð (G°e·l±lð (GÀuÇ|Á|÷ (Gr1   r!   c                   óh   ‡ — e Zd Zdefˆ fd„Zdeeej                        dej                  fd„Z	ˆ xZ
S )r"   r   c                 ón  •— t         ‰| �  «        |j                  j                  | _        t	        j
                  | j                  «      | _        t	        j                  | j                  |d¬«      | _        t	        j                  «       | _
        t	        j                  || j                  d¬«      | _        y)z:Simple MLP block with intermediate_size and embedding sizeFr;   N)r   r   r   r	   r   r$   ÚlnrB   ÚfcÚReLUÚactÚc_proj)r&   Úintermediate_sizer   r(   s      €r)   r   zIdeficsMLP.__init__®   st   ø€ ä‰ÑÔØ×-Ñ-×7Ñ7ˆŒÜ—,‘,˜tŸ~™~Ó.ˆŒÜ—)‘)˜DŸN™NÐ,=ÀEÔJˆŒÜ—7‘7“9ˆŒÜ—i‘iÐ 1°4·>±>ÈÔNˆ�r1   Úhidden_statesr   c                 óŽ   — | j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }|S )N)rb   rc   re   rf   )r&   rh   s     r)   r0   zIdeficsMLP.forward·   s@   € ØŸ™ Ó.ˆØŸ™ Ó.ˆØŸ™ Ó/ˆØŸ™ MÓ2ˆàÐr1   )r2   r3   r4   r   r   r   Útupler   ÚFloatTensorr0   r7   r8   s   @r)   r"   r"   ­   s:   ø„ ðO°-õ Oð X¨e°E×4EÑ4EÑ.FÑ%Gð ÈE×L]ÑL]÷ r1   r"   )Ú__doc__Útypingr   r   Útorch.nnr   Úconfiguration_ideficsr   ÚModuler   r!   r"   © r1   r)   ú<module>rr      sL   ðñ4õ ã Ý å 0ô9( §	¡	ô 9(ôx>G §	¡	ô >GôB�—‘õ r1   