
    g                     
   d Z ddlmZ ddlmZmZmZmZ ddlZddl	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 ddlmZ ddlmZmZ ddlmZmZmZmZm Z m!Z! ddl"m#Z# ddl$m%Z%m&Z&  e            rddl'm(Z(  e j)        e*          Z+dZ,e G d de                      Z-e G d de                      Z. G d de
j/                  Z0 G d de
j/                  Z1 G d de1          Z2e1e2dZ3 G d  d!e
j/                  Z4 G d" d#e
j/                  Z5 G d$ d%e
j/                  Z6 G d& d'e
j/                  Z7d(ej8        d)e9d*ej8        fd+Z: G d, d-e
j/                  Z; G d. d/e
j/                  Z<d0Z= ed1e=           G d2 d3e                      Z>d4Z? ed5e?           G d6 d7e>                      Z@d8ZA ed9e=           G d: d;e>                      ZB ed<e=           G d= d>e>e                      ZCdS )?zPyTorch Idefics3 model.    )	dataclass)ListOptionalTupleUnionN)nn)CrossEntropyLoss   )PreTrainedModel)ACT2FN)CacheDynamicCache)GenerationMixin)_prepare_4d_attention_mask)BaseModelOutputModelOutput)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )	AutoModel   )Idefics3ConfigIdefics3VisionConfig)_flash_attention_forwardr   c                       e Zd ZU dZdZej        ed<   dZe	e
e
ej                                   ed<   dZe	e
ej                          ed<   dZe	e
ej                          ed<   dZe	e
ej                          ed<   dS )Idefics3BaseModelOutputWithPasta	  
    Base class for Idefics3 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
    Nlast_hidden_statepast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r!   torchFloatTensor__annotations__r"   r   r   r#   r$   r%        j/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/idefics3/modeling_idefics3.pyr    r    4   s          < ,0u(///AEOXeE%*;$<=>EEE8<M8E%"345<<<59Ju012999>B%(9":;BBBBBr.   r    c                      e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
eeej                          ed<   dZeeej                          ed<   dZeeej                          ed<   dZeeej                          ed<   dS )	Idefics3CausalLMOutputWithPasta  
    Base class for Idefics causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.
            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder
    Nlosslogitsr"   r#   r$   r%   )r&   r'   r(   r)   r2   r   r*   r+   r,   r3   r"   r   r#   r   r$   r%   r-   r.   r/   r1   r1   [   s          8 )-D(5$
%,,, $FE$$$9=OXd5#456===8<M8E%"345<<<59Ju012999>B%(9":;BBBBBr.   r1   c                   Z     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 )Idefics3VisionEmbeddingsaP  
    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                    t                                                       |j        | _        |j        | _        |j        | _        t          j        |j        | j        | j        | j        d          | _	        | j        | j        z  | _
        | j
        dz  | _        | j        | _        t          j        | j        | j                  | _        d S )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selfr6   	__class__s     r/   r?   z!Idefics3VisionEmbeddings.__init__   s    + + +!y+? 
  
  
 %)Ot$F!4a7!-"$,t/A4>"R"Rr.   pixel_valuespatch_attention_maskreturnc                    |j         \  }}}}|                     |          }|                    d                              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         
                                }|d         
                                }t          j        ddd|z            }t          j        ddd|z            }t          j        ||d          }t          j        ||d          }|d d d f         | j        z  |z                                   }|||         |                    d	                                          <   |                    | j        j        j                  }||                     |          z   }|S )
Nr   r   g      ?r   )size
fill_valueg!?T)right)shaperF   flatten	transposerC   r*   arangerG   full	enumeratesum	bucketizeviewcputorK   weightdevice)rM   rO   rP   
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fractional_coords_hfractional_coords_wbucket_coords_hbucket_coords_wpos_idss                         r/   forwardz Idefics3VisionEmbeddings.forward   s   ,8,>)
Ax++L99!))!,,66q!<<
-5-H(VZVeJe*\!d&?"?a$JcFcdd
z
4DGW4W'Xefggg&/0D&E&E 	J 	J"I{&qqq!t,0022L&q>--//L"',q(A<L"M"M"',q(A<L"M"M#o.A:UYZZZO#o.A:UYZZZO&qqq$w/$2KKo]ffhhGBIL#K$4$4R$8$8$<$<$>$>??#t'>'E'LMM$"9"9,"G"GG
r.   )r&   r'   r(   r)   r   r?   r*   r+   
BoolTensorTensorrw   __classcell__rN   s   @r/   r5   r5      s         S3 S S S S S S&E$5 UM] bgbn        r.   r5   c                        e Zd ZdZ fdZ	 	 d
dej        deej                 dee         de	ej        eej                 f         fd	Z
 xZS )Idefics3VisionAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        | j        | j        z  | j        k    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| _        d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      F)r>   r?   r6   r@   rA   num_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutdropoutr   Lineark_projv_projq_projout_proj	is_causalrL   s     r/   r?   z Idefics3VisionAttention.__init__   s   +3$.8=4>)T^;;'dn ' 'N' ' '   ]D(
/i??i??i??	$.$.AA r.   NFr#   attention_maskoutput_attentionsrQ   c                 (   |                                 \  }}}|                     |          }|                     |          }|                     |          }	|                    ||| j        | j                                      dd          }|                    ||| j        | j                                      dd          }|	                    ||| j        | j                                      dd          }	|j        d         }
t          j
        ||                    dd                    | j        z  }|                                 || j        ||
fk    r0t          d|| j        ||
f d|                                            |L|                                 |d||
fk    r+t          d|d||
f d|                                            ||z   }t          j                            |d	t          j        
                              |j                  }t          j                            || j        | j                  }t          j
        ||	          }|                                 || j        || j        fk    r5t          d|| j        || j        f d|                                            |                    dd                                          }|                    ||| j                  }|                     |          }||fS )z#Input shape: Batch x Time x Channelr   r   r
   z$Attention weights should be of size z	, but is Nz!Attention mask should be of size rV   )dimdtype)ptrainingz `attn_output` should be of size )rS   r   r   r   r_   r   r   rY   rW   r*   matmulr   r   r   
functionalsoftmaxfloat32ra   r   r   r   
contiguousreshaperA   r   )rM   r#   r   r   rd   q_lenre   query_states
key_statesvalue_statesk_v_seq_lenattn_weightsattn_outputs                r/   rw   zIdefics3VisionAttention.forward   s     -1133
E1{{=11[[//
{{=11#((UDNDMZZddefhijj__ZVV``abdeff
#((UDNDMZZddefhijj &r*|L*2F2Fq!2L2LMMPTPZZ:t~uk"RRR*
DNTY[f7g * * %%''* *  
 %""$$Q{(KKK }Q{8[}}ftfyfyf{f{}}   (.8L },,\r,WWZZ[g[mnn},,\T\TXTa,bbl<>>*dneT]!SSS)JPUW[Wd3e ) )$$&&) )  
 "++Aq11<<>>!))*eT^LLmmK00L((r.   )NF)r&   r'   r(   r)   r?   r*   ry   r   boolr   rw   rz   r{   s   @r/   r}   r}      s        GG    2 26,1	2) 2)|2) !.2) $D>	2)
 
u|Xel33	42) 2) 2) 2) 2) 2) 2) 2)r.   r}   c                        e Zd ZdZ fdZ	 	 	 	 	 d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 )Idefics3VisionFlashAttention2aX  
    Idefics3Vision flash attention module. This module inherits from `Idefics3VisionAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S N)r>   r?   r   _flash_attn_uses_top_left_mask)rM   argskwargsrN   s      r/   r?   z&Idefics3VisionFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r.   NFr#   r   rm   past_key_valuer   	use_cacherQ   c           
         d}|                                 \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j        | j                  }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|j        d         }|||	                    || j
                  z  }|                    dd          }|                    dd          }| j        r| j        nd}|j        }|t          j        k    rt          j                    rt          j                    }n3t%          | j        d          r| j        j        }n| j        j        j        }t,                              d| d           |                    |          }|                    |          }|                    |          }t3          |||||	|| j        | j        	          }|                    ||	| j                                                  }|                     |          }|sd }||fS )
NFr   r   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   r   use_top_left_mask) rS   r   r   r   r_   r   r   rY   rW   get_usable_length	layer_idxr   r   r   r*   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr6   r   rb   loggerwarning_oncera   r   r   r   r   rA   r   r   )rM   r#   r   rm   r   r   r   r   bszr   re   r   r   r   
kv_seq_lendropout_rateinput_dtypetarget_dtyper   r   s                       r/   rw   z%Idefics3VisionFlashAttention2.forward  s    "%**,,UA{{=11[[//
{{=11
 $((eT^T]SS__S%OOYYZ[]^__
#((eT^T]SS]]^_abcc%b)
%.:::t~VVVJ  ))!Q//
#--a33'+}=t||# #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L. n"A	
 	
 	
 "))#udnEEPPRRmmK00  	 LL((r.   )NNNFF)r&   r'   r(   r)   r?   r*   ry   r   
LongTensorr   r   r   rw   rz   r{   s   @r/   r   r     s         X X X X X 6:37*."'O) O)|O) !!12O) u/0	O)
 !O)  O) O) 
u|Xel3XeEL>Q5RR	SO) O) O) O) O) O) O) O)r.   r   )eagerflash_attention_2c                   B     e Zd Z fdZdej        dej        fdZ xZS )Idefics3VisionMLPc                    t                                                       || _        t          |j                 | _        t          j        |j        |j	                  | _
        t          j        |j	        |j                  | _        d S r   )r>   r?   r6   r   
hidden_actactivation_fnr   r   r@   intermediate_sizefc1fc2rL   s     r/   r?   zIdefics3VisionMLP.__init__w  sf    #F$569V/1IJJ9V5v7IJJr.   r#   rQ   c                     |                      |          }|                     |          }|                     |          }|S r   )r   r   r   )rM   r#   s     r/   rw   zIdefics3VisionMLP.forward~  s=    //**=99//r.   )r&   r'   r(   r?   r*   ry   rw   rz   r{   s   @r/   r   r   v  sc        K K K K KU\ el        r.   r   c                   $     e Zd Z fdZd Z xZS )Idefics3SimpleMLPc                     t                                                       |j        j        |j        dz  z  }|j        j        }t          j        ||d          | _        d S )Nr   Fbias)	r>   r?   vision_configr@   scale_factortext_configr   r   proj)rM   r6   
input_sizeoutput_sizerN   s       r/   r?   zIdefics3SimpleMLP.__init__  sX    )59La9OP
(4Ij+EBBB			r.   c                 ,    |                      |          S r   )r   )rM   xs     r/   rw   zIdefics3SimpleMLP.forward  s    yy||r.   )r&   r'   r(   r?   rw   rz   r{   s   @r/   r   r     sL        C C C C C      r.   r   c            
       v     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 )
Idefics3EncoderLayerr6   c                 Z   t                                                       |j        | _        t	          |j                 |          | _        t          j        | j        |j	                  | _
        t          |          | _        t          j        | j        |j	                  | _        d S )Neps)r>   r?   r@   rA    IDEFICS_VISION_ATTENTION_CLASSES_attn_implementation	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2rL   s     r/   r?   zIdefics3EncoderLayer.__init__  s    +9&:UVW]^^<F<QRRR$V,,<F<QRRRr.   Fr#   r   r   rQ   c                     |}|                      |          }|                     |||          \  }}||z   }|}|                     |          }|                     |          }||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   )rM   r#   r   r   residualr   outputss          r/   rw   zIdefics3EncoderLayer.forward  s      !((77&*nn')/ '5 '
 '
#|
 !=0 ((77// =0 " 	'&Gr.   )F)r&   r'   r(   r   r?   r*   ry   r   r   r   r+   rw   rz   r{   s   @r/   r   r     s        S3 S S S S S S -2	$ $|$ $ $D>	$
 
u 	!$ $ $ $ $ $ $ $r.   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 )Idefics3Encoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Idefics3EncoderLayer`].

    Args:
        config: Idefics3Config
    r6   c                     t                                                       | _        t          j        fdt          j                  D                       | _        d| _        d S )Nc                 .    g | ]}t                    S r-   )r   ).0re   r6   s     r/   
<listcomp>z,Idefics3Encoder.__init__.<locals>.<listcomp>  s"    $k$k$ka%9&%A%A$k$k$kr.   F)	r>   r?   r6   r   
ModuleListrangenum_hidden_layerslayersgradient_checkpointingrL   s    `r/   r?   zIdefics3Encoder.__init__  sa    m$k$k$k$k5QWQiKjKj$k$k$kll&+###r.   Nr   r   output_hidden_statesreturn_dictrQ   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|rdnd}|rdnd}|}| j        D ]Z}	|r||fz   }| j        r%| j        r|                     |	j        |||          }
n |	|||          }
|
d         }|r||
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.
        Nr-   )r   r   r   c              3      K   | ]}||V  	d S r   r-   r   vs     r/   	<genexpr>z*Idefics3Encoder.forward.<locals>.<genexpr>  s(      eeqWXWdWdWdWdWdeer.   r!   r#   r$   )r6   r   r   use_return_dictr   r   r   _gradient_checkpointing_func__call__tupler   )rM   inputs_embedsr   r   r   r   encoder_statesall_attentionsr#   encoder_layerlayer_outputss              r/   rw   zIdefics3Encoder.forward  sx   < 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]3=0:d%![ 	F 	FM# C!/=2B!B* t}  $ A A!*!"%	! ! !.!"&7! ! ! *!,M  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r.   NNNN)r&   r'   r(   r)   r   r?   r   r*   ry   r   r   r   r   rw   rz   r{   s   @r/   r   r     s         ,~ , , , , , , 26,0/3&*E
 E
 !.E
 $D>	E

 'tnE
 d^E
 
uo%	&E
 E
 E
 E
 E
 E
 E
 E
r.   r   r#   n_reprQ   c                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||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)rW   expandr   )r#   r  batchnum_key_value_headsslenr   s         r/   	repeat_kvr    s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr.   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Idefics3RMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z>
        Idefics3RMSNorm is equivalent to T5LayerNorm
        N)r>   r?   r   	Parameterr*   onesrb   variance_epsilon)rM   r@   r   rN   s      r/   r?   zIdefics3RMSNorm.__init__*  sD     	l5:k#:#:;; #r.   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr   rV   T)keepdim)	r   ra   r*   r   powmeanrsqrtr  rb   )rM   r#   r   variances       r/   rw   zIdefics3RMSNorm.forward2  s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r.   c                 H    t          | j        j                   d| j         S )Nz, eps=)r   rb   rW   r  rM   s    r/   
extra_reprzIdefics3RMSNorm.extra_repr9  s&    )**II$2GIIIr.   )r  )r&   r'   r(   r?   rw   r  rz   r{   s   @r/   r
  r
  )  sb        $ $ $ $ $ $; ; ;J J J J J J Jr.   r
  c                   ,     e Zd Z fdZddZd Z xZS )Idefics3Connectorc                     t                                                       |j        | _        t          |          | _        d S r   )r>   r?   r   r   modality_projectionrL   s     r/   r?   zIdefics3Connector.__init__>  s:    "/#4V#<#<   r.   r   c                     |                                 \  }}}t          |dz            x}}|                    ||||          }|                    ||t          ||z            ||z            }|                    dddd          }|                    |t          ||z            t          ||z            ||dz  z            }|                    dddd          }|                    |t          ||dz  z            ||dz  z            }|S )Ng      ?r   r   r   r
   )rS   intr_   permuter   )rM   r   r   r   seqrA   heightwidths           r/   pixel_shufflezIdefics3Connector.pixel_shuffleC  s   ffhhS)S#X&FF3y11FF3EL$8 9 99|;STTIIaAq!!IIc3u|344c&<:O6P6PR[_kmn_nRoppIIaAq!!IIc3slAo677lTUo9VWWr.   c                 f    |                      || j                  }|                     |          }|S r   )r#  r   r  )rM   r%   s     r/   rw   zIdefics3Connector.forwardN  s7    "001DdFWXX"667JKK""r.   )r   )r&   r'   r(   r?   r#  rw   rz   r{   s   @r/   r  r  =  s[        = = = = =
	 	 	 	# # # # # # #r.   r  ai  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`Idefics3Config`] or [`Idefics3VisionConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zVThe bare Idefics3 Model outputting raw hidden-states without any specific head on top.c                   8    e Zd ZeZdZdZddgZdZdZ	dZ
dZd ZdS )Idefics3PreTrainedModelmodelTr}   Idefics3DecoderLayerr"   c                    t          | j        d          r| j        j        j        n| j        j        j        }t          |d          r!|j        j                            d|           t          |t          j	        t          j
        f          rJ|j        j                            d|           |j         |j        j                                         d S d S t          |t          j                  rS|j        j                            d|           |j        -|j        j        |j                                                  d S d S d S )Ninitializer_rangeclass_embeddingr   )r  std)r   r6   r   r*  r+  datanormal_
isinstancer   r   rD   rb   r   zero_rJ   padding_idx)rM   moduler,  s      r/   _init_weightsz%Idefics3PreTrainedModel._init_weightst  sA    t{$788;DK#55(: 	 6,-- 	C"'//Sc/BBBfry")455 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r.   N)r&   r'   r(   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_classr3  r-   r.   r/   r&  r&  e  sY        
 "L&*#24JK"3!N ? ? ? ? ?r.   r&  aS  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`Idefics3VisionConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zEThe Idefics3 Vision Transformer Model outputting raw image embedding.c                        e Zd ZeZdZdef fdZd Z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 )Idefics3VisionTransformerFr6   c                     t                                          |           |j        }t          |          | _        t          |          | _        |j        | _        t          j	        ||j
                  | _        |j        dk    | _        d S )Nr   r   )r>   r?   r@   r5   ri   r   encoderrC   r   r   r   post_layernormr   _use_flash_attention_2)rM   r6   rA   rN   s      r/   r?   z"Idefics3VisionTransformer.__init__  s|       &	26::&v.. + l9&:OPPP&,&AEX&X###r.   c                     | j         S r   ri   r  s    r/   get_input_embeddingsz.Idefics3VisionTransformer.get_input_embeddings  s
    r.   c                     || _         d S r   rC  rM   values     r/   set_input_embeddingsz.Idefics3VisionTransformer.set_input_embeddings  s    r.   NrP   r   r   r   rQ   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|                    d          }|p| j        }t          j        ||                    d          |z  |                    d          |z  f          }|                    t          j	        |j
                  }|                     ||          }|                    |d          }t          j        |           sd }n| j        st          ||j                  }|                     |||||          }	|	d         }
|                     |
          }
|s|
f|	dd          z   S t'          |
|	j        |	j        	          S )
Nr   r   r
   r   rc   rO   rP   rV   )r   r   r   r   r   r   r   )r6   r   r   r   rS   rC   r*   r  ra   r   rc   ri   r_   anyrA  r   r   r?  r@  r   r#   r$   )rM   rO   rP   r   r   r   rd   rC   r#   encoder_outputsr!   s              r/   rw   z!Idefics3VisionTransformer.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]!&&q))
'J#(: %%a((J6 %%a((J6$ $  $8#:#:T`Tg#:#h#h \Xlmm388RHH y..// 	i#'  , 	i#=>RTaTg#h#h ,,'//!5# ' 
 
 ,A. //0ABB 	>%'/!""*===/)7&1
 
 
 	
r.   r  )r&   r'   r(   r   r4  r:  r?   rD  rH  r   r*   rx   r   r   r   r   rw   rz   r{   s   @r/   r=  r=    s        
 (LNY3 Y Y Y Y Y Y        <@,0/3&*7
 7
 'u'787
 $D>	7

 'tn7
 d^7
 
uo%	&7
 7
 7
 7
 7
 7
 7
 7
r.   r=  a,  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

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

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

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

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

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

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

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

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

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
            [`CLIPImageProcessor`] for processing images).
        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.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zPIdefics3 model consisting of a SIGLIP vision encoder and Llama3 language decoderc                       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 ede          	 	 	 	 	 	 	 	 	 	 	 	 dd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         deeef         fd            Z xZS )Idefics3Modelr6   c                 4   t                                          |           | j        j        j        | _        | j        j        j        | _        t                              |j	                  | _
        t          |          | _        t          j        |j                  | _        t!          |j	        j        |j	        j        z  dz  |j        dz  z            | _        | j        j        | _        |j        j        dk    | _        |                                  d S )Nr   r   )r>   r?   r6   r   pad_token_idr1  
vocab_sizer=  _from_configr   vision_modelr  	connectorr   from_config
text_modelr  rB   rC   r   image_seq_lenimage_token_idr   rA  	post_initrL   s     r/   r?   zIdefics3Model.__init__8  s       ;2?+1<5BB6CWXX*622#/0BCC "-1E1PPUVV[a[npq[qr
 
 #k8&,&8&MQd&d#r.   c                     f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                     t          t          |                                                     dk    r| S  t          |                                           d                   S )Nr   )lenlistchildren)r2  get_lowest_modules    r/   r`  zCIdefics3Model.enable_input_require_grads.<locals>.get_lowest_moduleU  sW    4))**++q00 )(foo.?.?)@)@)CDDDr.   c                 0    |                     d           d S NTrequires_grad_r2  inputoutputs      r/   make_inputs_require_gradszKIdefics3Model.enable_input_require_grads.<locals>.make_inputs_require_grads]      !!$'''''r.   N)rD  register_forward_hook_text_require_grads_hookrT  _vision_require_grads_hook)rM   rh  r`  s     @r/   enable_input_require_gradsz(Idefics3Model.enable_input_require_gradsK  s    	E 	E 	E 	E 	E	( 	( 	( )-(A(A(C(C(Y(YZs(t(t%*;*;D<M*N*N*d*d%+
 +
'''r.   c                 j    | j                                          | j                                         d S r   rk  removerl  r  s    r/   disable_input_require_gradsz)Idefics3Model.disable_input_require_gradsf  2    %,,...'..00000r.   c                 4    | j                                         S r   )rW  rD  r  s    r/   rD  z"Idefics3Model.get_input_embeddingsk  s    33555r.   c                 :    | j                             |           d S r   )rW  rH  rF  s     r/   rH  z"Idefics3Model.set_input_embeddingso  s    ,,U33333r.   	input_idsr   r%   c                     |j         \  }}}|| j        k    }|                                }|                    d|          }	|	                    |j                  }	|	||<   |S )ar  
        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 that hidden state, after a pixel shuffle operation, 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.
        rV   )rW   rY  cloner_   ra   r   )
rM   ru  r   r%   
num_imagesre   vision_hidden_sizespecial_image_token_masknew_inputs_embedsreshaped_image_hidden_statess
             r/   inputs_mergerzIdefics3Model.inputs_mergerr  su     -@,E)
A)#,0C#C )//11':'?'?DV'W'W$'C'F'F}GZ'['[$6R23  r.   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.
        Nr   rm   r"   rO   pixel_attention_maskr   r   r   r   rQ   c           
      f   |
|
n| j         j        }
||n| j         j        }|	|	n| j         j        }	||n| j         j        }| j        r*| j        j        r|	rt          	                    d           d}	||j
        \  }}n||j
        \  }}}nt          d          d}|	r$|t                      }|                                }|||dk    rt          d          |: | j                                        |                              | j                  }||t          d          ||j
        \  }}}}}|                    | j                  } |j        ||z  g|j
        dd          R  }|j
        d	d                                          }|d
k                        d          |k    }||                                         }|ct-          j        |                    d          |                    d          |                    d          ft,          j        |j                  }n8 |j        ||z  g|j
        dd          R  }||                                         }| j         j        j        }|                    d	||          }|                    d||          }|                    d          dk                                    }|                     ||          j        }|                     |          }n#|!|                    | j        |j                  }|dk    r|||                      |||          }|                     |||||	|
||          }|stC          d g ||D                       S tE          |j        |j#        |j$        |j%        |          S )NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fz5You have to specify either input_ids or inputs_embedsr   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 time)r   r   r   r   )rV   r   )r   r
   )rS   r   rc   )	dimensionrS   step)rV   r   rK  rJ  )ru  r   r%   )r   r   rm   r"   r   r   r   r   c              3      K   | ]}||V  	d S r   r-   r   s     r/   r   z(Idefics3Model.forward.<locals>.<genexpr>  s"      UUqq}}}}}UUr.   )r!   r"   r#   r$   r%   )&r6   r   r   r   r   r   rW  r   r   r   rW   r   r   get_seq_lengthrD  ra   rc   r   r_   numelr]   r   r*   r  rS   r   r   rC   unfoldrT  r!   rU  r}  r   r    r"   r#   r$   )rM   ru  r   rm   r"   r   rO   r~  r%   r   r   r   r   rd   
seq_lengthre   past_seen_tokensrx  rE   r!  r"  nb_values_per_imagereal_images_indsrC   patches_subgridrP   r   s                              r/   rw   zIdefics3Model.forward  s   6 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]= 	T_C 		 	l   I  %._"J

&(5(;%J
AATUUU 	@&"....==??$):?OST?T?Tvwww BDO@@BB9MMPPQUQ\]]M #(;(Glmmm%BNBT?J
L&%'???<<L,<,Z*-D^|GYZ[Z\Z\G]^^^L #/"4QRR"8">">"@"@ , 388\8JJNaa'(89DDFFL $+',z&++A..0A0A!0D0DlFWFWXYFZFZ[*'.( ( ($$ (A';'@+(.B.H.L( ( ($ (<<L'M'X'X'Z'Z$2=J299AJ]g9hhO-44qzXb4ccO$3$7$7H$7$E$E$I#O#O#Q#Q  #'"3"3)%9 #4 # #     #'..1D"E"E ,"5"8"8tzR[Rb"8"c"cq  ]%>CVCb !..#+$7 /  M //')%+/!5# " 	
 	
  	VUU$Cg$C/B$CUUUUUU.%7#3!/) 3
 
 
 	
r.   )NNNNNNNNNNNN)r&   r'   r(   r   r?   rm  rq  rD  rH  r*   r   r   ry   r}  r   IDEFICS3_INPUTS_DOCSTRINGr   r+   rx   r   r   r   r    rw   rz   r{   s   @r/   rO  rO  3  s       
~      &
 
 
61 1 1
6 6 64 4 4!#!  -! &el3	! ! ! !2 +*	 	"  '+1537=A5948;?;?$(,0/3&*y
 y
#y
 !.y
 u/0	y

 "$u'8"9:y
   12y
 u01y
 'u'78y
 &e&78y
 D>y
 $D>y
 'tny
 d^y
 
u55	6y
 y
 y
 y
 y
 y
 y
 y
r.   rO  zThe Idefics3 Model with a language modeling head. It is made up a SigLIP vision encoder, with a language modeling head on top. c            !           e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
d	 Z ee           eee
          	 	 	 	 	 	 	 	 	 	 	 	 	 dd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ef         fd                        Z	 	 	 	 	 	 	 	 ddZ fdZ xZS ) Idefics3ForConditionalGenerationzlm_head.weightc                 >   t                                          |           t          |          | _        | j        j        | _        t          j        |j        j	        |j        j
        d          | _        |j        j
        | _
        |                                  d S )NFr   )r>   r?   rO  r'  r6   rY  r   r   r   r@   rR  lm_headrZ  rL   s     r/   r?   z)Idefics3ForConditionalGeneration.__init__  s       "6**
"k8y!3!?ASA^ejkkk ,7 	r.   c                     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                 0    |                     d           d S rb  rc  re  s      r/   rh  z^Idefics3ForConditionalGeneration.enable_input_require_grads.<locals>.make_inputs_require_grads-  ri  r.   N)rD  rj  rk  r'  rT  rl  )rM   rh  s     r/   rm  z;Idefics3ForConditionalGeneration.enable_input_require_grads'  sh    	( 	( 	( )-(A(A(C(C(Y(YZs(t(t%*.**A*V*V*X*X*n*n%+
 +
'''r.   c                 j    | j                                          | j                                         d S r   ro  r  s    r/   rq  z<Idefics3ForConditionalGeneration.disable_input_require_grads6  rr  r.   c                 >    | j         j                                        S r   )r'  rW  rD  r  s    r/   rD  z5Idefics3ForConditionalGeneration.get_input_embeddings;  s    z$99;;;r.   c                 D    | j         j                            |           d S r   )r'  rW  rH  rF  s     r/   rH  z5Idefics3ForConditionalGeneration.set_input_embeddings?  s!    
22599999r.   c                     | j         S r   r  r  s    r/   get_output_embeddingsz6Idefics3ForConditionalGeneration.get_output_embeddingsC  s
    |r.   c                     || _         d S r   r  )rM   new_embeddingss     r/   set_output_embeddingsz6Idefics3ForConditionalGeneration.set_output_embeddingsG  s    %r.   c                     |                                  }|                                 }t          | j        dd          r|j        |_        dS dS )z
        Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of DecoupledLinear and DecoupledEmbedding.
        tie_word_embeddingsTN)r  rD  getattrr6   rb   )rM   output_embeddingsinput_embeddingss      r/   tie_weightsz,Idefics3ForConditionalGeneration.tie_weightsK  s[     !668844664; 5t<< 	?'7'>$$$	? 	?r.   )output_typer4  Nru  r   rm   r"   r   rO   r~  r%   labelsr   r   r   r   rQ   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||||||
|||          }|d         }|                     |          }d}|	L|                                }|	                    |j                  }	||dd|j	        d         dz
   df                             |j                  }|dddddf         |dk             
                                }|	dddf         |dk             
                                }n?|dddddf         
                                }|	dddf         
                                }t                      } ||                    d|                    d                    |                    d                    }|s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        |j                  S )a  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `Idefics3ForConditionalGeneration`).
                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]`.
        Returns:

        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/Idefics3-8B-Llama3")
        >>> model = AutoModelForVision2Seq.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3", torch_dtype=torch.bfloat16, device_map="auto")

        >>> # Create inputs
        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image"},
        ...             {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
        ...             {"type": "image"},
        ...             {"type": "text", "text": "What can we see in this image?"},
        ...         ]
        ...     },
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image"},
        ...             {"type": "text", "text": "In which city is that bridge located?"},
        ...         ]
        ...     }
        ... ]

        >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
        >>> images = [[image1, image2], [image3]]
        >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)

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

        >>> print(generated_texts[0])
        Assistant: There are buildings, trees, lights, and water visible in this image.

        >>> print(generated_texts[1])
        Assistant: The bridge is in San Francisco.
        ```N)ru  r   rm   r"   r   rO   r~  r%   r   r   r   r   r   r   .rV   )r2   r3   r"   r#   r$   r%   )r6   r   r   r   r'  r  floatra   rc   rW   r   r	   r_   rS   r1   r"   r#   r$   r%   )rM   ru  r   rm   r"   r   rO   r~  r%   r  r   r   r   r   r   r#   r3   r2   shift_attention_maskshift_logitsshift_labelsloss_fctrg  s                          r/   rw   z(Idefics3ForConditionalGeneration.forwardU  s^   ` 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'%!5 3/!5#  
 
  
m,,\\^^FYYv}--F) (6aaa6<?Q;N9O9Q9Q6Q'R'U'UV\Vc'd'd$%c3B3k23G13LMXXZZ%c122g/Cq/HITTVV%c3B3k2==??%c122g99;;'))H8L--b,2C2CB2G2GHH,J[J[\^J_J_``D 	DY,F'+'7D7V##VC-#3!/) ' ;
 
 
 	
r.   c
           
      z   |E||d d |j         d          d f         }n(|j         d         |j         d         k    r|d d |f         }|
                    dd           }|b|`|                                                    d          dz
  }|                    |dk    d           |r|d d |j         d          d f         }||d         dk    r||d}n#|                    t          j                  d d}|	|	|d<   |d }d }n|}|}|                    |||
                    d	          ||||d
           |S )Nr   r   rm   rV   )r   ru  )memory_format)ru  r   num_logits_to_keepr   )rm   r"   r   r   rO   r~  r%   )	rW   getlongcumsummasked_fill_rw  r*   contiguous_formatupdate)rM   ru  r"   r   r   cache_positionrO   r~  r%   r  r   rm   model_inputss                r/   prepare_inputs_for_generationz>Idefics3ForConditionalGeneration.prepare_inputs_for_generation  s   " &(%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	zz.$77%,*>)..0077;;a?L%%n&91=== F+AAA	0B/B/D/D,DE $):a)?)?-:SSLL *3uG^)_)_rvwwL)1CL-.*L#'  'L#7  ,#2#ZZ44"0 ,(<': 
	
 
	
 
	
 r.   c                 V     t                      j        d|||d|}|j        |d<   |S )N)r   model_kwargsis_encoder_decoderr%   r-   )r>   #_update_model_kwargs_for_generationr%   )rM   r   r  r  r   rN   s        r/   r  zDIdefics3ForConditionalGeneration._update_model_kwargs_for_generation  sN    BuwwB 
%1
 
 	
 
 /6.I*+r.   )NNNNNNNNNNNNN)NNNNNNNN)r&   r'   r(   _tied_weights_keysr?   rm  rq  rD  rH  r  r  r  r   r  r   r1   _CONFIG_FOR_DOCr*   r   r   ry   r   r+   rx   r   r   r   rw   r  r  rz   r{   s   @r/   r  r    sn       
 ++	 	 	 	 	
 
 
1 1 1
< < <: : :  & & &? ? ? +*+DEE+IXghhh '+1537=A5948;?;?-1$(,0/3&*E
 E
#E
 !.E
 u/0	E

 "$u'8"9:E
   12E
 u01E
 'u'78E
 &e&78E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u44	5E
 E
 E
 ih FEE
V ! ; ; ; ;|	 	 	 	 	 	 	 	 	r.   r  )Dr)   dataclassesr   typingr   r   r   r   r*   torch.utils.checkpointr   torch.nnr	    r   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   utilsr   r   r   r   r   r   autor   configuration_idefics3r   r   modeling_flash_attention_utilsr   
get_loggerr&   r   r  r    r1   Moduler5   r}   r   r   r   r   r   r   ry   r  r  r
  r  IDEFICS3_START_DOCSTRINGr&  IDEFICS3_VISION_START_DOCSTRINGr=  r  rO  r  r-   r.   r/   <module>r     s     ! ! ! ! ! ! / / / / / / / / / / / /            % % % % % %       ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) ) B B B B B B < < < < < < < <                      H H H H H H H H  KJJJJJJ 
	H	%	%" #C #C #C #C #Ck #C #C #CL "C "C "C "C "C[ "C "C "CL7 7 7 7 7ry 7 7 7vL) L) L) L) L)bi L) L) L)`_) _) _) _) _)$; _) _) _)F %6$ $      	       	   . . . . .29 . . .dU
 U
 U
 U
 U
bi U
 U
 U
r	UU\ 	U# 	U%, 	U 	U 	U 	UJ J J J Jbi J J J(# # # # #	 # # #. " \ ? ? ? ? ?o ? ?	 ?># " K# M
 M
 M
 M
 M
 7 M
 M
	 M
`C L Z Y
 Y
 Y
 Y
 Y
+ Y
 Y
	 Y
x  J O O O O O'> O O	 O O Or.   