modeling_glm4v.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/glm4v/modular_glm4v.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_glm4v.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 The ZhipuAI Inc. team and HuggingFace Inc. team. All rights reserved.
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. import itertools
  22. from dataclasses import dataclass
  23. from typing import Any, Callable, Optional, Union
  24. import torch
  25. import torch.nn as nn
  26. import torch.nn.functional as F
  27. from torch.nn import LayerNorm
  28. from ...activations import ACT2FN
  29. from ...cache_utils import Cache, DynamicCache
  30. from ...generation import GenerationMixin
  31. from ...integrations import use_kernel_forward_from_hub
  32. from ...masking_utils import create_causal_mask
  33. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  34. from ...modeling_layers import GradientCheckpointingLayer
  35. from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
  36. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  37. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  38. from ...processing_utils import Unpack
  39. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling
  40. from ...utils.generic import check_model_inputs
  41. from .configuration_glm4v import Glm4vConfig, Glm4vTextConfig, Glm4vVisionConfig
  42. @use_kernel_forward_from_hub("RMSNorm")
  43. class Glm4vRMSNorm(nn.Module):
  44. def __init__(self, hidden_size, eps=1e-6):
  45. """
  46. Glm4vRMSNorm is equivalent to T5LayerNorm
  47. """
  48. super().__init__()
  49. self.weight = nn.Parameter(torch.ones(hidden_size))
  50. self.variance_epsilon = eps
  51. def forward(self, hidden_states):
  52. input_dtype = hidden_states.dtype
  53. hidden_states = hidden_states.to(torch.float32)
  54. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  55. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  56. return self.weight * hidden_states.to(input_dtype)
  57. def extra_repr(self):
  58. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  59. class Glm4VisionMlp(nn.Module):
  60. def __init__(self, config, bias: bool = False):
  61. super().__init__()
  62. self.hidden_size = config.hidden_size
  63. self.intermediate_size = config.out_hidden_size
  64. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
  65. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
  66. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
  67. self.act_fn = ACT2FN[config.hidden_act]
  68. def forward(self, hidden_state):
  69. return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
  70. class Glm4vVisionPatchEmbed(nn.Module):
  71. def __init__(self, config: Glm4vVisionConfig) -> None:
  72. super().__init__()
  73. self.patch_size = config.patch_size
  74. self.temporal_patch_size = config.temporal_patch_size
  75. self.in_channels = config.in_channels
  76. self.embed_dim = config.hidden_size
  77. kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
  78. self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size)
  79. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  80. target_dtype = self.proj.weight.dtype
  81. hidden_states = hidden_states.view(
  82. -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
  83. )
  84. hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
  85. return hidden_states
  86. class Glm4vVisionRotaryEmbedding(nn.Module):
  87. inv_freq: torch.Tensor # fix linting for `register_buffer`
  88. def __init__(self, dim: int, theta: float = 10000.0) -> None:
  89. super().__init__()
  90. inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
  91. self.register_buffer("inv_freq", inv_freq, persistent=False)
  92. def forward(self, seqlen: int) -> torch.Tensor:
  93. seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
  94. freqs = torch.outer(seq, self.inv_freq)
  95. return freqs
  96. class Glm4vVisionPatchMerger(nn.Module):
  97. def __init__(self, dim: int, context_dim: int, hidden_act: str, bias: bool = False) -> None:
  98. super().__init__()
  99. self.proj = nn.Linear(dim, dim, bias=bias)
  100. self.post_projection_norm = LayerNorm(dim)
  101. self.gate_proj = nn.Linear(dim, context_dim, bias=bias)
  102. self.up_proj = nn.Linear(dim, context_dim, bias=bias)
  103. self.down_proj = nn.Linear(context_dim, dim, bias=bias)
  104. self.act1 = nn.GELU()
  105. self.act_fn = ACT2FN[hidden_act]
  106. def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
  107. hidden_state = self.proj(hidden_state)
  108. hidden_state = self.act1(self.post_projection_norm(hidden_state))
  109. return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
  110. class Glm4vVisionEmbeddings(nn.Module):
  111. def __init__(self, config: Glm4vVisionConfig):
  112. super().__init__()
  113. self.config = config
  114. self.embed_dim = config.hidden_size
  115. self.image_size = config.image_size
  116. self.patch_size = config.patch_size
  117. self.num_patches = (self.image_size // self.patch_size) ** 2
  118. self.num_positions = self.num_patches
  119. self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
  120. self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
  121. def forward(self, embeddings, lengths, image_shapes, h_coords, w_coords) -> torch.Tensor:
  122. """
  123. Forward pass with integrated position encoding adaptation using 2D interpolation.
  124. Args:
  125. embeddings: Input embeddings tensor
  126. lengths (torch.Tensor): Sequence lengths for each image in the batch.
  127. image_shapes (torch.Tensor): Tensor of shape [batch_size, 3] representing the image shapes (t, h, w).
  128. h_coords (torch.Tensor): Tensor of shape [total_seq] representing the h coordinate for each patch.
  129. w_coords (torch.Tensor): Tensor of shape [total_seq] representing the w coordinate for each patch.
  130. Returns:
  131. torch.Tensor: Embeddings with adapted position encoding added.
  132. """
  133. # Get position embedding parameters
  134. pos_embed_weight = self.position_embedding.weight
  135. hidden_size = pos_embed_weight.shape[1]
  136. total_seq = h_coords.shape[0]
  137. device = pos_embed_weight.device
  138. # Move coordinates to correct device
  139. h_coords, w_coords = h_coords.to(device), w_coords.to(device)
  140. # Handle empty sequence case
  141. if total_seq == 0:
  142. adapted_pos_embed = torch.empty(0, hidden_size, device=device, dtype=pos_embed_weight.dtype)
  143. else:
  144. # Convert inputs to tensors if needed
  145. if isinstance(lengths, list):
  146. lengths = torch.tensor(lengths, device=device, dtype=torch.long)
  147. if not isinstance(image_shapes, torch.Tensor):
  148. image_shapes = torch.tensor(image_shapes, device=device, dtype=torch.long)
  149. # Prepare 2D position embedding
  150. orig_size_sq = pos_embed_weight.shape[0]
  151. orig_size = int(orig_size_sq**0.5)
  152. pos_embed_2d = (
  153. pos_embed_weight.view(orig_size, orig_size, hidden_size)
  154. .permute(2, 0, 1)
  155. .unsqueeze(0)
  156. .to(device=device, dtype=torch.float32)
  157. )
  158. # Calculate target dimensions for each patch
  159. target_h = torch.cat([image_shapes[i, 1].repeat(lengths[i]) for i in range(len(lengths))]).to(
  160. device=device, dtype=torch.float32
  161. )
  162. target_w = torch.cat([image_shapes[i, 2].repeat(lengths[i]) for i in range(len(lengths))]).to(
  163. device=device, dtype=torch.float32
  164. )
  165. # Normalize coordinates to [-1, 1] range for grid_sample
  166. h_coords = h_coords.to(device=device, dtype=torch.float32)
  167. w_coords = w_coords.to(device=device, dtype=torch.float32)
  168. norm_w = ((w_coords + 0.5) / target_w) * 2 - 1
  169. norm_h = ((h_coords + 0.5) / target_h) * 2 - 1
  170. # Create sampling grid
  171. grid = torch.stack((norm_w, norm_h), dim=-1).unsqueeze(0).unsqueeze(2)
  172. # Perform bicubic interpolation
  173. interpolated_embed_fp32 = F.grid_sample(
  174. pos_embed_2d, grid, mode="bicubic", align_corners=False, padding_mode="border"
  175. )
  176. # Reshape and convert back to original dtype
  177. adapted_pos_embed_fp32 = interpolated_embed_fp32.squeeze(0).squeeze(-1).permute(1, 0)
  178. adapted_pos_embed = adapted_pos_embed_fp32.to(pos_embed_weight.dtype).to(embeddings.device)
  179. # Add adapted position encoding to embeddings
  180. embeddings = embeddings + adapted_pos_embed
  181. return embeddings
  182. def rotate_half(x):
  183. """Rotates half the hidden dims of the input."""
  184. x1 = x[..., : x.shape[-1] // 2]
  185. x2 = x[..., x.shape[-1] // 2 :]
  186. return torch.cat((-x2, x1), dim=-1)
  187. def apply_rotary_pos_emb_vision(
  188. q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
  189. ) -> tuple[torch.Tensor, torch.Tensor]:
  190. orig_q_dtype = q.dtype
  191. orig_k_dtype = k.dtype
  192. q, k = q.float(), k.float()
  193. cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
  194. q_embed = (q * cos) + (rotate_half(q) * sin)
  195. k_embed = (k * cos) + (rotate_half(k) * sin)
  196. q_embed = q_embed.to(orig_q_dtype)
  197. k_embed = k_embed.to(orig_k_dtype)
  198. return q_embed, k_embed
  199. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  200. """
  201. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  202. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  203. """
  204. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  205. if n_rep == 1:
  206. return hidden_states
  207. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  208. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  209. def eager_attention_forward(
  210. module: nn.Module,
  211. query: torch.Tensor,
  212. key: torch.Tensor,
  213. value: torch.Tensor,
  214. attention_mask: Optional[torch.Tensor],
  215. scaling: float,
  216. dropout: float = 0.0,
  217. **kwargs: Unpack[TransformersKwargs],
  218. ):
  219. key_states = repeat_kv(key, module.num_key_value_groups)
  220. value_states = repeat_kv(value, module.num_key_value_groups)
  221. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  222. if attention_mask is not None:
  223. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  224. attn_weights = attn_weights + causal_mask
  225. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  226. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  227. attn_output = torch.matmul(attn_weights, value_states)
  228. attn_output = attn_output.transpose(1, 2).contiguous()
  229. return attn_output, attn_weights
  230. class Glm4vVisionAttention(nn.Module):
  231. def __init__(self, config: Glm4vVisionConfig) -> None:
  232. super().__init__()
  233. self.dim = config.hidden_size
  234. self.num_heads = config.num_heads
  235. self.head_dim = self.dim // self.num_heads
  236. self.num_key_value_groups = 1 # needed for eager attention
  237. self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.attention_bias)
  238. self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
  239. self.scaling = self.head_dim**-0.5
  240. self.config = config
  241. self.attention_dropout = config.attention_dropout
  242. self.is_causal = False
  243. def forward(
  244. self,
  245. hidden_states: torch.Tensor,
  246. cu_seqlens: torch.Tensor,
  247. rotary_pos_emb: Optional[torch.Tensor] = None,
  248. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  249. **kwargs,
  250. ) -> torch.Tensor:
  251. seq_length = hidden_states.shape[0]
  252. query_states, key_states, value_states = (
  253. self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
  254. )
  255. cos, sin = position_embeddings
  256. query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
  257. query_states = query_states.transpose(0, 1).unsqueeze(0)
  258. key_states = key_states.transpose(0, 1).unsqueeze(0)
  259. value_states = value_states.transpose(0, 1).unsqueeze(0)
  260. attention_interface: Callable = eager_attention_forward
  261. if self.config._attn_implementation != "eager":
  262. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  263. if self.config._attn_implementation == "flash_attention_2":
  264. # Flash Attention 2: Use cu_seqlens for variable length attention
  265. max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
  266. attn_output, _ = attention_interface(
  267. self,
  268. query_states,
  269. key_states,
  270. value_states,
  271. attention_mask=None,
  272. scaling=self.scaling,
  273. dropout=0.0 if not self.training else self.attention_dropout,
  274. cu_seq_lens_q=cu_seqlens,
  275. cu_seq_lens_k=cu_seqlens,
  276. max_length_q=max_seqlen,
  277. max_length_k=max_seqlen,
  278. is_causal=False,
  279. **kwargs,
  280. )
  281. else:
  282. # Other implementations: Process each chunk separately
  283. lengths = cu_seqlens[1:] - cu_seqlens[:-1]
  284. splits = [
  285. torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
  286. ]
  287. attn_outputs = [
  288. attention_interface(
  289. self,
  290. q,
  291. k,
  292. v,
  293. attention_mask=None,
  294. scaling=self.scaling,
  295. dropout=0.0 if not self.training else self.attention_dropout,
  296. is_causal=False,
  297. **kwargs,
  298. )[0]
  299. for q, k, v in zip(*splits)
  300. ]
  301. attn_output = torch.cat(attn_outputs, dim=1)
  302. attn_output = attn_output.reshape(seq_length, -1).contiguous()
  303. attn_output = self.proj(attn_output)
  304. return attn_output
  305. class Glm4vVisionBlock(GradientCheckpointingLayer):
  306. def __init__(self, config) -> None:
  307. super().__init__()
  308. self.norm1 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  309. self.norm2 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  310. self.attn = Glm4vVisionAttention(config)
  311. self.mlp = Glm4VisionMlp(config, bias=False)
  312. def forward(
  313. self,
  314. hidden_states: torch.Tensor,
  315. cu_seqlens: torch.Tensor,
  316. rotary_pos_emb: Optional[torch.Tensor] = None,
  317. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  318. **kwargs,
  319. ) -> torch.Tensor:
  320. hidden_states = hidden_states + self.attn(
  321. self.norm1(hidden_states),
  322. cu_seqlens=cu_seqlens,
  323. rotary_pos_emb=rotary_pos_emb,
  324. position_embeddings=position_embeddings,
  325. **kwargs,
  326. )
  327. hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
  328. return hidden_states
  329. class Glm4vTextRotaryEmbedding(nn.Module):
  330. inv_freq: torch.Tensor # fix linting for `register_buffer`
  331. def __init__(self, config: Glm4vTextConfig, device=None):
  332. super().__init__()
  333. # BC: "rope_type" was originally "type"
  334. if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
  335. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  336. else:
  337. self.rope_type = "default"
  338. self.max_seq_len_cached = config.max_position_embeddings
  339. self.original_max_seq_len = config.max_position_embeddings
  340. self.config = config
  341. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  342. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  343. self.register_buffer("inv_freq", inv_freq, persistent=False)
  344. self.original_inv_freq = self.inv_freq
  345. @torch.no_grad()
  346. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  347. def forward(self, x, position_ids):
  348. # In contrast to other models, Glm4vText has different position ids for the grids
  349. # So we expand the inv_freq to shape (3, ...)
  350. inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
  351. position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
  352. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  353. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  354. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
  355. emb = torch.cat((freqs, freqs), dim=-1)
  356. cos = emb.cos() * self.attention_scaling
  357. sin = emb.sin() * self.attention_scaling
  358. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  359. def rotate_half_llm(x):
  360. """Rotates half the hidden dims of the input."""
  361. x1 = x[..., 0::2]
  362. x2 = x[..., 1::2]
  363. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  364. def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
  365. """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
  366. Explanation:
  367. Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
  368. sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
  369. vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
  370. Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
  371. For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
  372. height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
  373. difference with modern LLMs.
  374. Args:
  375. q (`torch.Tensor`): The query tensor.
  376. k (`torch.Tensor`): The key tensor.
  377. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  378. sin (`torch.Tensor`): The sine part of the rotary embedding.
  379. mrope_section(`List(int)`):
  380. Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
  381. unsqueeze_dim (`int`, *optional*, defaults to 1):
  382. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  383. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  384. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  385. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  386. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  387. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  388. Returns:
  389. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  390. """
  391. mrope_section = mrope_section * 2
  392. cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
  393. unsqueeze_dim
  394. )
  395. sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
  396. unsqueeze_dim
  397. )
  398. # Interleave them instead of usual shape
  399. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  400. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  401. # Keep half or full tensor for later concatenation
  402. rotary_dim = cos.shape[-1]
  403. q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
  404. k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
  405. # Apply rotary embeddings on the first half or full tensor
  406. q_embed = (q_rot * cos) + (rotate_half_llm(q_rot) * sin)
  407. k_embed = (k_rot * cos) + (rotate_half_llm(k_rot) * sin)
  408. # Concatenate back to full shape
  409. q_embed = torch.cat([q_embed, q_pass], dim=-1)
  410. k_embed = torch.cat([k_embed, k_pass], dim=-1)
  411. return q_embed, k_embed
  412. class Glm4vTextAttention(nn.Module):
  413. """
  414. Multi-headed attention from 'Attention Is All You Need' paper.
  415. and "Generating Long Sequences with Sparse Transformers".
  416. """
  417. def __init__(self, config: Glm4vTextConfig, layer_idx: Optional[int] = None):
  418. super().__init__()
  419. self.config = config
  420. self.layer_idx = layer_idx
  421. self.hidden_size = config.hidden_size
  422. self.num_heads = config.num_attention_heads
  423. self.head_dim = self.hidden_size // self.num_heads
  424. self.num_key_value_heads = config.num_key_value_heads
  425. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  426. self.is_causal = True
  427. self.attention_dropout = config.attention_dropout
  428. self.rope_scaling = config.rope_scaling
  429. self.scaling = self.head_dim**-0.5
  430. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
  431. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  432. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
  433. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
  434. def forward(
  435. self,
  436. hidden_states: torch.Tensor,
  437. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  438. attention_mask: Optional[torch.Tensor] = None,
  439. position_ids: Optional[torch.LongTensor] = None,
  440. past_key_values: Optional[Cache] = None,
  441. cache_position: Optional[torch.LongTensor] = None,
  442. **kwargs: Unpack[FlashAttentionKwargs],
  443. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  444. bsz, q_len, _ = hidden_states.size()
  445. query_states = self.q_proj(hidden_states)
  446. key_states = self.k_proj(hidden_states)
  447. value_states = self.v_proj(hidden_states)
  448. query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  449. key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  450. value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
  451. cos, sin = position_embeddings
  452. query_states, key_states = apply_multimodal_rotary_pos_emb( # diff with Llama
  453. query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
  454. )
  455. if past_key_values is not None:
  456. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
  457. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  458. attention_interface: Callable = eager_attention_forward
  459. if self.config._attn_implementation != "eager":
  460. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  461. attn_output, attn_weights = attention_interface(
  462. self,
  463. query_states,
  464. key_states,
  465. value_states,
  466. attention_mask,
  467. dropout=0.0 if not self.training else self.attention_dropout,
  468. scaling=self.scaling,
  469. **kwargs,
  470. )
  471. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  472. attn_output = self.o_proj(attn_output)
  473. return attn_output, attn_weights
  474. class Glm4vTextMLP(nn.Module):
  475. def __init__(self, config):
  476. super().__init__()
  477. self.config = config
  478. self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
  479. self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
  480. self.activation_fn = ACT2FN[config.hidden_act]
  481. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  482. up_states = self.gate_up_proj(hidden_states)
  483. gate, up_states = up_states.chunk(2, dim=-1)
  484. up_states = up_states * self.activation_fn(gate)
  485. return self.down_proj(up_states)
  486. class Glm4vTextDecoderLayer(GradientCheckpointingLayer):
  487. def __init__(self, config: Glm4vTextConfig, layer_idx: int):
  488. super().__init__()
  489. self.hidden_size = config.hidden_size
  490. self.self_attn = Glm4vTextAttention(config, layer_idx)
  491. self.mlp = Glm4vTextMLP(config)
  492. self.input_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  493. self.post_attention_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  494. self.post_self_attn_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  495. self.post_mlp_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  496. def forward(
  497. self,
  498. hidden_states: torch.Tensor,
  499. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  500. attention_mask: Optional[torch.Tensor] = None,
  501. position_ids: Optional[torch.LongTensor] = None,
  502. past_key_values: Optional[Cache] = None,
  503. output_attentions: Optional[bool] = False,
  504. use_cache: Optional[bool] = False,
  505. cache_position: Optional[torch.LongTensor] = None,
  506. **kwargs,
  507. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  508. residual = hidden_states
  509. hidden_states = self.input_layernorm(hidden_states)
  510. # Self Attention
  511. hidden_states, _ = self.self_attn(
  512. hidden_states=hidden_states,
  513. position_embeddings=position_embeddings,
  514. attention_mask=attention_mask,
  515. position_ids=position_ids,
  516. past_key_values=past_key_values,
  517. output_attentions=output_attentions,
  518. use_cache=use_cache,
  519. cache_position=cache_position,
  520. **kwargs,
  521. )
  522. hidden_states = self.post_self_attn_layernorm(hidden_states)
  523. hidden_states = residual + hidden_states
  524. # Fully Connected
  525. residual = hidden_states
  526. hidden_states = self.post_attention_layernorm(hidden_states)
  527. hidden_states = self.mlp(hidden_states)
  528. hidden_states = self.post_mlp_layernorm(hidden_states)
  529. hidden_states = residual + hidden_states
  530. return hidden_states
  531. @dataclass
  532. @auto_docstring(
  533. custom_intro="""
  534. Base class for Llava outputs, with hidden states and attentions.
  535. """
  536. )
  537. class Glm4vModelOutputWithPast(ModelOutput):
  538. r"""
  539. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  540. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  541. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  542. `past_key_values` input) to speed up sequential decoding.
  543. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  544. The rope index difference between sequence length and multimodal rope.
  545. """
  546. last_hidden_state: Optional[torch.FloatTensor] = None
  547. past_key_values: Optional[Cache] = None
  548. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  549. attentions: Optional[tuple[torch.FloatTensor]] = None
  550. rope_deltas: Optional[torch.LongTensor] = None
  551. @auto_docstring
  552. class Glm4vPreTrainedModel(PreTrainedModel):
  553. config: Glm4vConfig
  554. base_model_prefix = "model"
  555. supports_gradient_checkpointing = True
  556. _no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
  557. _skip_keys_device_placement = "past_key_values"
  558. _supports_flash_attn = True
  559. _supports_sdpa = True
  560. _can_compile_fullgraph = True
  561. _supports_attention_backend = True
  562. _can_record_outputs = {
  563. "hidden_states": Glm4vTextDecoderLayer,
  564. "attentions": Glm4vTextAttention,
  565. }
  566. class Glm4vVisionModel(Glm4vPreTrainedModel):
  567. config: Glm4vVisionConfig
  568. _no_split_modules = ["Glm4vVisionBlock"]
  569. def __init__(self, config) -> None:
  570. super().__init__(config)
  571. self.spatial_merge_size = config.spatial_merge_size
  572. self.patch_size = config.patch_size
  573. self.embeddings = Glm4vVisionEmbeddings(config)
  574. self.patch_embed = Glm4vVisionPatchEmbed(config)
  575. head_dim = config.hidden_size // config.num_heads
  576. self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(head_dim // 2)
  577. self.blocks = nn.ModuleList([Glm4vVisionBlock(config) for _ in range(config.depth)])
  578. self.merger = Glm4vVisionPatchMerger(
  579. dim=config.out_hidden_size, context_dim=config.intermediate_size, hidden_act=config.hidden_act
  580. )
  581. self.post_conv_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  582. self.downsample = nn.Conv2d(
  583. in_channels=config.hidden_size,
  584. out_channels=config.out_hidden_size,
  585. kernel_size=config.spatial_merge_size,
  586. stride=config.spatial_merge_size,
  587. )
  588. self.post_layernorm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  589. self.gradient_checkpointing = False
  590. self.post_init()
  591. def rot_pos_emb(self, grid_thw):
  592. pos_ids = []
  593. for t, h, w in grid_thw:
  594. hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
  595. hpos_ids = hpos_ids.reshape(
  596. h // self.spatial_merge_size,
  597. self.spatial_merge_size,
  598. w // self.spatial_merge_size,
  599. self.spatial_merge_size,
  600. )
  601. hpos_ids = hpos_ids.permute(0, 2, 1, 3)
  602. hpos_ids = hpos_ids.flatten()
  603. wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
  604. wpos_ids = wpos_ids.reshape(
  605. h // self.spatial_merge_size,
  606. self.spatial_merge_size,
  607. w // self.spatial_merge_size,
  608. self.spatial_merge_size,
  609. )
  610. wpos_ids = wpos_ids.permute(0, 2, 1, 3)
  611. wpos_ids = wpos_ids.flatten()
  612. pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
  613. pos_ids = torch.cat(pos_ids, dim=0)
  614. max_grid_size = grid_thw[:, 1:].max()
  615. rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
  616. rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
  617. return rotary_pos_emb, pos_ids
  618. def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
  619. """
  620. Args:
  621. hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
  622. The final hidden states of the model.
  623. grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
  624. The temporal, height and width of feature shape of each image in LLM.
  625. Returns:
  626. `torch.Tensor`: hidden_states.
  627. """
  628. hidden_states = self.patch_embed(hidden_states)
  629. hidden_states = self.post_conv_layernorm(hidden_states)
  630. rotary_pos_emb, image_type_ids = self.rot_pos_emb(grid_thw)
  631. emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
  632. position_embeddings = (emb.cos(), emb.sin())
  633. cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
  634. dim=0,
  635. # Select dtype based on the following factors:
  636. # - FA2 requires that cu_seqlens_q must have dtype int32
  637. # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
  638. # See https://github.com/huggingface/transformers/pull/34852 for more information
  639. dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
  640. )
  641. cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
  642. seqlens = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
  643. hidden_states = self.embeddings(hidden_states, seqlens, grid_thw, image_type_ids[:, 0], image_type_ids[:, 1])
  644. for blk in self.blocks:
  645. hidden_states = blk(
  646. hidden_states,
  647. cu_seqlens=cu_seqlens,
  648. position_embeddings=position_embeddings,
  649. )
  650. hidden_states = self.post_layernorm(hidden_states)
  651. hidden_states = hidden_states.view(
  652. -1, self.spatial_merge_size, self.spatial_merge_size, hidden_states.shape[-1]
  653. )
  654. hidden_states = hidden_states.permute(0, 3, 1, 2)
  655. hidden_states = self.downsample(hidden_states).view(-1, self.config.out_hidden_size)
  656. hidden_states = self.merger(hidden_states)
  657. return hidden_states
  658. @auto_docstring
  659. class Glm4vTextModel(Glm4vPreTrainedModel):
  660. config: Glm4vTextConfig
  661. def __init__(self, config: Glm4vTextConfig):
  662. super().__init__(config)
  663. self.padding_idx = config.pad_token_id
  664. self.vocab_size = config.vocab_size
  665. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  666. self.layers = nn.ModuleList(
  667. [Glm4vTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  668. )
  669. self.norm = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  670. self.rotary_emb = Glm4vTextRotaryEmbedding(config=config)
  671. self.gradient_checkpointing = False
  672. # Initialize weights and apply final processing
  673. self.post_init()
  674. @auto_docstring
  675. @check_model_inputs()
  676. def forward(
  677. self,
  678. input_ids: Optional[torch.LongTensor] = None,
  679. attention_mask: Optional[torch.Tensor] = None,
  680. position_ids: Optional[torch.LongTensor] = None,
  681. past_key_values: Optional[Cache] = None,
  682. inputs_embeds: Optional[torch.FloatTensor] = None,
  683. use_cache: Optional[bool] = None,
  684. cache_position: Optional[torch.LongTensor] = None,
  685. **kwargs: Unpack[FlashAttentionKwargs],
  686. ) -> Union[tuple, BaseModelOutputWithPast]:
  687. if (input_ids is None) ^ (inputs_embeds is not None):
  688. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  689. # torch.jit.trace() doesn't support cache objects in the output
  690. if use_cache and past_key_values is None and not torch.jit.is_tracing():
  691. past_key_values = DynamicCache(config=self.config)
  692. if inputs_embeds is None:
  693. inputs_embeds = self.embed_tokens(input_ids)
  694. if cache_position is None:
  695. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  696. cache_position = torch.arange(
  697. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  698. )
  699. # the hard coded `3` is for temporal, height and width.
  700. if position_ids is None:
  701. position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
  702. elif position_ids.dim() == 2:
  703. position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
  704. causal_mask = create_causal_mask(
  705. config=self.config,
  706. input_embeds=inputs_embeds,
  707. attention_mask=attention_mask,
  708. cache_position=cache_position,
  709. past_key_values=past_key_values,
  710. position_ids=position_ids,
  711. )
  712. hidden_states = inputs_embeds
  713. # create position embeddings to be shared across the decoder layers
  714. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  715. for decoder_layer in self.layers:
  716. layer_outputs = decoder_layer(
  717. hidden_states,
  718. position_embeddings=position_embeddings,
  719. attention_mask=causal_mask,
  720. position_ids=position_ids,
  721. past_key_values=past_key_values,
  722. cache_position=cache_position,
  723. **kwargs,
  724. )
  725. hidden_states = layer_outputs
  726. hidden_states = self.norm(hidden_states)
  727. return BaseModelOutputWithPast(
  728. last_hidden_state=hidden_states,
  729. past_key_values=past_key_values,
  730. )
  731. @auto_docstring
  732. class Glm4vModel(Glm4vPreTrainedModel):
  733. base_model_prefix = ""
  734. _checkpoint_conversion_mapping = {}
  735. # Reference: fix gemma3 grad acc #37208
  736. accepts_loss_kwargs = False
  737. config: Glm4vConfig
  738. _no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
  739. def __init__(self, config):
  740. super().__init__(config)
  741. self.visual = Glm4vVisionModel._from_config(config.vision_config)
  742. self.language_model = Glm4vTextModel._from_config(config.text_config)
  743. self.rope_deltas = None # cache rope_deltas here
  744. # Initialize weights and apply final processing
  745. self.post_init()
  746. def get_input_embeddings(self):
  747. return self.language_model.get_input_embeddings()
  748. def set_input_embeddings(self, value):
  749. self.language_model.set_input_embeddings(value)
  750. def set_decoder(self, decoder):
  751. self.language_model = decoder
  752. def get_decoder(self):
  753. return self.language_model
  754. def get_rope_index(
  755. self,
  756. input_ids: Optional[torch.LongTensor] = None,
  757. image_grid_thw: Optional[torch.LongTensor] = None,
  758. video_grid_thw: Optional[torch.LongTensor] = None,
  759. attention_mask: Optional[torch.Tensor] = None,
  760. ) -> tuple[torch.Tensor, torch.Tensor]:
  761. """
  762. Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
  763. Explanation:
  764. Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
  765. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
  766. Examples:
  767. input_ids: [T T T T T], here T is for text.
  768. temporal position_ids: [0, 1, 2, 3, 4]
  769. height position_ids: [0, 1, 2, 3, 4]
  770. width position_ids: [0, 1, 2, 3, 4]
  771. For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
  772. and 1D rotary position embedding for text part.
  773. Examples:
  774. Temporal (Time): 3 patches, representing different segments of the video in time.
  775. Height: 2 patches, dividing each frame vertically.
  776. Width: 2 patches, dividing each frame horizontally.
  777. We also have some important parameters:
  778. fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
  779. 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.
  780. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
  781. 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.
  782. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
  783. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
  784. vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
  785. vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
  786. text temporal position_ids: [101, 102, 103, 104, 105]
  787. text height position_ids: [101, 102, 103, 104, 105]
  788. text width position_ids: [101, 102, 103, 104, 105]
  789. Here we calculate the text start position_ids as the max vision position_ids plus 1.
  790. Args:
  791. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  792. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  793. it.
  794. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  795. The temporal, height and width of feature shape of each image in LLM.
  796. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  797. The temporal, height and width of feature shape of each video in LLM.
  798. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  799. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  800. - 1 for tokens that are **not masked**,
  801. - 0 for tokens that are **masked**.
  802. Returns:
  803. position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
  804. mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
  805. """
  806. spatial_merge_size = self.config.vision_config.spatial_merge_size
  807. image_token_id = self.config.image_token_id
  808. video_start_token_id = self.config.video_start_token_id
  809. video_end_token_id = self.config.video_end_token_id
  810. mrope_position_deltas = []
  811. if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
  812. total_input_ids = input_ids
  813. if attention_mask is None:
  814. attention_mask = torch.ones_like(total_input_ids)
  815. position_ids = torch.ones(
  816. 3,
  817. input_ids.shape[0],
  818. input_ids.shape[1],
  819. dtype=input_ids.dtype,
  820. device=input_ids.device,
  821. )
  822. image_index, video_index = 0, 0
  823. video_group_index = 0
  824. attention_mask = attention_mask.to(total_input_ids.device)
  825. for i, input_ids in enumerate(total_input_ids):
  826. input_ids = input_ids[attention_mask[i] == 1]
  827. input_tokens = input_ids.tolist()
  828. input_token_type = []
  829. video_check_flg = False
  830. for token in input_tokens:
  831. if token == video_start_token_id:
  832. video_check_flg = True
  833. elif token == video_end_token_id:
  834. video_check_flg = False
  835. if token == image_token_id and not video_check_flg:
  836. input_token_type.append("image")
  837. elif token == image_token_id and video_check_flg:
  838. input_token_type.append("video")
  839. else:
  840. input_token_type.append("text")
  841. input_type_group = []
  842. for key, group in itertools.groupby(enumerate(input_token_type), lambda x: x[1]):
  843. group = list(group)
  844. start_index = group[0][0]
  845. end_index = group[-1][0] + 1
  846. input_type_group.append((key, start_index, end_index))
  847. llm_pos_ids_list = []
  848. video_frame_num = 1
  849. for modality_type, start_idx, end_idx in input_type_group:
  850. st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
  851. if modality_type == "image":
  852. t, h, w = (
  853. image_grid_thw[image_index][0],
  854. image_grid_thw[image_index][1],
  855. image_grid_thw[image_index][2],
  856. )
  857. llm_grid_t, llm_grid_h, llm_grid_w = (
  858. t.item(),
  859. h.item() // spatial_merge_size,
  860. w.item() // spatial_merge_size,
  861. )
  862. t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
  863. h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
  864. w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
  865. llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
  866. image_index += 1
  867. video_frame_num = 1
  868. elif modality_type == "video":
  869. t, h, w = (
  870. video_frame_num,
  871. video_grid_thw[video_index][1],
  872. video_grid_thw[video_index][2],
  873. )
  874. llm_grid_t, llm_grid_h, llm_grid_w = (
  875. t,
  876. h.item() // spatial_merge_size,
  877. w.item() // spatial_merge_size,
  878. )
  879. for t_idx in range(llm_grid_t):
  880. t_index = torch.tensor(t_idx).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
  881. h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(1, -1, llm_grid_w).flatten()
  882. w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(1, llm_grid_h, -1).flatten()
  883. llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + st_idx)
  884. video_group_index += 1
  885. if video_group_index >= video_grid_thw[video_index][0]:
  886. video_index += 1
  887. video_group_index = 0
  888. video_frame_num += 1
  889. else:
  890. text_len = end_idx - start_idx
  891. llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
  892. video_frame_num = 1
  893. llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
  894. position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
  895. mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
  896. mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
  897. return position_ids, mrope_position_deltas
  898. else:
  899. if attention_mask is not None:
  900. position_ids = attention_mask.long().cumsum(-1) - 1
  901. position_ids.masked_fill_(attention_mask == 0, 1)
  902. position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
  903. max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
  904. mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
  905. else:
  906. position_ids = (
  907. torch.arange(input_ids.shape[1], device=input_ids.device)
  908. .view(1, 1, -1)
  909. .expand(3, input_ids.shape[0], -1)
  910. )
  911. mrope_position_deltas = torch.zeros(
  912. [input_ids.shape[0], 1],
  913. device=input_ids.device,
  914. dtype=input_ids.dtype,
  915. )
  916. return position_ids, mrope_position_deltas
  917. def get_video_features(
  918. self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
  919. ):
  920. """
  921. Encodes videos into continuous embeddings that can be forwarded to the language model.
  922. Args:
  923. pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  924. The tensors corresponding to the input videos.
  925. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  926. The temporal, height and width of feature shape of each video in LLM.
  927. """
  928. pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
  929. # reshape video_grid_thw -> [b, 3] -> [1, h, w] * frames
  930. temp_frames_hw = []
  931. for t, h, w in video_grid_thw:
  932. repeated_row = torch.tensor([1, h.item(), w.item()]).unsqueeze(0).repeat(t, 1)
  933. temp_frames_hw.append(repeated_row)
  934. flattened_video_grid_thw = torch.cat(temp_frames_hw, dim=0)
  935. video_embeds = self.visual(pixel_values_videos, grid_thw=flattened_video_grid_thw)
  936. split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
  937. video_embeds = torch.split(video_embeds, split_sizes)
  938. return video_embeds
  939. def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
  940. """
  941. Encodes images into continuous embeddings that can be forwarded to the language model.
  942. Args:
  943. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  944. The tensors corresponding to the input images.
  945. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  946. The temporal, height and width of feature shape of each image in LLM.
  947. """
  948. pixel_values = pixel_values.type(self.visual.dtype)
  949. image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
  950. split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
  951. image_embeds = torch.split(image_embeds, split_sizes)
  952. return image_embeds
  953. def get_placeholder_mask(
  954. self,
  955. input_ids: torch.LongTensor,
  956. inputs_embeds: torch.FloatTensor,
  957. image_features: Optional[torch.FloatTensor] = None,
  958. video_features: Optional[torch.FloatTensor] = None,
  959. ):
  960. """
  961. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  962. equal to the length of multimodal features. If the lengths are different, an error is raised.
  963. """
  964. if input_ids is None:
  965. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  966. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  967. )
  968. special_image_mask = special_image_mask.all(-1)
  969. special_video_mask = inputs_embeds == self.get_input_embeddings()(
  970. torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
  971. )
  972. special_video_mask = special_video_mask.all(-1)
  973. else:
  974. # GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask
  975. special_image_mask = input_ids == self.config.image_token_id
  976. special_video_mask = input_ids == self.config.image_token_id
  977. n_image_tokens = special_image_mask.sum()
  978. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  979. if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
  980. raise ValueError(
  981. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
  982. )
  983. n_video_tokens = special_video_mask.sum()
  984. special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  985. if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
  986. raise ValueError(
  987. f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
  988. )
  989. return special_image_mask, special_video_mask
  990. @auto_docstring
  991. @can_return_tuple
  992. def forward(
  993. self,
  994. input_ids: Optional[torch.LongTensor] = None,
  995. attention_mask: Optional[torch.Tensor] = None,
  996. position_ids: Optional[torch.LongTensor] = None,
  997. past_key_values: Optional[Cache] = None,
  998. inputs_embeds: Optional[torch.FloatTensor] = None,
  999. pixel_values: Optional[torch.Tensor] = None,
  1000. pixel_values_videos: Optional[torch.FloatTensor] = None,
  1001. image_grid_thw: Optional[torch.LongTensor] = None,
  1002. video_grid_thw: Optional[torch.LongTensor] = None,
  1003. rope_deltas: Optional[torch.LongTensor] = None,
  1004. cache_position: Optional[torch.LongTensor] = None,
  1005. **kwargs: Unpack[TransformersKwargs],
  1006. ) -> Union[tuple, Glm4vModelOutputWithPast]:
  1007. r"""
  1008. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  1009. The temporal, height and width of feature shape of each image in LLM.
  1010. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  1011. The temporal, height and width of feature shape of each video in LLM.
  1012. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  1013. The rope index difference between sequence length and multimodal rope.
  1014. """
  1015. if (input_ids is None) ^ (inputs_embeds is not None):
  1016. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  1017. if inputs_embeds is None:
  1018. inputs_embeds = self.get_input_embeddings()(input_ids)
  1019. if pixel_values is not None:
  1020. image_embeds = self.get_image_features(pixel_values, image_grid_thw)
  1021. image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
  1022. image_mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds, image_features=image_embeds)
  1023. inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
  1024. if pixel_values_videos is not None:
  1025. video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
  1026. video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
  1027. _, video_mask = self.get_placeholder_mask(input_ids, inputs_embeds, video_features=video_embeds)
  1028. inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
  1029. if position_ids is None:
  1030. attention_mask_tensor = (
  1031. attention_mask if not isinstance(attention_mask, dict) else attention_mask["full_attention"]
  1032. )
  1033. if attention_mask_tensor is not None and attention_mask_tensor.ndim == 4:
  1034. attention_mask_tensor = torch.diagonal(attention_mask_tensor[:, 0], dim1=1, dim2=2)
  1035. # Only apply conversion for floating point tensors (inverted masks)
  1036. if attention_mask_tensor.dtype.is_floating_point:
  1037. attention_mask_tensor = attention_mask_tensor / torch.finfo(attention_mask_tensor.dtype).min
  1038. attention_mask_tensor = (1.0 - attention_mask_tensor).int()
  1039. # Calculate RoPE index once per generation in the pre-fill stage only.
  1040. # When compiling, we can't check tensor values thus we check only input length
  1041. # It is safe to assume that `length!=1` means we're in pre-fill because compiled
  1042. # models currently cannot do asssisted decoding
  1043. prefill_compiled_stage = is_torchdynamo_compiling() and (
  1044. (input_ids is not None and input_ids.shape[1] != 1)
  1045. or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
  1046. )
  1047. prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
  1048. (cache_position is not None and cache_position[0] == 0)
  1049. or (past_key_values is None or past_key_values.get_seq_length() == 0)
  1050. )
  1051. if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
  1052. position_ids, rope_deltas = self.get_rope_index(
  1053. input_ids,
  1054. image_grid_thw,
  1055. video_grid_thw,
  1056. attention_mask=attention_mask_tensor,
  1057. )
  1058. self.rope_deltas = rope_deltas
  1059. # then use the prev pre-calculated rope-deltas to get the correct position ids
  1060. else:
  1061. batch_size, seq_length, _ = inputs_embeds.shape
  1062. delta = (
  1063. (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
  1064. if cache_position is not None
  1065. else 0
  1066. )
  1067. position_ids = torch.arange(seq_length, device=inputs_embeds.device)
  1068. position_ids = position_ids.view(1, -1).expand(batch_size, -1)
  1069. if cache_position is not None: # otherwise `deltas` is an int `0`
  1070. delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
  1071. position_ids = position_ids.add(delta)
  1072. position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
  1073. outputs = self.language_model(
  1074. input_ids=None,
  1075. position_ids=position_ids,
  1076. attention_mask=attention_mask,
  1077. past_key_values=past_key_values,
  1078. inputs_embeds=inputs_embeds,
  1079. cache_position=cache_position,
  1080. **kwargs,
  1081. )
  1082. return Glm4vModelOutputWithPast(
  1083. last_hidden_state=outputs.last_hidden_state,
  1084. past_key_values=outputs.past_key_values,
  1085. hidden_states=outputs.hidden_states,
  1086. attentions=outputs.attentions,
  1087. rope_deltas=self.rope_deltas,
  1088. )
  1089. @dataclass
  1090. @auto_docstring(
  1091. custom_intro="""
  1092. Base class for Glm4v causal language model (or autoregressive) outputs.
  1093. """
  1094. )
  1095. class Glm4vCausalLMOutputWithPast(ModelOutput):
  1096. r"""
  1097. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  1098. Language modeling loss (for next-token prediction).
  1099. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  1100. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  1101. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1102. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  1103. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  1104. `past_key_values` input) to speed up sequential decoding.
  1105. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  1106. The rope index difference between sequence length and multimodal rope.
  1107. """
  1108. loss: Optional[torch.FloatTensor] = None
  1109. logits: Optional[torch.FloatTensor] = None
  1110. past_key_values: Optional[Cache] = None
  1111. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  1112. attentions: Optional[tuple[torch.FloatTensor]] = None
  1113. rope_deltas: Optional[torch.LongTensor] = None
  1114. class Glm4vForConditionalGeneration(Glm4vPreTrainedModel, GenerationMixin):
  1115. _checkpoint_conversion_mapping = {}
  1116. _tied_weights_keys = ["lm_head.weight"]
  1117. # Reference: fix gemma3 grad acc #37208
  1118. accepts_loss_kwargs = False
  1119. def __init__(self, config):
  1120. super().__init__(config)
  1121. self.model = Glm4vModel(config)
  1122. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  1123. self.post_init()
  1124. def get_input_embeddings(self):
  1125. return self.model.get_input_embeddings()
  1126. def set_input_embeddings(self, value):
  1127. self.model.set_input_embeddings(value)
  1128. def set_decoder(self, decoder):
  1129. self.model.set_decoder(decoder)
  1130. def get_decoder(self):
  1131. return self.model.get_decoder()
  1132. def get_video_features(
  1133. self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
  1134. ):
  1135. return self.model.get_video_features(pixel_values_videos, video_grid_thw)
  1136. def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
  1137. return self.model.get_image_features(pixel_values, image_grid_thw)
  1138. # Make modules available through conditional class for BC
  1139. @property
  1140. def language_model(self):
  1141. return self.model.language_model
  1142. @property
  1143. def visual(self):
  1144. return self.model.visual
  1145. @can_return_tuple
  1146. @auto_docstring
  1147. def forward(
  1148. self,
  1149. input_ids: Optional[torch.LongTensor] = None,
  1150. attention_mask: Optional[torch.Tensor] = None,
  1151. position_ids: Optional[torch.LongTensor] = None,
  1152. past_key_values: Optional[Cache] = None,
  1153. inputs_embeds: Optional[torch.FloatTensor] = None,
  1154. labels: Optional[torch.LongTensor] = None,
  1155. pixel_values: Optional[torch.Tensor] = None,
  1156. pixel_values_videos: Optional[torch.FloatTensor] = None,
  1157. image_grid_thw: Optional[torch.LongTensor] = None,
  1158. video_grid_thw: Optional[torch.LongTensor] = None,
  1159. rope_deltas: Optional[torch.LongTensor] = None,
  1160. cache_position: Optional[torch.LongTensor] = None,
  1161. logits_to_keep: Union[int, torch.Tensor] = 0,
  1162. **kwargs: Unpack[TransformersKwargs],
  1163. ) -> Union[tuple, Glm4vCausalLMOutputWithPast]:
  1164. r"""
  1165. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1166. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1167. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1168. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1169. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  1170. The temporal, height and width of feature shape of each image in LLM.
  1171. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
  1172. The temporal, height and width of feature shape of each video in LLM.
  1173. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
  1174. The rope index difference between sequence length and multimodal rope.
  1175. Example:
  1176. ```python
  1177. >>> from PIL import Image
  1178. >>> import requests
  1179. >>> from transformers import AutoProcessor, Glm4vForConditionalGeneration
  1180. >>> model = Glm4vForConditionalGeneration.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
  1181. >>> processor = AutoProcessor.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
  1182. >>> messages = [
  1183. {
  1184. "role": "user",
  1185. "content": [
  1186. {"type": "image"},
  1187. {"type": "text", "text": "What is shown in this image?"},
  1188. ],
  1189. },
  1190. ]
  1191. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  1192. >>> image = Image.open(requests.get(url, stream=True).raw)
  1193. >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
  1194. >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
  1195. >>> # Generate
  1196. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  1197. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  1198. "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 ..."
  1199. ```"""
  1200. outputs = self.model(
  1201. input_ids=input_ids,
  1202. pixel_values=pixel_values,
  1203. pixel_values_videos=pixel_values_videos,
  1204. image_grid_thw=image_grid_thw,
  1205. video_grid_thw=video_grid_thw,
  1206. position_ids=position_ids,
  1207. attention_mask=attention_mask,
  1208. past_key_values=past_key_values,
  1209. inputs_embeds=inputs_embeds,
  1210. cache_position=cache_position,
  1211. **kwargs,
  1212. )
  1213. hidden_states = outputs[0]
  1214. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1215. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1216. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1217. loss = None
  1218. if labels is not None:
  1219. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
  1220. return Glm4vCausalLMOutputWithPast(
  1221. loss=loss,
  1222. logits=logits,
  1223. past_key_values=outputs.past_key_values,
  1224. hidden_states=outputs.hidden_states,
  1225. attentions=outputs.attentions,
  1226. rope_deltas=outputs.rope_deltas,
  1227. )
  1228. def prepare_inputs_for_generation(
  1229. self,
  1230. input_ids,
  1231. past_key_values=None,
  1232. attention_mask=None,
  1233. inputs_embeds=None,
  1234. cache_position=None,
  1235. position_ids=None,
  1236. use_cache=True,
  1237. pixel_values=None,
  1238. pixel_values_videos=None,
  1239. image_grid_thw=None,
  1240. video_grid_thw=None,
  1241. **kwargs,
  1242. ):
  1243. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  1244. model_inputs = super().prepare_inputs_for_generation(
  1245. input_ids,
  1246. past_key_values=past_key_values,
  1247. attention_mask=attention_mask,
  1248. inputs_embeds=inputs_embeds,
  1249. cache_position=cache_position,
  1250. position_ids=position_ids,
  1251. pixel_values=pixel_values,
  1252. pixel_values_videos=pixel_values_videos,
  1253. image_grid_thw=image_grid_thw,
  1254. video_grid_thw=video_grid_thw,
  1255. use_cache=use_cache,
  1256. **kwargs,
  1257. )
  1258. # GLM-4.1V position_ids are prepareed with rope_deltas in forward
  1259. model_inputs["position_ids"] = None
  1260. if cache_position[0] != 0:
  1261. model_inputs["pixel_values"] = None
  1262. model_inputs["pixel_values_videos"] = None
  1263. return model_inputs
  1264. def _get_image_nums_and_video_nums(
  1265. self,
  1266. input_ids: Optional[torch.LongTensor],
  1267. inputs_embeds: Optional[torch.Tensor] = None,
  1268. ) -> tuple[torch.Tensor, torch.Tensor]:
  1269. """
  1270. Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
  1271. These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
  1272. Args:
  1273. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1274. Indices of input sequence tokens in the vocabulary.
  1275. Returns:
  1276. image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
  1277. video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
  1278. """
  1279. if inputs_embeds is not None:
  1280. is_image = (
  1281. inputs_embeds
  1282. == self.get_input_embeddings()(
  1283. torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
  1284. )
  1285. )[..., 0]
  1286. is_video_start = (
  1287. inputs_embeds
  1288. == self.get_input_embeddings()(
  1289. torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
  1290. )
  1291. )[..., 0]
  1292. is_video_end = (
  1293. inputs_embeds
  1294. == self.get_input_embeddings()(
  1295. torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
  1296. )
  1297. )[..., 0]
  1298. else:
  1299. is_image = input_ids == self.config.image_start_token_id
  1300. is_video_start = input_ids == self.config.video_start_token_id
  1301. is_video_end = input_ids == self.config.video_end_token_id
  1302. # Cumulative sum to track if we're inside a video span
  1303. # We'll assume well-formed video tags (i.e. matching starts and ends)
  1304. video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
  1305. inside_video = video_level > 0 # shape (batch_size, seq_length)
  1306. # Mask out image tokens that are inside video spans
  1307. standalone_images = is_image & (~inside_video)
  1308. # Count per batch
  1309. image_counts = standalone_images.sum(dim=1)
  1310. video_counts = is_video_start.sum(dim=1)
  1311. return image_counts, video_counts
  1312. def _expand_inputs_for_generation(
  1313. self,
  1314. expand_size: int = 1,
  1315. is_encoder_decoder: bool = False,
  1316. input_ids: Optional[torch.LongTensor] = None,
  1317. **model_kwargs,
  1318. ) -> tuple[torch.LongTensor, dict[str, Any]]:
  1319. # Overwritten -- Support for expanding tensors without a batch size dimension
  1320. # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
  1321. # pixel_values.shape[0] is sum(seqlen_images for samples)
  1322. # image_grid_thw.shape[0] is sum(num_images for samples)
  1323. if expand_size == 1:
  1324. return input_ids, model_kwargs
  1325. visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
  1326. def _expand_dict_for_generation_visual(dict_to_expand):
  1327. image_grid_thw = model_kwargs.get("image_grid_thw", None)
  1328. video_grid_thw = model_kwargs.get("video_grid_thw", None)
  1329. image_nums, video_nums = self._get_image_nums_and_video_nums(
  1330. input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
  1331. )
  1332. def _repeat_interleave_samples(x, lengths, repeat_times):
  1333. samples = torch.split(x, lengths)
  1334. repeat_args = [repeat_times] + [1] * (x.dim() - 1)
  1335. result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
  1336. return result
  1337. for key in dict_to_expand:
  1338. if key == "pixel_values":
  1339. # split images into samples
  1340. samples = torch.split(image_grid_thw, list(image_nums))
  1341. # compute the sequence length of images for each sample
  1342. lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
  1343. dict_to_expand[key] = _repeat_interleave_samples(
  1344. dict_to_expand[key], lengths=lengths, repeat_times=expand_size
  1345. )
  1346. elif key == "image_grid_thw":
  1347. # get the num of images for each sample
  1348. lengths = list(image_nums)
  1349. dict_to_expand[key] = _repeat_interleave_samples(
  1350. dict_to_expand[key], lengths=lengths, repeat_times=expand_size
  1351. )
  1352. elif key == "pixel_values_videos":
  1353. samples = torch.split(video_grid_thw, list(video_nums))
  1354. lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
  1355. dict_to_expand[key] = _repeat_interleave_samples(
  1356. dict_to_expand[key], lengths=lengths, repeat_times=expand_size
  1357. )
  1358. elif key == "video_grid_thw":
  1359. lengths = list(video_nums)
  1360. dict_to_expand[key] = _repeat_interleave_samples(
  1361. dict_to_expand[key], lengths=lengths, repeat_times=expand_size
  1362. )
  1363. elif key == "second_per_grid_ts":
  1364. dict_to_expand[key] = _repeat_interleave_samples(
  1365. dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
  1366. )
  1367. return dict_to_expand
  1368. def _expand_dict_for_generation(dict_to_expand):
  1369. for key in dict_to_expand:
  1370. if (
  1371. key != "cache_position"
  1372. and dict_to_expand[key] is not None
  1373. and isinstance(dict_to_expand[key], torch.Tensor)
  1374. and key not in visual_keys
  1375. ):
  1376. dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
  1377. return dict_to_expand
  1378. model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
  1379. if input_ids is not None:
  1380. input_ids = input_ids.repeat_interleave(expand_size, dim=0)
  1381. model_kwargs = _expand_dict_for_generation(model_kwargs)
  1382. if is_encoder_decoder:
  1383. if model_kwargs.get("encoder_outputs") is None:
  1384. raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
  1385. model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
  1386. return input_ids, model_kwargs
  1387. __all__ = ["Glm4vForConditionalGeneration", "Glm4vModel", "Glm4vPreTrainedModel", "Glm4vTextModel"]