
    Ph                     `   d dl Zd dlmZ d dl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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# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z*  ed       G d de
jV                               Z,	 dDde
jV                  dejZ                  dejZ                  dejZ                  deejZ                     de.de.fdZ/ G d de
jV                        Z0e e!d !       G d" d#e                    Z1 G d$ d%e
jV                        Z2 G d& d'e
jV                        Z3 G d( d)e
jV                        Z4e
jj                  e,d*Z6 G d+ d,e      Z7 G d- d.e
jV                        Z8e! G d/ d0e             Z9e! G d1 d2e9             Z:e! G d3 d4e             Z; G d5 d6e
jV                        Z<e e!d7!       G d8 d9e                    Z= e!d:!       G d; d<e;             Z>e e!d=!       G d> d?e                    Z? e!d@!       G dA dBe;e             Z@g dCZAy)E    N)	dataclass)CallableOptionalUnion   )ACT2FN)Cache)GenerationMixin)use_kernel_forward_from_hub)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPastBaseModelOutputWithPooling)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tuple	torch_int)check_model_inputs   )	AutoModel   )InternVLConfigInternVLVisionConfigRMSNormc                   ,     e Zd Zd fd	Zd Zd Z xZS )InternVLVisionRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)zD
        InternVLVisionRMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      h/var/www/html/saasai/venv/lib/python3.12/site-packages/transformers/models/internvl/modeling_internvl.pyr#   zInternVLVisionRMSNorm.__init__.   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr   T)keepdim)	dtypetor&   float32powmeanrsqrtr)   r(   )r*   hidden_statesinput_dtypevariances       r.   forwardzInternVLVisionRMSNorm.forward6   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r/   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler(   shaper)   r*   s    r.   
extra_reprz InternVLVisionRMSNorm.extra_repr=   s*    ))*+6$2G2G1HIIr/   )gư>)__name__
__module____qualname__r#   r<   rA   __classcell__r-   s   @r.   r    r    ,   s    $;Jr/   r    modulequerykeyvalueattention_maskscalingdropoutc                    |}|}	t        j                  ||j                  dd            |z  }
|#|d d d d d d d |j                  d   f   }|
|z   }
t        j
                  j                  |
d      }
t        j
                  j                  |
|| j                        }
t        j                  |
|	      }|j                  dd      j                         }||
fS )Nr   r   r1   dim)ptrainingr   )
r&   matmul	transposer?   r$   
functionalsoftmaxrM   rS   
contiguous)rG   rH   rI   rJ   rK   rL   rM   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r.   eager_attention_forwardr_   A   s     JL<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1 ==((2(>L==((6??([L,,|\:K''1-88:K$$r/   c                   t     e Zd ZdZdef fdZ	 ddej                  deej                     de	e
   fdZ xZS )	InternVLVisionAttentionz+Attention Class for InternVL Vision Encoderconfigc                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        |j                  | _
        |j                  }|j                  }d| _        t        j                  | j                  | j                  | j                  z  |j                         | _        t        j                  | j                  | j                  | j                  z  |j                         | _        t        j                  | j                  | j                  | j                  z  |j                         | _        t        j                  | j                  | j                        | _        |dkD  rt        j*                  |      nt        j,                         | _        |rt/        | j                        nt        j,                         | _        |rt/        | j                        | _        y t        j,                         | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      Fbiasr   )r"   r#   rb   r+   	embed_dimnum_attention_heads	num_headshead_dim
ValueErrorscaleattention_dropoutprojection_dropoutuse_qk_norm	is_causalr$   Linearattention_biasq_projk_projv_projprojection_layerDropoutIdentityr    q_normk_norm)r*   rb   proj_dropoutqk_normr-   s       r.   r#   z InternVLVisionAttention.__init___   s   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
!'!9!900$$ ii0NU[UjUjkii0NU[UjUjkii0NU[UjUjk "		$..$.. I>JQ>N"**\":TVT_T_Ta?F+DNN;BKKM?F+DNN;BKKMr/   r9   rK   rY   c                    |j                         \  }}}| j                  |      }| 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  rt        | j                  j                     }
 |
| |||	|f| j                  sdn| j                   | j"                  dd|\  }}|j                  ||| j$                        }| j'                  |      }| j)                  |      }||fS )Nr   r   eager        F)rM   rL   ro   )sizerr   rs   rt   rx   ry   reshaperh   ri   rU   viewr_   rb   _attn_implementationr   rS   rl   rk   rf   ru   rm   )r*   r9   rK   rY   
batch_sizeseq_len_query_statesrZ   r[   attention_interfacer^   r\   outputs                 r.   r<   zInternVLVisionAttention.forward{   s    "/!3!3!5
GQ{{=1[[/
{{=1{{<0[[,
#++JQUQ^Q^_iijkmno''
GT^^T]][eefgijk
#((Wdnndmm\ffghjkl(?;;++w6"9$++:Z:Z"[$7
%
  $}}C$2H2HJJ
%
 
%
!\ "))*gt~~N&&{3((0|##r/   N)rB   rC   rD   __doc__r   r#   r&   Tensorr   r   r   r<   rE   rF   s   @r.   ra   ra   \   sN    5Z3 Z> 26'$||'$ !.'$ +,	'$r/   ra   z7
    Class for outputs of [`InternVLVisionModel`].
    )custom_introc                       e Zd ZdZy)$InternVLVisionModelOutputWithPoolingaF  
    pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
        Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
        *config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
        will be returned.
    N)rB   rC   rD   r    r/   r.   r   r      s    r/   r   c                   Z     e Zd ZdZ fdZdej                  dej                  fdZ xZS )InternVLVisionPatchEmbeddingsz
    This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
    `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
    Transformer.
    c                 ^   t         |           |j                  |j                  }}|j                  |j
                  }}|d   |d   z  |d   |d   z  z  }|d   |d   z  |d   |d   z  f}|| _        || _        || _        || _        || _        t        j                  ||||      | _
        y )Nr   r   )kernel_sizestride)r"   r#   
image_size
patch_sizenum_channelsr+   num_patchespatch_shaper$   Conv2d
projection)	r*   rb   r   r   r   r+   r   r   r-   s	           r.   r#   z&InternVLVisionPatchEmbeddings.__init__   s    !'!2!2F4E4EJ
$*$7$79K9Kk!!}
15*Q-:VW=:XY!!}
15z!}
ST7UV$$(&&))L+:^hir/   pixel_valuesreturnc                    |j                   \  }}}}|| j                  k7  rt        d      | j                  |      }|j                   d   |j                   d   }}|j	                  d      j                  dd      }|||ffS )NzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.r   r   r   )r?   r   rj   r   flattenrU   )	r*   r   r   r   heightwidth
embeddingspatch_heightpatch_widths	            r.   r<   z%InternVLVisionPatchEmbeddings.forward   s    2>2D2D/
L&%4,,,w  __\2
$.$4$4Q$79I9I!9Lk''*44Q:
L+666r/   )	rB   rC   rD   r   r#   r&   r   r<   rE   rF   s   @r.   r   r      s)    j7ELL 7U\\ 7r/   r   c                        e Zd ZdZdeddf fdZdej                  dededej                  fd	Z		 dd
ej                  de
ej                     dej                  fdZ xZS )InternVLVisionEmbeddingszc
    Construct the CLS token, position and patch embeddings. Optionally, also the mask token.

    rb   r   Nc                 2   t         |           t        j                  t	        j
                  dd|j                              | _        |j                  r:t        j                  t	        j
                  dd|j                              | _	        nd | _	        t        |      | _        |j                  | _        t        |j                  t        j                   j"                        r|j                  n|j                  |j                  f| _        | j                  j$                  }|j&                  r=t        j                  t	        j
                  d|dz   |j                              | _        nd | _        t        j*                  |j,                        | _        y )Nr   )r"   r#   r$   r%   r&   zerosr+   	cls_tokenuse_mask_token
mask_tokenr   patch_embeddingsr   
isinstancer   collectionsabcIterabler    use_absolute_position_embeddingsposition_embeddingsrv   hidden_dropout_probrM   )r*   rb   r   r-   s      r.   r#   z!InternVLVisionEmbeddings.__init__   s$   ekk!Q8J8J&KL   ll5;;q!V=O=O+PQDO"DO =f E ++ &++[__-E-EF ##V%6%67 	
 ++7722')||EKK;QR?TZTfTf4g'hD$'+D$zz&"<"<=r/   r   r   r   c                    |j                   d   dz
  }| j                  j                   d   dz
  }t        j                  j	                         s||k(  r||k(  r| j                  S | j                  ddddf   }| j                  ddddf   }|j                   d   }|| j
                  d   z  }	|| j
                  d   z  }
t        |dz        }|j                  d|||      }|j                  dddd      }t        j                  j                  ||	|
fdd	
      }|j                  dddd      j                  dd|      }t        j                  ||fd      S )a   
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   Nr1   r         ?r   r   bicubicF)r   modealign_cornersrP   )r?   r   r&   jit
is_tracingr   r   r   permuter$   rV   interpolater   cat)r*   r   r   r   r   num_positionsclass_pos_embedpatch_pos_embedrQ   
new_height	new_widthsqrt_num_positionss               r.   interpolate_pos_encodingz1InternVLVisionEmbeddings.interpolate_pos_encoding   sj    !&&q)A-0066q9A= yy##%+*F6UZ?+++221bqb59221ab59r"tq11
T__Q//	&}c'9:)11!5GI[]`a)11!Q1=--33i(	 4 
 *11!Q1=BB1b#Nyy/?;CCr/   r   bool_masked_posc                    |j                   \  }}}}| j                  |      \  }\  }}|j                         \  }	}
}|K| j                  j	                  |	|
d      }|j                  d      j                  |      }|d|z
  z  ||z  z   }| j                  j	                  |	dd      }t        j                  ||fd      }| j                  || j                  |||      z   }| j                  |      }|||ffS )Nr1   r   rP   )r?   r   r   r   expand	unsqueezetype_asr   r&   r   r   r   rM   )r*   r   r   r   r   r   r   r   r   r   r   mask_tokensw
cls_tokenss                 r.   r<   z InternVLVisionEmbeddings.forward  s   
 +001fe262G2G2U/
/\;!+!2
GQ&//00WbIK))"-55kBA#q1u-a?J^^**:r2>
YY
J7Q?
##/#d&C&CJPVX]&^^J\\*-
L+666r/   r   )rB   rC   rD   r   r   r#   r&   r   intr   r   
BoolTensorr<   rE   rF   s   @r.   r   r      s    
>3 > >,&D5<< &D &DUX &D]b]i]i &DV 7;7ll7 "%"2"237 
	7r/   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )InternVLVisionMLPc                    t         |           || _        t        |j                     | _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        y r   )r"   r#   rb   r   
hidden_actactivation_fnr$   rp   r+   intermediate_sizefc1fc2r*   rb   r-   s     r.   r#   zInternVLVisionMLP.__init__9  sd    #F$5$5699V//1I1IJ99V55v7I7IJr/   r9   r   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   )r*   r9   s     r.   r<   zInternVLVisionMLP.forward@  s4    /**=9/r/   )rB   rC   rD   r#   r&   r   r<   rE   rF   s   @r.   r   r   8  s$    KU\\ ell r/   r   )
layer_normrms_normc                        e Zd ZdZdeddf fdZdej                  dee	ej                     e	ej                  ej                  f   f   fdZ
 xZS )InternVLVisionLayerz?This corresponds to the Block class in the timm implementation.rb   r   Nc                    t         |           |j                  | _        d| _        t	        |      | _        t        |      | _        t        |j                     |j                  |j                        | _        t        |j                     |j                  |j                        | _        |j                  }t        j                   |t#        j$                  |j                        z  d      | _        t        j                   |t#        j$                  |j                        z  d      | _        t        j*                  |j,                        | _        y )Nr   r,   T)requires_grad)r"   r#   chunk_size_feed_forwardseq_len_dimra   	attentionr   mlpNORM2FN	norm_typer+   layer_norm_epslayernorm_beforelayernorm_afterlayer_scale_init_valuer$   r%   r&   r'   lambda_1lambda_2rv   r   rM   )r*   rb   init_valuesr-   s      r.   r#   zInternVLVisionLayer.__init__M  s    '-'E'E$08$V, '(8(8 9&:L:LRXRgRg h&v'7'789K9KQWQfQfg33[5::f>P>P3Q%Qaef[5::f>P>P3Q%Qaefzz&"<"<=r/   r9   c                    | j                  | j                  |            \  }}| j                  |z  }||z   }| j                  |      }| j	                  |      }| j                  |      }| j                  | j                  |z  }||z   }|S r   )r   r   r   r   r   rM   r   )r*   r9   attention_outputr   layer_outputs        r.   r<   zInternVLVisionLayer.forward\  s     #nn!!-0
!  ==+;; )=8 ++M:xx-||L1==$==<7L $m3r/   )rB   rC   rD   r   r   r#   r&   r   r   r>   r<   rE   rF   s   @r.   r   r   J  sZ    I>3 > >|| 
uU\\"E%,,*D$EE	Fr/   r   c                   `     e Zd Zdeddf fdZedej                  dee	e
f   fd       Z xZS )InternVLVisionEncoderrb   r   Nc                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
r"   r#   rb   r$   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)r*   rb   ir-   s      r.   r#   zInternVLVisionEncoder.__init__y  sU    ]]vOgOgIh#iIhA$7$?Ih#ij
&+# $js   A#r9   c                 L    | j                   D ]
  } ||      } t        |      S )N)last_hidden_state)r   r   )r*   r9   layer_modules      r.   r<   zInternVLVisionEncoder.forward  s.    
 !JJL(7M ' +
 	
r/   )rB   rC   rD   r   r#   r   r&   r   r   r>   r   r<   rE   rF   s   @r.   r   r   x  sK    ,3 , , 	
||	
 
uo%	&	
 	
r/   r   c                   V     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eedZ fdZ xZS )InternVLVisionPreTrainedModelrb   internvl_visionr   Tr   )r9   
attentionsc                 V   t         |   |       t        |t              r|j                  j
                  j                          |j                  $|j                  j
                  j                          |j                  %|j                  j
                  j                          yyt        |t              rs|j                  j
                  j                  | j                  j                         |j                  j
                  j                  | j                  j                         yy)zInitialize the weightsN)r"   _init_weightsr   r   r   datazero_r   r   r   r   fill_rb   r   r   )r*   rG   r-   s     r.   r  z+InternVLVisionPreTrainedModel._init_weights  s    f%f67!!'')  ,!!&&,,.))5**//557 6 34OO  &&t{{'I'IJOO  &&t{{'I'IJ 5r/   )rB   rC   rD   r   __annotations__base_model_prefixmain_input_namesupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backendr   ra   _can_record_outputsr  rE   rF   s   @r.   r   r     sV      )$O&*#./N"& --
K Kr/   r   c                        e Zd Zdeddf fdZd Zee	 d	dej                  de
ej                     deeef   fd              Z xZS )
InternVLVisionModelrb   r   Nc                 2   t         |   |       || _        t        |      | _        t        |      | _        |j                  rt        j                         n*t        j                  |j                  |j                        | _        | j                          y )Nr   )r"   r#   rb   r   r   r   encoderuse_mean_poolingr$   rw   	LayerNormr+   r   	layernorm	post_initr   s     r.   r#   zInternVLVisionModel.__init__  so     26:,V4 $44BKKM",,vGYGY_e_t_t:u 	
 	r/   c                 .    | j                   j                  S r   )r   r   r@   s    r.   get_input_embeddingsz(InternVLVisionModel.get_input_embeddings  s    ///r/   r   r   c                     | j                  ||      \  }}| j                  |      }|d   }| j                  |      }t        ||j                  |j
                        S )z
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
        )r   r   )r   r9   r   )r   r  r  r   r9   r   )r*   r   r   embedding_outputr   encoder_outputssequence_outputs          r.   r<   zInternVLVisionModel.forward  se     #oolOo\!,,'78)!,..93-)77&11
 	
r/   r   )rB   rC   rD   r   r#   r  r   r   r&   r   r   r   r   r>   r   r<   rE   rF   s   @r.   r  r    ss    3  0  7;
ll
 "%"2"23
 
u::	;	
  
r/   r  c                   8    e Zd ZU eed<   dZdZdZdZdZ	dZ
dZdZy)InternVLPreTrainedModelrb    Tpast_key_valuesN)rB   rC   rD   r   r  r  r  _skip_keys_device_placementr  r
  _can_compile_fullgraphr  r  r   r/   r.   r  r    s7    &*#"3N!"&r/   r  c                   *     e Zd Zdef fdZd Z xZS )InternVLMultiModalProjectorrb   c                 *   t         |           t        j                  |j                  j
                  t        d|j                  z        dz  z        | _        t        j                  |j                  j
                  t        d|j                  z        dz  z  |j                  j
                        | _        t        |j                     | _        t        j                  |j                  j
                  |j                  j
                        | _        y )Nr   r   )r"   r#   r$   r  vision_configr+   r   downsample_ratior   rp   text_configlinear_1r   projector_hidden_actactlinear_2r   s     r.   r#   z$InternVLMultiModalProjector.__init__  s    ,,v';';'G'G#aRXRiRiNiJjnoJo'op		  ,,s1v7N7N3N/OST/TTV\VhVhVtVt
 &556		&"4"4"@"@&BTBTB`B`ar/   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }|S r   )r   r)  r+  r,  )r*   image_featuresr9   s      r.   r<   z#InternVLMultiModalProjector.forward  s@    7m4/m4r/   )rB   rC   rD   r   r#   r<   rE   rF   s   @r.   r$  r$    s    b~ br/   r$  zM
    Base class for InternVL outputs, with hidden states and attentions.
    c                   :    e Zd ZU dZdZeej                     ed<   y)InternVLModelOutputWithPasta  
    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)	rB   rC   rD   r   r1  r   r&   FloatTensorr  r   r/   r.   r0  r0    s    	 8<%"3"34;r/   r0  zx
    The InternVL model which consists of a vision backbone and a language model, without a language modeling head.
    c                   .    e Zd ZddiZdef fdZd Zd Zd Zd Z		 	 dd	e
j                  d
eeeee   f      dee   fdZde
j$                  de
j                  de
j                  fdZee	 	 	 	 	 	 	 	 	 ddee
j$                     d	ee
j                     dee
j,                     dee
j$                     dee   dee
j                     d
eeeee   f      dee   dee
j$                     dee   deeef   fd              Zdde
j,                  defdZ xZS )InternVLModelzlanguage_model.modellanguage_modelrb   c                     t         |   |       t        j                  |j                        | _        t        |      | _        t        j                  |j                        | _	        | j                          y r   )r"   r#   r   from_configr&  vision_towerr$  multi_modal_projectorr(  r5  r  r   s     r.   r#   zInternVLModel.__init__  sY     %11&2F2FG%@%H"'33F4F4FGr/   c                 6    | j                   j                         S r   )r5  r  r@   s    r.   r  z"InternVLModel.get_input_embeddings  s    ""7799r/   c                 :    | j                   j                  |       y r   )r5  set_input_embeddingsr*   rJ   s     r.   r<  z"InternVLModel.set_input_embeddings  s    007r/   c                     || _         y r   r5  r*   decoders     r.   set_decoderzInternVLModel.set_decoder"  s
    %r/   c                     | j                   S r   r?  r@   s    r.   get_decoderzInternVLModel.get_decoder%  s    """r/   r   vision_feature_layervision_feature_select_strategyc                    ||n| j                   j                  }||n| j                   j                  }|j                  | j                        }| j                   j
                  }|dk(  r| j                  |      j                  }n| j                  |      j                  |   }|dk(  r|ddddddf   }|j                  d   }t        |dz        }|j                  d   }	|j                  |	||d      }| j                  ||	      }|j                  |	d|j                  d         }| j                  |      }|S )
a%  
        Obtains image last hidden states from the vision tower and apply multimodal projection.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
               The tensors corresponding to the input images.
            vision_feature_layer (`int` or `list[int]`):
                Layer index or list of layer indices to extract features from.
        Returns:
            vision_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`.
        N)r3   r1   )r   defaultr   r   r   )scale_factor)rb   rE  rF  r4   r3   r'  r8  r   vision_modelr9   r?   r   r   pixel_shuffler9  )
r*   r   rE  rF  rY   r'  vision_featureschannelsfeature_sizer   s
             r.   get_image_featuresz InternVLModel.get_image_features(  sX   & %9$D $++JjJj 	
 .9 +;; 	'
 $TZZ8;;772%"//\/J\\O"//\/JXXYmnO)Y6-aQh7O #((+8S=)$**1-
 *11*lLZ\] ,,_K[,\ *11*b/BWBWXZB[\ 44_Er/   	input_idsinputs_embedsr.  c                 P   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d      j                  |      j                  |j                        }|j                  d   |j                  d   z  }||   j                         |j                         k7  rt        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.
        )r3   devicer1   r   r   z6Image features and image tokens do not match: tokens: z, features )r  r&   tensorrb   image_token_idlongrS  allsumr   	expand_asr4   r?   numelrj   )r*   rP  rQ  r.  special_image_maskn_image_tokensn_image_featuress          r.   get_placeholder_maskz"InternVLModel.get_placeholder_mask^  s    !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H+//1/99"=GGVYYZgZnZno)//2^5I5I!5LL+,2248L8L8NNHHXXcdtcuv  "!r/   rK   position_idsr   cache_positionrY   r   c
           	      8   ||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt        d      | | j	                         |      }|`| j                  |||      }|j                  |j                  |j                        }| j                  |||      }|j                  ||      } | j                  d|||||	d|
}t        |j                  |j                  |j                  |j                   |      S d       S )Nz:You must specify exactly one of input_ids or inputs_embedsr   rE  rF  )rQ  r.  )rK   r_  r   rQ  r`  )r   r   r9   r   r1  r   )rb   rE  rF  rj   r  rO  r4   rS  r3   r^  masked_scatterr5  r0  r   r   r9   r   )r*   rP  r   rK   r_  r   rQ  rE  rF  r`  rY   r.  r[  outputss                 r.   r<   zInternVLModel.forwardv  sj     %9$D $++JjJj 	
 .9 +;; 	' -t";<YZZ 7D557	BM#!44)%9/M 5 N
 ,..}/C/C]EXEXYN!%!:!:~ "; " *889K^\M%$%% 
)%+')
 
 +%77#33!//))2>2J
 	

 QU
 	
r/   rL  rI  c           
         |j                         \  }}}}||z  dk7  s||z  dk7  rt        d      |j                  ||t        ||z        t        ||z              }|j	                  dddd      j                         }|j                  |t        ||z        t        ||z        t        ||dz  z              }|j	                  dddd      j                         }|S )a&  Perform pixel shuffle downsampling on vision features.

        Args:
            vision_features (`torch.Tensor`):
                Input tensor of shape (batch_size, width, height, channels).
            scale_factor (`float`, *optional*, defaults to `0.5`):
                Factor by which to downsample. Default is 0.5, which halves the dimensions.

        Returns:
            vision_features (`torch.Tensor`):
                Downsampled tensor of shape (batch_size, height*scale_factor, width*scale_factor, channels/(scale_factor^2)).
        r   zKHeight and width must be divisible by scale_factor for proper downsampling.r   r   r   )r   rj   r   r   r   rX   )r*   rL  rI  r   r   r   rM  s          r.   rK  zInternVLModel.pixel_shuffle  s     />.B.B.D+
E68L A%)=)Bjkk *..s6L#893x,?V;W
 *11!Q1=HHJ *..F\12C8L4MsS[_kmn_nSoOp

 *11!Q1=HHJr/   NN)	NNNNNNNNN)r   ) rB   rC   rD   _checkpoint_conversion_mappingr   r#   r  r<  rB  rD  r&   r2  r   r   r   liststrrO  
LongTensorr^  r   r   r   r	   r   r   r>   r0  r<   floatrK  rE   rF   s   @r.   r4  r4    s    '=>N%O"~ :8&# AE8<	4''4 'uS$s)^'<=4 )1	4l"))":?:K:K"]b]n]n"0  15481537+/59@D8<597
E,,-7
 u0017
 !.	7

 u//07
 "%7
   1 127
 'uS$s)^'<=7
 )17
 !!1!127
 +,7
 
u11	27
  7
r!U\\ ! !r/   r4  zT
    Base class for InternVL causal language model (or autoregressive) outputs.
    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d<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   y)	InternVLCausalLMOutputWithPasta4  
    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logitsr   r9   r   r1  )rB   rC   rD   r   rn  r   r&   r2  r  ro  r   r	   r9   r>   r   r1  r   r/   r.   rm  rm    s     )-D(5$$
%,*.FHU&&'.'+OXe_+8<M8E%"3"345<59Ju001297;%"3"34;r/   rm  zV
    The INTERNVL model which consists of a vision backbone and a language model.
    c            !           e Zd ZdddddZdgZdef fdZd	 Zd
 Zde	j                  fdZd Zd Z	 	 d"dej                  deeeee   f      dee   fdZed        Zed        Zed        Zee	 	 	 	 	 	 	 	 	 	 	 	 d#deej8                     deej                     deej:                     deej8                     dee   deej                     deeeee   f      dee   deej8                     deej8                     deeej:                  f   deej:                     dee    dee!e"f   fd               Z#	 	 	 	 	 	 d$ fd!	Z$ xZ%S )% InternVLForConditionalGenerationzmodel.language_modelzmodel.vision_towerzmodel.multi_modal_projectorlm_head)z^language_model.modelz^vision_towerz^multi_modal_projectorz^language_model.lm_headzlm_head.weightrb   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y )NFrd   )r"   r#   r4  modelr$   rp   r(  r+   
vocab_sizerr  r  r   s     r.   r#   z)InternVLForConditionalGeneration.__init__  sS     "6*
yy!3!3!?!?ASASA^A^ejkr/   c                 6    | j                   j                         S r   )rt  r  r@   s    r.   r  z5InternVLForConditionalGeneration.get_input_embeddings  s    zz..00r/   c                 :    | j                   j                  |       y r   )rt  r<  r=  s     r.   r<  z5InternVLForConditionalGeneration.set_input_embeddings
  s    

''.r/   r   c                     | j                   S r   )rr  r@   s    r.   get_output_embeddingsz6InternVLForConditionalGeneration.get_output_embeddings  s    ||r/   c                 :    | j                   j                  |       y r   )rt  rB  r@  s     r.   rB  z,InternVLForConditionalGeneration.set_decoder  s    

w'r/   c                 6    | j                   j                         S r   )rt  rD  r@   s    r.   rD  z,InternVLForConditionalGeneration.get_decoder  s    zz%%''r/   r   rE  rF  c                 B     | j                   j                  d|||d|S )Nrb  r   )rt  rO  )r*   r   rE  rF  rY   s        r.   rO  z3InternVLForConditionalGeneration.get_image_features  s5     -tzz,, 
%!5+I
 	
 	
r/   c                 .    | j                   j                  S r   )rt  r5  r@   s    r.   r5  z/InternVLForConditionalGeneration.language_model%  s    zz(((r/   c                 .    | j                   j                  S r   )rt  r8  r@   s    r.   r8  z-InternVLForConditionalGeneration.vision_tower)  s    zz&&&r/   c                 .    | j                   j                  S r   )rt  r9  r@   s    r.   r9  z6InternVLForConditionalGeneration.multi_modal_projector-  s    zz///r/   rP  rK   r_  r   rQ  labelsr`  logits_to_keepimage_sizesrY   c                    ||n| j                   j                  }||n| j                   j                  } | j                  d|||||||||
|d
|}|d   }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }d}|	4 | j                  d||	| j                   j                  j                  d|}t        |||j                  |j                  |j                  |j                        S )ac  
        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, AutoModelForImageTextToText

        >>> torch_device = "cuda"
        >>> processor = AutoProcessor.from_pretrained("OpenGVLab/InternVL3-1B-hf")
        >>> model = AutoModelForImageTextToText.from_pretrained(
        ...     "OpenGVLab/InternVL3-1B-hf", dtype=torch.bfloat16, device_map=torch_device
        ... )

        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {
        ...                 "type": "image",
        ...                 "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg",
        ...             },
        ...             {
        ...                 "type": "image",
        ...                 "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg",
        ...             },
        ...             {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"},
        ...         ],
        ...     },
        ... ]

        >>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(torch_device)
        >>> generate_ids = model.generate(**inputs, max_new_tokens=200)
        >>> print(processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
        The images depict the Statue of Liberty and the Golden Gate Bridge.
        ```N)
rP  r   rK   r_  r   rQ  rE  rF  r`  r  r   )ro  r  ru  )rn  ro  r   r9   r   r1  r   )rb   rE  rF  rt  r   r   slicerr  loss_functionr(  ru  rm  r   r9   r   r1  )r*   rP  r   rK   r_  r   rQ  rE  rF  r  r`  r  r  rY   rd  r9   slice_indicesro  rn  s                      r.   r<   z(InternVLForConditionalGeneration.forward1  s7   l %9$D $++JjJj 	
 .9 +;; 	' $** 
%)%+'!5+I)#
 
  
8B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD .#33!//)) ' ; ;
 	
r/   c           	      N    t        
|   |f|||||d|}	|d   dk(  r||	d<   |	S )N)r   rQ  rK   r`  r  r   r   )r"   prepare_inputs_for_generation)r*   rP  r   rQ  r   rK   r`  r  rY   model_inputsr-   s             r.   r  z>InternVLForConditionalGeneration.prepare_inputs_for_generation  sV     w<
+')))
 
 !! ,8L(r/   rf  )NNNNNNNNNNr   N)NNNNNN)&rB   rC   rD   rg  _tied_weights_keysr   r#   r  r<  r$   Modulery  rB  rD  r&   r2  r   r   r   rh  ri  rO  propertyr5  r8  r9  r   r   rj  r   r	   r   r   r>   rm  r<   r  rE   rF   s   @r.   rq  rq    s_    "8-"?#,	&" ++~ 1/ryy (( AE8<	
''
 'uS$s)^'<=
 )1	
 ) ) ' ' 0 0  15481537+/59@D8<-15934.2\
E,,-\
 u001\
 !.	\

 u//0\
 "%\
   1 12\
 'uS$s)^'<=\
 )1\
 ))*\
 !!1!12\
 c5<</0\
 ell+\
 +,\
 
u44	5\
  \
B  r/   rq  )r   r  r  r4  rq  )r~   )Bcollections.abcr   dataclassesr   typingr   r   r   r&   torch.nnr$   activationsr   cache_utilsr	   
generationr
   integrationsr   modeling_layersr   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   autor   configuration_internvlr   r   r  r    r   rk  r_   ra   r   r   r   r   r  r   r   r   r   r  r  r$  r0  r4  rm  rq  __all__r   r/   r.   <module>r     s  .  ! , ,   !   ) 7 9 d d F & a a /  H Y'JBII J (J6 %II%<<% 
% <<	%
 U\\*% % %6F$bii F$R 
+E  !7BII !7L[7ryy [7|		  3H
I+4 +\
BII 
( KO K K< '
7 '
 '
T 'o ' '")) $ 
<"9 < < 
A+ A
AH 
<[ < <0 
u'> u
upr/   