U
    ,-e                    @   st  d 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
  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 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 ddlm Z  ddl!m"Z" ddl#m$Z$ e%e&Z'dZ(ddgZ)eG dd deZ*eG dd deZ+dEddZ,dd Z-dFddZ.g fd d!Z/G d"d# d#e
j0Z1G d$d% d%e
j2Z3dGej4ej5ej6e7d&d'd(Z8dHej9ej5ee7 d)d*d+Z:G d,d- d-e
j;Z<e=e< G d.d/ d/ej
j;Z>d0d1 Z?d2d3 Z@G d4d5 d5e
j;ZAG d6d7 d7e
j;ZBG d8d9 d9e
j;ZCG d:d; d;e
j;ZDd<ZEed=eEG d>d? d?eZFd@ZGed=eEG dAdB dBeFZHG dCdD dDeFZIdS )Iz PyTorch Idefics model.    )	dataclass)ListOptionalTupleUnionN)nn)CrossEntropyLoss   )PreTrainedModel)ACT2FN)ModelOutput)PretrainedConfig)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )IdeficsConfig)IdeficsPerceiverResampler)IdeficsVisionTransformerr   zHuggingFaceM4/idefics-9bzHuggingFaceM4/idefics-80bc                   @   s|   e Zd ZU dZdZejed< dZe	e
e
ej   ed< dZe	e
ej  ed< dZe	e
ej  ed< dZe	e
ej  ed< dS )IdeficsBaseModelOutputWithPasta	  
    Base class for Idefics model's outputs that may also contain a past key/values (to speed up sequential decoding).

    Args:
        last_hidden_state (`torch.FloatTensor` 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(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (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last_hidden_statepast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r   torchFloatTensor__annotations__r   r   r   r   r   r    r$   r$   m/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/idefics/modeling_idefics.pyr   9   s   
$r   c                   @   s   e Zd ZU dZdZeej ed< dZ	ejed< dZ
eeej  ed< dZeeej  ed< dZeeej  ed< dZeeej  ed< dS )	IdeficsCausalLMOutputWithPasta  
    Base class for Idefics causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` 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(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (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losslogitsr   r   r   r   )r   r   r   r    r'   r   r!   r"   r#   r(   r   r   r   r   r   r   r$   r$   r$   r%   r&   f   s   
 r&   Fc                 K   sB  t | jd ddd|d| j}| d|} |dd |d< |dd |d< |dd |d< |dd |d< d|kr|d }|d||d< |d k	r|d||d	< |d d k	r|d d||d< |d d k	r|d d||d< nF|d d k	r|d d||d< n"|d d k	r:|d d||d< | |fS )
Nr   r   pixel_valuesimage_encoder_embeddingsperceiver_embeddingsimage_attention_masktoken_type_idsattention_mask)	r!   arangeshapeviewrepeattodeviceindex_selectget)	input_idsZexpand_sizeis_encoder_decoderr/   Zencoder_outputsmodel_kwargsZexpanded_return_idxr.   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f dgdd|d< d|kr|d }tj|||jd dfgdd|d< d|kr|d }|d d dd d f d}||d< | j|d	< |S )
Nr   r.   r)   dimr/   r   r   r-   r   )r   r!   cat	unsqueezeZnew_onesr1   r   )outputsr:   r.   r/   r-   Z	last_maskr$   r$   r%   "update_model_kwargs_for_generation   s$    ( 

rA   c                 K   s  | dd }|rD| d d df d} |d k	rD|d d df d}| dd }| dd }|d k	r|d kr| dd }||dkd |r|d d df d}| dd }| dd }| d	d }| d
d }	| dd}
| || d|||||||	|
dS )Nr.   r)   r/   position_idsr   r   r*   r+   r,   r-   interpolate_pos_encodingF	use_cache)r8   r   rD   rB   r/   r.   r*   r+   r,   r-   rC   )r7   r?   longcumsummasked_fill_)r8   r   kwargsr.   r/   rB   r*   r+   r,   r-   rC   r$   r$   r%   prepare_inputs_for_generation   s:    rI   c                    sf   t jt jt jd  fdd|D }|  D ]4|rVtfdd|D rVd q,d q,| S )N)	LayerNormLinear	Embeddingc                    s   g | ]} | qS r$   r$   ).0m)mappingr$   r%   
<listcomp>  s     z freeze_model.<locals>.<listcomp>c                 3   s   | ]}t  |V  qd S N)
isinstance)rM   t)moduler$   r%   	<genexpr>	  s     zfreeze_model.<locals>.<genexpr>TF)r   rJ   rK   rL   modulesanyrequires_grad_)modelmodule_exceptionsZmodule_exceptions_mappedr$   )rO   rT   r%   freeze_model  s    r[   c                       sD   e Zd ZdZdee dd fddZdd Zed	d
dZ	  Z
S )IdeficsDecoupledEmbeddinga  
    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 `nn.Embedding`.
    FN)partially_freezereturnc           	         s   |dk	r$||kr$t d| d| t jf |||||d| || _|| _|| _|| _|rj| jd | jdkrt	j
| j|||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.
            padding_idx (`int`, *optional*):
                The padding index (needs to be less than num_embeddings)

        Note: there are a lot of other parameters to initialize a standard `nn.Embedding` such as `padding_idx`,
        `max_norm` or `norm_type`. We are not supporting these.
        Nz/padding_idx must be within num_embeddings. Got z and )num_embeddingsembedding_dimr5   dtypepadding_idxFr   )r_   r`   r5   ra   )
ValueErrorsuper__init__r_   rb   num_additional_embeddingsr]   weightrX   r   rL   additional_embedding)	selfr_   rf   r`   r]   r5   ra   rb   rH   	__class__r$   r%   re     s0    
z"IdeficsDecoupledEmbedding.__init__c                 C   sj   | j dkrt|| jS | }t|| jk}|| }| || j }d||< t|| j}|||< |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   )	rf   FZ	embeddingrg   cloner!   wherer_   rh   )ri   r8   Zadditional_vocab_indicesZinput_ids_additional_vocabZadditional_embeddingsZfull_vectorr$   r$   r%   forwardN  s    
z!IdeficsDecoupledEmbedding.forwardr^   c                 C   s   d | j| j| j| jS )NzVnum_embeddings={}, num_additional_embeddings={}, embedding_dim={}, partially_freeze={})formatr_   rf   r`   r]   ri   r$   r$   r%   
extra_repru  s    z$IdeficsDecoupledEmbedding.extra_repr)FNNN)r   r   r   r    r   boolre   ro   strrs   __classcell__r$   r$   rj   r%   r\     s       5'r\   c                       sT   e Zd ZdZdeeeeedd fddZejejdd	d
Z	e
dddZ  ZS )IdeficsDecoupledLineara  
    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 `nn.Linear`.
    r   TN)in_featuresout_featuresout_additional_featuresbiasr]   r^   c                    sn   t  ||||| || _|| _|| _|| _|rL| jd |rL| jd |dkrjt	j
|||||d| _dS )aG  
        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 nn.Linear.
        Fr   )rx   ry   r{   r5   ra   N)rd   re   rz   r]   rx   ry   rg   rX   r{   r   rK   additional_fc)ri   rx   ry   rz   r{   r]   r5   ra   rj   r$   r%   re     s"    zIdeficsDecoupledLinear.__init__)inputr^   c                 C   s:   t || j| j}| jdkr6| |}t||fd}|S )Nr   r)   )rl   Zlinearrg   r{   rz   r|   r!   r>   )ri   r}   outputZadditional_featuresr$   r$   r%   ro     s
    

zIdeficsDecoupledLinear.forwardrp   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)rq   rx   ry   rz   r{   r]   rr   r$   r$   r%   rs     s    z!IdeficsDecoupledLinear.extra_repr)r   TTNN)r   r   r   r    intrt   re   r!   Tensorro   ru   rs   rv   r$   r$   rj   r%   rw   ~  s         $	rw   )input_ids_shapera   r5   past_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    r5   r)   r   r   ra   r5   r<   N)r!   fullfinfominr0   sizerG   r2   r4   r>   zerosexpand)r   ra   r5   r   bsztgt_lenmaskZ	mask_condr$   r$   r%   _make_causal_mask  s    "
 r   )r   ra   r   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)r   r   r4   Zmasked_fillr!   rt   r   r   )r   ra   r   r   Zsrc_lenZexpanded_maskZinverted_maskr$   r$   r%   _expand_mask  s
    *r   c                       s&   e Zd Zd fdd	Zdd Z  ZS )IdeficsRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        IdeficsRMSNorm is equivalent to T5LayerNorm
        N)rd   re   r   	Parameterr!   onesrg   variance_epsilon)ri   hidden_sizeepsrj   r$   r%   re     s    
zIdeficsRMSNorm.__init__c                 C   s\   | tjdjddd}|t|| j  }| jjtj	tj
fkrR| | jj}| j| S )N   r)   T)Zkeepdim)r4   r!   Zfloat32powmeanZrsqrtr   rg   ra   Zfloat16Zbfloat16)ri   r   Zvariancer$   r$   r%   ro     s
    zIdeficsRMSNorm.forward)r   r   r   r   re   ro   rv   r$   r$   rj   r%   r     s   r   c                       s(   e Zd Zd fdd	Zd	ddZ  ZS )
IdeficsEmbedding   '  Nc           	         s   t    d|td|d ||   }| d| || _tj| j| jj	| jj
d}td|| j}tj||fdd}| jd	| d d d d d d f d
d | jd| d d d d d d f d
d d S )Nr   r   r   inv_freqr5   ra   i,j->ijr)   r<   
cos_cachedF
persistent
sin_cached)rd   re   r!   r0   floatr4   register_buffermax_seq_len_cachedr   r5   ra   einsumr>   cossin)	ri   r=   Zmax_position_embeddingsbaser5   r   rS   freqsembrj   r$   r%   re     s    
$(zIdeficsEmbedding.__init__c                 C   s   || j kr|| _ tj| j |j| jjd}td|| j}tj||fdd|j}| j	d|
 d d d d d d f dd | j	d| d d d d d d f dd | jd d d d d |d	f j|jd
| jd d d d d |d	f j|jd
fS )Nr   r   r)   r<   r   Fr   r   .)ra   )r   r!   r0   r5   r   ra   r   r>   r4   r   r   r   r   r   )ri   xseq_lenrS   r   r   r$   r$   r%   ro     s    
((&&zIdeficsEmbedding.forward)r   r   N)Nr   r$   r$   rj   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   r<   )r1   r!   r>   )r   x1Zx2r$   r$   r%   rotate_half  s    r   c                 C   s   |d d d d d d f }| d|jd d|jd }t| |jd dddd|}t| |jd dddd|}| | t| |  }|| t||  }||fS )Nr   r	   r   r   )r3   r1   r!   gatherr   )qkr   r   rB   Zgather_indicesZq_embedZk_embedr$   r$   r%   apply_rotary_pos_emb  s      r   c                       s.   e Zd Zeeed fddZdd Z  ZS )
IdeficsMLPr   intermediate_size
hidden_actc                    sN   t    tj||dd| _tj||dd| _tj||dd| _t| | _d S )NFr{   )	rd   re   r   rK   	gate_proj	down_projup_projr   act_fn)ri   r   r   r   rj   r$   r%   re   +  s
    
zIdeficsMLP.__init__c                 C   s    |  | | || | S rQ   )r   r   r   r   )ri   r   r$   r$   r%   ro   7  s    zIdeficsMLP.forward)r   r   r   r   ru   re   ro   rv   r$   r$   rj   r%   r   *  s
   r   c                       s   e Zd ZdZdeeeeeed fddZe	j
eedd	d
Zde	j
ee	j
 ee	j
 ee	j eee	j
  eeee	j
ee	j
 eee	j
  f dddZ  ZS )IdeficsAttentionz=Multi-headed attention from 'Attention Is All You Need' paper        FN)r   	num_headsdropoutis_cross_attentionconfigqk_layer_normsc                    s|  t    || _|| _|| | _|| _| j| | jkrNtd| j d| d|| _tt	j
dshtd| jrt|jds| jn|jj}t	j| j|| j dd| _t	j||| j dd| _t	j||| j dd| _nNt	j| j|| j dd| _t	j| j|| j dd| _t	j| j|| j dd| _t	j|| j |dd| _t| j| _|| _| jrxt| j|jd	| _t| j|jd	| _d S )
Nz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).scaled_dot_product_attentionz)this model requires pytorch 2.0 or higher	embed_dimFr   r   )rd   re   r   r   head_dimr   rc   r   hasattrr   
functionalvision_configr   rK   q_projk_projv_projo_projr   
rotary_embr   r   rms_norm_epsq_layer_normk_layer_norm)ri   r   r   r   r   r   r   Zkv_input_dimrj   r$   r%   re   ?  sf    	


zIdeficsAttention.__init__)tensorr   r   c                 C   s    | ||| j| jdd S )Nr   r   )r2   r   r   	transpose
contiguous)ri   r   r   r   r$   r$   r%   _shape  s    zIdeficsAttention._shape)r   key_value_statesr/   rB   past_key_valueoutput_attentionsrD   r^   c                 C   sn  | j p|d k	}| \}	}
}| ||	|
| j| jdd}|s| ||	|
| j| jdd}| ||	|
| j| jdd}nR| \}}}| ||	|| j| jdd}| ||	|| j| jdd}|j	d }|d k	r||d j	d 7 }|s0| j
|t||
d\}}t|||||\}}|d k	rftj|d |gdd}tj|d |gdd}|rt||fnd }| jr| |}| |}|d k	r| |	d|
|fkrtd|	d|
|f d|  tjj||||| jd	}| |	| j|
| jfkr*td
|	| j|
| jf d|  |dd}||	|
| j}| |}d }|rdtd |||fS )Nr   r   r   )r   r<   z!Attention mask should be of size z	, but is )Z	attn_maskZ	dropout_pz `attn_output` should be of size z^attn_weights are not extracted in scaled_dot_product_attention. The model returns None instead)r   r   r   r2   r   r   r   r   r   r1   r   maxr   r!   r>   r   r   r   rc   r   r   r   r   Zreshaper   r   loggerwarning_once)ri   r   r   r/   rB   r   r   rD   r   r   Zq_len_Zquery_statesZ
key_statesZvalue_statesZkv_lenZ
kv_seq_lenr   r   Zattn_outputZattn_weightsr$   r$   r%   ro     s`    ""$" 





zIdeficsAttention.forward)r   FNF)NNNNFF)r   r   r   r    r   r   rt   r   re   r!   r   r   r   
LongTensorr   ro   rv   r$   r$   rj   r%   r   <  s<       E      r   c                       sx   e Zd Zed fddZd	ejeej eej ee	ej  ee
 ee
 e	ejee	ejejf  f dddZ  ZS )
IdeficsDecoderLayerr   c                    sp   t    |j| _t| j|j|j|d| _t| j|j|j	d| _
t|j|jd| _t|j|jd| _|j| _d S )N)r   r   r   r   r   r   )rd   re   r   r   num_attention_headsr   	self_attnr   r   r   mlpr   r   input_layernormpost_attention_layernormri   r   rj   r$   r%   re     s     
zIdeficsDecoderLayer.__init__NF)r   r/   rB   r   r   rD   r^   c                 C   s   |}|  |}| j||||||d\}}}	tjj|| j| jd}|| }|}| |}| |}tjj|| j| jd}|| }|f}
|r|
|f7 }
|r|
|	f7 }
|
S )a]  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *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(torch.FloatTensor)`, *optional*): cached past key and value projection states
        )r   r/   rB   r   r   rD   ptraining)r   r   r   r   r   r   r   r   )ri   r   r/   rB   r   r   rD   residualself_attn_weightspresent_key_valuer@   r$   r$   r%   ro     s.    




zIdeficsDecoderLayer.forward)NNNFF)r   r   r   r   re   r!   r   r   r   r   rt   r"   ro   rv   r$   r$   rj   r%   r     s        r   c                       s   e Zd Zed fddZd	ejeej eej eej ee ee ee	ej  ee e	ej
ee	ej
ej
f  f d	ddZ  ZS )
IdeficsGatedCrossAttentionLayerr   c                    s  t    |j| _t| j|jd|j||jd| _t| j|j	|j
d| _t|j|jd| _t|j|jd| _|j| _t | _t | _|jdkr|jdkrttdd| j| _ttdd| j| _nB|jdkrttd| _ttd| _ntd	|j d
nV|jdkr|jdkr^ttdd| j| _ttdd| j| _nD|jdkrttd| _ttd| _ntd	|j d
n|jdkrX|jdkrttjd|jdd| jfd| _ttjd|jdd| jfd| _nT|jdkrDttjd|jdd| _ttjd|jdd| _ntd	|j d
nt d|j dt!| drt!| dstdd S )NT)r   r   r   r   r   r   r   r   r   Zvectorr   r   z Unknown value for `alpha_type` ()r   >   gaussianrandomnormalr   )r   stdr   zAlpha initialization scheme z not yet implemented!alpha_cross_attnalpha_densez+Alpha parameters not initialized correctly!)"rd   re   r   r   r   r   r   
cross_attnr   r   r   r   r   r   r   r   r   r   ZTanhact_cross_attn	act_denseZalpha_initializerZ
alpha_typer   r!   r   r   r   rc   r   r   Zalphas_initializer_rangeNotImplementedErrorr   r   rj   r$   r%   re   $  sj    




z(IdeficsGatedCrossAttentionLayer.__init__NF)	r   r/   r   r-   r   rD   r   	no_imagesr^   c	                 C   s   |dkrt d|dk	r td|}	| |}| j||||d\}}
}tjj|| j| jd}|rddnd}|	|| 	| j
 |  }|}	| |}| |}tjj|| j| jd}|	| | j|  }|f}|r||
f7 }|r||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *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(torch.FloatTensor)`, *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.zMPast key value states are not implemented for Idefics cross attention module.)r   r   r/   r   r   r   r   )rc   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )ri   r   r/   r   r-   r   rD   r   r   r   r   r   Zgater@   r$   r$   r%   ro   e  s8    




z'IdeficsGatedCrossAttentionLayer.forward)NNNFFNF)r   r   r   r   re   r!   r   r   rt   r   r"   ro   rv   r$   r$   rj   r%   r   #  s&   D       r   aL  
    This model inherits from [`PreTrainedModel`]. 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 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch 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
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare LLaMA Model outputting raw hidden-states without any specific head on top.c                   @   s2   e Zd ZeZdZdZddgZdd Zddd	Z	d
S )IdeficsPreTrainedModelrY   Tr   r   c                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )Nr   )r   r   )r   Zinitializer_rangerR   r   rK   rg   dataZnormal_r{   Zzero_rL   rb   )ri   rT   r   r$   r$   r%   _init_weights  s    

z$IdeficsPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S rQ   )rR   IdeficsModelgradient_checkpointing)ri   rT   valuer$   r$   r%   _set_gradient_checkpointing  s    
z2IdeficsPreTrainedModel._set_gradient_checkpointingN)F)
r   r   r   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   r  r$   r$   r$   r%   r     s   r   aI  
    Args:
        input_ids (`torch.LongTensor` 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 (`torch.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 (`torch.LongTensor` 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(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` 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 (`torch.FloatTensor` 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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dejeej eej eeej  eej eej eej eej eej ee ee ee ee ee eeef dddZ  ZS )r  z
    Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a [`IdeficsDecoderLayer`]

    Args:
        config: IdeficsConfig
    r   c                    s  t     | _ j| _ j| _t j j j j	| jd| _
 jj| _ j| _t j| _ jr j}t  jj|j|j|j|j| _t fddt jD | _ j| _ j| j }t fddt|D | _d| _t  j j!d| _"d| _| #  | $  d S )N)r_   rf   r`   r]   rb   c                    s   g | ]}t  qS r$   )r   rM   r   r   r$   r%   rP   ?  s     z)IdeficsModel.__init__.<locals>.<listcomp>c                    s   g | ]}t  qS r$   )r   r  r   r$   r%   rP   D  s     Fr   )%rd   re   r   Zpad_token_idrb   
vocab_sizer\   additional_vocab_sizer   freeze_text_layersembed_tokensr   Z
image_sizer   vision_modeluse_resamplerperceiver_configr   r   Zresampler_depthZresampler_n_headsZresampler_head_dimZresampler_n_latentsperceiver_resamplerr   Z
ModuleListrangeZnum_hidden_layerslayerscross_layer_intervalgated_cross_attn_layersr  r   r   norm	post_initfreeze_relevant_params)ri   r   r  Znum_cross_layersrj   r   r%   re   !  sF    
	 zIdeficsModel.__init__Nc                 C   s:   |d kr| j }|jr | |j |jr6t| j|jd d S N)rZ   )r   r	  Zfreeze_text_module_exceptionsfreeze_vision_layersr[   r  Zfreeze_vision_module_exceptionsr   r$   r$   r%   r  P  s    z#IdeficsModel.freeze_relevant_paramsc                 C   s"   | j | jfD ]}t||d qd S r  )r  r  r[   )ri   rZ   rT   r$   r$   r%   r	  Z  s    zIdeficsModel.freeze_text_layersc                 C   s   t | j|d d S r  )r[   r  )ri   rZ   r$   r$   r%   r  ^  s    z!IdeficsModel.freeze_vision_layersc                 C   s   | j S rQ   r
  rr   r$   r$   r%   get_input_embeddingsa  s    z!IdeficsModel.get_input_embeddingsc                 C   s
   || _ d S rQ   r  ri   r  r$   r$   r%   set_input_embeddingsd  s    z!IdeficsModel.set_input_embeddingsc                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr)   r   )r5   r   )r   )r   ra   r5   r   r4   )ri   r/   Zinput_shapeinputs_embedsr   Zcombined_attention_maskZexpanded_attn_maskr$   r$   r%   _prepare_decoder_attention_maskh  s    z,IdeficsModel._prepare_decoder_attention_maskF)r8   r/   rB   r   r  r*   r+   r,   r-   rD   r   output_hidden_statesrC   return_dictr^   c           (      C   sJ  |d k	r|j n|j }|d k	r |n| jj}|d k	r4|n| jj}|
d k	rH|
n| jj}
|d k	r\|n| jj}|d k	r~|d k	r~tdn2|d k	r|j\}}n|d k	r|j\}}}ntd|}d}|d k	r|d d jd }|| }|d k	r|d kr| 	dd }|
|dkd n\|d kr^|d k	r,|j n|j }tj||| tj|d}|dd|}n|d| }d}|||fd dkrtd	n|d k	rtt|dk}|j| j|d}|jd d \}}| j|| f|jdd   }| j||d
j}n>|d k	rB| \}}}}|j| j|j d}||| ||}| jjr|d krx| |}|d|d }}n| \}}}}|}n*|d kr|d|d }}ntd|||| |}|	d}|	d}	|	ddd|}	|	|||| }	|d k	rD| \}}}||f}|	d kr8tj||d}	| |	}	nd }	|d kr\| |}|d kr~tj||ftj|j d}| |||f||}|}| j r| j!r|
rt"#d d}
|rdnd }|rdnd } |
rdnd }!t$| j%D ]\}"}#|r||f7 }|d k	r||" nd }$dd }%| j rz| j!rzd }$|
rLt"#d d}
tj&j''|%|#||||$||	||
||"| j(| j)}&n&|%|#||||$||	||
||"| j(| j)d}&|&d }|
r|!|&|rdnd f7 }!|r| |&d f7 } q| *|}|r||f7 }|
r|!nd }'|||||}|s8t+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   r)   r   r   Fz_Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None.)r*   rC   zBIf `perceiver_embeddings` are passed, use_resampler should be Truer   zZ`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   )r/   r   r-   r   rD   r   r   )r/   rB   r   r   rD   r$   )Z
main_blockr   r/   rB   r   r   r-   r   rD   r   	layer_idxr  r  Zxblockr@   layer_outputsr$   r$   r%   vblock  s,    
	z$IdeficsModel.forward.<locals>.vblock)r/   rB   r   r   r-   r   rD   r   r   r  r  c                 s   s   | ]}|d k	r|V  qd S rQ   r$   )rM   vr$   r$   r%   rU   o  s   z'IdeficsModel.forward.<locals>.<genexpr>)r   r   r   r   r   )-r5   r   r   r  rD   use_return_dictrc   r1   rE   rF   rG   r!   r0   r?   r2   countlenZnonzeror4   ra   r   r  r   r   r  r  r3   r   Zinvert_attention_maskr
  rt   r  r  r   r   r   	enumerater  utils
checkpointr  r  r  tupler   )(ri   r8   r/   rB   r   r  r*   r+   r,   r-   rD   r   r  rC   r  r5   Z
batch_sizeZ
seq_lengthr   Zseq_length_with_pastr   r   Z
num_imagesr   Zimage_seq_lenZimage_hidden_sizeZtext_seq_lenZimage_batch_sizeZimage_sequence_lengthZimage_hidden_shaper   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerr   r"  r!  Z
next_cacher$   r$   r%   ro     s<   

   
" 












     
)

zIdeficsModel.forward)N)NNNNNNNNNNNNFN)r   r   r   r    r   re   r  r	  r  r  r  r  r   LLAMA_INPUTS_DOCSTRINGr!   r   r   r   r   r"   rt   r   r   r   ro   rv   r$   r$   rj   r%   r    sP   /

              
r  c                       s,  e Zd ZdgZddg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dd"ejeej eej eeej  eej eej eej eej eej eej ee ee ee ee ee eeef dddZd#ddZedd Zedd Zedd  Z   Z!S )$IdeficsForVisionText2Textzlm_head.weightzmodel.embed_tokens.weightNc                    s>   t  | t|| _t|j|j|jd|jd| _	| 
  d S )NF)rx   ry   rz   r{   r]   )rd   re   r  rY   rw   r   r  r  Zfreeze_lm_headlm_headr  )ri   r   r  rj   r$   r%   re     s    
	z"IdeficsForVisionText2Text.__init__c                 C   s   | j jS rQ   rY   r
  rr   r$   r$   r%   r    s    z.IdeficsForVisionText2Text.get_input_embeddingsc                 C   s   || j _d S rQ   r/  r  r$   r$   r%   r    s    z.IdeficsForVisionText2Text.set_input_embeddingsc                 C   s   | j S rQ   r.  rr   r$   r$   r%   get_output_embeddings  s    z/IdeficsForVisionText2Text.get_output_embeddingsc                 C   s
   || _ d S rQ   r0  )ri   Znew_embeddingsr$   r$   r%   set_output_embeddings  s    z/IdeficsForVisionText2Text.set_output_embeddingsc                 C   s
   || _ d S rQ   rY   )ri   decoderr$   r$   r%   set_decoder  s    z%IdeficsForVisionText2Text.set_decoderc                 C   s   | j S rQ   r3  rr   r$   r$   r%   get_decoder  s    z%IdeficsForVisionText2Text.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   ry   r_   rz   rf   N)r1  r  getattrr   rg   rf   rz   AssertionErrorrh   r|   r   r_   ry   )ri   Zoutput_embeddingsZinput_embeddingsr$   r$   r%   tie_weights  s    
 z%IdeficsForVisionText2Text.tie_weights)output_typer  F)r8   r/   rB   r   r  r*   r+   r,   r-   labelsrD   r   r  rC   r  r^   c                 C   sx  |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  }t }||d|	d|d}|s\|f|dd  }|dk	rX|f| S |S t
|||j|j|j|jdS )a  
        Args:
            labels (`torch.LongTensor` 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, IdeficsForVisionText2Text

        >>> model = IdeficsForVisionText2Text.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
        >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

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

        >>> # 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."
        ```N)r8   r/   rB   r   r  r*   r+   r,   r-   rD   r   r  rC   r  r   .r   r)   )r'   r(   r   r   r   r   )r   r   r  r$  rY   r.  r   r   r2   r   r&   r   r   r   r   )ri   r8   r/   rB   r   r  r*   r+   r,   r-   r;  rD   r   r  rC   r  r@   r   r(   r'   Zshift_attention_maskZshift_logitsZshift_labelsZloss_fctr~   r$   r$   r%   ro     sV    .

"z!IdeficsForVisionText2Text.forwardc                 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   r,   r+   r*   pastr.   )popr   r  rI   )ri   r8   r<  rH   r   inputsZunwanted_kwargskwargr$   r$   r%   rI     s    
z7IdeficsForVisionText2Text.prepare_inputs_for_generationc                  O   s
   t | |S rQ   )r;   )argsr:   r$   r$   r%   _expand_inputs_for_generation)  s    z7IdeficsForVisionText2Text._expand_inputs_for_generationc                 C   s
   t | |S rQ   )rA   )r@   r:   r9   r$   r$   r%   #_update_model_kwargs_for_generation0  s    z=IdeficsForVisionText2Text._update_model_kwargs_for_generationc                    s.   d}| D ] }|t  fdd|D f7 }q|S )Nr$   c                 3   s   | ]}| d  V  qdS )r   N)r6   )rM   Z
past_statebeam_idxr$   r%   rU   8  s     z;IdeficsForVisionText2Text._reorder_cache.<locals>.<genexpr>)r*  )r<  rD  Zreordered_pastZ
layer_pastr$   rC  r%   _reorder_cache4  s    z(IdeficsForVisionText2Text._reorder_cache)N)NNNNNNNNNNNNNFN)N)"r   r   r   Z_keys_to_ignore_on_load_missingZ_tied_weights_keysre   r  r  r1  r2  r5  r6  r9  r   r,  r   r&   _CONFIG_FOR_DOCr!   r   r   r   r   r"   rt   r   r   ro   rI   staticmethodrA  rB  rE  rv   r$   r$   rj   r%   r-  }  sh   
               
b


r-  )r   FNN)N)r   )N)Jr    dataclassesr   typingr   r   r   r   r!   Ztorch.nn.functionalr   r   rl   Ztorch.utils.checkpointZtorch.nnr    r
   Zactivationsr   Zmodeling_outputsr   Zmodeling_utilsr   Zpytorch_utilsr   r(  r   r   r   r   Zconfiguration_ideficsr   Z	perceiverr   Zvisionr   Z
get_loggerr   r   rF  Z%IDEFICS_PRETRAINED_MODEL_ARCHIVE_LISTr   r&   r;   rA   rI   r[   rL   r\   rK   rw   Sizera   r5   r   r   r   r   Moduler   appendr   r   r   r   r   r   r   ZLLAMA_START_DOCSTRINGr   r,  r  r-  r$   r$   r$   r%   <module>   s   
,+    
-
'nC    
  L >  f