processing_colmodernvbert.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/colmodernvbert/modular_colmodernvbert.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_colmodernvbert.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2026 Illuin Technology and contributors, and The HuggingFace Inc. team. All rights reserved.
  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. import re
  21. from itertools import accumulate
  22. from typing import TYPE_CHECKING, Optional, Union
  23. import numpy as np
  24. import torch
  25. from ...feature_extraction_utils import BatchFeature
  26. from ...image_utils import ImageInput, is_valid_image, load_image
  27. from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
  28. from ...tokenization_utils_base import AddedToken, BatchEncoding, TextInput
  29. from ...utils import auto_docstring
  30. from ...utils.import_utils import requires
  31. if TYPE_CHECKING:
  32. from ...tokenization_utils_base import PreTokenizedInput
  33. class ColModernVBertProcessorKwargs(ProcessingKwargs, total=False):
  34. _defaults = {
  35. "text_kwargs": {
  36. "padding": "longest",
  37. },
  38. "images_kwargs": {
  39. "return_row_col_info": True,
  40. "data_format": "channels_first",
  41. "do_convert_rgb": True,
  42. },
  43. "common_kwargs": {"return_tensors": "pt"},
  44. }
  45. def is_url(val) -> bool:
  46. return isinstance(val, str) and val.startswith("http")
  47. def is_image_or_image_url(elem):
  48. return is_url(elem) or is_valid_image(elem)
  49. def _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token):
  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_img_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_img_token):
  66. """Prompt with expanded image tokens for a single image."""
  67. return (
  68. f"{fake_token_around_image}"
  69. + f"{global_img_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_img_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_img_token=global_img_token,
  82. )
  83. return _prompt_split_image(
  84. image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token
  85. )
  86. @requires(backends=("torch",))
  87. @auto_docstring
  88. class ColModernVBertProcessor(ProcessorMixin):
  89. r"""
  90. Constructs a ColModernVBert processor which wraps a ModernVBertProcessor and special methods to process images and queries, as
  91. well as to compute the late-interaction retrieval score.
  92. [`ColModernVBertProcessor`] offers all the functionalities of [`ModernVBertProcessor`]. See the [`~ModernVBertProcessor.__call__`]
  93. for more information.
  94. Args:
  95. image_processor ([`Idefics3ImageProcessor`]): An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
  96. tokenizer (`PreTrainedTokenizerFast`, *optional*): An instance of [`PreTrainedTokenizerFast`]. This should correspond with the model's text model. The tokenizer is a required input.
  97. image_seq_len (`int`, *optional*, defaults to 64): The length of the image sequence i.e. the number of <image> tokens per image in the input.
  98. visual_prompt_prefix (`Optional`, *optional*): A prefix to be prepended to visual prompts.
  99. query_prefix (`Optional`, *optional*): A prefix to be prepended to query prompts.
  100. """
  101. def __init__(
  102. self,
  103. image_processor,
  104. tokenizer=None,
  105. chat_template=None,
  106. image_seq_len: int = 64,
  107. visual_prompt_prefix: str | None = None,
  108. query_prefix: str | None = None,
  109. **kwargs,
  110. ):
  111. r"""
  112. image_seq_len (`int`, *optional*, defaults to 64):
  113. The length of the image sequence i.e. the number of <image> tokens per image in the input.
  114. visual_prompt_prefix (`str`, *optional*):
  115. A string that gets tokenized and prepended to the image tokens.
  116. query_prefix (`str`, *optional*):
  117. A prefix to be used for the query.
  118. """
  119. chat_template = None # ColModernVBert does not use chat templates
  120. self.fake_image_token = AddedToken("<fake_token_around_image>", normalized=False, special=True).content
  121. self.image_token = AddedToken("<image>", normalized=False, special=True).content
  122. self.end_of_utterance_token = AddedToken("<end_of_utterance>", normalized=False, special=True).content
  123. self.global_image_tag = "<global-img>" # https://github.com/huggingface/transformers/pull/32473/files/8063e5e17362571b693f1db95167f5443a3be1b2#r1734825341
  124. self.image_seq_len = image_seq_len
  125. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  126. self.fake_image_token_id = tokenizer.convert_tokens_to_ids(self.fake_image_token)
  127. self.global_image_token_id = tokenizer.convert_tokens_to_ids(self.global_image_tag)
  128. self.row_col_ids = [
  129. tokenizer.convert_tokens_to_ids(f"<row_{i + 1}_col_{j + 1}>") for i in range(6) for j in range(6)
  130. ]
  131. # This regex matches one or more occurrences of <global-img> tags (optionally surrounded by newline characters)
  132. # or <row_x_col_y> tags (where x and y are digits, also optionally surrounded by newline characters).
  133. self._regex_to_remove_extra_special_tokens = re.compile(r"(\n?<global-img>\n?|<row_\d+_col_\d+>\n?)+")
  134. tokens_to_add = {
  135. "additional_special_tokens": [
  136. self.fake_image_token,
  137. self.image_token,
  138. self.end_of_utterance_token,
  139. ]
  140. }
  141. tokenizer.add_special_tokens(tokens_to_add)
  142. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  143. super().__init__(image_processor, tokenizer, chat_template=chat_template, **kwargs)
  144. self.visual_prompt_prefix = visual_prompt_prefix or (
  145. f"<|begin_of_text|>User:{self.image_token}Describe the image.<end_of_utterance>\nAssistant:"
  146. )
  147. self.query_prefix = query_prefix or ""
  148. self.query_augmentation_token = self.end_of_utterance_token
  149. def _extract_images_from_prompts(self, prompts):
  150. prompt_images = []
  151. for prompt in prompts:
  152. images = []
  153. for elem in prompt:
  154. if is_valid_image(elem):
  155. images.append(elem)
  156. elif is_url(elem):
  157. images.append(load_image(elem))
  158. prompt_images.append(images)
  159. return prompt_images
  160. @auto_docstring
  161. def __call__(
  162. self,
  163. images: ImageInput | list[ImageInput] | list[list[ImageInput]] = None,
  164. text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
  165. image_seq_len: int | None = None,
  166. **kwargs: Unpack[ColModernVBertProcessorKwargs],
  167. ) -> BatchEncoding:
  168. r"""
  169. image_seq_len (`int`, *optional*):
  170. The length of the image sequence. If not provided, the default value of self.image_seq_len is used.
  171. image_seq_len should be equal to int(((image_size // patch_size) ** 2) / (scale_factor**2))
  172. """
  173. if text is None and images is None:
  174. raise ValueError("You must provide either `text` or `images`.")
  175. output_kwargs = self._merge_kwargs(
  176. ColModernVBertProcessorKwargs,
  177. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  178. **kwargs,
  179. )
  180. image_seq_len = image_seq_len if image_seq_len is not None else self.image_seq_len
  181. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  182. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  183. n_images_in_text = []
  184. n_images_in_images = []
  185. inputs = {}
  186. if text is not None:
  187. if isinstance(text, str):
  188. text = [text]
  189. elif not isinstance(text, list) and not isinstance(text[0], str):
  190. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  191. n_images_in_text = [sample.count(self.image_token) for sample in text]
  192. if images is not None:
  193. if is_image_or_image_url(images):
  194. images = [[images]]
  195. elif isinstance(images, (list, tuple)) and is_image_or_image_url(images[0]):
  196. if text is not None:
  197. if sum(n_images_in_text) != len(images):
  198. raise ValueError(
  199. f"The total number of {self.image_token} tokens in the prompts should be the same as the number of images passed."
  200. f" Found {sum(n_images_in_text)} {self.image_token} tokens and {len(images)} images."
  201. )
  202. # Reorganize the images to match the prompts
  203. cumsum_images_in_text = [0] + list(accumulate(n_images_in_text))
  204. images = [
  205. images[cumsum_images_in_text[i] : cumsum_images_in_text[i + 1]]
  206. for i in range(len(n_images_in_text))
  207. ]
  208. else:
  209. images = [images]
  210. elif (
  211. not isinstance(images, (list, tuple))
  212. and not isinstance(images[0], (list, tuple))
  213. and not is_image_or_image_url(images[0][0])
  214. ):
  215. raise ValueError(
  216. "Invalid input images. Please provide a single image or a list of images or a list of list of images."
  217. )
  218. n_images_in_images = [len(sample) for sample in images]
  219. # Load images if they are URLs
  220. images = [[load_image(im) if is_url(im) else im for im in sample] for sample in images]
  221. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  222. inputs.update(image_inputs)
  223. if text is not None:
  224. if n_images_in_images != n_images_in_text:
  225. raise ValueError(
  226. f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
  227. )
  228. image_rows = inputs.pop("rows", [[0] * n_images for n_images in n_images_in_text])
  229. image_cols = inputs.pop("cols", [[0] * n_images for n_images in n_images_in_text])
  230. fake_image_token = self.fake_image_token
  231. image_token = self.image_token
  232. global_img_token = self.global_image_tag
  233. prompt_strings = []
  234. batch_image_seq_lengths = []
  235. for sample, sample_rows, sample_cols in zip(text, image_rows, image_cols):
  236. # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
  237. image_prompt_strings = []
  238. image_seq_lengths = []
  239. for n_rows, n_cols in zip(sample_rows, sample_cols):
  240. image_prompt_string = get_image_prompt_string(
  241. n_rows,
  242. n_cols,
  243. image_seq_len,
  244. image_token=image_token,
  245. fake_token_around_image=fake_image_token,
  246. global_img_token=global_img_token,
  247. )
  248. # Add +2 and +3 for special BOI/EOI/fake_image_wrapper tokens
  249. row_length = (self.image_seq_len + 2) * n_cols + 1
  250. image_seq_lengths.append((self.image_seq_len + 3) + row_length * n_rows)
  251. image_prompt_strings.append(image_prompt_string)
  252. batch_image_seq_lengths.append(image_seq_lengths)
  253. split_sample = sample.split(image_token)
  254. if len(split_sample) == 0:
  255. raise ValueError("The image token should be present in the text.")
  256. # Place in the image prompt strings where the image tokens are
  257. sample = split_sample[0]
  258. for i, image_prompt_string in enumerate(image_prompt_strings):
  259. sample += image_prompt_string + split_sample[i + 1]
  260. prompt_strings.append(sample)
  261. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  262. self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
  263. inputs.update(text_inputs)
  264. elif text is not None:
  265. if any(n_images_in_text):
  266. raise ValueError(
  267. f"Found {sum(n_images_in_text)} {self.image_token} tokens in the text but no images were passed."
  268. )
  269. text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  270. inputs.update(text_inputs)
  271. if return_mm_token_type_ids:
  272. inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(inputs["input_ids"], batch_image_seq_lengths)
  273. return BatchFeature(data=inputs, tensor_type=return_tensors)
  274. def create_mm_token_type_ids(self, input_ids: list, batch_image_seq_lengths: list[int]) -> list[list[int]]:
  275. # We have to iterate for each list separately because inputs
  276. # might be non-padded lists and we can't cast numpy on that!
  277. # Then cast numpy as each input for faster indexing
  278. mm_token_type_ids = []
  279. for i, seq_lengths in enumerate(batch_image_seq_lengths):
  280. array_ids = np.array(input_ids[i])
  281. mm_token_types = np.zeros_like(array_ids)
  282. image_start_positions = np.where(array_ids == self.fake_image_token_id)[0]
  283. j = 0
  284. for seq_len in seq_lengths:
  285. if j >= len(image_start_positions):
  286. break
  287. start = image_start_positions[j]
  288. end = start + seq_len
  289. mm_token_types[start:end] = 1
  290. j = np.searchsorted(image_start_positions, end)
  291. mm_token_type_ids.append(mm_token_types.tolist())
  292. return mm_token_type_ids
  293. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  294. """
  295. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  296. Args:
  297. image_sizes (`list[list[int]]`, *optional*):
  298. The input sizes formatted as (height, width) per each image.
  299. Returns:
  300. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  301. input modalities, along with other useful data.
  302. """
  303. vision_data = {}
  304. if image_sizes is not None:
  305. images_kwargs = ColModernVBertProcessorKwargs._defaults.get("images_kwargs", {})
  306. images_kwargs.update(kwargs)
  307. num_image_row_cols = [
  308. self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
  309. for image_size in image_sizes
  310. ]
  311. base_image_length = self.image_seq_len + 3
  312. col_length = self.image_seq_len + 2
  313. num_image_tokens = []
  314. num_image_patches = []
  315. for num_patches, num_rows, num_cols in num_image_row_cols:
  316. row_length = col_length * num_cols + 1
  317. num_image_tokens.append(base_image_length + (row_length * num_rows))
  318. num_image_patches.append(num_patches)
  319. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  320. return MultiModalData(**vision_data)
  321. def process_images(
  322. self,
  323. images: ImageInput | None = None,
  324. **kwargs: Unpack[ColModernVBertProcessorKwargs],
  325. ) -> BatchFeature:
  326. """
  327. Prepare for the model one or several image(s). Handles input validation, RGB conversion,
  328. and prepends the `visual_prompt_prefix` to each image. Optionally computes labels from
  329. `token_type_ids` when a `suffix` is provided in `text_kwargs`.
  330. Args:
  331. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  332. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  333. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  334. number of channels, H and W are image height and width.
  335. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  336. If set, will return tensors of a particular framework. Acceptable values are:
  337. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  338. - `'np'`: Return NumPy `np.ndarray` objects.
  339. Returns:
  340. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  341. - **input_ids** -- List of token ids to be fed to a model.
  342. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  343. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  344. `None`).
  345. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  346. """
  347. output_kwargs = self._merge_kwargs(
  348. ColModernVBertProcessorKwargs,
  349. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  350. **kwargs,
  351. )
  352. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  353. return_token_type_ids = suffix is not None
  354. # Normalize input to a flat list of images
  355. if is_valid_image(images):
  356. images = [images]
  357. elif isinstance(images, list) and is_valid_image(images[0]):
  358. pass
  359. elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
  360. raise ValueError("images must be an image, list of images or list of list of images")
  361. # Ensure all images are in RGB format
  362. images = [image.convert("RGB") for image in images]
  363. # Pair each image with the visual prompt prefix for the VLM backbone
  364. batch_doc = self.__call__(
  365. text=[self.visual_prompt_prefix] * len(images),
  366. images=images,
  367. images_kwargs=output_kwargs["images_kwargs"],
  368. text_kwargs=output_kwargs["text_kwargs"],
  369. )
  370. # When suffix is provided, generate labels by masking non-suffix tokens
  371. if return_token_type_ids:
  372. labels = batch_doc["input_ids"].masked_fill(batch_doc["token_type_ids"] == 0, -100)
  373. batch_doc.update({"labels": labels})
  374. return batch_doc
  375. def process_queries(
  376. self,
  377. text: TextInput | list[TextInput],
  378. **kwargs: Unpack[ColModernVBertProcessorKwargs],
  379. ) -> BatchFeature:
  380. """
  381. Prepare for the model one or several text queries. Handles input validation, prepends the
  382. `query_prefix`, and appends query augmentation tokens (used to pad query embeddings for
  383. better late-interaction retrieval performance).
  384. Args:
  385. text (`str`, `list[str]`, `list[list[str]]`):
  386. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  387. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  388. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  389. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  390. If set, will return tensors of a particular framework. Acceptable values are:
  391. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  392. - `'np'`: Return NumPy `np.ndarray` objects.
  393. Returns:
  394. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  395. - **input_ids** -- List of token ids to be fed to a model.
  396. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  397. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  398. `None`).
  399. """
  400. output_kwargs = self._merge_kwargs(
  401. ColModernVBertProcessorKwargs,
  402. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  403. **kwargs,
  404. )
  405. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  406. if isinstance(text, str):
  407. text = [text]
  408. elif not (isinstance(text, list) and isinstance(text[0], str)):
  409. raise ValueError("Text must be a string or a list of strings")
  410. # Default suffix: repeat the augmentation token to pad query embeddings
  411. if suffix is None:
  412. suffix = self.query_augmentation_token * 10
  413. # Build final queries: prefix + original query + augmentation suffix
  414. texts_query: list[str] = [self.query_prefix + query + suffix for query in text]
  415. batch_query = self.__call__(
  416. text=texts_query,
  417. return_token_type_ids=False,
  418. text_kwargs=output_kwargs["text_kwargs"],
  419. )
  420. return batch_query
  421. def score_retrieval(
  422. self,
  423. query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  424. passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  425. batch_size: int = 128,
  426. output_dtype: Optional["torch.dtype"] = None,
  427. output_device: Union["torch.device", str] = "cpu",
  428. ) -> "torch.Tensor":
  429. """
  430. Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
  431. query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
  432. image of a document page.
  433. Because the embedding tensors are multi-vector and can thus have different shapes, they
  434. should be fed as:
  435. (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
  436. (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
  437. obtained by padding the list of tensors.
  438. Args:
  439. query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
  440. passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
  441. batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
  442. output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
  443. If `None`, the dtype of the input embeddings is used.
  444. output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
  445. Returns:
  446. `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
  447. tensor is saved on the "cpu" device.
  448. """
  449. if len(query_embeddings) == 0:
  450. raise ValueError("No queries provided")
  451. if len(passage_embeddings) == 0:
  452. raise ValueError("No passages provided")
  453. if query_embeddings[0].device != passage_embeddings[0].device:
  454. raise ValueError("Queries and passages must be on the same device")
  455. if query_embeddings[0].dtype != passage_embeddings[0].dtype:
  456. raise ValueError("Queries and passages must have the same dtype")
  457. if output_dtype is None:
  458. output_dtype = query_embeddings[0].dtype
  459. scores: list[torch.Tensor] = []
  460. for i in range(0, len(query_embeddings), batch_size):
  461. batch_scores: list[torch.Tensor] = []
  462. batch_queries = torch.nn.utils.rnn.pad_sequence(
  463. query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
  464. )
  465. for j in range(0, len(passage_embeddings), batch_size):
  466. batch_passages = torch.nn.utils.rnn.pad_sequence(
  467. passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
  468. )
  469. batch_scores.append(
  470. torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
  471. )
  472. scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
  473. return torch.cat(scores, dim=0)
  474. __all__ = ["ColModernVBertProcessor"]