question_answering.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. import inspect
  2. import types
  3. import warnings
  4. from collections.abc import Iterable
  5. from typing import TYPE_CHECKING, Optional, Union
  6. import numpy as np
  7. from ..data import SquadExample, SquadFeatures, squad_convert_examples_to_features
  8. from ..modelcard import ModelCard
  9. from ..tokenization_utils import PreTrainedTokenizer
  10. from ..utils import (
  11. PaddingStrategy,
  12. add_end_docstrings,
  13. is_tf_available,
  14. is_tokenizers_available,
  15. is_torch_available,
  16. logging,
  17. )
  18. from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
  19. logger = logging.get_logger(__name__)
  20. if TYPE_CHECKING:
  21. from ..modeling_tf_utils import TFPreTrainedModel
  22. from ..modeling_utils import PreTrainedModel
  23. if is_tokenizers_available():
  24. import tokenizers
  25. if is_tf_available():
  26. import tensorflow as tf
  27. from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
  28. Dataset = None
  29. if is_torch_available():
  30. import torch
  31. from torch.utils.data import Dataset
  32. from ..models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
  33. def decode_spans(
  34. start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
  35. ) -> tuple:
  36. """
  37. Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
  38. answer.
  39. In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
  40. answer end position being before the starting position. The method supports output the k-best answer through the
  41. topk argument.
  42. Args:
  43. start (`np.ndarray`): Individual start probabilities for each token.
  44. end (`np.ndarray`): Individual end probabilities for each token.
  45. topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
  46. max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
  47. undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer
  48. """
  49. # Ensure we have batch axis
  50. if start.ndim == 1:
  51. start = start[None]
  52. if end.ndim == 1:
  53. end = end[None]
  54. # Compute the score of each tuple(start, end) to be the real answer
  55. outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))
  56. # Remove candidate with end < start and end - start > max_answer_len
  57. candidates = np.tril(np.triu(outer), max_answer_len - 1)
  58. # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
  59. scores_flat = candidates.flatten()
  60. if topk == 1:
  61. idx_sort = [np.argmax(scores_flat)]
  62. elif len(scores_flat) < topk:
  63. idx_sort = np.argsort(-scores_flat)
  64. else:
  65. idx = np.argpartition(-scores_flat, topk)[0:topk]
  66. idx_sort = idx[np.argsort(-scores_flat[idx])]
  67. starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:]
  68. desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero())
  69. starts = starts[desired_spans]
  70. ends = ends[desired_spans]
  71. scores = candidates[0, starts, ends]
  72. return starts, ends, scores
  73. def select_starts_ends(
  74. start,
  75. end,
  76. p_mask,
  77. attention_mask,
  78. min_null_score=1000000,
  79. top_k=1,
  80. handle_impossible_answer=False,
  81. max_answer_len=15,
  82. ):
  83. """
  84. Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
  85. `decode_spans()` to generate probabilities for each span to be the actual answer.
  86. Args:
  87. start (`np.ndarray`): Individual start logits for each token.
  88. end (`np.ndarray`): Individual end logits for each token.
  89. p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer
  90. attention_mask (`np.ndarray`): The attention mask generated by the tokenizer
  91. min_null_score(`float`): The minimum null (empty) answer score seen so far.
  92. topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
  93. handle_impossible_answer(`bool`): Whether to allow null (empty) answers
  94. max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
  95. """
  96. # Ensure padded tokens & question tokens cannot belong to the set of candidate answers.
  97. undesired_tokens = np.abs(np.array(p_mask) - 1)
  98. if attention_mask is not None:
  99. undesired_tokens = undesired_tokens & attention_mask
  100. # Generate mask
  101. undesired_tokens_mask = undesired_tokens == 0.0
  102. # Make sure non-context indexes in the tensor cannot contribute to the softmax
  103. start = np.where(undesired_tokens_mask, -10000.0, start)
  104. end = np.where(undesired_tokens_mask, -10000.0, end)
  105. # Normalize logits and spans to retrieve the answer
  106. start = np.exp(start - start.max(axis=-1, keepdims=True))
  107. start = start / start.sum()
  108. end = np.exp(end - end.max(axis=-1, keepdims=True))
  109. end = end / end.sum()
  110. if handle_impossible_answer:
  111. min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item())
  112. # Mask CLS
  113. start[0, 0] = end[0, 0] = 0.0
  114. starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens)
  115. return starts, ends, scores, min_null_score
  116. class QuestionAnsweringArgumentHandler(ArgumentHandler):
  117. """
  118. QuestionAnsweringPipeline requires the user to provide multiple arguments (i.e. question & context) to be mapped to
  119. internal [`SquadExample`].
  120. QuestionAnsweringArgumentHandler manages all the possible to create a [`SquadExample`] from the command-line
  121. supplied arguments.
  122. """
  123. _load_processor = False
  124. _load_image_processor = False
  125. _load_feature_extractor = False
  126. _load_tokenizer = True
  127. def normalize(self, item):
  128. if isinstance(item, SquadExample):
  129. return item
  130. elif isinstance(item, dict):
  131. for k in ["question", "context"]:
  132. if k not in item:
  133. raise KeyError("You need to provide a dictionary with keys {question:..., context:...}")
  134. elif item[k] is None:
  135. raise ValueError(f"`{k}` cannot be None")
  136. elif isinstance(item[k], str) and len(item[k]) == 0:
  137. raise ValueError(f"`{k}` cannot be empty")
  138. return QuestionAnsweringPipeline.create_sample(**item)
  139. raise ValueError(f"{item} argument needs to be of type (SquadExample, dict)")
  140. def __call__(self, *args, **kwargs):
  141. # Detect where the actual inputs are
  142. if args is not None and len(args) > 0:
  143. if len(args) == 1:
  144. inputs = args[0]
  145. elif len(args) == 2 and {type(el) for el in args} == {str}:
  146. inputs = [{"question": args[0], "context": args[1]}]
  147. else:
  148. inputs = list(args)
  149. # Generic compatibility with sklearn and Keras
  150. # Batched data
  151. elif "X" in kwargs:
  152. warnings.warn(
  153. "Passing the `X` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
  154. FutureWarning,
  155. )
  156. inputs = kwargs["X"]
  157. elif "data" in kwargs:
  158. warnings.warn(
  159. "Passing the `data` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
  160. FutureWarning,
  161. )
  162. inputs = kwargs["data"]
  163. elif "question" in kwargs and "context" in kwargs:
  164. if isinstance(kwargs["question"], list) and isinstance(kwargs["context"], str):
  165. inputs = [{"question": Q, "context": kwargs["context"]} for Q in kwargs["question"]]
  166. elif isinstance(kwargs["question"], list) and isinstance(kwargs["context"], list):
  167. if len(kwargs["question"]) != len(kwargs["context"]):
  168. raise ValueError("Questions and contexts don't have the same lengths")
  169. inputs = [{"question": Q, "context": C} for Q, C in zip(kwargs["question"], kwargs["context"])]
  170. elif isinstance(kwargs["question"], str) and isinstance(kwargs["context"], str):
  171. inputs = [{"question": kwargs["question"], "context": kwargs["context"]}]
  172. else:
  173. raise ValueError("Arguments can't be understood")
  174. else:
  175. raise ValueError(f"Unknown arguments {kwargs}")
  176. # When user is sending a generator we need to trust it's a valid example
  177. generator_types = (types.GeneratorType, Dataset) if Dataset is not None else (types.GeneratorType,)
  178. if isinstance(inputs, generator_types):
  179. return inputs
  180. # Normalize inputs
  181. if isinstance(inputs, dict):
  182. inputs = [inputs]
  183. elif isinstance(inputs, Iterable):
  184. # Copy to avoid overriding arguments
  185. inputs = list(inputs)
  186. else:
  187. raise ValueError(f"Invalid arguments {kwargs}")
  188. for i, item in enumerate(inputs):
  189. inputs[i] = self.normalize(item)
  190. return inputs
  191. @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
  192. class QuestionAnsweringPipeline(ChunkPipeline):
  193. """
  194. Question Answering pipeline using any `ModelForQuestionAnswering`. See the [question answering
  195. examples](../task_summary#question-answering) for more information.
  196. Example:
  197. ```python
  198. >>> from transformers import pipeline
  199. >>> oracle = pipeline(model="deepset/roberta-base-squad2")
  200. >>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin")
  201. {'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'}
  202. ```
  203. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  204. This question answering pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  205. `"question-answering"`.
  206. The models that this pipeline can use are models that have been fine-tuned on a question answering task. See the
  207. up-to-date list of available models on
  208. [huggingface.co/models](https://huggingface.co/models?filter=question-answering).
  209. """
  210. default_input_names = "question,context"
  211. handle_impossible_answer = False
  212. def __init__(
  213. self,
  214. model: Union["PreTrainedModel", "TFPreTrainedModel"],
  215. tokenizer: PreTrainedTokenizer,
  216. modelcard: Optional[ModelCard] = None,
  217. framework: Optional[str] = None,
  218. task: str = "",
  219. **kwargs,
  220. ):
  221. super().__init__(
  222. model=model,
  223. tokenizer=tokenizer,
  224. modelcard=modelcard,
  225. framework=framework,
  226. task=task,
  227. **kwargs,
  228. )
  229. self._args_parser = QuestionAnsweringArgumentHandler()
  230. self.check_model_type(
  231. TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
  232. if self.framework == "tf"
  233. else MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
  234. )
  235. @staticmethod
  236. def create_sample(
  237. question: Union[str, list[str]], context: Union[str, list[str]]
  238. ) -> Union[SquadExample, list[SquadExample]]:
  239. """
  240. QuestionAnsweringPipeline leverages the [`SquadExample`] internally. This helper method encapsulate all the
  241. logic for converting question(s) and context(s) to [`SquadExample`].
  242. We currently support extractive question answering.
  243. Arguments:
  244. question (`str` or `list[str]`): The question(s) asked.
  245. context (`str` or `list[str]`): The context(s) in which we will look for the answer.
  246. Returns:
  247. One or a list of [`SquadExample`]: The corresponding [`SquadExample`] grouping question and context.
  248. """
  249. if isinstance(question, list):
  250. return [SquadExample(None, q, c, None, None, None) for q, c in zip(question, context)]
  251. else:
  252. return SquadExample(None, question, context, None, None, None)
  253. def _sanitize_parameters(
  254. self,
  255. padding=None,
  256. topk=None,
  257. top_k=None,
  258. doc_stride=None,
  259. max_answer_len=None,
  260. max_seq_len=None,
  261. max_question_len=None,
  262. handle_impossible_answer=None,
  263. align_to_words=None,
  264. **kwargs,
  265. ):
  266. # Set defaults values
  267. preprocess_params = {}
  268. if padding is not None:
  269. preprocess_params["padding"] = padding
  270. if doc_stride is not None:
  271. preprocess_params["doc_stride"] = doc_stride
  272. if max_question_len is not None:
  273. preprocess_params["max_question_len"] = max_question_len
  274. if max_seq_len is not None:
  275. preprocess_params["max_seq_len"] = max_seq_len
  276. postprocess_params = {}
  277. if topk is not None and top_k is None:
  278. warnings.warn("topk parameter is deprecated, use top_k instead", UserWarning)
  279. top_k = topk
  280. if top_k is not None:
  281. if top_k < 1:
  282. raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
  283. postprocess_params["top_k"] = top_k
  284. if max_answer_len is not None:
  285. if max_answer_len < 1:
  286. raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len}")
  287. postprocess_params["max_answer_len"] = max_answer_len
  288. if handle_impossible_answer is not None:
  289. postprocess_params["handle_impossible_answer"] = handle_impossible_answer
  290. if align_to_words is not None:
  291. postprocess_params["align_to_words"] = align_to_words
  292. return preprocess_params, {}, postprocess_params
  293. def __call__(self, *args, **kwargs):
  294. """
  295. Answer the question(s) given as inputs by using the context(s).
  296. Args:
  297. question (`str` or `list[str]`):
  298. One or several question(s) (must be used in conjunction with the `context` argument).
  299. context (`str` or `list[str]`):
  300. One or several context(s) associated with the question(s) (must be used in conjunction with the
  301. `question` argument).
  302. top_k (`int`, *optional*, defaults to 1):
  303. The number of answers to return (will be chosen by order of likelihood). Note that we return less than
  304. top_k answers if there are not enough options available within the context.
  305. doc_stride (`int`, *optional*, defaults to 128):
  306. If the context is too long to fit with the question for the model, it will be split in several chunks
  307. with some overlap. This argument controls the size of that overlap.
  308. max_answer_len (`int`, *optional*, defaults to 15):
  309. The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
  310. max_seq_len (`int`, *optional*, defaults to 384):
  311. The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
  312. model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.
  313. max_question_len (`int`, *optional*, defaults to 64):
  314. The maximum length of the question after tokenization. It will be truncated if needed.
  315. handle_impossible_answer (`bool`, *optional*, defaults to `False`):
  316. Whether or not we accept impossible as an answer.
  317. align_to_words (`bool`, *optional*, defaults to `True`):
  318. Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt on
  319. non-space-separated languages (like Japanese or Chinese)
  320. Return:
  321. A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
  322. - **score** (`float`) -- The probability associated to the answer.
  323. - **start** (`int`) -- The character start index of the answer (in the tokenized version of the input).
  324. - **end** (`int`) -- The character end index of the answer (in the tokenized version of the input).
  325. - **answer** (`str`) -- The answer to the question.
  326. """
  327. # Convert inputs to features
  328. if args:
  329. warnings.warn(
  330. "Passing a list of SQuAD examples to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.",
  331. FutureWarning,
  332. )
  333. examples = self._args_parser(*args, **kwargs)
  334. if isinstance(examples, (list, tuple)) and len(examples) == 1:
  335. return super().__call__(examples[0], **kwargs)
  336. return super().__call__(examples, **kwargs)
  337. def preprocess(self, example, padding="do_not_pad", doc_stride=None, max_question_len=64, max_seq_len=None):
  338. # XXX: This is special, args_parser will not handle anything generator or dataset like
  339. # For those we expect user to send a simple valid example either directly as a SquadExample or simple dict.
  340. # So we still need a little sanitation here.
  341. if isinstance(example, dict):
  342. example = SquadExample(None, example["question"], example["context"], None, None, None)
  343. if max_seq_len is None:
  344. max_seq_len = min(self.tokenizer.model_max_length, 384)
  345. if doc_stride is None:
  346. doc_stride = min(max_seq_len // 2, 128)
  347. if doc_stride > max_seq_len:
  348. raise ValueError(f"`doc_stride` ({doc_stride}) is larger than `max_seq_len` ({max_seq_len})")
  349. if not self.tokenizer.is_fast:
  350. features = squad_convert_examples_to_features(
  351. examples=[example],
  352. tokenizer=self.tokenizer,
  353. max_seq_length=max_seq_len,
  354. doc_stride=doc_stride,
  355. max_query_length=max_question_len,
  356. padding_strategy=PaddingStrategy.MAX_LENGTH,
  357. is_training=False,
  358. tqdm_enabled=False,
  359. )
  360. else:
  361. # Define the side we want to truncate / pad and the text/pair sorting
  362. question_first = self.tokenizer.padding_side == "right"
  363. encoded_inputs = self.tokenizer(
  364. text=example.question_text if question_first else example.context_text,
  365. text_pair=example.context_text if question_first else example.question_text,
  366. padding=padding,
  367. truncation="only_second" if question_first else "only_first",
  368. max_length=max_seq_len,
  369. stride=doc_stride,
  370. return_token_type_ids=True,
  371. return_overflowing_tokens=True,
  372. return_offsets_mapping=True,
  373. return_special_tokens_mask=True,
  374. )
  375. # When the input is too long, it's converted in a batch of inputs with overflowing tokens
  376. # and a stride of overlap between the inputs. If a batch of inputs is given, a special output
  377. # "overflow_to_sample_mapping" indicate which member of the encoded batch belong to which original batch sample.
  378. # Here we tokenize examples one-by-one so we don't need to use "overflow_to_sample_mapping".
  379. # "num_span" is the number of output samples generated from the overflowing tokens.
  380. num_spans = len(encoded_inputs["input_ids"])
  381. # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
  382. # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens)
  383. p_mask = [
  384. [tok != 1 if question_first else 0 for tok in encoded_inputs.sequence_ids(span_id)]
  385. for span_id in range(num_spans)
  386. ]
  387. features = []
  388. for span_idx in range(num_spans):
  389. input_ids_span_idx = encoded_inputs["input_ids"][span_idx]
  390. attention_mask_span_idx = (
  391. encoded_inputs["attention_mask"][span_idx] if "attention_mask" in encoded_inputs else None
  392. )
  393. token_type_ids_span_idx = (
  394. encoded_inputs["token_type_ids"][span_idx] if "token_type_ids" in encoded_inputs else None
  395. )
  396. # keep the cls_token unmasked (some models use it to indicate unanswerable questions)
  397. if self.tokenizer.cls_token_id is not None:
  398. cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
  399. for cls_index in cls_indices:
  400. p_mask[span_idx][cls_index] = 0
  401. submask = p_mask[span_idx]
  402. features.append(
  403. SquadFeatures(
  404. input_ids=input_ids_span_idx,
  405. attention_mask=attention_mask_span_idx,
  406. token_type_ids=token_type_ids_span_idx,
  407. p_mask=submask,
  408. encoding=encoded_inputs[span_idx],
  409. # We don't use the rest of the values - and actually
  410. # for Fast tokenizer we could totally avoid using SquadFeatures and SquadExample
  411. cls_index=None,
  412. token_to_orig_map={},
  413. example_index=0,
  414. unique_id=0,
  415. paragraph_len=0,
  416. token_is_max_context=0,
  417. tokens=[],
  418. start_position=0,
  419. end_position=0,
  420. is_impossible=False,
  421. qas_id=None,
  422. )
  423. )
  424. for i, feature in enumerate(features):
  425. fw_args = {}
  426. others = {}
  427. model_input_names = self.tokenizer.model_input_names + ["p_mask", "token_type_ids"]
  428. for k, v in feature.__dict__.items():
  429. if k in model_input_names:
  430. if self.framework == "tf":
  431. tensor = tf.constant(v)
  432. if tensor.dtype == tf.int64:
  433. tensor = tf.cast(tensor, tf.int32)
  434. fw_args[k] = tf.expand_dims(tensor, 0)
  435. elif self.framework == "pt":
  436. tensor = torch.tensor(v)
  437. if tensor.dtype == torch.int32:
  438. tensor = tensor.long()
  439. fw_args[k] = tensor.unsqueeze(0)
  440. else:
  441. others[k] = v
  442. is_last = i == len(features) - 1
  443. yield {"example": example, "is_last": is_last, **fw_args, **others}
  444. def _forward(self, inputs):
  445. example = inputs["example"]
  446. model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
  447. # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
  448. model_forward = self.model.forward if self.framework == "pt" else self.model.call
  449. if "use_cache" in inspect.signature(model_forward).parameters:
  450. model_inputs["use_cache"] = False
  451. output = self.model(**model_inputs)
  452. if isinstance(output, dict):
  453. return {"start": output["start_logits"], "end": output["end_logits"], "example": example, **inputs}
  454. else:
  455. start, end = output[:2]
  456. return {"start": start, "end": end, "example": example, **inputs}
  457. def postprocess(
  458. self,
  459. model_outputs,
  460. top_k=1,
  461. handle_impossible_answer=False,
  462. max_answer_len=15,
  463. align_to_words=True,
  464. ):
  465. min_null_score = 1000000 # large and positive
  466. answers = []
  467. for output in model_outputs:
  468. if self.framework == "pt" and output["start"].dtype == torch.bfloat16:
  469. start_ = output["start"].to(torch.float32)
  470. end_ = output["end"].to(torch.float32)
  471. else:
  472. start_ = output["start"]
  473. end_ = output["end"]
  474. example = output["example"]
  475. p_mask = output["p_mask"]
  476. attention_mask = (
  477. output["attention_mask"].numpy() if output.get("attention_mask", None) is not None else None
  478. )
  479. pre_topk = (
  480. top_k * 2 + 10 if align_to_words else top_k
  481. ) # Some candidates may be deleted if we align to words
  482. starts, ends, scores, min_null_score = select_starts_ends(
  483. start_,
  484. end_,
  485. p_mask,
  486. attention_mask,
  487. min_null_score,
  488. pre_topk,
  489. handle_impossible_answer,
  490. max_answer_len,
  491. )
  492. if not self.tokenizer.is_fast:
  493. char_to_word = np.array(example.char_to_word_offset)
  494. # Convert the answer (tokens) back to the original text
  495. # Score: score from the model
  496. # Start: Index of the first character of the answer in the context string
  497. # End: Index of the character following the last character of the answer in the context string
  498. # Answer: Plain text of the answer
  499. for s, e, score in zip(starts, ends, scores):
  500. token_to_orig_map = output["token_to_orig_map"]
  501. answers.append(
  502. {
  503. "score": score.item(),
  504. "start": np.where(char_to_word == token_to_orig_map[s])[0][0].item(),
  505. "end": np.where(char_to_word == token_to_orig_map[e])[0][-1].item(),
  506. "answer": " ".join(example.doc_tokens[token_to_orig_map[s] : token_to_orig_map[e] + 1]),
  507. }
  508. )
  509. else:
  510. # Convert the answer (tokens) back to the original text
  511. # Score: score from the model
  512. # Start: Index of the first character of the answer in the context string
  513. # End: Index of the character following the last character of the answer in the context string
  514. # Answer: Plain text of the answer
  515. question_first = self.tokenizer.padding_side == "right"
  516. enc = output["encoding"]
  517. # Encoding was *not* padded, input_ids *might*.
  518. # It doesn't make a difference unless we're padding on
  519. # the left hand side, since now we have different offsets
  520. # everywhere.
  521. if self.tokenizer.padding_side == "left":
  522. offset = (output["input_ids"] == self.tokenizer.pad_token_id).numpy().sum()
  523. else:
  524. offset = 0
  525. # Sometimes the max probability token is in the middle of a word so:
  526. # - we start by finding the right word containing the token with `token_to_word`
  527. # - then we convert this word in a character span with `word_to_chars`
  528. sequence_index = 1 if question_first else 0
  529. for s, e, score in zip(starts, ends, scores):
  530. s = s - offset
  531. e = e - offset
  532. start_index, end_index = self.get_indices(enc, s, e, sequence_index, align_to_words)
  533. target_answer = example.context_text[start_index:end_index]
  534. answer = self.get_answer(answers, target_answer)
  535. if answer:
  536. answer["score"] += score.item()
  537. else:
  538. answers.append(
  539. {
  540. "score": score.item(),
  541. "start": start_index,
  542. "end": end_index,
  543. "answer": example.context_text[start_index:end_index],
  544. }
  545. )
  546. if handle_impossible_answer:
  547. answers.append({"score": min_null_score, "start": 0, "end": 0, "answer": ""})
  548. answers = sorted(answers, key=lambda x: x["score"], reverse=True)[:top_k]
  549. if len(answers) == 1:
  550. return answers[0]
  551. return answers
  552. def get_answer(self, answers: list[dict], target: str) -> Optional[dict]:
  553. for answer in answers:
  554. if answer["answer"].lower() == target.lower():
  555. return answer
  556. return None
  557. def get_indices(
  558. self, enc: "tokenizers.Encoding", s: int, e: int, sequence_index: int, align_to_words: bool
  559. ) -> tuple[int, int]:
  560. if align_to_words:
  561. try:
  562. start_word = enc.token_to_word(s)
  563. end_word = enc.token_to_word(e)
  564. start_index = enc.word_to_chars(start_word, sequence_index=sequence_index)[0]
  565. end_index = enc.word_to_chars(end_word, sequence_index=sequence_index)[1]
  566. except Exception:
  567. # Some tokenizers don't really handle words. Keep to offsets then.
  568. start_index = enc.offsets[s][0]
  569. end_index = enc.offsets[e][1]
  570. else:
  571. start_index = enc.offsets[s][0]
  572. end_index = enc.offsets[e][1]
  573. return start_index, end_index
  574. def span_to_answer(self, text: str, start: int, end: int) -> dict[str, Union[str, int]]:
  575. """
  576. When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
  577. Args:
  578. text (`str`): The actual context to extract the answer from.
  579. start (`int`): The answer starting token index.
  580. end (`int`): The answer end token index.
  581. Returns:
  582. Dictionary like `{'answer': str, 'start': int, 'end': int}`
  583. """
  584. words = []
  585. token_idx = char_start_idx = char_end_idx = chars_idx = 0
  586. for word in text.split(" "):
  587. token = self.tokenizer.tokenize(word)
  588. # Append words if they are in the span
  589. if start <= token_idx <= end:
  590. if token_idx == start:
  591. char_start_idx = chars_idx
  592. if token_idx == end:
  593. char_end_idx = chars_idx + len(word)
  594. words += [word]
  595. # Stop if we went over the end of the answer
  596. if token_idx > end:
  597. break
  598. # Append the subtokenization length to the running index
  599. token_idx += len(token)
  600. chars_idx += len(word) + 1
  601. # Join text with spaces
  602. return {
  603. "answer": " ".join(words),
  604. "start": max(0, char_start_idx),
  605. "end": min(len(text), char_end_idx),
  606. }