o
    	۷i'                     @   sv   d Z ddlmZ ddlZddlmZ ddlmZ G dd	 d	ej	j
jZG d
d dej	j
jZG dd dej	j
jZdS )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   )
shape_list   )IdeficsConfigc                       s\   e Zd Zdededededededdf fd	d
Z fddZdejdejfddZ	  Z
S )TFIdeficsPerceiverResamplerconfig	embed_dimdepthn_headshead_dim	n_latentsreturnNc           	         s   t  jdi | ||||f\| _| _| _| _|jj| _t	|j
ds'| jd n|j
jd | _g | _t|D ]#}| jt| j| j| j| jd| ddt| j|d| ddg q5tjjjddd	| _d
S )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).

        r	      zblocks.z.0namez.1h㈵>
layer_normepsilonr   N )super__init__r	   r   r   r   perceiver_configqk_layer_norms_perceiverqk_layer_normshasattrvision_configintermediate_dimblocksrangeappendTFIdeficsPerceiverAttentionTFIdeficsMLPtfkeraslayersLayerNormalizationr   )	selfr   r	   r
   r   r   r   kwargsi	__class__r   ^/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/idefics/perceiver_tf.pyr   1   s"   


	z$TFIdeficsPerceiverResampler.__init__c                    s,   | j | j| jfdddd| _t | d S )Nrandom_normalTlatents)shapeinitializer	trainabler   )
add_weightr   r	   r/   r   build)r(   input_shaper+   r   r-   r4   \   s   z!TFIdeficsPerceiverResampler.buildcontextc                 C   s`   t j| jdd}t |t |d ddg}| jD ]\}}|||| }||| }q| |S )zWResample arbitrary length context & *compress* down to self.n_latents latent embeddingsr   axisr   )r$   expand_dimsr/   tiler0   r   r   )r(   r6   r/   attnffr   r   r-   callc   s   
z TFIdeficsPerceiverResampler.call)__name__
__module____qualname__r   intr   r4   r$   Tensorr=   __classcell__r   r   r+   r-   r   0   s$    +r   c                
       sN   e Zd Zdededededdf
 fddZd	ejd
ejdejfddZ  Z	S )r"   r	   r   r   r   r   Nc                    s  t  jdi | |||| _| _| _|| _tjjj	ddd| _
tjjj	ddd| _| jrBtjjj	ddd| _tjjj	ddd| _| jd | _tjjj| j| j dd	d
| _tjjj| j| j ddd
| _tjjj| j| j ddd
| _tjjj|ddd
| _dS )ziPerceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`r   context_layer_normr   latents_layer_normq_layer_normk_layer_normg      Fq_projuse_biasr   k_projv_projoutput_projNr   )r   r   r	   r   r   r   r$   r%   r&   r'   rD   rE   rF   rG   qk_scaleDenserH   rK   rL   rM   )r(   r	   r   r   r   r)   r+   r   r-   r   p   s   z$TFIdeficsPerceiverAttention.__init__r6   r/   c              	      s
   |}|}t|\ }}|}tj||gdd}tj||gdd} fdd|||fD \}}}jrK	|}
|}td|j |}|tj|ddd }	tjj|	dd}
td	|
|}ttj|g d
d djj fS )a=  
        Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension!

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

        Returns:
            `tf.Tensor`: Tensor of shape `[bsz, n_latents, embed_dim]` representing attention over latents w/ cross
            from context.
        r7   c              
      s8   g | ]}t jt | |jd  jjfg ddqS )r   r      r   r   perm)r$   	transposereshaper0   r   r   ).0x
batch_sizer(   r   r-   
<listcomp>   s    *z4TFIdeficsPerceiverAttention.call.<locals>.<listcomp>z... i d, ... j d -> ... i jT)r8   keepdimsz... i j, ... j d -> ... i drQ   rS   )rD   rE   r   rH   rK   r$   concatrL   r   rF   rG   einsumrN   
reduce_maxnnsoftmaxrM   rV   rU   r   r   )r(   r6   r/   
seq_lengthr	   qkvscoresstabilized_scoresr;   	resampledr   rY   r-   r=      s&   




&z TFIdeficsPerceiverAttention.call)
r>   r?   r@   rA   boolr   r$   rB   r=   rC   r   r   r+   r-   r"   o   s    "$r"   c                       s@   e Zd Zdef fddZdeeej  dejfddZ	  Z
S )r#   r   c                    st   t  jdi | |jj| _tjjjddd| _tjjj	|ddd| _
tjjjdd| _tjjj	| jdd	d| _d
S )z:Simple MLP block with intermediate_size and embedding sizer   lnr   FfcrI   actr   c_projNr   )r   r   r   r	   r$   r%   r&   r'   rk   rO   rl   ReLUrm   rn   )r(   intermediate_sizer   r)   r+   r   r-   r      s   
zTFIdeficsMLP.__init__hidden_statesr   c                 C   s,   |  |}| |}| |}| |}|S )N)rk   rl   rm   rn   )r(   rq   r   r   r-   r=      s
   



zTFIdeficsMLP.call)r>   r?   r@   r   r   r   tupler$   rB   r=   rC   r   r   r+   r-   r#      s    &	r#   )__doc__typingr   
tensorflowr$   modeling_tf_utilsr   configuration_ideficsr   r%   r&   Layerr   r"   r#   r   r   r   r-   <module>   s   ?D