modular_glm46v.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright 2025 the HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring
  18. from ...video_utils import VideoMetadata
  19. from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel
  20. from ..glm4v.image_processing_glm4v import Glm4vImageProcessor
  21. from ..glm4v.image_processing_pil_glm4v import Glm4vImageProcessorPil
  22. from ..glm4v.modeling_glm4v import Glm4vForConditionalGeneration, Glm4vModel, Glm4vPreTrainedModel
  23. from ..glm4v.processing_glm4v import Glm4vProcessor
  24. from ..glm4v.video_processing_glm4v import Glm4vVideoProcessor
  25. @auto_docstring(checkpoint="zai-org/GLM-4.1V-9B-Thinking")
  26. @strict
  27. class Glm46VConfig(PreTrainedConfig):
  28. r"""
  29. image_start_token_id (`int`, *optional*, defaults to 151339):
  30. The image start token index to encode the start of image.
  31. image_end_token_id (`int`, *optional*, defaults to 151340):
  32. The image end token index to encode the end of image.
  33. video_start_token_id (`int`, *optional*, defaults to 151361):
  34. The video start token index to encode the start of video.
  35. video_end_token_id (`int`, *optional*, defaults to 151362):
  36. The video end token index to encode the end of video.
  37. ```python
  38. >>> from transformers import Glm46VForConditionalGeneration, Glm46VConfig
  39. >>> # Initializing a GLM-4.6V style configuration
  40. >>> configuration = Glm46VConfig()
  41. >>> # Initializing a model from the GLM-4.6V style configuration
  42. >>> model = Glm4vForConditionalGeneration(configuration)
  43. >>> # Accessing the model configuration
  44. >>> configuration = model.config
  45. ```"""
  46. model_type = "glm46v"
  47. sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
  48. keys_to_ignore_at_inference = ["past_key_values"]
  49. text_config: dict | PreTrainedConfig | None = None
  50. vision_config: dict | PreTrainedConfig | None = None
  51. image_token_id: int = 151343
  52. video_token_id: int = 151344
  53. image_start_token_id: int = 151339
  54. image_end_token_id: int = 151340
  55. video_start_token_id: int = 151361
  56. video_end_token_id: int = 151362
  57. tie_word_embeddings: bool = False
  58. def __post_init__(self, **kwargs):
  59. if isinstance(self.vision_config, dict):
  60. self.vision_config["model_type"] = self.vision_config.get("model_type", "glm4v_vision")
  61. self.vision_config = CONFIG_MAPPING[self.vision_config["model_type"]](**self.vision_config)
  62. elif self.vision_config is None:
  63. self.vision_config = CONFIG_MAPPING["glm4v_vision"]()
  64. if isinstance(self.text_config, dict):
  65. self.text_config["model_type"] = self.text_config.get("model_type", "glm4v_text")
  66. self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
  67. elif self.text_config is None:
  68. self.text_config = CONFIG_MAPPING["glm4v_text"]()
  69. super().__post_init__(**kwargs)
  70. class Glm46VPreTrainedModel(Glm4vPreTrainedModel):
  71. _can_record_outputs = None
  72. _no_split_modules = None
  73. def _init_weights(self, module):
  74. raise AttributeError("Not needed")
  75. class Glm46VModel(Glm4vModel):
  76. _no_split_modules = None
  77. def __init__(self, config):
  78. super().__init__(config)
  79. self.visual = AutoModel.from_config(config.vision_config)
  80. self.language_model = AutoModel.from_config(config.text_config)
  81. class Glm46VForConditionalGeneration(Glm4vForConditionalGeneration):
  82. pass
  83. class Glm46VProcessor(Glm4vProcessor):
  84. def replace_frame_token_id(self, timestamp_sec):
  85. return f"<|begin_of_image|>{self.image_token}<|end_of_image|>{timestamp_sec:.1f} seconds"
  86. class Glm46VImageProcessorPil(Glm4vImageProcessorPil):
  87. pass
  88. class Glm46VImageProcessor(Glm4vImageProcessor):
  89. pass
  90. class Glm46VVideoProcessor(Glm4vVideoProcessor):
  91. def sample_frames(
  92. self,
  93. metadata: VideoMetadata,
  94. fps: int | float | None = None,
  95. **kwargs,
  96. ):
  97. if metadata is None or getattr(metadata, "fps", None) is None:
  98. raise ValueError(
  99. "Asked to sample frames per second but no video metadata was provided which is required when sampling in Glm46V. "
  100. "Please pass in `VideoMetadata` object or set `do_sample_frames=False`"
  101. )
  102. total_frames = metadata.total_num_frames
  103. max_frame_idx = total_frames - 1
  104. duration = metadata.duration or round(max_frame_idx / metadata.fps) + 1
  105. DYNAMIC_FPS_THRES = {30: 3, 300: 1, 2400: 0.5}
  106. MAX_FRAME_COUNT_DYNAMIC = 640
  107. MAX_DURATION = 2400
  108. effective_duration = min(duration, MAX_DURATION)
  109. if effective_duration <= 30:
  110. target_fps = DYNAMIC_FPS_THRES[30]
  111. elif effective_duration <= 300:
  112. target_fps = DYNAMIC_FPS_THRES[300]
  113. else:
  114. target_fps = DYNAMIC_FPS_THRES[2400]
  115. extract_t = int(effective_duration * target_fps * self.temporal_patch_size)
  116. extract_t = min(extract_t, MAX_FRAME_COUNT_DYNAMIC)
  117. duration_per_frame = 1 / metadata.fps
  118. timestamps = [i * duration_per_frame for i in range(total_frames)]
  119. max_second = int(duration)
  120. if total_frames < extract_t:
  121. frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
  122. else:
  123. frame_indices = []
  124. current_second = 0
  125. inv_fps = 1 / (self.temporal_patch_size * target_fps)
  126. for frame_index in range(total_frames):
  127. if timestamps[frame_index] >= current_second:
  128. current_second += inv_fps
  129. frame_indices.append(frame_index)
  130. if current_second >= max_second:
  131. break
  132. if len(frame_indices) < extract_t:
  133. if len(frame_indices) == 0:
  134. start, end = 0, max(total_frames - 1, 0)
  135. else:
  136. start, end = frame_indices[0], frame_indices[-1]
  137. frame_indices = np.linspace(start, end, extract_t, dtype=int).tolist()
  138. elif len(frame_indices) > extract_t:
  139. frame_indices = np.linspace(0, total_frames - 1, extract_t, dtype=int).tolist()
  140. seen, uniq = set(), []
  141. for idx in frame_indices:
  142. if idx not in seen:
  143. seen.add(idx)
  144. uniq.append(idx)
  145. if len(uniq) & 1:
  146. uniq.append(uniq[-1])
  147. return np.array(uniq)
  148. __all__ = [
  149. "Glm46VConfig",
  150. "Glm46VModel",
  151. "Glm46VPreTrainedModel",
  152. "Glm46VForConditionalGeneration",
  153. "Glm46VProcessor",
  154. "Glm46VImageProcessor",
  155. "Glm46VImageProcessorPil",
  156. "Glm46VVideoProcessor",
  157. ]