
    %	&h4                        d Z ddlmZ ddlmZmZmZmZ ddlZddlm	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mZ ddlmZ dZdZ ede       G d de             Ze G d de             ZdZ ed       G d de             Zg dZy)zPyTorch ColPali model    )	dataclass)ListOptionalTupleUnionN)nn)AutoModelForImageTextToText   )Cache)PreTrainedModel)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardreplace_return_docstrings   )ColPaliConfigr   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 ([`ColPaliConfig`]):
            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.
zUThe bare ColPali model outputting raw hidden-states without any specific head on top.c                       e Zd ZeZdZg Zd Zy)ColPaliPreTrainedModelmodelc                    t        | j                  d      r| j                  j                  n)| j                  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 y )Ninitializer_rangeg        )meanstd)hasattrconfigr   
vlm_configtext_config
isinstancer   LinearConv2dweightdatanormal_biaszero_	Embeddingpadding_idx)selfmoduler   s      /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/colpali/modeling_colpali.py_init_weightsz$ColPaliPreTrainedModel._init_weights@   s     t{{$78 KK))''33EE 	 fryy"))45MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .    N)__name__
__module____qualname__r   config_classbase_model_prefix_no_split_modulesr+    r,   r*   r   r   7   s    
 !L?r,   r   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ej                     ef      ed<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   y)	ColPaliForRetrievalOutputa/  
    Base class for ColPali embeddings output.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            The embeddings of the model.
        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 (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
    Nloss
embeddingspast_key_valueshidden_states
attentionsimage_hidden_states)r-   r.   r/   __doc__r6   r   torchFloatTensor__annotations__r7   Tensorr8   r   r   r   r9   r   r:   r;   r3   r,   r*   r5   r5   Q   s    < )-D(5$$
%,)-J&-GKOXeD):):$;U$BCDK8<M8E%"3"345<59Ju001297;%"3"34;r,   r5   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)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
            The tensors corresponding to the input images. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`SiglipImageProcessor.__call__`] for details ([]`PaliGemmaProcessor`] uses
            [`SiglipImageProcessor`] for processing images). If none, ColPali will only process text (query embeddings).
        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**.
        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.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional key word arguments passed along to the vlm backbone model.
u\  
    In our proposed ColPali approach, we leverage VLMs to construct efficient multi-vector embeddings directly
    from document images (“screenshots”) for document retrieval. We train the model to maximize the similarity
    between these document embeddings and the corresponding query embeddings, using the late interaction method
    introduced in ColBERT.

    Using ColPali removes the need for potentially complex and brittle layout recognition and OCR pipelines with a
    single model that can take into account both the textual and visual content (layout, charts, etc.) of a document.
    c                   Z    e Zd Zdef fdZ ee       eee	      	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
e   de
e   d	e
e   d
eeef   fd              Zd Zd Zd Zd Zd Zd Zd Z	 	 	 dde
e   de
e   ded
ej8                  fdZ xZS )ColPaliForRetrievalr   c                 F   t         |   |       || _        |j                  j                  j
                  | _        t        j                  |j                        }|j                  j                  ,|j                  j                  D cg c]  }d| 	 c}| _	        || _
        | j                  j                  | _        t        j                  | j                  j                  j                  j                  | j                        | _        | j!                          y c c}w )Nzvlm.language_model.)super__init__r   r   r   
vocab_sizer	   from_configlanguage_model_tied_weights_keysvlmembedding_dimr   r   hidden_sizeembedding_proj_layer	post_init)r(   r   rJ   k	__class__s       r*   rE   zColPaliForRetrieval.__init__   s      ++77BB)55f6G6GH00<JMJ\J\JoJo&pQ)<QC'@&pD#![[66$&IIKK""..::%
!
 	 'qs   
D)output_typer0   	input_idspixel_valuesattention_maskoutput_attentionsoutput_hidden_statesreturn_dictreturnc           
         d|v r"|d   j                  | j                        |d<   ||n| j                  j                  }||n| j                  j                  }||n| j                  j
                  } | j                  d
|||d||d|}|j                  d   }	| j                  |	      }
|
|
j                  dd      z  }
|
|j                  d      z  }
d}|s3|
f|dd z   }||d   nd|d<   ||j                  ndf|d<   ||f|z   S |S t        ||
|j                  |r|j                  nd|j                  ||j                  	      S d	      S )z
        Returns:
        rS   )dtypeNT)rR   rT   rS   rV   rW   rU   )dimkeepdim   )r6   r7   r8   r9   r:   r;   r3   )torZ   r   rU   rV   use_return_dictrJ   r9   rM   norm	unsqueezer;   r5   r8   r:   )r(   rR   rS   rT   rU   rV   rW   kwargsoutputslast_hidden_statesr7   r6   outputs                r*   forwardzColPaliForRetrieval.forward   s    V#%+N%;%>%>TZZ%>%PF>"1B1N-TXT_T_TqTq %9$D $++JjJj 	 &1%<k$++B]B]$(( 
)%!%#/
 
 %2226../AB
  *//b$/"GG
.":":2">>
 ]WQR[0F%9%Eq	4F1I9E9Q'55W[]F2J'+'7D7V#CVC(!#333G'//T))?K?W ; ;
 	
 ^b
 	
r,   c                 J    | j                   j                  j                         S N)rJ   rH   get_input_embeddingsr(   s    r*   rj   z(ColPaliForRetrieval.get_input_embeddings   s    xx&&;;==r,   c                 N    | j                   j                  j                  |       y ri   )rJ   rH   set_input_embeddings)r(   values     r*   rm   z(ColPaliForRetrieval.set_input_embeddings   s    44U;r,   c                 J    | j                   j                  j                         S ri   )rJ   rH   get_output_embeddingsrk   s    r*   rp   z)ColPaliForRetrieval.get_output_embeddings   s    xx&&<<>>r,   c                 N    | j                   j                  j                  |       y ri   )rJ   rH   set_output_embeddings)r(   new_embeddingss     r*   rr   z)ColPaliForRetrieval.set_output_embeddings  s    55nEr,   c                 N    | j                   j                  j                  |       y ri   )rJ   rH   set_decoder)r(   decoders     r*   ru   zColPaliForRetrieval.set_decoder  s    ++G4r,   c                 J    | j                   j                  j                         S ri   )rJ   rH   get_decoderrk   s    r*   rx   zColPaliForRetrieval.get_decoder      xx&&2244r,   c                 J    | j                   j                  j                         S ri   )rJ   rH   tie_weightsrk   s    r*   r{   zColPaliForRetrieval.tie_weights
  ry   r,   new_num_tokenspad_to_multiple_ofmean_resizingc                 V   | j                   j                  j                  |||      }|j                  | j                  j
                  j                  _        |j                  | j                  j
                  _        |j                  | j                   _        |j                  | _        |S )N)r|   r}   r~   )rJ   rH   resize_token_embeddingsnum_embeddingsr   r   r   rF   )r(   r|   r}   r~   model_embedss        r*   r   z+ColPaliForRetrieval.resize_token_embeddings  s     xx..FF)1' G 
 9E8S8S**5,8,G,G)*99&55r,   )NNNNNN)NNT)r-   r.   r/   r   rE   r   %COLPALI_FOR_RETRIEVAL_INPUT_DOCSTRINGr   r5   _CONFIG_FOR_DOCr   r=   
LongTensorr>   r@   boolr   r   rg   rj   rm   rp   rr   ru   rx   r{   intr   r&   r   __classcell__)rP   s   @r*   rB   rB      s1   } $ ++PQ+DSbc 154815,0/3&*6
E,,-6
 u0016
 !.	6

 $D>6
 'tn6
 d^6
 
u//	06
 d R6
p><?F555
 )-,0"	  %SM 	
 
r,   rB   )rB   r5   r   )r<   dataclassesr   typingr   r   r   r   r=   r   transformersr	   cache_utilsr   modeling_utilsr   utilsr   r   r   r   configuration_colpalir   r   COLPALI_START_DOCSTRINGr   r5   r   rB   __all__r3   r,   r*   <module>r      s     ! / /   4   -  1 " " [?_ ?	?, $< $< $<N$) %N 
s0 s
slr,   