U
    4Af]9                    @  sf  d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
ZddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZ ddl m!Z! ddl"m#Z# ddl$m%Z% e&e'Z(dZ)eG dd deZ*eG dd deZ+dBddZ,dd Z-dCddZ.g fddZ/G dd  d ej0j1j2Z3G d!d" d"ej0j1j4Z5dDd#d$Z6dEd%d&Z7G d'd( d(ej0j1j4Z8G d)d* d*ej0j1j4Z9d+d, Z:d-d. Z;G d/d0 d0ej0j1j4Z<G d1d2 d2ej0j1j4Z=G d3d4 d4ej0j1j4Z>G d5d6 d6ej0j1j4Z?d7Z@ed8e@G d9d: d:eZAd;ZBed8e@eG d<d= d=ej0j1j4ZCG d>d? d?eAZDG d@dA dAeeZEdS )FzTF 2.0 Idefics model.    )annotations)	dataclass)ListOptionalTupleUnionN   )TFPreTrainedModel)get_tf_activation)ModelOutput)TFCausalLanguageModelingLossTFModelInputTypekeras_serializable
shape_listunpack_inputs)invert_attention_maskscaled_dot_product_attention)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )IdeficsConfig)TFIdeficsPerceiverResampler)TFIdeficsVisionTransformerr   c                   @  sN   e Zd ZU dZdZded< dZded< dZded< dZded	< dZ	ded
< dS ) TFIdeficsBaseModelOutputWithPasta	  
    Base class for Idefics model's outputs that may also contain a past key/values (to speed up sequential decoding).

    Args:
        last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.

            If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
            hidden_size)` is output.
        past_key_values (`tuple(tuple(tf.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(tf.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
            `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
            input) to speed up sequential decoding.
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(tf.Tensor)`, *optional*):
            Tuple of `tf.Tensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.

            image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
    N	tf.Tensorlast_hidden_statez!Optional[Tuple[Tuple[tf.Tensor]]]past_key_valuesOptional[Tuple[tf.Tensor]]hidden_states
attentionsimage_hidden_states)
__name__
__module____qualname____doc__r   __annotations__r   r    r!   r"    r(   r(   S/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/idefics/modeling_tf_idefics.pyr   8   s   
$r   c                   @  sZ   e Zd ZU dZdZded< dZded< dZded< dZd	ed
< dZ	d	ed< dZ
d	ed< dS )TFIdeficsCausalLMOutputWithPasta  
    Base class for Idefics causal language model (or autoregressive) outputs.

    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(tf.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(tf.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(tf.Tensor)`, *optional*):
            Tuple of `tf.Tensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.

            image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
    NOptional[tf.Tensor]lossr   logitsOptional[List[tf.Tensor]]r   r   r    r!   r"   )r#   r$   r%   r&   r,   r'   r-   r   r    r!   r"   r(   r(   r(   r)   r*   e   s   
 r*   Fc              	   K  s:  t t t t | d |dg}t | |} |dd |d< |dd |d< |dd |d< |dd |d< d|kr|d }t |||d< |d k	rt |||d< |d d k	rt |d ||d< |d d k	rt |d ||d< nF|d d k	rt |d ||d< n"|d d k	r2t |d ||d< | |fS )	Nr   pixel_valuesimage_encoder_embeddingsperceiver_embeddingsimage_attention_masktoken_type_idsattention_mask)tfreshaperepeatrangeshapegatherget)	input_idsZexpand_sizeis_encoder_decoderr5   Zencoder_outputsmodel_kwargsZexpanded_return_idxr4   r(   r(   r)   expand_inputs_for_generation   s.    & 
r@   c                 C  s   d| kr| j |d< nd |d< d|krT|d }tj||d d dd df gdd|d< d|kr|d }tj|t|d d dd df gdd|d< d|kr|d }|d d dd df }||d< | j|d< |S )	Nr   r4   r/   .axisr5   r3   r"   )r   r6   concatZ	ones_liker"   )outputsr?   r4   r5   r3   Z	last_maskr(   r(   r)   "update_model_kwargs_for_generation   s$    ( 

rE   c                 K  s  | dd }|d k	rD| d d dd f } |d k	rD|d d dd f }| dd }| dd }|d k	r|d krtjjtj|tjdddd }t|dkd|}|d k	r|d d dd f }| d	d }| d
d }| dd }| dd }	| dd}
| || d|||||||	|
dS )Nr4   r/   r5   position_idsdtyperA   r   r   r0   r1   r2   r3   interpolate_pos_encodingF	use_cache)r=   r   rJ   rF   r5   r4   r0   r1   r2   r3   rI   )r<   r6   mathcumsumcastZint64where)r=   r   kwargsr4   r5   rF   r0   r1   r2   r3   rI   r(   r(   r)   prepare_inputs_for_generation   s:     rP   c                   s|   t jjjt jjjt jjjdfdd|D }t| dsDd| _| S | jD ], |rpt fdd|D rpd _qJd _qJ| S )	N)Z	LayerNormDense	Embeddingc                   s   g | ]} | qS r(   r(   ).0m)mappingr(   r)   
<listcomp>   s     z freeze_model.<locals>.<listcomp>layersFc                 3  s   | ]}t  |V  qd S N)
isinstance)rS   t)layerr(   r)   	<genexpr>  s     zfreeze_model.<locals>.<genexpr>T)	r6   kerasrW   ZLayerNormalizationrQ   rR   hasattr	trainableany)modelmodule_exceptionsZmodule_exceptions_mappedr(   )r[   rU   r)   freeze_model   s    

rc   c                      sD   e Zd ZdZdddd fddZ fd	d
ZddddZ  ZS )TFIdeficsDecoupledEmbeddinga  
    Implements a decoupling of parameters to allow freezing (or not) a subset of the embeddings. In practise, the
    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `num_additional_embeddings` > 0,
    then it will create `num_additional_embeddings` additional parameters that are always trained. If
    `num_additional_embeddings=0`, then the module defaults back to the regular behavior of `tf.keras.layers.Embedding`.
    FNOptional[bool]None)partially_freezereturnc                   s^   t  jf |||d| || _|| _|| _|r6d| _| jdkrZtjjj	| j||dd| _
dS )a  
        Args:
            num_embeddings (`int`):
                Size of the dictionary of embeddings
            num_additional_embeddings (`int`):
                Number of additional embeddings. Only useful when you `partially_freeze=True`.
            embedding_dim (`int`):
                The size of each embedding vector
            partially_freeze: (`bool`, *optional*, defaults to `False`):
                If `True`, the regular `weight` will be frozen. `additional_weight` is never frozen.

        Note: there are a lot of other parameters to initialize a standard `tf.keras.layers.Embedding` such as `mask_zero`,
        `input_length` or `embeddings_initializer`. We are not supporting these.
        )	input_dim
output_dimrH   Fr   additional_embedding)ri   rj   rH   nameN)super__init__num_embeddingsnum_additional_embeddingsrg   r_   r6   r]   rW   rR   rk   )selfro   rp   embedding_dimrg   rH   rO   	__class__r(   r)   rn     s&    
z$TFIdeficsDecoupledEmbedding.__init__c                   s   | j dkrt |S t|}t|| jk}t||}| || j }t	||tj
t|d |jd}t |}t	|||}|S )a  
        we have 2 embeddings, with different indices - one pretrained self.weight and another
        self.additional_embedding.weight that is being trained.

        in order to make a lookup of the input ids, we:
        1. find out the indices of the entries belonging to the 2nd embedding
        2. extract those values while subtracting the size of the first embedding (num_embeddings), since the 2nd
           embedding starts from 0 and not num_embeddings
        3. perform the 2nd embedding lookup
        4. now we handle the 1st embedding, we overwrite indices belonging to the 2nd embedding with a padding index
        5. perform the 1st embedding lookup
        6. now we overwrite the values in the 1st embedding lookup with the values of the 2nd embedding lookup

        note: for the 1st embedding lookup we could have looked up only the low indices and not do the padding, but
        then we have to create a new tensor and populate it with 2 tensors that are spread out across various indices -
        i.e. not a simple concat - I haven't benchmarked the complex case if it's any faster, given that seqlens are
        usually relatively short it's probably not faster or if faster not by much - but might be a good idea to
        measure.

        r   rG   )rp   rm   callr6   identityrN   ro   Z	gather_ndrk   Ztensor_scatter_nd_updatezerosr:   rH   )rq   r=   Zadditional_vocab_indicesZinput_ids_additional_vocabZadditional_embeddingsZfull_vectorrs   r(   r)   ru   @  s    

z TFIdeficsDecoupledEmbedding.callstrrh   c                 C  s   d | j| j| j| jS )NzVnum_embeddings={}, num_additional_embeddings={}, embedding_dim={}, partially_freeze={})formatro   rp   rj   rg   rq   r(   r(   r)   
extra_reprl  s    z&TFIdeficsDecoupledEmbedding.extra_repr)FN)r#   r$   r%   r&   rn   ru   r|   __classcell__r(   r(   rs   r)   rd     s     ,,rd   c                      sr   e Zd ZdZdddddddd fdd	Zd
d
dddZ fddZddddZedd Z	dddZ
  ZS )TFIdeficsDecoupledLineara  
    Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the
    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0,
    then it will create `out_additional_features * in_features` additional parameters that are always trained. If
    `out_additional_features=0`, then the module defaults back to the regular behavior of `tf.keras.layers.Dense`.
    r   Tintboolrf   )in_featuresout_featuresout_additional_featuresbiasrg   rh   c                   sN   t  jf | || _|| _|| _|| _|| _|dkrJtjj	j
||dd| _dS )aS  
        out_additional_features: int. Number of additional trainable dimensions. Only makes sense when
        `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra
        parameters (if any) will be trainable. If False, default to the regular behavior of tf.keras.layers.Dense.
        r   additional_fc)Zunitsuse_biasrl   N)rm   rn   r   rg   r   r   r   r6   r]   rW   rQ   r   )rq   r   r   r   r   rg   rO   rs   r(   r)   rn   }  s      z!TFIdeficsDecoupledLinear.__init__r   )inputsrh   c                 C  sX   t jj|| jdd}| jd k	r.t j|| j}| jdkrT| |}t j	||gdd}|S )NT)abZtranspose_br   r/   rA   )
r6   Zlinalgmatmulweightr   nnZbias_addr   r   rC   )rq   r   outputZadditional_featuresr(   r(   r)   ru     s    


zTFIdeficsDecoupledLinear.callc                   s2   t   }|| j| j| j| jd k	| jd |S )N)r   r   r   r   rg   )rm   
get_configupdater   r   r   r   rg   rq   configrs   r(   r)   r     s    
	z#TFIdeficsDecoupledLinear.get_configrx   ry   c                 C  s    d | j| j| j| jdk	| jS )z=Overwriting `nn.Linear.extra_repr` to include new parameters.zYin_features={}, out_features={}, out_additional_features={}, bias={}, partially_freeze={}N)rz   r   r   r   r   rg   r{   r(   r(   r)   r|     s    z#TFIdeficsDecoupledLinear.extra_reprc                 C  s
   | f |S rX   r(   )clsr   r(   r(   r)   from_config  s    z$TFIdeficsDecoupledLinear.from_configNc              	   C  s   | j r
d S d| _ | j| j| jf| j dd| _| jrP| j| jf| j dd| _nd | _t| dd d k	rt	
| jj | j| j W 5 Q R X d S )NTr   )r:   r_   rl   r   r   )built
add_weightr   r   rg   r   r   r   getattrr6   
name_scoper   rl   buildrq   input_shaper(   r(   r)   r     s    
  zTFIdeficsDecoupledLinear.build)r   TT)N)r#   r$   r%   r&   rn   ru   r   r|   classmethodr   r   r}   r(   r(   rs   r)   r~   u  s      

r~   c                 C  s   | \}}t ||ft j|j}t |}t |dddf |dddf kd|}|dkr~t jt j||f|d|gdd}|dkrt 	|d}t 	|d}t 
||dddg}n,t |ddddddf |d||| f}|S )zm
    Make causal mask used for bi-directional self-attention, supporting both static and dynamic shapes.
    N        r   rG   r/   rA   r   )r6   fillZdtypesZas_dtypeminr9   rN   rC   rw   expand_dimsZtilebroadcast_to)Zinput_ids_shaperH   past_key_values_lengthbsztgt_lenmaskZ	mask_condr(   r(   r)   _make_causal_mask  s    
* ,r   c                 C  s|   t | \}}|dk	r|n|}tt| dd}t||d||g}dt|| }tt|ttjt |tjj	d|S )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)Zdimsvalue)
r   r6   r   r   rM   rN   r   r   float32r   )r   rH   r   r   Zsrc_lenZexpanded_maskZinverted_maskr(   r(   r)   _expand_mask  s    
  r   c                      s2   e Zd Zd fdd	Z fddZdd Z  ZS )	TFIdeficsRMSNormư>c                   s   t  jf | || _|| _dS )z?
        TFIdeficsRMSNorm is equivalent to T5LayerNorm
        N)rm   rn   hidden_sizevariance_epsilon)rq   r   epsrO   rs   r(   r)   rn     s    zTFIdeficsRMSNorm.__init__c                   s6   | j r
d S d| _ | jd| jgdd| _t | d S )NTr   ones)rl   r:   initializer)r   r   r   r   rm   r   r   rs   r(   r)   r     s
    zTFIdeficsRMSNorm.buildc                 C  sh   t jjt jt |t jddd}|t j|| j  }| jj	t j
t jfkr^t || jj	}| j| S )Nr/   T)rB   Zkeepdims)r6   rK   Zreduce_meanZsquarerM   r   Zrsqrtr   r   rH   Zfloat16Zbfloat16)rq   r    Zvariancer(   r(   r)   ru     s
    $zTFIdeficsRMSNorm.call)r   r#   r$   r%   rn   r   ru   r}   r(   r(   rs   r)   r     s   r   c                      s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )TFIdeficsEmbedding   '  c              
     sR   t  jf | || _|| _|| _td| jtjd| jdtjd| j   | _	d S )Nr   r      )startlimitdeltarH   )
rm   rn   dimmax_position_embeddingsbaser6   Zconstantr9   r   inv_freq)rq   r   r   r   rO   rs   r(   r)   rn     s    $zTFIdeficsEmbedding.__init__c                 C  sH   t j|| jjd}t d|| j}t j||fdd}t |t |fS )NrG   z
i, j -> ijr/   rA   )r6   r9   r   rH   ZeinsumrC   cossin)rq   seq_lenrZ   ZfreqsZembr(   r(   r)   _compute_cos_sin!  s    z#TFIdeficsEmbedding._compute_cos_sinNc                 C  s    |d krt |d }| j|dS )Nr   )r   )r   r   )rq   xr   r(   r(   r)   ru   (  s    zTFIdeficsEmbedding.call)r   r   )N)r#   r$   r%   rn   r   ru   r}   r(   r(   rs   r)   r     s   
r   c                 C  sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr/   r   rA   )r:   r6   rC   )r   x1Zx2r(   r(   r)   rotate_half/  s    r   c                 C  s`   t ||}t ||}t |d}t |d}| | t| |  }|| t||  }||fS )Nr   )r6   r;   r   r   )qkr   r   rF   Zq_embedZk_embedr(   r(   r)   apply_rotary_pos_emb6  s    r   c                      s8   e Zd Zdddd fddZdd Zdd	d
Z  ZS )TFIdeficsMLPr   rx   )r   intermediate_size
hidden_actc                   sj   t  jf | tjjj|ddd| _tjjj|ddd| _tjjj|ddd| _t	|| _
|| _|| _d S )NF	gate_projr   rl   	down_projup_proj)rm   rn   r6   r]   rW   rQ   r   r   r   r
   act_fnr   r   )rq   r   r   r   rO   rs   r(   r)   rn   A  s    
zTFIdeficsMLP.__init__c                 C  s    |  | | || | S rX   )r   r   r   r   )rq   r   r(   r(   r)   ru   P  s    zTFIdeficsMLP.callNc              	   C  s   | j r
d S d| _ t| dd d k	rHt| jj | j| j W 5 Q R X t| dd d k	rt| jj | j| j	 W 5 Q R X t| dd d k	rt| j
j | j
| j W 5 Q R X d S )NTr   r   r   )r   r   r6   r   r   rl   r   r   r   r   r   r   r(   r(   r)   r   S  s    zTFIdeficsMLP.build)Nr#   r$   r%   rn   ru   r   r}   r(   r(   rs   r)   r   @  s   r   c                
      sl   e Zd ZdZdddddddd	 fd
dZddddddZddddddddddddZdddZ  ZS )TFIdeficsAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr   FNr   floatr   r   )r   	num_headsdropoutis_cross_attentionr   qk_layer_normsc                   s  t  jf | || _|| _|| | _|| _|| _d| _| j| | jkr^td| j d| d|| _	t
jjj|| j ddd| _t
jjj|| j ddd| _t
jjj|| j dd	d| _t
jjj|dd
d| _t| jdd| _|| _| jrt| j|jdd| _t| j|jdd| _d S )NTz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fq_projr   k_projv_projo_proj
rotary_embrl   q_layer_normr   rl   k_layer_norm)rm   rn   r   r   head_dimr   r   	is_causal
ValueErrorr   r6   r]   rW   rQ   r   r   r   r   r   r   r   r   rms_norm_epsr   r   )rq   r   r   r   r   r   r   rO   rs   r(   r)   rn   e  sJ    

zTFIdeficsAttention.__init__r   )tensorr   r   c                 C  s*   t jt |||| j| jfddddgdS )Nr   r   r   r   perm)r6   	transposer7   r   r   )rq   r   r   r   r(   r(   r)   _shape  s    zTFIdeficsAttention._shaper+   r   zATuple[tf.Tensor, Optional[tf.Tensor], Optional[Tuple[tf.Tensor]]])r    key_value_statesr5   rF   past_key_valueoutput_attentionsrJ   rh   c              	   C  s^  | j p|d k	}t|\}	}
}| | ||
|	}|s^| | ||
|	}| | ||
|	}n6t|\}}}| | |||	}| | |||	}t|d }|d k	r|t|d d 7 }|st|rt||
}n
t	||
}| 
||\}}t|||||\}}|d k	r>tj|d |gdd}tj|d |gdd}|rL||fnd }| jrl| |}| |}tjjt||	d|
|gd|	d|
|g dt| d t||||| jo|d ko|
dkd	}tjjt||	| j|
| jgd|	| j|
| jg dt| d ttj|dddd
gd|	|
| jf}| |}d }|rTtd |||fS )Nr   r   rA   r   z$Attention weights should be of size z	, but is )message)Z	attn_maskr   r   r   z^attn_weights are not extracted in scaled_dot_product_attention. The model returns None instead)r   r   r   r   r   r   r6   Z	is_tensorZ
reduce_maxmaxr   r   rC   r   r   r   	debuggingZassert_equalr:   r   r   r   r   r7   r   r   r   loggerwarning_once)rq   r    r   r5   rF   r   r   rJ   r   r   Zq_len_Zquery_statesZ
key_statesZvalue_statesZkv_lenZ
kv_seq_lenr   r   r   Zattn_outputZattn_weightsr(   r(   r)   ru     sd    





	 &
zTFIdeficsAttention.callc              	   C  s\  | j r
d S d| _ | jr6t| jjds*| jn| jjj}n| j}t| dd d k	rzt	| j
j | j
| j| j  W 5 Q R X t| dd d k	rt	| jj | j| j W 5 Q R X t| dd d k	rt	| jj | j| W 5 Q R X t| dd d k	r t	| jj | j| W 5 Q R X t| dd d k	rXt	| jj | jd  W 5 Q R X d S )NT	embed_dimr   r   r   r   r   )r   r   r^   r   vision_configr   r   r   r6   r   r   rl   r   r   r   r   r   r   r   )rq   r   Zkv_input_dimr(   r(   r)   r     s0    zTFIdeficsAttention.build)r   FNF)NNNNFF)N)	r#   r$   r%   r&   rn   r   ru   r   r}   r(   r(   rs   r)   r   b  s       5      Qr   c                	      sH   e Zd Zdd fddZddddd	d
d
ddddZdddZ  ZS )TFIdeficsDecoderLayerr   r   c                   s|   t  jf | |j| _t| j|j|j|dd| _t| j|j|j	dd| _
t|j|jdd| _t|j|jdd| _|j| _d S )N	self_attn)r   r   r   r   rl   mlpr   r   r   rl   input_layernormr   post_attention_layernorm)rm   rn   r   r   num_attention_headsr   r   r   r   r   r   r   r   r   r   rq   r   rO   rs   r(   r)   rn     s,      zTFIdeficsDecoderLayer.__init__NFr   r+   r   re   7Tuple[tf.Tensor, Optional[Tuple[tf.Tensor, tf.Tensor]]])r    r5   rF   r   r   rJ   rh   c                 C  s   |}|  |}| j||||||d\}}	}
tjj|| jd}|| }|}| |}| |}tjj|| jd}|| }|f}|r||	f7 }|r||
f7 }|S )aE  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`, *optional*): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(tf.Tensor)`, *optional*): cached past key and value projection states
        )r    r5   rF   r   r   rJ   Zrate)r   r   r6   r   r   r   r   )rq   r    r5   rF   r   r   rJ   trainingresidualself_attn_weightspresent_key_valuerD   r(   r(   r)   ru   "  s.    




zTFIdeficsDecoderLayer.callc              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X t| dd d k	rt| j	j | j	d  W 5 Q R X d S )NTr   r   r   r   )
r   r   r6   r   r   rl   r   r   r   r   r   r(   r(   r)   r   [  s    zTFIdeficsDecoderLayer.build)NNNFFF)Nr   r(   r(   rs   r)   r     s         9r   c                      sN   e Zd Zdd fddZ fddZdd	d
d
d
d
ddddd	ddZ  ZS )!TFIdeficsGatedCrossAttentionLayerr   r   c              	     s   t  jf | |j| _t| j|jd|j||jdd| _t| j|j	|j
dd| _t|j|jdd| _t|j|jdd| _|j| _tjjj| _tjjj| _|j| _|j| _|j| _d S )	NT
cross_attn)r   r   r   r   r   r   rl   r   r   r   r   r   )rm   rn   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r6   r]   Zactivationstanhact_cross_attn	act_densealpha_initializer
alpha_typealphas_initializer_ranger   rs   r(   r)   rn   n  s:    	  z*TFIdeficsGatedCrossAttentionLayer.__init__c              	     s  | j r
d S d| _ | jdkr| jdkr^| jdd| jfdddd| _| jdd| jfdddd| _nF| jdkr| jd	dddd| _| jd	dddd| _ntd
| j dn| jdkrB| jdkr| jdd| jfdddd| _| jdd| jfdddd| _nH| jdkr.| jd	dddd| _| jd	dddd| _ntd
| j dn| jdkr| jdkr| jdd| jftj	j
jd| jdddd| _| jdd| jftj	j
jd| jdddd| _nh| jdkr
| jd	tj	j
jd| jdddd| _| jd	tj	j
jd| jdddd| _ntd
| j dntd| j dt| drHt| dsPtdt| jj | jd  W 5 Q R X t| jj | jd  W 5 Q R X t| jj | jd  W 5 Q R X t| jj | jd  W 5 Q R X t | d S )NTrw   Zvectorr   alpha_cross_attn)r:   r   r_   rl   alpha_denser   )r   z Unknown value for `alpha_type` ()r   >   gaussiannormalrandomr   )Zmeanstddevr	  zAlpha initialization scheme z not yet implemented!z+Alpha parameters not initialized correctly!)r   r  r	  r   r   r  r  r   r6   r]   ZinitializersZRandomNormalr
  NotImplementedErrorr^   r   r  rl   r   r   r   r   rm   r   rs   r(   r)   r     s    


   
   

   

   
   
   



z'TFIdeficsGatedCrossAttentionLayer.buildNFr   r+   re   r   r   )	r    r5   r"   r3   cross_attention_gater   rJ   r   rh   c	                 C  s*  |dkrt d|dkr t d|dk	r0td|}	| |}| j||||d\}}
}tjj|| jd}tj|dk|j	d}t
|d	}tt|t|d
kt||}|	| | j|  }|}	| |}| |}tjj|| jd}|	| | j|  }|f}|r||
f7 }|r&||f7 }|S )a  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`, *optional*): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(tf.Tensor)`, *optional*): cached past key and value projection states
            no_images (`bool`, *optional*, defaults to `False`): If `True` the vision part is ignored
        Nzt`image_hidden_states` is required for Idefics cross attention module which are visual features to be conditioned on.z`cross_attention_gate` is required for Idefics cross attention module to zero-out the cross-attention hidden_states attending to no images.zMPast key value states are not implemented for Idefics cross attention module.)r    r   r5   r   r   r   rG   r/   r   )r   r  r   r  r6   r   r   r   rM   rH   r   rN   r   r:   Z
zeros_liker  r  r   r   r  r  )rq   r    r5   r"   r3   r  r   rJ   r   r   r  r  r   rD   r(   r(   r)   ru     sL    
  



z&TFIdeficsGatedCrossAttentionLayer.call)NNNNFFNr   r(   r(   rs   r)   r  m  s   T       r  ag  
    This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a TensorFlow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) subclass.
    Use it as a regular TensorFlow Layer and refer to the TensorFlow documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`IdeficsConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare LLaMA Model outputting raw hidden-states without any specific head on top.c                   @  s    e Zd ZeZdZdZddgZdS )TFIdeficsPreTrainedModelra   Tr   r  N)r#   r$   r%   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr(   r(   r(   r)   r  =  s   r  a   
    Args:
        input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        past_key_values (`tuple(tuple(tf.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(tf.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                      s   e Zd ZdZeZd ddd fddZd!d	d
Zg fddZg fddZ	dd Z
dd Zdd Zeeed"dddddddddddddddddddZd#ddZ  ZS )$TFIdeficsMainLayerz
    Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a [`IdeficsDecoderLayer`]

    Args:
        config: IdeficsConfig
    Tr   r   )r   add_pooling_yearc              	     s  t  jf |  | _ j| _ j| _t j j j j	dd| _
 jj| _ j| _t jdd| _ jr j}t  jj|j|j|j|jdd| _ fddt jD | _ j| _ j| j } fddt|D | _d	| _t j jd
d| _ d	| _| !  d S )Nembed_tokens)ro   rp   rr   rg   rl   vision_modelr   perceiver_resamplerc                   s   g | ]}t  d | dqS )zlayers.r   )r   rS   ir   r(   r)   rV     s    z/TFIdeficsMainLayer.__init__.<locals>.<listcomp>c                   s   g | ]}t  d | dqS )zgated_cross_attn_layers.r   )r  r  r   r(   r)   rV     s   Fnormr   )"rm   rn   r   Zpad_token_idZpadding_idx
vocab_sizerd   additional_vocab_sizer   freeze_text_layersr  r   Z
image_sizer   r  use_resamplerperceiver_configr   r   Zresampler_depthZresampler_n_headsZresampler_head_dimZresampler_n_latentsr  r9   Znum_hidden_layersdecoder_layerscross_layer_intervalgated_cross_attn_layersgradient_checkpointingr   r   r  freeze_relevant_params)rq   r   r  rO   r"  Znum_cross_layersrs   r   r)   rn     sJ    



zTFIdeficsMainLayer.__init__Nc                 C  s:   |d kr| j }|jr | |j |jr6t| j|jd d S N)rb   )r   r   Zfreeze_text_module_exceptionsfreeze_vision_layersrc   r  Zfreeze_vision_module_exceptionsr   r(   r(   r)   r'    s    z)TFIdeficsMainLayer.freeze_relevant_paramsc                 C  s"   | j | jfD ]}t||d qd S r(  )r#  r  rc   )rq   rb   moduler(   r(   r)   r     s    z%TFIdeficsMainLayer.freeze_text_layersc                 C  s   t | j|d d S r(  )rc   r  )rq   rb   r(   r(   r)   r)    s    z'TFIdeficsMainLayer.freeze_vision_layersc                 C  s   | j S rX   r  r{   r(   r(   r)   get_input_embeddings  s    z'TFIdeficsMainLayer.get_input_embeddingsc                 C  s
   || _ d S rX   r+  rq   r   r(   r(   r)   set_input_embeddings  s    z'TFIdeficsMainLayer.set_input_embeddingsc                 C  sH   d }t ||j|d}|d k	rDt||j|d d}|d kr<|n|| }|S )N)r   r/   )r   )r   rH   r   )rq   r5   r   inputs_embedsr   Zcombined_attention_maskZexpanded_attn_maskr(   r(   r)   _prepare_decoder_attention_mask  s    z2TFIdeficsMainLayer._prepare_decoder_attention_maskFTFModelInputType | Noner+   r.   re   9Union[TFIdeficsBaseModelOutputWithPast, Tuple[tf.Tensor]]r=   r5   rF   r   r/  r0   r1   r2   r3   rJ   r   output_hidden_statesrI   return_dictr   rh   c           )      C  s  |d k	r|n| j j}|d k	r |n| j j}|
d k	r4|
n| j j}
|d k	rH|n| j j}|d k	rj|d k	rjtdn6|d k	rt|\}}n |d k	rt|\}}}ntd|}d}|d k	rt|d d d }|| }|d k	r|d krtjj	tj
|tjdddd }t|dkd|}n,|d kr@tj||| tjd}t|d}d	}tt|d kt|d kt|d kfdkrztd
n|d k	r.ttj
|tjddk}tj
|| jd}t|jdkrt|d }t|d }nDt|jdkrt|d d \}}t||| f|jdd  }| j||dj}n@|d k	rnt|\}}}}tj
|| jd}t||| ||f}| j jr|d kr| |}t|dd \}}nt|\}}}}|}n(|d krt|dd \}}ntdt|||| |f}|d k	r0t|jdkr0|	d kr0tj||dftjd}	t|	d }t|	d}	tj|	|d}	t|	|||| f}	|d k	rt|\}}}||f}|	d krtj|tjd}	t|	}	nd }	tjtj
tj|	dkdd| jddd}|d kr|  |}|d krtj||ftj!d}| "|||f||}|}| j#rH|rH|
rHt$%d d	}
|rRdnd } |r`dnd }!|
rndnd }"t&| j'D ]\}#}$|r| |f7 } |d k	r||# nd }%dd }&| j#r|rd }%|
rt$%d d	}
t(|&|$||||%||	||
||#| j)| j*}'n&|&|$||||%||	|||
|#| j)| j*d}'|'d }|
rN|"|'|rDdnd f7 }"|r||!|'d f7 }!q|| +|}|r| |f7 } |
r|"nd }(t|||||f}|st,dd ||(| |!|fD S t-||(| |!|dS )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timezEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r   rG   r/   rA   r   Fz_Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None.      )r0   rI   r   zBIf `perceiver_embeddings` are passed, use_resampler should be True)ZrepeatszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...r(   c              
   S  sP   |
| dkr8||
|  }||||||||	d d}|d }| ||||||	d}|S )Nr   )r5   r"   r3   r  r   rJ   r   )r5   rF   r   r   rJ   r(   )Z
main_blockr    r5   rF   r   r"   r3   r  r   rJ   	layer_idxr$  r%  ZxblockrD   layer_outputsr(   r(   r)   vblock  s,    
	z'TFIdeficsMainLayer.call.<locals>.vblock)r5   rF   r   r"   r3   r  r   rJ   r8  r$  r%  c                 s  s   | ]}|d k	r|V  qd S rX   r(   )rS   vr(   r(   r)   r\     s   z*TFIdeficsMainLayer.call.<locals>.<genexpr>)r   r   r    r!   r"   ).r   r   r4  rJ   use_return_dictr   r   r6   rK   rL   rM   Zint32rN   r9   r   sumr   Z
reduce_sumrH   lenr:   r7   r  r   r!  r  rw   r8   r   r   ZsqueezeZ
reduce_anyr  r   r0  r&  r   r   	enumerater#  Zrecompute_gradr$  r%  r  tupler   ))rq   r=   r5   rF   r   r/  r0   r1   r2   r3   rJ   r   r4  rI   r5  r   Z
batch_sizeZ
seq_lengthr   Zseq_length_with_pastr   Z	no_imagesZ
num_imagesr"   Zimage_seq_lenZimage_hidden_sizeZtext_seq_lenZimage_batch_sizeZimage_sequence_lengthZimage_hidden_shaper  r    Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerr   r:  r9  Z
next_cacher(   r(   r)   ru     sP   
 
$
  

 



 $


 


   
)

 
zTFIdeficsMainLayer.callc              
   C  sp  | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X t| dd d k	rt| j	j | j	d  W 5 Q R X t| dd d k	r*| j
D ](}t|j |d  W 5 Q R X q t| dd d k	rl| jD ](}t|j |d  W 5 Q R X qBd S )NTr  r  r  r  r#  r%  )r   r   r6   r   r  rl   r   r  r  r  r#  r%  )rq   r   r[   r(   r(   r)   r     s.    

zTFIdeficsMainLayer.build)T)N)NNNNNNNNNNNNFNN)N)r#   r$   r%   r&   r   r  rn   r'  r   r)  r,  r.  r0  r   r   LLAMA_INPUTS_DOCSTRINGru   r   r}   r(   r(   rs   r)   r    s<   0

               2  r  c                      sZ   e Zd Zdd fddZddddd	dddddd
d
d
d
d
d
ddddZdddZ  ZS )TFIdeficsModelr   r   c                   s&   t  j|f|| t|dd| _d S )Nra   r   )rm   rn   r  ra   )rq   r   r   rO   rs   r(   r)   rn     s    zTFIdeficsModel.__init__NFr1  r+   r.   re   r2  r3  c                 C  s,   | j |||||||||	|
|||||d}|S )Nr=   r5   rF   r   r/  r0   r1   r2   r3   rJ   r   r4  rI   r5  r   ra   )rq   r=   r5   rF   r   r/  r0   r1   r2   r3   rJ   r   r4  rI   r5  r   rD   r(   r(   r)   ru     s$    zTFIdeficsModel.callc              	   C  sJ   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X d S )NTra   )r   r   r6   r   ra   rl   r   r   r(   r(   r)   r   B  s    zTFIdeficsModel.build)NNNNNNNNNNNNFNN)Nr   r(   r(   rs   r)   rC    s$                  .%rC  c                      s   e Zd ZdgZddgZeZd( fdd	Zdd Zdd	 Z	d
d Z
dd Zdd Zdd Zdd Zeeeeeedd)dddddddddddddddddddZd*ddZed d! Zed"d# Zed$d% Zd+d&d'Z  ZS ),TFIdeficsForVisionText2Textzlm_head.weightzmodel.embed_tokens.weightNc                   s@   t  j|f| t|dd| _t|j|j|jd|jdd| _	d S )Nra   r   Flm_head)r   rg   rl   )
rm   rn   r  ra   r~   r   r  r  Zfreeze_lm_headrG  )rq   r   r  rO   rs   r(   r)   rn   P  s    z$TFIdeficsForVisionText2Text.__init__c                 C  s   | j jS rX   ra   r  r{   r(   r(   r)   r,  \  s    z0TFIdeficsForVisionText2Text.get_input_embeddingsc                 C  s   || j _d S rX   rH  r-  r(   r(   r)   r.  _  s    z0TFIdeficsForVisionText2Text.set_input_embeddingsc                 C  s   | j S rX   rG  r{   r(   r(   r)   get_output_embeddingsb  s    z1TFIdeficsForVisionText2Text.get_output_embeddingsc                 C  s
   || _ d S rX   rI  )rq   Znew_embeddingsr(   r(   r)   set_output_embeddingse  s    z1TFIdeficsForVisionText2Text.set_output_embeddingsc                 C  s
   || _ d S rX   rE  )rq   decoderr(   r(   r)   set_decoderh  s    z'TFIdeficsForVisionText2Text.set_decoderc                 C  s   | j S rX   rE  r{   r(   r(   r)   get_decoderk  s    z'TFIdeficsForVisionText2Text.get_decoderc                 C  s   |   }|  }t| jddrL|j|_|jdkrL|j|jks@t|jj|j	_t
|drt
|dr|j|_t
|drt
|dr|j|_dS )	z
        Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of
        IdeficsDecoupledLinear and IdeficsDecoupledEmbedding.
        Ztie_word_embeddingsTr   r   ro   r   rp   N)rJ  r,  r   r   r   rp   r   AssertionErrorrk   r   r^   ro   r   )rq   Zoutput_embeddingsZinput_embeddingsr(   r(   r)   tie_weightsn  s    
 z'TFIdeficsForVisionText2Text.tie_weights)output_typer  Fr1  r+   r.   re   z8Union[TFIdeficsCausalLMOutputWithPast, Tuple[tf.Tensor]])r=   r5   rF   r   r/  r0   r1   r2   r3   labelsrJ   r   r4  rI   r5  rh   c                 C  sp  |dk	r|n| j j}|dk	r |n| j j}|dk	r4|n| j j}| j|||||||||	||||||d}|d }| |}d}|
dk	r$|dk	r|dddf }|dddddf |dk }|
dddf |dk }n&|dddddf }|
dddf }| jt|dgt|d|j	d gd}|sT|f|dd  }|dk	rP|f| S |S t
|||j|j|j|jdS )	a  
        Args:
            labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        Example:

        ```python
        >> from transformers import AutoTokenizer, TFIdeficsForVisionText2Text

        >> model = TFIdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
        >> tokenizer = AutoTokenizer.from_pretrained("HuggingFaceM4/idefics-9b")

        >> prompt = "Hey, are you consciours? Can you talk to me?"
        >> inputs = tokenizer(prompt, return_tensors="tf")

        >> # Generate
        >> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
        ```NrD  r   .r   r/   )rR  r-   )r,   r-   r   r    r!   r"   )r   r   r4  r<  ra   rG  Zhf_compute_lossr6   r7   r:   r*   r   r    r!   r"   )rq   r=   r5   rF   r   r/  r0   r1   r2   r3   rR  rJ   r   r4  rI   r5  r   rD   r    r-   r,   Zshift_attention_maskZshift_logitsZshift_labelsr   r(   r(   r)   ru     s\    0

 z TFIdeficsForVisionText2Text.callc                 K  sj   | dd }|d k	r6| jjr&||d< n||d< d |d< t|fd|i|}dg}|D ]}| |d  qT|S )Nr"   r2   r1   r0   pastr4   )popr   r!  rP   )rq   r=   rS  rO   r"   r   Zunwanted_kwargskwargr(   r(   r)   rP     s    
z9TFIdeficsForVisionText2Text.prepare_inputs_for_generationc                  O  s
   t | |S rX   )r@   )argsr?   r(   r(   r)   _expand_inputs_for_generation  s    z9TFIdeficsForVisionText2Text._expand_inputs_for_generationc                 C  s
   t | |S rX   )rE   )rD   r?   r>   r(   r(   r)   #_update_model_kwargs_for_generation   s    z?TFIdeficsForVisionText2Text._update_model_kwargs_for_generationc                   s.   d}| D ] }|t  fdd|D f7 }q|S )Nr(   c                 3  s   | ]}t | V  qd S rX   )r6   r;   )rS   Z
past_statebeam_idxr(   r)   r\     s     z=TFIdeficsForVisionText2Text._reorder_cache.<locals>.<genexpr>)r@  )rS  rZ  Zreordered_pastZ
layer_pastr(   rY  r)   _reorder_cache  s    z*TFIdeficsForVisionText2Text._reorder_cachec              	   C  s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X d S )NTra   rG  )r   r   r6   r   ra   rl   r   rG  r   r(   r(   r)   r     s    z!TFIdeficsForVisionText2Text.build)N)NNNNNNNNNNNNNFNF)N)N)r#   r$   r%   Z_keys_to_ignore_on_load_missingZ_tied_weights_keysr   r  rn   r,  r.  rJ  rK  rM  rN  rP  r   r   rB  r   r*   _CONFIG_FOR_DOCru   rP   staticmethodrW  rX  r[  r   r}   r(   r(   rs   r)   rF  K  sN   
                4e



rF  )r   FNN)N)r   )N)Fr&   
__future__r   Zdataclassesr   typingr   r   r   r   Z
tensorflowr6    r	   Zactivations_tfr
   Zmodeling_tf_outputsr   Zmodeling_tf_utilsr   r   r   r   r   Ztf_utilsr   r   utilsr   r   r   r   Zconfiguration_ideficsr   Zperceiver_tfr   Z	vision_tfr   Z
get_loggerr#   r   r\  r   r*   r@   rE   rP   rc   r]   rW   rR   rd   ZLayerr~   r   r   r   r   r   r   r   r   r   r  ZLLAMA_START_DOCSTRINGr  rB  r  rC  rF  r(   r(   r(   r)   <module>   sv   
,+    
'
'iY


" *b @>   4