o
    ei1                    @   sz  d dl Z d dlmZ d dlmZ d dlmZmZ d dlZd dl	m
Z
 d dlm
  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 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)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z; edG dd de
j<Z=G dd de
j<Z>G dd de
j<Z?G dd  d e
j<Z@G d!d" d"e
j<ZAG d#d$ d$e
j<ZBd%d& ZCd'ejDd(ejDd)ejDd*ejDd+eEejDejDf f
d,d-ZFd.ejDd/eGd+ejDfd0d1ZH	2d_d3e
j<d4ejDd5ejDd6ejDd7ejDdB d8eId9eId:e,e. fd;d<ZJG d=d> d>e
j<ZKG d?d@ d@e ZLG dAdB dBe
j<ZMdCdD ZNd`dEdFZOG dGdH dHe
j<ZPG dIdJ dJe
j<ZQG dKdL dLe ZRee/dMdNG dOdP dPe$ZSe/G dQdR dRe*ZTG dSdT dTeTZUe/G dUdV dVeTZVe/G dWdX dXeTZWee/dYdNG dZd[ d[e$ZXG d\d] d]eTeZYg d^ZZdS )a    N)Callable)	dataclass)AnyOptional)	LayerNorm   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastBaseModelOutputWithPoolingModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupletorch_compilable_check)is_flash_attention_requestedmaybe_autocastmerge_with_config_defaults)capture_outputs   )Glm4vConfigGlm4vTextConfigGlm4vVisionConfigRMSNormc                       sF   e Zd Zddeddf fddZdejdejfdd	Zd
d Z  Z	S )Glm4vRMSNormư>epsreturnNc                    s&   t    tt|| _|| _dS )z;
        Glm4vRMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parametertorchonesweightvariance_epsilon)selfhidden_sizer(   	__class__ f/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/glm4v/modeling_glm4v.pyr+   2   s   

zGlm4vRMSNorm.__init__hidden_statesc                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor.   float32powmeanrsqrtr1   r0   )r2   r8   input_dtypevariancer6   r6   r7   forward:   s
   zGlm4vRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler0   shaper1   r2   r6   r6   r7   
extra_reprA   s   zGlm4vRMSNorm.extra_repr)r'   )
__name__
__module____qualname__floatr+   r.   TensorrD   rH   __classcell__r6   r6   r4   r7   r&   0   s    r&   c                       s,   e Zd Zddef fddZdd Z  ZS )Glm4VisionMlpFbiasc                    sl   t    |j| _|j| _tj| j| j|d| _tj| j| j|d| _tj| j| j|d| _	t
|j | _d S NrP   )r*   r+   r3   out_hidden_sizeintermediate_sizer,   Linear	gate_projup_proj	down_projr	   
hidden_actact_fn)r2   configrP   r4   r6   r7   r+   F   s   
zGlm4VisionMlp.__init__c                 C   s    |  | | || | S N)rX   rZ   rV   rW   r2   hidden_stater6   r6   r7   rD   O   s    zGlm4VisionMlp.forwardF)rI   rJ   rK   boolr+   rD   rN   r6   r6   r4   r7   rO   E   s    	rO   c                       s<   e Zd Zdeddf fddZdejdejfddZ  ZS )	Glm4vVisionPatchEmbedr[   r)   Nc                    sV   t    |j| _|j| _|j| _|j| _| j| j| jg}tj| j| j||d| _	d S )N)kernel_sizestride)
r*   r+   
patch_sizetemporal_patch_sizein_channelsr3   	embed_dimr,   Conv3dproj)r2   r[   rb   r4   r6   r7   r+   T   s   
zGlm4vVisionPatchEmbed.__init__r8   c                 C   sD   | j jj}|d| j| j| j| j}|  |j|dd| j}|S )Nr:   r<   )	ri   r0   r<   viewrf   re   rd   r=   rg   )r2   r8   target_dtyper6   r6   r7   rD   ^   s   
zGlm4vVisionPatchEmbed.forward	rI   rJ   rK   r$   r+   r.   rM   rD   rN   r6   r6   r4   r7   ra   S   s    
ra   c                       sL   e Zd ZU ejed< ddededdf fddZd	edejfd
dZ	  Z
S )Glm4vVisionRotaryEmbeddinginv_freq     @dimthetar)   Nc                    sJ   t    || _|| _d|tjd|dtjd|   }| jd|dd d S )N      ?r   r9   rj   ro   F
persistent)r*   r+   rq   rr   r.   arangerL   register_buffer)r2   rq   rr   ro   r4   r6   r7   r+   j   s
   
 z#Glm4vVisionRotaryEmbedding.__init__seqlenc                 C   s*   t j|| jj| jjd}t || j}|S )Ndevicer<   )r.   rv   ro   rz   r<   outer)r2   rx   seqfreqsr6   r6   r7   rD   q   s   z"Glm4vVisionRotaryEmbedding.forward)rp   )rI   rJ   rK   r.   rM   __annotations__intrL   r+   rD   rN   r6   r6   r4   r7   rn   g   s   
 
rn   c                       sJ   e Zd Zddededededdf
 fdd	Zd
ejdejfddZ	  Z
S )Glm4vVisionPatchMergerFrq   context_dimrY   rP   r)   Nc                    st   t    tj|||d| _t|| _tj|||d| _tj|||d| _tj|||d| _	t
 | _t| | _d S rQ   )r*   r+   r,   rU   ri   r   post_projection_normrV   rW   rX   GELUact1r	   rZ   )r2   rq   r   rY   rP   r4   r6   r7   r+   x   s   


zGlm4vVisionPatchMerger.__init__r^   c                 C   s:   |  |}| | |}| | | || | S r\   )ri   r   r   rX   rZ   rV   rW   r]   r6   r6   r7   rD      s   
 zGlm4vVisionPatchMerger.forwardr_   )rI   rJ   rK   r   strr`   r+   r.   rM   rD   rN   r6   r6   r4   r7   r   w   s    $
r   c                       s2   e Zd Zdef fddZdejfddZ  ZS )Glm4vVisionEmbeddingsr[   c                    s^   t    || _|j| _|j| _|j| _| j| j d | _| j| _t	
| j| j| _d| _d S )Nr9   bicubic)r*   r+   r[   r3   rg   
image_sizerd   num_patchesnum_positionsr,   	Embeddingposition_embeddinginterpolated_methodr2   r[   r4   r6   r7   r+      s   

zGlm4vVisionEmbeddings.__init__r)   c                    sd  | j j}|jd }|j}ttrtj|tjd|jd }	t	|	d }
|
|
|
|ddddj|tjd}t fddttD j|tjd}t fddttD j|tjd}|d | d d }|d | d d }tj||fd	d
dd}tj||| jddd}|dd	dd}||j|j}|| }|S )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.
        r!   ry   r   g      ?r9   c                    "   g | ]} |d f  | qS r!   repeat.0iimage_shapeslengthsr6   r7   
<listcomp>      " z1Glm4vVisionEmbeddings.forward.<locals>.<listcomp>c                    r   )r9   r   r   r   r6   r7   r      r   r:   rq   Fborder)modealign_cornerspadding_mode)r   r0   rF   rz   
isinstancelistr.   tensorlongr   rk   permute	unsqueezer=   r>   catrangelenstackFgrid_sampler   squeezer<   )r2   
embeddingsr   r   h_coordsw_coordspos_embed_weightr3   rz   orig_size_sq	orig_sizepos_embed_2dtarget_htarget_wnorm_wnorm_hgridinterpolated_embed_fp32adapted_pos_embed_fp32adapted_pos_embedr6   r   r7   rD      s:   



""zGlm4vVisionEmbeddings.forwardrm   r6   r6   r4   r7   r      s    r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )*Rotates half the hidden dims of the input..Nr:   r9   r   )rF   r.   r   xx1x2r6   r6   r7   rotate_half   s   r   qkcossinr)   c                 C   s   | j }|j }|  | } }|d |d }}| | t| |  }|| t||  }||}||}||fS )N)r<   rL   r   r   r=   )r   r   r   r   orig_q_dtypeorig_k_dtypeq_embedk_embedr6   r6   r7   apply_rotary_pos_emb_vision   s   

r   r8   n_repc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r!   N)rF   expandreshape)r8   r   batchnum_key_value_headsslenhead_dimr6   r6   r7   	repeat_kv   s
   0r           modulequerykeyvalueattention_maskscalingdropoutkwargsc                 K   s   t || j}t || j}	t||dd| }
|d ur |
| }
tjj|
dtjd	|j
}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr9   r   r:   rq   r<   )ptrainingr!   )r   num_key_value_groupsr.   matmul	transposer,   
functionalsoftmaxr>   r=   r<   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputr6   r6   r7   eager_attention_forward   s   
r   c                       sf   e Zd Zdeddf fddZ		ddejdejdejdB d	eejejf dB dejf
d
dZ  Z	S )Glm4vVisionAttentionr[   r)   Nc                    s   t    |j| _|j| _| j| j | _d| _tj|j|jd |j	d| _
tj|j|jdd| _| jd | _|| _|j| _d| _d S )Nr!   r   rR   F      )r*   r+   r3   rq   	num_headsr   r   r,   rU   attention_biasqkvri   r   r[   attention_dropout	is_causalr   r4   r6   r7   r+     s   

zGlm4vVisionAttention.__init__r8   
cu_seqlensrotary_pos_embposition_embeddingsc                    sr  |j d }||djdddddd\}}}	|\}
}t|||
|\}}|ddd}|ddd}|	ddd}	t	
jjt tjr~|dd  |d d   } |||	fd jjsndnj||||dd\}}n,|dd  |d d  fd	d
|||	fD } fdd
t| D }tj|dd}||d }|}|S )Nr   r   r:   r!   r9   r   F)r   r   r   cu_seq_lens_qcu_seq_lens_kmax_length_qmax_length_kr   c                    s    g | ]}t j|  d dqS )r9   r   )r.   splittolist)r   r   )r   r6   r7   r   G  s    z0Glm4vVisionAttention.forward.<locals>.<listcomp>c              	      sD   g | ]\}}} |||fd j jsdnjddd qS )Nr   F)r   r   r   r   r   )r   r   r   )r   r   r   v)attention_interfacer   r2   r6   r7   r   K  s$    	
r   )rF   r   r   r   r   unbindr   r   r   r   get_interfacer[   _attn_implementationr   r   maxr   r   r   zipr.   r   r   ri   )r2   r8   r   r   r   r   
seq_lengthquery_statesr   r   r   r   
max_seqlenr   _splitsattn_outputsr6   )r   r   r   r2   r7   rD     sR   
(


zGlm4vVisionAttention.forwardNN)
rI   rJ   rK   r$   r+   r.   rM   rE   rD   rN   r6   r6   r4   r7   r     s    r   c                       s^   e Zd Zd fddZ		ddejdejdejdB deejejf dB dejf
d	d
Z  ZS )Glm4vVisionBlockr)   Nc                    sJ   t    t|j|jd| _t|j|jd| _t|| _t	|dd| _
d S )Nr(   FrR   )r*   r+   r&   r3   rms_norm_epsnorm1norm2r   attnrO   mlpr   r4   r6   r7   r+   a  s
   

zGlm4vVisionBlock.__init__r8   r   r   r   c                 K   s<   || j | |f|||d| }|| | | }|S )N)r   r   r   )r  r  r  r  )r2   r8   r   r   r   r   r6   r6   r7   rD   h  s   zGlm4vVisionBlock.forwardr)   Nr  )	rI   rJ   rK   r+   r.   rM   rE   rD   rN   r6   r6   r4   r7   r	  `  s    r	  c                       s   e Zd ZU ejed< ddef fddZe			ddedB de	d de
dB d	ed
ef fddZe edd Zdd Z  ZS )Glm4vTextRotaryEmbeddingro   Nr[   c                    s   t    |j| _|j| _|| _| jjd | _| j}| jdkr$t	| j }|| j|\}| _
| jd|dd | jd| dd |jdg d| _d S )	N	rope_typedefaultro   Frt   original_inv_freqmrope_section)      r  )r*   r+   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr[   rope_parametersr  compute_default_rope_parametersr   attention_scalingrw   clonegetr  )r2   r[   rz   rope_init_fnro   r4   r6   r7   r+   ~  s   


z!Glm4vTextRotaryEmbedding.__init__rz   ztorch.deviceseq_lenr)   ztorch.Tensorc           	      C   st   | j d }| j dd}t| ddp| j| j }t|| }d}d|tjd|dtjdj	|tj
d	|   }||fS )
a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetapartial_rotary_factorrs   r   Nr   r9   rj   ry   )r  r  getattrr3   num_attention_headsr   r.   rv   int64r=   rL   )	r[   rz   r!  baser#  r   rq   attention_factorro   r6   r6   r7   r    s   
&z8Glm4vTextRotaryEmbedding.compute_default_rope_parametersc           
      C   s  | j d d d d d f  d|jd dd}|d d d d d d d f  }t|jjtr7|jjdkr7|jjnd}t|dd2 | |  	dd}| 
|| j}tj||fdd	}| | j }| | j }	W d    n1 stw   Y  |j|jd
|	j|jd
fS )Nr   r!   r:   mpscpuF)device_typeenabledr9   r   rj   )ro   rL   r   rF   r   rz   typer   r   r   apply_mroper  r.   r   r   r  r   r=   r<   )
r2   r   position_idsinv_freq_expandedposition_ids_expandedr+  r}   embr   r   r6   r6   r7   rD     s   , &z Glm4vTextRotaryEmbedding.forwardc                 C   s2   |}|j |dd}tjdd t|D dd}|S )Nr:   r   c                 S   s   g | ]
\}}||d   qS )r   r6   )r   r   chunkr6   r6   r7   r     s    z8Glm4vTextRotaryEmbedding.apply_mrope.<locals>.<listcomp>)r   r.   r   	enumerate)r2   r}   r  sectionchunksresultr6   r6   r7   r.    s   z$Glm4vTextRotaryEmbedding.apply_mroper\   )NNN)rI   rJ   rK   r.   rM   r~   r#   r+   staticmethodr   r   rE   rL   r  no_gradr   rD   r.  rN   r6   r6   r4   r7   r  {  s(   
 

r  c                 C   s>   | ddddf }| ddddf }t j| |fdddS )	r   .r   Nr9   r!   r:   r   r   )r.   r   flattenr   r6   r6   r7   rotate_half_llm  s   r;  c                 C   s   | |}| |}|dd|jd d f jddd}|dd|jd d f jddd}|jd }| dd|f | d|df }}|dd|f |d|df }}	|| t||  }
|| t||  }tj|
|gdd}
tj||	gdd}|
|fS )a  Applies Rotary Position Embedding to the query and key tensors.

    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.
        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.
    .Nr:   r9   r   )r   rF   repeat_interleaver;  r.   r   )r   r   r   r   unsqueeze_dim
rotary_dimq_rotq_passk_rotk_passr   r   r6   r6   r7   apply_rotary_pos_emb  s   

$$
""rC  c                       s   e Zd ZdZddededB f fddZ				ddejde	ejejf dB d	ejdB d
e
dB dejdB dee de	ejejdB e	ej dB f fddZ  ZS )Glm4vTextAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper.
    and "Generating Long Sequences with Sparse Transformers".
    Nr[   	layer_idxc                    s   t    || _|| _|j| _|j| _| j| j | _|j| _| j| j | _	d| _
|j| _|j| _| jd | _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j | jdd| _d S )NTr   rR   F)r*   r+   r[   rE  r3   r%  r   r   r   r   r   r   r  r   r,   rU   q_projk_projv_projo_projr2   r[   rE  r4   r6   r7   r+     s    
 zGlm4vTextAttention.__init__r8   r   r   past_key_valuescache_positionr   r)   c                 K   s"  |  \}}}	| |}
| |}| |}|
||d| jdd}
|||d| jdd}|||d| jdd}|\}}t|
|||\}
}|d ur_|||d}|||| j	|\}}t
| jjt}|| |
|||f| jssdn| j| jd|\}}|||d }| |}||fS )Nr:   r!   r9   )r   r   rL  r   )r   r   )sizerF  rG  rH  rk   r   r   rC  updaterE  r   r   r[   r   r   r   r   r   r   r   rI  )r2   r8   r   r   rK  rL  r   bszq_lenr  r  r   r   r   r   cache_kwargsr   r   r   r6   r6   r7   rD     s<   	




zGlm4vTextAttention.forwardr\   NNNN)rI   rJ   rK   __doc__r#   r   r+   r.   rM   rE   r
   
LongTensorr   r   rD   rN   r6   r6   r4   r7   rD    s,    rD  c                       s2   e Zd Z fddZdejdejfddZ  ZS )Glm4vTextMLPc                    sP   t    || _tj|jd|j dd| _tj|j|jdd| _t	|j
 | _d S )Nr9   FrR   )r*   r+   r[   r,   rU   r3   rT   gate_up_projrX   r	   rY   activation_fnr   r4   r6   r7   r+   @  s
   
zGlm4vTextMLP.__init__r8   r)   c                 C   s4   |  |}|jddd\}}|| | }| |S )Nr9   r:   r   )rV  r3  rW  rX   )r2   r8   	up_statesgater6   r6   r7   rD   H  s   

zGlm4vTextMLP.forward)rI   rJ   rK   r+   r.   FloatTensorrD   rN   r6   r6   r4   r7   rU  ?  s    rU  c                       s   e Zd Zdedef fddZe						ddejde	ejejf dB d	ejdB d
ej
dB dedB dedB dej
dB de	eje	ejejf dB f fddZ  ZS )Glm4vTextDecoderLayerr[   rE  c                    st   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
t|j|jd| _t|j|jd| _d S )Nr
  )r*   r+   r3   rD  	self_attnrU  r  r&   r  input_layernormpost_attention_layernormpost_self_attn_layernormpost_mlp_layernormrJ  r4   r6   r7   r+   R  s   

zGlm4vTextDecoderLayer.__init__NFr8   r   r   r/  rK  	use_cacherL  r)   c              
   K   sr   |}	|  |}| jd|||||||d|\}}
| |}|	| }|}	| |}| |}| |}|	| }|S )N)r8   r   r   r/  rK  ra  rL  r6   )r]  r\  r_  r^  r  r`  )r2   r8   r   r   r/  rK  ra  rL  r   residualr  r6   r6   r7   rD   \  s*   





zGlm4vTextDecoderLayer.forward)NNNNFN)rI   rJ   rK   r#   r   r+   r   r.   rM   rE   rT  r
   r`   rZ  rD   rN   r6   r6   r4   r7   r[  Q  s4    

r[  zJ
    Base class for Llava outputs, with hidden states and attentions.
    )custom_introc                   @   sr   e Zd ZU dZdZejdB ed< dZe	dB ed< dZ
eej dB ed< dZeej dB ed< dZejdB ed< dS )Glm4vModelOutputWithPasta[  
    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.
    rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
        The rope index difference between sequence length and multimodal rope.
    Nlast_hidden_staterK  r8   
attentionsrope_deltas)rI   rJ   rK   rS  re  r.   rZ  r~   rK  r
   r8   rE   rf  rg  rT  r6   r6   r6   r7   rd    s   
 
rd  c                       sX   e Zd ZU eed< dZdZdZddgZdZ	dZ
dZdZdZeedZ fd	d
Z  ZS )Glm4vPreTrainedModelr[   model)imagevideotextTr[  r	  rK  r8   rf  c                    sR   t  | t|tr'd|jtjd|jdtjd|j   }t	
|j| d S d S )Nrs   r   r9   rj   )r*   _init_weightsr   rn   rr   r.   rv   rq   rL   initcopy_ro   )r2   r   ro   r4   r6   r7   rn    s
   
&z"Glm4vPreTrainedModel._init_weights)rI   rJ   rK   r"   r~   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraph_supports_attention_backendr[  rD  _can_record_outputsrn  rN   r6   r6   r4   r7   rh    s   
 rh  c                       sv   e Zd ZU eed< dZdgZeedZ	d fddZ
d	d
 Zeeedejdejdee deeB fddZ  ZS )Glm4vVisionModelr[   )rj  rk  r	  rm  r)   Nc                    s   t     j| _ j| _t | _t | _ j j	 }t
|d | _t fddt jD | _t j j jd| _t j jd| _tj j j j jd| _t j jd| _d| _|   d S )Nr9   c                    s   g | ]}t  qS r6   )r	  )r   r  r[   r6   r7   r     s    z-Glm4vVisionModel.__init__.<locals>.<listcomp>)rq   r   rY   r
  )rf   out_channelsrb   rc   F)r*   r+   spatial_merge_sizerd   r   r   ra   patch_embedr3   r   rn   r   r,   
ModuleListr   depthblocksr   rS   rT   rY   mergerr&   r  post_conv_layernormConv2d
downsamplepost_layernormgradient_checkpointing	post_init)r2   r[   r   r4   r|  r7   r+     s*   

 zGlm4vVisionModel.__init__c                 C   s  g }|D ]e\}}}t |dd|}||| j | j|| j | j}|dddd}| }t |d|d}||| j | j|| j | j}|dddd}| }|t j	||gdd
|d qt j|dd}|d d dd f  }| |}	|	| d}
|
|fS )Nr!   r:   r   r9   r   r   )r.   rv   r   r   r   r~  r   r:  appendr   r   r   r   r   )r2   grid_thwpos_idsthwhpos_idswpos_idsmax_grid_sizerotary_pos_emb_fullr   r6   r6   r7   rot_pos_emb  s4   "
zGlm4vVisionModel.rot_pos_embr8   r  r   c              	   K   s|  |  |}| |}| |\}}tj||fdd}| | f}t|dddf |dddf  |dddf jdtj	
 rE|jntjd}tj|ddd	}|dd |dd   }	| ||	||dddf |j|dddf |j}| jD ]}
|
|f||d
|}q| |}|d| j| j|jd }|dddd}| |d| jj}| |}t||dS )a\  
        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   Nr!   r9   r   r   )r!   r   )r   )r   r   r   )re  pooler_output)r  r  r  r.   r   r   r   r<  cumsumjit
is_tracingr<   int32r   padr   r   r=   rz   r  r  rk   r~  rF   r   r  r[   rS   r  r   )r2   r8   r  r   r   image_type_idsr2  r   r   seqlensblkmerged_hidden_statesr6   r6   r7   rD     sL   

4


zGlm4vVisionModel.forwardr  )rI   rJ   rK   r$   r~   rr  rt  r	  r   rz  r+   r  r   r    r   r.   rM   r   r   rE   r   rD   rN   r6   r6   r4   r7   r{    s*   
 r{  c                       s   e Zd ZU eed< dZdef fddZeee								dde
jdB de
jdB de
jdB d	edB d
e
jdB dedB de
jdB dee deeB fddZ  ZS )Glm4vTextModelr[   )rl  c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r6   )r[  )r   rE  r|  r6   r7   r   C      z+Glm4vTextModel.__init__.<locals>.<listcomp>r
  r|  F)r*   r+   pad_token_idpadding_idx
vocab_sizer,   r   r3   embed_tokensr  r   num_hidden_layerslayersr&   r  normr  
rotary_embr  r  r   r4   r|  r7   r+   <  s   zGlm4vTextModel.__init__N	input_idsr   r/  rK  inputs_embedsra  rL  r   r)   c              	   K   sv  |d u |d uA rt d|r|d u rtj st| jd}|d u r&| |}|d u rB|d ur2| nd}	tj|	|	|j	d  |j
d}|d u rV|dddd|j	d d}n|jdkrg|d	 d|j	d d}|jdkr~|j	d d
kr~|d }
|dd  }nd }
| j|||||
d}tdi |}|}| j||d}| jD ]}||f||
|||d|}|}q| |}t||dS )N:You must specify exactly one of input_ids or inputs_embedsr|  r   r!   rz   r:   r   r9   N.   )r[   r  r   rL  rK  r/  )r/  )r   r/  rK  rL  r   )re  rK  r6   )
ValueErrorr.   r  r  r   r[   r  get_seq_lengthrv   rF   rz   rk   r   ndimr   r  r  r  r   )r2   r  r   r/  rK  r  ra  rL  r   past_seen_tokenstext_position_idsmask_kwargscausal_maskr8   r   decoder_layerlayer_outputsr6   r6   r7   rD   L  s^   
 
	
	
zGlm4vTextModel.forward)NNNNNNN)rI   rJ   rK   r#   r~   rr  r+   r   r   r    r.   rT  rM   r
   rZ  r`   r   r   rE   r   rD   rN   r6   r6   r4   r7   r  7  sB   
 	
r  c                       s(  e Zd ZdZi ZdZddgZ fddZdd Zd	d
 Z					d'de
jdB de
jdB de
jdB de
jdB dee
je
jf f
ddZee	d(de
jde
jdB dee deeB fddZee	d(de
jde
jdB dee deeB fddZ		d)de
jde
jde
jdB de
jdB fddZ				d'de
jdB de
jdB de
jdB de
jdB de
jdB de
jdB de
jdB fd d!Zee											d*de
jdB de
jdB d"e
jdB dedB de
jdB de
jdB de
jdB de
jdB de
jdB d#e
jdB d$e
jdB dee deeB fd%d&Z  ZS )+
Glm4vModelri  Fr[  r	  c                    s:   t  | t|j| _t|j| _d | _	| 
  d S r\   )r*   r+   r{  _from_configvision_configvisualr  text_configlanguage_modelrg  r  r   r4   r6   r7   r+     s
   zGlm4vModel.__init__c                 C   
   | j  S r\   )r  get_input_embeddingsrG   r6   r6   r7   r       
zGlm4vModel.get_input_embeddingsc                 C      | j | d S r\   )r  set_input_embeddingsr2   r   r6   r6   r7   r       zGlm4vModel.set_input_embeddingsNr  image_grid_thwvideo_grid_thwr   r)   c           /   
   K   s  | j jj}| j j}| j j}| j j}	g }
|}|du rt|}tjd|j	d |j	d |j
|jd}d\}}d}|dur>| nd}|durH| nd}||j}t|D ]\}}||| dk }| }g }d}|D ],}||krtd}n||	krzd}||kr|s|d	 qk||kr|r|d
 qk|d qkg }tt|dd D ]\}}t|}|d d }|d d d }||||f qg }d}|D ]\}}} t|dkr|d  d nd}!|d	kr>|| \}"}#}$|"|#| |$| }%}&}'t|%ddd|&|'  }(t|&ddd|%d|' })t|'ddd|%|&d }*|t|(|)|*g|!  |d7 }d}q|d
kr|| \}+}#}$|}"|"|#| |$| }%}&}'t|%D ]C},t|,ddd|&|'  }(t|&ddddd|' })t|'dddd|&d }*|t|(|)|*g|!  q\|d7 }||| d kr|d7 }d}|d7 }q| | }-|t|-dddd|!  d}qtj|dddd}.|.|j|d||| dkf< |
|. d t||   qTtj|
|jdd}
||
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)`)
        Nr   r   r!   r<   rz   )r   r   FTrj  rk  rl  c                 S   s   | d S )Nr!   r6   )r   r6   r6   r7   <lambda>  s    z+Glm4vModel.get_rope_index.<locals>.<lambda>r:   r   .r  )r[   r  r~  image_token_idvideo_start_token_idvideo_end_token_idr.   	ones_liker/   rF   r<   rz   r   r=   r4  r  	itertoolsgroupbyr   r   r   rv   rk   r   r:  r   r   r   r   r   r   )/r2   r  r  r  r   r   r~  r  r  r  mrope_position_deltastotal_input_idsr/  image_indexvideo_indexvideo_group_indeximage_grid_thw_listvideo_grid_thw_listr   input_tokensinput_token_typevideo_check_flgtokeninput_type_groupr   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_indexr  t_idxtext_lenllm_positionsr6   r6   r7   get_rope_index  s   
<
 

"""

"""
$ zGlm4vModel.get_rope_indexpixel_values_videosr   c                 K   s   | | jj}g }| }|D ]\}}}td||gd|d}	||	 qtj	|dd}
| j|f|
dd|}|
d| jjd   }t|j|}||_|S )[  
        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.
        r!   r   r   Tr  return_dictr:   r9   )r-  r  r<   r   r.   r   r   r   r  r   prodr~  r   r  )r2   r  r  r   temp_frames_hwr  r  r  r  repeated_rowflattened_video_grid_thwvision_outputssplit_sizesvideo_embedsr6   r6   r7   get_video_featuresO  s$   zGlm4vModel.get_video_featurespixel_valuesc                 K   sX   | | jj}| j|f|dd|}|d| jjd   }t|j|}||_|S )T  
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input images.
        image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
            The temporal, height and width of feature shape of each image in LLM.
        Tr  r:   r9   )	r-  r  r<   r  r~  r   r.   r   r  )r2   r  r  r   r  r  image_embedsr6   r6   r7   get_image_featuresn  s   zGlm4vModel.get_image_featuresr  image_featuresvideo_featuresc           	      C   s.  |du r3||   tj| jjtj|jdk}|d}||   tj| jjtj|jdk}|d}n|| jjk}|| jjk}|	 }|
d||j}|durit||  | kd| d|jd   |	 }|
d||j}|durt||  | kd| d|jd   ||f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.
        Nr  r:   z6Image features and image tokens do not match, tokens: z, features: r   z6Video features and video tokens do not match, tokens: )r  r.   r   r[   r  r   rz   allvideo_token_idsumr   	expand_asr=   r   numelrF   )	r2   r  r  r  r  special_image_maskspecial_video_maskn_image_tokensn_video_tokensr6   r6   r7   get_placeholder_mask  s4   
zGlm4vModel.get_placeholder_maskrK  c                 C   s.  |d u rdn|  }|d uo|d up|d u}|r1| jd u s!|dkr1| j||||d\}	}
|
| _|	S | jd ur|j\}}}|d urb| dd }	|	|dkd}	|	d|dddd	|j
}	nt||| }	|	dddd|d	|j
}	| jj|| jjd  dd}|	|j	|	j
d }	|	S d }	|	S )Nr   )r  r  r   r:   r!   r   r   r  )r  rg  r  rF   r   r  masked_fillrk   r   r=   rz   r.   rv   r   r<  )r2   r  r  r  r  r   rK  past_key_values_lengthcan_compute_mroper/  rg  
batch_sizer  r  deltar6   r6   r7   compute_3d_position_ids  s0   	

" z"Glm4vModel.compute_3d_position_idsr/  rg  rL  c              	   K   s(  |du |duA rt d|du r|  |}|dur@| j||ddj}tj|dd|j|j}| j	|||d\}}|
||}|durj| j||	ddj}tj|dd|j|j}| j	|||d\}}|
||}|du ry| j|||	|||d	}| jdd|||||d
|}tdi |d| ji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  T)r  r   r   )r  )r  )r  r  r  r  r   rK  )r  r/  r   rK  r  rL  rg  r6   )r  r  r  r  r.   r   r=   rz   r<   r	  masked_scatterr  r  r  rd  rg  )r2   r  r   r/  rK  r  r  r  r  r  rg  rL  r   r  
image_maskr  r  
video_maskoutputsr6   r6   r7   rD     sL   	
zGlm4vModel.forwardrR  r\   r  )NNNNNNNNNNN)rI   rJ   rK   rq  _checkpoint_conversion_mappingaccepts_loss_kwargsrt  r+   r  r  r.   rT  rM   rE   r  r   r   rZ  r   r   r   r  r  r	  r  r
   rd  rD   rN   r6   r6   r4   r7   r    s    	
 
.
%	
r  zQ
    Base class for Glm4v causal language model (or autoregressive) outputs.
    c                   @   s   e Zd ZU dZdZejdB ed< dZejdB ed< dZ	e
dB ed< dZeej dB ed< dZeej dB ed< dZejdB ed< dS )	Glm4vCausalLMOutputWithPasta  
    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.
    rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
        The rope index difference between sequence length and multimodal rope.
    NlosslogitsrK  r8   rf  rg  )rI   rJ   rK   rS  r  r.   rZ  r~   r  rK  r
   r8   rE   rf  rg  rT  r6   r6   r6   r7   r    s   
 r  c                        s  e Zd Zi ZddiZdZ fddZdd Zdd	 Ze		
d,de
jde
jd
B dee deeB fddZe		
d,de
jde
jd
B dee deeB fddZee		
	
	
	
	
	
	
	
	
	
	
	d-de
jd
B de
jd
B de
jd
B ded
B de
jd
B de
jd
B de
jd
B de
jd
B de
jd
B de
jd
B de
jd
B dee
jB dee deeB fddZ	
	
	
	
	
	 	
	
	
	
	d. fd!d"	Z fd#d$Z	
d,de
jd
B de
jd
B dee
je
jf fd%d&Z	'		
d/d(ed)ede
jd
B dee
jeeef f fd*d+Z   Z!S )0Glm4vForConditionalGenerationzlm_head.weightz(model.language_model.embed_tokens.weightFc                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S )NFrR   )r*   r+   r  ri  r,   rU   r  r3   r  lm_headr  r   r4   r6   r7   r+   ;  s   
z&Glm4vForConditionalGeneration.__init__c                 C   r  r\   )ri  r  rG   r6   r6   r7   r  B  r  z2Glm4vForConditionalGeneration.get_input_embeddingsc                 C   r  r\   )ri  r  r  r6   r6   r7   r  E  r  z2Glm4vForConditionalGeneration.set_input_embeddingsNr  r  r   r)   c                 K      | j jd||d|S )r  )r  r  Nr6   )ri  r  )r2   r  r  r   r6   r6   r7   r  H  s
   z0Glm4vForConditionalGeneration.get_video_featuresr  r  c                 K   r  )r  )r  r  Nr6   )ri  r  )r2   r  r  r   r6   r6   r7   r  Y  s   z0Glm4vForConditionalGeneration.get_image_featuresr   r  r   r/  rK  r  labelsrL  logits_to_keepc                 K   s   | j d||||	|
|||||d
|}|d }t|tr"t| dn|}| |dd|ddf }d}|durC| j||| jjjd}t	|||j
|j|j|jd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.

        Example:

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

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

        >>> messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
                    {"type": "text", "text": "What is shown in this image?"},
                ],
            },
        ]
        >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> 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 ..."
        ```)
r  r  r  r  r  r/  r   rK  r  rL  r   N)r  r  r  )r  r  rK  r8   rf  rg  r6   )ri  r   r   slicer  loss_functionr[   r  r  r  rK  r8   rf  rg  )r2   r  r   r/  rK  r  r  r  r  r  r  rL  r  r   r  r8   slice_indicesr  r  r6   r6   r7   rD   h  s8   <z%Glm4vForConditionalGeneration.forwardTc                    sH   t  j|f|||||||	|
|||d|}|s"|r"d |d< d |d< |S )N)rK  r   r  rL  r/  r  r  r  r  ra  is_first_iterationr  r  )r*   prepare_inputs_for_generation)r2   r  rK  r   r  rL  r/  ra  r  r  r  r  r!  r   model_inputsr4   r6   r7   r"    s*   z;Glm4vForConditionalGeneration.prepare_inputs_for_generationc           
         s<  t  ||}d}|d }d ur| }|dkr*| jjd ur*|d | jj }|S d|v r;|d jd dkr;|d }t|jdkoJ|jt	j
t	jfv }|ru|dd us[|dd urud	d
 | D }| jj|fi |\}}	|	| j_n|dddd}t	j|jd dt	j|jd| j_|d }t	j||gdd}|S )Nr   rK  r  r  r!   r9   r  r  c                 S   s   i | ]\}}|d kr||qS )r  r6   )r   r   r   r6   r6   r7   
<dictcomp>      zVGlm4vForConditionalGeneration._prepare_position_ids_for_generation.<locals>.<dictcomp>r   r:   r  r   )r*   $_prepare_position_ids_for_generationr  r  ri  rg  rF   r   r<   r.   r   r   itemsr  r   r   zerosrz   r   )
r2   inputs_tensormodel_kwargstext_positionspast_lengthcacher/  is_input_idsvision_positionsrg  r4   r6   r7   r&    s,    

zBGlm4vForConditionalGeneration._prepare_position_ids_for_generationc                 C   s   |durA||   tj| jjtj|jdkd }||   tj| jjtj|jdkd }||   tj| jjtj|jdkd }n|| jjk}|| jjk}|| jjk}tj	|
 |
  dd}|dk}|| @ }|jdd}	|jd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)`)
        Nr  ).r   r!   r   r   )r  r.   r   r[   image_start_token_idr   rz   r  r  r  r   r  )r2   r  r  is_imageis_video_startis_video_endvideo_levelinside_videostandalone_imagesimage_countsvideo_countsr6   r6   r7   _get_image_nums_and_video_nums  s>   
z<Glm4vForConditionalGeneration._get_image_nums_and_video_numsr!   expand_sizeis_encoder_decoderc                    s    dkrfS g d fdd} fdd}|d ur+j  dd||rDd	d u r<td
|d	 d	< fS )Nr!   )r  r  r  r  second_per_grid_tsc           	         s6   dd } dd }j dd d\}}dd }| D ]y}|dkr@t|t|}dd	 |D }|| | | d
| |< q|dkrTt|}|| | | d
| |< q|dkrst|t|}dd	 |D }|| | | d
| |< q|dkrt|}|| | | d
| |< q|dkr|| | t| d
| |< q| S )Nr  r  r  )r  c                    sD   t | |}|gdg|  d    t j fdd|D dd}|S )Nr!   c                    s   g | ]}|j   qS r6   r   r   samplerepeat_argsr6   r7   r   d  r  zGlm4vForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visual.<locals>._repeat_interleave_samples.<locals>.<listcomp>r   r   )r.   r   rq   r   )r   r   repeat_timessamplesr7  r6   r?  r7   _repeat_interleave_samplesa  s   zGlm4vForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visual.<locals>._repeat_interleave_samplesr  c                 S      g | ]}t j|d d qS r!   r   r.   r  r  r=  r6   r6   r7   r   l  r%  z{Glm4vForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visual.<locals>.<listcomp>)r   rA  r  c                 S   rD  rE  rF  r=  r6   r6   r7   r   x  r%  r<  )r  r9  r.   r   r   )	dict_to_expandr  r  
image_nums
video_numsrC  r   rB  r   )r:  r  r*  r2   r6   r7   "_expand_dict_for_generation_visualZ  sF   





zgGlm4vForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visualc                    s~   | D ]:}|dkr| | j dkr| | j dd| |< q|dkr<| | d ur<t| | tjr<|vr<| | j dd| |< q| S )Nr/  r   r!   r   rL  r   )r  r<  r   r.   rM   )rG  r   )r:  visual_keysr6   r7   _expand_dict_for_generation  s   z`Glm4vForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generationr   r   encoder_outputszMIf `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.)r<  r  r  )r2   r:  r;  r  r*  rJ  rL  r6   )r:  r  r*  r2   rK  r7   _expand_inputs_for_generationI  s   -z;Glm4vForConditionalGeneration._expand_inputs_for_generationr\   )NNNNNNNNNNNr   )NNNNNTNNNNF)r!   FN)"rI   rJ   rK   r  _tied_weights_keysr  r+   r  r  r   r.   rZ  rT  r   r   rE   r   r  r  r   rM   r
   r   r  rD   r"  r&  r9  r`   dictr   r   rN  rN   r6   r6   r4   r7   r  5  s    	
^('
:r  )r  r  rh  r  r{  )r   r   )[r  collections.abcr   dataclassesr   typingr   r   r.   torch.nnr,   torch.nn.functionalr   r   r    r   ro  activationsr	   cache_utilsr
   r   
generationr   integrationsr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   r   utils.output_capturingr    configuration_glm4vr"   r#   r$   Moduler&   rO   ra   rn   r   r   r   rM   rE   r   r   r   rL   r   r   r	  r  r;  rC  rD  rU  r[  rd  rh  r{  r  r  r  r  __all__r6   r6   r6   r7   <module>   s   K

SM
(H4 k  v  p