modeling_colpali.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch ColPali model"""
  16. from dataclasses import dataclass
  17. from typing import Optional
  18. import torch
  19. from torch import nn
  20. from transformers import AutoModelForImageTextToText
  21. from ...cache_utils import Cache
  22. from ...modeling_utils import PreTrainedModel
  23. from ...utils import ModelOutput, auto_docstring, can_return_tuple
  24. from .configuration_colpali import ColPaliConfig
  25. @auto_docstring
  26. class ColPaliPreTrainedModel(PreTrainedModel):
  27. config: ColPaliConfig
  28. base_model_prefix = "model"
  29. _no_split_modules = []
  30. _supports_sdpa = True
  31. _supports_flash_attn = True
  32. _supports_flex_attn = True
  33. def _init_weights(self, module):
  34. std = (
  35. self.config.initializer_range
  36. if hasattr(self.config, "initializer_range")
  37. else self.config.vlm_config.text_config.initializer_range
  38. )
  39. if isinstance(module, (nn.Linear, nn.Conv2d)):
  40. module.weight.data.normal_(mean=0.0, std=std)
  41. if module.bias is not None:
  42. module.bias.data.zero_()
  43. elif isinstance(module, nn.Embedding):
  44. module.weight.data.normal_(mean=0.0, std=std)
  45. if module.padding_idx is not None:
  46. module.weight.data[module.padding_idx].zero_()
  47. @dataclass
  48. @auto_docstring(
  49. custom_intro="""
  50. Base class for ColPali embeddings output.
  51. """
  52. )
  53. class ColPaliForRetrievalOutput(ModelOutput):
  54. r"""
  55. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  56. Language modeling loss (for next-token prediction).
  57. embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  58. The embeddings of the model.
  59. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  60. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  61. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  62. `past_key_values` input) to speed up sequential decoding.
  63. image_hidden_states (`torch.FloatTensor`, *optional*):
  64. A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
  65. image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
  66. """
  67. loss: Optional[torch.FloatTensor] = None
  68. embeddings: Optional[torch.Tensor] = None
  69. past_key_values: Optional[Cache] = None
  70. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  71. attentions: Optional[tuple[torch.FloatTensor]] = None
  72. image_hidden_states: Optional[torch.FloatTensor] = None
  73. @auto_docstring(
  74. custom_intro="""
  75. The ColPali architecture leverages VLMs to construct efficient multi-vector embeddings directly
  76. from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
  77. between these document embeddings and the corresponding query embeddings, using the late interaction method
  78. introduced in ColBERT.
  79. Using ColPali removes the need for potentially complex and brittle layout recognition and OCR pipelines with a
  80. single model that can take into account both the textual and visual content (layout, charts, etc.) of a document.
  81. ColPali is part of the ColVision model family, which was first introduced in the following paper:
  82. [*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
  83. """
  84. )
  85. class ColPaliForRetrieval(ColPaliPreTrainedModel):
  86. _checkpoint_conversion_mapping = {
  87. "vlm.language_model.model": "vlm.model.language_model",
  88. "vlm.vision_tower": "vlm.model.vision_tower",
  89. "vlm.multi_modal_projector": "vlm.model.multi_modal_projector",
  90. "vlm.language_model.lm_head": "vlm.lm_head",
  91. }
  92. def __init__(self, config: ColPaliConfig):
  93. super().__init__(config)
  94. self.config = config
  95. self.vocab_size = config.vlm_config.text_config.vocab_size
  96. self.vlm = AutoModelForImageTextToText.from_config(config.vlm_config)
  97. self._tied_weights_keys = [f"vlm.language_model.{k}" for k in (self.vlm._tied_weights_keys or [])]
  98. self.embedding_dim = self.config.embedding_dim
  99. self.embedding_proj_layer = nn.Linear(
  100. self.config.vlm_config.text_config.hidden_size,
  101. self.embedding_dim,
  102. )
  103. self.post_init()
  104. @can_return_tuple
  105. @auto_docstring
  106. def forward(
  107. self,
  108. input_ids: Optional[torch.LongTensor] = None,
  109. pixel_values: Optional[torch.FloatTensor] = None,
  110. attention_mask: Optional[torch.Tensor] = None,
  111. output_attentions: Optional[bool] = None,
  112. output_hidden_states: Optional[bool] = None,
  113. return_dict: Optional[bool] = None,
  114. **kwargs,
  115. ) -> ColPaliForRetrievalOutput:
  116. if pixel_values is not None:
  117. pixel_values = pixel_values.to(dtype=self.dtype)
  118. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  119. output_hidden_states = (
  120. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  121. )
  122. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  123. vlm_output = self.vlm.model(
  124. input_ids=input_ids,
  125. attention_mask=attention_mask,
  126. pixel_values=pixel_values,
  127. output_hidden_states=True,
  128. return_dict=True,
  129. output_attentions=output_attentions,
  130. **kwargs,
  131. )
  132. vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
  133. vlm_image_hidden_states = vlm_output.image_hidden_states if pixel_values is not None else None
  134. last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
  135. proj_dtype = self.embedding_proj_layer.weight.dtype
  136. embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
  137. # L2 normalization
  138. embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
  139. if attention_mask is not None:
  140. embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
  141. return ColPaliForRetrievalOutput(
  142. embeddings=embeddings,
  143. past_key_values=vlm_output.past_key_values,
  144. hidden_states=vlm_hidden_states,
  145. attentions=vlm_output.attentions,
  146. image_hidden_states=vlm_image_hidden_states,
  147. )
  148. def get_input_embeddings(self):
  149. return self.vlm.get_input_embeddings()
  150. def set_input_embeddings(self, value):
  151. self.vlm.set_input_embeddings(value)
  152. def get_output_embeddings(self):
  153. return self.vlm.get_output_embeddings()
  154. def set_output_embeddings(self, new_embeddings):
  155. self.vlm.set_output_embeddings(new_embeddings)
  156. def tie_weights(self):
  157. return self.vlm.tie_weights()
  158. def resize_token_embeddings(
  159. self,
  160. new_num_tokens: Optional[int] = None,
  161. pad_to_multiple_of: Optional[int] = None,
  162. mean_resizing: bool = True,
  163. ) -> nn.Embedding:
  164. model_embeds = self.vlm.resize_token_embeddings(
  165. new_num_tokens=new_num_tokens,
  166. pad_to_multiple_of=pad_to_multiple_of,
  167. mean_resizing=mean_resizing,
  168. )
  169. self.config.vlm_config.text_config.vocab_size = model_embeds.num_embeddings
  170. self.config.vlm_config.vocab_size = model_embeds.num_embeddings
  171. self.vlm.vocab_size = model_embeds.num_embeddings
  172. self.vocab_size = model_embeds.num_embeddings
  173. return model_embeds
  174. __all__ = [
  175. "ColPaliForRetrieval",
  176. "ColPaliPreTrainedModel",
  177. ]