modular_smolvlm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # Copyright 2025 the HuggingFace Inc. team. All rights reserved.
  2. # Written by Orr Zohar
  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. import torch
  16. from huggingface_hub.dataclasses import strict
  17. from torch import nn
  18. from ...cache_utils import Cache, DynamicCache
  19. from ...generation import GenerationConfig
  20. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  21. from ...modeling_outputs import BaseModelOutputWithPooling
  22. from ...processing_utils import ImagesKwargs, Unpack
  23. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check
  24. from ..idefics3.configuration_idefics3 import Idefics3Config, Idefics3VisionConfig
  25. from ..idefics3.image_processing_idefics3 import Idefics3ImageProcessor
  26. from ..idefics3.image_processing_pil_idefics3 import Idefics3ImageProcessorPil
  27. from ..idefics3.modeling_idefics3 import (
  28. Idefics3BaseModelOutputWithPast,
  29. Idefics3ForConditionalGeneration,
  30. Idefics3Model,
  31. Idefics3PreTrainedModel,
  32. Idefics3VisionTransformer,
  33. )
  34. logger = logging.get_logger(__name__)
  35. @auto_docstring(checkpoint="HuggingFaceTB/SmolVLM2-2.2B-Instruct")
  36. @strict
  37. class SmolVLMVisionConfig(Idefics3VisionConfig):
  38. r"""
  39. Example:
  40. ```python
  41. >>> from transformers.models.smolvlm.modeling_smolvlm import SmolVLMVisionTransformer
  42. >>> from transformers.models.smolvlm.configuration_smolvlm import SmolVLMVisionConfig
  43. >>> # Initializing a SmolVLMVisionConfig with google/siglip-so400m-patch14-384 style configuration
  44. >>> configuration = SmolVLMVisionConfig()
  45. >>> # Initializing a SmolVLMVisionTransformer (with random weights) from the google/siglip-so400m-patch14-384 style configuration
  46. >>> model = SmolVLMVisionTransformer(configuration)
  47. >>> # Accessing the model configuration
  48. >>> configuration = model.config
  49. ```"""
  50. model_type = "smolvlm_vision"
  51. class SmolVLMPreTrainedModel(Idefics3PreTrainedModel):
  52. pass
  53. class SmolVLMVisionTransformer(Idefics3VisionTransformer):
  54. pass
  55. @auto_docstring(checkpoint="HuggingFaceTB/SmolVLM2-2.2B-Instruct")
  56. @strict
  57. class SmolVLMConfig(Idefics3Config):
  58. r"""
  59. scale_factor (`int`, *optional*, defaults to 2):
  60. The scale factor for the image encoder.
  61. Example:
  62. ```python
  63. >>> from transformers import SmolVLMModel, SmolVLMConfig
  64. >>> # Initializing configuration
  65. >>> configuration = SmolVLMConfig()
  66. >>> # Initializing a model from the configuration
  67. >>> model = SmolVLMModel(configuration)
  68. >>> # Accessing the model configuration
  69. >>> configuration = model.config
  70. ```"""
  71. model_type = "smolvlm"
  72. class SmolVLMImageProcessorKwargs(ImagesKwargs, total=False):
  73. """
  74. do_image_splitting (`bool`, *optional*, defaults to `True`):
  75. Whether to split the image into sub-images concatenated with the original image. They are split into patches
  76. such that each patch has a size of `max_image_size["height"]` x `max_image_size["width"]`.
  77. max_image_size (`Dict`, *optional*, defaults to `{"longest_edge": 364}`):
  78. Maximum resolution of the patches of images accepted by the model. This is a dictionary containing the key "longest_edge".
  79. return_row_col_info (`bool`, *optional*, defaults to `False`):
  80. Whether to return the row and column information of the images.
  81. """
  82. do_image_splitting: bool
  83. max_image_size: dict[str, int]
  84. return_row_col_info: bool
  85. class SmolVLMImageProcessor(Idefics3ImageProcessor):
  86. pass
  87. class SmolVLMImageProcessorPil(Idefics3ImageProcessorPil):
  88. pass
  89. class SmolVLMBaseModelOutputWithPast(Idefics3BaseModelOutputWithPast):
  90. pass
  91. class SmolVLMModel(Idefics3Model):
  92. """
  93. A subclass of Idefics3Model. We do *not* remove or block the call to inputs_merger
  94. in forward. Instead, we override inputs_merger here with custom logic.
  95. """
  96. def inputs_merger(
  97. self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, image_hidden_states: torch.Tensor
  98. ):
  99. _, patch_size, _ = image_hidden_states.shape
  100. if input_ids is None:
  101. image_mask = inputs_embeds == self.get_input_embeddings()(
  102. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  103. )
  104. image_mask = image_mask[..., 0] # slice off the hidden dim
  105. else:
  106. image_mask = input_ids == self.config.image_token_id
  107. num_image_tokens = image_mask.sum(dim=1)
  108. torch_compilable_check(
  109. torch.all(num_image_tokens % patch_size == 0),
  110. "At least one sample has <image> tokens not divisible by patch_size.",
  111. )
  112. blocks_per_sample = num_image_tokens // patch_size
  113. offsets = torch.nn.functional.pad(blocks_per_sample.cumsum(dim=0), (1, 0), value=0)
  114. block_offset = offsets[:-1]
  115. row_cum = image_mask.cumsum(dim=-1)
  116. chunk_idx = (row_cum - 1) // patch_size
  117. local_idx = (row_cum - 1) % patch_size
  118. block_idx = block_offset.unsqueeze(1) + chunk_idx
  119. image_embeds = torch.zeros_like(inputs_embeds)
  120. image_embeds[image_mask] = image_hidden_states[block_idx[image_mask], local_idx[image_mask], :]
  121. merged_embeds = torch.where(image_mask.unsqueeze(-1), image_embeds, inputs_embeds)
  122. return merged_embeds
  123. @can_return_tuple
  124. @auto_docstring(
  125. custom_intro="Encodes images into continuous embeddings that can be forwarded to the language model."
  126. )
  127. def get_image_features(
  128. self,
  129. pixel_values: torch.FloatTensor,
  130. pixel_attention_mask: torch.LongTensor | None = None,
  131. **kwargs: Unpack[TransformersKwargs],
  132. ) -> tuple | BaseModelOutputWithPooling:
  133. r"""
  134. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  135. The tensors corresponding to the input images.
  136. pixel_attention_mask (`torch.LongTensor`, *optional*):
  137. The attention mask indicating padded regions in the image.
  138. """
  139. batch_size, num_images, num_channels, height, width = pixel_values.shape
  140. pixel_values = pixel_values.to(dtype=self.dtype) # fp16 compatibility
  141. pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
  142. # Remove padding images - padding images are full 0.
  143. nb_values_per_image = pixel_values.shape[1:].numel()
  144. real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
  145. # If no images, leave one empty image.
  146. real_images_inds[0] |= ~torch.any(real_images_inds)
  147. pixel_values = pixel_values[real_images_inds].contiguous()
  148. # Handle the vision attention mask
  149. if pixel_attention_mask is None:
  150. pixel_attention_mask = torch.ones(
  151. size=[pixel_values.shape[i] for i in (0, 2, 3)],
  152. dtype=torch.bool,
  153. device=pixel_values.device,
  154. )
  155. else:
  156. # Remove padding images from the mask
  157. pixel_attention_mask = pixel_attention_mask.view(batch_size * num_images, *pixel_attention_mask.shape[2:])
  158. pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
  159. patch_size = self.config.vision_config.patch_size
  160. patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
  161. patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
  162. patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
  163. # Get sequence from the vision encoder
  164. image_outputs = self.vision_model(
  165. pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, return_dict=True, **kwargs
  166. )
  167. image_hidden_states = image_outputs.last_hidden_state
  168. # Modality projection & resampling
  169. image_features = self.connector(image_hidden_states)
  170. image_outputs.pooler_output = image_features
  171. return image_outputs
  172. @can_return_tuple
  173. @auto_docstring(
  174. custom_intro="""
  175. Inputs fed to the model can have an arbitrary number of images. To account for this, pixel_values fed to
  176. the model have image padding -> (batch_size, max_num_images, 3, max_heights, max_widths) where
  177. max_num_images is the maximum number of images among the batch_size samples in the batch.
  178. Padding images are not needed beyond padding the pixel_values at the entrance of the model.
  179. For efficiency, we only pass through the vision_model's forward the real images by
  180. discarding the padding images i.e. pixel_values of size (image_batch_size, 3, height, width) where
  181. image_batch_size would be 7 when num_images_per_sample=[1, 3, 1, 2] and max_num_images would be 3.
  182. """
  183. )
  184. @can_return_tuple
  185. def forward(
  186. self,
  187. input_ids: torch.LongTensor | None = None,
  188. attention_mask: torch.Tensor | None = None,
  189. position_ids: torch.LongTensor | None = None,
  190. past_key_values: Cache | None = None,
  191. inputs_embeds: torch.FloatTensor | None = None,
  192. pixel_values: torch.FloatTensor | None = None,
  193. pixel_attention_mask: torch.BoolTensor | None = None,
  194. image_hidden_states: torch.FloatTensor | None = None,
  195. use_cache: bool | None = None,
  196. **kwargs: Unpack[FlashAttentionKwargs],
  197. ) -> tuple | SmolVLMBaseModelOutputWithPast:
  198. if self.training and self.text_model.gradient_checkpointing and use_cache:
  199. logger.warning_once(
  200. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  201. )
  202. use_cache = False
  203. if input_ids is not None:
  204. batch_size, seq_length = input_ids.shape
  205. elif inputs_embeds is not None:
  206. batch_size, seq_length, _ = inputs_embeds.shape
  207. else:
  208. raise ValueError("You have to specify either input_ids or inputs_embeds")
  209. if use_cache and past_key_values is None:
  210. past_key_values = DynamicCache(config=self.config)
  211. if inputs_embeds is None:
  212. inputs_embeds = self.text_model.get_input_embeddings()(input_ids).to(input_ids.device)
  213. if pixel_values is not None and image_hidden_states is not None:
  214. raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
  215. if pixel_values is not None:
  216. image_hidden_states = self.get_image_features(
  217. pixel_values, pixel_attention_mask, return_dict=True
  218. ).pooler_output
  219. image_hidden_states = image_hidden_states.to(inputs_embeds.device)
  220. elif image_hidden_states is not None:
  221. image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=inputs_embeds.device)
  222. if image_hidden_states is not None:
  223. inputs_embeds = self.inputs_merger(
  224. input_ids=input_ids,
  225. inputs_embeds=inputs_embeds,
  226. image_hidden_states=image_hidden_states,
  227. )
  228. outputs = self.text_model(
  229. inputs_embeds=inputs_embeds,
  230. attention_mask=attention_mask,
  231. position_ids=position_ids,
  232. past_key_values=past_key_values,
  233. use_cache=use_cache,
  234. **kwargs,
  235. )
  236. return SmolVLMBaseModelOutputWithPast(
  237. last_hidden_state=outputs.last_hidden_state,
  238. past_key_values=outputs.past_key_values,
  239. hidden_states=outputs.hidden_states,
  240. attentions=outputs.attentions,
  241. image_hidden_states=image_hidden_states,
  242. )
  243. class SmolVLMForConditionalGeneration(Idefics3ForConditionalGeneration):
  244. _tied_weights_keys = {"lm_head.weight": "model.text_model.embed_tokens.weight"}
  245. def __init__(self, config):
  246. super().__init__(config)
  247. self.model = SmolVLMModel(config)
  248. self.model.text_model.generation_config = GenerationConfig.from_model_config(config)
  249. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  250. self.post_init()
  251. def forward(self, **super_kwargs):
  252. r"""
  253. pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
  254. Mask to avoid performing attention on padding pixel indices.
  255. image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  256. The hidden states of the image encoder after modality projection.
  257. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  258. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  259. config.vocab_size]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
  260. ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  261. Example:
  262. ```python
  263. >>> import httpx
  264. >>> from io import BytesIO
  265. >>> import torch
  266. >>> from PIL import Image
  267. >>> from io import BytesIO
  268. >>> from transformers import AutoProcessor, AutoModelForImageTextToText
  269. >>> from transformers.image_utils import load_image
  270. >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
  271. >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
  272. >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
  273. >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
  274. >>> processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct")
  275. >>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct", dtype=torch.bfloat16, device_map="auto")
  276. >>> # Create inputs
  277. >>> messages = [
  278. ... {
  279. ... "role": "user",
  280. ... "content": [
  281. ... {"type": "video", "path": path/to/video},
  282. ... {"type": "text", "text": "What is happening in this video?"},
  283. ... ]
  284. ... }
  285. ... ]
  286. >>> inputs = processor.apply_chat_template([messages], add_generation_prompt=True)
  287. >>> # Generate
  288. >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
  289. >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
  290. >>> print(generated_texts)
  291. ```"""
  292. super().forward(**super_kwargs)
  293. __all__ = [
  294. "SmolVLMVisionConfig",
  295. "SmolVLMConfig",
  296. "SmolVLMImageProcessor",
  297. "SmolVLMImageProcessorPil",
  298. "SmolVLMForConditionalGeneration",
  299. "SmolVLMPreTrainedModel",
  300. "SmolVLMModel",
  301. "SmolVLMVisionTransformer",
  302. ]