
    qi                     x   d dl Z d dlmZ d dlmZ d dlZd dlmZ ddlm	Z	 ddl
mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZ e G d de             Ze ed       G d de                    Ze G d de             Ze ed       G d de                    Z G d dee      Z g dZ!y)    N)	dataclass)Any   )Cache)GenerationMixin)BaseModelOutputWithPoolingModelOutput)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupletorch_compilable_check   )	AutoModel   )Glm46VConfigc                   @    e Zd ZU eed<   dZdZdZdZdZ	dZ
dZdZdZdZy)Glm46VPreTrainedModelconfigmodel)imagevideotextTNpast_key_values)__name__
__module____qualname__r   __annotations__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_backend_can_record_outputs     \/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/glm46v/modeling_glm46v.pyr   r   '   sC    1&*#"3N!"&r+   r   zJ
    Base class for Llava outputs, with hidden states and attentions.
    )custom_introc                       e Zd ZU dZdZej                  dz  ed<   dZe	dz  ed<   dZ
eej                     dz  ed<   dZeej                     dz  ed<   dZej                  dz  ed<   y)Glm46VModelOutputWithPasta[  
    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_stater   hidden_states
attentionsrope_deltas)r   r   r   __doc__r0   torchFloatTensorr   r   r   r1   tupler2   r3   
LongTensorr*   r+   r,   r/   r/   7   sv     37u((4/6$(OUT\(59M5**+d2926Je''(4/6+/K!!D(/r+   r/   c                    j    e Zd ZdZi ZdZdZ fdZd Zd Z		 	 	 	 d$de
dee
e
e
f   ej                  z  d	e
d
e
de
deej                  z  dz  fdZ	 	 	 d%dej"                  dej$                  dej"                  dz  dej"                  dz  dej                  dz  deej                  ej                  f   fdZee	 d&dej.                  dej"                  dz  dee   deez  fd              Zee	 d&dej.                  dej"                  dz  dee   deez  fd              Z	 	 d'dej"                  dej.                  dej.                  dz  dej.                  dz  fdZ	 	 	 	 	 d(dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dej$                  dz  dej                  dz  fdZee	 	 	 	 	 	 	 	 	 	 	 	 d)dej"                  dz  dej                  dz  d ej"                  dz  dedz  dej.                  dz  dej                  dz  dej.                  dz  dej"                  dz  dej"                  dz  d!ej"                  dz  dej$                  dz  d"ej"                  dz  dee   dee z  fd#              Z! xZ"S )*Glm46VModelr   FNc                     t         |   |       t        j                  |j                        | _        t        j                  |j                        | _        d | _        | j                          y N)
super__init__r   from_configvision_configvisualtext_configlanguage_modelr3   	post_initselfr   	__class__s     r,   r>   zGlm46VModel.__init__W   sU     ++F,@,@A'33F4F4FG 	r+   c                 6    | j                   j                         S r<   )rC   get_input_embeddingsrF   s    r,   rI   z Glm46VModel.get_input_embeddings`   s    ""7799r+   c                 :    | j                   j                  |       y r<   )rC   set_input_embeddingsrF   values     r,   rL   z Glm46VModel.set_input_embeddingsc   s    007r+   start_positiongrid_thwtemp_merge_sizespatial_merge_sizetime_intervaldevicec                    |d   j                         |z  |d   j                         |z  |d   j                         |z  }	}}||	z  |z  }
t        j                  |||	z   |      j                  ||z        }t        j                  |||z   |      j	                  |	|z        }t        j
                  |
f||t        j                        }||z  }t        j                  |||gd      }|S )a  
        Compute 3D positional indices for vision tokens derived from a single image or video input.

        The positions are generated from the input grid defined by temporal (T), height (H), and
        width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
        merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.

        Args:
            start_position (`int`):
                Offset added to all computed positional indices.
            grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
                The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
            temp_merge_size (`int`, *optional*):
                Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
                by this value. Defaults to 1.
            spatial_merge_size (`int`, *optional*):
                Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
                by this value. Defaults to 1.
            time_interval (`int`, *optional*):
                Spacing factor applied between consecutive temporal position indices.Defaults to 1.
            device (`str` or `torch.device`, *optional*):
                Device on which the resulting tensor is allocated. If `None`, uses the current default device.

        Returns:
            torch.LongTensor of shape (3, sequence_length):
                Positional indices for temporal, height, and width dimensions,
                flattened into sequence form and offset by `start_position`.
        r   r   r   rT   )rT   dtypedim)itemr5   arangerepeatrepeat_interleavefulllongstack)rF   rO   rP   rQ   rR   rS   rT   
llm_grid_t
llm_grid_h
llm_grid_wimage_seq_lengthposition_widthposition_heightposition_temporalvision_position_idss                  r,   get_vision_position_idsz#Glm46VModel.get_vision_position_idsf   s   L QK/1QK"44QK"44 !+J
 &
2Z?nnz6QZ`ahh#
  ,,~~
7R[abtt#
 "JJ(8':NSYafakakl-=#kk+<o~*^def""r+   	input_idsmm_token_type_idsimage_grid_thwvideo_grid_thwattention_maskreturnc           	      0   | j                   j                  j                  }g }t        j                  d|j
                  d   |j
                  d   |j                  |j                        }	|t        |      nd|t        |      ndd}
t        |      D ]K  \  }}||   }|,|||   j                            }|||   j                            }g }t        j                  t        |j                               d       D ]7  \  }}t        |      }|d   d   }|d   d   dz   }|j                  |||f       9 d}d}g }|D ]  \  }}}|dk(  r^||z
  }|j                  t        j                   ||j                  	      j#                  dd      j%                  dd      |z          ||z  }j|d
k(  r%|dk(  rt'        |
|         }|dz  }|d   k\  rdn|}nt'        |
|         }|d   }| j)                  |||||j                  	      }|j                  |       |t+        |d   |d
         |z  z  } t        j,                  |d      j/                  dd      }|5|j1                  |	j                        |	dd|||   j                         f<   n"|j1                  |	j                        |	dd|f<   |j                  |j+                         dz   t3        |      z
         N t        j4                  ||j                  	      j7                  d      }|	|fS )u	  
        Calculate the 3D rope index based on image and video's sizes. The utility expects a `vision + text`
        sequence and will error out otherwise. For pure text sequence, please rely on model's auto-inferred
        position ids. In a mixed vision + text sequence, vision tokens use 3D RoPE (temporal, height, width)
        while text tokens use standard 1D RoPE.

        Example:
            Temporal patches: 3; Height patches: 2; Width patches: 2
            Each vision input results in (temporal x height × width) positions. Here: 3 x 2 × 2 = 12 positions total.

            Temporal position IDs are spaced by:
                `interval = tokens_per_second * temporal_patch_size / fps`

                If fps = 1; tokens_per_second = 25; temporal_patch_size = 2, temporal IDs increase by 50 for each temporal patch:
                `[0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]`

            Height IDs repeat per row: `[0, 0, 1, 1, ...]`
            Width IDs alternate per column: `[0, 1, 0, 1, ...]`
            Text tokens follow standard 1D RoPE and the position IDs grow consequently with a step of `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.
            mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, sequence_length)`):
                Token type ids matching each modality to a different value in the input sequence, i.e. text (0), image (1), video (2).
            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   r   rW   rT   N)r   r   c                     | d   S )Nr   r*   )xs    r,   <lambda>z,Glm46VModel.get_rope_index.<locals>.<lambda>   s    `abc`d r+   rV   r   rX   )r   r@   rR   r5   zerosshaperW   rT   iter	enumeratebool	itertoolsgroupbytolistlistappendr[   viewexpandnextri   maxcatreshapetolentensor	unsqueeze)rF   rj   rk   rl   rm   rn   kwargsrR   mrope_position_deltasposition_ids
grid_iters	batch_idxcurrent_input_idsinput_token_typeinput_type_groupkeygroupstart_index	end_indexcurrent_posvideo_group_indexllm_pos_ids_listmodality_type	start_idxend_idxtext_lenrP   rQ   rh   llm_positionss                                 r,   get_rope_indexzGlm46VModel.get_rope_index   sj   b "[[66II "{{OOAOOA//##
 (6'AtN#t'5'AtN#t


 -6i,@ 1	[(I(0;)$5nY6O6T6T6V$W!#3N94M4R4R4T#U !'//	:J:Q:Q:S0TVde G
UU#Ahqk!"IaL1,	 ''k9(EF	G K !!5E W1y' A%&2H$++Xi6F6FGLLQPRSZZ[\^`adoo  8+K %),1'+J},E'FH)Q.)1Bhqk1QAWh)#'
=(A#B '/qkO*.*F*F#X@R[d[k[k +G +' %++,?@3x{HQK#@DV#VVK7W8 "II&6A>FFq"MM)O\O_O_`l`s`sOtQ	>)+D+I+I+KKL-:-=-=l>Q>Q-RQ	\*!(():):)<q)@3GXCY)YZc1	[d !&-B9K[K[ \ f fgh i222r+   pixel_values_videosr   c                 4   |j                  | j                  j                        }g }|j                         }|D ]N  \  }}}t	        j
                  d||g      j                  d      j                  |d      }	|j                  |	       P t	        j                  |d      }
 | j                  |f|
dd|}|j                  d      | j                  j                  dz  z  j                         }t	        j                  |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   rX   TrP   return_dictru   r   )typerA   rW   r}   r5   r   r   r\   r   r   prodrR   splitpooler_output)rF   r   rm   r   temp_frames_hwvideo_grid_thw_listthwrepeated_rowflattened_video_grid_thwvision_outputssplit_sizesvideo_embedss                 r,   get_video_featureszGlm46VModel.get_video_features  s    266t{{7H7HI,335* 	0GAq! <<Aq	2<<Q?FFq!LL!!,/	0 $)99^#C $
*BPT
X^
 &**2.$++2P2PRS2SS[[]{{>#?#?M'3$r+   pixel_valuesc                 <   |j                  | j                  j                        } | j                  |f|dd|}|j                  d      | j                  j                  dz  z  j                         }t        j                  |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   ru   r   )	r   rA   rW   r   rR   r}   r5   r   r   )rF   r   rl   r   r   r   image_embedss          r,   get_image_featureszGlm46VModel.get_image_features2  s     $(():):;$\gNX\g`fg%**2.$++2P2PRS2SS[[]{{>#?#?M'3$r+   inputs_embedsimage_featuresvideo_featuresc                 T   || | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n2|| j                  j                  k(  }|| j                  j                  k(  }|j                         }|j                  d      j                  |      j                  |j                        }|At        ||   j                         |j                         k(  d| d|j                  d           |j                         }|j                  d      j                  |      j                  |j                        }|At        ||   j                         |j                         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.
        rq   ru   z6Image features and image tokens do not match, tokens: z, features: r   z6Video features and video tokens do not match, tokens: )rI   r5   r   r   image_token_idr_   rT   allvideo_token_idsumr   	expand_asr   r   numelrw   )	rF   rj   r   r   r   special_image_maskspecial_video_maskn_image_tokensn_video_tokenss	            r,   get_placeholder_maskz Glm46VModel.get_placeholder_maskH  s    !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!; "+dkk.H.H!H!*dkk.H.H!H+//1/99"=GGVYYZgZnZno%"01779^=Q=Q=SSHHXXdeseyeyz{e|d}~
 ,//1/99"=GGVYYZgZnZno%"01779^=Q=Q=SSHHXXdeseyeyz{e|d}~ "#555r+   r   c                 L   |dn|j                         }|d uxr |d uxr
 |d uxs |d u}	|	r3| j                  |dk(  r"| j                  |||||      \  }
}|| _        |
S | j                  5|j                  \  }}}|u|j	                         j                  d      dz
  }
|
j                  |dk(  d      }
|
j                  d|d      j                  ddd      j                  |j                        }
nVt        j                  |||z         }
|
j                  ddd      j                  d|d      j                  |j                        }
| j                  j                  || j                  j                  d   z  d      }|
|j                  |j                        z   }
|
S d }
|
S )Nr   )rl   rm   rn   rk   ru   r   r   rX   rV   )get_seq_lengthr3   r   rw   r_   cumsummasked_fillr   r\   r   rT   r5   r[   r   r]   )rF   rj   r   rl   rm   rn   r   rk   past_key_values_lengthcan_compute_mroper   r3   
batch_size
seq_length_deltas                   r,   compute_3d_position_idsz#Glm46VModel.compute_3d_position_idsr  s    '6&=?CaCaCcT! K!-Kt+I~T/I 	 $"2"2":>TXY>Y(,(;(;---"3 )< )%L+  +D   )(5(;(;%J
A)-224;;B?!C+77!8KQO+00JCJJ1aQRSVVWdWkWkl$||,BDZ]gDgh+00Ar:AA!ZQSTWWXeXlXlm$$66zTEUEUE[E[\]E^7^de6fE'%((-:N:N(*OOL   Lr+   r   r3   cache_positionc           
         |du |duz  rt        d      | | j                         |      }|| j                  ||d      j                  }t	        j
                  |d      j                  |j                  |j                        }| j                  |||      \  }}|j                  ||      }|| j                  ||	d      j                  }t	        j
                  |d      j                  |j                  |j                        }| j                  |||      \  }}|j                  ||      }|| j                  |||	||||	      } | 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.
        Nz:You must specify exactly one of input_ids or inputs_embedsT)r   r   rX   )r   )r   )rj   rl   rm   r   rn   r   rk   )rj   r   rn   r   r   r   r3   r*   )
ValueErrorrI   r   r   r5   r   r   rT   rW   r   masked_scatterr   r   rC   r/   r3   )rF   rj   rn   r   r   r   r   r   rl   rm   r3   rk   r   r   r   
image_maskr   r   
video_maskoutputss                       r,   forwardzGlm46VModel.forward  s   4 -t";<YZZ 7D557	BM#22<]a2bppL 99\q9<<]=Q=QS`SfSfgL 55i_k5lMJ)88\RM*223Fdh2iwwL 99\q9<<]=Q=QS`SfSfgL 55i_k5lMAz)88\RM77#--+- /"3 8 L &$%% 
%)+')
 
 ) 

((
 	
r+   )r   r   r   N)NNNr<   )NN)NNNNN)NNNNNNNNNNNN)#r   r   r   r    _checkpoint_conversion_mappingaccepts_loss_kwargsr#   r>   rI   rL   intr~   r5   TensorstrrT   ri   r8   	IntTensorr7   r   r   r   r6   r   r   r   r   r   r   r   r   r/   r   __classcell__rG   s   @r,   r:   r:   O   sQ   %'":8  !"#,06#6# sC}%46# 	6#
  6# 6# ell"T)6#x 3726.2s3##s3 !??s3 ((4/	s3
 ((4/s3 t+s3 
u||U\\)	*s3j  37".. ((4/ +,	
 
+	+  :  37'' ((4/ +,	
 
+	+  0 4837(6##(6 (((6 ))D0	(6
 ))D0(6\ /3.2.2/348)<<$&) ||d*) t+	)
 t+) t+) ,) !??T1) 
	)V  .2.204(,26,08<2626/34826B
##d*B
 t+B
 &&-	B

 B
 ((4/B
 llT)B
 #..5B
 ((4/B
 ((4/B
 %%,B
 !??T1B
 ((4/B
 +,B
 
*	*B
  B
r+   r:   zR
    Base class for Glm46V causal language model (or autoregressive) outputs.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
dz  ed<   dZeej                     dz  ed<   dZeej                     dz  ed<   dZej                  dz  ed<   y)	Glm46VCausalLMOutputWithPasta  
    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logitsr   r1   r2   r3   )r   r   r   r4   r   r5   r6   r   r   r   r   r1   r7   r2   r3   r8   r*   r+   r,   r   r     s     &*D%

d
")'+FE$+$(OUT\(59M5**+d2926Je''(4/6+/K!!D(/r+   r   c            "           e Zd Zi ZddiZdZ fdZd Zd Ze		 d de
j                  d	e
j                  dz  d
ee   deez  fd       Ze		 d de
j                  de
j                  dz  d
ee   deez  fd       Zee		 	 	 	 	 	 	 	 	 	 	 	 	 d!de
j                  dz  de
j(                  dz  de
j                  dz  dedz  de
j                  dz  de
j                  dz  de
j(                  dz  de
j                  dz  de
j                  dz  d	e
j                  dz  de
j,                  dz  de
j                  dz  dee
j(                  z  d
ee   deez  fd              Z	 	 	 	 	 	 	 	 	 	 	 d" fd	Z fdZ	 d de
j                  dz  de
j(                  dz  dee
j(                  e
j(                  f   fdZ	 	 	 d#dedede
j                  dz  dee
j                  eee f   f   fdZ! xZ"S )$Glm46VForConditionalGenerationzlm_head.weightz(model.language_model.embed_tokens.weightFc                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y )NF)bias)r=   r>   r:   r   nnLinearrB   hidden_size
vocab_sizelm_headrD   rE   s     r,   r>   z'Glm46VForConditionalGeneration.__init__  sS      (
yy!3!3!?!?ASASA^A^ejkr+   c                 6    | j                   j                         S r<   )r   rI   rJ   s    r,   rI   z3Glm46VForConditionalGeneration.get_input_embeddings  s    zz..00r+   c                 :    | j                   j                  |       y r<   )r   rL   rM   s     r,   rL   z3Glm46VForConditionalGeneration.set_input_embeddings  s    

''.r+   Nr   rm   r   ro   c                 @     | j                   j                  d||d|S )r   )r   rm   r*   )r   r   )rF   r   rm   r   s       r,   r   z1Glm46VForConditionalGeneration.get_video_features  s/     -tzz,, 
 3N
V\
 	
r+   r   rl   c                 @     | j                   j                  d||d|S )r   )r   rl   r*   )r   r   )rF   r   rl   r   s       r,   r   z1Glm46VForConditionalGeneration.get_image_features%  s'     -tzz,,p,Wepioppr+   rj   rn   r   r   r   labelsrk   r   logits_to_keepc                     | 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.

        Example:

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

        >>> model = Glm46VForConditionalGeneration.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 ..."
        ```)rj   r   r   rl   rm   rk   r   rn   r   r   r   r   N)r   r   r   )r   r   r   r1   r2   r3   r*   )r   
isinstancer   slicer   loss_functionr   rB   r   r   r   r1   r2   r3   )rF   rj   rn   r   r   r   r   r   r   rl   rm   rk   r   r   r   r   r1   slice_indicesr   r   s                       r,   r   z&Glm46VForConditionalGeneration.forward4  s    z $** 
% 3))/%)+')
 
  
 9C>SV8W~ot4]kmA}a,?@A%%VFt{{OfOfOqOq%rD+#33!//))++
 	
r+   c                 \    t        |   |f|||||||	|
|||d|}|s|r
d |d<   d |d<   |S )N)r   rn   r   r   r   r   r   rl   rm   	use_cacheis_first_iterationr   r   )r=   prepare_inputs_for_generation)rF   rj   r   rn   r   r   r   r   r   r   rl   rm   r   r   model_inputsrG   s                  r,   r   z<Glm46VForConditionalGeneration.prepare_inputs_for_generation  si    $ w<
+)')%% 3))1
 
  "i+/L(26L./r+   c                    t         |   ||      }d}|j                  d      x}|j                         }|dk7  r4| j                  j
                  |d   | j                  j
                  z   }|S d|v r|d   j                  d   dkD  r|d   }t        |j                        dk(  xr, |j                  t        j                  t        j                  fv }|r|j                  d      }|j                  d      |j                  d	      [|j                         D 	ci c]  \  }}	|dk7  s||	 }}}	 | j                  j                  |fi |\  }
}|| j                  _        no|j                  d      j                  d
dd      }
t        j                   |j                  d   dt        j                  |j"                        | j                  _        |d   }t        j$                  ||
gd      }|S c c}	}w )Nr   r   )N.rj   r   r   rk   rl   rm   r   ru   rq   rX   )r=   $_prepare_position_ids_for_generationgetr   r   r3   rw   r   rW   r5   r   r_   itemsr   r   r   rv   rT   r   )rF   inputs_tensormodel_kwargstext_positionspast_lengthcacher   is_input_idskvvision_positionsr3   rG   s               r,   r   zCGlm46VForConditionalGeneration._prepare_position_ids_for_generation  s    EmUab !%%&788EE..0K!

 6 6 B))4tzz7M7MML ,&<+D+J+J1+MPQ+Q(5M=../14g9L9LQVQZQZ\a\f\fPg9g  !45A!!"23?<CSCSTdCeCq-9-?-?-AVTQQ+EUAqDVLV,EDJJ,E,Em,dWc,d)k%0DJJ"-77:AA!RL%*[[##A&MDXDX&DJJ"
 (	2yy.2B!CK Ws   G3*G3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)`)
        rq   ).r   r   rX   r   )rI   r5   r   r   image_start_token_idr_   rT   video_start_token_idvideo_end_token_idr   r   r   )rF   rj   r   is_imageis_video_startis_video_endvideo_levelinside_videostandalone_imagesimage_countsvideo_countss              r,   _get_image_nums_and_video_numsz=Glm46VForConditionalGeneration._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\))r+   expand_sizeis_encoder_decoderc                      dk(  rfS g d fd}fd} |      j                  d       |      |r*j                  d      t        d       |d         d<   fS )	Nr   )r   rl   r   rm   second_per_grid_tsc                 4   j                  dd       }j                  dd       }j                  j                  dd             \  }}d }| D ]9  }|dk(  rct        j                  |t	        |            }|D cg c]'  }t        j
                  |d      j                         ) }	} || |   |	
	      | |<   l|dk(  rt	        |      }	 || |   |	
	      | |<   |d
k(  rct        j                  |t	        |            }|D cg c]'  }t        j
                  |d      j                         ) }	} || |   |	
	      | |<   |dk(  rt	        |      }	 || |   |	
	      | |<   |dk(  s  || |   t	        |      
	      | |<   < | S c c}w c c}w )Nrl   rm   r   )r   c                     t        j                  | |      }|gdg| j                         dz
  z  z   }t        j                  |D cg c]  } |j                  |  c}d      }|S c c}w )Nr   r   rX   )r5   r   rY   r   r\   )rs   lengthsrepeat_timessamplesrepeat_argssampleresults          r,   _repeat_interleave_sampleszGlm46VForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visual.<locals>._repeat_interleave_samples1  sa    ++a1+nsaeegk/BBg#VFMFMM;$?#V\]^ $Ws   A&r   r   rX   )r  r   r   r  )r  r  r5   r   r~   r   r   )dict_to_expandrl   rm   
image_nums
video_numsr%  r   r!  r#  r  r  rj   r  rF   s             r,   "_expand_dict_for_generation_visualzhGlm46VForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generation_visual*  s   )--.>EN)--.>EN%)%H%H)9)9/4)P &I &"J
 & .(#kk.$z:JKGMTU6uzz&a8<<>UGU*D&s+W;+N3' ,,":.G*D&s+W;+N3' 11#kk.$z:JKGMTU6uzz&a8<<>UGU*D&s+W;+N3' ,,":.G*D&s+W;+N3' 00*D&s+T*5ET_+N3'7< "!3 V Vs   =,F,Fc                    | D ]{  }|dk(  r,| |   j                   dk(  r| |   j                  d      | |<   4|dk7  s:| |   @t        | |   t        j                        s^|vsc| |   j                  d      | |<   } | S )Nr   r   r   rX   r   r   )ndimr]   r   r5   r   )r&  r   r  visual_keyss     r,   _expand_dict_for_generationzaGlm46VForConditionalGeneration._expand_inputs_for_generation.<locals>._expand_dict_for_generationW  s    % 	d.(^C-@-E-E-J*8*=*O*OP[ab*O*cN3'++&s+7">##6E;.*8*=*O*OP[ab*O*cN3'	d "!r+   r   rX   encoder_outputszMIf `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.)r]   r  r   )rF   r  r  rj   r  r)  r-  r,  s   `` ``  @r,   _expand_inputs_for_generationz<Glm46VForConditionalGeneration._expand_inputs_for_generation  s     !l**w+	"Z	" :,G !33KQ3GI2<@ 12: !pqq.I,WhJi.jL*+,&&r+   r<   )NNNNNNNNNNNNr   )NNNNNTNNNNF)r   FN)#r   r   r   r   _tied_weights_keysr   r>   rI   rL   r   r5   r6   r8   r   r   r7   r   r   r   r   r   r   r   r   r   r   r   r   r  rz   dictr   r   r/  r   r   s   @r,   r   r     s9   %'"*,VW1/  37
"..
 ((4/
 +,	

 
+	+
 
   37q''q ((4/q +,	q
 
+	+q q  .2.204(,26*.,08<26264826-.[
##d*[
 t+[
 &&-	[

 [
 ((4/[
   4'[
 llT)[
 #..5[
 ((4/[
 ((4/[
 !??T1[
 ((4/[
 ell*[
 +,[
  
-	-![
  [
@   &P$R .26*##d*6* ||d*6* 
u||U\\)	*	6*t #(-1	W'W' !W' ##d*	W' 
uc3h/	0W'r+   r   )r:   r   r   )"r{   dataclassesr   typingr   r5   torch.nnr   cache_utilsr   
generationr   modeling_outputsr   r	   modeling_utilsr
   processing_utilsr   utilsr   r   r   r   autor   configuration_glm46vr   r   r/   r:   r   r   __all__r*   r+   r,   <module>r>     s   ,  !      ) G - & a a  . O   
0 0 0$ Q
' Q
 Q
h 
0; 0 0.o'%:O o'd Ur+   