modeling_colqwen2.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.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_colqwen2.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2025 The HuggingFace Inc. team.
  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. from dataclasses import dataclass
  21. from torch import nn
  22. from transformers import AutoModel
  23. from ... import initialization as init
  24. from ...cache_utils import Cache
  25. from ...modeling_utils import PreTrainedModel
  26. from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_torch_available
  27. from .configuration_colqwen2 import ColQwen2Config
  28. if is_torch_available():
  29. import torch
  30. @auto_docstring
  31. class ColQwen2PreTrainedModel(PreTrainedModel):
  32. config: ColQwen2Config
  33. base_model_prefix = "model"
  34. input_modalities = ("image", "text")
  35. _no_split_modules = []
  36. _supports_sdpa = True
  37. _supports_flash_attn = True
  38. _supports_flex_attn = True
  39. @torch.no_grad()
  40. def _init_weights(self, module):
  41. std = (
  42. self.config.initializer_range
  43. if hasattr(self.config, "initializer_range")
  44. else self.config.vlm_config.text_config.initializer_range
  45. )
  46. if isinstance(module, (nn.Linear, nn.Conv2d)):
  47. init.normal_(module.weight, mean=0.0, std=std)
  48. if module.bias is not None:
  49. init.zeros_(module.bias)
  50. elif isinstance(module, nn.Embedding):
  51. init.normal_(module.weight, mean=0.0, std=std)
  52. # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
  53. if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
  54. init.zeros_(module.weight[module.padding_idx])
  55. @dataclass
  56. @auto_docstring(
  57. custom_intro="""
  58. Base class for ColQwen2 embeddings output.
  59. """
  60. )
  61. class ColQwen2ForRetrievalOutput(ModelOutput):
  62. r"""
  63. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  64. Language modeling loss (for next-token prediction).
  65. embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  66. The embeddings of the model.
  67. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  68. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  69. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  70. `past_key_values` input) to speed up sequential decoding.
  71. """
  72. loss: torch.FloatTensor | None = None
  73. embeddings: torch.Tensor | None = None
  74. past_key_values: Cache | None = None
  75. hidden_states: tuple[torch.FloatTensor] | None = None
  76. attentions: tuple[torch.FloatTensor] | None = None
  77. @auto_docstring(
  78. custom_intro="""
  79. Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
  80. from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
  81. between these document embeddings and the corresponding query embeddings, using the late interaction method
  82. introduced in ColBERT.
  83. Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
  84. a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
  85. ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
  86. [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
  87. """
  88. )
  89. class ColQwen2ForRetrieval(ColQwen2PreTrainedModel):
  90. base_model_prefix = "vlm"
  91. def __init__(self, config: ColQwen2Config):
  92. super().__init__(config)
  93. self.config = config
  94. self.vocab_size = config.vlm_config.text_config.vocab_size
  95. self.vlm = AutoModel.from_config(config.vlm_config)
  96. self.embedding_dim = self.config.embedding_dim
  97. self.embedding_proj_layer = nn.Linear(
  98. self.config.vlm_config.text_config.hidden_size,
  99. self.embedding_dim,
  100. )
  101. self.post_init()
  102. @can_return_tuple
  103. @auto_docstring
  104. def forward(
  105. self,
  106. input_ids: torch.LongTensor | None = None,
  107. attention_mask: torch.Tensor | None = None,
  108. position_ids: torch.LongTensor | None = None,
  109. past_key_values: Cache | None = None,
  110. labels: torch.LongTensor | None = None,
  111. inputs_embeds: torch.FloatTensor | None = None,
  112. use_cache: bool | None = None,
  113. output_attentions: bool | None = None,
  114. output_hidden_states: bool | None = None,
  115. return_dict: bool | None = None,
  116. pixel_values: torch.Tensor | None = None,
  117. image_grid_thw: torch.LongTensor | None = None,
  118. **kwargs,
  119. ) -> ColQwen2ForRetrievalOutput:
  120. r"""
  121. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
  122. The temporal, height and width of feature shape of each image in LLM.
  123. """
  124. # Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
  125. if pixel_values is not None and image_grid_thw is not None:
  126. # NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
  127. offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,)
  128. arange = torch.arange(pixel_values.shape[1], device=offsets.device) # (max_len,)
  129. mask = arange.unsqueeze(0) < offsets.unsqueeze(1) # (batch_size, max_len)
  130. pixel_values = pixel_values[mask] # (total_valid_patches, channels, height, width)
  131. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  132. output_hidden_states = (
  133. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  134. )
  135. return_dict = return_dict if return_dict is not None else self.config.return_dict
  136. # Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
  137. if inputs_embeds is None:
  138. inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
  139. if pixel_values is not None:
  140. image_embeds = self.vlm.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True).pooler_output
  141. image_mask = (
  142. (input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
  143. )
  144. image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
  145. inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
  146. vlm_output = self.vlm(
  147. input_ids=None,
  148. position_ids=position_ids,
  149. attention_mask=attention_mask,
  150. past_key_values=past_key_values,
  151. inputs_embeds=inputs_embeds,
  152. use_cache=use_cache,
  153. output_attentions=output_attentions,
  154. output_hidden_states=output_hidden_states,
  155. return_dict=return_dict,
  156. )
  157. vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
  158. last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
  159. proj_dtype = self.embedding_proj_layer.weight.dtype
  160. embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
  161. # L2 normalization
  162. embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
  163. if attention_mask is not None:
  164. embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
  165. return ColQwen2ForRetrievalOutput(
  166. embeddings=embeddings,
  167. past_key_values=vlm_output.past_key_values,
  168. hidden_states=vlm_hidden_states,
  169. attentions=vlm_output.attentions,
  170. )
  171. __all__ = ["ColQwen2ForRetrieval", "ColQwen2PreTrainedModel"]