configuration_glm4v.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. from ...configuration_utils import PretrainedConfig
  22. from ...modeling_rope_utils import rope_config_validation
  23. class Glm4vVisionConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`Glm4vVisionModel`]. It is used to instantiate an Glm4vVisionModel
  26. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
  27. a similar configuration to that of
  28. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  29. Args:
  30. hidden_size (`int`, *optional*, defaults to 1536):
  31. Dimensionality of the encoder layers and the pooler layer.
  32. depth (`int`, *optional*, defaults to 24):
  33. Number of layers (depth) in the model.
  34. attention_bias (`bool`, *optional*, defaults to `False`):
  35. Whether to add a bias to the queries, keys and values.
  36. intermediate_size (`int`, *optional*, defaults to 13696):
  37. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  38. hidden_act (`str` or `function`, *optional*, defaults to `"selu"`):
  39. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  40. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  41. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  42. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  43. attention_dropout (`float`, *optional*, defaults to 0.0):
  44. Dropout probability for attention weights.
  45. projection_dropout (`float`, *optional*, defaults to 0.0):
  46. Dropout probability for the projection layer.
  47. initializer_range (`float`, *optional*, defaults to 0.02):
  48. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  49. image_size (`int` or `list[int]`, *optional*, defaults to `[336, 336]`):
  50. The size (resolution) of each image.
  51. patch_size (`int`, *optional*, defaults to `14`):
  52. The size (resolution) of each patch.
  53. num_channels (`int`, *optional*, defaults to 3):
  54. The number of input channels.
  55. out_hidden_size (`int`, *optional*, defaults to 4096):
  56. The output hidden size of the vision model.
  57. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  58. The epsilon used by the rms normalization layers.
  59. spatial_merge_size (`int`, *optional*, defaults to 2):
  60. The size used for merging spatial dimensions.
  61. temporal_patch_size (`int`, *optional*, defaults to 2):
  62. The size used for patches along the temporal dimension.
  63. Example:
  64. ```python
  65. >>> from transformers import Glm4vVisionConfig, Glm4vVisionModel
  66. >>> # Initializing a Glm4vVisionConfig GLM-4.1V-9B style configuration
  67. >>> configuration = Glm4vVisionConfig()
  68. >>> # Initializing a model (with random weights) from the GLM-4.1V-9B configuration
  69. >>> model = Glm4vVisionModel(configuration)
  70. >>> # Accessing the model configuration
  71. >>> configuration = model.config
  72. ```"""
  73. model_type = "glm4v"
  74. base_config_key = "vision_config"
  75. def __init__(
  76. self,
  77. depth=24,
  78. hidden_size=1536,
  79. hidden_act="silu",
  80. attention_bias=False,
  81. attention_dropout=0.0,
  82. num_heads=12,
  83. in_channels=3,
  84. image_size=336,
  85. patch_size=14,
  86. rms_norm_eps=1e-05,
  87. spatial_merge_size=2,
  88. temporal_patch_size=2,
  89. out_hidden_size=4096,
  90. intermediate_size=13696,
  91. initializer_range=0.02,
  92. **kwargs,
  93. ):
  94. super().__init__(**kwargs)
  95. self.depth = depth
  96. self.hidden_size = hidden_size
  97. self.hidden_act = hidden_act
  98. self.num_heads = num_heads
  99. self.in_channels = in_channels
  100. self.image_size = image_size
  101. self.patch_size = patch_size
  102. self.spatial_merge_size = spatial_merge_size
  103. self.temporal_patch_size = temporal_patch_size
  104. self.out_hidden_size = out_hidden_size
  105. self.intermediate_size = intermediate_size
  106. self.initializer_range = initializer_range
  107. self.rms_norm_eps = rms_norm_eps
  108. self.attention_bias = attention_bias
  109. self.attention_dropout = attention_dropout
  110. class Glm4vTextConfig(PretrainedConfig):
  111. r"""
  112. This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
  113. GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
  114. configuration with the defaults will yield a similar configuration to that of
  115. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  116. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  117. documentation from [`PretrainedConfig`] for more information.
  118. Args:
  119. vocab_size (`int`, *optional*, defaults to 151552):
  120. Vocabulary size of the Glm4v model. Defines the number of different tokens that can be represented by the
  121. `inputs_ids` passed when calling [`Glm4vModel`]
  122. hidden_size (`int`, *optional*, defaults to 4096):
  123. Dimension of the hidden representations.
  124. intermediate_size (`int`, *optional*, defaults to 13696):
  125. Dimension of the MLP representations.
  126. num_hidden_layers (`int`, *optional*, defaults to 40):
  127. Number of hidden layers in the Transformer encoder.
  128. num_attention_heads (`int`, *optional*, defaults to 32):
  129. Number of attention heads for each attention layer in the Transformer encoder.
  130. num_key_value_heads (`int`, *optional*, defaults to 2):
  131. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  132. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  133. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  134. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  135. by meanpooling all the original heads within that group. For more details checkout [this
  136. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
  137. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  138. The non-linear activation function (function or string) in the decoder.
  139. max_position_embeddings (`int`, *optional*, defaults to 32768):
  140. The maximum sequence length that this model might ever be used with.
  141. initializer_range (`float`, *optional*, defaults to 0.02):
  142. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  143. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  144. The epsilon used by the rms normalization layers.
  145. use_cache (`bool`, *optional*, defaults to `True`):
  146. Whether or not the model should return the last key/values attentions (not used by all models). Only
  147. relevant if `config.is_decoder=True`.
  148. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  149. Whether the model's input and output word embeddings should be tied.
  150. rope_theta (`float`, *optional*, defaults to 10000.0):
  151. The base period of the RoPE embeddings.
  152. attention_dropout (`float`, *optional*, defaults to 0.0):
  153. The dropout ratio for the attention probabilities.
  154. rope_scaling (`Dict`, *optional*):
  155. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  156. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  157. accordingly.
  158. Expected contents:
  159. `rope_type` (`str`):
  160. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  161. 'llama3'], with 'default' being the original RoPE implementation.
  162. `factor` (`float`, *optional*):
  163. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  164. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  165. original maximum pre-trained length.
  166. `original_max_position_embeddings` (`int`, *optional*):
  167. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  168. pretraining.
  169. `attention_factor` (`float`, *optional*):
  170. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  171. computation. If unspecified, it defaults to value recommended by the implementation, using the
  172. `factor` field to infer the suggested value.
  173. image_token_id (`int`, *optional*):
  174. Token index used as placeholder for image embeddings.
  175. video_token_id (`int`, *optional*):
  176. Token index used as placeholder for video embeddings.
  177. ```python
  178. >>> from transformers import Glm4vTextModel, Glm4vConfig
  179. >>> # Initializing a GLM-4.1V style configuration
  180. >>> configuration = Glm4vConfig()
  181. >>> # Initializing a model from the GLM-4.1V style configuration
  182. >>> model = Glm4vTextModel(configuration)
  183. >>> # Accessing the model configuration
  184. >>> configuration = model.config
  185. ```"""
  186. model_type = "glm4v_text"
  187. base_config_key = "text_config"
  188. keys_to_ignore_at_inference = ["past_key_values"]
  189. # Default tensor parallel plan for base model `Glm4v`
  190. base_model_tp_plan = {
  191. "layers.*.self_attn.q_proj": "colwise",
  192. "layers.*.self_attn.k_proj": "colwise",
  193. "layers.*.self_attn.v_proj": "colwise",
  194. "layers.*.self_attn.o_proj": "rowwise",
  195. "layers.*.mlp.gate_up_proj": "colwise_rep", # we need to replicate here due to the `chunk` operation
  196. "layers.*.mlp.down_proj": "rowwise_rep", # we need to replicate here due to the `chunk` operation
  197. }
  198. base_model_pp_plan = {
  199. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  200. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  201. "norm": (["hidden_states"], ["hidden_states"]),
  202. }
  203. def __init__(
  204. self,
  205. vocab_size=151552,
  206. hidden_size=4096,
  207. intermediate_size=13696,
  208. num_hidden_layers=40,
  209. num_attention_heads=32,
  210. num_key_value_heads=2,
  211. hidden_act="silu",
  212. max_position_embeddings=32768,
  213. initializer_range=0.02,
  214. rms_norm_eps=1e-05,
  215. use_cache=True,
  216. tie_word_embeddings=False,
  217. rope_theta=10000.0,
  218. attention_dropout=0.0,
  219. rope_scaling=None,
  220. image_token_id=None,
  221. video_token_id=None,
  222. **kwargs,
  223. ):
  224. self.vocab_size = vocab_size
  225. self.max_position_embeddings = max_position_embeddings
  226. self.hidden_size = hidden_size
  227. self.intermediate_size = intermediate_size
  228. self.num_hidden_layers = num_hidden_layers
  229. self.num_attention_heads = num_attention_heads
  230. # for backward compatibility
  231. if num_key_value_heads is None:
  232. num_key_value_heads = num_attention_heads
  233. self.num_key_value_heads = num_key_value_heads
  234. self.hidden_act = hidden_act
  235. self.initializer_range = initializer_range
  236. self.rms_norm_eps = rms_norm_eps
  237. self.use_cache = use_cache
  238. self.rope_theta = rope_theta
  239. self.attention_dropout = attention_dropout
  240. self.rope_scaling = rope_scaling
  241. # Validate the correctness of rotary position embeddings parameters
  242. # BC: if there is a 'type' field, move it to 'rope_type'.
  243. if self.rope_scaling is not None and "type" in self.rope_scaling:
  244. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  245. rope_config_validation(self, ignore_keys={"mrope_section"})
  246. self.image_token_id = image_token_id
  247. self.video_token_id = video_token_id
  248. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  249. class Glm4vConfig(PretrainedConfig):
  250. r"""
  251. This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
  252. GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a
  253. configuration with the defaults will yield a similar configuration to that of
  254. GLM-4.1V-9B-Thinking [THUDM/GLM-4.1V-9B-Thinking](https://huggingface.co/THUDM/GLM-4.1V-9B-Thinking).
  255. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  256. documentation from [`PretrainedConfig`] for more information.
  257. Args:
  258. text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Glm4vTextConfig`):
  259. The config object or dictionary of the text backbone.
  260. vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Glm4vVisionConfig`):
  261. The config object or dictionary of the vision backbone.
  262. image_token_id (`int`, *optional*, defaults to 151343):
  263. The image token index to encode the image prompt.
  264. video_token_id (`int`, *optional*, defaults to 151344):
  265. The video token index to encode the image prompt.
  266. image_start_token_id (`int`, *optional*, defaults to 151339):
  267. The image start token index to encode the start of image.
  268. image_end_token_id (`int`, *optional*, defaults to 151340):
  269. The image end token index to encode the end of image.
  270. video_start_token_id (`int`, *optional*, defaults to 151341):
  271. The video start token index to encode the start of video.
  272. video_end_token_id (`int`, *optional*, defaults to 151342):
  273. The video end token index to encode the end of video.
  274. ```python
  275. >>> from transformers import Glm4vForConditionalGeneration, Glm4vConfig
  276. >>> # Initializing a GLM-4.1V style configuration
  277. >>> configuration = Glm4vConfig()
  278. >>> # Initializing a model from the GLM-4.1V style configuration
  279. >>> model = Glm4vForConditionalGeneration(configuration)
  280. >>> # Accessing the model configuration
  281. >>> configuration = model.config
  282. ```"""
  283. model_type = "glm4v"
  284. sub_configs = {"vision_config": Glm4vVisionConfig, "text_config": Glm4vTextConfig}
  285. keys_to_ignore_at_inference = ["past_key_values"]
  286. def __init__(
  287. self,
  288. text_config=None,
  289. vision_config=None,
  290. image_token_id=151343,
  291. video_token_id=151344,
  292. image_start_token_id=151339,
  293. image_end_token_id=151340,
  294. video_start_token_id=151341,
  295. video_end_token_id=151342,
  296. **kwargs,
  297. ):
  298. if isinstance(vision_config, dict):
  299. self.vision_config = self.sub_configs["vision_config"](**vision_config)
  300. elif vision_config is None:
  301. self.vision_config = self.sub_configs["vision_config"]()
  302. if isinstance(text_config, dict):
  303. self.text_config = self.sub_configs["text_config"](**text_config)
  304. elif text_config is None:
  305. self.text_config = self.sub_configs["text_config"](**kwargs)
  306. self.image_token_id = image_token_id
  307. self.video_token_id = video_token_id
  308. self.video_start_token_id = video_start_token_id
  309. self.video_end_token_id = video_end_token_id
  310. self.image_start_token_id = image_start_token_id
  311. self.image_end_token_id = image_end_token_id
  312. super().__init__(**kwargs)
  313. __all__ = ["Glm4vConfig", "Glm4vTextConfig"]