modular_glm4v.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. # coding=utf-8
  2. # Copyright 2025 The ZhipuAI Inc. team and HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import itertools
  16. from typing import Callable, Optional, Union
  17. import numpy as np
  18. import torch
  19. import torch.nn as nn
  20. import torch.nn.functional as F
  21. from torch.nn import LayerNorm
  22. from ...activations import ACT2FN
  23. from ...cache_utils import Cache, DynamicCache
  24. from ...configuration_utils import PretrainedConfig
  25. from ...feature_extraction_utils import BatchFeature
  26. from ...image_utils import ImageInput
  27. from ...masking_utils import create_causal_mask
  28. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  29. from ...modeling_layers import GradientCheckpointingLayer
  30. from ...modeling_outputs import BaseModelOutputWithPast
  31. from ...modeling_rope_utils import rope_config_validation
  32. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
  33. from ...processing_utils import ImagesKwargs, Unpack
  34. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  35. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
  36. from ...utils.generic import check_model_inputs
  37. from ...video_utils import VideoInput
  38. from ..glm4.modeling_glm4 import Glm4MLP, Glm4RMSNorm, eager_attention_forward
  39. from ..qwen2_5_vl.modeling_qwen2_5_vl import (
  40. Qwen2_5_VisionPatchEmbed,
  41. Qwen2_5_VisionRotaryEmbedding,
  42. Qwen2_5_VLCausalLMOutputWithPast,
  43. Qwen2_5_VLForConditionalGeneration,
  44. Qwen2_5_VLMLP,
  45. Qwen2_5_VLModel,
  46. Qwen2_5_VLModelOutputWithPast,
  47. Qwen2_5_VLPreTrainedModel,
  48. Qwen2_5_VLRotaryEmbedding,
  49. Qwen2_5_VLTextModel,
  50. Qwen2_5_VLVisionAttention,
  51. Qwen2_5_VLVisionBlock,
  52. )
  53. from ..qwen2_5_vl.processing_qwen2_5_vl import Qwen2_5_VLVideosProcessorKwargs
  54. from ..qwen2_vl.processing_qwen2_vl import (
  55. Qwen2_VLProcessor,
  56. Qwen2_VLProcessorKwargs,
  57. )
  58. logger = logging.get_logger(__name__)
  59. class Glm4vVisionConfig(PretrainedConfig):
  60. r"""
  61. This is the configuration class to store the configuration of a [`Glm4vVisionModel`]. It is used to instantiate an Glm4vVisionModel
  62. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
  63. a similar configuration to that of
  64. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  65. Args:
  66. hidden_size (`int`, *optional*, defaults to 1536):
  67. Dimensionality of the encoder layers and the pooler layer.
  68. depth (`int`, *optional*, defaults to 24):
  69. Number of layers (depth) in the model.
  70. attention_bias (`bool`, *optional*, defaults to `False`):
  71. Whether to add a bias to the queries, keys and values.
  72. intermediate_size (`int`, *optional*, defaults to 13696):
  73. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  74. hidden_act (`str` or `function`, *optional*, defaults to `"selu"`):
  75. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  76. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  77. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  78. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  79. attention_dropout (`float`, *optional*, defaults to 0.0):
  80. Dropout probability for attention weights.
  81. projection_dropout (`float`, *optional*, defaults to 0.0):
  82. Dropout probability for the projection layer.
  83. initializer_range (`float`, *optional*, defaults to 0.02):
  84. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  85. image_size (`int` or `list[int]`, *optional*, defaults to `[336, 336]`):
  86. The size (resolution) of each image.
  87. patch_size (`int`, *optional*, defaults to `14`):
  88. The size (resolution) of each patch.
  89. num_channels (`int`, *optional*, defaults to 3):
  90. The number of input channels.
  91. out_hidden_size (`int`, *optional*, defaults to 4096):
  92. The output hidden size of the vision model.
  93. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  94. The epsilon used by the rms normalization layers.
  95. spatial_merge_size (`int`, *optional*, defaults to 2):
  96. The size used for merging spatial dimensions.
  97. temporal_patch_size (`int`, *optional*, defaults to 2):
  98. The size used for patches along the temporal dimension.
  99. Example:
  100. ```python
  101. >>> from transformers import Glm4vVisionConfig, Glm4vVisionModel
  102. >>> # Initializing a Glm4vVisionConfig GLM-4.1V-9B style configuration
  103. >>> configuration = Glm4vVisionConfig()
  104. >>> # Initializing a model (with random weights) from the GLM-4.1V-9B configuration
  105. >>> model = Glm4vVisionModel(configuration)
  106. >>> # Accessing the model configuration
  107. >>> configuration = model.config
  108. ```"""
  109. model_type = "glm4v"
  110. base_config_key = "vision_config"
  111. def __init__(
  112. self,
  113. depth=24,
  114. hidden_size=1536,
  115. hidden_act="silu",
  116. attention_bias=False,
  117. attention_dropout=0.0,
  118. num_heads=12,
  119. in_channels=3,
  120. image_size=336,
  121. patch_size=14,
  122. rms_norm_eps=1e-05,
  123. spatial_merge_size=2,
  124. temporal_patch_size=2,
  125. out_hidden_size=4096,
  126. intermediate_size=13696,
  127. initializer_range=0.02,
  128. **kwargs,
  129. ):
  130. super().__init__(**kwargs)
  131. self.depth = depth
  132. self.hidden_size = hidden_size
  133. self.hidden_act = hidden_act
  134. self.num_heads = num_heads
  135. self.in_channels = in_channels
  136. self.image_size = image_size
  137. self.patch_size = patch_size
  138. self.spatial_merge_size = spatial_merge_size
  139. self.temporal_patch_size = temporal_patch_size
  140. self.out_hidden_size = out_hidden_size
  141. self.intermediate_size = intermediate_size
  142. self.initializer_range = initializer_range
  143. self.rms_norm_eps = rms_norm_eps
  144. self.attention_bias = attention_bias
  145. self.attention_dropout = attention_dropout
  146. class Glm4vTextConfig(PretrainedConfig):
  147. r"""
  148. This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
  149. GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
  150. configuration with the defaults will yield a similar configuration to that of
  151. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  152. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  153. documentation from [`PretrainedConfig`] for more information.
  154. Args:
  155. vocab_size (`int`, *optional*, defaults to 151552):
  156. Vocabulary size of the Glm4v model. Defines the number of different tokens that can be represented by the
  157. `inputs_ids` passed when calling [`Glm4vModel`]
  158. hidden_size (`int`, *optional*, defaults to 4096):
  159. Dimension of the hidden representations.
  160. intermediate_size (`int`, *optional*, defaults to 13696):
  161. Dimension of the MLP representations.
  162. num_hidden_layers (`int`, *optional*, defaults to 40):
  163. Number of hidden layers in the Transformer encoder.
  164. num_attention_heads (`int`, *optional*, defaults to 32):
  165. Number of attention heads for each attention layer in the Transformer encoder.
  166. num_key_value_heads (`int`, *optional*, defaults to 2):
  167. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  168. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  169. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  170. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  171. by meanpooling all the original heads within that group. For more details checkout [this
  172. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
  173. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  174. The non-linear activation function (function or string) in the decoder.
  175. max_position_embeddings (`int`, *optional*, defaults to 32768):
  176. The maximum sequence length that this model might ever be used with.
  177. initializer_range (`float`, *optional*, defaults to 0.02):
  178. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  179. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  180. The epsilon used by the rms normalization layers.
  181. use_cache (`bool`, *optional*, defaults to `True`):
  182. Whether or not the model should return the last key/values attentions (not used by all models). Only
  183. relevant if `config.is_decoder=True`.
  184. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  185. Whether the model's input and output word embeddings should be tied.
  186. rope_theta (`float`, *optional*, defaults to 10000.0):
  187. The base period of the RoPE embeddings.
  188. attention_dropout (`float`, *optional*, defaults to 0.0):
  189. The dropout ratio for the attention probabilities.
  190. rope_scaling (`Dict`, *optional*):
  191. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  192. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  193. accordingly.
  194. Expected contents:
  195. `rope_type` (`str`):
  196. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  197. 'llama3'], with 'default' being the original RoPE implementation.
  198. `factor` (`float`, *optional*):
  199. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  200. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  201. original maximum pre-trained length.
  202. `original_max_position_embeddings` (`int`, *optional*):
  203. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  204. pretraining.
  205. `attention_factor` (`float`, *optional*):
  206. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  207. computation. If unspecified, it defaults to value recommended by the implementation, using the
  208. `factor` field to infer the suggested value.
  209. image_token_id (`int`, *optional*):
  210. Token index used as placeholder for image embeddings.
  211. video_token_id (`int`, *optional*):
  212. Token index used as placeholder for video embeddings.
  213. ```python
  214. >>> from transformers import Glm4vTextModel, Glm4vConfig
  215. >>> # Initializing a GLM-4.1V style configuration
  216. >>> configuration = Glm4vConfig()
  217. >>> # Initializing a model from the GLM-4.1V style configuration
  218. >>> model = Glm4vTextModel(configuration)
  219. >>> # Accessing the model configuration
  220. >>> configuration = model.config
  221. ```"""
  222. model_type = "glm4v_text"
  223. base_config_key = "text_config"
  224. keys_to_ignore_at_inference = ["past_key_values"]
  225. # Default tensor parallel plan for base model `Glm4v`
  226. base_model_tp_plan = {
  227. "layers.*.self_attn.q_proj": "colwise",
  228. "layers.*.self_attn.k_proj": "colwise",
  229. "layers.*.self_attn.v_proj": "colwise",
  230. "layers.*.self_attn.o_proj": "rowwise",
  231. "layers.*.mlp.gate_up_proj": "colwise_rep", # we need to replicate here due to the `chunk` operation
  232. "layers.*.mlp.down_proj": "rowwise_rep", # we need to replicate here due to the `chunk` operation
  233. }
  234. base_model_pp_plan = {
  235. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  236. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  237. "norm": (["hidden_states"], ["hidden_states"]),
  238. }
  239. def __init__(
  240. self,
  241. vocab_size=151552,
  242. hidden_size=4096,
  243. intermediate_size=13696,
  244. num_hidden_layers=40,
  245. num_attention_heads=32,
  246. num_key_value_heads=2,
  247. hidden_act="silu",
  248. max_position_embeddings=32768,
  249. initializer_range=0.02,
  250. rms_norm_eps=1e-05,
  251. use_cache=True,
  252. tie_word_embeddings=False,
  253. rope_theta=10000.0,
  254. attention_dropout=0.0,
  255. rope_scaling=None,
  256. image_token_id=None,
  257. video_token_id=None,
  258. **kwargs,
  259. ):
  260. self.vocab_size = vocab_size
  261. self.max_position_embeddings = max_position_embeddings
  262. self.hidden_size = hidden_size
  263. self.intermediate_size = intermediate_size
  264. self.num_hidden_layers = num_hidden_layers
  265. self.num_attention_heads = num_attention_heads
  266. # for backward compatibility
  267. if num_key_value_heads is None:
  268. num_key_value_heads = num_attention_heads
  269. self.num_key_value_heads = num_key_value_heads
  270. self.hidden_act = hidden_act
  271. self.initializer_range = initializer_range
  272. self.rms_norm_eps = rms_norm_eps
  273. self.use_cache = use_cache
  274. self.rope_theta = rope_theta
  275. self.attention_dropout = attention_dropout
  276. self.rope_scaling = rope_scaling
  277. # Validate the correctness of rotary position embeddings parameters
  278. # BC: if there is a 'type' field, move it to 'rope_type'.
  279. if self.rope_scaling is not None and "type" in self.rope_scaling:
  280. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  281. rope_config_validation(self, ignore_keys={"mrope_section"})
  282. self.image_token_id = image_token_id
  283. self.video_token_id = video_token_id
  284. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  285. class Glm4vConfig(PretrainedConfig):
  286. r"""
  287. This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
  288. GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
  289. configuration with the defaults will yield a similar configuration to that of
  290. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  291. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  292. documentation from [`PretrainedConfig`] for more information.
  293. Args:
  294. text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Glm4vTextConfig`):
  295. The config object or dictionary of the text backbone.
  296. vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Glm4vVisionConfig`):
  297. The config object or dictionary of the vision backbone.
  298. image_token_id (`int`, *optional*, defaults to 151343):
  299. The image token index to encode the image prompt.
  300. video_token_id (`int`, *optional*, defaults to 151344):
  301. The video token index to encode the image prompt.
  302. image_start_token_id (`int`, *optional*, defaults to 151339):
  303. The image start token index to encode the start of image.
  304. image_end_token_id (`int`, *optional*, defaults to 151340):
  305. The image end token index to encode the end of image.
  306. video_start_token_id (`int`, *optional*, defaults to 151341):
  307. The video start token index to encode the start of video.
  308. video_end_token_id (`int`, *optional*, defaults to 151342):
  309. The video end token index to encode the end of video.
  310. ```python
  311. >>> from transformers import Glm4vForConditionalGeneration, Glm4vConfig
  312. >>> # Initializing a GLM-4.1V style configuration
  313. >>> configuration = Glm4vConfig()
  314. >>> # Initializing a model from the GLM-4.1V style configuration
  315. >>> model = Glm4vForConditionalGeneration(configuration)
  316. >>> # Accessing the model configuration
  317. >>> configuration = model.config
  318. ```"""
  319. model_type = "glm4v"
  320. sub_configs = {"vision_config": Glm4vVisionConfig, "text_config": Glm4vTextConfig}
  321. keys_to_ignore_at_inference = ["past_key_values"]
  322. def __init__(
  323. self,
  324. text_config=None,
  325. vision_config=None,
  326. image_token_id=151343,
  327. video_token_id=151344,
  328. image_start_token_id=151339,
  329. image_end_token_id=151340,
  330. video_start_token_id=151341,
  331. video_end_token_id=151342,
  332. **kwargs,
  333. ):
  334. if isinstance(vision_config, dict):
  335. self.vision_config = self.sub_configs["vision_config"](**vision_config)
  336. elif vision_config is None:
  337. self.vision_config = self.sub_configs["vision_config"]()
  338. if isinstance(text_config, dict):
  339. self.text_config = self.sub_configs["text_config"](**text_config)
  340. elif text_config is None:
  341. self.text_config = self.sub_configs["text_config"](**kwargs)
  342. self.image_token_id = image_token_id
  343. self.video_token_id = video_token_id
  344. self.video_start_token_id = video_start_token_id
  345. self.video_end_token_id = video_end_token_id
  346. self.image_start_token_id = image_start_token_id
  347. self.image_end_token_id = image_end_token_id
  348. super().__init__(**kwargs)
  349. # Will be used for both Text and Vision modalities
  350. class Glm4vRMSNorm(Glm4RMSNorm):
  351. pass
  352. class Glm4VisionMlp(Qwen2_5_VLMLP):
  353. def __init__(self, config, bias: bool = False):
  354. super().__init__(config, bias)
  355. self.intermediate_size = config.out_hidden_size
  356. class Glm4vVisionPatchEmbed(Qwen2_5_VisionPatchEmbed):
  357. def __init__(self, config: Glm4vVisionConfig) -> None:
  358. nn.Module.__init__(self)
  359. self.patch_size = config.patch_size
  360. self.temporal_patch_size = config.temporal_patch_size
  361. self.in_channels = config.in_channels
  362. self.embed_dim = config.hidden_size
  363. kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
  364. self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size)
  365. class Glm4vVisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding):
  366. pass
  367. class Glm4vVisionPatchMerger(nn.Module):
  368. def __init__(self, dim: int, context_dim: int, hidden_act: str, bias: bool = False) -> None:
  369. super().__init__()
  370. self.proj = nn.Linear(dim, dim, bias=bias)
  371. self.post_projection_norm = LayerNorm(dim)
  372. self.gate_proj = nn.Linear(dim, context_dim, bias=bias)
  373. self.up_proj = nn.Linear(dim, context_dim, bias=bias)
  374. self.down_proj = nn.Linear(context_dim, dim, bias=bias)
  375. self.act1 = nn.GELU()
  376. self.act_fn = ACT2FN[hidden_act]
  377. def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
  378. hidden_state = self.proj(hidden_state)
  379. hidden_state = self.act1(self.post_projection_norm(hidden_state))
  380. return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
  381. class Glm4vVisionEmbeddings(nn.Module):
  382. def __init__(self, config: Glm4vVisionConfig):
  383. super().__init__()
  384. self.config = config
  385. self.embed_dim = config.hidden_size
  386. self.image_size = config.image_size
  387. self.patch_size = config.patch_size
  388. self.num_patches = (self.image_size // self.patch_size) ** 2
  389. self.num_positions = self.num_patches
  390. self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
  391. self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
  392. def forward(self, embeddings, lengths, image_shapes, h_coords, w_coords) -> torch.Tensor:
  393. """
  394. Forward pass with integrated position encoding adaptation using 2D interpolation.
  395. Args:
  396. embeddings: Input embeddings tensor
  397. lengths (torch.Tensor): Sequence lengths for each image in the batch.
  398. image_shapes (torch.Tensor): Tensor of shape [batch_size, 3] representing the image shapes (t, h, w).
  399. h_coords (torch.Tensor): Tensor of shape [total_seq] representing the h coordinate for each patch.
  400. w_coords (torch.Tensor): Tensor of shape [total_seq] representing the w coordinate for each patch.
  401. Returns:
  402. torch.Tensor: Embeddings with adapted position encoding added.
  403. """
  404. # Get position embedding parameters
  405. pos_embed_weight = self.position_embedding.weight
  406. hidden_size = pos_embed_weight.shape[1]
  407. total_seq = h_coords.shape[0]
  408. device = pos_embed_weight.device
  409. # Move coordinates to correct device
  410. h_coords, w_coords = h_coords.to(device), w_coords.to(device)
  411. # Handle empty sequence case
  412. if total_seq == 0:
  413. adapted_pos_embed = torch.empty(0, hidden_size, device=device, dtype=pos_embed_weight.dtype)
  414. else:
  415. # Convert inputs to tensors if needed
  416. if isinstance(lengths, list):
  417. lengths = torch.tensor(lengths, device=device, dtype=torch.long)
  418. if not isinstance(image_shapes, torch.Tensor):
  419. image_shapes = torch.tensor(image_shapes, device=device, dtype=torch.long)
  420. # Prepare 2D position embedding
  421. orig_size_sq = pos_embed_weight.shape[0]
  422. orig_size = int(orig_size_sq**0.5)
  423. pos_embed_2d = (
  424. pos_embed_weight.view(orig_size, orig_size, hidden_size)
  425. .permute(2, 0, 1)
  426. .unsqueeze(0)
  427. .to(device=device, dtype=torch.float32)
  428. )
  429. # Calculate target dimensions for each patch
  430. target_h = torch.cat([image_shapes[i, 1].repeat(lengths[i]) for i in range(len(lengths))]).to(
  431. device=device, dtype=torch.float32
  432. )
  433. target_w = torch.cat([image_shapes[i, 2].repeat(lengths[i]) for i in range(len(lengths))]).to(
  434. device=device, dtype=torch.float32
  435. )
  436. # Normalize coordinates to [-1, 1] range for grid_sample
  437. h_coords = h_coords.to(device=device, dtype=torch.float32)
  438. w_coords = w_coords.to(device=device, dtype=torch.float32)
  439. norm_w = ((w_coords + 0.5) / target_w) * 2 - 1
  440. norm_h = ((h_coords + 0.5) / target_h) * 2 - 1
  441. # Create sampling grid
  442. grid = torch.stack((norm_w, norm_h), dim=-1).unsqueeze(0).unsqueeze(2)
  443. # Perform bicubic interpolation
  444. interpolated_embed_fp32 = F.grid_sample(
  445. pos_embed_2d, grid, mode="bicubic", align_corners=False, padding_mode="border"
  446. )
  447. # Reshape and convert back to original dtype
  448. adapted_pos_embed_fp32 = interpolated_embed_fp32.squeeze(0).squeeze(-1).permute(1, 0)
  449. adapted_pos_embed = adapted_pos_embed_fp32.to(pos_embed_weight.dtype).to(embeddings.device)
  450. # Add adapted position encoding to embeddings
  451. embeddings = embeddings + adapted_pos_embed
  452. return embeddings
  453. class Glm4vVisionAttention(Qwen2_5_VLVisionAttention):
  454. def __init__(self, config: Glm4vVisionConfig) -> None:
  455. super().__init__(config)
  456. self.attention_dropout = config.attention_dropout
  457. self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.attention_bias)
  458. self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
  459. class Glm4vVisionBlock(Qwen2_5_VLVisionBlock):
  460. def __init__(self, config) -> None:
  461. super().__init__(config)
  462. self.norm1 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  463. self.norm2 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  464. self.attn = Glm4vVisionAttention(config)
  465. self.mlp = Glm4VisionMlp(config, bias=False)
  466. class Glm4vTextRotaryEmbedding(Qwen2_5_VLRotaryEmbedding):
  467. pass
  468. def rotate_half_llm(x):
  469. """Rotates half the hidden dims of the input."""
  470. x1 = x[..., 0::2]
  471. x2 = x[..., 1::2]
  472. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  473. def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
  474. """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
  475. Explanation:
  476. Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
  477. sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
  478. vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
  479. Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
  480. For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
  481. height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
  482. difference with modern LLMs.
  483. Args:
  484. q (`torch.Tensor`): The query tensor.
  485. k (`torch.Tensor`): The key tensor.
  486. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  487. sin (`torch.Tensor`): The sine part of the rotary embedding.
  488. mrope_section(`List(int)`):
  489. Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
  490. unsqueeze_dim (`int`, *optional*, defaults to 1):
  491. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  492. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  493. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  494. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  495. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  496. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  497. Returns:
  498. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  499. """
  500. mrope_section = mrope_section * 2
  501. cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
  502. unsqueeze_dim
  503. )
  504. sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
  505. unsqueeze_dim
  506. )
  507. # Interleave them instead of usual shape
  508. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  509. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  510. # Keep half or full tensor for later concatenation
  511. rotary_dim = cos.shape[-1]
  512. q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
  513. k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
  514. # Apply rotary embeddings on the first half or full tensor
  515. q_embed = (q_rot * cos) + (rotate_half_llm(q_rot) * sin)
  516. k_embed = (k_rot * cos) + (rotate_half_llm(k_rot) * sin)
  517. # Concatenate back to full shape
  518. q_embed = torch.cat([q_embed, q_pass], dim=-1)
  519. k_embed = torch.cat([k_embed, k_pass], dim=-1)
  520. return q_embed, k_embed
  521. class Glm4vTextAttention(nn.Module):
  522. """
  523. Multi-headed attention from 'Attention Is All You Need' paper.
  524. and "Generating Long Sequences with Sparse Transformers".
  525. """
  526. def __init__(self, config: Glm4vTextConfig, layer_idx: Optional[int] = None):
  527. super().__init__()
  528. self.config = config
  529. self.layer_idx = layer_idx
  530. self.hidden_size = config.hidden_size
  531. self.num_heads = config.num_attention_heads
  532. self.head_dim = self.hidden_size // self.num_heads
  533. self.num_key_value_heads = config.num_key_value_heads
  534. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  535. self.is_causal = True
  536. self.attention_dropout = config.attention_dropout
  537. self.rope_scaling = config.rope_scaling
  538. self.scaling = self.head_dim**-0.5
  539. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
  540. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  541. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  542. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  543. def forward(
  544. self,
  545. hidden_states: torch.Tensor,
  546. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  547. attention_mask: Optional[torch.Tensor] = None,
  548. position_ids: Optional[torch.LongTensor] = None,
  549. past_key_values: Optional[Cache] = None,
  550. cache_position: Optional[torch.LongTensor] = None,
  551. **kwargs: Unpack[FlashAttentionKwargs],
  552. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  553. bsz, q_len, _ = hidden_states.size()
  554. query_states = self.q_proj(hidden_states)
  555. key_states = self.k_proj(hidden_states)
  556. value_states = self.v_proj(hidden_states)
  557. query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  558. key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  559. value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  560. cos, sin = position_embeddings
  561. query_states, key_states = apply_multimodal_rotary_pos_emb( # diff with Llama
  562. query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
  563. )
  564. if past_key_values is not None:
  565. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
  566. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  567. attention_interface: Callable = eager_attention_forward
  568. if self.config._attn_implementation != "eager":
  569. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  570. attn_output, attn_weights = attention_interface(
  571. self,
  572. query_states,
  573. key_states,
  574. value_states,
  575. attention_mask,
  576. dropout=0.0 if not self.training else self.attention_dropout,
  577. scaling=self.scaling,
  578. **kwargs,
  579. )
  580. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  581. attn_output = self.o_proj(attn_output)
  582. return attn_output, attn_weights
  583. class Glm4vTextMLP(Glm4MLP):
  584. pass
  585. class Glm4vTextDecoderLayer(GradientCheckpointingLayer):
  586. def __init__(self, config: Glm4vTextConfig, layer_idx: int):
  587. super().__init__()
  588. self.hidden_size = config.hidden_size
  589. self.self_attn = Glm4vTextAttention(config, layer_idx)
  590. self.mlp = Glm4vTextMLP(config)
  591. self.input_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  592. self.post_attention_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  593. self.post_self_attn_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  594. self.post_mlp_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  595. def forward(
  596. self,
  597. hidden_states: torch.Tensor,
  598. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  599. attention_mask: Optional[torch.Tensor] = None,
  600. position_ids: Optional[torch.LongTensor] = None,
  601. past_key_values: Optional[Cache] = None,
  602. output_attentions: Optional[bool] = False,
  603. use_cache: Optional[bool] = False,
  604. cache_position: Optional[torch.LongTensor] = None,
  605. **kwargs,
  606. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  607. residual = hidden_states
  608. hidden_states = self.input_layernorm(hidden_states)
  609. # Self Attention
  610. hidden_states, _ = self.self_attn(
  611. hidden_states=hidden_states,
  612. position_embeddings=position_embeddings,
  613. attention_mask=attention_mask,
  614. position_ids=position_ids,
  615. past_key_values=past_key_values,
  616. output_attentions=output_attentions,
  617. use_cache=use_cache,
  618. cache_position=cache_position,
  619. **kwargs,
  620. )
  621. hidden_states = self.post_self_attn_layernorm(hidden_states)
  622. hidden_states = residual + hidden_states
  623. # Fully Connected
  624. residual = hidden_states
  625. hidden_states = self.post_attention_layernorm(hidden_states)
  626. hidden_states = self.mlp(hidden_states)
  627. hidden_states = self.post_mlp_layernorm(hidden_states)
  628. hidden_states = residual + hidden_states
  629. return hidden_states
  630. class Glm4vModelOutputWithPast(Qwen2_5_VLModelOutputWithPast):
  631. pass
  632. class Glm4vPreTrainedModel(Qwen2_5_VLPreTrainedModel):
  633. _no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
  634. _can_record_outputs = {
  635. "hidden_states": Glm4vTextDecoderLayer,
  636. "attentions": Glm4vTextAttention,
  637. }
  638. class Glm4vVisionModel(Glm4vPreTrainedModel):
  639. config: Glm4vVisionConfig
  640. _no_split_modules = ["Glm4vVisionBlock"]
  641. def __init__(self, config) -> None:
  642. super().__init__(config)
  643. self.spatial_merge_size = config.spatial_merge_size
  644. self.patch_size = config.patch_size
  645. self.embeddings = Glm4vVisionEmbeddings(config)
  646. self.patch_embed = Glm4vVisionPatchEmbed(config)
  647. head_dim = config.hidden_size // config.num_heads
  648. self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(head_dim // 2)
  649. self.blocks = nn.ModuleList([Glm4vVisionBlock(config) for _ in range(config.depth)])
  650. self.merger = Glm4vVisionPatchMerger(
  651. dim=config.out_hidden_size, context_dim=config.intermediate_size, hidden_act=config.hidden_act
  652. )
  653. self.post_conv_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  654. self.downsample = nn.Conv2d(
  655. in_channels=config.hidden_size,
  656. out_channels=config.out_hidden_size,
  657. kernel_size=config.spatial_merge_size,
  658. stride=config.spatial_merge_size,
  659. )
  660. self.post_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  661. self.gradient_checkpointing = False
  662. self.post_init()
  663. def rot_pos_emb(self, grid_thw):
  664. pos_ids = []
  665. for t, h, w in grid_thw:
  666. hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
  667. hpos_ids = hpos_ids.reshape(
  668. h // self.spatial_merge_size,
  669. self.spatial_merge_size,
  670. w // self.spatial_merge_size,
  671. self.spatial_merge_size,
  672. )
  673. hpos_ids = hpos_ids.permute(0, 2, 1, 3)
  674. hpos_ids = hpos_ids.flatten()
  675. wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
  676. wpos_ids = wpos_ids.reshape(
  677. h // self.spatial_merge_size,
  678. self.spatial_merge_size,
  679. w // self.spatial_merge_size,
  680. self.spatial_merge_size,
  681. )
  682. wpos_ids = wpos_ids.permute(0, 2, 1, 3)
  683. wpos_ids = wpos_ids.flatten()
  684. pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
  685. pos_ids = torch.cat(pos_ids, dim=0)
  686. max_grid_size = grid_thw[:, 1:].max()
  687. rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
  688. rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
  689. return rotary_pos_emb, pos_ids
  690. def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
  691. """
  692. Args:
  693. hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
  694. The final hidden states of the model.
  695. grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
  696. The temporal, height and width of feature shape of each image in LLM.
  697. Returns:
  698. `torch.Tensor`: hidden_states.
  699. """
  700. hidden_states = self.patch_embed(hidden_states)
  701. hidden_states = self.post_conv_layernorm(hidden_states)
  702. rotary_pos_emb, image_type_ids = self.rot_pos_emb(grid_thw)
  703. emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
  704. position_embeddings = (emb.cos(), emb.sin())
  705. cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
  706. dim=0,
  707. # Select dtype based on the following factors:
  708. # - FA2 requires that cu_seqlens_q must have dtype int32
  709. # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
  710. # See https://github.com/huggingface/transformers/pull/34852 for more information
  711. dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
  712. )
  713. cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
  714. seqlens = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
  715. hidden_states = self.embeddings(hidden_states, seqlens, grid_thw, image_type_ids[:, 0], image_type_ids[:, 1])
  716. for blk in self.blocks:
  717. hidden_states = blk(
  718. hidden_states,
  719. cu_seqlens=cu_seqlens,
  720. position_embeddings=position_embeddings,
  721. )
  722. hidden_states = self.post_layernorm(hidden_states)
  723. hidden_states = hidden_states.view(
  724. -1, self.spatial_merge_size, self.spatial_merge_size, hidden_states.shape[-1]
  725. )
  726. hidden_states = hidden_states.permute(0, 3, 1, 2)
  727. hidden_states = self.downsample(hidden_states).view(-1, self.config.out_hidden_size)
  728. hidden_states = self.merger(hidden_states)
  729. return hidden_states
  730. class Glm4vTextModel(Qwen2_5_VLTextModel):
  731. def __init__(self, config: Glm4vTextConfig):
  732. super().__init__(config)
  733. self.layers = nn.ModuleList(
  734. [Glm4vTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  735. )
  736. self.norm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  737. self.rotary_emb = Glm4vTextRotaryEmbedding(config=config)
  738. del self._attn_implementation
  739. del self.has_sliding_layers
  740. @auto_docstring
  741. @check_model_inputs()
  742. def forward(
  743. self,
  744. input_ids: Optional[torch.LongTensor] = None,
  745. attention_mask: Optional[torch.Tensor] = None,
  746. position_ids: Optional[torch.LongTensor] = None,
  747. past_key_values: Optional[Cache] = None,
  748. inputs_embeds: Optional[torch.FloatTensor] = None,
  749. use_cache: Optional[bool] = None,
  750. cache_position: Optional[torch.LongTensor] = None,
  751. **kwargs: Unpack[FlashAttentionKwargs],
  752. ) -> Union[tuple, BaseModelOutputWithPast]:
  753. if (input_ids is None) ^ (inputs_embeds is not None):
  754. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  755. # torch.jit.trace() doesn't support cache objects in the output
  756. if use_cache and past_key_values is None and not torch.jit.is_tracing():
  757. past_key_values = DynamicCache(config=self.config)
  758. if inputs_embeds is None:
  759. inputs_embeds = self.embed_tokens(input_ids)
  760. if cache_position is None:
  761. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  762. cache_position = torch.arange(
  763. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  764. )
  765. # the hard coded `3` is for temporal, height and width.
  766. if position_ids is None:
  767. position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
  768. elif position_ids.dim() == 2:
  769. position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
  770. causal_mask = create_causal_mask(
  771. config=self.config,
  772. input_embeds=inputs_embeds,
  773. attention_mask=attention_mask,
  774. cache_position=cache_position,
  775. past_key_values=past_key_values,
  776. position_ids=position_ids,
  777. )
  778. hidden_states = inputs_embeds
  779. # create position embeddings to be shared across the decoder layers
  780. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  781. for decoder_layer in self.layers:
  782. layer_outputs = decoder_layer(
  783. hidden_states,
  784. position_embeddings=position_embeddings,
  785. attention_mask=causal_mask,
  786. position_ids=position_ids,
  787. past_key_values=past_key_values,
  788. cache_position=cache_position,
  789. **kwargs,
  790. )
  791. hidden_states = layer_outputs
  792. hidden_states = self.norm(hidden_states)
  793. return BaseModelOutputWithPast(
  794. last_hidden_state=hidden_states,
  795. past_key_values=past_key_values,
  796. )
  797. class Glm4vModel(Qwen2_5_VLModel):
  798. _checkpoint_conversion_mapping = {}
  799. _no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
  800. def __init__(self, config):
  801. super().__init__(config)
  802. self.visual = Glm4vVisionModel._from_config(config.vision_config)
  803. def get_rope_index(
  804. self,
  805. input_ids: Optional[torch.LongTensor] = None,
  806. image_grid_thw: Optional[torch.LongTensor] = None,
  807. video_grid_thw: Optional[torch.LongTensor] = None,
  808. attention_mask: Optional[torch.Tensor] = None,
  809. ) -> tuple[torch.Tensor, torch.Tensor]:
  810. """
  811. Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
  812. Explanation:
  813. Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
  814. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
  815. Examples:
  816. input_ids: [T T T T T], here T is for text.
  817. temporal position_ids: [0, 1, 2, 3, 4]
  818. height position_ids: [0, 1, 2, 3, 4]
  819. width position_ids: [0, 1, 2, 3, 4]
  820. For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
  821. and 1D rotary position embedding for text part.
  822. Examples:
  823. Temporal (Time): 3 patches, representing different segments of the video in time.
  824. Height: 2 patches, dividing each frame vertically.
  825. Width: 2 patches, dividing each frame horizontally.
  826. We also have some important parameters:
  827. fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
  828. 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.
  829. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
  830. 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.
  831. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
  832. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
  833. vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
  834. vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
  835. text temporal position_ids: [101, 102, 103, 104, 105]
  836. text height position_ids: [101, 102, 103, 104, 105]
  837. text width position_ids: [101, 102, 103, 104, 105]
  838. Here we calculate the text start position_ids as the max vision position_ids plus 1.
  839. Args:
  840. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  841. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  842. it.
  843. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  844. The temporal, height and width of feature shape of each image in LLM.
  845. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  846. The temporal, height and width of feature shape of each video in LLM.
  847. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  848. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  849. - 1 for tokens that are **not masked**,
  850. - 0 for tokens that are **masked**.
  851. Returns:
  852. position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
  853. mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
  854. """
  855. spatial_merge_size = self.config.vision_config.spatial_merge_size
  856. image_token_id = self.config.image_token_id
  857. video_start_token_id = self.config.video_start_token_id
  858. video_end_token_id = self.config.video_end_token_id
  859. mrope_position_deltas = []
  860. if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
  861. total_input_ids = input_ids
  862. if attention_mask is None:
  863. attention_mask = torch.ones_like(total_input_ids)
  864. position_ids = torch.ones(
  865. 3,
  866. input_ids.shape[0],
  867. input_ids.shape[1],
  868. dtype=input_ids.dtype,
  869. device=input_ids.device,
  870. )
  871. image_index, video_index = 0, 0
  872. video_group_index = 0
  873. attention_mask = attention_mask.to(total_input_ids.device)
  874. for i, input_ids in enumerate(total_input_ids):
  875. input_ids = input_ids[attention_mask[i] == 1]
  876. input_tokens = input_ids.tolist()
  877. input_token_type = []
  878. video_check_flg = False
  879. for token in input_tokens:
  880. if token == video_start_token_id:
  881. video_check_flg = True
  882. elif token == video_end_token_id:
  883. video_check_flg = False
  884. if token == image_token_id and not video_check_flg:
  885. input_token_type.append("image")
  886. elif token == image_token_id and video_check_flg:
  887. input_token_type.append("video")
  888. else:
  889. input_token_type.append("text")
  890. input_type_group = []
  891. for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]):
  892. group = list(group)
  893. start_index = group[0][0]
  894. end_index = group[-1][0] + 1
  895. input_type_group.append((key, start_index, end_index))
  896. llm_pos_ids_list = []
  897. video_frame_num = 1
  898. for modality_type, start_idx, end_idx in input_type_group:
  899. st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
  900. if modality_type == "image":
  901. t, h, w = (
  902. image_grid_thw[image_index][0],
  903. image_grid_thw[image_index][1],
  904. image_grid_thw[image_index][2],
  905. )
  906. llm_grid_t, llm_grid_h, llm_grid_w = (
  907. t.item(),
  908. h.item() // spatial_merge_size,
  909. w.item() // spatial_merge_size,
  910. )
  911. t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
  912. h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
  913. w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
  914. llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
  915. image_index += 1
  916. video_frame_num = 1
  917. elif modality_type == "video":
  918. t, h, w = (
  919. video_frame_num,
  920. video_grid_thw[video_index][1],
  921. video_grid_thw[video_index][2],
  922. )
  923. llm_grid_t, llm_grid_h, llm_grid_w = (
  924. t,
  925. h.item() // spatial_merge_size,
  926. w.item() // spatial_merge_size,
  927. )
  928. for t_idx in range(llm_grid_t):
  929. t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
  930. h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten()
  931. w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten()
  932. llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
  933. video_group_index += 1
  934. if video_group_index >= video_grid_thw[video_index][0]:
  935. video_index += 1
  936. video_group_index = 0
  937. video_frame_num += 1
  938. else:
  939. text_len = end_idx - start_idx
  940. llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
  941. video_frame_num = 1
  942. llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
  943. position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
  944. mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
  945. mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
  946. return position_ids, mrope_position_deltas
  947. else:
  948. if attention_mask is not None:
  949. position_ids = attention_mask.long().cumsum(-1) - 1
  950. position_ids.masked_fill_(attention_mask == 0, 1)
  951. position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
  952. max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
  953. mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
  954. else:
  955. position_ids = (
  956. torch.arange(input_ids.shape[1], device=input_ids.device)
  957. .view(1, 1, -1)
  958. .expand(3, input_ids.shape[0], -1)
  959. )
  960. mrope_position_deltas = torch.zeros(
  961. [input_ids.shape[0], 1],
  962. device=input_ids.device,
  963. dtype=input_ids.dtype,
  964. )
  965. return position_ids, mrope_position_deltas
  966. def get_video_features(
  967. self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
  968. ):
  969. """
  970. Encodes videos into continuous embeddings that can be forwarded to the language model.
  971. Args:
  972. pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  973. The tensors corresponding to the input videos.
  974. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  975. The temporal, height and width of feature shape of each video in LLM.
  976. """
  977. pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
  978. # reshape video_grid_thw -> [b, 3] -> [1, h, w] * frames
  979. temp_frames_hw = []
  980. for t, h, w in video_grid_thw:
  981. repeated_row = torch.tensor([1, h.item(), w.item()]).unsqueeze(0).repeat(t, 1)
  982. temp_frames_hw.append(repeated_row)
  983. flattened_video_grid_thw = torch.cat(temp_frames_hw, dim=0)
  984. video_embeds = self.visual(pixel_values_videos, grid_thw=flattened_video_grid_thw)
  985. split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
  986. video_embeds = torch.split(video_embeds, split_sizes)
  987. return video_embeds
  988. def get_placeholder_mask(
  989. self,
  990. input_ids: torch.LongTensor,
  991. inputs_embeds: torch.FloatTensor,
  992. image_features: Optional[torch.FloatTensor] = None,
  993. video_features: Optional[torch.FloatTensor] = None,
  994. ):
  995. """
  996. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  997. equal to the length of multimodal features. If the lengths are different, an error is raised.
  998. """
  999. if input_ids is None:
  1000. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  1001. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  1002. )
  1003. special_image_mask = special_image_mask.all(-1)
  1004. special_video_mask = inputs_embeds == self.get_input_embeddings()(
  1005. torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
  1006. )
  1007. special_video_mask = special_video_mask.all(-1)
  1008. else:
  1009. # GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask
  1010. special_image_mask = input_ids == self.config.image_token_id
  1011. special_video_mask = input_ids == self.config.image_token_id
  1012. n_image_tokens = special_image_mask.sum()
  1013. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  1014. if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
  1015. raise ValueError(
  1016. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
  1017. )
  1018. n_video_tokens = special_video_mask.sum()
  1019. special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  1020. if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
  1021. raise ValueError(
  1022. f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
  1023. )
  1024. return special_image_mask, special_video_mask
  1025. @auto_docstring
  1026. @can_return_tuple
  1027. def forward(
  1028. self,
  1029. input_ids: Optional[torch.LongTensor] = None,
  1030. attention_mask: Optional[torch.Tensor] = None,
  1031. position_ids: Optional[torch.LongTensor] = None,
  1032. past_key_values: Optional[Cache] = None,
  1033. inputs_embeds: Optional[torch.FloatTensor] = None,
  1034. pixel_values: Optional[torch.Tensor] = None,
  1035. pixel_values_videos: Optional[torch.FloatTensor] = None,
  1036. image_grid_thw: Optional[torch.LongTensor] = None,
  1037. video_grid_thw: Optional[torch.LongTensor] = None,
  1038. rope_deltas: Optional[torch.LongTensor] = None,
  1039. cache_position: Optional[torch.LongTensor] = None,
  1040. **kwargs: Unpack[TransformersKwargs],
  1041. ) -> Union[tuple, Glm4vModelOutputWithPast]:
  1042. r"""
  1043. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  1044. The temporal, height and width of feature shape of each image in LLM.
  1045. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  1046. The temporal, height and width of feature shape of each video in LLM.
  1047. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  1048. The rope index difference between sequence length and multimodal rope.
  1049. """
  1050. if (input_ids is None) ^ (inputs_embeds is not None):
  1051. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  1052. if inputs_embeds is None:
  1053. inputs_embeds = self.get_input_embeddings()(input_ids)
  1054. if pixel_values is not None:
  1055. image_embeds = self.get_image_features(pixel_values, image_grid_thw)
  1056. image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
  1057. image_mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds, image_features=image_embeds)
  1058. inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
  1059. if pixel_values_videos is not None:
  1060. video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
  1061. video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
  1062. _, video_mask = self.get_placeholder_mask(input_ids, inputs_embeds, video_features=video_embeds)
  1063. inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
  1064. if position_ids is None:
  1065. attention_mask_tensor = (
  1066. attention_mask if not isinstance(attention_mask, dict) else attention_mask["full_attention"]
  1067. )
  1068. if attention_mask_tensor is not None and attention_mask_tensor.ndim == 4:
  1069. attention_mask_tensor = torch.diagonal(attention_mask_tensor[:, 0], dim1=1, dim2=2)
  1070. # Only apply conversion for floating point tensors (inverted masks)
  1071. if attention_mask_tensor.dtype.is_floating_point:
  1072. attention_mask_tensor = attention_mask_tensor / torch.finfo(attention_mask_tensor.dtype).min
  1073. attention_mask_tensor = (1.0 - attention_mask_tensor).int()
  1074. # Calculate RoPE index once per generation in the pre-fill stage only.
  1075. # When compiling, we can't check tensor values thus we check only input length
  1076. # It is safe to assume that `length!=1` means we're in pre-fill because compiled
  1077. # models currently cannot do asssisted decoding
  1078. prefill_compiled_stage = is_torchdynamo_compiling() and (
  1079. (input_ids is not None and input_ids.shape[1] != 1)
  1080. or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
  1081. )
  1082. prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
  1083. (cache_position is not None and cache_position[0] == 0)
  1084. or (past_key_values is None or past_key_values.get_seq_length() == 0)
  1085. )
  1086. if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
  1087. position_ids, rope_deltas = self.get_rope_index(
  1088. input_ids,
  1089. image_grid_thw,
  1090. video_grid_thw,
  1091. attention_mask=attention_mask_tensor,
  1092. )
  1093. self.rope_deltas = rope_deltas
  1094. # then use the prev pre-calculated rope-deltas to get the correct position ids
  1095. else:
  1096. batch_size, seq_length, _ = inputs_embeds.shape
  1097. delta = (
  1098. (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
  1099. if cache_position is not None
  1100. else 0
  1101. )
  1102. position_ids = torch.arange(seq_length, device=inputs_embeds.device)
  1103. position_ids = position_ids.view(1, -1).expand(batch_size, -1)
  1104. if cache_position is not None: # otherwise `deltas` is an int `0`
  1105. delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
  1106. position_ids = position_ids.add(delta)
  1107. position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
  1108. outputs = self.language_model(
  1109. input_ids=None,
  1110. position_ids=position_ids,
  1111. attention_mask=attention_mask,
  1112. past_key_values=past_key_values,
  1113. inputs_embeds=inputs_embeds,
  1114. cache_position=cache_position,
  1115. **kwargs,
  1116. )
  1117. return Glm4vModelOutputWithPast(
  1118. last_hidden_state=outputs.last_hidden_state,
  1119. past_key_values=outputs.past_key_values,
  1120. hidden_states=outputs.hidden_states,
  1121. attentions=outputs.attentions,
  1122. rope_deltas=self.rope_deltas,
  1123. )
  1124. class Glm4vCausalLMOutputWithPast(Qwen2_5_VLCausalLMOutputWithPast):
  1125. pass
  1126. class Glm4vForConditionalGeneration(Qwen2_5_VLForConditionalGeneration):
  1127. _checkpoint_conversion_mapping = {}
  1128. def forward(
  1129. self,
  1130. input_ids: Optional[torch.LongTensor] = None,
  1131. attention_mask: Optional[torch.Tensor] = None,
  1132. position_ids: Optional[torch.LongTensor] = None,
  1133. past_key_values: Optional[Cache] = None,
  1134. inputs_embeds: Optional[torch.FloatTensor] = None,
  1135. labels: Optional[torch.LongTensor] = None,
  1136. pixel_values: Optional[torch.Tensor] = None,
  1137. pixel_values_videos: Optional[torch.FloatTensor] = None,
  1138. image_grid_thw: Optional[torch.LongTensor] = None,
  1139. video_grid_thw: Optional[torch.LongTensor] = None,
  1140. rope_deltas: Optional[torch.LongTensor] = None,
  1141. cache_position: Optional[torch.LongTensor] = None,
  1142. logits_to_keep: Union[int, torch.Tensor] = 0,
  1143. **kwargs: Unpack[TransformersKwargs],
  1144. ) -> Union[tuple, Glm4vCausalLMOutputWithPast]:
  1145. r"""
  1146. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1147. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1148. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1149. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1150. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  1151. The temporal, height and width of feature shape of each image in LLM.
  1152. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  1153. The temporal, height and width of feature shape of each video in LLM.
  1154. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  1155. The rope index difference between sequence length and multimodal rope.
  1156. Example:
  1157. ```python
  1158. >>> from PIL import Image
  1159. >>> import requests
  1160. >>> from transformers import AutoProcessor, Glm4vForConditionalGeneration
  1161. >>> model = Glm4vForConditionalGeneration.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
  1162. >>> processor = AutoProcessor.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
  1163. >>> messages = [
  1164. {
  1165. "role": "user",
  1166. "content": [
  1167. {"type": "image"},
  1168. {"type": "text", "text": "What is shown in this image?"},
  1169. ],
  1170. },
  1171. ]
  1172. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  1173. >>> image = Image.open(requests.get(url, stream=True).raw)
  1174. >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
  1175. >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
  1176. >>> # Generate
  1177. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  1178. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1179. "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 ..."
  1180. ```"""
  1181. outputs = self.model(
  1182. input_ids=input_ids,
  1183. pixel_values=pixel_values,
  1184. pixel_values_videos=pixel_values_videos,
  1185. image_grid_thw=image_grid_thw,
  1186. video_grid_thw=video_grid_thw,
  1187. position_ids=position_ids,
  1188. attention_mask=attention_mask,
  1189. past_key_values=past_key_values,
  1190. inputs_embeds=inputs_embeds,
  1191. cache_position=cache_position,
  1192. **kwargs,
  1193. )
  1194. hidden_states = outputs[0]
  1195. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1196. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1197. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1198. loss = None
  1199. if labels is not None:
  1200. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
  1201. return Glm4vCausalLMOutputWithPast(
  1202. loss=loss,
  1203. logits=logits,
  1204. past_key_values=outputs.past_key_values,
  1205. hidden_states=outputs.hidden_states,
  1206. attentions=outputs.attentions,
  1207. rope_deltas=outputs.rope_deltas,
  1208. )
  1209. def prepare_inputs_for_generation(
  1210. self,
  1211. input_ids,
  1212. past_key_values=None,
  1213. attention_mask=None,
  1214. inputs_embeds=None,
  1215. cache_position=None,
  1216. position_ids=None,
  1217. use_cache=True,
  1218. pixel_values=None,
  1219. pixel_values_videos=None,
  1220. image_grid_thw=None,
  1221. video_grid_thw=None,
  1222. **kwargs,
  1223. ):
  1224. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  1225. model_inputs = super().prepare_inputs_for_generation(
  1226. input_ids,
  1227. past_key_values=past_key_values,
  1228. attention_mask=attention_mask,
  1229. inputs_embeds=inputs_embeds,
  1230. cache_position=cache_position,
  1231. position_ids=position_ids,
  1232. pixel_values=pixel_values,
  1233. pixel_values_videos=pixel_values_videos,
  1234. image_grid_thw=image_grid_thw,
  1235. video_grid_thw=video_grid_thw,
  1236. use_cache=use_cache,
  1237. **kwargs,
  1238. )
  1239. # GLM-4.1V position_ids are prepareed with rope_deltas in forward
  1240. model_inputs["position_ids"] = None
  1241. if cache_position[0] != 0:
  1242. model_inputs["pixel_values"] = None
  1243. model_inputs["pixel_values_videos"] = None
  1244. return model_inputs
  1245. def _get_image_nums_and_video_nums(
  1246. self,
  1247. input_ids: Optional[torch.LongTensor],
  1248. inputs_embeds: Optional[torch.Tensor] = None,
  1249. ) -> tuple[torch.Tensor, torch.Tensor]:
  1250. """
  1251. Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
  1252. These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
  1253. Args:
  1254. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1255. Indices of input sequence tokens in the vocabulary.
  1256. Returns:
  1257. image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
  1258. video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
  1259. """
  1260. if inputs_embeds is not None:
  1261. is_image = (
  1262. inputs_embeds
  1263. == self.get_input_embeddings()(
  1264. torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
  1265. )
  1266. )[..., 0]
  1267. is_video_start = (
  1268. inputs_embeds
  1269. == self.get_input_embeddings()(
  1270. torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
  1271. )
  1272. )[..., 0]
  1273. is_video_end = (
  1274. inputs_embeds
  1275. == self.get_input_embeddings()(
  1276. torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
  1277. )
  1278. )[..., 0]
  1279. else:
  1280. is_image = input_ids == self.config.image_start_token_id
  1281. is_video_start = input_ids == self.config.video_start_token_id
  1282. is_video_end = input_ids == self.config.video_end_token_id
  1283. # Cumulative sum to track if we're inside a video span
  1284. # We'll assume well-formed video tags (i.e. matching starts and ends)
  1285. video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
  1286. inside_video = video_level > 0 # shape (batch_size, seq_length)
  1287. # Mask out image tokens that are inside video spans
  1288. standalone_images = is_image & (~inside_video)
  1289. # Count per batch
  1290. image_counts = standalone_images.sum(dim=1)
  1291. video_counts = is_video_start.sum(dim=1)
  1292. return image_counts, video_counts
  1293. class Glm4vVideosProcessorKwargs(Qwen2_5_VLVideosProcessorKwargs):
  1294. pass
  1295. class Glm4vImagesKwargs(ImagesKwargs):
  1296. patch_size: Optional[int]
  1297. temporal_patch_size: Optional[int]
  1298. merge_size: Optional[int]
  1299. class Glm4vProcessorKwargs(Qwen2_VLProcessorKwargs):
  1300. images_kwargs: Glm4vImagesKwargs
  1301. videos_kwargs: Glm4vVideosProcessorKwargs
  1302. _defaults = {
  1303. "text_kwargs": {
  1304. "padding": False,
  1305. "return_token_type_ids": False,
  1306. "return_mm_token_type_ids": False,
  1307. },
  1308. "videos_kwargs": {"return_metadata": True},
  1309. }
  1310. class Glm4vProcessor(Qwen2_VLProcessor):
  1311. r"""
  1312. Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor.
  1313. [`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information.
  1314. Args:
  1315. image_processor ([`Glm4vProcessor`], *optional*):
  1316. The image processor is a required input.
  1317. tokenizer ([`PreTrainedTokenizerFast`], *optional*):
  1318. The tokenizer is a required input.
  1319. video_processor ([`Glm4vVideoProcessor`], *optional*):
  1320. The video processor is a required input.
  1321. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  1322. in a chat into a tokenizable string.
  1323. """
  1324. tokenizer_class = ("PreTrainedTokenizer", "PreTrainedTokenizerFast")
  1325. def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
  1326. super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
  1327. self.image_token = "<|image|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
  1328. self.video_token = "<|video|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
  1329. def __call__(
  1330. self,
  1331. images: Optional[ImageInput] = None,
  1332. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  1333. videos: Optional[VideoInput] = None,
  1334. **kwargs: Unpack[Glm4vProcessorKwargs],
  1335. ) -> BatchFeature:
  1336. """
  1337. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  1338. and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
  1339. the text.
  1340. Args:
  1341. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  1342. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  1343. tensor. Both channels-first and channels-last formats are supported.
  1344. text (`str`, `List[str]`, `List[List[str]]`):
  1345. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  1346. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  1347. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  1348. videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
  1349. The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
  1350. tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
  1351. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  1352. If set, will return tensors of a particular framework. Acceptable values are:
  1353. - `'tf'`: Return TensorFlow `tf.constant` objects.
  1354. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  1355. - `'np'`: Return NumPy `np.ndarray` objects.
  1356. - `'jax'`: Return JAX `jnp.ndarray` objects.
  1357. Returns:
  1358. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  1359. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  1360. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  1361. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  1362. `None`).
  1363. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  1364. - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
  1365. - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
  1366. - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
  1367. """
  1368. output_kwargs = self._merge_kwargs(
  1369. Glm4vProcessorKwargs,
  1370. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  1371. **kwargs,
  1372. )
  1373. if images is not None:
  1374. image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
  1375. image_grid_thw = image_inputs["image_grid_thw"]
  1376. else:
  1377. image_inputs = {}
  1378. image_grid_thw = None
  1379. if videos is not None:
  1380. videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"])
  1381. # If user has not requested video metadata, pop it
  1382. if "return_metadata" not in kwargs:
  1383. video_metadata = videos_inputs.pop("video_metadata")
  1384. else:
  1385. video_metadata = videos_inputs["video_metadata"]
  1386. video_grid_thw = videos_inputs["video_grid_thw"]
  1387. else:
  1388. videos_inputs = {}
  1389. video_grid_thw = None
  1390. if not isinstance(text, list):
  1391. text = [text]
  1392. text = text.copy() # below lines change text in-place
  1393. if image_grid_thw is not None:
  1394. merge_length = self.image_processor.merge_size**2
  1395. index = 0
  1396. for i in range(len(text)):
  1397. while self.image_token in text[i]:
  1398. num_image_tokens = image_grid_thw[index].prod() // merge_length
  1399. text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
  1400. index += 1
  1401. text[i] = text[i].replace("<|placeholder|>", self.image_token)
  1402. if video_grid_thw is not None:
  1403. merge_length = self.video_processor.merge_size**2
  1404. video_index = 0
  1405. for i in range(len(text)):
  1406. while self.video_token in text[i]:
  1407. num_frames = video_grid_thw[video_index][0]
  1408. video_structure = ""
  1409. metadata = video_metadata[video_index]
  1410. if metadata.fps is None:
  1411. logger.warning_once(
  1412. "SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. "
  1413. "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. "
  1414. "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
  1415. )
  1416. metadata.fps = 24 if metadata.fps is None else metadata.fps
  1417. timestamps = metadata.timestamps[::2] # mrope
  1418. unique_timestamps = []
  1419. for idx in range(0, len(timestamps)):
  1420. unique_timestamps.append(timestamps[idx])
  1421. selected_timestamps = unique_timestamps[:num_frames]
  1422. while len(selected_timestamps) < num_frames:
  1423. selected_timestamps.append(selected_timestamps[-1] if selected_timestamps else 0)
  1424. for frame_idx in range(num_frames):
  1425. timestamp_sec = selected_timestamps[frame_idx]
  1426. frame_structure = f"<|begin_of_image|>{self.image_token}<|end_of_image|>{int(timestamp_sec)}"
  1427. video_structure += frame_structure
  1428. text[i] = text[i].replace(self.video_token, video_structure, 1)
  1429. num_image_tokens = (
  1430. video_grid_thw[video_index].prod() // merge_length // video_grid_thw[video_index][0]
  1431. )
  1432. for frame_idx in range(num_frames):
  1433. if self.image_token in text[i]:
  1434. text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
  1435. video_index += 1
  1436. text[i] = text[i].replace("<|placeholder|>", self.image_token)
  1437. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  1438. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  1439. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
  1440. self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
  1441. if return_mm_token_type_ids:
  1442. array_ids = np.array(text_inputs["input_ids"])
  1443. mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
  1444. mm_token_type_ids[array_ids == self.image_token_id] = 1
  1445. text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
  1446. return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
  1447. __all__ = [
  1448. "Glm4vConfig",
  1449. "Glm4vTextConfig",
  1450. "Glm4vForConditionalGeneration",
  1451. "Glm4vModel",
  1452. "Glm4vPreTrainedModel",
  1453. "Glm4vProcessor",
  1454. "Glm4vTextModel",
  1455. ]