U
    4Af	                    @   sB  d Z ddlmZ ddlmZmZ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 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.d<ddZ/d=ddZ0g fddZ1G dd  d ej2Z3G d!d" d"ej4Z5G d#d$ d$ej6Z7e8e7 G d%d& d&e
jj6Z9d'd( Z:d>d)d*Z;G d+d, d,ej6Z<G d-d. d.ej6Z=G d/d0 d0ej6Z>G d1d2 d2ej6Z?d3Z@ed4e@G d5d6 d6eZAd7ZBed4e@G d8d9 d9eAZCG d:d; d;eAZDdS )?zPyTorch Idefics model.    )	dataclass)AnyDictListOptionalTupleUnionN)nn)CrossEntropyLoss   )PreTrainedModel)ACT2FN)*_prepare_4d_causal_attention_mask_for_sdpa)ModelOutput)PretrainedConfig)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )IdeficsConfig)IdeficsPerceiverResampler)IdeficsVisionTransformerr   c                   @   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'   P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/idefics/modeling_idefics.pyr   5   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)   b   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_decoderr2   Zencoder_outputsmodel_kwargsZexpanded_return_idxr1   r'   r'   r(   expand_inputs_for_generation   s<    	,  
 r>   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 )Nr1   r,   r2   position_idsr   r   r-   r.   r/   r0   interpolate_pos_encodingF	use_cache)r;   r   rA   r?   r2   r1   r-   r.   r/   r0   r@   )r:   	unsqueezelongcumsummasked_fill_)r;   r   kwargsr1   r2   r?   r-   r.   r/   r0   r@   r'   r'   r(   prepare_inputs_for_generation   s:    rG   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)rK   t)moduler'   r(   	<genexpr>   s     zfreeze_model.<locals>.<genexpr>TF)r	   rH   rI   rJ   modulesanyrequires_grad_)modelmodule_exceptionsZmodule_exceptions_mappedr'   )rM   rR   r(   freeze_model   s    rY   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_dimr8   dtypepadding_idxFr   )r]   r^   r8   r_   )
ValueErrorsuper__init__r]   r`   num_additional_embeddingsr[   weightrV   r	   rJ   additional_embedding)	selfr]   rd   r^   r[   r8   r_   r`   rF   	__class__r'   r(   rc      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   )	rd   FZ	embeddingre   cloner$   wherer]   rf   )rg   r;   Zadditional_vocab_indicesZinput_ids_additional_vocabZadditional_embeddingsZfull_vectorr'   r'   r(   forward-  s    
z!IdeficsDecoupledEmbedding.forwardr\   c                 C   s   d | j| j| j| jS )NzVnum_embeddings={}, num_additional_embeddings={}, embedding_dim={}, partially_freeze={})formatr]   rd   r^   r[   rg   r'   r'   r(   
extra_reprT  s    z$IdeficsDecoupledEmbedding.extra_repr)FNNN)r    r!   r"   r#   r   boolrc   rm   strrq   __classcell__r'   r'   rh   r(   rZ      s       5'rZ   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   )rv   rw   ry   r8   r_   N)rb   rc   rx   r[   rv   rw   re   rV   ry   r	   rI   additional_fc)rg   rv   rw   rx   ry   r[   r8   r_   rh   r'   r(   rc   f  s"    zIdeficsDecoupledLinear.__init__)inputr\   c                 C   s:   t || j| j}| jdkr6| |}t||fd}|S )Nr   r,   )rj   Zlinearre   ry   rx   rz   r$   cat)rg   r{   outputZadditional_featuresr'   r'   r(   rm     s
    

zIdeficsDecoupledLinear.forwardrn   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)ro   rv   rw   rx   ry   r[   rp   r'   r'   r(   rq     s    z!IdeficsDecoupledLinear.extra_repr)r   TTNN)r    r!   r"   r#   intrr   rc   r$   Tensorrm   rs   rq   rt   r'   r'   rh   r(   ru   ]  s         $	ru   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	IdeficsRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        IdeficsRMSNorm is equivalent to T5LayerNorm
        N)rb   rc   r	   	Parameterr$   onesre   variance_epsilon)rg   hidden_sizeepsrh   r'   r(   rc     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)r7   r$   Zfloat32powmeanZrsqrtr   re   r_   Zfloat16Zbfloat16)rg   r   Zvariancer'   r'   r(   rm     s
    zIdeficsRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tuplere   r4   r   rp   r'   r'   r(   rq     s    zIdeficsRMSNorm.extra_repr)r   )r    r!   r"   rc   rm   rq   rt   r'   r'   rh   r(   r     s   
r   c                       s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )IdeficsEmbedding   '  Nc                    sx   t    || _|| _|| _d| jtjd| jdtjd 	|| j   }| j
d|dd | j|| jjt d d S )	Ng      ?r   r   r_   inv_freqF
persistentseq_lenr8   r_   )rb   rc   dimmax_position_embeddingsbaser$   r3   int64floatr7   register_buffer_set_cos_sin_cacher   r8   Zget_default_dtype)rg   r   r   r   r8   r   rh   r'   r(   rc     s    
0  zIdeficsEmbedding.__init__c                 C   s|   || _ tj| j |tjd| j}td|| j}tj||fdd}| jd|	 
|dd | jd| 
|dd d S )	N)r8   r_   zi,j->ijr,   r   
cos_cachedFr   
sin_cached)max_seq_len_cachedr$   r3   r   Ztype_asr   Zeinsumr|   r   cosr7   sin)rg   r   r8   r_   rQ   ZfreqsZembr'   r'   r(   r     s    z#IdeficsEmbedding._set_cos_sin_cachec                 C   sN   || j kr| j||j|jd | jd | j|jd| jd | j|jdfS )Nr   r   )r   r   r8   r_   r   r7   r   )rg   xr   r'   r'   r(   rm     s
    
zIdeficsEmbedding.forward)r   r   N)N)r    r!   r"   rc   r   rm   rt   r'   r'   rh   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   )r4   r$   r|   )r   x1Zx2r'   r'   r(   rotate_half  s    r   c                 C   sL   ||  |}||  |}| | t| |  }|| t||  }||fS )an  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )rB   r   )qkr   r   r?   Zunsqueeze_dimZ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ry   )	rb   rc   r	   rI   	gate_proj	down_projup_projr   act_fn)rg   r   r   r   rh   r'   r(   rc     s
    
zIdeficsMLP.__init__c                 C   s    |  | | || | S rO   )r   r   r   r   )rg   r   r'   r'   r(   rm     s    zIdeficsMLP.forward)r    r!   r"   r~   rs   rc   rm   rt   r'   r'   rh   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    || _|| _|| | _|| _d| _| j| | jkrTtd| j d| d|| _t	t
jdsnt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r~t| j|jd
| _t| j|jd
| _d S )NTz?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   )rb   rc   r   r   head_dimr   	is_causalra   r   hasattrr	   
functionalvision_configr   rI   q_projk_projv_projo_projr   
rotary_embr   r   rms_norm_epsq_layer_normk_layer_norm)rg   r   r   r   r   r   r   Zkv_input_dimrh   r'   r(   rc     sh    	


zIdeficsAttention.__init__)tensorr   bszc                 C   s    | ||| j| jdd S )Nr   r   )r5   r   r   	transpose
contiguous)rg   r   r   r   r'   r'   r(   _shape^  s    zIdeficsAttention._shape)r   key_value_statesr2   r?   past_key_valueoutput_attentionsrA   r\   c                 C   s  | 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|  |jjd	kr|d k	r| }| }| }| jr$|d kr$|
dkr$d
nd}tjjj||||| jrF| jnd|d}| |	| j|
| jfkrtd|	| j|
| jf d|  |dd}||	|
| j}| |}d }|rt d |||fS )Nr   r   r   )r   r   z!Attention mask should be of size z	, but is ZcudaTFr   )Z	attn_maskZ	dropout_pr   z `attn_output` should be of size z^attn_weights are not extracted in scaled_dot_product_attention. The model returns None instead)!r   sizer   r5   r   r   r   r   r   r4   r   maxr   r$   r|   r   r   r   ra   r8   typer   r   r	   r   r   trainingr   Zreshaper   r   loggerwarning_once)rg   r   r   r2   r?   r   r   rA   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(   rm   a  sl    ""$" 




$	
zIdeficsAttention.forward)r   FNF)NNNNFF)r    r!   r"   r#   r~   r   rr   r   rc   r$   r   r   r   
LongTensorr   rm   rt   r'   r'   rh   r(   r     s<       F      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   )rb   rc   r   r   num_attention_headsr   	self_attnr   r   r   mlpr   r   input_layernormpost_attention_layernormrg   r   rh   r'   r(   rc     s     
zIdeficsDecoderLayer.__init__NF)r   r2   r?   r   r   rA   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   r2   r?   r   r   rA   pr   )r   r   r	   r   r   r   r   r   )rg   r   r2   r?   r   r   rA   residualself_attn_weightspresent_key_valueoutputsr'   r'   r(   rm     s.    




zIdeficsDecoderLayer.forward)NNNFF)r    r!   r"   r   rc   r$   r   r   r   r   rr   r%   rm   rt   r'   r'   rh   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j ee ee ee	ej  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   zerosZvectorr   r   z Unknown value for `alpha_type` ()r   >   gaussiannormalrandomr   )r   stdr   zAlpha initialization scheme z not yet implemented!alpha_cross_attnalpha_densez+Alpha parameters not initialized correctly!)"rb   rc   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   ra   r   r   Zalphas_initializer_rangeNotImplementedErrorr   r   rh   r'   r(   rc     sj    




z(IdeficsGatedCrossAttentionLayer.__init__NF)	r   r2   r   r0   cross_attention_gater   rA   r   r\   c	                 C   s  |dkrt d|dkr t d|dk	r0td|}	| |}| j||||d\}}
}tjj|| j| jd}||dk 	d||dk< |	| 
| 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.
            image_attention_mask (`torch.FloatTensor`, *optional*): image attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            cross_attention_gate (`torch.FloatTensor`, *optional*):
                gate of size `(batch, seq_len)` used to zero-out cross-attention output for tokens attending no images.
            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
        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   r2   r   r   r   )ra   r   r   r   r	   r   r   r   r   Zfill_r   r   r   r   r   r   )rg   r   r2   r   r0   r   r   rA   r   r   r   r   r   r'   r'   r(   rm   L  s@    




z'IdeficsGatedCrossAttentionLayer.forward)NNNNFFN)r    r!   r"   r   rc   r$   r   r   rr   r   r%   rm   rt   r'   r'   rh   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                   @   sB   e Zd ZeZdZdZddgZdZdd Z	e
deedd	d
ZdS )IdeficsPreTrainedModelrW   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_rangerP   r	   rI   re   dataZnormal_ry   Zzero_rJ   r`   )rg   rR   r   r'   r'   r(   _init_weights  s    

z$IdeficsPreTrainedModel._init_weightsF)hard_check_onlyr\   c                 C   s"   t | dd}|r|S |sd|_|S )NZuse_bettertransformerFZsdpa)getattrZ_attn_implementation)clsr   r   Z_is_bettertransformerr'   r'   r(   _check_and_enable_sdpa  s    z-IdeficsPreTrainedModel._check_and_enable_sdpaN)F)r    r!   r"   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_sdpar   classmethodrr   r   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
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 )IdeficsModelz
    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 S )N)r]   rd   r^   r[   r`   c                    s   g | ]}t  qS r'   )r   rK   r   r   r'   r(   rN   7  s     z)IdeficsModel.__init__.<locals>.<listcomp>c                    s   g | ]}t  qS r'   )r   r   r   r'   r(   rN   <  s     Fr   )%rb   rc   r   Zpad_token_idr`   
vocab_sizerZ   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_layersgradient_checkpointingr   r   norm	post_initfreeze_relevant_params)rg   r   r  Znum_cross_layersrh   r   r(   rc     sD    
	 zIdeficsModel.__init__Nc                 C   s:   |d kr| j }|jr | |j |jr6t| j|jd d S N)rX   )r   r  Zfreeze_text_module_exceptionsfreeze_vision_layersrY   r  Zfreeze_vision_module_exceptionsr   r'   r'   r(   r  G  s    z#IdeficsModel.freeze_relevant_paramsc                 C   s"   | j | jfD ]}t||d qd S r  )r  r  rY   )rg   rX   rR   r'   r'   r(   r  Q  s    zIdeficsModel.freeze_text_layersc                 C   s   t | j|d d S r  )rY   r  )rg   rX   r'   r'   r(   r  U  s    z!IdeficsModel.freeze_vision_layersc                 C   s   | j S rO   r  rp   r'   r'   r(   get_input_embeddingsX  s    z!IdeficsModel.get_input_embeddingsc                 C   s
   || _ d S rO   r  rg   valuer'   r'   r(   set_input_embeddings[  s    z!IdeficsModel.set_input_embeddingsF)r;   r2   r?   r   inputs_embedsr-   r.   r/   r0   rA   r   output_hidden_statesr@   return_dictr\   c           (      C   s$  |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>tj||| tj|d}|d}|||fd dkr^tdn|d k	r|j| j|d}|jd d \}}| j|| f|jdd   }| j||d	j}n<|d k	r| \}}}}|j| j|d}||| ||}| jjrF|d kr0| |}|d|d }}n| \}}}}|}n*|d krh|d|d }}ntd
|||| |}|	d}|	d}	|	ddd|}	|	|||| }	|d k	r| \}}}||f}|	d krtj||d}	| |	}	nd }	|	dkjddj| jdjdd|}|d kr<| |}|d kr^tj||ftj|j d}t|||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 rT| j!rTd }$|
r*t"#d d}
| &|%|#||||$||	|||
|"| j'| j(}&n&|%|#||||$||	|||
|"| j'| j(d}&|&d }|
r|!|&|rdnd f7 }!|r| |&d f7 } q| )|}|r||f7 }|
r|!nd }'|||||}|st*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_   r8   z_Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None.)r-   r@   zBIf `perceiver_embeddings` are passed, use_resampler should be True)r8   r   r   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr'   c              
   S   sP   |
| dkr8||
|  }||||||||	d d}|d }| ||||||	d}|S )Nr   )r2   r   r0   r   r   rA   r   )r2   r?   r   r   rA   r'   )Z
main_blockr   r2   r?   r   r   r0   r   r   rA   	layer_idxr	  r
  Zxblockr   layer_outputsr'   r'   r(   vblock  s,    
	z$IdeficsModel.forward.<locals>.vblock)r2   r?   r   r   r0   r   r   rA   r  r	  r
  c                 s   s   | ]}|d k	r|V  qd S rO   r'   )rK   vr'   r'   r(   rS   R  s   z'IdeficsModel.forward.<locals>.<genexpr>)r   r   r   r   r   ),r8   r   r   r  rA   use_return_dictra   r4   rC   rD   rE   r$   r3   rB   countr7   r_   r   r5   r  r   r   r  r  r6   r   Zinvert_attention_maskrU   Zsqueezer  rr   r   r  r   r   r   	enumerater  Z_gradient_checkpointing_funcr	  r
  r  r   r   )(rg   r;   r2   r?   r   r  r-   r.   r/   r0   rA   r   r  r@   r  r8   Z
batch_sizeZ
seq_lengthr   Zseq_length_with_pastZpast_key_values_lengthZ
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  r  Z
next_cacher'   r'   r(   rm   ^  s:   

   

" 









"


     
)

zIdeficsModel.forward)N)NNNNNNNNNNNNFN)r    r!   r"   r#   r   rc   r  r  r  r  r  r   LLAMA_INPUTS_DOCSTRINGr$   r   r   r   r   r%   rr   r   r   r   rm   rt   r'   r'   rh   r(   r     sN   .

              
r   c                       sL  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d%ee e!e"f eee e!e"f d f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)rv   rw   rx   ry   r[   )rb   rc   r   rW   ru   r   r   r   Zfreeze_lm_headlm_headr  )rg   r   r  rh   r'   r(   rc   d  s    
	z"IdeficsForVisionText2Text.__init__c                 C   s   | j jS rO   rW   r  rp   r'   r'   r(   r  s  s    z.IdeficsForVisionText2Text.get_input_embeddingsc                 C   s   || j _d S rO   r$  r  r'   r'   r(   r  v  s    z.IdeficsForVisionText2Text.set_input_embeddingsc                 C   s   | j S rO   r#  rp   r'   r'   r(   get_output_embeddingsy  s    z/IdeficsForVisionText2Text.get_output_embeddingsc                 C   s
   || _ d S rO   r%  )rg   Znew_embeddingsr'   r'   r(   set_output_embeddings|  s    z/IdeficsForVisionText2Text.set_output_embeddingsc                 C   s
   || _ d S rO   rW   )rg   decoderr'   r'   r(   set_decoder  s    z%IdeficsForVisionText2Text.set_decoderc                 C   s   | j S rO   r(  rp   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   rw   r]   rx   rd   N)r&  r  r   r   re   rd   rx   AssertionErrorrf   rz   r   r]   rw   )rg   Zoutput_embeddingsZinput_embeddingsr'   r'   r(   tie_weights  s    
 z%IdeficsForVisionText2Text.tie_weights)output_typer   F)r;   r2   r?   r   r  r-   r.   r/   r0   labelsrA   r   r  r@   r  r\   c                 C   s  |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@|
|j}
|dk	r|dddf |j}|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}|sp|f|dd  }|dk	rl|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 AutoProcessor, IdeficsForVisionText2Text

        >>> model = IdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
        >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b")

        >>> dogs_image_url_1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg"
        >>> dogs_image_url_2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg"

        >>> prompts = [
        ...     [
        ...         "User:",
        ...         dogs_image_url_1,
        ...         "Describe this image.\nAssistant: An image of two dogs.\n",
        ...         "User:",
        ...         dogs_image_url_2,
        ...         "Describe this image.\nAssistant:",
        ...     ]
        ... ]
        >>> inputs = processor(prompts, return_tensors="pt")
        >>> generate_ids = model.generate(**inputs, max_new_tokens=6)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True)
        ```N)r;   r2   r?   r   r  r-   r.   r/   r0   rA   r   r  r@   r  r   .r   r,   )r*   r+   r   r   r   r   )r   r   r  r  rW   r#  r7   r8   r   r
   r5   r   r)   r   r   r   r   )rg   r;   r2   r?   r   r  r-   r.   r/   r0   r/  rA   r   r  r@   r  r   r   r+   r*   Zshift_attention_maskZshift_logitsZshift_labelsZloss_fctr}   r'   r'   r(   rm     sX    7

"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-   pastr1   )popr   r  rG   )rg   r;   r0  rF   r   inputsZunwanted_kwargskwargr'   r'   r(   rG     s    
z7IdeficsForVisionText2Text.prepare_inputs_for_generationc                  O   s
   t | |S rO   )r>   )argsr=   r'   r'   r(   _expand_inputs_for_generation  s    z7IdeficsForVisionText2Text._expand_inputs_for_generation)r   r=   r<   standardize_cache_formatr\   c                    sT   t  ||||}d|krF|d }|d d dd d f d}||d< |j|d< |S )Nr0   r,   r   r   )rb   #_update_model_kwargs_for_generationrB   r   )rg   r   r=   r<   r6  r0   Z	last_maskrh   r'   r(   r7    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)r9   )rK   Z
past_statebeam_idxr'   r(   rS   8  s     z;IdeficsForVisionText2Text._reorder_cache.<locals>.<genexpr>)r   )r0  r9  Zreordered_pastZ
layer_pastr'   r8  r(   _reorder_cache4  s    z(IdeficsForVisionText2Text._reorder_cache)N)NNNNNNNNNNNNNFN)N)FF)&r    r!   r"   Z_keys_to_ignore_on_load_missingZ_tied_weights_keysrc   r  r  r&  r'  r*  r+  r-  r   r!  r   r)   _CONFIG_FOR_DOCr$   r   r   r   r   r%   rr   r   r   rm   rG   staticmethodr5  r   r   rs   r   r7  r:  rt   r'   r'   rh   r(   r"  `  sv   
               
l


  

r"  )r   FNN)N)r   )Er#   Zdataclassesr   typingr   r   r   r   r   r   r$   Ztorch.nn.functionalr	   r   rj   Ztorch.utils.checkpointZtorch.nnr
    r   Zactivationsr   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   r   r   Zconfiguration_ideficsr   Z	perceiverr   Zvisionr   Z
get_loggerr    r   r;  r   r)   r>   rG   rY   rJ   rZ   rI   ru   Moduler   appendr   r   r   r   r   r   r   ZLLAMA_START_DOCSTRINGr   r!  r   r"  r'   r'   r'   r(   <module>   st    
,+    
-
'nB
$
 *L ">  Q