
    rhr                     B   d Z ddlmZ ddlmZmZmZ ddlZddlZddlm	Z	 ddl
mZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z(  e#jR                  e*      Z+e e!d       G d de                    Z,e e!d       G d de                    Z- G d de	j\                        Z/	 dDde	j\                  dej`                  d ej`                  d!ej`                  d"eej`                     d#e1d$e1fd%Z2 G d& d'e	j\                        Z3 G d( d)e	j\                        Z4 G d* d+e	j\                        Z5 G d, d-e      Z6 G d. d/e	j\                        Z7d0ej`                  d1e8d2ej`                  fd3Z9 G d4 d5e	j\                        Z: G d6 d7e	j\                        Z;e! G d8 d9e             Z< e!d:       G d; d<e<             Z= e!d=       G d> d?e<             Z> e!d@       G dA dBe<e             Z?g dCZ@y)EzPyTorch Idefics3 model.    )	dataclass)CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)_prepare_4d_attention_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputModelOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging   )	AutoModel   )Idefics3ConfigIdefics3VisionConfigz|
    Base class for Idefics3 model's outputs that may also contain a past key/values (to speed up sequential decoding).
    custom_introc                       e Zd ZU dZdZeej                     ed<   dZ	ee
e
ej                           ed<   dZee
ej                        ed<   dZee
ej                        ed<   dZee
ej                        ed<   y)Idefics3BaseModelOutputWithPastaH  
    last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
        Sequence of hidden-states at the output of the last layer of the model.
        If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
        hidden_size)` is output.
    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
        `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
        `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
        encoder_sequence_length, embed_size_per_head)`.
        Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
        `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
        input) to speed up sequential decoding.
    image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
        Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
        sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder
    Nlast_hidden_statepast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r"   r   torchFloatTensor__annotations__r#   tupler$   r%   r&        /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/idefics3/modeling_idefics3.pyr!   r!   )   s    & 6:x 1 129AEOXeE%*;*;$<=>E8<M8E%"3"345<59Ju00129>B%(9(9":;Br0   r!   zS
    Base class for Idefics causal language model (or autoregressive) outputs.
    c                      e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   y)	Idefics3CausalLMOutputWithPastak  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Language modeling loss (for next-token prediction).
    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
        `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
        `past_key_values` input) to speed up sequential decoding.
    image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
        Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
        sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder
    Nlosslogitsr#   r$   r%   r&   )r'   r(   r)   r*   r4   r   r+   r,   r-   r5   r#   listr$   r.   r%   r&   r/   r0   r1   r3   r3   J   s      )-D(5$$
%,*.FHU&&'.9=OXd5#4#456=8<M8E%"3"345<59Ju00129>B%(9(9":;Br0   r3   c                   x     e Zd ZdZdef fdZdej                  dej                  dej                  fdZ
 xZS )Idefics3VisionEmbeddingsaX  
    This is a modified version of `siglip.modelign_siglip.SiglipVisionEmbeddings` to enable images of variable
    resolution.

    The modifications are adapted from [Patch n' Pack: NaViT, a Vision Transformer for any Aspect Ratio and Resolution](https://huggingface.co/papers/2307.06304)
    which allows treating images in their native aspect ratio and without the need to resize them to the same
    fixed size. In particular, we start from the original pre-trained SigLIP model
    (which uses images of fixed-size square images) and adapt it by training on images of variable resolutions.
    configc                    t         |           |j                  | _        |j                  | _        |j
                  | _        t        j                  |j                  | j                  | j
                  | j
                  d      | _	        | j                  | j
                  z  | _
        | j                  dz  | _        | j                  | _        t        j                  | j                  | j                        | _        y )Nvalid)in_channelsout_channelskernel_sizestridepaddingr   )super__init__hidden_size	embed_dim
image_size
patch_sizer   Conv2dnum_channelspatch_embeddingnum_patches_per_sidenum_patchesnum_positions	Embeddingposition_embeddingselfr9   	__class__s     r1   rB   z!Idefics3VisionEmbeddings.__init__u   s    ++ ++ ++!yy++?? 
 %)OOt$F!44a7!--"$,,t/A/A4>>"Rr0   pixel_valuespatch_attention_maskreturnc                 .   |j                   \  }}}}| j                  |      }|j                  d      j                  dd      }|| j                  z  || j                  z  }
}	t        j                  d| j                  z  dd| j                  z        }t        j                  ||	|
z  fd      }t        |      D ]  \  }}|d d df   j                         }|d   j                         }t        j                  ||j                  |j                        }t        j                  ||j                  |j                        }||z  dz  }||z  dz  }t        j                  ||d	      }t        j                  ||d	      }|d d d f   | j                  z  |z   j                         }|||   |j                  d
      j                         <    |j!                  | j"                  j$                  j                        }|| j#                  |      z   }|S )Nr   r         ?r   )size
fill_value)devicedtypeg!?T)right)shaperI   flatten	transposerF   r+   arangerJ   full	enumeratesumrY   rZ   	bucketizeviewcputorN   weight)rP   rR   rS   
batch_size_max_im_hmax_im_wpatch_embeds
embeddingsmax_nb_patches_hmax_nb_patches_w
boundariesposition_ids	batch_idxp_attn_masknb_patches_hnb_patches_w	h_indices	w_indicesfractional_coords_hfractional_coords_wbucket_coords_hbucket_coords_wpos_idss                           r1   forwardz Idefics3VisionEmbeddings.forward   s   ,8,>,>)
Ax++L9!))!,66q!<
-5-H(VZVeVeJe*\\!d&?&?"?a$JcJcFcd
zz
4DGW4W'Xefg&/0D&E 	J"I{&q!t,002L&q>--/L\,:M:MUaUgUghI\,:M:MUaUgUghI"+l":h"G"+l":h"G#oo.A:UYZO#oo.A:UYZO&q$w/$2K2KKo]ffhGBIL#K$4$4R$8$<$<$>?	J  $t'>'>'E'E'L'LM$"9"9,"GG
r0   )r'   r(   r)   r*   r   rB   r+   r,   
BoolTensorTensorr~   __classcell__rQ   s   @r1   r8   r8   j   sD    S3 S&E$5$5 UM]M] bgbnbn r0   r8   modulequerykeyvalueattention_maskscalingdropoutc                    t        j                  ||j                  dd            |z  }|||z   }t        j                  j                  |dt         j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr\   )dimrZ   )ptrainingr   r   )r+   matmulr_   r   
functionalsoftmaxfloat32rg   rZ   r   r   
contiguous)
r   r   r   r   r   r   r   kwargsattn_weightsattn_outputs
             r1   eager_attention_forwardr      s     <<s}}R'<=GL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r0   c            
            e Zd ZdZ fdZ	 ddej                  deej                     deej                  eej                     f   fdZ	 xZ
S )Idefics3VisionAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        |j                  | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        d| _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      F)rA   rB   r9   rC   rD   num_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutr   r   Lineark_projv_projq_projout_proj	is_causalrO   s     r1   rB   z Idefics3VisionAttention.__init__   s   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//ii?ii?ii?		$..$..A r0   r$   r   rT   c           
      :   |j                   \  }}}| j                  |      }| j                  |      }| j                  |      }	|j	                  ||| j
                  | j                        j                  dd      }|j	                  ||| j
                  | j                        j                  dd      }|	j	                  ||| j
                  | j                        j                  dd      }	t        }
| j                  j                  dk7  rt        | j                  j                     }
 |
| |||	|| j                  | j                  | j                  sdn| j                        \  }}|j!                  |||      j#                         }| j%                  |      }||fS )z#Input shape: Batch x Time x Channelr   r   eager        )r   r   r   )r]   r   r   r   re   r   r   r_   r   r9   _attn_implementationr   r   r   r   r   reshaper   r   )rP   r$   r   r   ri   
seq_lengthrD   querieskeysvaluesattention_interfacer   r   s                r1   r~   zIdefics3VisionAttention.forward   sa    -:,?,?)
J	++m,{{=)]+,,z:t~~t}}U__`acdeyyZOYYZ[]^_ZT^^T]]S]]^_abc(?;;++w6"9$++:Z:Z"[$7nnJJ#}}C$,,	%
!\ "))*j)LWWYmmK0L((r0   N)r'   r(   r)   r*   rB   r+   r   r   r.   r~   r   r   s   @r1   r   r      sU    G2 26$)||$) !.$)
 
u||Xell33	4$)r0   r   c                   V     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                        | _        y r   )rA   rB   r9   r	   
hidden_actactivation_fnr   r   rC   intermediate_sizefc1fc2rO   s     r1   rB   zIdefics3VisionMLP.__init__  sd    #F$5$5699V//1I1IJ99V55v7I7IJr0   r$   rT   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   )rP   r$   s     r1   r~   zIdefics3VisionMLP.forward
  s4    /**=9/r0   )r'   r(   r)   rB   r+   r   r~   r   r   s   @r1   r   r     s$    KU\\ ell r0   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      | _        y )Nr   Fbias)	rA   rB   vision_configrC   scale_factortext_configr   r   proj)rP   r9   
input_sizeoutput_sizerQ   s       r1   rB   zIdefics3SimpleMLP.__init__  sT    ))559L9La9OP
((44IIj+EB	r0   c                 $    | j                  |      S r   )r   )rP   xs     r1   r~   zIdefics3SimpleMLP.forward  s    yy|r0   )r'   r(   r)   rB   r~   r   r   s   @r1   r   r     s    Cr0   r   c            
            e Zd Zdef fdZ	 ddej                  dej                  dee   de	ej                     fdZ xZS )	Idefics3EncoderLayerr9   c                 D   t         |           |j                  | _        t	        |      | _        t        j                  | j                  |j                        | _	        t        |      | _        t        j                  | j                  |j                        | _        y )Neps)rA   rB   rC   rD   r   	self_attnr   	LayerNormlayer_norm_epslayer_norm1r   mlplayer_norm2rO   s     r1   rB   zIdefics3EncoderLayer.__init__  sm    ++08<<F<Q<QR$V,<<F<Q<QRr0   r$   r   output_attentionsrT   c                     |}| j                  |      }| j                  |||      \  }}||z   }|}| j                  |      }| j                  |      }||z   }|f}|r||fz  }|S )a=  
        Args:
            hidden_states (`torch.FloatTensor`):
                Input to the layer of shape `(batch, seq_len, embed_dim)`.
            attention_mask (`torch.FloatTensor`):
                Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*, defaults to `False`):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r$   r   r   )r   r   r   r   )rP   r$   r   r   residualr   outputss          r1   r~   zIdefics3EncoderLayer.forward'  s      !((7&*nn')/ '5 '
#|
 !=0 ((7/ =0 "&Gr0   )F)r'   r(   r)   r   rB   r+   r   r   boolr.   r,   r~   r   r   s   @r1   r   r     sY    S3 S -2	$||$ $ $D>	$
 
u  	!$r0   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
    r9   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
rA   rB   r9   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing)rP   r9   rj   rQ   s      r1   rB   zIdefics3Encoder.__init__X  sP    mm5QWQiQiKj$ka%9&%A$kl&+# %ls   A#r   r   output_hidden_statesreturn_dictrT   c                 ~   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|rdnd}|rdnd}|}| j                  D ]&  }	|r||fz   } |	|||      }
|
d   }|s||
d   fz   }( |r||fz   }|st        d |||fD              S t        |||      S )ad  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        Nr/   )r   r   r   c              3   &   K   | ]	  }||  y wr   r/   ).0vs     r1   	<genexpr>z*Idefics3Encoder.forward.<locals>.<genexpr>  s     eqWXWdes   r"   r$   r%   )r9   r   r   use_return_dictr   r.   r   )rP   inputs_embedsr   r   r   r   encoder_statesall_attentionsr$   encoder_layerlayer_outputss              r1   r~   zIdefics3Encoder.forward_  s   < 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d%![[ 	FM#!/=2B!B)"3M *!,M !/=3C2E!E	F  +}.>>Ne]NN$Seee+>Vd
 	
r0   NNNN)r'   r(   r)   r*   r   rB   r   r+   r   r   r   r.   r   r~   r   r   s   @r1   r   r   O  sx    ,~ , 26,0/3&*=
 !.=
 $D>	=

 'tn=
 d^=
 
uo%	&=
r0   r   r$   n_reprT   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r]   expandr   )r$   r   batchnum_key_value_headsslenr   s         r1   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr0   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Idefics3RMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z>
        Idefics3RMSNorm is equivalent to T5LayerNorm
        N)rA   rB   r   	Parameterr+   onesrh   variance_epsilon)rP   rC   r   rQ   s      r1   rB   zIdefics3RMSNorm.__init__  s1     	ll5::k#:; #r0   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr   r\   T)keepdim)	rZ   rg   r+   r   powmeanrsqrtr   rh   )rP   r$   input_dtypevariances       r1   r~   zIdefics3RMSNorm.forward  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r0   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r.   rh   r]   r   rP   s    r1   
extra_reprzIdefics3RMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr0   )gư>)r'   r(   r)   rB   r~   r  r   r   s   @r1   r   r     s    $;Jr0   r   c                   ,     e Zd Z fdZddZd Z xZS )Idefics3Connectorc                 d    t         |           |j                  | _        t        |      | _        y r   )rA   rB   r   r   modality_projectionrO   s     r1   rB   zIdefics3Connector.__init__  s)    "//#4V#< r0   c                    |j                         \  }}}t        |dz        x}}|j                  ||||      }|j                  ||t        ||z        ||z        }|j                  dddd      }|j	                  |t        ||z        t        ||z        ||dz  z        }|j                  dddd      }|j	                  |t        ||dz  z        ||dz  z        }|S )Ng      ?r   r   r   r   )rW   intre   permuter   )rP   r   r   bszseqrD   heightwidths           r1   pixel_shufflezIdefics3Connector.pixel_shuffle  s    ffhS)S#X&FF3y1FF3EL$8 99|;STIIaAq!IIc3u|34c&<:O6PR[_kmn_nRopIIaAq!IIc3slAo67lTUo9VWr0   c                 `    | j                  || j                        }| j                  |      }|S r   )r  r   r	  )rP   r&   s     r1   r~   zIdefics3Connector.forward  s4    "001DdFWFWX"667JK""r0   )r   )r'   r(   r)   rB   r  r~   r   r   s   @r1   r  r    s    =
	#r0   r  c                   B    e Zd ZU eed<   dZdZddgZdZdZ	dZ
dZdZd Zy)	Idefics3PreTrainedModelr9   modelTr   Idefics3DecoderLayerr#   c                    t        | j                  d| j                  j                         j                        }t	        |t
        j                  t
        j                  f      rY|j                  j                  j                  d|       |j                  %|j                  j                  j                          y y t	        |t
        j                        rf|j                  j                  j                  d|       |j                  2|j                  j                  |j                     j                          y y t	        |t
        j                        rJ|j                  j                  j!                  d       |j                  j                  j                          y t	        |t"              r&|j                  j                  j!                  d       y y )Ninitializer_ranger   )r   stdrV   )getattrr9   get_text_configr  
isinstancer   r   rG   rh   datanormal_r   zero_rM   padding_idxr   fill_r   )rP   r   r  s      r1   _init_weightsz%Idefics3PreTrainedModel._init_weights  sA   dkk#68S8S8U8g8ghfryy"))45MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> .-MM$$S)KK""$0MM$$S) 1r0   N)r'   r(   r)   r   r-   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr"  r/   r0   r1   r  r    sB    &*#24JK"3N"&*r0   r  zO
    The Idefics3 Vision Transformer Model outputting raw image embedding.
    c                        e Zd ZU eed<   dZdZdZdef fdZd Z	d Z
	 	 	 	 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 )Idefics3VisionTransformerr9   Tc                    t         |   |       |j                  }t        |      | _        t        |      | _        |j                  | _        t        j                  ||j                        | _        |j                  dk(  | _        y )Nr   flash_attention_2)rA   rB   rC   r8   rn   r   encoderrF   r   r   r   post_layernormr   _use_flash_attention_2)rP   r9   rD   rQ   s      r1   rB   z"Idefics3VisionTransformer.__init__  sm     &&	26:&v. ++ ll9&:O:OP&,&A&AEX&X#r0   c                     | j                   S r   rn   r  s    r1   get_input_embeddingsz.Idefics3VisionTransformer.get_input_embeddings  s    r0   c                     || _         y r   r3  rP   r   s     r1   set_input_embeddingsz.Idefics3VisionTransformer.set_input_embeddings  s	    r0   rS   r   r   r   rT   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|j	                  d      }|s| j
                  }t        j                  ||j	                  d      |z  |j	                  d      |z  f      }|j                  t        j                  |j                        }| j                  ||      }|j                  |d      }| j                  st        ||j                        }nt        j                   |       sd }| j#                  |||||      }	|	d   }
| j%                  |
      }
|s	|
f|	dd  z   S t'        |
|	j(                  |	j*                  	      S )
Nr   r   r   rZ   rY   rR   rS   r\   )r   r   r   r   r   r   r   )r9   r   r   r   rW   rF   r+   r   rg   r   rY   rn   re   r1  r   rZ   anyr/  r0  r   r$   r%   )rP   rR   rS   r   r   r   ri   rF   r$   encoder_outputsr"   s              r1   r~   z!Idefics3VisionTransformer.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]!&&q)
'J#(:: %%a(J6 %%a(J6$  $8#:#:T`TgTg#:#h \Xlm388RH **#=>RTaTgTg#h 001#' ,,'//!5# ' 
 ,A. //0AB%'/!"*===/)77&11
 	
r0   r   )r'   r(   r)   r   r-   r(  r'  r)  rB   r4  r7  r   r+   r   r   r   r.   r   r~   r   r   s   @r1   r,  r,    s     ! NY3 Y  <@,0/3&*7
 'u'7'787
 $D>	7

 'tn7
 d^7
 
uo%	&7
r0   r,  zZ
    Idefics3 model consisting of a SIGLIP vision encoder and Llama3 language decoder
    c            #       R    e Zd Zdef fdZd Zd Zd Zd Zde	j                  dee	j                     d	ee	j                     fd
Zdde	j                  de	j                  fdZe ed      	 	 	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     dee   dee	j                     dee	j                     dee	j&                     d	ee	j                     dee   dee   dee   dee	j                     dee   dee   deeef   fd              Z xZS )Idefics3Modelr9   c                    t         |   |       | j                  j                  j                  | _        | j                  j                  j                  | _        t        j                  |j                        | _
        t        |      | _        t        j                  |j                        | _        t!        |j                  j"                  |j                  j$                  z  dz  |j&                  dz  z        | _        | j                  j*                  | _        |j                  j,                  dk(  | _        | j1                          y )Nr   r.  )rA   rB   r9   r   pad_token_idr   
vocab_sizer,  _from_configr   vision_modelr  	connectorr   from_config
text_modelr  rE   rF   r   image_seq_lenimage_token_idr   r1  	post_initrO   s     r1   rB   zIdefics3Model.__init__T  s     ;;22??++11<<5BB6CWCWX*62#//0B0BC ""--1E1E1P1PPUVV[a[n[npq[qr
 #kk88&,&8&8&M&MQd&d#r0   c                     fdd }| j                         j                  |      | _         | j                        j                  |      | _        y)aE  
        Enables the gradients for the input embeddings.

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

        Override to set output.requires_grad = True for both the decoder's and vision model's embeddings.
        c                     t        t        | j                                     dk(  r| S  t        | j                               d         S )Nr   )lenr6   children)r   get_lowest_modules    r1   rN  zCIdefics3Model.enable_input_require_grads.<locals>.get_lowest_moduleq  s?    4)*+q0 )foo.?)@)CDDr0   c                 &    |j                  d       y NTrequires_grad_r   inputoutputs      r1   make_inputs_require_gradszKIdefics3Model.enable_input_require_grads.<locals>.make_inputs_require_gradsy      !!$'r0   N)r4  register_forward_hook_text_require_grads_hookrC  _vision_require_grads_hook)rP   rV  rN  s     @r1   enable_input_require_gradsz(Idefics3Model.enable_input_require_gradsg  sN    	E	( )-(A(A(C(Y(YZs(t%*;D<M<M*N*d*d%+
'r0   c                 l    | j                   j                          | j                  j                          y r   rY  removerZ  r  s    r1   disable_input_require_gradsz)Idefics3Model.disable_input_require_grads  &    %%,,.''..0r0   c                 6    | j                   j                         S r   )rF  r4  r  s    r1   r4  z"Idefics3Model.get_input_embeddings  s    3355r0   c                 :    | j                   j                  |       y r   )rF  r7  r6  s     r1   r7  z"Idefics3Model.set_input_embeddings  s    ,,U3r0   	input_idsr   r&   c                    |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                  d      j                  |      j                  |j                        }|j                  |j                  |j                        }|j                  ||      }|S )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.
        r9  r\   )r4  r+   tensorr9   rH  longrY   all	unsqueeze	expand_asrg   rZ   masked_scatter)rP   rc  r   r&   special_image_masks        r1   inputs_mergerzIdefics3Model.inputs_merger  s     !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H/99"=GGVYYZgZnZno144]5I5I=K^K^_%445GI\]r0   rR   pixel_attention_maskc                    |j                   \  }}}}}|j                  | j                        } |j                  ||z  g|j                   dd  }|j                   dd j	                         }|dk(  j                  d      |k7  }	||	   j                         }|at        j                  |j                  d      |j                  d      |j                  d	      ft        j                  |j                  
      }n6 |j                  ||z  g|j                   dd  }||	   j                         }| j                  j                  j                  }
|j                  d|
|
      }|j                  d|
|
      }|j                  d      dkD  j                         }| j!                  ||      }|j"                   | j%                  |j"                        }|S )a  
        Encodes images into continuous embeddings that can be forwarded to the language model.

        Args:
            pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
                The tensors corresponding to the input images.
            pixel_attention_mask (`torch.LongTensor`, *optional*):
                The attention mask indicating padded regions in the image.
        )rZ   r   Nr   r   )r\   r   )r   r   r   )rW   rZ   rY   )	dimensionrW   step)r\   r   r:  )r]   rg   rZ   re   numelrc   r   r+   r   rW   r   rY   r9   r   rF   unfoldrC  r"   rD  )rP   rR   rm  ri   
num_imagesrH   r  r  nb_values_per_imagereal_images_indsrF   patches_subgridrS   r&   s                 r1   get_image_featuresz Idefics3Model.get_image_features  s    ?K>P>P;
Jfe#TZZ8(|((j)@Z<CUCUVWVXCYZ +004::<(C/444FJ]]#$45@@B  '#(::"''*L,=,=a,@,BSBSTUBVWjj#**$  $=#7#<#<Z*=T#vWkWqWqrsrtWu#v #78H#I#T#T#V [[..99
.55
Yc5d)001:T^0_ / 3 3 3 AA EKKM #//\`t/u-- #nn-@-R-RS""r0   a  
        Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
        the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
        max_num_images is the maximum number of images among the batch_size samples in the batch.
        Padding images are not needed beyond padding the pixel_values at the entrance of the model.
        For efficiency, we only pass through the vision_model's forward the real images by
        discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
        image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
        r   r   rr   r#   	use_cacher   r   cache_positionr   r   rT   c                    |
|
n| j                   j                  }
||n| j                   j                  }|	|	n| j                   j                  }	||n| j                   j                  }| j
                  r/| j                  j                  r|	rt        j                  d       d}	||j                  \  }}n||j                  \  }}}nt        d      |	r|
t               }|9 | j                  j                         |      j                  | j                        }||t        d      || j!                  ||      }n)|'|j                  | j"                  |j                        }|| j%                  |||      } | j                  d
|||||	|
||dd	|}t'        |j(                  |j*                  |j,                  |j.                  |	      S )a|  
        pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
            Mask to avoid performing attention on padding pixel indices.
        image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The hidden states of the image encoder after modality projection.
        zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fz5You have to specify either input_ids or inputs_embedszMYou cannot specify both pixel_values and image_hidden_states at the same timer9  )rc  r   r&   T)	r   r   rr   r#   ry  r   r   rz  r   )r"   r#   r$   r%   r&   r/   )r9   r   r   ry  r   r   rF  r   loggerwarning_oncer]   r   r   r4  rg   rY   rx  rZ   rl  r!   r"   r#   r$   r%   )rP   rc  r   rr   r#   r   rR   rm  r&   ry  r   r   rz  r   r   ri   r   rj   r   s                      r1   r~   zIdefics3Model.forward  s   F 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]==T__CC	l I  %.__"J
&(5(;(;%J
ATUU0*nO BDOO@@B9MPPQUQ\Q\]M #(;(Glmm%"&"9"9,H\"] ,"5"8"8tzzR[RbRb"8"c* !..#+$7 / M "$// 
')%+/!5)
 
 /%77#33!//)) 3
 	
r0   r   )NNNNNNNNNNNNN)r'   r(   r)   r   rB   r[  r_  r4  r7  r+   
LongTensorr   r   rl  r,   rx  r   r   r
   r   r   r   r   r   r.   r!   r~   r   r   s   @r1   r>  r>  N  s   ~ &
61
64##  - &ell3	8*#u/@/@ *#X]XhXh *#X 
 151537+/5948;?;?$(,0/359&*V
E,,-V
 !.V
 u//0	V

 "%V
   1 12V
 u001V
 'u'7'78V
 &e&7&78V
 D>V
 $D>V
 'tnV
 !!1!12V
 d^V
 -.V
  
u55	6!V

 V
r0   r>  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            '       H    e Zd ZdgZ fdZd Zd Zd Zd Zdde	j                  de	j                  fd	Zee	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd
ee	j                     dee	j                      dee	j                     dee   dee	j                     dee	j                     dee	j$                     dee	j                     dee	j                     dee   dee   dee   dee	j                     dee   deee	j                   f   dee   deeef   f"d              Z	 	 	 	 	 	 	 	 d fd	Z xZS ) Idefics3ForConditionalGenerationzlm_head.weightc                 Z   t         |   |       t        |      | _        | j                  j
                  | _        t        j                  |j                  j                  |j                  j                  d      | _        |j                  j                  | _
        | j                          y )NFr   )rA   rB   r>  r  r9   rH  r   r   r   rC   rA  lm_headrI  rO   s     r1   rB   z)Idefics3ForConditionalGeneration.__init__D  sz     "6*
"kk88yy!3!3!?!?ASASA^A^ejk ,,77 	r0   c                     d }| j                         j                  |      | _        | j                  j                  j                         j                  |      | _        y)z
        Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping
        the model weights fixed.
        c                 &    |j                  d       y rP  rQ  rS  s      r1   rV  z^Idefics3ForConditionalGeneration.enable_input_require_grads.<locals>.make_inputs_require_gradsV  rW  r0   N)r4  rX  rY  r  rC  rZ  )rP   rV  s     r1   r[  z;Idefics3ForConditionalGeneration.enable_input_require_gradsP  sO    	( )-(A(A(C(Y(YZs(t%*.***A*A*V*V*X*n*n%+
'r0   c                 l    | j                   j                          | j                  j                          y r   r]  r  s    r1   r_  z<Idefics3ForConditionalGeneration.disable_input_require_grads_  r`  r0   c                 J    | j                   j                  j                         S r   )r  rF  r4  r  s    r1   r4  z5Idefics3ForConditionalGeneration.get_input_embeddingsd  s    zz$$99;;r0   c                 N    | j                   j                  j                  |       y r   )r  rF  r7  r6  s     r1   r7  z5Idefics3ForConditionalGeneration.set_input_embeddingsh  s    

2259r0   rR   rm  c                 <    | j                   j                  ||      S )N)rR   rm  )r  rx  )rP   rR   rm  s      r1   rx  z3Idefics3ForConditionalGeneration.get_image_featuresk  s    zz,,,]q,rrr0   rc  r   rr   r#   r   r&   labelsry  r   r   rz  r   logits_to_keepr   rT   c                 >   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  } | j                  d|||||||||
|||dd|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|	4 | j                  d||	| j                   j                  j                  d|}t        |||j                  |j                  |j                  |j                         S )a  
        pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
            Mask to avoid performing attention on padding pixel indices.
        image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The hidden states of the image encoder after modality projection.
        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]`.

        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.
        ```NT)rc  r   rr   r#   r   rR   rm  r&   ry  r   r   rz  r   r   )r5   r  rA  )r4   r5   r#   r$   r%   r&   r/   )r9   r   r   r   r  r  r  slicer  loss_functionr   rA  r3   r#   r$   r%   r&   )rP   rc  r   rr   r#   r   rR   rm  r&   r  ry  r   r   rz  r   r  r   r   r$   slice_indicesr5   r4   s                         r1   r~   z(Idefics3ForConditionalGeneration.forwardn  sU   j 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B] $** 
)%+'%!5 3/!5)
 
"  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD .#33!//)) ' ; ;
 	
r0   c
                 b    t        |   |f||||||||	d|
}||d   dk7  r
d |d<   d |d<   |S )N)r#   r   r   rz  rR   rm  r&   r  r   rR   rm  )rA   prepare_inputs_for_generation)rP   rc  r#   r   r   rz  rR   rm  r&   r  r   model_inputsrQ   s               r1   r  z>Idefics3ForConditionalGeneration.prepare_inputs_for_generation  sm      w<
+)')%!5 3)
 
 *nQ.?1.D+/L(37L/0r0   r   )NNNNNNNNNNNNNNr   )NNNNNNNN)r'   r(   r)   _tied_weights_keysrB   r[  r_  r4  r7  r+   r,   r~  rx  r   r   r   r   r
   r   r   r   r  r   r   r.   r3   r~   r  r   r   s   @r1   r  r  ;  s	    ++	
1
<:su/@/@ sX]XhXh s  151537+/5948;?;?-1$(,0/359&*34!}
E,,-}
 !.}
 u//0	}

 "%}
   1 12}
 u001}
 'u'7'78}
 &e&7&78}
 ))*}
 D>}
 $D>}
 'tn}
 !!1!12}
 d^}
  c5<</0!}
" +,#}
$ 
u44	5%}
  }
F ! ! !r0   r  )r  r  r>  r,  )r   )Ar*   dataclassesr   typingr   r   r   r+   torch.utils.checkpointr   activationsr	   cache_utilsr
   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   autor   configuration_idefics3r   r   
get_loggerr'   r|  r!   r3   Moduler8   r   floatr   r   r   r   r   r   r  r   r   r  r  r,  r>  r  __all__r/   r0   r1   <module>r     sj    ! , ,    ! . ) B B 9 < F & R R  H 
		H	% 
Ck C C6 
C[ C C4:ryy :J %II%<<% 
% <<	%
 U\\*% % %0>)bii >)D		 		 .5 .dM
bii M
b	UU\\ 	U# 	U%,, 	UJbii J(#		 #. *o * *< 
O
 7 O

O
d 
e
+ e

e
P 
Q'> Q
Qh xr0   