
    rh7                        d Z ddlmZ ddl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 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#jT                  e+      Z,e e!d       G d de                    Z-e e!d       G d de                    Z. G d de	j^                        Z0	 dMde	j^                  dejb                  d ejb                  d!ejb                  d"eejb                     d#e2d$e2fd%Z3 G d& d'e	j^                        Z4 G d( d)e	j^                        Z5 G d* d+e	j^                        Z6 G d, d-e	j^                        Z7 G d. d/e      Z8 G d0 d1e	j^                        Z9e! G d2 d3e             Z: e!d4       G d5 d6e:             Z;d7ejb                  d8e<d9ejb                  fd:Z= G d; d<e	j^                        Z> G d= d>e	j^                        Z? G d? d@e	j^                        Z@ e!dA       G dB dCe:             ZA G dD dEe	j^                        ZB e!dF       G dG dHe:             ZC e!dI       G dJ dKe:e             ZDg dLZEy)NzPyTorch Idefics2 model.    )	dataclass)CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)_prepare_4d_attention_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging   )	AutoModel   )Idefics2ConfigIdefics2PerceiverConfigIdefics2VisionConfigz|
    Base class for Idefics2 model's outputs that may also contain a past key/values (to speed up sequential decoding).
    custom_introc                       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<   y)Idefics2BaseModelOutputWithPastai  
    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 (`Cache`, *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.
    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$   tupler%   r&   r'        /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/idefics2/modeling_idefics2.pyr"   r"   )   s    & 6:x 1 129AEOXeE%*;*;$<=>E8<M8E%"3"345<59Ju00129>B%(9(9":;Br1   r"   zT
    Base class for Idefics2 causal language model (or autoregressive) outputs.
    c                      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<   y)	Idefics2CausalLMOutputWithPasta  
    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 (`Cache`, *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.
    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+   r5   r   r,   r-   r.   r6   r$   listr%   r/   r&   r'   r0   r1   r2   r4   r4   J   s      )-D(5$$
%,*.FHU&&'.9=OXd5#4#456=8<M8E%"3"345<59Ju00129>B%(9(9":;Br1   r4   c                   x     e Zd ZdZdef fdZdej                  dej                  dej                  fdZ
 xZS )Idefics2VisionEmbeddingsaX  
    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://huggingface.co/papers/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                    t         |           |j                  | _        |j                  | _        |j
                  | _        t        j                  |j                  | j                  | j
                  | j
                  d      | _	        | j                  | j
                  z  | _
        | j                  dz  | _        | j                  | _        t        j                  | j                  | j                        | _        y )Nvalid)in_channelsout_channelskernel_sizestridepaddingr   )super__init__hidden_size	embed_dim
image_size
patch_sizer   Conv2dnum_channelspatch_embeddingnum_patches_per_sidenum_patchesnum_positions	Embeddingposition_embeddingselfr:   	__class__s     r2   rC   z!Idefics2VisionEmbeddings.__init__u   s    ++ ++ ++!yy++?? 
 %)OOt$F!44a7!--"$,,t/A/A4>>"Rr1   pixel_valuespatch_attention_maskreturnc                 .   |j                   \  }}}}| j                  |      }|j                  d      j                  dd      }|| j                  z  || j                  z  }
}	t        j                  d| j                  z  dd| j                  z        }t        j                  ||	|
z  fd      }t        |      D ]  \  }}|d d df   j                         }|d   j                         }t        j                  ||j                  |j                        }t        j                  ||j                  |j                        }||z  dz  }||z  dz  }t        j                  ||d	      }t        j                  ||d	      }|d d d f   | j                  z  |z   j                         }|||   |j                  d
      j                         <    |j!                  | j"                  j$                  j                        }|| j#                  |      z   }|S )Nr   r         ?r   )size
fill_value)devicedtypeg!?T)right)shaperJ   flatten	transposerG   r,   arangerK   full	enumeratesumrZ   r[   	bucketizeviewcputorO   weight)rQ   rS   rT   
batch_size_max_im_hmax_im_wpatch_embeds
embeddingsmax_nb_patches_hmax_nb_patches_w
boundariesposition_ids	batch_idxp_attn_masknb_patches_hnb_patches_w	h_indices	w_indicesfractional_coords_hfractional_coords_wbucket_coords_hbucket_coords_wpos_idss                           r2   forwardz Idefics2VisionEmbeddings.forward   s   ,8,>,>)
Ax++L9!))!,66q!<
-5-H(VZVeVeJe*\\!d&?&?"?a$JcJcFcd
zz
4DGW4W'Xefg&/0D&E 	J"I{&q!t,002L&q>--/L\,:M:MUaUgUghI\,:M:MUaUgUghI"+l":h"G"+l":h"G#oo.A:UYZO#oo.A:UYZO&q$w/$2K2KKo]ffhGBIL#K$4$4R$8$<$<$>?	J  $t'>'>'E'E'L'LM$"9"9,"GG
r1   )r(   r)   r*   r+   r   rC   r,   r-   
BoolTensorTensorr   __classcell__rR   s   @r2   r9   r9   j   sD    S3 S&E$5$5 UM]M] bgbnbn r1   r9   modulequerykeyvalueattention_maskscalingdropoutc                 l   t        | d      r,t        || j                        }t        || j                        }t        j                  ||j                  dd            |z  }|#|d d d d d d d |j                  d   f   }	||	z   }t        j                  j                  |dt        j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||      }
|
j                  dd      j                         }
|
|fS )	Nnum_key_value_groupsr   r   r]   )dimr[   )ptrainingr   )hasattr	repeat_kvr   r,   matmulr`   r^   r   
functionalsoftmaxfloat32rh   r[   r   r   
contiguous)r   r   r   r   r   r   r   kwargsattn_weightscausal_maskattn_outputs              r2   eager_attention_forwardr      s    v-.V889%!<!<=<<s}}Q':;gEL!$Q1o		"o%=>#k1==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r1   c            
            e Zd ZdZ fdZ	 ddej                  deej                     deej                  eej                     f   fdZ	 xZ
S )Idefics2VisionAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        |j                  | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        d| _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).      F)rB   rC   r:   rD   rE   num_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutr   r   Lineark_projv_projq_projout_proj	is_causalrP   s     r2   rC   z Idefics2VisionAttention.__init__   s   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//ii?ii?ii?		$..$..A r1   r%   r   rU   c           
      :   |j                   \  }}}| j                  |      }| j                  |      }| j                  |      }	|j	                  ||| j
                  | j                        j                  dd      }|j	                  ||| j
                  | j                        j                  dd      }|	j	                  ||| j
                  | j                        j                  dd      }	t        }
| j                  j                  dk7  rt        | j                  j                     }
 |
| |||	|| j                  | j                  | j                  sdn| j                        \  }}|j!                  |||      j#                         }| j%                  |      }||fS )z#Input shape: Batch x Time x Channelr   r   eager        r   r   r   )r^   r   r   r   rf   r   r   r`   r   r:   _attn_implementationr   r   r   r   r   reshaper   r   )rQ   r%   r   r   rj   
seq_lengthrE   querieskeysvaluesattention_interfacer   r   s                r2   r   zIdefics2VisionAttention.forward   sa    -:,?,?)
J	++m,{{=)]+,,z:t~~t}}U__`acdeyyZOYYZ[]^_ZT^^T]]S]]^_abc(?;;++w6"9$++:Z:Z"[$7nnJJ#}}C$,,	%
!\ "))*j)LWWYmmK0L((r1   N)r(   r)   r*   r+   rC   r,   r   r   r/   r   r   r   s   @r2   r   r      sU    G2 26$)||$) !.$)
 
u||Xell33	4$)r1   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )Idefics2VisionMLPc                    t         |           || _        t        |j                     | _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        y r   )rB   rC   r:   r	   
hidden_actactivation_fnr   r   rD   intermediate_sizefc1fc2rP   s     r2   rC   zIdefics2VisionMLP.__init__  sd    #F$5$5699V//1I1IJ99V55v7I7IJr1   r%   rU   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   )rQ   r%   s     r2   r   zIdefics2VisionMLP.forward  s4    /**=9/r1   )r(   r)   r*   rC   r,   r   r   r   r   s   @r2   r   r     s$    KU\\ ell r1   r   c                   6     e Zd Zdedededef fdZd Z xZS )Idefics2MLPrD   r   output_sizer   c                     t         |           t        j                  ||d      | _        t        j                  ||d      | _        t        j                  ||d      | _        t        |   | _        y NFbias)	rB   rC   r   r   	gate_projup_proj	down_projr	   act_fn)rQ   rD   r   r   r   rR   s        r2   rC   zIdefics2MLP.__init__  s[     	;0ANyy.?eL#4kNZ(r1   c                     | j                  | j                  | j                  |            | j                  |      z        S r   )r   r   r   r   )rQ   xs     r2   r   zIdefics2MLP.forward"  s0    ~~dkk$..*;<t||ANOOr1   )r(   r)   r*   intstrrC   r   r   r   s   @r2   r   r     s4    )) ) 	)
 )Pr1   r   c                   .     e Zd ZdZdef fdZd Z xZS )%Idefics2MultiheadAttentionPoolingHeadzMultihead Attention Pooling.r:   c                    t         |           t        j                  t	        j
                  dd|j                              | _        t        j                  j                  |j                  |j                  d      | _
        t        j                  |j                  |j                        | _        t        |j                  |j                  |j                   |j                        | _        y )Nr   T)batch_firsteps)rD   r   r   r   )rB   rC   r   	Parameterr,   randnrD   probeMultiheadAttentionr   	attention	LayerNormlayer_norm_eps	layernormr   r   r   mlprP   s     r2   rC   z.Idefics2MultiheadAttentionPoolingHead.__init__*  s    \\%++aF4F4F"GH
44V5G5GIcIcqu4vf&8&8f>S>ST**$66((**	
r1   c                     |j                   d   }| j                  j                  |dd      }| j                  |||      d   }|}| j	                  |      }|| j                  |      z   }|d d df   S )Nr   r   )r^   r   repeatr   r   r   )rQ   hidden_staterj   r   residuals        r2   r   z-Idefics2MultiheadAttentionPoolingHead.forward8  sv    !''*


!!*a3~~e\<HK~~l3$((<"88AqD!!r1   )r(   r)   r*   r+   r   rC   r   r   r   s   @r2   r   r   '  s    &
3 

"r1   r   c            
            e Zd Zdef fdZ	 ddej                  dej                  dee   de	ej                     fdZ xZS )	Idefics2EncoderLayerr:   c                 D   t         |           |j                  | _        t	        |      | _        t        j                  | j                  |j                        | _	        t        |      | _        t        j                  | j                  |j                        | _        y )Nr   )rB   rC   rD   rE   r   	self_attnr   r   r   layer_norm1r   r   layer_norm2rP   s     r2   rC   zIdefics2EncoderLayer.__init__F  sm    ++08<<F<Q<QR$V,<<F<Q<QRr1   r%   r   output_attentionsrU   c                     |}| j                  |      }| j                  |||      \  }}||z   }|}| j                  |      }| j                  |      }||z   }|f}|r||fz  }|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%   r   r   )r   r   r   r   )rQ   r%   r   r   r   r   outputss          r2   r   zIdefics2EncoderLayer.forwardO  s      !((7&*nn')/ '5 '
#|
 !=0 ((7/ =0 "&Gr1   )F)r(   r)   r*   r   rC   r,   r   r   boolr/   r-   r   r   r   s   @r2   r   r   E  sY    S3 S -2	$||$ $ $D>	$
 
u  	!$r1   r   c                        e Zd ZdZdef fdZ	 	 	 	 d
deej                     dee	   dee	   dee	   de
eef   f
d	Z xZS )Idefics2Encoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Idefics2EncoderLayer`].

    Args:
        config: Idefics2Config
    r:   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
rB   rC   r:   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing)rQ   r:   rk   rR   s      r2   rC   zIdefics2Encoder.__init__  sP    mm5QWQiQiKj$ka%9&%A$kl&+# %ls   A#r   r   output_hidden_statesreturn_dictrU   c                 ~   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|rdnd}|rdnd}|}| j                  D ]&  }	|r||fz   } |	|||      }
|
d   }|s||
d   fz   }( |r||fz   }|st        d |||fD              S t        |||      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.
        Nr0   )r   r   r   c              3   &   K   | ]	  }||  y wr   r0   ).0vs     r2   	<genexpr>z*Idefics2Encoder.forward.<locals>.<genexpr>  s     eqWXWdes   r#   r%   r&   )r:   r   r   use_return_dictr   r/   r   )rQ   inputs_embedsr   r   r   r   encoder_statesall_attentionsr%   encoder_layerlayer_outputss              r2   r   zIdefics2Encoder.forward  s   < 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d%![[ 	FM#!/=2B!B)"3M *!,M !/=3C2E!E	F  +}.>>Ne]NN$Seee+>Vd
 	
r1   NNNN)r(   r)   r*   r+   r   rC   r   r,   r   r   r   r/   r   r   r   r   s   @r2   r   r   w  sx    ,~ , 26,0/3&*=
 !.=
 $D>	=

 'tn=
 d^=
 
uo%	&=
r1   r   c                   B    e Zd ZU eed<   dZdZg dZdZdZ	dZ
dZdZd Zy)Idefics2PreTrainedModelr:   modelT)r   r   Idefics2PerceiverLayerIdefics2DecoderLayerr$   c                    t        | j                  d| j                  j                         j                        }t	        |t
        j                  t
        j                  f      rY|j                  j                  j                  d|       |j                  %|j                  j                  j                          y y t	        |t
        j                        rf|j                  j                  j                  d|       |j                  2|j                  j                  |j                     j                          y y t	        |t
        j                        rJ|j                  j                  j!                  d       |j                  j                  j                          y t	        |t"              r&|j                  j                  j!                  d       y t	        |t
        j$                        r|j'                          y t	        |t(              r%|j*                  j                  j                          y t	        |t,              r&|j.                  j                  j!                  d       y y )Ninitializer_ranger   )meanstdrW   )getattrr:   get_text_configr  
isinstancer   r   rH   ri   datanormal_r   zero_rN   padding_idxr   fill_Idefics2RMSNormr   _reset_parametersr   r   Idefics2PerceiverResamplerlatents)rQ   r   r  s      r2   _init_weightsz%Idefics2PreTrainedModel._init_weights  s   dkk#68S8S8U8g8ghfryy"))45MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> .-MM$$S)KK""$0MM$$S) 5 56$$& EFLL%%' :;NN%%c* <r1   N)r(   r)   r*   r   r.   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr  r0   r1   r2   r  r    s<    &*#t"3N"&+r1   r  zK
    Idefics2 vision encoder model that returnss raw image embeddings.
    c                        e Zd ZU eed<   dZdZdZdef fdZd Z	d Z
e	 	 	 	 ddeej                     dee   dee   d	ee   d
eeef   f
d       Z xZS )Idefics2VisionTransformerr:   Tc                     t         |   |       |j                  }|| _        t	        |      | _        t        |      | _        t        j                  ||j                        | _        |j                  dk(  | _        y Nr   flash_attention_2)rB   rC   rD   r:   r9   ro   r   encoderr   r   r   post_layernormr   _use_flash_attention_2)rQ   r:   rE   rR   s      r2   rC   z"Idefics2VisionTransformer.__init__  sg     &&	26:&v. ll9&:O:OP&,&A&AEX&X#r1   c                     | j                   S r   ro   rQ   s    r2   get_input_embeddingsz.Idefics2VisionTransformer.get_input_embeddings  s    r1   c                     || _         y r   r,  rQ   r   s     r2   set_input_embeddingsz.Idefics2VisionTransformer.set_input_embeddings  s	    r1   rT   r   r   r   rU   c                 0   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|j	                  d      }|}| j                   j
                  }t        j                  ||j	                  d      |z  |j	                  d      |z  f      }|j                  t        j                  |j                        }| j                  ||      }|j                  |d      }t        j                  |       sd}n"| j                  st        ||j                         }| j#                  |||||      }	|	d   }
| j%                  |
      }
|s	|
f|	d	d z   S t'        |
|	j(                  |	j*                  
      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   r[   rZ   rS   rT   r]   )r   r   r   r   r   r   r   )r:   r   r   r   rX   rG   r,   onesrh   r   rZ   ro   rf   anyr*  r   r[   r(  r)  r   r%   r&   )rQ   rS   rT   r   r   r   rj   rG   r%   encoder_outputsr#   s              r2   r   z!Idefics2VisionTransformer.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]!&&q)
'//J#(:: %%a(J6 %%a(J6$  $8#:#:T`TgTg#:#h \Xlm388RH yy../#' ,,#=>RTaTgTg#h ,,'//!5# ' 
 ,A. //0AB%'/!"*===/)77&11
 	
r1   r  )r(   r)   r*   r   r.   r   r  r!  rC   r.  r1  r   r   r,   r   r   r   r/   r   r   r   r   s   @r2   r$  r$    s     ! NY3 Y   <@,0/3&*;
 'u'7'78;
 $D>	;

 'tn;
 d^;
 
uo%	&;
 ;
r1   r$  r%   n_reprU   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      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)r^   expandr   )r%   r8  batchnum_key_value_headsslenr   s         r2   r   r   G  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr1   c                   ,     e Zd Zd fd	Zd Zd Z xZS )r  c                     t         |           t        j                  t	        j
                  |            | _        || _        y)z>
        Idefics2RMSNorm is equivalent to T5LayerNorm
        N)rB   rC   r   r   r,   r5  ri   variance_epsilon)rQ   rD   r   rR   s      r2   rC   zIdefics2RMSNorm.__init__U  s1     	ll5::k#:; #r1   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr   r]   T)keepdim)	r[   rh   r,   r   powr  rsqrtr@  ri   )rQ   r%   input_dtypevariances       r2   r   zIdefics2RMSNorm.forward]  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r1   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r/   ri   r^   r@  r-  s    r2   
extra_reprzIdefics2RMSNorm.extra_reprd  s*    ))*+6$2G2G1HIIr1   )gư>)r(   r)   r*   rC   r   rH  r   r   s   @r2   r  r  T  s    $;Jr1   r  c                        e Zd Zddee   ddf fdZ	 	 	 	 	 ddej                  dej                  deej                     deej                     d	ee	   d
e
de
deej                  eej                     eeej                        f   fdZ xZS )Idefics2PerceiverAttentionN	layer_idxrU   c                 J   t         |           || _        d| _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _	        | j                  | j                  z  | _
        |j                  | _        | j                  dz  | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  z  | j                  d      | _        d| _        y)ziPerceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`Nr   Fr   )rB   rC   r:   rK  rD   resampler_n_headsr   resampler_head_dimr   r<  r   r   r   r   r   r   r   r   o_projr   rQ   r:   rK  rR   s      r2   rC   z#Idefics2PerceiverAttention.__init__i  s2   !--1111#)#=#= $(NNd6N6N$N!!'!9!9}}d*ii 0 0$..4==2PW\]ii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii >@P@PW\]r1   r  contextr   rs   past_key_valuer   	use_cachec           
      |   |j                         \  }}	}
|	|j                         d   z   }t        j                  ||gd      }| j                  |      }| j	                  |      }| j                  |      }|j                  ||	| j                  | j                        j                  dd      }|j                  ||| j                  | j                        j                  dd      }|j                  ||| j                  | j                        j                  dd      }t        | d|      }| |j                  ||| j                        \  }}t        }| j                  j                   dk7  rN| j                  j                   dk(  r|rt"        j%                  d	       nt&        | j                  j                      } || ||||| j(                  | j*                  | j,                  sd
n| j.                        \  }}|j1                  ||	| j                  | j                  z        }| j3                  |      }|sd}|||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   r   r   r   rR  Nr   sdpaz`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   )rX   r,   concatr   r   r   rf   r   r   r`   r<  r  updaterK  r   r:   r   loggerwarning_oncer   r   r   r   r   r   rO  )rQ   r  rQ  r   rs   rR  r   rS  bszq_lenrk   
kv_seq_lenr%   r   r   r   r   r   r   s                      r2   r   z"Idefics2PerceiverAttention.forward}  s   ,  UAW\\^A..
gw%7R@++g&{{=)]+,,sE4>>4==ISSTUWXYyyj$*B*BDMMR\\]^`abS*d.F.FV``abdef '7H%)00vt~~NLD&(?;;++w6{{//69>O##L
 '>dkk>^>^&_#$7nnLL#}}C$2H2H	%
!\ "))#udnnt}}6TUkk+. LL.88r1   r   NNNFF)r(   r)   r*   r   r   rC   r,   r   
LongTensorr
   r   r/   r   r   r   s   @r2   rJ  rJ  h  s    (3- 4 0 2637*."'C9C9 C9 !.	C9
 u//0C9 !C9  C9 C9 
u||Xell3XeELL>Q5RR	SC9r1   rJ  c                       e Zd Zdef fdZ	 	 	 	 	 ddej                  dej                  deej                     deej                     dee	   dee
   d	ee
   d
eej                  eeej                  ej                  f      f   fdZ xZS )r  rK  c                 0   t         |           |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        | j                  | j                        | _	        t        | j                  | j                        | _
        t        ||      | _        t        | j                  | j                        | _        t        |j                  |j                  dz  |j                  |j                        | _        y )Nr   )rK     rD   r   r   r   )rB   rC   rD   resampler_n_latents	n_latentsresampler_depthdepthrms_norm_epsr  input_latents_norminput_context_normrJ  r   post_attention_layernormr   r   r   rP  s      r2   rC   zIdefics2PerceiverLayer.__init__  s    !--33++
"//"1$2B2BHYHY"Z"1$2B2BHYHY"Z3FiP(78H8HdN_N_(`%**$0014**((	
r1   r  rQ  r   rs   rR  r   rS  rU   c                     |}	| j                  |      }| j                  |      }| j                  |||      \  }}
}|	|z   }|}	| j                  |      }| j	                  |      }|	|z   }|f}|r||
fz  }|r||fz  }|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  rQ  r   )ri  rj  r   rk  r   )rQ   r  rQ  r   rs   rR  r   rS  r   r   self_attn_weightspresent_key_valuer   s                r2   r   zIdefics2PerceiverLayer.forward  s    2 ))'2))'28<) 9G 9
5"$5
 W$//8((7#W$*)++G)++Gr1   r^  )r(   r)   r*   r   rC   r,   r   r   r_  r
   r   r/   r-   r   r   r   s   @r2   r  r    s    
# 
, 2637*.,1$)22 2 !.	2
 u//02 !2 $D>2 D>2 
u  (51B1BEDUDU1U+V"WW	X2r1   r  zi
    Idefics2 perceiver resampler model that performs `depth` blocks of cross-attention with a fixed
    c                        e Zd ZU eed<   dZdZdZd fdZe	de
j                  de
j                  de
j                  fd       Z xZS )	r  r:   TrU   c           	      Z   t         |   |       |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j
                  | j                              | _        t        j                  t        | j                        D cg c]  }t!        ||       c}      | _        t%        | j                  | j                        | _        |j(                  dk(  | _        y c c}w r&  )rB   rC   rD   r   rd  re  rf  rg  rh  r   r   r,   r5  r  r   r   r  r   r  normr   r*  )rQ   r:   idxrR   s      r2   rC   z#Idefics2PerceiverResampler.__init__  s     !-- ++33++
"// ||EJJt~~t?O?O$PQ mmTYZ^ZdZdTe$fS%;FC%H$fg#D$4$4$:K:KL	&,&A&AEX&X# %gs   D(rQ  r   c           
      F   | j                   j                  d      j                  |j                  d   g| j                   j	                               }t        j                  |j	                  d      |j	                  d      f|j                  |j                        }t        j                  ||gd      }| j                  s"t        ||j                  | j                        n|}|}| j                  D ]  } ||||dddd	      }|d   } | j                  |      }|S )
zw
        context (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`):
            Input to the layer.
        r   r   r3  r]   rU  )tgt_lenNF)r   rs   rR  r   rS  )r  	unsqueezer:  r^   rX   r,   r5  r[   rZ   catr*  r   re  r   rq  )rQ   rQ  r   r  latent_attention_maskcompressed_contextperceiver_layerr  s           r2   r   z"Idefics2PerceiverResampler.forward'  s    ,,((+22GMM!4D3[t||GXGXGZ3[\ %

  #W\\!_5^=Q=QZhZoZo!
 N4I#JPRS .. '~w}}dnn] 	 %#{{ 	2O+"-!#"'M "/q!1	2 "YY'9:!!r1   )rU   N)r(   r)   r*   r   r.   r   _supports_flash_attention_2r!  rC   r   r,   r   r   r   r   s   @r2   r  r    s^     $#N"&Y" &"&" &" 
	&" &"r1   r  c                   $     e Zd Z fdZd Z xZS )Idefics2Connectorc                 2   t         |           t        |j                  j                  |j
                  j                  |j
                  j                  |j
                  j                        | _        t        j                  |j                        | _        y )Nrc  )rB   rC   r   vision_configrD   text_configr   r   modality_projectionr  _from_configperceiver_configperceiver_resamplerrP   s     r2   rC   zIdefics2Connector.__init__R  sr    #.,,88$00BB**66))44	$
  $>#J#J6KbKb#c r1   c                 N    | j                  |      }| j                  ||      }|S )N)rQ  r   )r  r  )rQ   r'   r   s      r2   r   zIdefics2Connector.forward\  s2    "667JK"66?Rcq6r""r1   )r(   r)   r*   rC   r   r   r   s   @r2   r|  r|  Q  s    d#r1   r|  z[
    Idefics2 model consisting of a SIGLIP vision encoder and Mistral language decoder
    c            #       R    e Zd Zdef fdZd Zd Zd Zd Zde	j                  dee	j                     d	ee	j                     fd
Zdde	j                  de	j                  fdZe ed      	 	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     dee   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              Z xZS )Idefics2Modelr:   c                 0   t         |   |       | j                  j                  j                  | _        | j                  j                  j                  | _        t        j                  |j                        | _
        t        |      | _        t        j                  |j                        | _        |j                   j"                  | _        | j                  j&                  | _        |j                  j(                  dk(  | _        | j-                          y )Nr'  )rB   rC   r:   r  pad_token_idr  
vocab_sizer$  r  r~  vision_modelr|  	connectorr   from_config
text_modelr  rd  image_seq_lenimage_token_idr   r*  	post_initrP   s     r2   rC   zIdefics2Model.__init__h  s     ;;22??++11<<5BB6CWCWX*62#//0B0BC#44HH"kk88&,&8&8&M&MQd&d#r1   c                     fdd }| j                         j                  |      | _         | j                        j                  |      | _        y)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                     t        t        | j                                     dk(  r| S  t        | j                               d         S )Nr   )lenr7   children)r   get_lowest_modules    r2   r  zCIdefics2Model.enable_input_require_grads.<locals>.get_lowest_module  s?    4)*+q0 )foo.?)@)CDDr1   c                 &    |j                  d       y NTrequires_grad_r   inputoutputs      r2   make_inputs_require_gradszKIdefics2Model.enable_input_require_grads.<locals>.make_inputs_require_grads      !!$'r1   N)r.  register_forward_hook_text_require_grads_hookr  _vision_require_grads_hook)rQ   r  r  s     @r2   enable_input_require_gradsz(Idefics2Model.enable_input_require_gradsx  sN    	E	( )-(A(A(C(Y(YZs(t%*;D<M<M*N*d*d%+
'r1   c                 l    | j                   j                          | j                  j                          y r   r  remover  r-  s    r2   disable_input_require_gradsz)Idefics2Model.disable_input_require_grads  &    %%,,.''..0r1   c                 6    | j                   j                         S r   )r  r.  r-  s    r2   r.  z"Idefics2Model.get_input_embeddings  s    3355r1   c                 :    | j                   j                  |       y r   )r  r1  r0  s     r2   r1  z"Idefics2Model.set_input_embeddings  s    ,,U3r1   	input_idsr   r'   c                    |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                  d      j                  |      j                  |j                        }|j                  |j                  |j                        }|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.
        r3  r]   )r.  r,   tensorr:   r  longrZ   allru  	expand_asrh   r[   masked_scatter)rQ   r  r   r'   special_image_masks        r2   inputs_mergerzIdefics2Model.inputs_merger  s     !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H/99"=GGVYYZgZnZno144]5I5I=K^K^_%445GI\]r1   rS   pixel_attention_maskc                 &   |j                   \  }}}}}|j                  | j                        } |j                  ||z  g|j                   dd  }|j                   dd j	                         }|dk(  j                  d      |k7  }	||	   j                         }|at        j                  |j                  d      |j                  d      |j                  d	      ft        j                  |j                  
      }n6 |j                  ||z  g|j                   dd  }||	   j                         }| j                  j                  j                  }
|j                  d|
|
      }|j                  d|
|
      }|j                  d      |
|
z  k(  j                         }| j!                  ||      }|j"                  }| j%                  ||j                  |j                  d      d            }|j                  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.
        )r[   r   Nr   r   )r]   r   rU  r   r   )rX   r[   rZ   )	dimensionrX   step)r]   r   r4  r]   )r   )r^   rh   r[   rf   numelrd   r   r,   r5  rX   r   rZ   r:   r~  rG   unfoldr  r#   r  )rQ   rS   r  rj   
num_imagesrI   heightwidthnb_values_per_imagereal_images_indsrG   patches_subgridrT   r'   s                 r2   get_image_featuresz Idefics2Model.get_image_features  s1    ?K>P>P;
Jfe#TZZ8(|((j)@Z<CUCUVWVXCYZ +004::<(C/444FJ]]#$45@@B  '#(::"''*L,=,=a,@,BSBSTUBVWjj#**$  $=#7#<#<Z*=T#vWkWqWqrsrtWu#v #78H#I#T#T#V [[..99
.55
Yc5d)001:T^0_ / 3 3 3 AZR\E\ \bbd"//\`t/u1CC #nn0D0I0I,J[J[\]J^`b0c - 
 266r;N;T;TUW;XY""r1   a  
        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   r   rs   r$   rS  r   r   cache_positionr   r   rU   c                    |
|
n| j                   j                  }
||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }| j
                  r/| j                  j                  r|	rt        j                  d       d}	||j                  \  }}n||j                  \  }}}nt        d      t        |t        d      t        f      st        d      |	r|
t               }|  | j                  j!                         |      }||t        d      || j#                  ||      }n)|'|j%                  | j&                  |j(                        }|| j+                  |||      } | j                  d|||||	|
||d	d
	|}t-        |j.                  |j0                  |j2                  |j4                  |      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_embedszBThe `past_key_values` should be either a `Cache` object or `None`.zMYou cannot specify both pixel_values and image_hidden_states at the same timer3  )r  r   r'   T)	r   r   rs   r$   rS  r   r   r  r   )r#   r$   r%   r&   r'   r0   )r:   r   r   rS  r   r   r  r   rY  rZ  r^   r   r  typer
   r   r.  r  rh   r[   rZ   r  r"   r#   r$   r%   r&   )rQ   r  r   rs   r$   r   rS   r  r'   rS  r   r   r  r   r   rj   r   rk   r   s                      r2   r   zIdefics2Model.forward  s   H 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]==T__CC	l I  %.__"J
&(5(;(;%J
ATUU /DJ+>?abb0*nO BDOO@@B9MM #(;(Glmm%"&"9"9,H\"] ,"5"8"8tzzR[RbRb"8"c* !..#+$7 / M "$// 
')%+/!5)
 
 /%77#33!//)) 3
 	
r1   r   )NNNNNNNNNNNNN)r(   r)   r*   r   rC   r  r  r.  r1  r,   r_  r   r   r  r-   r  r   r   r
   r   r   r   r   r   r/   r"   r   r   r   s   @r2   r  r  b  s   ~  
4164##  - &ell3	8,#u/@/@ ,#X]XhXh ,#\ 	 151537+/5948;?;?$(,0/359&*Z
E,,-Z
 !.Z
 u//0	Z

 "%Z
   1 12Z
 u001Z
 'u'7'78Z
 &e&7&78Z
 D>Z
 $D>Z
 'tnZ
 !!1!12Z
 d^Z
 -.Z
  
u55	6!Z
 Z
r1   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            '       H    e Zd ZdgZ fdZd Zd Zd Zd Zdde	j                  de	j                  fd	Zee	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd
ee	j                     dee	j                      dee	j                     dee   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              Z	 	 	 	 	 	 	 	 d fd	Z xZS ) Idefics2ForConditionalGenerationzlm_head.weightc                 Z   t         |   |       t        |      | _        | j                  j
                  | _        t        j                  |j                  j                  |j                  j                  d      | _        |j                  j                  | _
        | j                          y r   )rB   rC   r  r  r:   r  r   r   r  rD   r  lm_headr  rP   s     r2   rC   z)Idefics2ForConditionalGeneration.__init__X  sz     "6*
"kk88yy!3!3!?!?ASASA^A^ejk ,,77 	r1   c                     d }| j                         j                  |      | _        | j                  j                  j                         j                  |      | _        y)z
        Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
        the model weights fixed.
        c                 &    |j                  d       y r  r  r  s      r2   r  z^Idefics2ForConditionalGeneration.enable_input_require_grads.<locals>.make_inputs_require_gradsi  r  r1   N)r.  r  r  r  r  r  )rQ   r  s     r2   r  z;Idefics2ForConditionalGeneration.enable_input_require_gradsc  sO    	( )-(A(A(C(Y(YZs(t%*.***A*A*V*V*X*n*n%+
'r1   c                 l    | j                   j                          | j                  j                          y r   r  r-  s    r2   r  z<Idefics2ForConditionalGeneration.disable_input_require_gradsq  r  r1   c                 J    | j                   j                  j                         S r   )r  r  r.  r-  s    r2   r.  z5Idefics2ForConditionalGeneration.get_input_embeddingsu  s    zz$$99;;r1   c                 N    | j                   j                  j                  |       y r   )r  r  r1  r0  s     r2   r1  z5Idefics2ForConditionalGeneration.set_input_embeddingsx  s    

2259r1   rS   r  c                 <    | j                   j                  ||      S )N)rS   r  )r  r  )rQ   rS   r  s      r2   r  z3Idefics2ForConditionalGeneration.get_image_features{  s    zz,,,]q,rrr1   r  r   rs   r$   r   r'   labelsrS  r   r   r   r  logits_to_keepr   rU   c                 >   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  } | j                  d|||||||||
|||dd|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|	4 | j                  d||	| j                   j                  j                  d|}t        |||j                  |j                  |j                  |j                         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)r  r   rs   r$   r   rS   r  r'   rS  r   r   r  r   r   )r6   r  r  )r5   r6   r$   r%   r&   r'   r0   )r:   r   r   r   r  r  r   slicer  loss_functionr  r  r4   r$   r%   r&   r'   )rQ   r  r   rs   r$   r   rS   r  r'   r  rS  r   r   r   r  r  r   r   r%   slice_indicesr6   r5   s                         r2   r   z(Idefics2ForConditionalGeneration.forward~  sU   L 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] $** 
)%+'%!5 3/!5)
 
"  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD .#33!//)) ' ; ;
 	
r1   c
                 b    t        |   |f||||||||	d|
}||d   dk7  r
d |d<   d |d<   |S )N)r$   r   r   r  rS   r  r'   r  r   rS   r  )rB   prepare_inputs_for_generation)rQ   r  r$   r   r   r  rS   r  r'   r  r   model_inputsrR   s               r2   r  z>Idefics2ForConditionalGeneration.prepare_inputs_for_generation  sm      w<
+)')%!5 3)
 
 *nQ.?1.D+/L(37L/0r1   r   )NNNNNNNNNNNNNNr   )NNNNNNNN)r(   r)   r*   _tied_weights_keysrC   r  r  r.  r1  r,   r-   r_  r  r   r   r   r   r
   r   r   r   r   r   r   r/   r4   r   r  r   r   s   @r2   r  r  P  s	    ++	
1<:su/@/@ sX]XhXh s  151537+/5948;?;?-1$(,0/3&*5934!n
E,,-n
 !.n
 u//0	n

 "%n
   1 12n
 u001n
 'u'7'78n
 &e&7&78n
 ))*n
 D>n
 $D>n
 'tnn
 d^n
 !!1!12n
  c5<</0!n
" +,#n
$ 
u44	5%n
  n
f ! ! !r1   r  )r  r  r  )r   )Fr+   dataclassesr   typingr   r   r   r,   torch.utils.checkpointr   activationsr	   cache_utilsr
   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   autor   configuration_idefics2r   r   r   
get_loggerr(   rY  r"   r4   Moduler9   r   floatr   r   r   r   r   r   r   r  r$  r   r   r  rJ  r  r  r|  r  r  __all__r0   r1   r2   <module>r     s    ! , ,    ! . ) B B 9 < F & R R  a a 
		H	% 
Ck C C6 C[ C C2:ryy :H %II%<<% 
% <<	%
 U\\*% % %8>)bii >)D		 P")) P&"BII "<.5 .dM
bii M
` !+o !+ !+H 
R
 7 R

R
l	UU\\ 	U# 	U%,, 	UJbii J(X9 X9vERYY EP 
>"!8 >"
>"B#		 #" 
f
+ f

f
R 
|'> |
|~ [r1   