
    ^jL                        d Z ddl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 dd
lmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ ddlm Z  ddl!m"Z"  ejF                  e$      Z% ed      e G d de                    Z& ed      e G d de                    Z' G d dejP                        Z)e G d de             Z* ed       G d d e*             Z+ ed       G d! d"e*e
             Z,g d#Z-y)$zPyTorch PaliGemmamodel.    )	dataclassN)nn   )Cache)PreTrainedConfig)GenerationMixin)create_causal_maskcreate_masks_for_generate!create_sliding_window_causal_mask)FlashAttentionKwargs)BaseModelOutputWithPastBaseModelOutputWithPooling)PreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tupleloggingtorch_compilable_check   )	AutoModel   )PaliGemmaConfigzN
    Base class for Paligemma outputs, with hidden states and attentions.
    custom_introc                   :    e Zd ZU dZdZej                  dz  ed<   y)PaligemmaModelOutputWithPasta  
    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 and after projecting the last hidden state.
    Nimage_hidden_states)__name__
__module____qualname____doc__r   torchFloatTensor__annotations__     {/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/paligemma/modeling_paligemma.pyr   r   ,   s     59**T18r(   r   zU
    Base class for PaliGemma causal language model (or autoregressive) outputs.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
dz  ed<   dZeej                     dz  ed<   dZeej                     dz  ed<   dZej                  dz  ed<   y)	PaliGemmaCausalLMOutputWithPasta8  
    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.text_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`):
        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

        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 (`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logitspast_key_valueshidden_states
attentionsr   )r    r!   r"   r#   r,   r$   r%   r&   r-   r.   r   r/   tupler0   r   r'   r(   r)   r+   r+   <   s     &*D%

d
")'+FE$+$(OUT\(59M5**+d2926Je''(4/648**T18r(   r+   c                   *     e Zd Zdef fdZd Z xZS )PaliGemmaMultiModalProjectorconfigc                     t         |           t        j                  |j                  j
                  |j                  j                  d      | _        y )NTbias)super__init__r   Linearvision_confighidden_sizeprojection_dimlinearselfr4   	__class__s     r)   r9   z%PaliGemmaMultiModalProjector.__init__[   s;    ii 4 4 @ @&BVBVBeBelpqr(   c                 (    | j                  |      }|S N)r>   )r@   image_featuresr/   s      r)   forwardz$PaliGemmaMultiModalProjector.forward_   s    N3r(   )r    r!   r"   r   r9   rE   __classcell__rA   s   @r)   r3   r3   Z   s    r rr(   r3   c                   D    e Zd ZU eed<   dZdZdZdgZdgZ	dZ
dZdZdZdZy)	PaliGemmaPreTrainedModelr4   model)imagetextTr3   r.   FN)r    r!   r"   r   r&   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_can_compile_fullgraph_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr'   r(   r)   rI   rI   e   sI    (&*#78#4"5"N"&r(   rI   z|
    The Base Paligemma model which consists of a vision backbone and a language model without language modeling head.,
    c                       e Zd ZdZdef fdZe ed      dej                  de
e   deez  fd	              Zd
ej                  dej                  dej                  fdZee	 	 	 	 	 	 	 	 	 dd
ej                  dz  dej                  dz  dej"                  dz  dej                  dz  dedz  dej                  dz  dej                  dz  dej                  dz  dedz  de
e   deez  fd              Z xZS )PaliGemmaModelFr4   c                    t         |   |       t        j                  |j                        | _        t        |      | _        |j                  j                  | _	        t        j                  |j                        }|| _
        | j                  j                         j                  xs | j                  | _        | j                          y )N)r4   )r8   r9   r   from_configr;   vision_towerr3   multi_modal_projectortext_config
vocab_sizelanguage_modelr4   get_text_configdtypetext_config_dtype	post_init)r@   r4   r_   rA   s      r)   r9   zPaliGemmaModel.__init__}   s     %119M9MN%A&%I" ,,77"..f6H6HI,!%!<!<!>!D!D!R

r(   zWObtains image last hidden states from the vision tower and apply multimodal projection.r   pixel_valueskwargsreturnc                 t     | j                   |fi |}|j                  }| j                  |      }||_        |S rC   )r[   last_hidden_stater\   pooler_output)r@   rd   re   image_outputsselected_image_featurerD   s         r)   get_image_featuresz!PaliGemmaModel.get_image_features   sF     *)),A&A!.!@!@334JK&4#r(   	input_idsinputs_embedsrD   c                 .   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d   |j                  d   z  }|j                  d      j                  |j                        }t        ||j                  d   z  |j                         k(  d| d|        |S )z
        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
        equal to the length of multimodal features. If the lengths are different, an error is raised.
        )ra   devicer   r   z6Image features and image tokens do not match, tokens: z, features: )get_input_embeddingsr$   tensorr4   image_token_idlongrp   allsumshape	unsqueezetor   numel)r@   rm   rn   rD   special_image_maskn_image_tokensn_image_featuress          r)   get_placeholder_maskz#PaliGemmaModel.get_placeholder_mask   s    !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H+//1)//2^5I5I!5LL/99"=@@AUAUV]00448L8L8NND^DTT`aq`rs	
 "!r(   Nattention_maskposition_idsr.   token_type_idslabels	use_cachec
           	         |du |duz  rt        d      |R| j                  j                  | j                  k\  r/|| j                  j                  k(  }|j	                         }d||<   n|}| | j                         |      }|Y||j                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      dz   }|g| j                  |      j                  }|j                  |j                  |j                        }| j!                  |||      }|j#                  ||      }| j                  j%                         ||||d}|du xs |j&                   xs |du}||rt        j(                  |dk(  dd      |d	<   t+        di |}t-        | j                  j.                  d
d      |j1                         }|t3        di |d} | j4                  d|||||	d|
}t7        |j8                  |j:                  |j<                  |j>                  |      S d      S )  
        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.text_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.text_config.vocab_size]`.

        Example:

        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration

        >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
        >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")

        >>> prompt = "Where is the cat standing?"
        >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> inputs = processor(images=image, text=prompt,  return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(**inputs,)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Where is the cat standing?\nsnow"
        ```Nz:You must specify exactly one of input_ids or inputs_embedsr   r   rp   )rn   rD   )r4   rn   r   r.   r   rq   block_sequence_idssliding_window)full_attentionsliding_attention)r   r   r.   rn   r   )rh   r.   r/   r0   r   r'   ) 
ValueErrorr4   rt   r^   clonerr   get_seq_lengthr$   arangerx   rp   ry   rl   ri   rz   ra   r   masked_scatterr`   is_initializedwherer	   getattrr]   copyr   r_   r   rh   r.   r/   r0   )r@   rm   rd   r   r   r.   r   rn   r   r   re   r|   llm_input_idspast_seen_tokensrD   mask_kwargsis_first_iterationcausal_masksliding_mask_kwargsoutputss                       r)   rE   zPaliGemmaModel.forward   s   Z -t";<YZZ  T[[%?%?4??%R!*dkk.H.H!H%OO-M01M,-%M 7D557FMCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4q8L #!44\BPPN+..}/C/C]EXEXYN!%!:!:~ "; " *889K^\M kk113*,.(
 -4vO<Z<Z8Zv^jrv^v%*<05Na<OQRTV0WK,- )7;74;;**,<dCO"-"2"2"4"-%F%]I\%]K
 &$%% 
&%+'
 
 ,%77#33!//))2>2J
 	

 QU
 	
r(   )	NNNNNNNNN)r    r!   r"   accepts_loss_kwargsr   r9   r   r   r$   r%   r   r   r1   r   rl   
LongTensorr   Tensorr   boolr   r   rE   rF   rG   s   @r)   rX   rX   t   s     
 
 n!--9?@R9S	+	+ "))":?:K:K"]b]n]n"0  .215.204(,2626*.!%l
##d*l
 ''$.l
 t+	l

 &&-l
 l
 ((4/l
 ((4/l
   4'l
 $;l
 -.l
 
-	-l
  l
r(   rX   c                   p    e Zd ZddiZdef fdZedej                  de	e
   fd       Zee	 	 	 	 	 	 	 	 	 	 dd	ej                  dz  dej                  dz  d
ej                  dz  dej                  dz  dedz  dej                  dz  dej                  dz  dej                  dz  dedz  deej                  z  de	e
   deez  fd              Z	 	 	 	 	 	 	 	 	 	 d fd	Ze	 	 ddedej                  d
ej                  dz  dedz  dej                  dz  dej                  dz  dedz  defd       Z xZS )!PaliGemmaForConditionalGenerationzlm_head.weightz(model.language_model.embed_tokens.weightr4   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y )NFr6   )r8   r9   rX   rJ   r   r:   r]   r<   r^   lm_headrc   r?   s     r)   r9   z*PaliGemmaForConditionalGeneration.__init__(  sS     #F+
yy!3!3!?!?ASASA^A^ejkr(   rd   re   c                 <     | j                   j                  |fi |S rC   )rJ   rl   )r@   rd   re   s      r)   rl   z4PaliGemmaForConditionalGeneration.get_image_features.  s    ,tzz,,\DVDDr(   Nrm   r   r   r.   r   rn   r   r   logits_to_keeprf   c                     | j                   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 )r   )	rm   rd   r   r   r   r.   rn   r   r   r   N)r-   r   r^   )r,   r-   r.   r/   r0   r   r'   )rJ   
isinstanceintslicer   loss_functionr4   r]   r^   r+   r.   r/   r0   r   )r@   rm   rd   r   r   r.   r   rn   r   r   r   re   r   r/   slice_indicesr-   r,   s                    r)   rE   z)PaliGemmaForConditionalGeneration.forward2  s    Z $** 
%))%+'
 
  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD /#33!//)) ' ; ;
 	
r(   c                     t        |   |f||||||	||d|}|j                  d      |d   dz   |d<   |s|s||d<   |S )N)r.   rn   r   r   r   r   r   r   r   r   rd   )r8   prepare_inputs_for_generationget)r@   rm   r.   rn   r   rd   r   r   r   r   r   r   re   model_inputsrA   s                 r)   r   z?PaliGemmaForConditionalGeneration.prepare_inputs_for_generation  s|      w<
+')%))1
 
 N+7+7+G!+KL( Y+7L(r(   r   c                     t        j                  g |j                         d d d|j                        }|t        j                  |dk(  dd      }t        | j                         |||||      S )Nrq   r   r   )r4   rn   r   r   r.   r   )r$   fullsizerp   r   r
   r`   )	r4   rn   r   r.   r   r   r   re   	group_idss	            r)   r
   z;PaliGemmaForConditionalGeneration.create_masks_for_generate  sy     JJ;!3!3!5cr!:;RH\H\]	% Na$7B?I())+'()+%
 	
r(   )
NNNNNNNNNr   )
NNNNNNTNNF)NF)r    r!   r"   _tied_weights_keysr   r9   r   r$   r%   r   r   rl   r   r   r   r   r   r   r1   r+   rE   r   staticmethodr   dictr
   rF   rG   s   @r)   r   r      s-    +,VW  Eu/@/@ EFSeLf E E  .215.204(,2626*.!%-.J
##d*J
 ''$.J
 t+	J

 &&-J
 J
 ((4/J
 ((4/J
   4'J
 $;J
 ell*J
 +,J
 
0	0J
  J
^  )V  /3*/
 
||
 t+
 	

 llT)
 t+
 !4K
 

 
r(   r   )r   rI   rX   ).r#   dataclassesr   r$   r   cache_utilsr   configuration_utilsr   
generationr   masking_utilsr	   r
   r   modeling_flash_attention_utilsr   modeling_outputsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   r   r   r   autor   configuration_paligemmar   
get_loggerr    loggerr   r+   Moduler3   rI   rX   r   __all__r'   r(   r)   <module>r      s<    !     3 ) m m B S - &   4 
		H	% 
 9#: 9 9 
 9k 9 90299  ' ' ' 
d
- d

d
N 
^
(@/ ^

^
B ^r(   