Ë
    ÜÓ^jJ  ã                   óÌ  — 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 ddlmZmZmZ ddlmZ ddlmZ ddlmZ  ed¬«      e G d„ de«      «       «       Z ed¬«      e G d„ de«      «       «       Z G d„ dej<                  «      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)#é    )Ú	dataclassN)Únné   )ÚACT2FN)ÚCache)ÚGenerationMixin)ÚBaseModelOutputWithPastÚBaseModelOutputWithPoolingÚModelOutput)ÚPreTrainedModel)ÚUnpack)ÚTransformersKwargsÚauto_docstringÚtorch_compilable_check)Úcan_return_tupleé   )Ú	AutoModelé   )ÚVipLlavaConfigzM
    Base class for VipLlava outputs, with hidden states and attentions.
    ©Úcustom_introc                   ó:   — e Zd ZU dZdZej                  dz  ed<   y)ÚVipLlavaModelOutputWithPastaÏ  
    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 and after projecting the last hidden state.
    NÚimage_hidden_states)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚtorchÚFloatTensorÚ__annotations__© ó    úy/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/vipllava/modeling_vipllava.pyr   r   &   s   … ñ	ð 59Ð˜×*Ñ*¨TÑ1Ô8r#   r   zT
    Base class for VipLlava 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)	ÚVipLlavaCausalLMOutputWithPasta4  
    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`):
        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 and after projecting the last hidden state.
    NÚlossÚlogitsÚpast_key_valuesÚhidden_statesÚ
attentionsr   )r   r   r   r   r'   r   r    r!   r(   r)   r   r*   Útupler+   r   r"   r#   r$   r&   r&   ;   s‹   … ñð &*€Dˆ%×
Ñ
˜dÑ
"Ó)Ø'+€FˆE×Ñ Ñ$Ó+Ø$(€O�U˜T‘\Ó(Ø59€M�5˜×*Ñ*Ñ+¨dÑ2Ó9Ø26€J��e×'Ñ'Ñ(¨4Ñ/Ó6Ø48Ð˜×*Ñ*¨TÑ1Ô8r#   r&   c                   ó*   ‡ — e Zd Zdefˆ fd„Zd„ Zˆ xZS )ÚVipLlavaMultiModalProjectorÚconfigc                 óH  •— t         ‰| �  «        t        |j                  t        «      rdnt        |j                  «      }t        j                  ||j                  j                  z  |j                  ¬«      | _        t        j                  ||j                  j                  z  |j                  j                  d¬«      | _        t        |j                      | _        t        j                  |j                  j                  |j                  j                  d¬«      | _        y )Nr   )ÚepsT©Úbias)ÚsuperÚ__init__Ú
isinstanceÚvision_feature_layersÚintÚlenr   Ú	LayerNormÚvision_configÚhidden_sizeÚprojector_layernorm_epsÚprojector_layernormÚLinearÚtext_configÚlinear_1r   Úprojector_hidden_actÚactÚlinear_2)Úselfr/   Únum_feature_layersÚ	__class__s      €r$   r5   z$VipLlavaMultiModalProjector.__init__Z   sØ   ø€ Ü‰ÑÔÜ",¨V×-IÑ-IÌ3Ô"O™QÔUXÐY_×YuÑYuÓUvÐÜ#%§<¡<Ø ×!5Ñ!5×!AÑ!AÑAÀv×GeÑGeô$
ˆÔ ô Ÿ	™	Ø ×!5Ñ!5×!AÑ!AÑAØ×Ñ×*Ñ*Øô
ˆŒô
 ˜&×5Ñ5Ñ6ˆŒÜŸ	™	 &×"4Ñ"4×"@Ñ"@À&×BTÑBT×B`ÑB`ÐgkÔlˆ�r#   c                 óŽ   — | j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      }|S ©N)r>   rA   rC   rD   )rE   r*   s     r$   Úforwardz#VipLlavaMultiModalProjector.forwardi   sB   € Ø×0Ñ0°Ó?ˆØŸ™ mÓ4ˆØŸ™ Ó/ˆØŸ™ mÓ4ˆØÐr#   )r   r   r   r   r5   rJ   Ú__classcell__©rG   s   @r$   r.   r.   Y   s   ø„ ðm˜~õ mör#   r.   c                   ó>   — e Zd ZU eed<   dZdZdZdgZdZ	dZ
dZdZdZy)ÚVipLlavaPreTrainedModelr/   Úmodel)ÚimageÚtextTr)   N)r   r   r   r   r!   Úbase_model_prefixÚinput_modalitiesÚsupports_gradient_checkpointingÚ_skip_keys_device_placementÚ_supports_flash_attnÚ_supports_sdpaÚ_can_compile_fullgraphÚ_supports_flex_attnÚ_supports_attention_backendr"   r#   r$   rN   rN   q   s@   … àÓØÐØ(ÐØ&*Ð#Ø#4Ð"5ÐàÐØ€Nà!ÐØÐØ"&Ñr#   rN   zx
    The VipLlava model which consists of a vision backbone and a language model, without a language modeling head.
    c                   óæ  ‡ — e Zd Zdefˆ fd„Ze ed¬«      	 ddej                  de	e
e	   z  dz  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	e
e	   z  dz  dedz  dee   d	eez  fd„«       «       Zˆ xZS )ÚVipLlavaModelr/   c                 óô   •— t         ‰| �  |«       t        j                  |j                  «      | _        t        |«      | _        t        j                  |j                  «      | _	        | j                  «        y rI   )r4   r5   r   Úfrom_configr;   Úvision_towerr.   Úmulti_modal_projectorr@   Úlanguage_modelÚ	post_init©rE   r/   rG   s     €r$   r5   zVipLlavaModel.__init__‡   sY   ø€ Ü‰Ñ˜Ô Ü%×1Ñ1°&×2FÑ2FÓGˆÔä%@ÀÓ%HˆÔ"Ü'×3Ñ3°F×4FÑ4FÓGˆÔØ�‰Õr#   zWObtains image last hidden states from the vision tower and apply multimodal projection.r   NÚpixel_valuesr7   ÚkwargsÚreturnc                 ón  — |�|n| j                   j                  }d|d<    | j                  |fi |¤Ž}t        |t        «      r|j
                  |   dd…dd…f   }n<|D �cg c]  }|j
                  |   dd…dd…f   ‘Œ }}t        j                  |d¬«      }| j                  |«      }||_	        |S c c}w )á\  
        pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
            The tensors corresponding to the input images.
        vision_feature_layers (`Union[int, list[int]]`, *optional*):
            The vision feature layer, or the list of indexes of the layers to select
            the vision feature.
        NTÚoutput_hidden_statesr   éÿÿÿÿ)Údim)
r/   r7   r_   r6   r8   r*   r   Úcatr`   Úpooler_output)rE   rd   r7   re   Úimage_outputsÚimage_featuresÚindexs          r$   Úget_image_featuresz VipLlavaModel.get_image_features�   sÖ   € ð$ &;Ð%FÑ!ÈDÏKÉK×LmÑLmð 	ð *.ˆÐ%Ñ&Ø)˜×)Ñ)Øñ
àñ
ˆô Ð+¬SÔ1Ø*×8Ñ8Ð9NÑOÒPQÐSTÑSUÐPUÑV‰Nð VkÖkÈE˜m×9Ñ9¸%Ñ@ÂÀAÁBÀÓGÐkˆNÐkÜ"ŸY™Y ~¸2Ô>ˆNØ×3Ñ3°NÓCˆØ&4ˆÔ#àÐùò ls   Á B2Ú	input_idsÚinputs_embedsro   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.
        )ÚdtypeÚdevicerj   r   r   z6Image features and image tokens do not match, tokens: z, features: )Úget_input_embeddingsr   Útensorr/   Úimage_token_idÚlongrv   ÚallÚsumÚshapeÚ	unsqueezeÚtor   Únumel)rE   rr   rs   ro   Úspecial_image_maskÚn_image_tokensÚn_image_featuress          r$   Úget_placeholder_maskz"VipLlavaModel.get_placeholder_mask·   s  € ð ÐØ!.Ð2M°$×2KÑ2KÓ2MÜ—‘˜TŸ[™[×7Ñ7¼u¿z¹zÐR_×RfÑRfÔgó3ñ "Ðð "4×!7Ñ!7¸Ó!;Ñà!*¨d¯k©k×.HÑ.HÑ!HÐà+×/Ñ/Ó1ˆØ)×/Ñ/°Ñ2°^×5IÑ5IÈ!Ñ5LÑLÐØ/×9Ñ9¸"Ó=×@Ñ@À×AUÑAUÓVÐÜØ˜]×0Ñ0°Ñ4Ñ4¸×8LÑ8LÓ8NÑNØDÀ^ÐDTÐT`ÐaqÐ`rÐsô	
ð "Ð!r#   Úattention_maskÚposition_idsr)   Ú	use_cacheÚ	lm_kwargsc	           	      ó  — |�|n| j                   j                  }|du |duz  rt        d«      ‚|€ | j                  «       |«      }|�i| j	                  ||¬«      j
                  }
|
j                  |j                  |j                  «      }
| j                  |||
¬«      }|j                  ||
«      } | j                  d|||||dœ|	¤Ž}t        |j                  |j                  |j                  |j                   |�
nd¬«      }|S )zÃ
        vision_feature_layers (`Union[int, list[int]]`, *optional*):
            The vision feature layer, or the list of indexes of the layers to select
            the vision feature.
        Nz:You must specify exactly one of input_ids or inputs_embeds©rd   r7   )rs   ro   )r…   r†   r)   rs   r‡   )Úlast_hidden_stater)   r*   r+   r   r"   )r/   r7   Ú
ValueErrorrw   rq   rm   r   rv   ru   r„   Úmasked_scatterra   r   r‹   r)   r*   r+   )rE   rr   rd   r…   r†   r)   rs   r7   r‡   rˆ   ro   r�   ÚoutputsÚoutputs                 r$   rJ   zVipLlavaModel.forwardÏ   sF  € ð( &;Ð%FÑ!ÈDÏKÉK×LmÑLmð 	ð ˜Ð -°tÐ";Ò<ÜÐYÓZÐZàÐ Ø7˜D×5Ñ5Ó7¸	ÓBˆMàÐ#Ø!×4Ñ4Ø)ÐAVð 5ó ç‰mð ð ,×.Ñ.¨}×/CÑ/CÀ]×EXÑEXÓYˆNØ!%×!:Ñ!:Ø¨À~ð ";ó "Ðð *×8Ñ8Ð9KÈ^Ó\ˆMà+>¨4×+>Ñ+>ð ,
Ø)Ø%Ø+Ø'Øñ,
ð ñ,
ˆô -Ø%×7Ñ7Ø#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø2>Ð2J¡ÐPTô
ˆð ˆr#   rI   )NNNNNNNN)r   r   r   r   r5   r   r   r   r    r8   Úlistr   r   r,   r
   rq   Ú
LongTensorr„   ÚTensorr   Úboolr   rJ   rK   rL   s   @r$   r\   r\   �   s›  ø„ ð˜~õ ð ÙØnôð 9=ñ"à×'Ñ'ð"ð  # T¨#¡Y™°Ñ5ð"ð Ð+Ñ,ð	"ð
 
Ð+Ñ	+ò"óó ð"ðH"Ø×)Ñ)ð"Ø:?×:KÑ:Kð"Ø]b×]nÑ]nó"ð0 Øð .2Ø15Ø.2Ø04Ø(,Ø26Ø8<Ø!%ñ5à×#Ñ# dÑ*ð5ð ×'Ñ'¨$Ñ.ð5ð Ÿ™ tÑ+ð	5ð
 ×&Ñ&¨Ñ-ð5ð  ™ð5ð ×(Ñ(¨4Ñ/ð5ð  # T¨#¡Y™°Ñ5ð5ð ˜$‘;ð5ð Ð.Ñ/ð5ð 
Ð,Ñ	,ò5ó ó ô5r#   r\   zV
    The VIPLLAVA model which consists of a vision backbone and a language model.
    c                   óþ  ‡ — e Zd ZddiZdefˆ fd„Zdej                  fd„Ze		 dde
j                  d	eee   z  dz  d
ee   deez  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ee   z  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ˆ xZS )Ú VipLlavaForConditionalGenerationzlm_head.weightz(model.language_model.embed_tokens.weightr/   c                 óî   •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  j                  |j                  j                  d¬«      | _	        | j                  «        y )NFr2   )r4   r5   r\   rO   r   r?   r@   r<   Ú
vocab_sizeÚlm_headrb   rc   s     €r$   r5   z)VipLlavaForConditionalGeneration.__init__  sS   ø€ Ü‰Ñ˜Ô Ü" 6Ó*ˆŒ
Ü—y‘y ×!3Ñ!3×!?Ñ!?À×ASÑAS×A^ÑA^ÐejÔkˆŒØ�‰Õr#   rf   c                 ó   — | j                   S rI   )r˜   )rE   s    r$   Úget_output_embeddingsz6VipLlavaForConditionalGeneration.get_output_embeddings  s   € Ø�|‰|Ðr#   Nrd   r7   re   c                 ó@   —  | j                   j                  d||dœ|¤ŽS )rh   rŠ   r"   )rO   rq   )rE   rd   r7   re   s       r$   rq   z3VipLlavaForConditionalGeneration.get_image_features  s0   € ð -ˆt�z‰z×,Ñ,ð 
Ø%Ð=Rñ
ØV\ñ
ð 	
r#   rr   r…   r†   r)   rs   Úlabelsr‡   Úlogits_to_keeprˆ   c                 óÖ  — |�|n| j                   j                  } | j                  d|||||||	|dœ|¤Ž}|j                  }t	        |
t
        «      rt        |
 d«      n|
}| j                  |dd…|dd…f   «      }d}|�2| j                  ||| j                   j                  j                  ¬«      }t        |||j                  |j                  |j                  |j                  ¬«      S )aó  
        vision_feature_layers (`Union[int, list[int]]`, *optional*):
            The vision feature layer, or the list of indexes of the layers to select
            the vision feature.
        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]`.

        Example:

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

        >>> model = VipLlavaForConditionalGeneration.from_pretrained("llava-hf/vip-llava-7b-hf", device_map="auto", dtype=torch.float16)
        >>> processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")

        >>> prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n{}###Assistant:"
        >>> question = "Can you please describe this image?"
        >>> prompt = prompt.format(question)
        >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> inputs = processor(text=text, images=image, return_tensors="pt").to(0, torch.float16)

        >>> # Generate
        >>> generate_ids = model.generate(**inputs, max_new_tokens=20)
        >>> processor.decode(generate_ids[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
        The image features a brown and white cat sitting on a green surface, with a red ball in its
        ```N)rr   rd   r…   r†   r)   rs   r‡   r7   )r(   rœ   r—   )r'   r(   r)   r*   r+   r   r"   )r/   r7   rO   r‹   r6   r8   Úslicer˜   Úloss_functionr@   r—   r&   r)   r*   r+   r   )rE   rr   rd   r…   r†   r)   rs   r7   rœ   r‡   r�   rˆ   rŽ   r*   Úslice_indicesr(   r'   s                    r$   rJ   z(VipLlavaForConditionalGeneration.forward,  s  € ðj &;Ð%FÑ!ÈDÏKÉK×LmÑLmð 	ð 0:¨t¯z©zð 
0
ØØ%Ø)Ø%Ø+Ø'ØØ"7ñ
0
ð ñ
0
ˆð  ×1Ñ1ˆä8BÀ>ÔSVÔ8Wœ˜~˜o¨tÔ4Ð]kˆØ—‘˜mªA¨}ºaÐ,?Ñ@ÓAˆàˆØÐØ×%Ñ%¨V¸FÈtÏ{É{×OfÑOf×OqÑOqÐ%ÓrˆDä-ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø '× ;Ñ ;ô
ð 	
r#   c           	      óf   •— t        ‰
| �  |f|||||dœ|¤Ž}	|s|j                  dd«      s||	d<   |	S )N)r)   rs   r…   r�   Úis_first_iterationr‡   Trd   )r4   Úprepare_inputs_for_generationÚget)rE   rr   r)   rs   rd   r…   r�   r£   re   Úmodel_inputsrG   s             €r$   r¤   z>VipLlavaForConditionalGeneration.prepare_inputs_for_generation‚  sY   ø€ ô ‘wÑ<Øð
à+Ø'Ø)Ø)Ø1ñ
ð ñ
ˆñ  V§Z¡Z°¸TÔ%Bð
 ,8ˆL˜Ñ(àÐr#   rI   )
NNNNNNNNNr   )NNNNNF)r   r   r   Ú_tied_weights_keysr   r5   r   ÚModulerš   r   r   r    r8   r�   r   r   r,   r
   rq   r   r‘   r’   r   r“   r&   rJ   r¤   rK   rL   s   @r$   r•   r•   	  sÔ  ø„ ð +Ð,VÐWÐð˜~õ ð r§y¡yó ð ð 9=ñ
à×'Ñ'ð
ð  # T¨#¡Y™°Ñ5ð
ð Ð+Ñ,ð	
ð
 
Ð+Ñ	+ò
ó ð
ð" Øð .2Ø15Ø.2Ø04Ø(,Ø26Ø8<Ø*.Ø!%Ø-.ñR
à×#Ñ# dÑ*ðR
ð ×'Ñ'¨$Ñ.ðR
ð Ÿ™ tÑ+ð	R
ð
 ×&Ñ&¨Ñ-ðR
ð  ™ðR
ð ×(Ñ(¨4Ñ/ðR
ð  # T¨#¡Y™°Ñ5ðR
ð × Ñ  4Ñ'ðR
ð ˜$‘;ðR
ð ˜eŸl™lÑ*ðR
ð Ð.Ñ/ðR
ð 
Ð/Ñ	/òR
ó ó ðR
ðn ØØØØØ ÷ñ r#   r•   )r\   r•   rN   )$Údataclassesr   r   r   Úactivationsr   Úcache_utilsr   Ú
generationr   Úmodeling_outputsr	   r
   r   Úmodeling_utilsr   Úprocessing_utilsr   Úutilsr   r   r   Úutils.genericr   Úautor   Úconfiguration_vipllavar   r   r&   r¨   r.   rN   r\   r•   Ú__all__r"   r#   r$   ú<module>rµ      s  ðõ* "ã Ý å !Ý  Ý )ß `Ñ `Ý -Ý &ß OÑ OÝ -Ý Ý 2ñ ðôð
 ô9Ð"9ó 9ó óð9ñ ðôð
 ô9 [ó 9ó óð9ô0 "§)¡)ô ð0 ô'˜oó 'ó ð'ñ ðôô
@Ð+ó @óð
@ñF ðôô
RÐ'>Àó Róð
Ròj [�r#   