Ë
    T^(hC  ã                   ód  — d dl mZ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 ddlmZmZ dd	lmZ dd
lmZmZmZmZmZ  ej.                  e«      Z G d„ de«      Z G d„ de«      Z G d„ de«      Z G d„ de«      Z G d„ de«      Z G d„ de«      Z G d„ de«      Z  G d„ de«      Z!g d¢Z"y)é    )ÚListÚOptionalÚTupleÚUnionN)Únné   )ÚDynamicCache)Úloggingé   )ÚIdefics3ConfigÚIdefics3VisionConfig)ÚIdefics3ImageProcessor)ÚIdefics3BaseModelOutputWithPastÚ Idefics3ForConditionalGenerationÚIdefics3ModelÚIdefics3PreTrainedModelÚIdefics3VisionTransformerc                   ó   — e Zd ZdZdZy)ÚSmolVLMVisionConfiga¿  
    This is the configuration class to store the configuration of a [`SmolVLMVisionModel`]. It is used to instantiate a
    SmolVLM vision encoder according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the SigLIP checkpoint
    [google/siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) used in SmolVLM
    [HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct).

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 1152):
            Dimensionality of the encoder layers and the pooler layer.
        intermediate_size (`int`, *optional*, defaults to 3072):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        num_channels (`int`, *optional*, defaults to 3):
            Number of channels in the input images.
        image_size (`int`, *optional*, defaults to 224):
            The size (resolution) of each image.
        patch_size (`int`, *optional*, defaults to 32):
            The size (resolution) of each patch.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
        layer_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the layer normalization layers.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

    Example:

    ```python
    >>> from transformers.models.smolvlm.modeling_smolvlm import SmolVLMVisionTransformer
    >>> from transformers.models.smolvlm.configuration_smolvlm import SmolVLMVisionConfig

    >>> # Initializing a SmolVLMVisionConfig with google/siglip-so400m-patch14-384 style configuration
    >>> configuration = SmolVLMVisionConfig()

    >>> # Initializing a SmolVLMVisionTransformer (with random weights) from the google/siglip-so400m-patch14-384 style configuration
    >>> model = SmolVLMVisionTransformer(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```Úsmolvlm_visionN©Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú
model_type© ó    úi/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/smolvlm/modular_smolvlm.pyr   r   (   s   „ ñ1ðf "€JØr   r   c                   ó   — e Zd Zy)ÚSmolVLMPreTrainedModelN©r   r   r   r   r   r   r!   r!   `   ó   „ Ør   r!   c                   ó   — e Zd Zy)ÚSmolVLMVisionTransformerNr"   r   r   r   r%   r%   d   r#   r   r%   c                   ó   — e Zd ZdZdZy)ÚSmolVLMConfigaÃ  
    This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a
    SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the model of the SmolVLM
    [HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should cache the key/value pairs of the attention mechanism. Only
            relevant if `config.is_decoder=True`.
        image_token_id (`int`, *optional*, defaults to 128257):
            The id of the "image" token.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether or not to tie the word embeddings with the token embeddings.
        vision_config (`IdeficsVisionConfig` or `dict`, *optional*, defaults to `IdeficsVisionConfig`):
            Custom vision config or dict for the vision tower
        text_config (`PretrainedConfig` or `dict`, *optional*, defaults to `LlamaConfig`):
            Custom text config or dict for the text model
        scale_factor (`int`, *optional*, defaults to 2):
            The scale factor for the image encoder.
        pad_token_id (`int`, *optional*, defaults to 128002):
            The id of the padding token.

    Example:
    ```python
    >>> from transformers import SmolVLMModel, SmolVLMConfig
    >>> # Initializing configuration
    >>> configuration = SmolVLMConfig()
    >>> # Initializing a model from the configuration
    >>> model = SmolVLMModel(configuration)
    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```ÚsmolvlmNr   r   r   r   r'   r'   h   s   „ ñ#ðJ €JØr   r'   c                   ó   — e Zd Zy)ÚSmolVLMImageProcessorNr"   r   r   r   r*   r*   ’   r#   r   r*   c                   ó   — e Zd Zy)ÚSmolVLMBaseModelOutputWithPastNr"   r   r   r   r,   r,   –   r#   r   r,   c                   óÎ  — e Zd ZdZdej
                  dej                  dej                  fd„Z	 	 	 	 	 	 	 	 	 	 	 	 	 ddeej
                     deej                     deej
                     d	ee	ej                        deej                     d
eej                     deej                     deej                     dee   dee   dee   dee   deej
                     deeef   fd„Zy)ÚSmolVLMModelz§
    A subclass of Idefics3Model. We do *not* remove or block the call to inputs_merger
    in forward. Instead, we override inputs_merger here with custom logic.
    Ú	input_idsÚinputs_embedsÚimage_hidden_statesc                 óH  — |j                   \  }}}|| j                  k(  }|j                  d¬«      }t        j                  ||z  dk(  «      st        d«      ‚||z  }t        j                  j                  j                  |j                  d¬«      dd¬«      }	|	d d }
|j                  d¬«      }|dz
  |z  }|dz
  |z  }|
j                  d«      |z   }t        j                  |«      }|||   ||   d d …f   ||<   t        j                  |j                  d«      ||«      }|S )Né   ©Údimr   zCAt least one sample has <image> tokens not divisible by patch_size.)r3   r   )Úvalueéÿÿÿÿ)ÚshapeÚimage_token_idÚsumÚtorchÚallÚ
ValueErrorr   Ú
functionalÚpadÚcumsumÚ	unsqueezeÚ
zeros_likeÚwhere)Úselfr/   r0   r1   Ú_Ú
patch_sizeÚ
image_maskÚnum_image_tokensÚblocks_per_sampleÚoffsetsÚblock_offsetÚrow_cumÚ	chunk_idxÚ	local_idxÚ	block_idxÚimage_embedsÚmerged_embedss                    r   Úinputs_mergerzSmolVLMModel.inputs_merger    s:  € ð /×4Ñ4Ñˆˆ:�qà $×"5Ñ"5Ñ5ˆ
Ø%Ÿ>™>¨a˜>Ó0ÐÜ�y‰yÐ)¨JÑ6¸!Ñ;Ô<ÜÐbÓcÐcà,°
Ñ:Ðä—(‘(×%Ñ%×)Ñ)Ð*;×*BÑ*BÀqÐ*BÓ*IÈ6ÐYZÐ)Ó[ˆØ˜s �|ˆØ×#Ñ#¨Ð#Ó+ˆØ˜q‘[ ZÑ/ˆ	Ø˜q‘[ JÑ.ˆ	Ø ×*Ñ*¨1Ó-°	Ñ9ˆ	ä×'Ñ'¨Ó6ˆØ#6°yÀÑ7LÈiÐXbÑNcÒefÐ7fÑ#gˆ�ZÑ äŸ™ J×$8Ñ$8¸Ó$<¸lÈMÓZˆØÐr   NÚattention_maskÚposition_idsÚpast_key_valuesÚpixel_valuesÚpixel_attention_maskÚ	use_cacheÚoutput_attentionsÚoutput_hidden_statesÚreturn_dictÚcache_positionÚreturnc                 ód  — |
�|
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«      ‚d}|	r|€
t        «       }|j                  «       }|�|€|dk(  rt        d«      ‚|€9 | j                  j                  «       |«      j                  |j                   «      }|�|�t        d«      ‚|��­|j                  \  }}}}}|} |j"                  ||z  g|j                  dd  ¢­Ž }|j                  dd  j%                  «       }|d	k(  j'                  d
¬«      |k7  }t)        |«      sd|d<   ||   j+                  «       }|€Lt-        j.                  dD �cg c]  }|j                  |   ‘Œ c}t,        j0                  |j                   ¬«      }n6 |j"                  ||z  g|j                  dd  ¢­Ž }||   j+                  «       }| j                   j2                  j4                  }|j7                  d||¬«      }|j7                  d||¬«      }|j'                  d¬«      dkD  j1                  «       }| j9                  ||¬«      j:                  }| j=                  |«      }n)|�'|j                  | j>                  |j                   ¬«      }|�|�| jA                  |||¬«      }| j                  |||||	|
|||¬«	      }|stC        d„ g |¢|‘D «       «      S tE        |j:                  |jF                  |jH                  |jJ                  |¬«      S c c}w )NzZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fz5You have to specify either input_ids or inputs_embedsr   zWWhen first calling the model, if input_embeds are passed, input_ids should not be None.zMYou cannot specify both pixel_values and image_hidden_states at the same timer   r3   g        )r7   éþÿÿÿéýÿÿÿr4   T)r   r   r   )ÚsizeÚdtypeÚdevice)Ú	dimensionra   Ústep)r7   r_   )rV   Úpatch_attention_mask)rb   rc   )r/   r0   r1   )	r0   rS   rT   rU   rX   rY   rZ   r[   r\   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­w)Nr   )Ú.0Úvs     r   ú	<genexpr>z'SmolVLMModel.forward.<locals>.<genexpr>1  s   è ø€ ÒU˜qÀqÁ}œÑUùs   ‚Š)Úlast_hidden_staterU   Úhidden_statesÚ
attentionsr1   )&ÚconfigrY   rZ   rX   Úuse_return_dictÚtrainingÚ
text_modelÚgradient_checkpointingÚloggerÚwarning_oncer8   r=   r	   Úget_seq_lengthÚget_input_embeddingsÚtorc   ÚviewÚnumelr:   ÚanyÚ
contiguousr;   ÚonesÚboolÚvision_configrF   ÚunfoldÚvision_modelrk   Ú	connectorrb   rR   Útupler,   rU   rl   rm   )rD   r/   rS   rT   rU   r0   rV   rW   r1   rX   rY   rZ   r[   r\   Ú
batch_sizeÚ
seq_lengthrE   Úpast_seen_tokensÚ
num_imagesÚnum_channelsÚheightÚwidthÚnb_values_per_imageÚreal_images_indsÚirF   Úpatches_subgridrf   Úoutputss                                r   ÚforwardzSmolVLMModel.forward¹   s  € ð  2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð "+Ð!6‘I¸D¿K¹K×<QÑ<Qˆ	Ø%0Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà�=Š=˜TŸ_™_×CÒCÉ	Ü×ÑØlôð ˆIð Ð Ø%.§_¡_Ñ"ˆJ™
ØÐ&Ø(5×(;Ñ(;Ñ%ˆJ˜
¡AäÐTÓUÐUàÐÙØÐ&Ü".£.�Ø.×=Ñ=Ó?ÐàÐ$¨Ð):Ð?OÐSTÒ?TÜÐvÓwÐwàÐ ØB˜DŸO™O×@Ñ@ÓBÀ9ÓM×PÑPÐQZ×QaÑQaÓbˆMð Ð#Ð(;Ð(GÜÐlÓmÐmØÑ%ØBN×BTÑBTÑ?ˆJ˜
 L°&¸%Ø'ˆLØ,˜<×,Ñ,¨Z¸*Ñ-DÐ^À|×GYÑGYÐZ[ÐZ\ÐG]Ò^ˆLð #/×"4Ñ"4°Q°RÐ"8×">Ñ">Ó"@ÐØ ,°Ñ 3×8Ñ8¸\Ð8ÓJÐNaÑaÐäÐ'Ô(à&*Ð  Ñ#à'Ð(8Ñ9×DÑDÓFˆLð $Ð+Ü',§z¡zØ9BÖC°A˜,×,Ñ,¨QÓ/ÒCÜŸ*™*Ø'×.Ñ.ô(Ñ$ð (AÐ';×'@Ñ'@Ø Ñ+ð(Ø.B×.HÑ.HÈÈÐ.Lò(Ð$ð (<Ð<LÑ'M×'XÑ'XÓ'ZÐ$àŸ™×2Ñ2×=Ñ=ˆJØ2×9Ñ9ÀAÈJÐ]gÐ9ÓhˆOØ-×4Ñ4¸qÀzÐXbÐ4ÓcˆOØ$3×$7Ñ$7¸HÐ$7Ó$EÈÑ$I×#OÑ#OÓ#QÐ ð #'×"3Ñ"3Ø)Ø%9ð #4ó #÷  Ñð  ð #'§.¡.Ð1DÓ"EÑà Ð,Ø"5×"8Ñ"8¸t¿z¹zÐR[×RbÑRbÐ"8Ó"cÐàÐ$Ð)<Ð)Hð !×.Ñ.Ø#Ø+Ø$7ð /ó ˆMð —/‘/Ø'Ø)Ø%Ø+ØØ/Ø!5Ø#Ø)ð "ó 

ˆñ ÜÑUÐ$C gÐ$CÐ/BÐ$CÔUÓUÐUä-Ø%×7Ñ7Ø#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø 3ô
ð 	
ùòi Ds   Ç9N-)NNNNNNNNNNNNN)r   r   r   r   r;   Ú
LongTensorÚTensorrR   r   r   ÚFloatTensorÚ
BoolTensorr}   r   r   r,   r�   r   r   r   r.   r.   š   s|  „ ñð
Ø×)Ñ)ðØ:?¿,¹,ðØ]b×]iÑ]ióð6 15Ø15Ø37Ø=AØ59Ø48Ø;?Ø;?Ø$(Ø,0Ø/3Ø&*Ø59ñ@
à˜E×,Ñ,Ñ-ð@
ð ! §¡Ñ.ð@
ð ˜u×/Ñ/Ñ0ð	@
ð
 " $ u×'8Ñ'8Ñ"9Ñ:ð@
ð   × 1Ñ 1Ñ2ð@
ð ˜u×0Ñ0Ñ1ð@
ð ' u×'7Ñ'7Ñ8ð@
ð & e×&7Ñ&7Ñ8ð@
ð ˜D‘>ð@
ð $ D™>ð@
ð ' t™nð@
ð ˜d‘^ð@
ð ! ×!1Ñ!1Ñ2ð@
ð 
ˆuÐ4Ð4Ñ	5ô@
r   r.   c                   ó,   ‡ — e Zd ZdZˆ fd„Zˆ fd„Zˆ xZS )ÚSmolVLMForConditionalGenerationzy
    A subclass of Idefics3ForConditionalGeneration that uses SmolVLMModel
    instead of the default Idefics3Model.
    c                 óî   •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  j                  |j                  j                  d¬«      | _	        | j                  «        y )NF)Úbias)ÚsuperÚ__init__r.   Úmodelr   ÚLinearÚtext_configÚhidden_sizeÚ
vocab_sizeÚlm_headÚ	post_init)rD   rn   Ú	__class__s     €r   r™   z(SmolVLMForConditionalGeneration.__init__B  sS   ø€ Ü‰Ñ˜Ô Ü! &Ó)ˆŒ
Ü—y‘y ×!3Ñ!3×!?Ñ!?À×ASÑAS×A^ÑA^ÐejÔkˆŒØ�‰Õr   c                 ó$   •— t        ‰| �  di |¤Ž y)aÌ  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `SmolVLMForConditionalGeneration`).
                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]`.
        Returns:

        Example:

        ```python
        >>> import requests
        >>> import torch
        >>> from PIL import Image
        >>> from io import BytesIO

        >>> from transformers import AutoProcessor, AutoModelForImageTextToText
        >>> 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("HuggingFaceTB/SmolVLM2-2.2B-Instruct")
        >>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct", torch_dtype=torch.bfloat16, device_map="auto")

        >>> # Create inputs
        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "video", "path": path/to/video},
        ...             {"type": "text", "text": "What is happening in this video?"},
        ...         ]
        ...     }
        ... ]

        >>> inputs = processor.apply_chat_template([messages], add_generation_prompt=True)

        >>> # Generate
        >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
        >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

        >>> print(generated_texts)
        ```Nr   )r˜   r�   )rD   Úsuper_kwargsr¡   s     €r   r�   z'SmolVLMForConditionalGeneration.forwardH  s   ø€ ô` 	‰‰Ñ'˜,Ó'r   )r   r   r   r   r™   r�   Ú__classcell__)r¡   s   @r   r•   r•   <  s   ø„ ñô
÷0(ð 0(r   r•   )r   r'   r*   r•   r!   r.   r%   )#Útypingr   r   r   r   r;   Útorch.utils.checkpointr   Úcache_utilsr	   Úutilsr
   Úidefics3.configuration_idefics3r   r   Ú"idefics3.image_processing_idefics3r   Úidefics3.modeling_idefics3r   r   r   r   r   Ú
get_loggerr   rs   r   r!   r%   r'   r*   r,   r.   r•   Ú__all__r   r   r   ú<module>r®      s¸   ð÷  0Ó /ã Û Ý å 'õ÷ SÝ G÷õ ð 
ˆ×	Ñ	˜HÓ	%€ô5	Ð.ô 5	ôp	Ð4ô 	ô	Ð8ô 	ô'	�Nô '	ôT	Ð2ô 	ô	Ð%Dô 	ô_
�=ô _
ôD<(Ð&Fô <(ò~�r   