Ë
    T^(h¼Ù  ã                   ó¾  — d dl mZ d dlmZ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 dd
lmZ ddlmZmZ ddlmZ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jH                  e%«      Z&dZ'dZ( ede(«       G d„ de«      «       Z) G d„ de	jT                  «      Z+	 d=de	jT                  dejX                  dejX                  dejX                  deejX                     de-de-fd „Z. G d!„ d"e	jT                  «      Z/ G d#„ d$e	jT                  «      Z0 G d%„ d&e	jT                  «      Z1 G d'„ d(e	jT                  «      Z2d)Z3 ed*e3«       G d+„ d,e)«      «       Z4e G d-„ d.e«      «       Z5 G d/„ d0e	jT                  «      Z6 G d1„ d2e	jT                  «      Z7d3Z8 ed4e(«       G d5„ d6e)«      «       Z9e G d7„ d8e«      «       Z: ed9e(«       G d:„ d;e)e«      «       Z;g d<¢Z<y)>é    )Ú	dataclass)ÚCallableÚListÚOptionalÚTupleÚUnionN)Únn)ÚCrossEntropyLossé   )ÚACT2FN)ÚDynamicCache)ÚGenerationMixin)Ú_prepare_4d_attention_mask)ÚBaseModelOutputÚModelOutput)ÚALL_ATTENTION_FUNCTIONSÚPreTrainedModel)Úadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsé   )Ú	AutoModelé   )ÚSmolVLMConfigÚSmolVLMVisionConfigr   ag  
    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 ([`SmolVLMConfig`] or [`SmolVLMVisionConfig`]):
            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 SmolVLM Model outputting raw hidden-states without any specific head on top.c                   ó:   — e Zd ZeZdZdZddgZdZdZ	dZ
dZdZd„ Zy)ÚSmolVLMPreTrainedModelÚmodelTÚSmolVLMVisionAttentionÚSmolVLMDecoderLayerÚpast_key_valuesc                 ó  — t        | j                  d«      r| j                  j                  n#| j                  j                  «       j                  }t        |d«      r'|j                  j
                  j                  d|¬«       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_rangeÚclass_embeddingç        )ÚmeanÚstd)ÚhasattrÚconfigr$   Úget_text_configr%   ÚdataÚnormal_Ú
isinstancer	   ÚLinearÚConv2dÚweightÚbiasÚzero_Ú	EmbeddingÚpadding_idx)ÚselfÚmoduler(   s      új/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/smolvlm/modeling_smolvlm.pyÚ_init_weightsz$SmolVLMPreTrainedModel._init_weightsR   s$  € ô �t—{‘{Ð$7Ô8ð �K‰K×)Ò)à—‘×,Ñ,Ó.×@Ñ@ð 	ô �6Ð,Ô-Ø×"Ñ"×'Ñ'×/Ñ/°S¸cÐ/ÔBä�fœrŸy™y¬"¯)©)Ð4Ô5Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .ó    N)Ú__name__Ú
__module__Ú__qualname__r   Úconfig_classÚbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_skip_keys_device_placementÚ_supports_flash_attn_2Ú_supports_sdpaÚ_supports_flex_attnÚ_supports_cache_classr9   © r:   r8   r   r   C   sC   „ ð
 !€LØÐØ&*Ð#Ø1Ð3HÐIÐØ"3ÐØ!ÐØ€NØÐØ Ðó?r:   r   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 )ÚSmolVLMVisionEmbeddingsaP  
    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://arxiv.org/abs/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.
    r*   c                 óú  •— 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	   r0   Únum_channelsÚpatch_embeddingÚnum_patches_per_sideÚnum_patchesÚnum_positionsr4   Úposition_embedding©r6   r*   Ú	__class__s     €r8   rR   z SmolVLMVisionEmbeddings.__init__q   s¼   ø€ Ü‰ÑÔØ×+Ñ+ˆŒØ ×+Ñ+ˆŒØ ×+Ñ+ˆŒä!Ÿy™yØ×+Ñ+ØŸ™ØŸ™Ø—?‘?Øô 
ˆÔð %)§O¡O°t·±Ñ$FˆÔ!Ø×4Ñ4°aÑ7ˆÔØ!×-Ñ-ˆÔÜ"$§,¡,¨t×/AÑ/AÀ4Ç>Á>Ó"RˆÕr:   Ú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                  ddd|z  «      }t        j                  dd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   g      ð?r   )ÚsizeÚ
fill_valuegé!çýÿï?T)Úrightéÿÿÿÿ)ÚshaperX   ÚflattenÚ	transposerV   ÚtorchÚarangerY   ÚfullÚ	enumerateÚsumÚ	bucketizeÚviewÚcpuÚtor\   r1   Údevice)r6   r_   r`   Ú
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Úfractional_coords_hÚfractional_coords_wÚbucket_coords_hÚbucket_coords_wÚpos_idss                         r8   ÚforwardzSmolVLMVisionEmbeddings.forward„   sÌ  € Ø,8×,>Ñ,>Ñ)ˆ
�A�x à×+Ñ+¨LÓ9ˆØ!×)Ñ)¨!Ó,×6Ñ6°q¸!Ó<ˆ
à-5¸¿¹Ñ-HÈ(ÐVZ×VeÑVeÑJeÐ*ÐÜ—\‘\ ! d×&?Ñ&?Ñ"?ÀÀaÈ$×JcÑJcÑFcÓdˆ
Ü—z‘z¨
Ð4DÐGWÑ4WÐ'XÐefÔgˆä&/Ð0DÓ&Eò 	JÑ"ˆI�{Ø&¢q¨! tÑ,×0Ñ0Ó2ˆLØ& q™>×-Ñ-Ó/ˆLä"'§,¡,¨q°(¸AÀÑ<LÓ"MÐÜ"'§,¡,¨q°(¸AÀÑ<LÓ"MÐä#Ÿo™oÐ.AÀ:ÐUYÔZˆOÜ#Ÿo™oÐ.AÀ:ÐUYÔZˆOà&¢q¨$ wÑ/°$×2KÑ2KÑKÈoÑ]×fÑfÓhˆGØBIˆL˜Ñ# K×$4Ñ$4°RÓ$8×$<Ñ$<Ó$>Ò?ð	Jð $—‘ t×'>Ñ'>×'EÑ'E×'LÑ'LÓMˆØ $×"9Ñ"9¸,Ó"GÑGˆ
ØÐr:   )r;   r<   r=   Ú__doc__r   rR   rj   ÚFloatTensorÚ
BoolTensorÚTensorr‡   Ú__classcell__©r^   s   @r8   rI   rI   f   sD   ø„ ñðSÐ2õ Sð& E×$5Ñ$5ð ÈU×M]ÑM]ð Ðbg×bnÑbn÷ r:   rI   r7   Ú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 )Nrf   éþÿÿÿ)ÚdimÚdtype)ÚpÚtrainingr   r   )rj   Úmatmulri   r	   Ú
functionalÚsoftmaxÚfloat32rr   r—   r“   r™   Ú
contiguous)
r7   rŽ   r�   r�   r‘   r’   r“   ÚkwargsÚattn_weightsÚattn_outputs
             r8   Úeager_attention_forwardr¢       sº   € ô —<‘<  s§}¡}°R¸Ó'<Ó=ÀÑG€LØÐ!Ø# nÑ4ˆä—=‘=×(Ñ(¨¸2ÄUÇ]Á]Ð(ÓS×VÑVÐW\×WbÑWbÓc€LÜ—=‘=×(Ñ(¨¸È6Ï?É?Ð(Ó[€Lä—,‘,˜|¨UÓ3€KØ×'Ñ'¨¨1Ó-×8Ñ8Ó:€Kà˜Ð$Ð$r:   c                   ó¬   ‡ — e Zd ZdZˆ fd„Z	 	 ddej                  deej                     dee   de	ej                  eej                     f   fd„Z
ˆ xZS )	r    z=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)rQ   rR   r*   rS   rT   Únum_attention_headsÚ	num_headsÚhead_dimÚ
ValueErrorÚscaleÚattention_dropoutr“   r	   r/   Úk_projÚv_projÚq_projÚout_projÚ	is_causalr]   s     €r8   rR   zSmolVLMVisionAttention.__init__º   s  ø€ Ü‰ÑÔØˆŒØ×+Ñ+ˆŒØ×3Ñ3ˆŒØŸ™¨$¯.©.Ñ8ˆŒØ�=‰=˜4Ÿ>™>Ñ)¨T¯^©^Ò;ÜØMÈdÏnÉnÐM]ð ^Ø—N‘NÐ# 2ð'óð ð —]‘] DÑ(ˆŒ
Ø×/Ñ/ˆŒä—i‘i §¡°·±Ó?ˆŒÜ—i‘i §¡°·±Ó?ˆŒÜ—i‘i §¡°·±Ó?ˆŒÜŸ	™	 $§.¡.°$·.±.ÓAˆŒð ˆ�r:   Úhidden_statesr‘   Úoutput_attentionsra   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  rN| j                  j                  dk(  r|rt        j                  d«       nt        | j                  j                     }
 |
| |||	|| j                  | j                  | j                   sdn| j"                  ¬«      \  }}|j%                  |||«      j'                  «       }| j)                  |«      }|sd}||fS )	z#Input shape: Batch x Time x Channelr   r   ÚeagerÚsdpazã`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r&   )r¯   r’   r“   N)rg   r­   r«   r¬   rp   r¦   r§   ri   r¢   r*   Ú_attn_implementationÚloggerÚwarning_oncer   r¯   r©   r™   r“   Úreshaperž   r®   )r6   r°   r‘   r±   rt   Ú
seq_lengthrT   ÚqueriesÚkeysÚvaluesÚattention_interfacer¡   r    s                r8   r‡   zSmolVLMVisionAttention.forwardÐ   s”  € ð -:×,?Ñ,?Ñ)ˆ
�J 	à—+‘+˜mÓ,ˆØ�{‰{˜=Ó)ˆØ—‘˜]Ó+ˆà—,‘,˜z¨:°t·~±~ÀtÇ}Á}ÓU×_Ñ_Ð`aÐcdÓeˆØ�y‰y˜ Z°·±ÀÇÁÓO×YÑYÐZ[Ð]^Ó_ˆØ—‘˜Z¨°T·^±^ÀTÇ]Á]ÓS×]Ñ]Ð^_ÐabÓcˆä(?ÐØ�;‰;×+Ñ+¨wÒ6Ø�{‰{×/Ñ/°6Ò9Ñ>OÜ×#Ñ#ðLõô
 '>¸d¿k¹k×>^Ñ>^Ñ&_Ð#á$7ØØØØØØ—n‘nØ—J‘JØ#Ÿ}š}‘C°$·,±,ô	%
Ñ!ˆ�\ð "×)Ñ)¨*°jÀ)ÓL×WÑWÓYˆØ—m‘m KÓ0ˆá ØˆLà˜LÐ(Ð(r:   ©NF)r;   r<   r=   rˆ   rR   rj   r‹   r   Úboolr   r‡   rŒ   r�   s   @r8   r    r    ·   sf   ø„ ÙGôð2 26Ø,1ñ	-)à—|‘|ð-)ð ! §¡Ñ.ð-)ð $ D™>ð	-)ð
 
ˆu�|‰|˜X e§l¡lÑ3Ð3Ñ	4÷-)r:   r    c                   óV   ‡ — e Zd Zˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚSmolVLMVisionMLPc                 ó  •— t         ‰| �  «        || _        t        |j                     | _        t        j                  |j                  |j                  «      | _
        t        j                  |j                  |j                  «      | _        y ©N)rQ   rR   r*   r   Ú
hidden_actÚactivation_fnr	   r/   rS   Úintermediate_sizeÚfc1Úfc2r]   s     €r8   rR   zSmolVLMVisionMLP.__init__  sd   ø€ Ü‰ÑÔØˆŒÜ# F×$5Ñ$5Ñ6ˆÔÜ—9‘9˜V×/Ñ/°×1IÑ1IÓJˆŒÜ—9‘9˜V×5Ñ5°v×7IÑ7IÓJˆ�r:   r°   ra   c                 ól   — | j                  |«      }| j                  |«      }| j                  |«      }|S rÃ   )rÇ   rÅ   rÈ   )r6   r°   s     r8   r‡   zSmolVLMVisionMLP.forward  s4   € ØŸ™ Ó/ˆØ×*Ñ*¨=Ó9ˆØŸ™ Ó/ˆØÐr:   )r;   r<   r=   rR   rj   r‹   r‡   rŒ   r�   s   @r8   rÁ   rÁ      s$   ø„ ôKð U§\¡\ð °e·l±l÷ r:   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 )	ÚSmolVLMEncoderLayerr*   c                 óD  •— t         ‰| �  «        |j                  | _        t	        |«      | _        t        j                  | j                  |j                  ¬«      | _	        t        |«      | _        t        j                  | j                  |j                  ¬«      | _        y )N©Úeps)rQ   rR   rS   rT   r    Ú	self_attnr	   Ú	LayerNormÚlayer_norm_epsÚlayer_norm1rÁ   ÚmlpÚlayer_norm2r]   s     €r8   rR   zSmolVLMEncoderLayer.__init__  sm   ø€ Ü‰ÑÔØ×+Ñ+ˆŒÜ/°Ó7ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÔÜ# FÓ+ˆŒÜŸ<™<¨¯©¸F×<QÑ<QÔRˆÕr:   r°   r‘   r±   ra   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Ó   )r6   r°   r‘   r±   Úresidualr    Úoutputss          r8   r‡   zSmolVLMEncoderLayer.forward  s�   € ð  !ˆà×(Ñ(¨Ó7ˆØ&*§n¡nØ'Ø)Ø/ð '5ó '
Ñ#ˆ�|ð
 ! =Ñ0ˆà ˆØ×(Ñ(¨Ó7ˆØŸ™ Ó/ˆØ  =Ñ0ˆà Ð"ˆáØ˜�Ñ&ˆGàˆr:   )F)r;   r<   r=   r   rR   rj   r‹   r   r¿   r   r‰   r‡   rŒ   r�   s   @r8   rË   rË     sY   ø„ ðSÐ2õ Sð -2ñ	$à—|‘|ð$ð Ÿ™ð$ð $ D™>ð	$ð
 
ˆu× Ñ Ñ	!÷$r:   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 )ÚSmolVLMEncoderz³
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`SmolVLMEncoderLayer`].

    Args:
        config: SmolVLMConfig
    r*   c                 óÐ   •— t         ‰| �  «        || _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        y c c}w r¾   )
rQ   rR   r*   r	   Ú
ModuleListÚrangeÚnum_hidden_layersrË   ÚlayersÚgradient_checkpointing)r6   r*   ru   r^   s      €r8   rR   zSmolVLMEncoder.__init__H  sP   ø€ Ü‰ÑÔØˆŒÜ—m‘mÌ%ÐPV×PhÑPhÓJiÖ$jÀQÔ%8¸Õ%@Ò$jÓkˆŒØ&+ˆÕ#ùò %ks   ½A#r‘   r±   Úoutput_hidden_statesÚreturn_dictra   c                 óì  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|rdnd}|rdnd}|}| j                  D ]]  }	|r||fz   }| j
                  r+| j                  r| j                  |	j                  |||«      }
n |	|||¬«      }
|
d   }|sŒU||
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.
        NrG   )r±   r   r   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrÃ   rG   ©Ú.0Úvs     r8   ú	<genexpr>z)SmolVLMEncoder.forward.<locals>.<genexpr>‘  s   è ø€ Òe˜qÐWXÑWdœÑeùó   ‚Š©Úlast_hidden_stater°   Ú
attentions)r*   r±   rà   Úuse_return_dictrÞ   rß   r™   Ú_gradient_checkpointing_funcÚ__call__Útupler   )r6   Úinputs_embedsr‘   r±   rà   rá   Úencoder_statesÚall_attentionsr°   Úencoder_layerÚlayer_outputss              r8   r‡   zSmolVLMEncoder.forwardO  s7  € ð< 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆá3™¸ˆÙ0™°dˆà%ˆØ!Ÿ[™[ò 	FˆMÙ#Ø!/°=Ð2BÑ!B�Ø×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!Ø"Ø%ó	!‘ñ !.Ø!Ø"Ø&7ô!�ð *¨!Ñ,ˆMâ Ø!/°=ÀÑ3CÐ2EÑ!E‘ð)	Fñ,  Ø+¨}Ð.>Ñ>ˆNáÜÑe ]°NÀNÐ$SÔeÓeÐeÜØ+¸>ÐVdô
ð 	
r:   ©NNNN)r;   r<   r=   rˆ   r   rR   r   rj   r‹   r¿   r   r   r   r‡   rŒ   r�   s   @r8   rÙ   rÙ   ?  s~   ø„ ñð,˜}õ ,ð 26Ø,0Ø/3Ø&*ñE
ð ! §¡Ñ.ðE
ð $ D™>ð	E
ð
 ' t™nðE
ð ˜d‘^ðE
ð 
ˆu�oÐ%Ñ	&÷E
r:   rÙ   aR  
    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 ([`SmolVLMVisionConfig`]):
            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.
zDThe SmolVLM Vision Transformer Model outputting raw image embedding.c                   óœ   ‡ — e Zd ZeZ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 )ÚSmolVLMVisionTransformerTr*   c                 ó  •— t         ‰| �  |«       |j                  }t        |«      | _        t        |«      | _        |j                  | _        t        j                  ||j                  ¬«      | _        |j                  dk(  | _        y )NrÍ   Úflash_attention_2)rQ   rR   rS   rI   ry   rÙ   ÚencoderrV   r	   rÐ   rÑ   Úpost_layernormrµ   Ú_use_flash_attention_2)r6   r*   rT   r^   s      €r8   rR   z!SmolVLMVisionTransformer.__init__²  sm   ø€ Ü‰Ñ˜Ô Ø×&Ñ&ˆ	ä1°&Ó9ˆŒÜ% fÓ-ˆŒØ ×+Ñ+ˆŒÜ Ÿl™l¨9¸&×:OÑ:OÔPˆÔØ&,×&AÑ&AÐEXÑ&XˆÕ#r:   c                 ó   — | j                   S rÃ   ©ry   ©r6   s    r8   Úget_input_embeddingsz-SmolVLMVisionTransformer.get_input_embeddings¼  s   € Ø�‰Ðr:   c                 ó   — || _         y rÃ   rþ   ©r6   r�   s     r8   Úset_input_embeddingsz-SmolVLMVisionTransformer.set_input_embeddings¿  s	   € Øˆ�r:   r`   r±   rà   rá   ra   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«      }t        j                  | «      sd }n"| j                  st        ||j                   «      }| j#                  |||||¬«      }	|	d   }
| j%                  |
«      }
|s	|
f|	dd  z   S t'        |
|	j(                  |	j*                  ¬	«      S )
Nr   r   r   ©r—   rs   ©r_   r`   rf   )rð   r‘   r±   rà   rá   r   ré   )r*   r±   rà   rì   rc   rV   rj   Úonesrr   r¿   rs   ry   rp   Úanyrü   r   r—   rú   rû   r   r°   rë   )r6   r_   r`   r±   rà   rá   rt   rV   r°   Úencoder_outputsrê   s              r8   r‡   z SmolVLMVisionTransformer.forwardÂ  s¨  € ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà!×&Ñ& qÓ)ˆ
ØÐ'ØŸ™ˆJÜ#(§:¡:àØ ×%Ñ% aÓ(¨JÑ6Ø ×%Ñ% aÓ(¨JÑ6ðó$Ð ð $8×#:Ñ#:ÄÇÁÐT`×TgÑTgÐ#:Ó#hÐ àŸ™°\ÐXl˜Ómˆà3×8Ñ8¸ÀRÓHÐô �y‰yÐ.Ð.Ô/Ø#'Ñ Ø×,Ò,Ü#=Ð>RÐTa×TgÑTgÓ#hÐ àŸ,™,Ø'Ø/Ø/Ø!5Ø#ð 'ó 
ˆð ,¨AÑ.ÐØ ×/Ñ/Ð0AÓBÐáØ%Ð'¨/¸!¸"Ð*=Ñ=Ð=äØ/Ø)×7Ñ7Ø&×1Ñ1ô
ð 	
r:   rõ   )r;   r<   r=   r   r>   rD   Ú_supports_flash_attention_2rE   rR   r   r  r   rj   rŠ   r¿   r   r   r   r‡   rŒ   r�   s   @r8   r÷   r÷   ¨  s›   ø„ ð
 '€LØ€NØ"&ÐØÐðYÐ2õ Yòò ð <@Ø,0Ø/3Ø&*ñ7
ð ' u×'7Ñ'7Ñ8ð7
ð $ D™>ð	7
ð
 ' t™nð7
ð ˜d‘^ð7
ð 
ˆu�oÐ%Ñ	&÷7
r:   r÷   c                   óø   — 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)ÚSmolVLMBaseModelOutputWithPasta¿	  
    Base class for SmolVLM model's outputs that may also contain a past key/values (to speed up sequential decoding).
    Args:
        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 (`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)`) 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.
        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 (`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
    Nrê   r"   r°   rë   Úimage_hidden_states)r;   r<   r=   rˆ   rê   r   rj   r‰   Ú__annotations__r"   r   r°   rë   r  rG   r:   r8   r  r  ü  s�   … ñð< 6:Ð�x × 1Ñ 1Ñ2Ó9ØAE€O�X˜e E¨%×*;Ñ*;Ñ$<Ñ=Ñ>ÓEØ8<€M�8˜E %×"3Ñ"3Ñ4Ñ5Ó<Ø59€J�˜˜u×0Ñ0Ñ1Ñ2Ó9Ø>BÐ˜ %¨×(9Ñ(9Ñ":Ñ;ÔBr:   r  c                   ó$   ‡ — e Zd Zˆ fd„Zd„ Zˆ xZS )ÚSmolVLMSimpleMLPc                 óÔ   •— t         ‰| �  «        |j                  j                  |j                  dz  z  }|j
                  j                  }t        j                  ||d¬«      | _        y )Nr   F©r2   )	rQ   rR   Úvision_configrS   Úscale_factorÚtext_configr	   r/   Úproj)r6   r*   Ú
input_sizeÚoutput_sizer^   s       €r8   rR   zSmolVLMSimpleMLP.__init__$  sT   ø€ Ü‰ÑÔØ×)Ñ)×5Ñ5¸×9LÑ9LÈaÑ9OÑPˆ
Ø×(Ñ(×4Ñ4ˆÜ—I‘I˜j¨+¸EÔBˆ�	r:   c                 ó$   — | j                  |«      S rÃ   )r  )r6   Úxs     r8   r‡   zSmolVLMSimpleMLP.forward*  s   € Ø�y‰y˜‹|Ðr:   )r;   r<   r=   rR   r‡   rŒ   r�   s   @r8   r  r  #  s   ø„ ôCör:   r  c                   ó,   ‡ — e Zd Zˆ fd„Zdd„Zd„ Zˆ xZS )ÚSmolVLMConnectorc                 ód   •— t         ‰| �  «        |j                  | _        t        |«      | _        y rÃ   )rQ   rR   r  r  Úmodality_projectionr]   s     €r8   rR   zSmolVLMConnector.__init__/  s)   ø€ Ü‰ÑÔØ"×/Ñ/ˆÔÜ#3°FÓ#;ˆÕ r:   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   )rc   Úintrp   Úpermuter¸   )r6   r  r  ÚbszÚseqrT   ÚheightÚwidths           r8   Úpixel_shufflezSmolVLMConnector.pixel_shuffle4  sé   € ØŸf™f›hÑˆˆS�)Ü˜S #™X›Ð&ˆ�Ø�F‰F�3˜  yÓ1ˆØ�F‰F�3˜¤ E¨LÑ$8Ó 9¸9À|Ñ;SÓTˆØ�I‰I�a˜˜A˜qÓ!ˆØ�I‰I�cœ3˜u |Ñ3Ó4´c¸&À<Ñ:OÓ6PÐR[Ð_kÐmnÑ_nÑRoÓpˆØ�I‰I�a˜˜A˜qÓ!ˆØ�I‰I�cœ3˜s l°A¡oÑ6Ó7¸ÀlÐTUÁoÑ9VÓWˆØˆr:   c                 ó`   — | j                  || j                  «      }| j                  |«      }|S rÃ   )r&  r  r  )r6   r  s     r8   r‡   zSmolVLMConnector.forward?  s4   € Ø"×0Ñ0Ð1DÀd×FWÑFWÓXÐØ"×6Ñ6Ð7JÓKÐØ"Ð"r:   )r   )r;   r<   r=   rR   r&  r‡   rŒ   r�   s   @r8   r  r  .  s   ø„ ô<ó
	ö#r:   r  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)
        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**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        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)`) and 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 in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            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.
        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 [`CLIPImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
            [`CLIPImageProcessor`] for processing images).
        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.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        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.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
zOSmolVLM model consisting of a SIGLIP vision encoder and Llama3 language decoderc                    ó  ‡ — e Zd ZdZdefˆ fd„Zd„ Zd„ Zd„ Zd„ Z	de
j                  d	e
j                  d
e
j                  fd„Z ede«      	 	 	 	 	 	 	 	 	 	 	 	 	 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ˆ xZS )Ú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.
    r*   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ù   )rQ   rR   r*   r  Úpad_token_idr5   Ú
vocab_sizer÷   Ú_from_configr  Úvision_modelr  Ú	connectorr   Úfrom_configÚ
text_modelr   rU   rV   r  Úimage_seq_lenÚimage_token_idrµ   rü   Ú	post_initr]   s     €r8   rR   zSmolVLMModel.__init__™  sù   ø€ Ü‰Ñ˜Ô ØŸ;™;×2Ñ2×?Ñ?ˆÔØŸ+™+×1Ñ1×<Ñ<ˆŒä4×AÑAÀ&×BVÑBVÓWˆÔÜ)¨&Ó1ˆŒÜ#×/Ñ/°×0BÑ0BÓCˆŒä Ø×"Ñ"×-Ñ-°×1EÑ1E×1PÑ1PÑPÐUVÑVÐ[a×[nÑ[nÐpqÑ[qÑró
ˆÔð #Ÿk™k×8Ñ8ˆÔà&,×&8Ñ&8×&MÑ&MÐQdÑ&dˆÔ#à�‰Õr:   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   )ÚlenÚlistÚchildren)r7   Úget_lowest_modules    €r8   r:  zBSmolVLMModel.enable_input_require_grads.<locals>.get_lowest_moduleµ  s?   ø€ Ü”4˜Ÿ™Ó)Ó*Ó+¨qÒ0à�ñ )¬¨f¯o©oÓ.?Ó)@ÀÑ)CÓDÐDr:   c                 ó&   — |j                  d«       y ©NT©Úrequires_grad_©r7   ÚinputÚoutputs      r8   Úmake_inputs_require_gradszJSmolVLMModel.enable_input_require_grads.<locals>.make_inputs_require_grads½  ó   € Ø×!Ñ! $Õ'r:   N)r   Úregister_forward_hookÚ_text_require_grads_hookr.  Ú_vision_require_grads_hook)r6   rB  r:  s     @r8   Úenable_input_require_gradsz'SmolVLMModel.enable_input_require_grads«  sN   ø€ ô	Eò	(ð )-×(AÑ(AÓ(C×(YÑ(YÐZsÓ(tˆÔ%Ù*;¸D×<MÑ<MÓ*N×*dÑ*dØ%ó+
ˆÕ'r:   c                 ól   — | j                   j                  «        | j                  j                  «        y rÃ   ©rE  ÚremoverF  rÿ   s    r8   Údisable_input_require_gradsz(SmolVLMModel.disable_input_require_gradsÅ  ó&   € Ø×%Ñ%×,Ñ,Ô.Ø×'Ñ'×.Ñ.Õ0r:   c                 ó6   — | j                   j                  «       S rÃ   )r1  r   rÿ   s    r8   r   z!SmolVLMModel.get_input_embeddingsÉ  s   € Ø�‰×3Ñ3Ó5Ð5r:   c                 ó:   — | j                   j                  |«       y rÃ   )r1  r  r  s     r8   r  z!SmolVLMModel.set_input_embeddingsÌ  s   € Ø�‰×,Ñ,¨UÕ3r:   Ú	input_idsrð   r  c                 ó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 )	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.
        r   ©r–   r   zCAt least one sample has <image> tokens not divisible by patch_size.)r   r   )r�   Nrf   )rg   r3  rn   rj   Úallr¨   r	   r›   ÚpadÚcumsumÚ	unsqueezeÚ
zeros_likeÚwhere)r6   rO  rð   r  ru   rV   Ú
image_maskÚnum_image_tokensÚblocks_per_sampleÚoffsetsÚblock_offsetÚrow_cumÚ	chunk_idxÚ	local_idxÚ	block_idxÚimage_embedsÚmerged_embedss                    r8   Ú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:   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}   r"   r_   Úpixel_attention_maskÚ	use_cacher±   rà   rá   Úcache_positionra   c                 ó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   r   r&   )rf   r•   éýÿÿÿrQ  T)r   r   r   )rc   r—   rs   )Ú	dimensionrc   Ústep)rf   r•   r  r  )rO  rð   r  )	rð   r‘   r}   r"   re  r±   rà   rá   rf  c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrÃ   rG   rä   s     r8   rç   z'SmolVLMModel.forward.<locals>.<genexpr>u  s   è ø€ ÒU˜qÀqÁ}œÑUùrè   )rê   r"   r°   rë   r  )&r*   r±   rà   re  rì   r™   r1  rß   r¶   r·   rg   r¨   r   Úget_seq_lengthr   rr   rs   rp   Únumelrn   r  rž   rj   r  r¿   r  rV   Úunfoldr.  rê   r/  r—   rc  rï   r  r"   r°   rë   )r6   rO  r‘   r}   r"   rð   r_   rd  r  re  r±   rà   rá   rf  rt   r¹   ru   Úpast_seen_tokensÚ
num_imagesrW   r$  r%  Únb_values_per_imageÚreal_images_indsÚirV   Úpatches_subgridr`   r×   s                                r8   r‡   zSmolVLMModel.forwardñ  s  € ð8 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   rR   rG  rK  r   r  rj   Ú
LongTensorr‹   rc  r   ÚSMOLVLM_INPUTS_DOCSTRINGr   r   r‰   rŠ   r¿   r   r   r  r‡   rŒ   r�   s   @r8   r)  r)  �  s½  ø„ ñ
ð
˜}õ ò$
ò41ò6ò4ð Ø×)Ñ)ð Ø:?¿,¹,ð Ø]b×]iÑ]ió ñD +ð	ð 	!óð 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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)	ÚSmolVLMCausalLMOutputWithPasta¯  
    Base class for Idefics causal language model (or autoregressive) outputs.

    Args:
        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 (`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 (`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ˆ   ry  r   rj   r‰   r  rz  r"   r   r°   r   rë   r  rG   r:   r8   rx  rx  €  sœ   … ñð8 )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø*.€FˆH�U×&Ñ&Ñ'Ó.Ø9=€O�X˜d 5×#4Ñ#4Ñ5Ñ6Ó=Ø8<€M�8˜E %×"3Ñ"3Ñ4Ñ5Ó<Ø59€J�˜˜u×0Ñ0Ñ1Ñ2Ó9Ø>BÐ˜ %¨×(9Ñ(9Ñ":Ñ;ÔBr:   rx  z~The SmolVLM Model with a language modeling head. It is made up a SigLIP vision encoder, with a language modeling head on top. c            %       óT  ‡ — e Zd ZdZdgZˆ fd„Zd„ Zd„ Zd„ Zd„ Z	d„ Z
d	„ Z ee«       eee¬
«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 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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ef   f d„«       «       Z	 	 	 	 	 	 	 	 dˆ fd„	Zˆ fd„Zˆ xZS ) ÚSmolVLMForConditionalGenerationzy
    A subclass of Idefics3ForConditionalGeneration that uses SmolVLMModel
    instead of the default Idefics3Model.
    zlm_head.weightc                 óZ  •— t         ‰| �  |«       t        |«      | _        | j                  j
                  | _        t        j                  |j                  j                  |j                  j                  d¬«      | _        |j                  j                  | _
        | j                  «        y )NFr  )rQ   rR   r)  r   r*   r3  r	   r/   r  rS   r,  Úlm_headr4  r]   s     €r8   rR   z(SmolVLMForConditionalGeneration.__init__²  sz   ø€ Ü‰Ñ˜Ô Ü! &Ó)ˆŒ
Ø"Ÿk™k×8Ñ8ˆÔÜ—y‘y ×!3Ñ!3×!?Ñ!?À×ASÑAS×A^ÑA^ÐejÔkˆŒØ ×,Ñ,×7Ñ7ˆŒð 	�‰Õr:   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 r<  r=  r?  s      r8   rB  z]SmolVLMForConditionalGeneration.enable_input_require_grads.<locals>.make_inputs_require_gradsÂ  rC  r:   N)r   rD  rE  r   r.  rF  )r6   rB  s     r8   rG  z:SmolVLMForConditionalGeneration.enable_input_require_grads¼  sO   € ò	(ð )-×(AÑ(AÓ(C×(YÑ(YÐZsÓ(tˆÔ%Ø*.¯*©*×*AÑ*A×*VÑ*VÓ*X×*nÑ*nØ%ó+
ˆÕ'r:   c                 ól   — | j                   j                  «        | j                  j                  «        y rÃ   rI  rÿ   s    r8   rK  z;SmolVLMForConditionalGeneration.disable_input_require_gradsÊ  rL  r:   c                 óJ   — | j                   j                  j                  «       S rÃ   )r   r1  r   rÿ   s    r8   r   z4SmolVLMForConditionalGeneration.get_input_embeddingsÎ  s   € Ø�z‰z×$Ñ$×9Ñ9Ó;Ð;r:   c                 óN   — | j                   j                  j                  |«       y rÃ   )r   r1  r  r  s     r8   r  z4SmolVLMForConditionalGeneration.set_input_embeddingsÑ  s   € Ø�
‰
×Ñ×2Ñ2°5Õ9r:   c                 ó   — | j                   S rÃ   ©r~  rÿ   s    r8   Úget_output_embeddingsz5SmolVLMForConditionalGeneration.get_output_embeddingsÔ  s   € Ø�|‰|Ðr:   c                 ó   — || _         y rÃ   r…  )r6   Únew_embeddingss     r8   Úset_output_embeddingsz5SmolVLMForConditionalGeneration.set_output_embeddings×  s	   € Ø%ˆ�r:   )Úoutput_typer>   rO  r‘   r}   r"   rð   r_   rd  r  Úlabelsre  r±   rà   rf  rá   Úlogits_to_keepra   c                 ó"  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |||||||||
||||¬«      }|d   }t        |t        «      rt        | d«      n|}| j                  |dd…|dd…f   «      }d}|	��|j                  «       }|	j                  |j                  «      }	|�s|dd…|j                  d   dz
   d…f   j                  |j                  «      }|ddd…dd…f   |dk7     j                  «       }|	ddd…f   |dk7     j                  «       }n1|ddd…dd…f   j                  «       }|	ddd…f   j                  «       }t        «       } ||j                  d|j!                  d«      «      |j                  d«      «      }|s|f|dd z   }|�|f|z   S |S t#        |||j$                  |j&                  |j(                  |j*                  ¬«      S )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)
        ```N)rO  r‘   r}   r"   rð   r_   rd  r  re  r±   rà   rf  rá   r   r   .rf   )ry  rz  r"   r°   rë   r  )r*   r±   rà   rì   r   r.   r   Úslicer~  Úfloatrr   rs   rg   rž   r
   rp   rc   rx  r"   r°   rë   r  )r6   rO  r‘   r}   r"   rð   r_   rd  r  r‹  re  r±   rà   rf  rá   rŒ  r×   r°   Úslice_indicesrz  ry  Úshift_attention_maskÚshift_logitsÚshift_labelsÚloss_fctrA  s                             r8   r‡   z'SmolVLMForConditionalGeneration.forwardÚ  sO  € ðF 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð —*‘*ØØ)Ø%Ø+Ø'Ø%Ø!5Ø 3ØØ/Ø!5Ø)Ø#ð ó 
ˆð    ™
ˆä8BÀ>ÔSVÔ8Wœ˜~˜o¨tÔ4Ð]kˆØ—‘˜mªA¨}ºaÐ,?Ñ@ÓAˆàˆØÑà—\‘\“^ˆFØ—Y‘Y˜vŸ}™}Ó-ˆFàÐ)ð (6²a¸6¿<¹<È¹?ÈQÑ;NÐ9OÑ9QÐ6QÑ'R×'UÑ'UÐV\×VcÑVcÓ'dÐ$Ø% c¨3¨B¨3² kÑ2Ð3GÈ1Ñ3LÑM×XÑXÓZ�Ø% c¨1©2 g™Ð/CÀqÑ/HÑI×TÑTÓV‘à% c¨3¨B¨3² kÑ2×=Ñ=Ó?�Ø% c¨1©2 g™×9Ñ9Ó;�ä'Ó)ˆHÙ˜L×-Ñ-¨b°,×2CÑ2CÀBÓ2GÓHÈ,×J[ÑJ[Ð\^ÓJ_Ó`ˆDáØ�Y ¨¨ Ñ,ˆFØ'+Ð'7�D�7˜VÑ#ÐC¸VÐCä,ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø '× ;Ñ ;ô
ð 	
r:   c
                 óp   •— t        ‰| �  |f||||||||	dœ|
¤Ž}|�|d   dk(  r||d<   |�
d |d<   d |d<   |S )N)r"   r‘   rð   rf  r_   rd  r  rŒ  r   rO  r_   rd  )rQ   Úprepare_inputs_for_generation)r6   rO  r"   r‘   rð   rf  r_   rd  r  rŒ  rŸ   Úmodel_inputsr^   s               €r8   r–  z=SmolVLMForConditionalGeneration.prepare_inputs_for_generationY  s}   ø€ ô  ‘wÑ<Øð
à+Ø)Ø'Ø)Ø%Ø!5Ø 3Ø)ñ
ð ñ
ˆð Ð$¨¸Ñ):¸aÒ)?Ø(1ˆL˜Ñ%àÐ*Ø+/ˆL˜Ñ(Ø37ˆLÐ/Ñ0àÐr:   c                 óL   •— t        ‰| �  d|||dœ|¤Ž}|j                  |d<   |S )N)r×   Úmodel_kwargsÚis_encoder_decoderr  rG   )rQ   Ú#_update_model_kwargs_for_generationr  )r6   r×   r™  rš  rŸ   r^   s        €r8   r›  zCSmolVLMForConditionalGeneration._update_model_kwargs_for_generation�  sC   ø€ Ü‘wÑBð 
ØØ%Ø1ñ
ð ñ	
ˆð /6×.IÑ.IˆÐ*Ñ+ØÐr:   )NNNNNNNNNNNNNNr   )NNNNNNNN) r;   r<   r=   rˆ   Ú_tied_weights_keysrR   rG  rK  r   r  r†  r‰  r   rv  r   rx  Ú_CONFIG_FOR_DOCr   rj   ru  r‹   r   r‰   rŠ   r¿   r   r   r   r‡   r–  r›  rŒ   r�   s   @r8   r|  r|  ¦  s  ø„ ñ
ð
 +Ð+Ðôò
ò1ò<ò:òò&ñ +Ð+CÓDÙÐ+HÐWfÔgð 15Ø15Ø37Ø=AØ59Ø48Ø;?Ø;?Ø-1Ø$(Ø,0Ø/3Ø59Ø&*Ø34ñ!{
à˜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ð{
ð ! ×!1Ñ!1Ñ2ð{
ð ˜d‘^ð{
ð  ˜c 5§<¡<Ð/Ñ0ð!{
ð" 
ˆuÐ3Ð3Ñ	4ò#{
ó hó Eð{
ð@ ØØØØØ!Ø Øõ&÷P	ð 	r:   r|  )r|  r   r)  r÷   )r&   )=Údataclassesr   Útypingr   r   r   r   r   rj   r	   Útorch.nnr
   Úactivationsr   Úcache_utilsr   Ú
generationr   Úmodeling_attn_mask_utilsr   Úmodeling_outputsr   r   Úmodeling_utilsr   r   Úutilsr   r   r   r   Úautor   Úconfiguration_smolvlmr   r   Ú
get_loggerr;   r¶   r�  ÚSMOLVLM_START_DOCSTRINGr   ÚModulerI   r‹   r�  r¢   r    rÁ   rË   rÙ   ÚSMOLVLM_VISION_START_DOCSTRINGr÷   r  r  r  rv  r)  rx  r|  Ú__all__rG   r:   r8   ú<module>r¯     s?  ðõ, "ß 9Õ 9ã Ý Ý %å !Ý 'Ý )Ý Bß <ß F÷ó õ ß Eð 
ˆ×	Ñ	˜HÓ	%€à!€ðÐ ñ" Ø[Øóô?˜_ó ?ó	ð?ô>7˜bŸi™iô 7ðB ñ%Ø�I‰Ið%à�<‰<ð%ð 
�‰ð%ð �<‰<ð	%ð
 ˜UŸ\™\Ñ*ð%ð ð%ð ó%ô.F)˜RŸY™Yô F)ôR�r—y‘yô ô-˜"Ÿ)™)ô -ô`U
�R—Y‘Yô U
ðp"Ð ñ" ØJØ"óôM
Ð5ó M
ó	ðM
ð` ô#C [ó #Có ð#CôL�r—y‘yô ô#�r—y‘yô #ð.GÐ ñT ØYØóôj
Ð)ó j
ó	ðj
ðZ ô"C Kó "Có ð"CñJ ð IØóô`Ð&<¸oó `ó	ð`òF t�r:   