
    rh6                    P   d dl Z d dlmZmZmZ d dlZd dlZd dlm	Z	 d dl
m	c mZ d dlZd dlmZ ddlmZ ddlmZmZ ddlmZ ddlmZ 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% ddl&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJ  e1j                  eL      ZM G d de      ZN G d de      ZO G d de9      ZP G d d e6      ZQ G d! d"e?      ZR G d# d$e;      ZS G d% d&e<      ZT G d' d(e	j                        ZV G d) d*e	j                        ZW G d+ d,eE      ZX G d- d.eF      ZY G d/ d0eB      ZZ G d1 d2eZ      Z[ G d3 d4eC      Z\d5 Z]dPd6Z^ G d7 d8e	j                        Z_ G d9 d:e5      Z` G d; d<e      Za G d= d>eA      Zb G d? d@eD      Zc G dA dBe@      Zd G dC dDe=      Ze G dE dFe>      Zf G dG dHeJ      Zg G dI dJe'      Zh G dK dLeI      Zi G dM dNeH      Zjg dOZky)Q    N)CallableOptionalUnion)	LayerNorm   )ACT2FN)CacheDynamicCache)PretrainedConfig)BatchFeature)
ImageInput)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPast)rope_config_validation)ALL_ATTENTION_FUNCTIONS)ImagesKwargsUnpack)PreTokenizedInput	TextInput)TransformersKwargsauto_docstringcan_return_tupleis_torchdynamo_compilinglogging)
VideoInput   )Glm4MLPGlm4RMSNormeager_attention_forward)Qwen2_5_VLConfig)Qwen2_5_VisionPatchEmbedQwen2_5_VisionRotaryEmbedding Qwen2_5_VLCausalLMOutputWithPast"Qwen2_5_VLForConditionalGenerationQwen2_5_VLMLPQwen2_5_VLModelQwen2_5_VLModelOutputWithPastQwen2_5_VLPreTrainedModelQwen2_5_VLRotaryEmbeddingQwen2_5_VLTextModelQwen2_5_VLVisionAttentionQwen2_5_VLVisionBlock)Qwen2_5_VLProcessorQwen2_5_VLProcessorKwargsQwen2_5_VLVideosProcessorKwargsc                   J     e Zd ZdZdZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Z xZS )Glm4vVisionConfiga  
    This is the configuration class to store the configuration of a [`Glm4vVisionModel`]. It is used to instantiate an Glm4vVisionModel
    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
    a similar configuration to that of
    GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).

    Args:
        hidden_size (`int`, *optional*, defaults to 1536):
            Dimensionality of the encoder layers and the pooler layer.
        depth (`int`, *optional*, defaults to 24):
            Number of layers (depth) in the model.
        attention_bias (`bool`, *optional*, defaults to `False`):
            Whether to add a bias to the queries, keys and values.
        intermediate_size (`int`, *optional*, defaults to 13696):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (`str` or `function`, *optional*, defaults to `"selu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            Dropout probability for attention weights.
        projection_dropout (`float`, *optional*, defaults to 0.0):
            Dropout probability for the projection layer.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        image_size (`int` or `list[int]`, *optional*, defaults to `[336, 336]`):
            The size (resolution) of each image.
        patch_size (`int`, *optional*, defaults to `14`):
            The size (resolution) of each patch.
        num_channels (`int`, *optional*, defaults to 3):
            The number of input channels.
        out_hidden_size (`int`, *optional*, defaults to 4096):
            The output hidden size of the vision model.
        rms_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        spatial_merge_size (`int`, *optional*, defaults to 2):
            The size used for merging spatial dimensions.
        temporal_patch_size (`int`, *optional*, defaults to 2):
            The size used for patches along the temporal dimension.
    Example:

    ```python
    >>> from transformers import Glm4vVisionConfig, Glm4vVisionModel

    >>> # Initializing a Glm4vVisionConfig GLM-4.1V-9B style configuration
    >>> configuration = Glm4vVisionConfig()

    >>> # Initializing a model (with random weights) from the GLM-4.1V-9B configuration
    >>> model = Glm4vVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```glm4vvision_configc                     t        |   di | || _        || _        || _        || _        || _        || _        |	| _        || _	        || _
        || _        || _        || _        |
| _        || _        || _        y )N )super__init__depthhidden_size
hidden_act	num_headsin_channels
image_size
patch_sizespatial_merge_sizetemporal_patch_sizeout_hidden_sizeintermediate_sizeinitializer_rangerms_norm_epsattention_biasattention_dropout)selfr:   r;   r<   rG   rH   r=   r>   r?   r@   rF   rA   rB   rC   rD   rE   kwargs	__class__s                    z/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/glm4v/modular_glm4v.pyr9   zGlm4vVisionConfig.__init__}   s    & 	"6"
&$"&$$"4#6 .!2!2(,!2    )   i   siluF           r   iP     h㈵>r         5  {Gz?)__name__
__module____qualname____doc__
model_typebase_config_keyr9   __classcell__rK   s   @rL   r3   r3   B   sN    5n J%O !#3 #3rM   r3   c                        e Zd ZdZdZdZdgZddddddd	Zd
gdgfddgdgfdgdgfdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Z	 xZ
S )Glm4vTextConfiga  
    This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
    GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of
    GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).

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

    Args:
        vocab_size (`int`, *optional*, defaults to 151552):
            Vocabulary size of the Glm4v model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`Glm4vModel`]
        hidden_size (`int`, *optional*, defaults to 4096):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 13696):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 40):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer encoder.
        num_key_value_heads (`int`, *optional*, defaults to 2):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
            by meanpooling all the original heads within that group. For more details checkout [this
            paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 32768):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether the model's input and output word embeddings should be tied.
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        rope_scaling (`Dict`, *optional*):
            Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
            and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
            accordingly.
            Expected contents:
                `rope_type` (`str`):
                    The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
                    'llama3'], with 'default' being the original RoPE implementation.
                `factor` (`float`, *optional*):
                    Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
                    most scaling types, a `factor` of x will enable the model to handle sequences of length x *
                    original maximum pre-trained length.
                `original_max_position_embeddings` (`int`, *optional*):
                    Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
                    pretraining.
                `attention_factor` (`float`, *optional*):
                    Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
                    computation. If unspecified, it defaults to value recommended by the implementation, using the
                    `factor` field to infer the suggested value.
        image_token_id (`int`, *optional*):
            Token index used as placeholder for image embeddings.
        video_token_id (`int`, *optional*):
            Token index used as placeholder for video embeddings.

    ```python
    >>> from transformers import Glm4vTextModel, Glm4vConfig

    >>> # Initializing a GLM-4.1V style configuration
    >>> configuration = Glm4vConfig()

    >>> # Initializing a model from the GLM-4.1V style configuration
    >>> model = Glm4vTextModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```
glm4v_texttext_configpast_key_valuescolwiserowwisecolwise_reprowwise_rep)zlayers.*.self_attn.q_projzlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzlayers.*.self_attn.o_projzlayers.*.mlp.gate_up_projzlayers.*.mlp.down_proj	input_idsinputs_embedshidden_statesattention_mask)embed_tokenslayersnormc                    || _         || _        || _        || _        || _        || _        ||}|| _        || _        |	| _        |
| _	        || _
        || _        || _        || _        | j                  *d| j                  v r| j                  d   | j                  d<   t        | dh       || _        || _        t#        | H  dd|i| y )Ntype	rope_typemrope_section)ignore_keystie_word_embeddingsr7   )
vocab_sizemax_position_embeddingsr;   rD   num_hidden_layersnum_attention_headsnum_key_value_headsr<   rE   rF   	use_cache
rope_thetarH   rope_scalingr   image_token_idvideo_token_idr8   r9   )rI   rv   r;   rD   rx   ry   rz   r<   rw   rE   rF   r{   ru   r|   rH   r}   r~   r   rJ   rK   s                      rL   r9   zGlm4vTextConfig.__init__  s    * %'>$&!2!2#6  &"5#6 $!2("$!2( (Vt7H7H-H-1->->v-FDk*t/1BC,,K-@KFKrM   )i P rU   rV   (       r   rO   i   rW   rS   TFg     @rP   NNN)rX   rY   rZ   r[   r\   r]   keys_to_ignore_at_inferencebase_model_tp_planbase_model_pp_planr9   r^   r_   s   @rL   ra   ra      s    Pd J#O#4"5 &/%.%.%.%2"/ &(9:#%568IJ!"_$56  %!%1L 1LrM   ra   c                   4     e Zd ZdZ	 	 	 	 	 	 	 	 d fd	Z xZS )Glm4vConfiga\  
    This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
    GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of
    GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).

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


    Args:
        text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Glm4vTextConfig`):
            The config object or dictionary of the text backbone.
        vision_config (`Union[PreTrainedConfig, dict]`,  *optional*, defaults to `Glm4vVisionConfig`):
            The config object or dictionary of the vision backbone.
        image_token_id (`int`, *optional*, defaults to 151343):
            The image token index to encode the image prompt.
        video_token_id (`int`, *optional*, defaults to 151344):
            The video token index to encode the image prompt.
        image_start_token_id (`int`, *optional*, defaults to 151339):
            The image start token index to encode the start of image.
        image_end_token_id (`int`, *optional*, defaults to 151340):
            The image end token index to encode the end of image.
        video_start_token_id (`int`, *optional*, defaults to 151341):
            The video start token index to encode the start of video.
        video_end_token_id (`int`, *optional*, defaults to 151342):
            The video end token index to encode the end of video.

    ```python
    >>> from transformers import Glm4vForConditionalGeneration, Glm4vConfig

    >>> # Initializing a GLM-4.1V style configuration
    >>> configuration = Glm4vConfig()

    >>> # Initializing a model from the GLM-4.1V style configuration
    >>> model = Glm4vForConditionalGeneration(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```c	                 Z    t         
|           || _        || _        || _        || _        y N)r8   r9   video_start_token_idvideo_end_token_idimage_start_token_idimage_end_token_id)rI   rc   r5   r~   r   r   r   r   r   rJ   rK   s             rL   r9   zGlm4vConfig.__init__f  s0     	$8!"4$8!"4rM   )NNi/O i0O i+O i,O i-O i.O )rX   rY   rZ   r[   r9   r^   r_   s   @rL   r   r   <  s-    'V #!#!5 5rM   r   c                       e Zd Zy)Glm4vRMSNormNrX   rY   rZ   r7   rM   rL   r   r   z      rM   r   c                   &     e Zd Zddef fdZ xZS )Glm4VisionMlpbiasc                 H    t         |   ||       |j                  | _        y r   )r8   r9   rC   rD   )rI   configr   rK   s      rL   r9   zGlm4VisionMlp.__init__  s     &!'!7!7rM   F)rX   rY   rZ   boolr9   r^   r_   s   @rL   r   r   ~  s    8T 8 8rM   r   c                       e Zd ZdeddfdZy)Glm4vVisionPatchEmbedr   returnNc                 ^   t        j                          |j                  | _        |j                  | _        |j                  | _        |j
                  | _        | j                  | j                  | j                  g}t        j                  | j                  | j                  ||      | _	        y )N)kernel_sizestride)
r#   r9   r@   rB   r>   r;   	embed_dimnnConv3dproj)rI   r   r   s      rL   r9   zGlm4vVisionPatchEmbed.__init__  s     ))+ ++#)#=#= !--++//$//RIId..K`kl	rM   )rX   rY   rZ   r3   r9   r7   rM   rL   r   r     s    m0 mT mrM   r   c                       e Zd Zy)Glm4vVisionRotaryEmbeddingNr   r7   rM   rL   r   r     r   rM   r   c                   n     e Zd Zd
dededededdf
 fdZdej                  dej                  fd	Z	 xZ
S )Glm4vVisionPatchMergerdimcontext_dimr<   r   r   Nc                 x   t         |           t        j                  |||      | _        t        |      | _        t        j                  |||      | _        t        j                  |||      | _        t        j                  |||      | _	        t        j                         | _        t        |   | _        y )Nr   )r8   r9   r   Linearr   r   post_projection_norm	gate_projup_proj	down_projGELUact1r   act_fn)rI   r   r   r<   r   rK   s        rL   r9   zGlm4vVisionPatchMerger.__init__  s    IIc3T2	$-cN!3$?yyk=;$?GGI	Z(rM   hidden_statec                     | j                  |      }| j                  | j                  |            }| j                  | j	                  | j                  |            | j                  |      z        S r   )r   r   r   r   r   r   r   )rI   r   s     rL   forwardzGlm4vVisionPatchMerger.forward  sY    yy.yy!:!:<!HI~~dkk$..*FG$,,WcJddeerM   r   )rX   rY   rZ   intstrr   r9   torchTensorr   r^   r_   s   @rL   r   r     sJ    )C )c )s )$ )[_ )fELL fU\\ frM   r   c                   D     e Zd Zdef fdZdej                  fdZ xZS )Glm4vVisionEmbeddingsr   c                    t         |           || _        |j                  | _        |j
                  | _        |j                  | _        | j
                  | j                  z  dz  | _        | j                  | _        t        j                  | j                  | j                        | _        | j                  dt        j                  | j                        j                  d      d       y )Nr   position_ids)rT   F)
persistent)r8   r9   r   r;   r   r?   r@   num_patchesnum_positionsr   	Embeddingposition_embeddingregister_bufferr   arangeexpandrI   r   rK   s     rL   r9   zGlm4vVisionEmbeddings.__init__  s    ++ ++ ++ OOt>1D!--"$,,t/A/A4>>"R^U\\$:L:L-M-T-TU\-]joprM   r   c           	         | j                   j                  }|j                  d   }|j                  d   }|j                  }	|j	                  |	      |j	                  |	      }}|dk(  r%t        j                  d||	|j                        }
nt        |t              r&t        j                  ||	t
        j                        }t        |t
        j                        s&t        j                  ||	t
        j                        }|j                  d   }t        |dz        }|j                  |||      j                  ddd      j!                  d      j	                  |	t
        j"                        }t        j$                  t'        t)        |            D cg c]  }||df   j+                  ||          c}      j	                  |	t
        j"                        }t        j$                  t'        t)        |            D cg c]  }||df   j+                  ||          c}      j	                  |	t
        j"                        }|j	                  |	t
        j"                        }|j	                  |	t
        j"                        }|dz   |z  dz  dz
  }|dz   |z  dz  dz
  }t        j,                  ||fd      j!                  d      j!                  d      }t/        j0                  ||dd	d
      }|j3                  d      j3                  d      j                  dd      }|j	                  |j                        j	                  |j                        }
||
z   }|S c c}w c c}w )a  
        Forward pass with integrated position encoding adaptation using 2D interpolation.

        Args:
            embeddings: Input embeddings tensor
            lengths (torch.Tensor): Sequence lengths for each image in the batch.
            image_shapes (torch.Tensor): Tensor of shape [batch_size, 3] representing the image shapes (t, h, w).
            h_coords (torch.Tensor): Tensor of shape [total_seq] representing the h coordinate for each patch.
            w_coords (torch.Tensor): Tensor of shape [total_seq] representing the w coordinate for each patch.

        Returns:
            torch.Tensor: Embeddings with adapted position encoding added.
        rT   r   devicedtypeg      ?r   r   r   bicubicFborder)modealign_cornerspadding_mode)r   weightshaper   tor   emptyr   
isinstancelisttensorlongr   r   viewpermute	unsqueezefloat32catrangelenrepeatstackFgrid_samplesqueeze)rI   
embeddingslengthsimage_shapesh_coordsw_coordspos_embed_weightr;   	total_seqr   adapted_pos_embedorig_size_sq	orig_sizepos_embed_2ditarget_htarget_wnorm_wnorm_hgridinterpolated_embed_fp32adapted_pos_embed_fp32s                         rL   r   zGlm4vVisionEmbeddings.forward  s     2299&,,Q/NN1%	!(( &[[0(++f2E( > %A{6QaQgQg h '4(,,wvUZZPlELL9$||LuzzZ ,11!4LL#-.I %%iKHAq!167	  yyQVWZ[bWcQd!eA,q!t"4";";GAJ"G!efiiU]] j H yyQVWZ[bWcQd!eA,q!t"4";";GAJ"G!efiiU]] j H
  {{&{FH{{&{FH#~1Q6:F#~1Q6:F ;;/R8BB1EOOPQRD '(mmd%V^'#
 &=%D%DQ%G%O%OPR%S%[%[\]_`%a" 6 9 9:J:P:P Q T TU_UfUf g  "33
7 "f "fs    M" M')	rX   rY   rZ   r3   r9   r   r   r   r^   r_   s   @rL   r   r     s'    
q0 
qGPUP\P\ GrM   r   c                   (     e Zd Zdeddf fdZ xZS )Glm4vVisionAttentionr   r   Nc                 "   t         |           |j                  | _        t        j                  |j
                  |j
                  dz  |j                        | _        t        j                  |j
                  |j
                  d      | _        y )Nr   r   F)	r8   r9   rH   r   r   r;   rG   qkvr   r   s     rL   r9   zGlm4vVisionAttention.__init__  sg    !'!9!999V//1C1Ca1GfNcNcdIIf00&2D2D5Q	rM   )rX   rY   rZ   r3   r9   r^   r_   s   @rL   r   r     s     R0 RT R RrM   r   c                         e Zd Zd fdZ xZS )Glm4vVisionBlockc                     t         |           t        |j                  |j                        | _        t        |j                  |j                        | _        t        |      | _        t        |d      | _
        y )NepsFr   )r8   r9   r   r;   rF   norm1norm2r   attnr   mlpr   s     rL   r9   zGlm4vVisionBlock.__init__  s\    !&"4"4&:M:MN
!&"4"4&:M:MN
(0	 e4rM   r   N)rX   rY   rZ   r9   r^   r_   s   @rL   r   r     s    5 5rM   r   c                       e Zd ZddgZy)Glm4vPreTrainedModelGlm4vTextDecoderLayerr   N)rX   rY   rZ   _no_split_modulesr7   rM   rL   r  r    s    02DErM   r  c                        e Zd ZU eed<   dgZd	 fdZd Zdej                  dej                  dej                  fdZ
 xZS )
Glm4vVisionModelr   r   r   c                 F   t         |   |       |j                  | _        |j                  | _        t	        |      | _        t        |      | _        |j                  |j                  z  }t        |dz        | _        t        j                  t        |j                        D cg c]  }t!        |       c}      | _        t%        |j&                  |j(                  |j*                        | _        t/        |j                  |j0                        | _        t        j4                  |j                  |j&                  |j                  |j                        | _        t/        |j                  |j0                        | _        d| _        | j=                          y c c}w )Nr   )r   r   r<   r   )r>   out_channelsr   r   F)r8   r9   rA   r@   r   r   r   patch_embedr;   r=   r   rotary_pos_embr   
ModuleListr   r:   r   blocksr   rC   rD   r<   mergerr   rF   post_conv_layernormConv2d
downsamplepost_layernormgradient_checkpointing	post_init)rI   r   head_dim_rK   s       rL   r9   zGlm4vVisionModel.__init__  sA    "(";"; ++/708%%)9)998QGmmuV\\GZ$[!%5f%=$[\,&&F4L4LY_YjYj
 $00B0BH[H[#\ ))**//11,,	
 +6+=+=6CVCVW&+# %\s   %Fc                    g }|D ]s  \  }}}t        j                  |      j                  d      j                  d|      }|j	                  || j
                  z  | j
                  || j
                  z  | j
                        }|j                  dddd      }|j                         }t        j                  |      j                  d      j                  |d      }|j	                  || j
                  z  | j
                  || j
                  z  | j
                        }|j                  dddd      }|j                         }|j                  t        j                  ||gd      j                  |d             v t        j                  |d      }|d d dd f   j                         }| j                  |      }	|	|   j                  d      }
|
|fS )NrT   r   r   r   r   r   )r   r   r   r   reshaperA   r   flattenappendr   r   r   maxr  )rI   grid_thwpos_idsthwhpos_idswpos_idsmax_grid_sizerotary_pos_emb_fullr  s              rL   rot_pos_embzGlm4vVisionModel.rot_pos_emb1  s    	SGAq!||A003::2qAH''T,,,''T,,,''	H  ''1a3H'')H||A003::1bAH''T,,,''T,,,''	H  ''1a3H'')HNN5;;(';DKKAqQR)	S* ))G+ AB++-"11-@,W5==a@w&&rM   rk   r   c           	         | j                  |      }| j                  |      }| j                  |      \  }}t        j                  ||fd      }|j                         |j                         f}t        j                  |dddf   |dddf   z  |dddf         j                  dt        j                  j                         r|j                  nt        j                        }t        j                  |dd	      }|dd |dd z
  j                         }| j!                  ||||dddf   |dddf         }| j"                  D ]  }	 |	|||
      } | j%                  |      }|j'                  d| j(                  | j(                  |j*                  d         }|j-                  dddd      }| j/                  |      j'                  d| j0                  j2                        }| j5                  |      }|S )az  
        Args:
            hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
                The final hidden states of the model.
            grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
                The temporal, height and width of feature shape of each image in LLM.

        Returns:
            `torch.Tensor`: hidden_states.
        r   r   NrT   r   r   )r   r   )rT   r   )value)
cu_seqlensposition_embeddingsr   )r  r  r)  r   r   cossinrepeat_interleavecumsumjit
is_tracingr   int32r   padtolistr   r  r  r   rA   r   r   r  r   rC   r  )
rI   rk   r   r  image_type_idsembr-  r,  seqlensblks
             rL   r   zGlm4vVisionModel.forwardN  s    ((700?)-)9)9()C&ii8bA"wwy#'')4,,Xad^hq!tn-LhWXZ[W[n]dd
 %*II$8$8$:(.. e 

 UU:vQ7
ab>JsO3;;=w.YZ\]Y]J^`noprsos`tu;; 	C%$7M	 ++M:%**'')@)@-BUBUVXBY
 &--aAq96;;B@[@[\M2rM   r  )rX   rY   rZ   r3   __annotations__r	  r9   r)  r   r   r   r^   r_   s   @rL   r  r    sB    +,8':.U\\ .U\\ .ell .rM   r  c                       e Zd Zy)Glm4vTextRotaryEmbeddingNr   r7   rM   rL   r=  r=    r   rM   r=  c                 |    | ddddf   }| ddddf   }t        j                  | |fd      j                  d      S )	z*Rotates half the hidden dims of the input..r   Nr   rT   r   r   )r   r   r  )xx1x2s      rL   rotate_half_llmrC    sJ    	
319B	
319B;;Ryb)11"55rM   c           	      R   |dz  }t        j                  t        |j                  |d            D cg c]  \  }}||dz      c}}d      j	                  |      }t        j                  t        |j                  |d            D cg c]  \  }}||dz      c}}d      j	                  |      }|dd|j
                  d   dz  f   j                  dd      }|dd|j
                  d   dz  f   j                  dd      }|j
                  d   }| dd|f   | d|df   }
}	|dd|f   |d|df   }}|	|z  t        |	      |z  z   }||z  t        |      |z  z   }t        j                  ||
gd      }t        j                  ||gd      }||fS c c}}w c c}}w )aX  Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).

    Explanation:
        Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
        sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
        vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
        Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
        For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
        height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
        difference with modern LLMs.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        mrope_section(`List(int)`):
            Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    r   r   r   r   .N)r   r   	enumeratesplitr   r   r0  rC  )qkr.  r/  rs   unsqueeze_dimr   m
rotary_dimq_rotq_passk_rotk_passq_embedk_embeds                  rL   apply_multimodal_rotary_pos_embrR    s   : "A%M
)))CIImQSI4T*UV$!QQq1uXV\^
_
i
iC )))CIImQSI4T*UV$!QQq1uXV\^
_
i
iC
 c'SYYr]a'''
(
:
:1"
:
EC
c'SYYr]a'''
(
:
:1"
:
EC 2Jc;J;&'3
+;)<6Ec;J;&'3
+;)<6E s{u5;<Gs{u5;<G ii&)r2Gii&)r2GG1 W Ws   F
F#
c                   l    e Zd ZdZddedee   f fdZ	 	 	 	 	 	 ddej                  de
ej                  ej                  f   deej                     deej                     d	ee   d
ededeej                     dee   de
ej                  eej                     ee
ej                        f   fdZ xZS )Glm4vTextAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper.
    and "Generating Long Sequences with Sparse Transformers".
    r   	layer_idxc                    t         |           || _        || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _	        d| _
        |j                  | _        |j                  | _        | j                  dz  | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  | j                  z  d      | _        t        j                  | j                  | j                  z  | j                  d      | _        y )NTg      r   F)r8   r9   r   rU  r;   ry   r=   r  rz   num_key_value_groups	is_causalrH   r}   scalingr   r   q_projk_projv_projo_projrI   r   rU  rK   s      rL   r9   zGlm4vTextAttention.__init__  sI   "!--33((DNN:#)#=#= $(NNd6N6N$N!!'!9!9"//}}d*ii 0 0$..4==2PW[\ii 0 0$2J2JT]]2Zaefii 0 0$2J2JT]]2Zaefii >@P@PW\]rM   rk   r-  rl   r   past_key_valueoutput_attentionsr{   cache_positionrJ   r   c	                    |j                         \  }
}}| j                  |      }| j                  |      }| j                  |      }|j	                  |
|d| j
                        j                  dd      }|j	                  |
|d| j
                        j                  dd      }|j	                  |
|d| j
                        j                  dd      }|\  }}t        ||||| j                  d         \  }}|'|||d}|j                  ||| j                  |      \  }}t        }| j                  j                  dk7  rt        | j                  j                     } || ||||f| j                  sdn| j                   | j"                  d|	\  }}|j%                  |
|d      j'                         }| j)                  |      }|||fS )	Nr   rT   r   rs   )r/  r.  ra  eagerrP   )dropoutrY  )sizerZ  r[  r\  r   r  	transposerR  r}   updaterU  r!   r   _attn_implementationr   trainingrH   rY  r  
contiguousr]  )rI   rk   r-  rl   r   r_  r`  r{   ra  rJ   bszq_lenr  query_states
key_statesvalue_statesr.  r/  cache_kwargsattention_interfaceattn_outputattn_weightss                         rL   r   zGlm4vTextAttention.forward  s    &**,UA{{=1[[/
{{=1#((eRGQQRSUVW__S%T]]CMMaQRS
#((eRGQQRSUVW&S#B*c30A0A/0R$
 j %#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "))#ub9DDFkk+.L.88rM   r   NNNFFN)rX   rY   rZ   r[   ra   r   r   r9   r   r   tuple
LongTensorr	   r   r   r   r   r^   r_   s   @rL   rT  rT    s   
^ ^8C= ^0 2637*."'5909||09 #5<<#=>09 !.	09
 u//009 !09  09 09 !!1!1209 -.09 
u||Xell3XeELL>Q5RR	S09rM   rT  c                       e Zd Zy)Glm4vTextMLPNr   r7   rM   rL   rx  rx    r   rM   rx  c                   x    e Zd Zdedef fdZ	 	 	 	 	 	 ddej                  deej                  ej                  f   de	ej                     de	ej                     de	eej                        d	e	e   d
e	e   de	ej                     deej                  e	eej                  ej                  f      f   fdZ xZS )r  r   rU  c                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        t        |j                  |j                        | _        t        |j                  |j                        | _        y )Nr   )r8   r9   r;   rT  	self_attnrx  r  r   rF   input_layernormpost_attention_layernormpost_self_attn_layernormpost_mlp_layernormr^  s      rL   r9   zGlm4vTextDecoderLayer.__init__  s    !--+FI>'+F,>,>FDWDWX(4V5G5GVM`M`(a%(4V5G5GVM`M`(a%".v/A/AvGZGZ"[rM   rk   r-  rl   r   r_  r`  r{   ra  r   c	                 0   |}
| j                  |      } | j                  d||||||||d|	\  }}}| j                  |      }|
|z   }|}
| j                  |      }| j	                  |      }| j                  |      }|
|z   }|f}|r||fz  }|r||fz  }|S )N)rk   r-  rl   r   r_  r`  r{   ra  r7   )r|  r{  r~  r}  r  r  )rI   rk   r-  rl   r   r_  r`  r{   ra  rJ   residualself_attn_weightspresent_key_valueoutputss                 rL   r   zGlm4vTextDecoderLayer.forward  s     !,,]; ?Mdnn 
?
' 3)%)/)
?
 
?
;(*; 55mD =0 !55mD///> =0 ")++G)++GrM   rt  )rX   rY   rZ   ra   r   r9   r   r   ru  r   rv  r   FloatTensorr   r^   r_   s   @rL   r  r    s    \ \3 \ 26378<,1$)59/||/ #5<<#=>/ !.	/
 u//0/ !u||!45/ $D>/ D>/ !!1!12/ 
u  (51B1BEDUDU1U+V"WW	X/rM   r  c                       e Zd Zy)Glm4vModelOutputWithPastNr   r7   rM   rL   r  r  Q  r   rM   r  c                   D    e Zd Zdef fdZ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   d	ee   d
ee   deej                     dee   deeef   fd              Z xZS )Glm4vTextModelr   c           	      .   t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t        |      | _        | `| `y c c}w )Nr   )r   )r8   r9   r   r  r   rx   r  rn   r   r;   rF   ro   r=  
rotary_embrh  has_sliding_layersr^  s      rL   r9   zGlm4vTextModel.__init__V  s{     mmGLVMeMeGfg)"695g
 !!3!39L9LM	2&A%# hs   Bri   rl   r   rd   rj   r{   r`  output_hidden_statesra  rJ   r   c
                 N   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}|r*|(t        j                  j                         s
t               }|| j                  |      }|	F||j                         nd}t        j                  |||j                   d   z   |j"                        }	|2|	j%                  ddd      j'                  d|j                   d   d      }n6|j)                         d	k(  r#|d
   j'                  d|j                   d   d      }t+        | j                   |||	||      }|}| j-                  ||      }|rdnd }|rdnd }| j.                  D ],  }|r||fz  } ||f|||||||	d|
}|d   }|s$||d   fz  }. | j1                  |      }|r||fz  }t3        ||r|nd ||      S )N:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   rT   r   r   r   r   )N.)r   input_embedsrl   ra  rd   r   r7   )r-  rl   r   r_  r`  r{   ra  )last_hidden_staterd   rk   
attentions)r   r`  r  r{   
ValueErrorr  ri  loggerwarning_oncer   r2  r3  r
   rm   get_seq_lengthr   r   r   r   r   r   r   r  rn   ro   r   )rI   ri   rl   r   rd   rj   r{   r`  r  ra  rJ   past_seen_tokenscausal_maskrk   r-  all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      rL   r   zGlm4vTextModel.forward`  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==##p "	 09M9M9O*nO  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN
 )..q!R8??=CVCVWXCY[]^L1$'	299!\=O=OPQ=RTVWL(;;&))+%
 & #oom\J #7BD0d![[ 	6M#!m%55!)
$7*)."3#-
 
M *!,M =#3"55'	6* 		-0  -!11&+/8Od+%	
 	
rM   )	NNNNNNNNN)rX   rY   rZ   ra   r9   r   r   r   r   rv  r   r   r  r   r   r   r   ru  r   r   r^   r_   s   @rL   r  r  U  s#   $ $  151537=A59$(,0/359b
E,,-b
 !.b
 u//0	b

 "$u'8'8"9:b
   1 12b
 D>b
 $D>b
 'tnb
 !!1!12b
 -.b
 
u--	.b
  b
rM   r  c            %           e Zd Zi ZddgZ fdZ	 	 	 	 ddeej                     deej                     deej                     deej                     de
ej                  ej                  f   f
d	Z	 dd
ej                  deej                     fdZee	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddej                  deej                     deej                     deeej                        deej                     dee   dee   dee   d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
ef   f d              Z xZS )
Glm4vModelr  r   c                 l    t         |   |       t        j                  |j                        | _        y r   )r8   r9   r  _from_configr5   visualr   s     rL   r9   zGlm4vModel.__init__  s(     &33F4H4HIrM   ri   image_grid_thwvideo_grid_thwrl   r   c           
      F   | j                   j                  j                  }| j                   j                  }| j                   j                  }| j                   j
                  }g }	|h||c|}
|t        j                  |
      }t        j                  d|j                  d   |j                  d   |j                  |j                        }d\  }}d}|j                  |
j                        }t        |
      D ]  \  }}|||   dk(     }|j                         }g }d}|D ]T  }||k(  rd}n||k(  rd}||k(  r|s|j                  d       +||k(  r|r|j                  d	       D|j                  d
       V g }t!        j"                  t        |      d       D ]7  \  }}t%        |      }|d   d   }|d   d   dz   }|j                  |||f       9 g }d}|D ]:  \  }}}t'        |      dkD  r|d   j)                         dz   nd}|dk(  rQ||   d   ||   d   ||   d   }!} }|j+                         | j+                         |z  |!j+                         |z  }$}#}"t        j,                  |"      j/                  dd      j1                  d|#|$z        j3                         }%t        j,                  |#      j/                  ddd      j1                  |"d|$      j3                         }&t        j,                  |$      j/                  ddd      j1                  |"|#d      j3                         }'|j                  t        j4                  |%|&|'g      |z          |dz  }d}|d	k(  rb|||   d   ||   d   }!} }|| j+                         |z  |!j+                         |z  }$}#}"t7        |"      D ]  }(t        j8                  |(      j/                  dd      j1                  d|#|$z        j3                         }%t        j,                  |#      j/                  ddd      j1                  dd|$      j3                         }&t        j,                  |$      j/                  ddd      j1                  d|#d      j3                         }'|j                  t        j4                  |%|&|'g      |z           |dz  }|||   d   k\  r|dz  }d}|dz  }||z
  })|j                  t        j,                  |)      j/                  dd      j1                  dd      |z          d}= t        j:                  |d      j=                  dd      }*|*j                  |j                        |d|||   dk(  f<   |	j                  |*j)                         dz   t'        |
|         z
          t        j8                  |	|j                        j?                  d      }	||	fS ||jA                         jC                  d      dz
  }|jE                  |dk(  d       |j?                  d      j1                  ddd      j                  |j                        }|j)                  dd      d   j)                  dd      d   }+|+dz   |j                  d   z
  }	||	fS t        j,                  |j                  d   |j                        j/                  ddd      j1                  d|j                  d   d      }t        jF                  |j                  d   dg|j                  |j                        }	||	fS )aU  
        Calculate the 3D rope index based on image and video's temporal, height and width in LLM.

        Explanation:
            Each embedding sequence contains vision embedding and text embedding or just contains text embedding.

            For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
            Examples:
                input_ids: [T T T T T], here T is for text.
                temporal position_ids: [0, 1, 2, 3, 4]
                height position_ids: [0, 1, 2, 3, 4]
                width position_ids: [0, 1, 2, 3, 4]

            For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
            and 1D rotary position embedding for text part.
            Examples:
                Temporal (Time): 3 patches, representing different segments of the video in time.
                Height: 2 patches, dividing each frame vertically.
                Width: 2 patches, dividing each frame horizontally.
                We also have some important parameters:
                fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
                tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
                temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
                interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
                input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
                vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
                vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
                vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
                text temporal position_ids: [101, 102, 103, 104, 105]
                text height position_ids: [101, 102, 103, 104, 105]
                text width position_ids: [101, 102, 103, 104, 105]
                Here we calculate the text start position_ids as the max vision position_ids plus 1.

        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.
            image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
                The temporal, height and width of feature shape of each image in LLM.
            video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
                The temporal, height and width of feature shape of each video in LLM.
            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**.

        Returns:
            position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
            mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
        r   r   rT   r   r   )r   r   FTimagevideotextc                     | d   S )NrT   r7   )r@  s    rL   <lambda>z+Glm4vModel.get_rope_index.<locals>.<lambda>2  s    [\]^[_ rM   r   r   r   .r  )keepdimr   )$r   r5   rA   r~   r   r   r   	ones_likeonesr   r   r   r   rE  r6  r  	itertoolsgroupbyr   r   r  itemr   r   r   r  r   r   r   r   r  r   r   r1  masked_fill_zeros),rI   ri   r  r  rl   rA   r~   r   r   mrope_position_deltastotal_input_idsr   image_indexvideo_indexvideo_group_indexr   input_tokensinput_token_typevideo_check_flgtokeninput_type_groupkeygroupstart_index	end_indexllm_pos_ids_listvideo_frame_nummodality_type	start_idxend_idxst_idxr"  r#  r$  
llm_grid_t
llm_grid_h
llm_grid_wt_indexh_indexw_indext_idxtext_lenllm_positionsmax_position_idss,                                               rL   get_rope_indexzGlm4vModel.get_rope_index  sL   v "[[66II33#{{??![[;; " n&@ND^'O%!&!A ::""oo ''L (,$K !+../E/EFN )/ : W`9%nQ&71&<=	(//1#% "') 8E 44*."44*/.(//8.0_(//8(//78 $& "+"3"3I>N4OQ_"` KJC KE"'(1+K %b	!q 0I$++S+y,IJ	K $& "#9I 7,5M9g?BCS?TWX?X-b1557!;^_F$/*;7:*;7:*;7:  1 FFHFFH(::FFH(:: 1;J
 #(,,z":"?"?A"F"M"MbR\_iRi"j"r"r"t"',,z":"?"?2q"I"P"PQ[]_ak"l"t"t"v"',,z":"?"?1b"I"P"PQ[]gik"l"t"t"v(//Wgw<W0X[a0ab#q(*+&'1+*;7:*;7:  1 FFH(::FFH(:: 1;J
 &+:%6 gE&+ll5&9&>&>r1&E&L&LRQ[^hQh&i&q&q&sG&+ll:&>&C&CAr1&M&T&TUVXZ\f&g&o&o&qG&+ll:&>&C&CAq"&M&T&TUVXbdf&g&o&o&qG,33EKK'SZ@[4\_e4efg *Q.),{0KA0NN'1,K01-'1, $+Y#6(//X0F0K0KAr0R0Y0YZ[]_0`ci0ij*+o7,r !&		*: B J J1b Q?L?O?OP\PcPc?dS!^A%6!%;;<%,,]->->-@1-Ds?[\K]G^-^_oW`p %*LL1FyO_O_$`$j$jkl$m!!666)-224;;B?!C)).A*=qA+55a8??2rJMMnNcNcd#/#3#3Au#3#Ea#H#L#LRY]#L#^_`#a (81(<~?S?STV?W(W%  !666 LL!3I<L<LMT!Q^VAyq126 
 ).__Q'+$++#//)%  !666rM   pixel_values_videosc                 $   |j                  | j                  j                        }g }|D ]j  \  }}}t        j                  d|j                         |j                         g      j                  d      j                  |d      }|j                  |       l t        j                  |d      }| j                  ||      }	|j                  d      | j                  j                  dz  z  j                         }
t        j                  |	|
      }	|	S )a  
        Encodes videos into continuous embeddings that can be forwarded to the language model.

        Args:
            pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
                The tensors corresponding to the input videos.
            video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
                The temporal, height and width of feature shape of each video in LLM.
        rT   r   r   )r   r   r   )rq   r  r   r   r   r  r   r   r  r   prodrA   r6  rF  )rI   r  r  temp_frames_hwr"  r#  r$  repeated_rowflattened_video_grid_thwvideo_embedssplit_sizess              rL   get_video_featureszGlm4vModel.get_video_features  s     266t{{7H7HI% 	0GAq! <<AFFHaffh(?@JJ1MTTUVXYZL!!,/	0 $)99^#C {{#6AY{Z%**2.$++2P2PRS2SS[[]{{<=rM   r   rd   rj   r{   r`  r  pixel_valuesrope_deltasra  rJ   c                    ||n| j                   j                  }||n| j                   j                  }|du |duz  rt        d      | | j	                         |      }|	v| j                  |	|      }t        j                  |d      j                  |j                  |j                        }| j                  |||      \  }}|j                  ||      }|
v| j                  |
|      }t        j                  |d      j                  |j                  |j                        }| j                  |||      \  }}|j                  ||      }|t        |t              s|n|d   }||j                   dk(  rtt        j"                  |dddf   d	d
      }|j                  j$                  r?|t        j&                  |j                        j(                  z  }d|z
  j+                         }t-               xr2 |duxr |j.                  d	   d	k7  xs |duxr |j.                  d	   d	k7  }t-                xr) |duxr |d   dk(  xs |du xs |j1                         dk(  }|s|s| j2                   | j5                  ||||      \  }}|| _        n|j.                  \  }}}|+|d   | j2                  z   j                  |j                        nd}t        j6                  ||j                        }|j9                  d	d      j;                  |d      }|#|j=                  ||j.                  d   z  d      }|j?                  |      }|jA                  d      j;                  ddd      } | jB                  dd|||||||d|d
|}tE        |jF                  |jH                  |jJ                  |jL                  | j2                        S )a  
        image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
            The temporal, height and width of feature shape of each image in LLM.
        video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
            The temporal, height and width of feature shape of each video in LLM.
        rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
            The rope index difference between sequence length and multimodal rope.
        Nr  r   r   )image_features)video_featuresfull_attention   rT   r   )dim1dim2g      ?)rl   r  r   r   T)
ri   r   rl   rd   rj   r{   r`  r  return_dictra  )r  rd   rk   r  r  r7   )'r   r`  r  r  get_input_embeddingsget_image_featuresr   r   r   r   r   get_placeholder_maskmasked_scatterr  r   dictndimdiagonalis_floating_pointfinfominr   r   r   r  r  r  r   r   r   r0  addr   language_modelr  r  rd   rk   r  )rI   ri   rl   r   rd   rj   r{   r`  r  r  r  r  r  r  ra  rJ   image_embeds
image_maskr  r  
video_maskattention_mask_tensorprefill_compiled_stageprefill_noncompiled_stage
batch_size
seq_lengthdeltar  s                               rL   r   zGlm4vModel.forward  s(   : 2C1N-TXT_T_TqTq$8$D $++JjJj 	 -t";<YZZ 7D557	BM#22<PL 99\q9<<]=Q=QS`SfSfgL 55i_k5lMJ)88\RM*223FWL 99\q9<<]=Q=QS`SfSfgL 55i_k5lMAz)88\RM&0&FN[kLl " %05J5O5OST5T(-7LQPQT7RYZab(c%(..@@,AEKKPePkPkDlDpDp,p)-03H-H,M,M,O) &>%? &$&B9??1+=+B O!-M-2E2Ea2HA2M # -E,F(F )t+Fq0AQ0F V#t+T/M/M/OST/T & '*CHXHXH`,0,?,?""#8	 -@ -)k $/  -:,?,?)
J &1 $A&)9)99==m>R>RS 
  %||J}?S?ST+00B7>>z2N!-!33J%++a.4PVW3XE+//6+55a8??2rJ%$%% 
%)+'/!5)
 
 (%77#33!//))((
 	
rM   NNNNr   )NNNNNNNNNNNNNN)rX   rY   rZ   _checkpoint_conversion_mappingr	  r9   r   r   rv  r   ru  r  r  r  r   r   r   r   r   r   r   r  r   r^   r_   s   @rL   r  r    sX   %'"02DEJ 15595915|7E,,-|7 !!1!12|7 !!1!12	|7
 !.|7 
u||U\\)	*|7~ dh#(#4#4FNuO_O_F`0  '+1537=A59$(,0/3/3;?59592659t
##t
 !.t
 u//0	t

 "$u'8'8"9:t
   1 12t
 D>t
 $D>t
 'tnt
 u||,t
 &e&7&78t
 !!1!12t
 !!1!12t
 e../t
 !!1!12t
  +,!t
" 
u..	/#t
  t
rM   r  c                       e Zd Zy)Glm4vCausalLMOutputWithPastNr   r7   rM   rL   r  r    r   rM   r  c            )           e Zd Zi Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd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
   dee
   d	ee
   d
ee
   d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ej                  f   dee   deeef   f&dZ	 	 	 	 	 	 	 	 	 	 d fd	Z	 ddeej
                     deej                     deej                  ej                  f   fdZ xZS )Glm4vForConditionalGenerationri   rl   r   rd   rj   labelsr{   r`  r  r  r  r  r  r  r  ra  logits_to_keeprJ   r   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | j                  d||||||||||||	|d|}|d   }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }d}|2| j                  ||| j                   j                  j                        }t        |||j                  |j                  |j                  |j                        S )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
            The temporal, height and width of feature shape of each image in LLM.
        video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
            The temporal, height and width of feature shape of each video in LLM.
        rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
            The rope index difference between sequence length and multimodal rope.

        Example:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, Glm4vForConditionalGeneration

        >>> model = Glm4vForConditionalGeneration.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
        >>> processor = AutoProcessor.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")

        >>> messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image"},
                    {"type": "text", "text": "What is shown in this image?"},
                ],
            },
        ]
        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
        ```N)ri   r  r  r  r  r   rl   rd   rj   r{   r`  r  ra  r   )logitsr  rv   )lossr  rd   rk   r  r  r7   )r   r`  r  modelr   r   slicelm_headloss_functionrc   rv   r  rd   rk   r  r  )rI   ri   rl   r   rd   rj   r  r{   r`  r  r  r  r  r  r  r  ra  r  rJ   r  rk   slice_indicesr  r  s                           rL   r   z%Glm4vForConditionalGeneration.forward%  s/   @ 2C1N-TXT_T_TqTq$8$D $++JjJj 	 $** 
% 3))%)+'/!5)
 
"  
 9C>SV8W~ot4]kmA}a,?@A%%VFt{{OfOfOqOq%rD*#33!//))++
 	
rM   c                 l    t        |   |f|||||||	|
||d
|}d |d<   |d   dk7  r
d |d<   d |d<   |S )N)
rd   rl   rj   ra  r   r  r  r  r  r{   r   r   r  r  )r8   prepare_inputs_for_generation)rI   ri   rd   rl   rj   ra  r   r{   r  r  r  r  rJ   model_inputsrK   s                 rL   r  z;Glm4vForConditionalGeneration.prepare_inputs_for_generation  sx    " w<
+)')%% 3))
 
  (,^$!!+/L(26L./rM   c                    || | j                         t        j                  | j                  j                  t        j
                  |j                              k(  d   }| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  d   }| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  d   }nK|| j                  j                  k(  }|| j                  j                  k(  }|| j                  j                  k(  }t        j                  |j                         |j                         z
  d      }|dkD  }|| z  }|j                  d      }	|j                  d      }
|	|
fS )aa  
        Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
        These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.

        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary.

        Returns:
            image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
            video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
        r  ).r   rT   r   r   )r  r   r   r   r   r   r   r   r   r1  r   sum)rI   ri   rj   is_imageis_video_startis_video_endvideo_levelinside_videostandalone_imagesimage_countsvideo_countss              rL   _get_image_nums_and_video_numsz<Glm4vForConditionalGeneration._get_image_nums_and_video_nums  s   $ $.4,,.LL!A!A\i\p\pq H .4,,.LL!A!A\i\p\pq N .4,,.LL!?!?uzzZgZnZno L !DKK$D$DDH&$++*J*JJN$(F(FFL ll>#5#5#7,:J:J:L#LRST"Q %6 ),,,3%))a)0\))rM   )NNNNNNNNNNNNNNNNr   )
NNNNNTNNNNr   )rX   rY   rZ   r  r   rv  r   r   r   r  r   r   r   r   r   ru  r  r   r  r  r^   r_   s   @rL   r   r   "  s5   %'" '+1537=A59-1$(,0/3&*/3;?5959265934%g
##g
 !.g
 u//0	g

 "$u'8'8"9:g
   1 12g
 ))*g
 D>g
 $D>g
 'tng
 d^g
 u||,g
 &e&7&78g
 !!1!12g
 !!1!12g
  e../!g
" !!1!12#g
$ c5<</0%g
& +,'g
( 
u11	2)g
X  'X 156*E,,-6*  -6* 
u||U\\)	*	6*rM   r   c                       e Zd Zy)Glm4vVideosProcessorKwargsNr   r7   rM   rL   r  r    r   rM   r  c                   >    e Zd ZU ee   ed<   ee   ed<   ee   ed<   y)Glm4vImagesKwargsr@   rB   
merge_sizeN)rX   rY   rZ   r   r   r;  r7   rM   rL   r  r    s     !#&rM   r  c                   0    e Zd ZU eed<   eed<   ddddiZy)Glm4vProcessorKwargsimages_kwargsvideos_kwargstext_kwargsF)paddingreturn_mm_token_type_idsN)rX   rY   rZ   r  r;  r  	_defaultsr7   rM   rL   r  r    s#    $$--(-
IrM   r  c                   l     e Zd ZdZdZd
 fd	Z	 	 	 ddedeee	e
e   e
e	   f   dedee   def
d	Z xZS )Glm4vProcessora  
    Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor.
    [`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information.
    Args:
        image_processor ([`Glm4vProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`PreTrainedTokenizerFast`], *optional*):
            The tokenizer is a required input.
        video_processor ([`Glm4vVideoProcessor`], *optional*):
            The video processor is a required input.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
    )PreTrainedTokenizerPreTrainedTokenizerFastc                     t         |   ||||       t        |d      sdn|j                  | _        t        |d      sd| _        y |j                  | _        y )N)chat_templateimage_tokenz	<|image|>video_tokenz	<|video|>)r8   r9   hasattrr,  r-  )rI   image_processor	tokenizervideo_processorr+  rJ   rK   s         rL   r9   zGlm4vProcessor.__init__  sS    )_Tab.5i.O;U^UjUj.5i.O;U^UjUjrM   imagesr  videosrJ   r   c                     | j                   t        fd| j                  j                  i|}| | j                  dd|i|d   }|d   }ni }d}|. | j
                  dd|i|d   }|j                  d      }	|d	   }
ni }g }	d}
t        |t              s|g}|j                         }|| j                  j                  d
z  }d}t        t        |            D ]  }| j                  ||   v rS||   j                         |z  }||   j                  | j                  d|z  d      ||<   |dz  }| j                  ||   v rS||   j                  d| j                        ||<    |
| j
                  j                  d
z  }d}t        t        |            D ]  }| j                   ||   v r||
|   d   }d}t#        |	d      r|	j%                         d   }nt        |	d   t              r|	d   n|	}g }t        dt        |            D ]  }|j'                  ||           |d| }t        |      |k  r'|j'                  |r|d   nd       t        |      |k  r't        |      D ]  }||   }d| j                   d| }||z  }  ||   j                  | j                   |d      ||<   |
|   j                         |z  |
|   d   z  }t        |      D ]:  }| j                  ||   v s||   j                  | j                  d|z  d      ||<   < |dz  }| j                   ||   v r|||   j                  d| j                        ||<    |d   j                  dd      }|d   j                  dd      } | j                  |fi |d   }| j)                  ||ddg       |rUt+        j,                  |d         }t+        j.                  |d         }d||| j0                  k(  <   |j%                         |d<   t3        i ||||      S )a^
  
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
        the text.

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. Both channels-first and channels-last formats are supported.
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
                tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:
                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.
                - `'jax'`: Return JAX `jnp.ndarray` objects.

        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
              `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
            - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
            - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
            - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
        tokenizer_init_kwargsNr2  r   r  r3  r!  
timestampsr  r   r   z<|placeholder|>rT    r6  r   z<|begin_of_image|>z<|end_of_image|>r"  return_tensorsr$  Fr  r  )
modalitiesri   mm_token_type_ids)datatensor_typer7   )_merge_kwargsr  r0  init_kwargsr/  r1  popr   r   copyr  r   r   r,  r  replacer-  r.  r6  r  _check_special_mm_tokensnparray
zeros_liker~   r   )rI   r2  r  r3  rJ   output_kwargsimage_inputsr  videos_inputsr6  r  merge_lengthindexr   num_image_tokensr  
num_framesvideo_structuretimestamps_listunique_timestampsidxselected_timestamps	frame_idxtimestamp_secframe_structurer8  r$  text_inputs	array_idsr:  s                                 rL   __call__zGlm4vProcessor.__call__  s   T +** 
"&.."<"<
 

 /4//`v`A_`L)*:;NL!N0D00aa-P_B`aM&**<8J*+;<NMJ!N$%6Dyy{%//::A=LE3t9% O&&$q'1'5e'<'A'A'C|'S$"1good.>.>@QTd@dfghDGQJE &&$q'1 q'//*;T=M=MNQO %//::A=LK3t9% !O&&$q'1!/!<Q!?J&(Oz84*4*;*;*=a*@;EjQRmUY;Z*Q-`j(*%$QO(<= G)001EFG +<KZ*H'12Z?+22Na3Fr3Jghi 12Z? &+:%6 ;	(;I(F,>t?O?O>PP`an`o*p'?:;
 #1good.>.>QRSDG&{388:lJn]hNijkNll % &+:%6 q	++tAw6&*1good6F6FHY\lHlno&pDGq  1$K= &&$q'1@ q'//*;T=M=MNQC!OD '}599:JDQ#0#?#C#CD^`e#f $dnnTJ]=-IJ%%dKWgDV%W#[!9:I "k+.F GBCi4+>+>>?/@/G/G/IK+,!QK!Q<!Q=!Q_mnnrM   r  )NNN)rX   rY   rZ   r[   tokenizer_classr9   r   r   r   r   r   r   r   r  r   rW  r^   r_   s   @rL   r'  r'    s     IOk "^b!	|o|o I0$y/4HYCZZ[|o 	|o
 -.|o 
|orM   r'  )r   ra   r   r  r  r'  r  )rT   )lr  typingr   r   r   numpyrC  r   torch.nnr   torch.nn.functional
functionalr   torch.utils.checkpointr   activationsr   cache_utilsr	   r
   configuration_utilsr   feature_extraction_utilsr   image_utilsr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   r   tokenization_utils_baser   r   utilsr   r   r   r   r   video_utilsr   glm4.modeling_glm4r   r    r!   #qwen2_5_vl.configuration_qwen2_5_vlr"   qwen2_5_vl.modeling_qwen2_5_vlr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.    qwen2_5_vl.processing_qwen2_5_vlr/   r0   r1   
get_loggerrX   r  r3   ra   r   r   r   r   r   Moduler   r   r   r   r  r  r=  rC  rR  rT  rx  r  r  r  r  r  r   r  r  r  r'  __all__r7   rM   rL   <module>ru     s!    , ,        ! . 3 4 % / B 9 7 9 5 4 C l l % N N B     
		H	%^3( ^3BVL& VLr:5" :5|	; 	8M 8	m4 	m	!> 	fRYY f"TBII TnR4 R5, 5F4 Fk+ k\	8 	66rJ9 J9Z	7 	:6 :z	< 	o
( o
dT
 T
n
	"B 	K*$F K*\	!@ 	 4 Ro( RojrM   