
    sg=                       d Z ddlmZ ddlmZmZmZmZmZm	Z	 ddl
Z
ddlmc mZ ddlZ
ddl
mZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddlmZ ddlmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-  e&j\                  e/      Z0dZ1e G d de             Z2e G d de             Z3	 	 	 	 d6dZ4g fdZ5 G d dejl                        Z7 G d dejp                        Z9 G d d ejt                        Z; e"jx                  e;        G d! d"e
j                  jt                        Z=d# Z>d7d$Z? G d% d&ejt                        Z@ G d' d(ejt                        ZA G d) d*ejt                        ZB G d+ d,ejt                        ZCd-ZD e$d.eD       G d/ d0e              ZEd1ZF e$d.eD       G d2 d3eE             ZG G d4 d5eEe      ZHy)8zPyTorch Idefics model.    )	dataclass)AnyDictListOptionalTupleUnionN)nn)CrossEntropyLoss   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)ModelOutput)PretrainedConfigPreTrainedModel)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )IdeficsConfig)IdeficsPerceiverResampler)IdeficsVisionTransformerr   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<   y)IdeficsBaseModelOutputWithPasta	  
    Base class for Idefics model's outputs that may also contain a past key/values (to speed up sequential decoding).

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.

            If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
            hidden_size)` is output.
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
            `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
            input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.

            image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
    Nlast_hidden_statepast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r!   torchFloatTensor__annotations__r"   r   r   r#   r$   r%        _/var/www/html/venv/lib/python3.12/site-packages/transformers/models/idefics/modeling_idefics.pyr    r    6   s    "H ,0u((/AEOXeE%*;*;$<=>E8<M8E%"3"345<59Ju00129>B%(9(9":;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<   y)	IdeficsCausalLMOutputWithPasta  
    Base class for Idefics causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
            Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
            sequence_length, hidden_size)`.

            image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
    Nlosslogitsr"   r#   r$   r%   )r&   r'   r(   r)   r2   r   r*   r+   r,   r3   r"   r   r#   r   r$   r%   r-   r.   r/   r1   r1   c   s    @ )-D(5$$
%, $FE$9=OXd5#4#456=8<M8E%"3"345<59Ju00129>B%(9(9":;Br.   r1   c                    t        j                  | j                  d         j                  dd      j	                  d|      j                  d      j                  | j                        }| j                  d|      } |j                  dd       |d<   |j                  dd       |d<   |j                  dd       |d<   |j                  dd       |d<   d|v r|d   }|j                  d|      |d<   ||j                  d|      |d	<   |d   |d   j                  d|      |d<   |d   |d   j                  d|      |d<   | |fS |d   |d   j                  d|      |d<   | |fS |d   |d   j                  d|      |d<   | |fS )
Nr   r   pixel_valuesimage_encoder_embeddingsperceiver_embeddingsimage_attention_masktoken_type_idsattention_mask)	r*   arangeshapeviewrepeattodeviceindex_selectget)	input_idsexpand_sizeis_encoder_decoderr;   encoder_outputsmodel_kwargsexpanded_return_idxr:   s           r/   expand_inputs_for_generationrJ      s    	Y__Q'(--b!4;;A{KPPQSTWWXaXhXhi  &&q*=>I#/#3#3ND#IL /;/?/?@Z\`/aL+,+7+;+;<RTX+YL'(+7+;+;<RTX+YL'(<'%&67)7)D)DQH[)\%&!)7)D)DQH[)\%&*+7/;<R/S/`/`"0
+, N#/'3N'C'P'PQRTg'h^$ l"" 
0	1	=3?@Z3[3h3h"4
/0 l"" 
,	-	9/;<R/S/`/`"0
+, l""r.   c                 2   t         j                  t         j                  t         j                  d}|D cg c]  }||   	 }}| j	                         D ];  |r&t        fd|D              rj                  d       +j                  d       = | S c c}w )N)	LayerNormLinear	Embeddingc              3   6   K   | ]  }t        |        y wN)
isinstance).0tmodules     r/   	<genexpr>zfreeze_model.<locals>.<genexpr>   s     $]qZ%:$]s   TF)r
   rL   rM   rN   modulesanyrequires_grad_)modelmodule_exceptionsmappingmmodule_exceptions_mappedrT   s        @r/   freeze_modelr^      s    \\))\\G
 5FFq
FF--/ )$]D\$]!]!!$'!!%(	)
 L  Gs   Bc                   N     e Zd ZdZ	 	 	 	 ddee   ddf fdZd ZdefdZ	 xZ
S )	IdeficsDecoupledEmbeddinga  
    Implements a decoupling of parameters to allow freezing (or not) a subset of the embeddings. In practise, the
    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `num_additional_embeddings` > 0,
    then it will create `num_additional_embeddings` additional parameters that are always trained. If
    `num_additional_embeddings=0`, then the module defaults back to the regular behavior of `nn.Embedding`.
    Npartially_freezereturnc           	      B   |||kD  rt        d| d|       t        	|   d|||||d| || _        || _        || _        || _        |r| j                  j                  d       | j
                  dkD  r)t        j                  | j
                  |||      | _        yy)	a)  
        Args:
            num_embeddings (`int`):
                Size of the dictionary of embeddings
            num_additional_embeddings (`int`):
                Number of additional embeddings. Only useful when you `partially_freeze=True`.
            embedding_dim (`int`):
                The size of each embedding vector
            partially_freeze: (`bool`, *optional*, defaults to `False`):
                If `True`, the regular `weight` will be frozen. `additional_weight` is never frozen.
            padding_idx (`int`, *optional*):
                The padding index (needs to be less than num_embeddings)

        Note: there are a lot of other parameters to initialize a standard `nn.Embedding` such as `padding_idx`,
        `max_norm` or `norm_type`. We are not supporting these.
        Nz/padding_idx must be within num_embeddings. Got z and )num_embeddingsembedding_dimrA   dtypepadding_idxFr   )rd   re   rA   rf   r-   )
ValueErrorsuper__init__rd   rg   num_additional_embeddingsra   weightrX   r
   rN   additional_embedding)
selfrd   rk   re   ra   rA   rf   rg   kwargs	__class__s
            r/   rj   z"IdeficsDecoupledEmbedding.__init__   s    6 "{^'CN{m[`ao`pqrr 	
)'#	
 	
 -&)B& 0KK&&u-))A-(*#==+	)D% .r.   c                 b   | j                   dk(  r t        j                  || j                        S |j	                         }t        j                  || j                  k\        }||   }| j                  || j                  z
        }d||<   t        j                  || j                        }|||<   |S )a  
        we have 2 embeddings, with different indices - one pretrained self.weight and another
        self.additional_embedding.weight that is being trained.

        in order to make a lookup of the input ids, we:
        1. find out the indices of the entries belonging to the 2nd embedding
        2. extract those values while subtracting the size of the first embedding (num_embeddings), since the 2nd
           embedding starts from 0 and not num_embeddings
        3. perform the 2nd embedding lookup
        4. now we handle the 1st embedding, we overwrite indices belonging to the 2nd embedding with a padding index
        5. perform the 1st embedding lookup
        6. now we overwrite the values in the 1st embedding lookup with the values of the 2nd embedding lookup

        note: for the 1st embedding lookup we could have looked up only the low indices and not do the padding, but
        then we have to create a new tensor and populate it with 2 tensors that are spread out across various indices -
        i.e. not a simple concat - I haven't benchmarked the complex case if it's any faster, given that seqlens are
        usually relatively short it's probably not faster or if faster not by much - but might be a good idea to
        measure.

        r   )	rk   F	embeddingrl   cloner*   whererd   rm   )rn   rD   additional_vocab_indicesinput_ids_additional_vocabadditional_embeddingsfull_vectors         r/   forwardz!IdeficsDecoupledEmbedding.forward  s    * ))Q.;;y$++66 OO%	#(;;yD<O<O/O#P %./G%H" $ 9 9:TW[WjWj:j k /0	*+kk)T[[9 1F,-r.   c                 z    dj                  | j                  | j                  | j                  | j                        S )NzVnum_embeddings={}, num_additional_embeddings={}, embedding_dim={}, partially_freeze={})formatrd   rk   re   ra   rn   s    r/   
extra_reprz$IdeficsDecoupledEmbedding.extra_repr.  s9    gnn**!!	
 	
r.   )FNNN)r&   r'   r(   r)   r   boolrj   rz   strr~   __classcell__rp   s   @r/   r`   r`      sF     ,13
 #4.3 
3j%N
C 
r.   r`   c                        e Zd ZdZ	 	 	 	 	 ddedededededdf fd	Zd
ej                  dej                  fdZ	de
fdZ xZS )IdeficsDecoupledLineara  
    Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the
    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0,
    then it will create `out_additional_features * in_features` additional parameters that are always trained. If
    `out_additional_features=0`, then the module defaults back to the regular behavior of `nn.Linear`.
    Nin_featuresout_featuresout_additional_featuresbiasra   rb   c                 "   t         |   |||||       || _        || _        || _        || _        |r8| j                  j                  d       |r| j                  j                  d       |dkD  r t        j                  |||||      | _        yy)aG  
        out_additional_features: int. Number of additional trainable dimensions. Only makes sense when
        `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra
        parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear.
        Fr   )r   r   r   rA   rf   N)ri   rj   r   ra   r   r   rl   rX   r   r
   rM   additional_fc)	rn   r   r   r   r   ra   rA   rf   rp   s	           r/   rj   zIdeficsDecoupledLinear.__init__@  s     	lD&%H'>$ 0&(KK&&u-		((/"Q&!#'4"D 'r.   inputc                     t        j                  || j                  | j                        }| j                  dkD  r)| j                  |      }t        j                  ||fd      }|S )Nr   r5   )rr   linearrl   r   r   r   r*   cat)rn   r   outputadditional_featuress       r/   rz   zIdeficsDecoupledLinear.forwardd  sV    %dii8''!+"&"4"4U";YY(;<bAFr.   c                     dj                  | j                  | j                  | j                  | j                  du| j
                        S )z=Overwriting `nn.Linear.extra_repr` to include new parameters.zYin_features={}, out_features={}, out_additional_features={}, bias={}, partially_freeze={}N)r|   r   r   r   r   ra   r}   s    r/   r~   z!IdeficsDecoupledLinear.extra_reprm  sE    jqq((IIT!!!
 	
r.   )r   TTNN)r&   r'   r(   r)   intr   rj   r*   Tensorrz   r   r~   r   r   s   @r/   r   r   7  s     ()!%"" " "%	"
 " " 
"HU\\ ell 
C 
r.   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )IdeficsRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        IdeficsRMSNorm is equivalent to T5LayerNorm
        N)ri   rj   r
   	Parameterr*   onesrl   variance_epsilon)rn   hidden_sizeepsrp   s      r/   rj   zIdeficsRMSNorm.__init__z  s1     	ll5::k#:; #r.   c                    |j                  t        j                        j                  d      j	                  dd      }|t        j
                  || j                  z         z  }| j                  j                  t        j                  t        j                  fv r%|j                  | j                  j                        }| j                  |z  S )N   r5   T)keepdim)r@   r*   float32powmeanrsqrtr   rl   rf   float16bfloat16)rn   r#   variances      r/   rz   zIdeficsRMSNorm.forward  s     ##EMM266q9>>r4>P%Ht?T?T4T(UU ;; ??),,T[[->->?M{{]**r.   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tuplerl   r=   r   r}   s    r/   r~   zIdeficsRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr.   )gư>)r&   r'   r(   rj   rz   r~   r   r   s   @r/   r   r   y  s    $+Jr.   r   c                   .     e Zd Zd fd	Zd ZddZ xZS )IdeficsEmbeddingc                    t         |           || _        || _        || _        d| j                  t        j                  d| j                  dt
        j                        j                         j                  |      | j                  z  z  z  }| j                  d|d       | j                  || j                  j                  t        j                                y )	Ng      ?r   r   rf   inv_freqF
persistentseq_lenrA   rf   )ri   rj   dimmax_position_embeddingsbaser*   r<   int64floatr@   register_buffer_set_cos_sin_cacher   rA   get_default_dtype)rn   r   r   r   rA   r   rp   s         r/   rj   zIdeficsEmbedding.__init__  s    '>$	$))Q!5;;(W(](](_(b(bci(jmqmumu(uvwZeD 	+DMM4H4HPUPgPgPi 	  	
r.   c                    || _         t        j                  | j                   |t        j                        j	                  | j
                        }t        j                  d|| j
                        }t        j                  ||fd      }| j                  d|j                         j                  |      d       | j                  d|j                         j                  |      d       y )	N)rA   rf   zi,j->ijr5   r   
cos_cachedFr   
sin_cached)max_seq_len_cachedr*   r<   r   type_asr   einsumr   r   cosr@   sin)rn   r   rA   rf   rS   freqsembs          r/   r   z#IdeficsEmbedding._set_cos_sin_cache  s    ")LL00u{{S[[\`\i\ijY4==9iiB/\3779<<+>5Q\3779<<+>5Qr.   c                    || j                   kD  r(| j                  ||j                  |j                         | j                  d | j                  |j                        | j                  d | j                  |j                        fS )Nr   r   )r   r   rA   rf   r   r@   r   )rn   xr   s      r/   rz   zIdeficsEmbedding.forward  sy    T,,,##GAHHAGG#T OOHW%((qww(7OOHW%((qww(7
 	
r.   )i   i'  NrP   )r&   r'   r(   rj   r   rz   r   r   s   @r/   r   r     s    
R
r.   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr5   r   r   )r=   r*   r   )r   x1x2s      r/   rotate_halfr     sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r.   c                     ||   j                  |      }||   j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )an  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr   r   position_idsunsqueeze_dimq_embedk_embeds           r/   apply_rotary_pos_embr     sg    * l

%
%m
4C
l

%
%m
4C3w;q>C/0G3w;q>C/0GGr.   c                   2     e Zd Zdededef fdZd Z xZS )
IdeficsMLPr   intermediate_size
hidden_actc                     t         |           t        j                  ||d      | _        t        j                  ||d      | _        t        j                  ||d      | _        t        |   | _        y )NFr   )	ri   rj   r
   rM   	gate_proj	down_projup_projr   act_fn)rn   r   r   r   rp   s       r/   rj   zIdeficsMLP.__init__  s[     	;0AN#4kNyy.?eLZ(r.   c                     | j                  | j                  | j                  |            | j                  |      z        S rP   )r   r   r   r   )rn   r   s     r/   rz   zIdeficsMLP.forward  s0    ~~dkk$..*;<t||ANOOr.   )r&   r'   r(   r   r   rj   rz   r   r   s   @r/   r   r     s*    
)
) 
) 	
)Pr.   r   c                       e Zd ZdZ	 	 	 	 	 ddededededededef fd	Zd
e	j                  dedefdZ	 	 	 	 	 	 	 dde	j                  dee	j                     dee	j                     dee	j                     deee	j                        dededee	j                     dee	j                  ee	j                     eee	j                        f   fdZ xZS )IdeficsAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr   	num_headsdropoutis_cross_attentionconfigqk_layer_norms	layer_idxc                    t         	|           || _        || _        ||z  | _        || _        d| _        || _        |-t        j                  d| j                  j                   d       | j                  |z  | j                  k7  rt        d| j                   d| d      || _        t        t        j                   d      st        d      | j                  rt        |j"                  d	      s| j                  n|j"                  j$                  }t        j&                  | j                  || j                  z  d
      | _        t        j&                  ||| j                  z  d
      | _        t        j&                  ||| j                  z  d
      | _        nt        j&                  | j                  || j                  z  d
      | _        t        j&                  | j                  || j                  z  d
      | _        t        j&                  | j                  || j                  z  d
      | _        t        j&                  || j                  z  |d
      | _        t1        | j                        | _        || _        | j4                  rMt7        | j                  |j8                        | _        t7        | j                  |j8                        | _        y y )NTzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).scaled_dot_product_attentionz)this model requires pytorch 2.0 or higher	embed_dimFr   r   )ri   rj   r   r   head_dimr   	is_causalr   loggerwarning_oncerp   r&   rh   r   hasattrr
   
functionalvision_configr   rM   q_projk_projv_projo_projr   
rotary_embr   r   rms_norm_epsq_layer_normk_layer_norm)
rn   r   r   r   r   r   r   r   kv_input_dimrp   s
            r/   rj   zIdeficsAttention.__init__  su    	&"#y0" !8!8 9 :, , MMI%$*:*::QRVRbRbQc$YKr3 
 #5r}}&DEHII""(/0D0Dk(R  X^XlXlXvXv  ))  DMM)DK
 ))L)dmm2KRWXDK))DMM)DK ))  DMM)DK
 ))  DMM)DK
 ))  DMM)DK
 ii%

 +4==9, .t}}&BUBU VD .t}}&BUBU VD r.   tensorr   bszc                     |j                  ||| j                  | j                        j                  dd      j	                         S )Nr   r   )r>   r   r   	transpose
contiguous)rn   r   r   r   s       r/   _shapezIdeficsAttention._shapeA  s7    {{3GQQRSUVWbbddr.   r#   key_value_statesr;   r   past_key_valueoutput_attentions	use_cachecache_positionrb   c	                    | j                   xs |d u}	|j                         \  }
}}| j                  |      j                  |
|| j                  | j
                        j                  dd      }|	s| j                  |      j                  |
|| j                  | j
                        j                  dd      }| j                  |      j                  |
|| j                  | j
                        j                  dd      }n|j                         \  }}}| j                  |      j                  |
|| j                  | j
                        j                  dd      }| j                  |      j                  |
|| j                  | j
                        j                  dd      }|j                  d   }|||d   z  }|	s2| j                  |t        ||            \  }}t        |||||      \  }}|%d|i}|j                  ||| j                  |      \  }}| j                  r"| j!                  |      }| j#                  |      }|}||d d d d d d d |j                  d   f   }|j$                  j&                  dk(  r2|0|j)                         }|j)                         }|j)                         }| j*                  r	||dkD  rdnd	}t,        j.                  j0                  j3                  ||||| j4                  r| j6                  nd
|      }|j                         |
| j                  || j
                  fk7  r7t9        d|
| j                  || j
                  f d|j                                |j                  dd      }|j;                  |
|| j<                        }| j?                  |      }d }|rt@        jC                  d       |||fS )Nr   r   r   )r   r  cudaTF        )	attn_mask	dropout_pr   z `attn_output` should be of size z	, but is z^attn_weights are not extracted in scaled_dot_product_attention. The model returns None instead)"r   sizer   r>   r   r   r   r   r   r=   r   maxr   updater   r   r   r   rA   typer   r   r*   r
   r   r   trainingr   rh   reshaper   r   r   r   )rn   r#   r   r;   r   r  r  r  r  r   r   q_len_query_states
key_statesvalue_stateskv_len
kv_seq_lenr   r   cache_kwargscausal_maskr   attn_outputattn_weightss                            r/   rz   zIdeficsAttention.forwardD  s    "44T8HPT8T%**,UA{{=166sE4>>SWS`S`akklmopq!]388eT^^UYUbUbcmmnoqrsJ;;}5::3t~~W[WdWdeoopqstuL+002LAvq%56;;CY]YfYfgqqrsuvwJ,-223PTP]P]^hhijlmn   %%b)
%.++J!|SU=STHC';L*VY[^`l'm$L* %,n=L'5'<'<ZW[WeWegs't$J,,\:L**:6J$%%aA/E1A1A"1E/E&EFK ##v-.2L'224L#..0J'224L
 !NN{/BuqyDV[	hh))FF!&*mmdll G 
 #t~~udmm!LL2CPTP]P]3^2_ `$$&') 
 "++Aq1!))#ud6F6FGkk+.p L.88r.   )r  FNFNNNNNFFN)r&   r'   r(   r)   r   r   r   r   rj   r*   r   r   r   
LongTensorr   rz   r   r   s   @r/   r   r     sr   G #(#'$MWMW MW 	MW
 !MW !MW MW MW^eU\\ eC ec e 4815378<"'59W9||W9 #5<<0W9 !.	W9
 u//0W9 !u||!45W9  W9 W9 !!1!12W9 
u||Xell3XeELL>Q5RR	SW9r.   r   c                   D    e Zd Zddedef fdZ	 	 	 	 	 	 ddej                  deej                     deej                     dee
ej                        dee   d	ee   d
eej                     de
ej                  ee
ej                  ej                  f      f   fdZ xZS )IdeficsDecoderLayerr   r   c                    t         |           |j                  | _        t        | j                  |j                  |j
                  ||      | _        t        | j                  |j                  |j                        | _
        t        |j                  |j                        | _        t        |j                  |j                        | _        |j
                  | _        y )N)r   r   r   r   r   r   r   r   r   )ri   rj   r   r   num_attention_headsr   	self_attnr   r   r   mlpr   r   input_layernormpost_attention_layernorm)rn   r   r   rp   s      r/   rj   zIdeficsDecoderLayer.__init__  s    !--)((00NN
 (($66((

  .f.@.@fFYFYZ(6v7I7IvObOb(c%~~r.   r#   r;   r   r  r  r  r  rb   c           	         |}| j                  |      }| j                  |||||||      \  }}	}
t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|f}|r||	fz  }|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`, *optional*): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
        )r#   r;   r   r  r  r  r  pr  )r%  r#  r
   r   r   r  r&  r$  )rn   r#   r;   r   r  r  r  r  residualself_attn_weightspresent_key_valueoutputss               r/   rz   zIdeficsDecoderLayer.forward  s   0 !,,]; ?Cnn')%)/) ?M ?
;(*; --mt||VZVcVc-d =0 !55mD/--mt||VZVcVc-d =0 ")++G)++Gr.   rP   )NNNFFN)r&   r'   r(   r   r   rj   r*   r   r   r  r   r   r+   rz   r   r   s   @r/   r  r    s    &} & &, 26378<,1$)598||8 !.8 u//0	8
 !u||!458 $D>8 D>8 !!1!128 
u  (51B1BEDUDU1U+V"WW	X8r.   r  c                   ^    e Zd Zdef fdZ	 	 	 	 	 	 	 dd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	ej                        de	ej                  ee	ej                  ej                  f      f   fdZ xZS )IdeficsGatedCrossAttentionLayerr   c           	      	   t         |           |j                  | _        t        | j                  |j                  d|j
                  ||j                        | _        t        | j                  |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        |j
                  | _        t#        j$                         | _        t#        j$                         | _        |j*                  dk(  r|j,                  dk(  rtt#        j.                  t1        j2                  dd| j                              | _        t#        j.                  t1        j2                  dd| j                              | _        n|j,                  dk(  r\t#        j.                  t1        j2                  d            | _        t#        j.                  t1        j2                  d            | _        nt9        d	|j,                   d
      |j*                  dk(  r|j,                  dk(  rtt#        j.                  t1        j:                  dd| j                              | _        t#        j.                  t1        j:                  dd| j                              | _        n|j,                  dk(  r\t#        j.                  t1        j:                  d            | _        t#        j.                  t1        j:                  d            | _        n|t9        d	|j,                   d
      |j*                  dv r;|j,                  dk(  rt#        j.                  t1        j<                  d|j>                  dd| j                  f            | _        t#        j.                  t1        j<                  d|j>                  dd| j                  f            | _        n|j,                  dk(  rut#        j.                  t1        j<                  d|j>                  d            | _        t#        j.                  t1        j<                  d|j>                  d            | _        n2t9        d	|j,                   d
      tA        d|j*                   d      tC        | d      rtC        | d      st9        d      y )NT)r   r   r   r   r   r   r!  r   zerosvectorr   r   z Unknown value for `alpha_type` ()r   >   normalrandomgaussianr  )r   stdr  zAlpha initialization scheme z not yet implemented!alpha_cross_attnalpha_densez+Alpha parameters not initialized correctly!)"ri   rj   r   r   r"  r   r   
cross_attnr   r   r   r$  r   r   r%  r&  r   r
   Tanhact_cross_attn	act_densealpha_initializer
alpha_typer   r*   r1  r8  r9  rh   r   r4  alphas_initializer_rangeNotImplementedErrorr   )rn   r   rp   s     r/   rj   z(IdeficsGatedCrossAttentionLayer.__init__  s   !--*((00#NN!00
 (($66((

  .f.@.@fFYFYZ(6v7I7IvObOb(c%nn ggi##w.  H,(*U[[AtGWGW5X(Y%#%<<Aq$BRBR0S#T ""g-(*U[[^(D%#%<<A#?  #CFDUDUCVVW!XYY%%/  H,(*UZZ1dFVFV5W(X%#%<<

1aAQAQ0R#S ""g-(*UZZ](C%#%<<

1#>  #CFDUDUCVVW!XYY%%)II  H,(*LLcv/N/NVWYZ\`\l\lUmn)% $&<<LLcv/N/NVWYZ\`\l\lUmn$  ""g-(*LLcv/N/NVWY)% $&<<#6KjKjrs0u#v  #CFDUDUCVVW!XYY &(DVE]E]D^^s&tuu01gdM6RJKK 7Sr.   r#   r;   r%   r9   cross_attention_gater  r  r  rb   c	                    |t        d      |t        d      |t        d      |}	| j                  |      }| j                  ||||      \  }}
}t        j
                  j                  || j                  | j                        }||dk(     j                  d      ||dk(  <   |	| j                  | j                        |z  z   }|}	| j                  |      }| j                  |      }t        j
                  j                  || j                  | j                        }|	| j                  | j                        |z  z   }|f}|r||
fz  }|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`, *optional*): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            image_attention_mask (`torch.FloatTensor`, *optional*): image attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            cross_attention_gate (`torch.FloatTensor`, *optional*):
                gate of size `(batch, seq_len)` used to zero-out cross-attention output for tokens attending no images.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
        zt`image_hidden_states` is required for Idefics cross attention module which are visual features to be conditioned on.z`cross_attention_gate` is required for Idefics cross attention module to zero-out the cross-attention hidden_states attending to no images.zMPast key value states are not implemented for Idefics cross attention module.)r#   r   r;   r  r(  r   )rh   rA  r%  r:  r
   r   r   r   r  fill_r<  r8  r&  r$  r=  r9  )rn   r#   r;   r%   r9   rB  r  r  r  r*  r+  r,  r-  s                r/   rz   z'IdeficsGatedCrossAttentionLayer.forward0  s   8 &# 
  ' ^  %%&uvv ,,]; ?Coo'0//	 ?N ?
;(*; --mt{{UYUbUb-c3@AUYZAZ3[3a3abc3d*a/0 4#6#6t7L7L#MP]#]] !55mD/--mt{{UYUbUb-c 4>>$2B2B#Cm#SS ")++G)++Gr.   r  )r&   r'   r(   r   rj   r*   r   r   r   r   r+   rz   r   r   s   @r/   r/  r/    s    ?L} ?LH 266:7;7;,1$)8<I||I !.I &ell3	I
 'u||4I 'u||4I $D>I D>I !u||!45I 
u  (51B1BEDUDU1U+V"WW	XIr.   r/  aL  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`IdeficsConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare LLaMA Model outputting raw hidden-states without any specific head on top.c                   2    e Zd ZeZdZdZddgZdZdZ	dZ
d Zy)IdeficsPreTrainedModelrY   Tr  r/  c                    | j                   j                  }t        |t        j                        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 y )Nr  )r   r7  )r   initializer_rangerQ   r
   rM   rl   datanormal_r   zero_rN   rg   )rn   rT   r7  s      r/   _init_weightsz$IdeficsPreTrainedModel._init_weights  s     kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r.   N)r&   r'   r(   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_cache_class_supports_static_cacherL  r-   r.   r/   rF  rF    s7    
 !L&*#.0QRN !?r.   rF  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.
        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.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c            $           e Zd ZdZdef fdZd"dZg fdZg fdZd Z	d Z
 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   deej                     deeef   f d       Zd
ej                   dej                   dej                   dedef
dZed
ej                   dededej8                  dej:                  dej                   d efd!       Z xZS )$IdeficsModelz
    Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a [`IdeficsDecoderLayer`]

    Args:
        config: IdeficsConfig
    r   c           	      f   t         |   |       || _        |j                  | _        |j
                  | _        t        |j
                  |j                  |j                  |j                  | j                        | _
        |j                  j                  | _        |j                  | _        t        |j                        | _        |j                  r]|j                   }t#        ||j                  j$                  |j&                  |j(                  |j*                  |j,                        | _        t1        j2                  t5        |j6                        D cg c]  }t9        ||       c}      | _        |j<                  | _        |j6                  | j<                  z  }t1        j2                  t5        |      D cg c]  }t?        |       c}      | _         d| _!        tE        |j                  |jF                        | _$        | jK                          | jM                  |       y c c}w c c}w )N)rd   rk   re   ra   rg   )r   Fr   )'ri   rj   r   pad_token_idrg   
vocab_sizer`   additional_vocab_sizer   freeze_text_layersembed_tokensr   
image_sizer   vision_modeluse_resamplerperceiver_configr   r   resampler_depthresampler_n_headsresampler_head_dimresampler_n_latentsperceiver_resamplerr
   
ModuleListrangenum_hidden_layersr  layerscross_layer_intervalr/  gated_cross_attn_layersgradient_checkpointingr   r   norm	post_initfreeze_relevant_params)rn   r   r_  inum_cross_layersr  rp   s         r/   rj   zIdeficsModel.__init__  s    !.. ++5!,,&,&B&B ,,#66((
 !..99#114V5I5IJ %66'@$$.. 00 22 33 44(D$ mm?DVE]E]?^_! 15_
 %+$?$?!!33t7P7PP')}}>CDT>UV,V4V(
$ ',#"6#5#56;N;NO	 	##F+ ` Ws   H)<H.c                     || j                   }|j                  r| j                  |j                         |j                  r"t	        | j
                  |j                         y y N)rZ   )r   rZ  freeze_text_module_exceptionsfreeze_vision_layersr^   r]  freeze_vision_module_exceptions)rn   r   s     r/   rn  z#IdeficsModel.freeze_relevant_params'  sQ    >[[F$$##F$H$HI&&**f>d>de 'r.   c                 X    | j                   | j                  fD ]  }t        ||        y rr  )rh  rl  r^   )rn   rZ   rT   s      r/   rZ  zIdeficsModel.freeze_text_layers1  s+    {{DII. 	FF3DE	Fr.   c                 2    t        | j                  |       y rr  )r^   r]  )rn   rZ   s     r/   rt  z!IdeficsModel.freeze_vision_layers5  s    T&&:KLr.   c                     | j                   S rP   r[  r}   s    r/   get_input_embeddingsz!IdeficsModel.get_input_embeddings8  s       r.   c                     || _         y rP   ry  rn   values     r/   set_input_embeddingsz!IdeficsModel.set_input_embeddings;  s
    !r.   rD   r;   r   r"   inputs_embedsr6   r7   r8   r9   r  r  output_hidden_statesinterpolate_pos_encodingreturn_dictr  rb   c                    ||j                   n|j                   }||n| j                  j                  }||n| j                  j                  }|
|
n| j                  j                  }
||n| j                  j
                  }|d u |d uz  rt        d      | j                  r%| j                  r|
rt        j                  d       d}
|| j                  |      }d}|
rIt        |t              s9d}|t               }n*t        j                  |      }t        j                  d       |j                   \  }}}||j#                         nd}||z   }|2t%        j&                  |||j                   d   z   |j                         }|F|D|j)                         j+                  d	      dz
  }|j-                  |dk(  d       |d d | d f   }n||j/                  d      }|||fj1                  d       d
k7  rt        d      |~|j3                  | j4                  |      }|j                   d d
 \  }} |j7                         j8                  ||z  g|j                   d
d   }| j;                  ||      j<                  }nJ|H|j?                         \  }}}}|j3                  | j4                  |      }|j9                  ||z  ||      }| j                  j@                  rN|4| jC                        }|j?                  d      |j?                  d
      }}n|j?                         \  }}}}|}n0|#j?                  d      |j?                  d
      }}nt        d      |j9                  ||z  |      }|	j?                  d      }|	j/                  d	      }	|	jE                  ddd|      }	|	j9                  ||||z        }	|C|j?                         \  }}}||f}|	t%        jF                  ||      }	| jI                  |	      }	nd }	|	dk(  jK                  d	      j3                  | j4                        jM                  d      j3                  |      }|2t%        jF                  ||ft$        jN                  |j                         }| jQ                  |||||      }|} |rdnd }!|rdnd }"d }#tS        | jT                        D ]  \  }$}%|r|!| fz  }!d }&| j                  r[| j                  rOd }|
rt        j                  d       d}
| jW                  |&|%| |||||	|||
|$| jX                  | jZ                  |      }'n* |&|%| |||||	|||
|$| jX                  | jZ                  |      }'|'d   } |
r	|'|rd
nd   }#|s|"|'d   fz  }" | j]                  |       } |r|!| fz  }!|
r|#nd }(|r|(j_                         }(|j9                  ||||      }|sta        d | |(|!|"|fD              S tc        | |(|!|"|      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   rA   r5   r   z_Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None.)rf   rA   )r6   r  zBIf `perceiver_embeddings` are passed, use_resampler should be Truer  r   r   r-   c           
      n    |
|z  dk(  r||
|z     } ||||||||	d       }|d   } | ||||||	|      }|S )Nr   )r;   r%   r9   rB  r  r  r  )r;   r   r  r  r  r  r-   )
main_blockr#   r;   r   r  r%   r9   rB  r  r  r   ri  rj  r  xblockr-  layer_outputss                    r/   vblockz$IdeficsModel.forward.<locals>.vblock  sv    " 33q84YBV5VWF$%'5,?-A-A*;"+'+	G %,AJM *!#1!-#1&7'#1! %$r.   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...)r;   r   r  r%   r9   rB  r  r  r   ri  rj  r  c              3   $   K   | ]  }|| 
 y wrP   r-   )rR   vs     r/   rU   z'IdeficsModel.forward.<locals>.<genexpr>?  s      = s   )r!   r"   r#   r$   r%   )2rA   r   r  r  r  use_return_dictrh   rk  r  r   r   r[  rQ   r   r   from_legacy_cacher=   get_seq_lengthr*   r<   longcumsummasked_fill_r   countr@   rf   r   r>   r]  r!   r  r^  rd  r?   r   invert_attention_maskrW   squeezer   _update_causal_mask	enumeraterh  _gradient_checkpointing_funcri  rj  rl  to_legacy_cacher   r    ))rn   rD   r;   r   r"   r  r6   r7   r8   r9   r  r  r  r  r  r  rA   return_legacy_cache
batch_size
seq_lengthr  past_key_values_lengthseq_length_with_past
num_imagesr%   image_seq_lenimage_hidden_sizetext_seq_lenimage_batch_sizeimage_sequence_lengthimage_hidden_shaperB  r#   all_hidden_statesall_self_attnsnext_decoder_cacheidxdecoder_layerr  r  
next_caches)                                            r/   rz   zIdeficsModel.forward>  s   & &/%:!!@T@T1B1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M $Z?"&&".."."@"@"Q##^ %2$7$7!
JETE`!?!?!Afg),BB!"\\&(>ATATUVAW(W`m`t`tN %,*>)..077;a?L%%n&91='J;<8L!)33A6L24HIOOPTUYZZq  %'??F?KL%1%7%7%;"J
9<22499*z:QkT`TfTfghgiTjkL #'"3"3)D\ #4 #   &1G_GdGdGfDJ
M3D":"="=DJJW]"="^"5":"::
;RTact"u;;$$#+'+'?'?@S'T$3G3L3LQ3OQeQjQjklQm0K_KdKdKfH
J7H"6!)/B/G/G/JL_LdLdefLg,Mabb166z:P]C]_pq ,0033==bA3::1aMR388\S]`mSmn*9L9Q9Q9S63Q"24I!J#+',zz2DV'T$#'#=#=>R#S #'  $83#>"C"C"C"K!O!OVZV`V`!O!a j jop j quu 

 !"ZZ12%**]MaMaN 11M>?L]
 & #7BD0d!"+DKK"8 `	6C#!m%55!)%V **t}}"&''t !&I $ A A!!" #'((%--00"!$ !'!!#1!-#2(;)=)=&7'!)-)B)B,0,H,H#1!" *!,M%28I1q%Q" =#3"55A`	6D 		-0  -!11+4'$
#335J166z:}^op '5FXkl  
 .+&+% 3
 	
r.   input_tensorc           
      
   | j                   j                  dk(  r	|d|v r|S y ||j                         nd}t        |t              }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  |j                  }	}|j                  d   }
|r|j                         }n1t        |t        j                        r|j                  d   n||
z   dz   }| j                  ||
|||	||j                  d         }| j                   j                  dk(  rR|P|j                  j                  d	k(  r7|s5t        j                   |      j"                  }t        j$                  ||      }|S )
Nflash_attention_2r  r   sdpa)r  r  is_trainingr   r5   )sequence_lengthtarget_lengthrf   rA   r  r  r  )r   _attn_implementationr  rQ   r   r   _ignore_causal_mask_sdpar  rf   rA   r=   get_max_cache_shaper*   r   5_prepare_4d_causal_attention_mask_with_cache_positionr  finfomin_unmask_unattended)rn   r;   r  r  r"   r  past_seen_tokensusing_static_cacherf   rA   r  r  r  	min_dtypes                 r/   r  z IdeficsModel._update_causal_maskM  s    ;;++/BB)c^.C%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**f4%
 E*..I0CCKQZ[Kr.   r  r  rf   rA   r  c                 f   | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| s|j                         }| j                  d   }
|ddddddd|
f   | ddddddf   z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerf   rA   r   )diagonalr  r5   r   )r   r*   r  r  fulltriur<   r  expandrt   r=   masked_fill)r;   r  r  rf   rA   r  r  ro   r  r  mask_lengthpadding_masks               r/   r  zBIdeficsModel._prepare_4d_causal_attention_mask_with_cache_position  s`   D %.*<*<*>!*C(K& # E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdd+q05@Aq,;,AV5W5c5c )6Aq!\k\12 r.   rP   )NNNNNNNNNNNNFNN) r&   r'   r(   r)   r   rj   rn  rZ  rt  rz  r~  r   LLAMA_INPUTS_DOCSTRINGr*   r  r   r   r   r+   r   r	   r   r    rz   r   r  staticmethodr   rf   rA   r  r   r   s   @r/   rU  rU    sg   
.,} .,`f 46 F 68 M!" ++AB '+1537=A5948@D<@7;$(,0/338&*59!K
##K
 !.K
 u//0	K

 "$u'8'8"9:K
   1 12K
 u001K
 #+5+<+<"=K
 'u'8'89K
 'u||4K
 D>K
 $D>K
 'tnK
 #+4.K
 d^K
  !!1!12!K
" 
u44	5#K
 CK
\?? ll? 	?
 ?  ?B 555 5 {{	5
 5 5 5 5r.   rU  c            '           e Zd ZdgZddgZd$ 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j&                     dee   dee   dee   dee   dee   deej&                     deeef   f"d              Z	 	 	 	 	 	 	 	 	 d&dZ	 d'ded eee f   d!edeee f   f fd"Z!e"d#        Z# xZ$S )(IdeficsForVisionText2Textzlm_head.weightzmodel.embed_tokens.weightc                     t         |   |       t        |      | _        t	        |j
                  |j                  |j                  d|j                        | _	        | j                          y )NF)r   r   r   r   ra   )ri   rj   rU  rY   r   r   rX  rY  freeze_lm_headlm_headrm  )rn   r   r]  rp   s      r/   rj   z"IdeficsForVisionText2Text.__init__  s[     !&)
-****$*$@$@#22
 	r.   c                 .    | j                   j                  S rP   rY   r[  r}   s    r/   rz  z.IdeficsForVisionText2Text.get_input_embeddings  s    zz&&&r.   c                 &    || j                   _        y rP   r  r|  s     r/   r~  z.IdeficsForVisionText2Text.set_input_embeddings  s    "'

r.   c                     | j                   S rP   r  r}   s    r/   get_output_embeddingsz/IdeficsForVisionText2Text.get_output_embeddings  s    ||r.   c                     || _         y rP   r  )rn   new_embeddingss     r/   set_output_embeddingsz/IdeficsForVisionText2Text.set_output_embeddings  s	    %r.   c                     || _         y rP   rY   )rn   decoders     r/   set_decoderz%IdeficsForVisionText2Text.set_decoder  s	    
r.   c                     | j                   S rP   r  r}   s    r/   get_decoderz%IdeficsForVisionText2Text.get_decoder  s    zzr.   c                    | j                         }| j                         }t        | j                  dd      r`|j                  |_        |j
                  dkD  r@|j                  |j
                  k(  sJ |j                  j                  |j                  _        t        |d      rJt        |d      r=|j                  |_        t        |d      rt        |d      r|j
                  |_        yyyyy)	z
        Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of
        IdeficsDecoupledLinear and IdeficsDecoupledEmbedding.
        tie_word_embeddingsTr   r   rd   r   rk   N)r  rz  getattrr   rl   rk   r   rm   r   r   rd   r   )rn   output_embeddingsinput_embeddingss      r/   tie_weightsz%IdeficsForVisionText2Text.tie_weights  s    
 !6684464;; 5t<'7'>'>$99A=(@@DTDnDnnnn9I9^9^9e9e!//6$n5'BRTd:e-=-L-L*(*CD "=J =M<f<f!9JD ;f5r.   )output_typerM  rD   r;   r   r"   r  r6   r7   r8   r9   labelsr  r  r  r  r  r  rb   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j	                  |||||||||	||||||      }|d   }| j                  |      }d}|
|
j                  |j                        }
|s|dd|j                  d   dz
   df   j                  |j                        }|dddddf   |dk7     j                         }|
dddf   |dk7     j                         }n1|dddddf   j                         }|
dddf   j                         }t               } ||j                  d|j                  d            |j                  d            }|s|f|dd z   }||f|z   S |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 -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoProcessor, IdeficsForVisionText2Text

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

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

        >>> prompts = [
        ...     [
        ...         "User:",
        ...         dogs_image_url_1,
        ...         "Describe this image.\nAssistant: An image of two dogs.\n",
        ...         "User:",
        ...         dogs_image_url_2,
        ...         "Describe this image.\nAssistant:",
        ...     ]
        ... ]
        >>> inputs = processor(prompts, return_tensors="pt")
        >>> generate_ids = model.generate(**inputs, max_new_tokens=6)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True)
        ```N)rD   r;   r   r"   r  r6   r7   r8   r9   r  r  r  r  r  r  r   r   .r5   )r2   r3   r"   r#   r$   r%   )r   r  r  r  rY   r  r@   rA   r=   r   r   r>   r  r1   r"   r#   r$   r%   )rn   rD   r;   r   r"   r  r6   r7   r8   r9   r  r  r  r  r  r  r  r-  r#   r3   r2   shift_attention_maskshift_logitsshift_labelsloss_fctr   s                             r/   rz   z!IdeficsForVisionText2Text.forward  s#   p 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] **)%+'%%=!5!5/!5%=#)  
$  
m,YYv}}-F) (6a6<<?Q;N9O9Q6Q'R'U'UV\VcVc'd$%c3B3k23G13LMXXZ%c12g/Cq/HITTV%c3B3k2==?%c12g99;')HL--b,2C2CB2GH,J[J[\^J_`DY,F'+'7D7V#CVC,#33!//)) ' ; ;
 	
r.   c                    i }|"| j                   j                  r||d<   n||d<   n||d<   |_||d d |j                  d    d f   }nC|j                  d   |j                  d   k7  r$|d d |f   }|	|	d d |j                  d    d f   }	|t|r|j                         j	                  d      dz
  }|j                  |dk(  d       |r9|d d |j                  d    d f   }|j                  t        j                        }||d   dk(  r|j                  |d d       n2|j                  |j                  t        j                        d d	       |j                  ||
||||	|j                  d
d      d       |S )Nr8   r7   r6   r   r   r5   )memory_format)r  rD   )rD   r  r  F)r"   r  r  r   r;   r9   r  )r   r^  r=   r  r  r  rt   r*   contiguous_formatr  rC   )rn   rD   r;   r   r  r"   r  r6   r%   r9   r  ro   model_inputss                r/   prepare_inputs_for_generationz7IdeficsForVisionText2Text.prepare_inputs_for_generationt  s     *{{((7J34;N78+7L( &(%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	'3+?IOOTUDVCVCX@X+Y(%,*>)..077;a?L%%n&91=+A	0B/B/D,DE  ,11@W@W1X $):a)?-d ST 'ooE<S<SoTgkl 	#2&"0 ,"0(<,2JJ7QSX,Y
	
 r.   r-  rH   rF   c                     t        |   |||fi |}d|v rT|d   }|d d dd d f   j                  d      }|j                  dd      r||d<   nt	        j
                  ||gd      |d<   |j                  |d<   |S )Nr9   r5   r   r  Tr   r%   )ri   #_update_model_kwargs_for_generationr   rC   r*   r   r%   )rn   r-  rH   rF   ro   r9   	last_maskrp   s          r/   r  z=IdeficsForVisionText2Text._update_model_kwargs_for_generation  s     wB
 	
 "\1#/0F#G ,QAX6@@CIT27@347<yyBVXaAbhi7j34 /6.I.I*+r.   c                 J    d}| D ]  }|t        fd|D              fz  } |S )Nr-   c              3   B   K   | ]  }|j                  d         yw)r   N)rB   )rR   
past_statebeam_idxs     r/   rU   z;IdeficsForVisionText2Text._reorder_cache.<locals>.<genexpr>  s     $gjZ%<%<Q%I$gs   )r   )pastr  reordered_past
layer_pasts    `  r/   _reorder_cachez(IdeficsForVisionText2Text._reorder_cache  s8     	jJu$g\f$ggiiN	jr.   rP   )NNNNNNNNNNNNNFNN)	NNNNNNNNN)F)%r&   r'   r(   _keys_to_ignore_on_load_missing_tied_weights_keysrj   rz  r~  r  r  r  r  r  r   r  r   r1   _CONFIG_FOR_DOCr*   r  r   r   r   r+   r   r	   r   rz   r  r   r   r   r   r  r  r  r   r   s   @r/   r  r    sh   '8&9#57GH'(&g* ++AB+HWfg '+1537=A5948@D<@7;-1$(,0/338&*59#n
##n
 !.n
 u//0	n

 "$u'8'8"9:n
   1 12n
 u001n
 #+5+<+<"=n
 'u'8'89n
 'u||4n
 ))*n
 D>n
 $D>n
 'tnn
 #+4.n
  d^!n
" !!1!12#n
$ 
u33	4%n
 h Cn
f  !AN $)	 38n !	 
c3h4  r.   r  )r   FNN)r   )Ir)   dataclassesr   typingr   r   r   r   r   r	   r*   torch.nn.functionalr
   r   rr   torch.utils.checkpointtorch.nnr   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   modeling_utilsr   r   pytorch_utilsr   utilsr   r   r   r   configuration_ideficsr   	perceiverr   visionr   
get_loggerr&   r   r  r    r1   rJ   r^   rN   r`   rM   r   Moduler   appendr   r   r   r   r   r  r/  LLAMA_START_DOCSTRINGrF  r  rU  r  r-   r.   r/   <module>r     s  (  ! : :      % ! ; ; ) > + ? 1  1 0 , 
		H	%! )C[ )C )CX &CK &C &CV *#Z +- k
 k
\>
RYY >
DJRYY J.    N +!
uxx !
H(:P P$l9ryy l9`L")) L^Kbii K\ " Y?_ ?	?0? D YV) V	VrN 6 Nr.   