modeling_glm4v.py 77 KB

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