processing_smolvlm.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # coding=utf-8
  2. # Copyright 2025 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. """
  16. Processor class for SmolVLM.
  17. """
  18. from datetime import timedelta
  19. from typing import TYPE_CHECKING, Optional, Union
  20. from ...feature_extraction_utils import BatchFeature
  21. from ...image_utils import ImageInput, make_nested_list_of_images
  22. from ...processing_utils import AllKwargsForChatTemplate, ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
  23. from ...tokenization_utils_base import BatchEncoding, TextInput
  24. from ...utils import is_num2words_available, is_vision_available, logging
  25. from ...video_utils import VideoInput
  26. if is_vision_available():
  27. from .video_processing_smolvlm import (
  28. DEFAULT_MEDIA_OUTTRO,
  29. DEFAULT_VIDEO_INTRO,
  30. FRAME_TIMESTAMP_MESSAGE,
  31. )
  32. if is_vision_available():
  33. from .video_processing_smolvlm import (
  34. DEFAULT_MEDIA_OUTTRO,
  35. DEFAULT_VIDEO_INTRO,
  36. FRAME_TIMESTAMP_MESSAGE,
  37. )
  38. if TYPE_CHECKING:
  39. from ...tokenization_utils_base import PreTokenizedInput
  40. logger = logging.get_logger(__name__)
  41. if is_num2words_available():
  42. from num2words import num2words
  43. else:
  44. num2words = None
  45. # The correct chat template to be used for videos after #38105
  46. DEFAULT_CHAT_TEMPLATE = "<|im_start|>{% for message in messages %}{{message['role'] | capitalize}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% elif line['type'] == 'video' %}{{ '<video>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"
  47. def _prompt_split_image(
  48. image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_image_token
  49. ):
  50. """Prompt with expanded image tokens for when the image is split into patches."""
  51. text_split_images = ""
  52. for n_h in range(image_rows):
  53. for n_w in range(image_cols):
  54. text_split_images += (
  55. f"{fake_token_around_image}" + f"<row_{n_h + 1}_col_{n_w + 1}>" + f"{image_token}" * image_seq_len
  56. )
  57. text_split_images += "\n"
  58. text_split_images += (
  59. f"\n{fake_token_around_image}"
  60. + f"{global_image_token}"
  61. + f"{image_token}" * image_seq_len
  62. + f"{fake_token_around_image}"
  63. )
  64. return text_split_images
  65. def _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_image_token):
  66. """Prompt with expanded image tokens for a single image."""
  67. return (
  68. f"{fake_token_around_image}"
  69. + f"{global_image_token}"
  70. + f"{image_token}" * image_seq_len
  71. + f"{fake_token_around_image}"
  72. )
  73. def get_image_prompt_string(
  74. image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_image_token
  75. ):
  76. if image_rows == 0 and image_cols == 0:
  77. return _prompt_single_image(
  78. image_seq_len,
  79. fake_token_around_image=fake_token_around_image,
  80. image_token=image_token,
  81. global_image_token=global_image_token,
  82. )
  83. return _prompt_split_image(
  84. image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_image_token
  85. )
  86. class SmolVLMImagesKwargs(ImagesKwargs, total=False):
  87. return_row_col_info: Optional[bool]
  88. max_image_size: Optional[dict[str, int]]
  89. class SmolVLMProcessorKwargs(ProcessingKwargs, total=False):
  90. images_kwargs: SmolVLMImagesKwargs
  91. _defaults = {
  92. "text_kwargs": {
  93. "add_special_tokens": True,
  94. "padding": False,
  95. "is_split_into_words": False,
  96. },
  97. "images_kwargs": {
  98. "return_row_col_info": True,
  99. },
  100. "videos_kwargs": {
  101. "return_metadata": True,
  102. },
  103. }
  104. class SmolVLMProcessor(ProcessorMixin):
  105. r"""
  106. Constructs a SmolVLM processor which wraps a LLama tokenizer and SmolVLM image processor into a single processor.
  107. [`SmolVLMProcessor`] offers all the functionalities of [`SmolVLMImageProcessor`] and [`SmolVLMTokenizerFast`]. See
  108. the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.
  109. Args:
  110. image_processor (`SmolVLMImageProcessor`):
  111. An instance of [`SmolVLMImageProcessor`]. The image processor is a required input.
  112. tokenizer (`PreTrainedTokenizerBase`):
  113. An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
  114. video_processor (`SmolVLMImageProcessor`):
  115. n instance of [`SmolVLMImageProcessor`]. The video processor is a required input.
  116. image_seq_len (`int`, *optional*, defaults to 169):
  117. The length of the image sequence i.e. the number of <image> tokens per image in the input.
  118. This parameter is used to build the string from the input prompt and image tokens and should match the
  119. value the model used. It is computed as: image_seq_len = int(((image_size // patch_size) ** 2) / (scale_factor**2))
  120. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  121. in a chat into a tokenizable string.
  122. """
  123. attributes = ["image_processor", "tokenizer", "video_processor"]
  124. image_processor_class = "SmolVLMImageProcessor"
  125. video_processor_class = "SmolVLMVideoProcessor" # NOTE: uses different interpolation than slow processors
  126. tokenizer_class = "AutoTokenizer"
  127. def __init__(
  128. self,
  129. image_processor,
  130. tokenizer,
  131. video_processor,
  132. image_seq_len: int = 169,
  133. chat_template: Optional[str] = None,
  134. **kwargs,
  135. ):
  136. self.fake_image_token = getattr(tokenizer, "fake_image_token", "<fake_token_around_image>")
  137. self.image_token = getattr(tokenizer, "image_token", "<image>")
  138. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  139. self.end_of_utterance_token = getattr(tokenizer, "end_of_utterance_token", "<end_of_utterance>")
  140. self.global_image_token = getattr(tokenizer, "global_image_token", "<global-img>")
  141. self.image_seq_len = image_seq_len
  142. self.video_token = getattr(tokenizer, "video_token", "<video>")
  143. if not num2words:
  144. raise ImportError(
  145. "Package `num2words` is required to run SmolVLM processor. Install it with `pip install num2words`."
  146. )
  147. super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template, **kwargs)
  148. def expand_text_with_image_tokens(self, text, image_rows, image_cols):
  149. prompt_strings = []
  150. image_rows = image_rows if image_rows is not None else [[0] * len(text)]
  151. image_cols = image_cols if image_cols is not None else [[0] * len(text)]
  152. for sample, sample_rows, sample_cols in zip(text, image_rows, image_cols):
  153. # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
  154. image_prompt_strings = []
  155. for n_rows, n_cols in zip(sample_rows, sample_cols):
  156. image_prompt_string = get_image_prompt_string(
  157. n_rows,
  158. n_cols,
  159. self.image_seq_len,
  160. image_token=self.image_token,
  161. fake_token_around_image=self.fake_image_token,
  162. global_image_token=self.global_image_token,
  163. )
  164. image_prompt_strings.append(image_prompt_string)
  165. split_sample = sample.split(self.image_token)
  166. if len(split_sample) == 0:
  167. raise ValueError("The image token should be present in the text.")
  168. # Place in the image prompt strings where the image tokens are
  169. sample = split_sample[0]
  170. for i, image_prompt_string in enumerate(image_prompt_strings):
  171. sample += image_prompt_string + split_sample[i + 1]
  172. prompt_strings.append(sample)
  173. return prompt_strings
  174. def expand_text_with_video_tokens(self, text, video_inputs):
  175. num_frames = video_inputs["pixel_values"].shape[1]
  176. video_metadata = iter(video_inputs["video_metadata"])
  177. prompt_strings = []
  178. for sample in text:
  179. while self.video_token in sample:
  180. metadata = next(video_metadata)
  181. if metadata.fps is None:
  182. logger.warning_once(
  183. "SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. "
  184. "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. "
  185. "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
  186. )
  187. metadata.fps = 24 # Set the default fps to 24 for BC, otherwise `timestamps` can't be inferred
  188. timestamps = [(int(second // 60), int(second % 60)) for second in metadata.timestamps]
  189. duration = int(metadata.duration) if metadata.duration is not None else int(metadata.timestamps[-1])
  190. duration_td = timedelta(seconds=int(duration))
  191. image_prompt_strings = DEFAULT_VIDEO_INTRO.format(
  192. frame_count=num2words(num_frames), video_duration=str(duration_td)
  193. )
  194. for timestamp in timestamps:
  195. image_prompt_string = _prompt_single_image(
  196. self.image_seq_len,
  197. image_token=self.image_token,
  198. fake_token_around_image=self.fake_image_token,
  199. global_image_token=self.global_image_token,
  200. )
  201. timestamp = f"{timestamp[0]:02d}:{timestamp[1]:02d}"
  202. image_prompt_string = FRAME_TIMESTAMP_MESSAGE.format(timestamp=timestamp) + image_prompt_string
  203. image_prompt_strings += image_prompt_string
  204. image_prompt_strings += DEFAULT_MEDIA_OUTTRO
  205. sample = sample.replace(self.video_token, image_prompt_strings, 1)
  206. prompt_strings.append(sample)
  207. return prompt_strings
  208. def __call__(
  209. self,
  210. images: Union[ImageInput, list[ImageInput], list[list[ImageInput]]] = None,
  211. text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
  212. audio=None,
  213. videos: Optional[VideoInput] = None,
  214. **kwargs: Unpack[SmolVLMProcessorKwargs],
  215. ) -> BatchEncoding:
  216. """
  217. Processes the input prompts and returns a BatchEncoding.
  218. Example:
  219. ```python
  220. >>> import requests
  221. >>> from transformers import SmolVLMProcessor
  222. >>> from transformers.image_utils import load_image
  223. >>> processor = SmolVLMProcessor.from_pretrained("HuggingFaceM4/SmolVLM2-256M-Video-Instruct")
  224. >>> processor.image_processor.do_image_splitting = False # Force as False to simplify the example
  225. >>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
  226. >>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"
  227. >>> image1, image2 = load_image(url1), load_image(url2)
  228. >>> images = [[image1], [image2]]
  229. >>> text = [
  230. ... "<image>In this image, we see",
  231. ... "bla bla bla<image>",
  232. ... ]
  233. >>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
  234. >>> input_ids = outputs.input_ids
  235. >>> input_tokens = processor.tokenizer.batch_decode(input_ids)
  236. >>> print(input_tokens)
  237. ['<|begin_of_text|><fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image> In this image, we see', '<|reserved_special_token_0|><|reserved_special_token_0|><|reserved_special_token_0|><|begin_of_text|>bla bla bla<fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image>']
  238. ```
  239. Args:
  240. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`, *optional*):
  241. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  242. tensor. If is of type `list[ImageInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
  243. text (`Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]`, *optional*):
  244. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  245. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  246. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  247. Wherever an image token, `<image>` is encountered it is expanded to
  248. `<fake_token_around_image>` + `<row_x_col_y>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
  249. videos (`list[PIL.Image.Image]`, `np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`, *optional*):
  250. The video or batch of videos to be prepared. Each video can be a list of PIL frames, NumPy array or PyTorch
  251. tensor. If is of type `list[VideoInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
  252. return_tensors (`Union[str, TensorType]`, *optional*):
  253. If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
  254. information.
  255. """
  256. if text is None and images is None and videos is None:
  257. raise ValueError("You must provide one of `text`, `images` or `videos'.")
  258. if text is None and ((images is None) ^ (videos is not None)):
  259. raise ValueError("You must specify exactly one of `images` or `videos`")
  260. output_kwargs = self._merge_kwargs(
  261. SmolVLMProcessorKwargs,
  262. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  263. **kwargs,
  264. )
  265. if text is not None:
  266. if isinstance(text, str):
  267. text = [text]
  268. elif not isinstance(text, list) and not isinstance(text[0], str):
  269. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  270. n_images_in_text = sum(sample.count(self.image_token) for sample in text)
  271. if n_images_in_text > 0 and (images is None and videos is None):
  272. raise ValueError(f"We detected {n_images_in_text} tokens in the text but no images/videos were passed")
  273. inputs = {}
  274. # Images and videos are mutually exclusive, so process one which is present
  275. if images is not None:
  276. images = self.image_processor.fetch_images(images)
  277. images = make_nested_list_of_images(images)
  278. vision_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  279. image_rows = vision_inputs.pop("rows", None)
  280. image_cols = vision_inputs.pop("cols", None)
  281. inputs.update(vision_inputs)
  282. if text is not None:
  283. n_images_in_text = [sample.count(self.image_token) for sample in text]
  284. n_images_in_images = [len(sublist) for sublist in images]
  285. if n_images_in_images != n_images_in_text:
  286. raise ValueError(
  287. f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
  288. )
  289. text = self.expand_text_with_image_tokens(text, image_rows=image_rows, image_cols=image_cols)
  290. elif videos is not None:
  291. vision_inputs = self.video_processor(videos, **output_kwargs["videos_kwargs"])
  292. if text is not None:
  293. n_videos_in_text = [sample.count(self.video_token) for sample in text]
  294. n_videos_in_videos = [len(sublist) for sublist in videos]
  295. if n_videos_in_videos != n_videos_in_text:
  296. raise ValueError(
  297. f"The number of videos in the text {n_videos_in_text} and videos {n_videos_in_videos} should be the same."
  298. )
  299. text = self.expand_text_with_video_tokens(text, vision_inputs)
  300. # If user has not requested video metadata, pop it. By default metadata
  301. # is always returned to expand video tokens correctly
  302. if "return_metadata" not in kwargs:
  303. vision_inputs.pop("video_metadata")
  304. inputs.update(vision_inputs)
  305. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  306. if text is not None:
  307. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
  308. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  309. inputs.update(text_inputs)
  310. return BatchFeature(inputs, tensor_type=return_tensors)
  311. def apply_chat_template(
  312. self,
  313. conversation: Union[list[dict[str, str]], list[list[dict[str, str]]]],
  314. chat_template: Optional[str] = None,
  315. **kwargs: Unpack[AllKwargsForChatTemplate],
  316. ) -> str:
  317. """
  318. Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
  319. conversations to turn them into a single tokenizable string.
  320. The input is expected to be in the following format, where each message content is a list consisting of text and
  321. optionally image or video inputs. One can also provide an image, video, URL or local path which will be used to form
  322. `pixel_values` when `return_dict=True`. If not provided, one will get only the formatted text, optionally tokenized text.
  323. conversation = [
  324. {
  325. "role": "user",
  326. "content": [
  327. {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
  328. {"type": "text", "text": "Please describe this image in detail."},
  329. ],
  330. },
  331. ]
  332. Args:
  333. conversation (`Union[list[Dict, [str, str]], list[list[dict[str, str]]]]`):
  334. The conversation to format.
  335. chat_template (`Optional[str]`, *optional*):
  336. The Jinja template to use for formatting the conversation. If not provided, the tokenizer's
  337. chat template is used.
  338. """
  339. if isinstance(conversation, (list, tuple)) and (
  340. isinstance(conversation[0], (list, tuple)) or hasattr(conversation[0], "content")
  341. ):
  342. conversations = conversation
  343. else:
  344. conversations = [conversation]
  345. has_video = any(
  346. (isinstance(content, dict) and content["type"] == "video")
  347. for conversation in conversations
  348. for message in conversation
  349. for content in message["content"]
  350. )
  351. if chat_template is None and has_video:
  352. # re-assign to the correct default template for BC, if user is not requesting their own template
  353. chat_template = DEFAULT_CHAT_TEMPLATE
  354. kwargs.setdefault("num_frames", self.video_processor.num_frames)
  355. kwargs.setdefault("fps", self.video_processor.fps)
  356. return super().apply_chat_template(conversation, chat_template, **kwargs)
  357. __all__ = ["SmolVLMProcessor"]