document_question_answering.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. # Copyright 2022 The Impira Team and the HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import re
  15. from typing import Any, Union, overload
  16. import numpy as np
  17. from ..generation import GenerationConfig
  18. from ..utils import (
  19. ExplicitEnum,
  20. add_end_docstrings,
  21. is_pytesseract_available,
  22. is_torch_available,
  23. is_vision_available,
  24. logging,
  25. )
  26. from .base import ChunkPipeline, build_pipeline_init_args
  27. if is_vision_available():
  28. from PIL import Image
  29. from ..image_utils import load_image
  30. if is_torch_available():
  31. import torch
  32. from ..models.auto.modeling_auto import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
  33. TESSERACT_LOADED = False
  34. if is_pytesseract_available():
  35. TESSERACT_LOADED = True
  36. import pytesseract
  37. logger = logging.get_logger(__name__)
  38. # normalize_bbox() and apply_tesseract() are derived from apply_tesseract in models/layoutlmv3/feature_extraction_layoutlmv3.py.
  39. # However, because the pipeline may evolve from what layoutlmv3 currently does, it's copied (vs. imported) to avoid creating an
  40. # unnecessary dependency.
  41. def normalize_box(box, width, height):
  42. return [
  43. int(1000 * (box[0] / width)),
  44. int(1000 * (box[1] / height)),
  45. int(1000 * (box[2] / width)),
  46. int(1000 * (box[3] / height)),
  47. ]
  48. def decode_spans(
  49. start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
  50. ) -> tuple:
  51. """
  52. Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
  53. answer.
  54. In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
  55. answer end position being before the starting position. The method supports output the k-best answer through the
  56. topk argument.
  57. Args:
  58. start (`np.ndarray`): Individual start probabilities for each token.
  59. end (`np.ndarray`): Individual end probabilities for each token.
  60. topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
  61. max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
  62. undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer
  63. """
  64. # Ensure we have batch axis
  65. if start.ndim == 1:
  66. start = start[None]
  67. if end.ndim == 1:
  68. end = end[None]
  69. # Compute the score of each tuple(start, end) to be the real answer
  70. outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))
  71. # Remove candidate with end < start and end - start > max_answer_len
  72. candidates = np.tril(np.triu(outer), max_answer_len - 1)
  73. # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
  74. scores_flat = candidates.flatten()
  75. if topk == 1:
  76. idx_sort = [np.argmax(scores_flat)]
  77. elif len(scores_flat) <= topk:
  78. idx_sort = np.argsort(-scores_flat)
  79. else:
  80. idx = np.argpartition(-scores_flat, topk)[0:topk]
  81. idx_sort = idx[np.argsort(-scores_flat[idx])]
  82. starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:]
  83. desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero())
  84. starts = starts[desired_spans]
  85. ends = ends[desired_spans]
  86. scores = candidates[0, starts, ends]
  87. return starts, ends, scores
  88. def select_starts_ends(
  89. start: np.ndarray,
  90. end: np.ndarray,
  91. p_mask: np.ndarray,
  92. attention_mask: np.ndarray,
  93. min_null_score=1000000,
  94. top_k=1,
  95. handle_impossible_answer=False,
  96. max_answer_len=15,
  97. ):
  98. """
  99. Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
  100. `decode_spans()` to generate probabilities for each span to be the actual answer.
  101. Args:
  102. start (`np.ndarray`): Individual start logits for each token.
  103. end (`np.ndarray`): Individual end logits for each token.
  104. p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer
  105. attention_mask (`np.ndarray`): The attention mask generated by the tokenizer
  106. min_null_score(`float`): The minimum null (empty) answer score seen so far.
  107. topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
  108. handle_impossible_answer(`bool`): Whether to allow null (empty) answers
  109. max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
  110. """
  111. # Ensure padded tokens & question tokens cannot belong to the set of candidate answers.
  112. undesired_tokens = np.abs(np.array(p_mask) - 1)
  113. if attention_mask is not None:
  114. undesired_tokens = undesired_tokens & attention_mask
  115. # Generate mask
  116. undesired_tokens_mask = undesired_tokens == 0.0
  117. # Make sure non-context indexes in the tensor cannot contribute to the softmax
  118. start = np.where(undesired_tokens_mask, -10000.0, start)
  119. end = np.where(undesired_tokens_mask, -10000.0, end)
  120. # Normalize logits and spans to retrieve the answer
  121. start = np.exp(start - start.max(axis=-1, keepdims=True))
  122. start = start / start.sum()
  123. end = np.exp(end - end.max(axis=-1, keepdims=True))
  124. end = end / end.sum()
  125. if handle_impossible_answer:
  126. min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item())
  127. # Mask CLS
  128. start[0, 0] = end[0, 0] = 0.0
  129. starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens)
  130. return starts, ends, scores, min_null_score
  131. def apply_tesseract(image: "Image.Image", lang: str | None, tesseract_config: str | None):
  132. """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
  133. # apply OCR
  134. data = pytesseract.image_to_data(image, lang=lang, output_type="dict", config=tesseract_config)
  135. words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]
  136. # filter empty words and corresponding coordinates
  137. irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
  138. words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
  139. left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
  140. top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
  141. width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
  142. height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]
  143. # turn coordinates into (left, top, left+width, top+height) format
  144. actual_boxes = []
  145. for x, y, w, h in zip(left, top, width, height):
  146. actual_box = [x, y, x + w, y + h]
  147. actual_boxes.append(actual_box)
  148. image_width, image_height = image.size
  149. # finally, normalize the bounding boxes
  150. normalized_boxes = []
  151. for box in actual_boxes:
  152. normalized_boxes.append(normalize_box(box, image_width, image_height))
  153. if len(words) != len(normalized_boxes):
  154. raise ValueError("Not as many words as there are bounding boxes")
  155. return words, normalized_boxes
  156. class ModelType(ExplicitEnum):
  157. LayoutLM = "layoutlm"
  158. LayoutLMv2andv3 = "layoutlmv2andv3"
  159. VisionEncoderDecoder = "vision_encoder_decoder"
  160. @add_end_docstrings(build_pipeline_init_args(has_image_processor=True, has_tokenizer=True))
  161. class DocumentQuestionAnsweringPipeline(ChunkPipeline):
  162. # TODO: Update task_summary docs to include an example with document QA and then update the first sentence
  163. """
  164. Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are
  165. similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd
  166. words/boxes) as input instead of text context.
  167. Unless the model you're using explicitly sets these generation parameters in its configuration files
  168. (`generation_config.json`), the following default values will be used:
  169. - max_new_tokens: 256
  170. Example:
  171. ```python
  172. >>> from transformers import pipeline
  173. >>> document_qa = pipeline(model="impira/layoutlm-document-qa")
  174. >>> document_qa(
  175. ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
  176. ... question="What is the invoice number?",
  177. ... )
  178. [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
  179. ```
  180. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  181. This document question answering pipeline can currently be loaded from [`pipeline`] using the following task
  182. identifier: `"document-question-answering"`.
  183. The models that this pipeline can use are models that have been fine-tuned on a document question answering task.
  184. See the up-to-date list of available models on
  185. [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering).
  186. """
  187. _pipeline_calls_generate = True
  188. _load_processor = False
  189. _load_image_processor = None
  190. _load_feature_extractor = None
  191. _load_tokenizer = True
  192. # Make sure the docstring is updated when the default generation config is changed
  193. _default_generation_config = GenerationConfig(
  194. max_new_tokens=256,
  195. )
  196. def __init__(self, *args, **kwargs):
  197. super().__init__(*args, **kwargs)
  198. if self.tokenizer is not None and not (
  199. self.tokenizer.__class__.__name__.endswith("Fast") or self.tokenizer.backend == "tokenizers"
  200. ):
  201. raise ValueError(
  202. "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer "
  203. f"(`{self.tokenizer.__class__.__name__}`) is provided."
  204. )
  205. if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig":
  206. self.model_type = ModelType.VisionEncoderDecoder
  207. if self.model.config.encoder.model_type != "donut-swin":
  208. raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut")
  209. else:
  210. self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES)
  211. if self.model.config.__class__.__name__ == "LayoutLMConfig":
  212. self.model_type = ModelType.LayoutLM
  213. else:
  214. self.model_type = ModelType.LayoutLMv2andv3
  215. def _sanitize_parameters(
  216. self,
  217. padding=None,
  218. doc_stride=None,
  219. max_question_len=None,
  220. lang: str | None = None,
  221. tesseract_config: str | None = None,
  222. max_answer_len=None,
  223. max_seq_len=None,
  224. top_k=None,
  225. handle_impossible_answer=None,
  226. timeout=None,
  227. **kwargs,
  228. ):
  229. preprocess_params, postprocess_params = {}, {}
  230. if padding is not None:
  231. preprocess_params["padding"] = padding
  232. if doc_stride is not None:
  233. preprocess_params["doc_stride"] = doc_stride
  234. if max_question_len is not None:
  235. preprocess_params["max_question_len"] = max_question_len
  236. if max_seq_len is not None:
  237. preprocess_params["max_seq_len"] = max_seq_len
  238. if lang is not None:
  239. preprocess_params["lang"] = lang
  240. if tesseract_config is not None:
  241. preprocess_params["tesseract_config"] = tesseract_config
  242. if timeout is not None:
  243. preprocess_params["timeout"] = timeout
  244. if top_k is not None:
  245. if top_k < 1:
  246. raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
  247. postprocess_params["top_k"] = top_k
  248. if max_answer_len is not None:
  249. if max_answer_len < 1:
  250. raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len})")
  251. postprocess_params["max_answer_len"] = max_answer_len
  252. if handle_impossible_answer is not None:
  253. postprocess_params["handle_impossible_answer"] = handle_impossible_answer
  254. forward_params = {}
  255. if getattr(self, "assistant_model", None) is not None:
  256. forward_params["assistant_model"] = self.assistant_model
  257. if getattr(self, "assistant_tokenizer", None) is not None:
  258. forward_params["tokenizer"] = self.tokenizer
  259. forward_params["assistant_tokenizer"] = self.assistant_tokenizer
  260. return preprocess_params, forward_params, postprocess_params
  261. @overload
  262. def __call__(
  263. self,
  264. image: Union["Image.Image", str],
  265. question: str,
  266. word_boxes: tuple[str, list[float]] | None = None,
  267. **kwargs: Any,
  268. ) -> list[dict[str, Any]]: ...
  269. @overload
  270. def __call__(self, image: dict[str, Any], **kwargs: Any) -> list[dict[str, Any]]: ...
  271. @overload
  272. def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
  273. def __call__(
  274. self,
  275. image: Union["Image.Image", str, list[dict[str, Any]]],
  276. question: str | None = None,
  277. word_boxes: tuple[str, list[float]] | None = None,
  278. **kwargs: Any,
  279. ) -> dict[str, Any] | list[dict[str, Any]]:
  280. """
  281. Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an
  282. optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not
  283. provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for
  284. LayoutLM-like models which require them as input. For Donut, no OCR is run.
  285. You can invoke the pipeline several ways:
  286. - `pipeline(image=image, question=question)`
  287. - `pipeline(image=image, question=question, word_boxes=word_boxes)`
  288. - `pipeline([{"image": image, "question": question}])`
  289. - `pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])`
  290. Args:
  291. image (`str` or `PIL.Image`):
  292. The pipeline handles three types of images:
  293. - A string containing a http link pointing to an image
  294. - A string containing a local path to an image
  295. - An image loaded in PIL directly
  296. The pipeline accepts either a single image or a batch of images. If given a single image, it can be
  297. broadcasted to multiple questions.
  298. question (`str`):
  299. A question to ask of the document.
  300. word_boxes (`list[str, tuple[float, float, float, float]]`, *optional*):
  301. A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the
  302. pipeline will use these words and boxes instead of running OCR on the image to derive them for models
  303. that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the
  304. pipeline without having to re-run it each time.
  305. top_k (`int`, *optional*, defaults to 1):
  306. The number of answers to return (will be chosen by order of likelihood). Note that we return less than
  307. top_k answers if there are not enough options available within the context.
  308. doc_stride (`int`, *optional*, defaults to 128):
  309. If the words in the document are too long to fit with the question for the model, it will be split in
  310. several chunks with some overlap. This argument controls the size of that overlap.
  311. max_answer_len (`int`, *optional*, defaults to 15):
  312. The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
  313. max_seq_len (`int`, *optional*, defaults to 384):
  314. The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
  315. model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.
  316. max_question_len (`int`, *optional*, defaults to 64):
  317. The maximum length of the question after tokenization. It will be truncated if needed.
  318. handle_impossible_answer (`bool`, *optional*, defaults to `False`):
  319. Whether or not we accept impossible as an answer.
  320. lang (`str`, *optional*):
  321. Language to use while running OCR. Defaults to english.
  322. tesseract_config (`str`, *optional*):
  323. Additional flags to pass to tesseract while running OCR.
  324. timeout (`float`, *optional*, defaults to None):
  325. The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
  326. the call may block forever.
  327. Return:
  328. A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
  329. - **score** (`float`) -- The probability associated to the answer.
  330. - **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided
  331. `word_boxes`).
  332. - **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided
  333. `word_boxes`).
  334. - **answer** (`str`) -- The answer to the question.
  335. - **words** (`list[int]`) -- The index of each word/box pair that is in the answer
  336. """
  337. if isinstance(question, str):
  338. inputs = {"question": question, "image": image}
  339. if word_boxes is not None:
  340. inputs["word_boxes"] = word_boxes
  341. else:
  342. inputs = image
  343. return super().__call__(inputs, **kwargs)
  344. def preprocess(
  345. self,
  346. input,
  347. padding="do_not_pad",
  348. doc_stride=None,
  349. max_seq_len=None,
  350. word_boxes: tuple[str, list[float]] | None = None,
  351. lang=None,
  352. tesseract_config="",
  353. timeout=None,
  354. ):
  355. # NOTE: This code mirrors the code in question answering and will be implemented in a follow up PR
  356. # to support documents with enough tokens that overflow the model's window
  357. if max_seq_len is None:
  358. max_seq_len = self.tokenizer.model_max_length
  359. if doc_stride is None:
  360. doc_stride = min(max_seq_len // 2, 256)
  361. image = None
  362. image_features = {}
  363. if input.get("image", None) is not None:
  364. image = load_image(input["image"], timeout=timeout)
  365. if self.image_processor is not None:
  366. image_inputs = self.image_processor(images=image, return_tensors="pt")
  367. image_inputs = image_inputs.to(self.dtype)
  368. image_features.update(image_inputs)
  369. elif self.feature_extractor is not None:
  370. image_features.update(self.feature_extractor(images=image, return_tensors="pt"))
  371. elif self.model_type == ModelType.VisionEncoderDecoder:
  372. raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor")
  373. words, boxes = None, None
  374. if self.model_type != ModelType.VisionEncoderDecoder:
  375. if "word_boxes" in input:
  376. words = [x[0] for x in input["word_boxes"]]
  377. boxes = [x[1] for x in input["word_boxes"]]
  378. elif "words" in image_features and "boxes" in image_features:
  379. words = image_features.pop("words")[0]
  380. boxes = image_features.pop("boxes")[0]
  381. elif image is not None:
  382. if not TESSERACT_LOADED:
  383. raise ValueError(
  384. "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract,"
  385. " but pytesseract is not available"
  386. )
  387. if TESSERACT_LOADED:
  388. words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config)
  389. else:
  390. raise ValueError(
  391. "You must provide an image or word_boxes. If you provide an image, the pipeline will automatically"
  392. " run OCR to derive words and boxes"
  393. )
  394. if self.tokenizer.padding_side != "right":
  395. raise ValueError(
  396. "Document question answering only supports tokenizers whose padding side is 'right', not"
  397. f" {self.tokenizer.padding_side}"
  398. )
  399. if self.model_type == ModelType.VisionEncoderDecoder:
  400. task_prompt = f"<s_docvqa><s_question>{input['question']}</s_question><s_answer>"
  401. # Adapted from https://huggingface.co/spaces/nielsr/donut-docvqa/blob/main/app.py
  402. encoding = {
  403. "inputs": image_features["pixel_values"],
  404. "decoder_input_ids": self.tokenizer(
  405. task_prompt, add_special_tokens=False, return_tensors="pt"
  406. ).input_ids,
  407. "return_dict_in_generate": True,
  408. }
  409. yield {
  410. **encoding,
  411. "p_mask": None,
  412. "word_ids": None,
  413. "words": None,
  414. "output_attentions": True,
  415. "is_last": True,
  416. }
  417. else:
  418. tokenizer_kwargs = {}
  419. if self.model_type == ModelType.LayoutLM:
  420. tokenizer_kwargs["text"] = input["question"].split()
  421. tokenizer_kwargs["text_pair"] = words
  422. tokenizer_kwargs["is_split_into_words"] = True
  423. else:
  424. tokenizer_kwargs["text"] = [input["question"]]
  425. tokenizer_kwargs["text_pair"] = [words]
  426. tokenizer_kwargs["boxes"] = [boxes]
  427. encoding = self.tokenizer(
  428. padding=padding,
  429. max_length=max_seq_len,
  430. stride=doc_stride,
  431. return_token_type_ids=True,
  432. truncation="only_second",
  433. return_overflowing_tokens=True,
  434. **tokenizer_kwargs,
  435. )
  436. # TODO: check why slower `LayoutLMTokenizer` and `LayoutLMv2Tokenizer` don't have this key in outputs
  437. # FIXME: ydshieh and/or Narsil
  438. encoding.pop("overflow_to_sample_mapping", None) # We do not use this
  439. num_spans = len(encoding["input_ids"])
  440. # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
  441. # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens)
  442. # This logic mirrors the logic in the question_answering pipeline
  443. p_mask = [[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)]
  444. for span_idx in range(num_spans):
  445. span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()}
  446. if "pixel_values" in image_features:
  447. span_encoding["image"] = image_features["pixel_values"]
  448. input_ids_span_idx = encoding["input_ids"][span_idx]
  449. # keep the cls_token unmasked (some models use it to indicate unanswerable questions)
  450. if self.tokenizer.cls_token_id is not None:
  451. cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
  452. for cls_index in cls_indices:
  453. p_mask[span_idx][cls_index] = 0
  454. # For each span, place a bounding box [0,0,0,0] for question and CLS tokens, [1000,1000,1000,1000]
  455. # for SEP tokens, and the word's bounding box for words in the original document.
  456. if "boxes" not in tokenizer_kwargs:
  457. bbox = []
  458. for input_id, sequence_id, word_id in zip(
  459. encoding.input_ids[span_idx],
  460. encoding.sequence_ids(span_idx),
  461. encoding.word_ids(span_idx),
  462. ):
  463. if sequence_id == 1:
  464. bbox.append(boxes[word_id])
  465. elif input_id == self.tokenizer.sep_token_id:
  466. bbox.append([1000] * 4)
  467. else:
  468. bbox.append([0] * 4)
  469. span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0)
  470. yield {
  471. **span_encoding,
  472. "p_mask": p_mask[span_idx],
  473. "word_ids": encoding.word_ids(span_idx),
  474. "words": words,
  475. "is_last": span_idx == num_spans - 1,
  476. }
  477. def _forward(self, model_inputs, **generate_kwargs):
  478. p_mask = model_inputs.pop("p_mask", None)
  479. word_ids = model_inputs.pop("word_ids", None)
  480. words = model_inputs.pop("words", None)
  481. is_last = model_inputs.pop("is_last", False)
  482. if self.model_type == ModelType.VisionEncoderDecoder:
  483. # User-defined `generation_config` passed to the pipeline call take precedence
  484. if "generation_config" not in generate_kwargs:
  485. generate_kwargs["generation_config"] = self.generation_config
  486. model_outputs = self.model.generate(**model_inputs, **generate_kwargs)
  487. else:
  488. model_outputs = self.model(**model_inputs)
  489. model_outputs = dict(model_outputs.items())
  490. model_outputs["p_mask"] = p_mask
  491. model_outputs["word_ids"] = word_ids
  492. model_outputs["words"] = words
  493. model_outputs["attention_mask"] = model_inputs.get("attention_mask", None)
  494. model_outputs["is_last"] = is_last
  495. return model_outputs
  496. def postprocess(self, model_outputs, top_k=1, **kwargs):
  497. if self.model_type == ModelType.VisionEncoderDecoder:
  498. answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs]
  499. else:
  500. answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs)
  501. answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k]
  502. return answers
  503. def postprocess_encoder_decoder_single(self, model_outputs, **kwargs):
  504. sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0]
  505. # TODO: A lot of this logic is specific to Donut and should probably be handled in the tokenizer
  506. # (see https://github.com/huggingface/transformers/pull/18414/files#r961747408 for more context).
  507. sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "")
  508. sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
  509. ret = {
  510. "answer": None,
  511. }
  512. answer = re.search(r"<s_answer>(.*)</s_answer>", sequence)
  513. if answer is not None:
  514. ret["answer"] = answer.group(1).strip()
  515. return ret
  516. def postprocess_extractive_qa(
  517. self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs
  518. ):
  519. min_null_score = 1000000 # large and positive
  520. answers = []
  521. for output in model_outputs:
  522. words = output["words"]
  523. if output["start_logits"].dtype in (torch.bfloat16, torch.float16):
  524. output["start_logits"] = output["start_logits"].float()
  525. if output["end_logits"].dtype in (torch.bfloat16, torch.float16):
  526. output["end_logits"] = output["end_logits"].float()
  527. starts, ends, scores, min_null_score = select_starts_ends(
  528. start=output["start_logits"],
  529. end=output["end_logits"],
  530. p_mask=output["p_mask"],
  531. attention_mask=output["attention_mask"].numpy()
  532. if output.get("attention_mask", None) is not None
  533. else None,
  534. min_null_score=min_null_score,
  535. top_k=top_k,
  536. handle_impossible_answer=handle_impossible_answer,
  537. max_answer_len=max_answer_len,
  538. )
  539. word_ids = output["word_ids"]
  540. for start, end, score in zip(starts, ends, scores):
  541. word_start, word_end = word_ids[start], word_ids[end]
  542. if word_start is not None and word_end is not None:
  543. answers.append(
  544. {
  545. "score": float(score),
  546. "answer": " ".join(words[word_start : word_end + 1]),
  547. "start": word_start,
  548. "end": word_end,
  549. }
  550. )
  551. if handle_impossible_answer:
  552. answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0})
  553. return answers