o
    Zh                     @   s  d Z ddlmZ ddlmZmZmZmZmZ ddl	Z	ddl
Z	ddl	mZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ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'm(Z(m)Z) e#*e+Z,eG dd deZ-eG dd deZ.G dd dej/Z0	dOdej/de	j1de	j1de	j1dee	j1 d e2d!e2fd"d#Z3G d$d% d%ej/Z4G d&d' d'ej/Z5G d(d) d)ej/Z6G d*d+ d+ej/Z7G d,d- d-ej/Z8G d.d/ d/ej/Z9e!G d0d1 d1eZ:e!d2d3G d4d5 d5e:Z;d6e	j1d7e<d8e	j1fd9d:Z=G d;d< d<ej/Z>G d=d> d>ej/Z?G d?d@ d@ej/Z@e!dAd3G dBdC dCe:ZAG dDdE dEej/ZBe!dFd3G dGdH dHe:ZCG dIdJ dJee ZDe!dKd3G dLdM dMe:eZEg dNZFdS )PzPyTorch Idefics2 model.    )	dataclass)CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)_prepare_4d_attention_mask)FlashAttentionKwargs)BaseModelOutputModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tuplelogging   )	AutoModel   )Idefics2ConfigIdefics2PerceiverConfigIdefics2VisionConfigc                   @   s   e Zd ZU dZdZe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 )Idefics2BaseModelOutputWithPasta	  
    Base class for Idefics2 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    r   torchFloatTensor__annotations__r!   r   r"   r#   r$    r,   r,   ]/var/www/auris/lib/python3.10/site-packages/transformers/models/idefics2/modeling_idefics2.pyr   (   s   
 r   c                   @   s   e Zd ZU dZdZeej ed< dZ	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Zeeej  ed< dS )	Idefics2CausalLMOutputWithPasta  
    Base class for Idefics2 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+   r0   r!   r   r"   r   r#   r$   r,   r,   r,   r-   r.   O   s   
 r.   c                       sB   e Zd ZdZdef fddZdejdejdej	fdd	Z
  ZS )
Idefics2VisionEmbeddingsaP  
    This is a modified version of `siglip.modelign_siglip.SiglipVisionEmbeddings` to enable images of variable
    resolution.

    The modifications are adapted from [Patch n' Pack: NaViT, a Vision Transformer for any Aspect Ratio and Resolution](https://arxiv.org/abs/2307.06304)
    which allows treating images in their native aspect ratio and without the need to resize them to the same
    fixed size. In particular, we start from the original pre-trained SigLIP model
    (which uses images of fixed-size square images) and adapt it by training on images of variable resolutions.
    configc                    sx   t    |j| _|j| _|j| _tj|j| j| j| jdd| _	| j| j | _
| j
d | _| j| _t| j| j| _d S )NZvalid)Zin_channelsZout_channelsZkernel_sizeZstridepaddingr   )super__init__hidden_size	embed_dimZ
image_size
patch_sizer   Conv2dnum_channelspatch_embeddingnum_patches_per_sideZnum_patchesZnum_positions	Embeddingposition_embeddingselfr2   	__class__r,   r-   r5      s   
z!Idefics2VisionEmbeddings.__init__pixel_valuespatch_attention_maskreturnc                 C   s<  |j \}}}}| |}|ddd}|| j || j }	}
td| j dd| j }tj||	|
 fdd}t	|D ]P\}}|d d df 
 }|d 
 }tddd| }tddd| }tj||dd}tj||dd}|d d d f | j |  }||| |d	 < q<|| jjj}|| | }|S )
Nr   r         ?r   )sizeZ
fill_valueg!?T)right)shaper;   flatten	transposer8   r)   Zaranger<   full	enumeratesumZ	bucketizeviewcputor>   weightdevice)r@   rC   rD   
batch_size_Zmax_im_hZmax_im_wZpatch_embeds
embeddingsZmax_nb_patches_hZmax_nb_patches_wZ
boundariesposition_idsZ	batch_idxZp_attn_maskZnb_patches_hZnb_patches_wZfractional_coords_hZfractional_coords_wZbucket_coords_hZbucket_coords_wZpos_idsr,   r,   r-   forward   s$   
z Idefics2VisionEmbeddings.forward)r%   r&   r'   r(   r   r5   r)   r*   
BoolTensorTensorrY   __classcell__r,   r,   rA   r-   r1   u   s    
$r1           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t | drt|| j}t|| j}t||dd| }|d ur8|d d d d d d d |jd f }	||	 }tjj	|dtj
d|j}tjj||| jd}t||}
|
dd }
|
|fS )	Nnum_key_value_groupsr   r	   rI   )dimdtype)ptrainingr   )hasattr	repeat_kvre   r)   matmulrL   rJ   r   Z
functionalZsoftmaxfloat32rR   rh   rd   rj   
contiguous)r^   r_   r`   ra   rb   rc   rd   kwargsattn_weightsZcausal_maskattn_outputr,   r,   r-   eager_attention_forward   s   

&rs   c                       s\   e Zd ZdZ fddZ		ddejdeej dee d	e	ejeej f fd
dZ
  ZS )Idefics2VisionAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    s   t    || _|j| _|j| _| j| j | _| j| j | jkr-td| j d| j d| jd | _	|j
| _t| j| j| _t| j| j| _t| j| j| _t| j| j| _d| _d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).      F)r4   r5   r2   r6   r7   num_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutrd   r   Lineark_projv_projq_projout_proj	is_causalr?   rA   r,   r-   r5      s$   


z Idefics2VisionAttention.__init__NFr"   rb   output_attentionsrE   c              
   C   s  |j \}}}| |}| |}| |}	|||| j| jdd}|||| j| jdd}|	||| j| jdd}	t}
| j	j
dkr[| j	j
dkrU|rUtd nt| j	j
 }
|
| |||	|| j| j| jsjdn| jd\}}|||| }| |}|sd}||fS )	z#Input shape: Batch x Time x Channelr   r   eagersdpa`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r]   r   rc   rd   N)rJ   r   r}   r~   rP   rw   rx   rL   rs   r2   _attn_implementationloggerwarning_oncer   r   rz   rj   rd   reshapero   r   )r@   r"   rb   r   rU   
seq_lengthr7   querieskeysvaluesattention_interfacerr   rq   r,   r,   r-   rY      s:   




zIdefics2VisionAttention.forward)NF)r%   r&   r'   r(   r5   r)   r[   r   boolr   rY   r\   r,   r,   rA   r-   rt      s    rt   c                       s2   e Zd Z fddZdejdejfddZ  ZS )Idefics2VisionMLPc                    sD   t    || _t|j | _t|j|j	| _
t|j	|j| _d S N)r4   r5   r2   r
   
hidden_actactivation_fnr   r|   r6   intermediate_sizefc1fc2r?   rA   r,   r-   r5     s
   
zIdefics2VisionMLP.__init__r"   rE   c                 C   s"   |  |}| |}| |}|S r   )r   r   r   )r@   r"   r,   r,   r-   rY     s   


zIdefics2VisionMLP.forward)r%   r&   r'   r5   r)   r[   rY   r\   r,   r,   rA   r-   r     s    r   c                       s6   e Zd Zdedededef fddZdd Z  ZS )	Idefics2MLPr6   r   output_sizer   c                    sN   t    tj||dd| _tj||dd| _tj||dd| _t| | _d S NFbias)	r4   r5   r   r|   	gate_projup_proj	down_projr
   act_fn)r@   r6   r   r   r   rA   r,   r-   r5   &  s
   
zIdefics2MLP.__init__c                 C   s    |  | | || | S r   )r   r   r   r   )r@   xr,   r,   r-   rY   3  s    zIdefics2MLP.forward)r%   r&   r'   intstrr5   rY   r\   r,   r,   rA   r-   r   %  s    r   c                       s.   e Zd ZdZdef fddZdd Z  ZS )%Idefics2MultiheadAttentionPoolingHeadzMultihead Attention Pooling.r2   c                    sl   t    ttdd|j| _tjj|j|j	dd| _
tj|j|jd| _t|j|j|j|jd| _d S )Nr   T)Zbatch_firsteps)r6   r   r   r   )r4   r5   r   	Parameterr)   Zrandnr6   probeMultiheadAttentionrv   	attention	LayerNormlayer_norm_eps	layernormr   r   r   mlpr?   rA   r,   r-   r5   ;  s   
z.Idefics2MultiheadAttentionPoolingHead.__init__c                 C   sX   |j d }| j|dd}| |||d }|}| |}|| | }|d d df S )Nr   r   )rJ   r   repeatr   r   r   )r@   Zhidden_staterU   r   residualr,   r,   r-   rY   I  s   

z-Idefics2MultiheadAttentionPoolingHead.forward)r%   r&   r'   r(   r   r5   rY   r\   r,   r,   rA   r-   r   8  s    r   c                
       sN   e Zd Zdef fddZ	ddejdejdee de	ej
 fd	d
Z  ZS )Idefics2EncoderLayerr2   c                    sR   t    |j| _t|| _tj| j|jd| _	t
|| _tj| j|jd| _d S )Nr   )r4   r5   r6   r7   rt   	self_attnr   r   r   layer_norm1r   r   layer_norm2r?   rA   r,   r-   r5   W  s   


zIdefics2EncoderLayer.__init__Fr"   rb   r   rE   c                 C   sb   |}|  |}| j|||d\}}|| }|}| |}| |}|| }|f}|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`):
                Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*, defaults to `False`):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r"   rb   r   )r   r   r   r   )r@   r"   rb   r   r   rq   outputsr,   r,   r-   rY   `  s    




zIdefics2EncoderLayer.forward)F)r%   r&   r'   r   r5   r)   r[   r   r   r   r*   rY   r\   r,   r,   rA   r-   r   V  s    r   c                       sh   e Zd ZdZdef fddZ				ddeej dee	 dee	 d	ee	 d
e
eef f
ddZ  ZS )Idefics2Encoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Idefics2EncoderLayer`].

    Args:
        config: Idefics2Config
    r2   c                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r,   )r   ).0rV   r2   r,   r-   
<listcomp>  s    z,Idefics2Encoder.__init__.<locals>.<listcomp>F)	r4   r5   r2   r   
ModuleListrangeZnum_hidden_layerslayersgradient_checkpointingr?   rA   r   r-   r5     s   
 
zIdefics2Encoder.__init__Nrb   r   output_hidden_statesreturn_dictrE   c                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}|r"dnd}|r(dnd}|}| jD ]-}	|r8||f }| jrH| jrH| |	j|||}
n|	|||d}
|
d }|r\||
d f }q/|rd||f }|srt	dd |||fD S t
|||dS )	ad  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                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.
            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)
            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.
        Nr,   )r   r   r   c                 s   s    | ]	}|d ur|V  qd S r   r,   )r   vr,   r,   r-   	<genexpr>  s    z*Idefics2Encoder.forward.<locals>.<genexpr>r    r"   r#   )r2   r   r   use_return_dictr   r   rj   Z_gradient_checkpointing_func__call__tupler   )r@   inputs_embedsrb   r   r   r   Zencoder_statesZall_attentionsr"   Zencoder_layerlayer_outputsr,   r,   r-   rY     sB   


zIdefics2Encoder.forwardNNNN)r%   r&   r'   r(   r   r5   r   r)   r[   r   r   r   r   rY   r\   r,   r,   rA   r-   r     s$    

r   c                   @   s@   e Zd ZeZdZdZg dZdZdZ	dZ
dZdZdZdd ZdS )Idefics2PreTrainedModelmodelT)rt   r   Idefics2PerceiverLayerZIdefics2DecoderLayerr!   c                 C   s2  t | jd| j j}t|tjtjfr,|jj	j
d|d |jd ur*|jj	  d S d S t|tjrM|jj	j
d|d |jd urK|jj	|j   d S d S t|tjrb|jj	d |jj	  d S t|trp|jj	d d S t|tjr||  d S t|tr|jj	
  d S t|tr|jj	d d S d S )Ninitializer_ranger]   )meanstdrF   )getattrr2   Zget_text_configr   
isinstancer   r|   r9   rS   dataZnormal_r   Zzero_r=   padding_idxr   Zfill_Idefics2RMSNormr   Z_reset_parametersr   r   Idefics2PerceiverResamplerlatents)r@   r^   r   r,   r,   r-   _init_weights  s.   




z%Idefics2PreTrainedModel._init_weightsN)r%   r&   r'   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2_supports_sdpa_supports_flex_attnZ_supports_cache_classZ_supports_attention_backendr   r,   r,   r,   r-   r     s    r   zK
    Idefics2 vision encoder model that returnss raw image embeddings.
    Zcustom_introc                       s   e Zd ZeZdZdZdZdef fddZdd Z	dd Z
e								dd
eej dee dee dee deeef f
ddZ  ZS )Idefics2VisionTransformerTr2   c                    sN   t  | |j}|| _t|| _t|| _tj	||j
d| _|jdk| _d S )Nr   flash_attention_2)r4   r5   r6   r2   r1   rW   r   encoderr   r   r   post_layernormr   _use_flash_attention_2)r@   r2   r7   rA   r,   r-   r5     s   

z"Idefics2VisionTransformer.__init__c                 C      | j S r   rW   r@   r,   r,   r-   get_input_embeddings     z.Idefics2VisionTransformer.get_input_embeddingsc                 C   
   || _ d S r   r   r@   ra   r,   r,   r-   set_input_embeddings     
z.Idefics2VisionTransformer.set_input_embeddingsNrD   r   r   r   rE   c                 C   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|d}|du rF| j j}t||d| |d| f}|jtj	|j
d}| j||d}||d}t| s\d}n	| jset||j}| j|||||d}	|	d }
| |
}
|s|
f|	d	d  S t|
|	j|	jd
S )z
        patch_attention_mask (`torch.BoolTensor` of shape `(batch_size, num_patches_height, num_patches_width)`, *optional*):
            The attention mask for the patches.
        Nr   r   r	   rh   rT   rC   rD   rI   )r   rb   r   r   r   r   r   )r2   r   r   r   rG   r8   r)   onesrR   r   rT   rW   rP   anyr   r   rh   r   r   r   r"   r#   )r@   rC   rD   r   r   r   rU   r8   r"   Zencoder_outputsr    r,   r,   r-   rY      sH   

z!Idefics2VisionTransformer.forwardr   )r%   r&   r'   r   r   r   _supports_flash_attention_2r   r5   r   r   r   r   r)   rZ   r   r   r   r   rY   r\   r,   r,   rA   r-   r     s0    

r   r"   n_reprE   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rJ   expandr   )r"   r   batchnum_key_value_headsslenrx   r,   r,   r-   rl   `  s
   0rl   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	r   ư>c                    s&   t    tt|| _|| _dS )z>
        Idefics2RMSNorm is equivalent to T5LayerNorm
        N)r4   r5   r   r   r)   r   rS   variance_epsilon)r@   r6   r   rA   r,   r-   r5   n  s   

zIdefics2RMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr   rI   T)Zkeepdim)	rh   rR   r)   rn   powr   Zrsqrtr   rS   )r@   r"   Zinput_dtypeZvariancer,   r,   r-   rY   v  s
   zIdefics2RMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   rS   rJ   r   r   r,   r,   r-   
extra_repr}  s   zIdefics2RMSNorm.extra_repr)r   )r%   r&   r'   r5   rY   r   r\   r,   r,   rA   r-   r   m  s    r   c                       s   e Zd Zddee ddf fddZ					ddejdejd	eej d
eej dee	ej  de
de
de	ejeej ee	ej  f fddZ  ZS )Idefics2PerceiverAttentionN	layer_idxrE   c                    s   t    || _d| _|j| _|j| _|j| _|j	| _	| j| j	 | _
|j| _| jd | _tj| j| j| j dd| _tj| j| j	| j dd| _tj| j| j	| j dd| _tj| j| j | jdd| _d| _dS )ziPerceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`Nru   Fr   )r4   r5   r2   r   r6   Zresampler_n_headsrw   Zresampler_head_dimrx   r   re   r{   rc   r   r|   r   r}   r~   o_projr   r@   r2   r   rA   r,   r-   r5     s   

z#Idefics2PerceiverAttention.__init__Fr   contextrb   rX   past_key_valuer   	use_cachec              
   C   s`  |  \}}	}
|	|  d  }tj||gdd}| |}| |}| |}|||	| j| j	dd}|||| j
| j	dd}|||| j
| j	dd}t| d|}|dure|||| j\}}t}| jjdkr| jjdkr{|r{td	 nt| jj }|| ||||| j| j| jsd
n| jd\}}|||	| j| j }| |}|sd}|||fS )a  
        Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension!

        Args:
            latents (`torch.Tensor`): Tensor of shape [bsz, n_latents, embed_dim] representing fixed length latents to compress to.
            context (`torch.Tensor`): Tensor of shape [bsz, seq, embed_dim] representing long-form context to resample.
            attention_mask (`torch.Tensor`, *optional*): Tensor of shape [bsz, 1, seq, n_latents] representing attention mask.
            position_ids (`torch.LongTensor`, *optional*): Tensor of shape [bsz, seq] representing position indices of each input token.
            past_key_value (`Tuple[torch.Tensor]`, *optional*): Tuple of tensors containing cached key and value states.
            output_attentions (`bool`, *optional*, defaults to `False`): Whether to return attention weights.
            use_cache (`bool`, *optional*, defaults to `False`): Whether to use past_key_value for caching.
        r   rf   rg   r   r   Nr   r   r   r]   r   )rG   r)   concatr   r}   r~   rP   rw   rx   rL   r   r   updater   rs   r2   r   r   r   r   r   rc   rj   r{   r   r   )r@   r   r   rb   rX   r   r   r   ZbszZq_lenrV   Z
kv_seq_lenr"   r   r   r   r   rr   rq   r,   r,   r-   rY     sD   





z"Idefics2PerceiverAttention.forwardr   NNNFF)r%   r&   r'   r   r   r5   r)   r[   
LongTensorr   r   rY   r\   r,   r,   rA   r-   r     s0    	r   c                       s   e Zd Zdef fddZ					ddejdejdeej d	eej d
ee	ej  dee
 dee
 de	ejee	ejejf  f fddZ  ZS )r   r   c                    s   t    |j| _|j| _|j| _|j| _t| j| jd| _	t| j| jd| _
t||d| _t| j| jd| _t|j|jd |j|jd| _d S )Nr   )r      r6   r   r   r   )r4   r5   r6   resampler_n_latents	n_latentsresampler_depthdepthrms_norm_epsr   input_latents_norminput_context_normr   r   post_attention_layernormr   r   r   r   rA   r,   r-   r5     s   
zIdefics2PerceiverLayer.__init__NFr   r   rb   rX   r   r   r   rE   c                 K   s|   |}	|  |}| |}| j|||d\}}
}|	| }|}	| |}| |}|	| }|f}|r5||
f7 }|r<||f7 }|S )a  
        Args:
            latents (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            context (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            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  r   r  r   )r@   r   r   rb   rX   r   r   r   rp   r   Zself_attn_weightsZpresent_key_valuer   r,   r,   r-   rY     s&   





zIdefics2PerceiverLayer.forwardr  )r%   r&   r'   r   r5   r)   r[   r   r  r   r   r*   rY   r\   r,   r,   rA   r-   r     s0    
r   zi
    Idefics2 perceiver resampler model that performs `depth` blocks of cross-attention with a fixed
    c                       sN   e Zd ZeZdZdZdZd
 fddZe	de
jde
jde
jfdd	Z  ZS )r   TrE   Nc                    s   t     j| _ j| _ j| _ j| _ j| _t	
t| j| j| _t	 fddt| jD | _t| j| jd| _ jdk| _d S )Nc                    s   g | ]}t  |qS r,   )r   )r   idxr   r,   r-   r   ;  s    z7Idefics2PerceiverResampler.__init__.<locals>.<listcomp>r   r   )r4   r5   r6   r   r  r  r  r  r	  r   r   r)   r   r   r   r   r   r   normr   r   r?   rA   r   r-   r5   /  s    z#Idefics2PerceiverResampler.__init__r   rb   c              
   C   s   | j d|jd g| j  R }tj|d|df|j|jd}tj	||gdd}| j
s:t||j| jdn|}|}| jD ]}||||ddddd	}|d }qA| |}|S )
zw
        context (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`):
            Input to the layer.
        r   r   r   rI   r   )Ztgt_lenNF)rb   rX   r   r   r   )r   Z	unsqueezer   rJ   rG   r)   r   rh   rT   catr   r   r  r   r  )r@   r   rb   r   Zlatent_attention_maskZcompressed_contextZperceiver_layerr   r,   r,   r-   rY   @  s.   &



z"Idefics2PerceiverResampler.forward)rE   N)r%   r&   r'   r   r   r   r   r   r5   r   r)   r[   rY   r\   r,   r,   rA   r-   r   $  s    r   c                       s$   e Zd Z fddZdd Z  ZS )Idefics2Connectorc                    s>   t    t|jj|jj|jj|jjd| _t	
|j| _d S )Nr  )r4   r5   r   vision_configr6   text_configr   r   modality_projectionr   _from_configperceiver_configperceiver_resamplerr?   rA   r,   r-   r5   k  s   
zIdefics2Connector.__init__c                 C   s   |  |}| j||d}|S )N)r   rb   )r  r  )r@   r$   rb   r,   r,   r-   rY   u  s   
zIdefics2Connector.forward)r%   r&   r'   r5   rY   r\   r,   r,   rA   r-   r  j  s    
r  z[
    Idefics2 model consisting of a SIGLIP vision encoder and Mistral language decoder
    c                #       sD  e Zd Zdef fddZdd Zdd Zdd	 Zd
d Zde	j
dee	j dee	j fddZd$de	jde	j
fddZeedd													d%dee	j
 dee	j dee	j
 deee	j  dee	j dee	j dee	j dee	j dee dee dee dee	j
 dee d ee d!eeef fd"d#Z  ZS )&Idefics2Modelr2   c                    sx   t  | | jjj| _| jjj| _t|j	| _
t|| _t|j| _|jj| _| jj| _|jjdk| _|   d S )Nr   )r4   r5   r2   r  Zpad_token_idr   
vocab_sizer   r  r  vision_modelr  	connectorr   Zfrom_config
text_modelr  r  Zimage_seq_lenimage_token_idr   r   	post_initr?   rA   r,   r-   r5     s   


zIdefics2Model.__init__c                    s:    fdd dd }|   || _ | j|| _dS )aE  
        Enables the gradients for the input embeddings.

        This is useful for lora when using gradient checkpointing.
        c.f. https://github.com/huggingface/peft/issues/1402#issuecomment-1913675032

        Override to set output.requires_grad = True for both the decoder's and vision model's embeddings.
        c                    s,   t t|  dkr| S  t|  d S )Nr   )lenlistchildren)r^   get_lowest_moduler,   r-   r"    s   zCIdefics2Model.enable_input_require_grads.<locals>.get_lowest_modulec                 S      | d d S NTZrequires_grad_r^   inputoutputr,   r,   r-   make_inputs_require_grads     zKIdefics2Model.enable_input_require_grads.<locals>.make_inputs_require_gradsN)r   register_forward_hook_text_require_grads_hookr  _vision_require_grads_hookr@   r)  r,   r!  r-   enable_input_require_grads  s   


z(Idefics2Model.enable_input_require_gradsc                 C      | j   | j  d S r   r,  remover-  r   r,   r,   r-   disable_input_require_grads     
z)Idefics2Model.disable_input_require_gradsc                 C   s
   | j  S r   )r  r   r   r,   r,   r-   r     r   z"Idefics2Model.get_input_embeddingsc                 C   s   | j | d S r   )r  r   r   r,   r,   r-   r     s   z"Idefics2Model.set_input_embeddings	input_idsr   r$   c                 C   s&   || j k}| }||j||< |S )aq  
        This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are fed to the transformer LM.
        The merging happens as follows:
        - The text token sequence is: `tok_1 tok_2 tok_3 <fake_token_around_image> <image> <image> ... <image> <fake_token_around_image> tok_4`.
        - We get the image hidden states for the image through the vision encoder (and potentially the perceiver), and that hidden state is then projected into the text embedding space.
        We thus have a sequence of image hidden states of size (1, image_seq_len, hidden_dim), where 1 is for batch_size of 1 image and hidden_dim is the hidden_dim of the LM transformer.
        - The merging happens so that we obtain the following sequence: `vector_tok_1 vector_tok_2 vector_tok_3 vector_fake_tok_around_image {sequence of image_seq_len image hidden states} vector_fake_toke_around_image vector_tok_4`. That sequence is fed to the LM.
        - To fit the format of that sequence, `input_ids`, `input_embeds`, `attention_mask` are all 3 adapted to insert the image hidden states.
        )r  clonerR   rT   )r@   r5  r   r$   Zspecial_image_token_maskZnew_inputs_embedsr,   r,   r-   inputs_merger  s   
zIdefics2Model.inputs_mergerNrC   pixel_attention_maskc                 C   sZ  |j \}}}}}|j| jd}|j|| g|j dd R  }|j dd  }|dkjdd|k}	||	  }|du rStj|	d|	d|	d	ftj
|jd
}n|j|| g|j dd R  }||	  }| jjj}
|jd|
|
d}|jd|
|
d}|jdd|
|
 k
 }| j||d}|j}| j|||	ddd}|d|j d }|S )a  
        Encodes images into continuous embeddings that can be forwarded to the language model.

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
                The tensors corresponding to the input images.
            pixel_attention_mask (`torch.LongTensor`, *optional*):
                The attention mask indicating padded regions in the image.
        )rh   r   Nr   r]   )rI   rf   r   r   r	   )rG   rh   rT   )	dimensionrG   step)rI   rf   r   rI   )rb   )rJ   rR   rh   rP   ZnumelrO   ro   r)   r   rG   r   rT   r2   r  r8   Zunfoldr  r    r  )r@   rC   r8  rU   Z
num_imagesr:   heightwidthZnb_values_per_imageZreal_images_indsr8   Zpatches_subgridrD   r$   r,   r,   r-   get_image_features  s2   
  
z Idefics2Model.get_image_featuresa  
        Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
        the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
        max_num_images is the maximum number of images among the batch_size samples in the batch.

        Padding images are not needed beyond padding the pixel_values at the entrance of the model.
        For efficiency, we only pass through the vision_model's forward the real images by
        discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
        image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
        r   rb   rX   r!   r   r   r   cache_positionr   rp   rE   c                 K   s  |
dur|
n| j j}
|dur|n| j j}|	dur|	n| j j}	|dur$|n| j j}| jr8| jjr8|	r8t	d d}	|durB|j
\}}n|durM|j
\}}}ntdd}d}|	rtt|tspd}|du rft }n
t|}t	d | }|dur|du r|dkrtd|du r| j |}|dur|durtd	|dur| ||}n|dur|j| j|jd
}|dkr|dur|dur| j|||d}| jd|||||	|
||dd	|}|r|	r|j |_t|j|j|j|j|dS )a  
        pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
            Mask to avoid performing attention on padding pixel indices.
        image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The hidden states of the image encoder after modality projection and perceiver resampling.
        NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fz5You have to specify either input_ids or inputs_embedsr   TzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)zWWhen first calling the model, if input_embeds are passed, input_ids should not be None.zMYou cannot specify both pixel_values and image_hidden_states at the same timer   )r5  r   r$   )	r   rb   rX   r!   r   r   r   r?  r   )r    r!   r"   r#   r$   r,   )r2   r   r   r   r   rj   r  r   r   r   rJ   ry   r   r   r   Zfrom_legacy_cacheZget_seq_lengthr   r>  rR   rh   rT   r7  r!   Zto_legacy_cacher   r    r"   r#   )r@   r5  rb   rX   r!   r   rC   r8  r$   r   r   r   r?  r   rp   rU   r   rV   Zpast_seen_tokensZreturn_legacy_cacher   r,   r,   r-   rY     s   $


zIdefics2Model.forwardr   )NNNNNNNNNNNNN)r%   r&   r'   r   r5   r/  r3  r   r   r)   r  r   r[   r7  r*   r>  r   r   r   rZ   r   r   r   r   r   r   rY   r\   r,   r,   rA   r-   r  {  s|    
.	

r  c                   @   s   e Zd ZdS )KwargsForCausalLMN)r%   r&   r'   r,   r,   r,   r-   r@  q  s    r@  z
    The Idefics2 Model with a language modeling head. It is made up a SigLIP vision encoder, with a language modeling head on top.
    c                '       sd  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
ee															d+deej deej deej deeej  deej deej deej deej deej dee dee dee dee deej d eeejf d!ee d"eeef f"d#d$Z								d, fd%d&	Z fd'd(Zed)d* Z  Z S )- Idefics2ForConditionalGenerationzlm_head.weightc                    sP   t  | t|| _| jj| _tj|jj	|jj
dd| _|jj
| _
|   d S r   )r4   r5   r  r   r2   r  r   r|   r  r6   r  lm_headr  r?   rA   r,   r-   r5   |  s   


z)Idefics2ForConditionalGeneration.__init__c                 C   s0   dd }|   || _| jj  || _dS )z
        Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
        the model weights fixed.
        c                 S   r#  r$  r%  r&  r,   r,   r-   r)    r*  z^Idefics2ForConditionalGeneration.enable_input_require_grads.<locals>.make_inputs_require_gradsN)r   r+  r,  r   r  r-  r.  r,   r,   r-   r/    s
   
z;Idefics2ForConditionalGeneration.enable_input_require_gradsc                 C   r0  r   r1  r   r,   r,   r-   r3    r4  z<Idefics2ForConditionalGeneration.disable_input_require_gradsc                 C   s   | j j S r   )r   r  r   r   r,   r,   r-   r     s   z5Idefics2ForConditionalGeneration.get_input_embeddingsc                 C   s   | j j| d S r   )r   r  r   r   r,   r,   r-   r     s   z5Idefics2ForConditionalGeneration.set_input_embeddingsc                 C   r   r   rB  r   r,   r,   r-   get_output_embeddings  r   z6Idefics2ForConditionalGeneration.get_output_embeddingsc                 C   r   r   rC  )r@   Znew_embeddingsr,   r,   r-   set_output_embeddings  r   z6Idefics2ForConditionalGeneration.set_output_embeddingsNr   r5  rb   rX   r!   r   rC   r8  r$   labelsr   r   r   r   r?  logits_to_keeprp   rE   c                 K   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| jd|||||||||
|||dd|}|d }t|trCt| dn|}| |dd|ddf }d}|	durh| j	d||	| j j
jd|}t|||j|j|j|jdS )a  
        pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
            Mask to avoid performing attention on padding pixel indices.
        image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The hidden states of the image encoder after modality projection and perceiver resampling.
        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 `model.image_token_id` (where `model` is your instance of `Idefics2ForConditionalGeneration`).
            Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only
            computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> import requests
        >>> import torch
        >>> from PIL import Image
        >>> from io import BytesIO

        >>> from transformers import AutoProcessor, AutoModelForVision2Seq
        >>> from transformers.image_utils import load_image

        >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
        >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
        >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
        >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")

        >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base")
        >>> model = AutoModelForVision2Seq.from_pretrained("HuggingFaceM4/idefics2-8b-base", device_map="auto")

        >>> BAD_WORDS_IDS = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
        >>> EOS_WORDS_IDS = [processor.tokenizer.eos_token_id]

        >>> # Create inputs
        >>> prompts = [
        ...   "<image>In this image, we can see the city of New York, and more specifically the Statue of Liberty.<image>In this image,",
        ...   "In which city is that bridge located?<image>",
        ... ]
        >>> images = [[image1, image2], [image3]]
        >>> inputs = processor(images=images, text=prompts, padding=True, return_tensors="pt").to("cuda")

        >>> # Generate
        >>> generated_ids = model.generate(**inputs, bad_words_ids=BAD_WORDS_IDS, max_new_tokens=20)
        >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

        >>> print(generated_texts)
        ['In this image, we can see the city of New York, and more specifically the Statue of Liberty. In this image, we can see the city of New York, and more specifically the Statue of Liberty.\n\n', 'In which city is that bridge located?\n\nThe bridge is located in the city of Pittsburgh, Pennsylvania.\n\n\nThe bridge is']
        ```NT)r5  rb   rX   r!   r   rC   r8  r$   r   r   r   r?  r   r   )r0   rF  r  )r/   r0   r!   r"   r#   r$   r,   )r2   r   r   r   r   r   r   slicerB  Zloss_functionr  r  r.   r!   r"   r#   r$   )r@   r5  rb   rX   r!   r   rC   r8  r$   rF  r   r   r   r   r?  rG  rp   r   r"   Zslice_indicesr0   r/   r,   r,   r-   rY     sN   Fz(Idefics2ForConditionalGeneration.forwardc
                    s^   t  j|f||||||||	d|
}|d ur!|d dkr!||d< |d ur-d |d< d |d< |S )N)r!   rb   r   r?  rC   r8  r$   rG  r   r5  rC   r8  )r4   prepare_inputs_for_generation)r@   r5  r!   rb   r   r?  rC   r8  r$   rG  rp   Zmodel_inputsrA   r,   r-   rI    s(   
z>Idefics2ForConditionalGeneration.prepare_inputs_for_generationc                    s(   t  jd|||d|}|j|d< |S )N)r   model_kwargsis_encoder_decoderr$   r,   )r4   #_update_model_kwargs_for_generationr$   )r@   r   rJ  rK  rp   rA   r,   r-   rL  ?  s   
zDIdefics2ForConditionalGeneration._update_model_kwargs_for_generationc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr,   c                 3   s$    | ]}| d  |jV  qdS )r   N)Zindex_selectrR   rT   )r   Z
past_statebeam_idxr,   r-   r   P  s   " zBIdefics2ForConditionalGeneration._reorder_cache.<locals>.<genexpr>)r   )r!   rN  Zreordered_pastZ
layer_pastr,   rM  r-   _reorder_cacheJ  s   z/Idefics2ForConditionalGeneration._reorder_cache)NNNNNNNNNNNNNNr   )NNNNNNNN)!r%   r&   r'   Z_tied_weights_keysr5   r/  r3  r   r   rD  rE  r   r   r   r)   r  r[   r   r*   rZ   r   r   r   r   r@  r   r.   rY   rI  rL  staticmethodrO  r\   r,   r,   rA   r-   rA  t  s    	

s(rA  )rA  r   r  )r]   )Gr(   dataclassesr   typingr   r   r   r   r   r)   Ztorch.utils.checkpointr   Zactivationsr
   Zcache_utilsr   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   r   autor   Zconfiguration_idefics2r   r   r   Z
get_loggerr%   r   r   r.   Moduler1   r[   floatrs   rt   r   r   r   r   r   r   r   r   rl   r   r   r   r   r  r  r@  rA  __all__r,   r,   r,   r-   <module>   s   
&$A
K2X$V[HA r ]